models.py 25 KB
Newer Older
Administrator committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
from django.db import models
from outils.common_imports import *

from outils.common import OdooAPI
from outils.common import CouchDB

from shelfs.models import Shelfs


p_fields = [
    'name',
    'list_price',
    'categ_id',
    'uom_id',
    'incoming_qty',
    'qty_available',
    'image_small',
    'price_volume',
    'price_weight_net']

max_timeslots_cart_file = 'shop/max_timeslot_carts.txt'

# Shop settings set by admin user
shop_admin_settings_file = 'shop/shop_admin_settings.json'

#  Already exists in Inventory, but since it has to be modified soon, copied here
def build_tree_from_categories(elts, parent_id = False):
    branch = []
    for e in elts:
        to_compare = e['parent_id']
        if not type(to_compare) == bool:
            to_compare = to_compare[0]
        if to_compare == parent_id:
            children = build_tree_from_categories(elts, e['id'])
            if len(children) > 0:
                e['children'] = children
            branch.append(e)

    return branch

def get_all_children(branch):
    children = []
    if 'children' in branch:
        for c in branch['children']:
            children.append({'id': c['id'], 'name': c['name']})
            if 'children' in c:
                children += get_all_children(c)
    return children

50 51 52 53 54
def get_all_children_ids(branch):
    ids = []
    for c in get_all_children(branch):
        ids.append(c['id'])
    return ids
Administrator committed
55 56 57 58 59 60 61 62 63 64 65 66 67 68

class CagetteShop(models.Model):
    """Class to handle cagette Shop."""

    @staticmethod
    def get_default_shop_admin_settings():
        return {'closing_dates': [],
                'capital_message': '',
                'max_timeslot_carts': settings.DEFAULT_MAX_TIMESLOT_CARTS}

    @staticmethod
    def filter_products_according_settings(pdts):
        res = pdts
        try:
69
            conditions = getattr(settings, 'SHOP_LIMIT_PRODUCTS', [])
Administrator committed
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
            filtered = []
            for p in pdts:
                keep_it = True
                if 'relatively_available' in conditions:
                    if float(p['qty_available']) <= 0 and float(p['incoming_qty']) <= 0:
                        keep_it = False
                if 'no_shelf' in conditions and (isinstance(p['shelf_id'], list) is False):
                    keep_it = False
                    # print(p['name'] + ' écarté car pas de rayon')
                if keep_it is True:
                    filtered.append(p)
            res = filtered
        except Exception as e:
            coop_logger.error("Shop, filter_products_according_settings : %s", str(e))

        return res

    @staticmethod
    def get_all_available_bought_products_by_member(member_id):
        res = {}
        try:
            pdts = []
            limit_conditions = []
            try:
                limit_conditions = settings.SHOP_LIMIT_PRODUCTS
            except:
                pass
            api = OdooAPI()
            params = {'member_id': member_id}
            odoo_result = api.execute('lacagette.pos_member_purchases', 'get_member_available_products_among_bought_pool', params)
            if odoo_result and 'pdts' in odoo_result:
                if len(odoo_result['pdts']) > 0:
                    pids = []
                    for p in odoo_result['pdts']:
                        pids.append(p['product_id'])
                    # removed ['qty_available', '>', 0]
                    c = [['id', 'in', pids], ['sale_ok', '=', True], ['active', '=', True]]
                    if 'no_shelf' in limit_conditions:
                        p_fields.append('shelf_id')
                    res_pdts = api.search_read('product.product', c, p_fields)
                    # construct pdts as to be ordered as odoo_result
                    for p in odoo_result['pdts']:
                        for rp in res_pdts:
                            if rp['id'] == p['product_id']:
                                rp['qty_available'] = float("{0:.3f}".format(rp['qty_available']))
                                pdts.append(rp)
            res['pdts'] = CagetteShop.filter_products_according_settings(pdts)
        except Exception as e:
            res['error'] = str(e)
        return res

    #  Already exists in Inventory, but since it has to be modified soon, copied here
    @staticmethod
    def get_product_categories():
        api = OdooAPI()
        tree = []

        try:
            fields = ['parent_id', 'name']
            res = api.search_read('product.category', [], fields)
            tree = build_tree_from_categories(res)
131 132
        except Exception as e:
            coop_logger.error('get_product_categories : %s', str(e))
Administrator committed
133 134 135 136 137
        return tree

    @staticmethod
    def get_cat_children_ids(categ_id):
        cat_ids = [categ_id]
138

Administrator committed
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
        tree = CagetteShop.get_product_categories()
        branch = None
        for cats in tree:
            if 'children' in cats:
                for c in cats['children']:
                    if str(c['id']) == str(categ_id):
                        branch = c
        if not (branch is None):
            cat_ids += get_all_children_ids(branch)

        return cat_ids

    @staticmethod
    def get_cat_children(categ_id):
        children = []
        tree = CagetteShop.get_product_categories()
        branch = None
        for cats in tree:
            if 'children' in cats:
                for c in cats['children']:
                    if str(c['id']) == str(categ_id):
                        branch = c
        if not (branch is None):
            children = get_all_children(branch)

        return children

166 167 168 169 170 171 172 173 174 175 176 177
    @staticmethod
    def get_categories_nb_of_products():
        """Needs lacagette_categories Odoo module to be activated"""
        res = {}
        try:
            api = OdooAPI()
            res = api.execute('lacagette.categories', 'get_all_with_products_count', {})
        except Exception as e:
            coop_logger.error('get_categories_nb_of_products %s', str(e))
            res['error'] = str(e)
        return res

Administrator committed
178 179 180 181 182
    @staticmethod
    def get_category_products(categ_id):
        res = {}
        try:
            pdts = []
183
            limit_conditions = getattr(settings, 'SHOP_LIMIT_PRODUCTS', [])
Administrator committed
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
            api = OdooAPI()
            cat_ids = CagetteShop.get_cat_children_ids(categ_id)
            # removed ['qty_available', '>', 0]
            c = [['categ_id.id', 'in', cat_ids], ['sale_ok', '=', True], ['active', '=', True]]
            if 'categ_id' in p_fields:
                p_fields.remove('categ_id')
            if 'no_shelf' in limit_conditions:
                p_fields.append('shelf_id')
            res_pdts = api.search_read('product.product', c, p_fields, order='name ASC')
            for rp in res_pdts:
                rp['qty_available'] = float("{0:.3f}".format(rp['qty_available']))
                pdts.append(rp)
            res['pdts'] = CagetteShop.filter_products_according_settings(pdts)

        except Exception as e:
199
            coop_logger.error('get_category_products %s %s', categ_id, str(e))
Administrator committed
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
            res['error'] = str(e)
        return res

    @staticmethod
    def get_products_matching(kw):
        res = {}
        try:
            pdts = []
            limit_conditions = []
            try:
                limit_conditions = settings.SHOP_LIMIT_PRODUCTS
            except:
                pass
            api = OdooAPI()
            # removed ['qty_available', '>', 0]
            c = [['name', 'ilike', '%' + kw + '%'], ['sale_ok', '=', True], ['active', '=', True]]
            if 'categ_id' in p_fields:
                p_fields.remove('categ_id')
            if 'no_shelf' in limit_conditions:
                p_fields.append('shelf_id')
            res_pdts = api.search_read('product.product', c, p_fields, order='name ASC')
            for rp in res_pdts:
                rp['qty_available'] = float("{0:.3f}".format(rp['qty_available']))
                pdts.append(rp)
            res['pdts'] = CagetteShop.filter_products_according_settings(pdts)

        except Exception as e:
            res['error'] = str(e)
        return res


    @staticmethod
    def registrerCartInitialization(cart, partner_id):
        result = {}
        try:
            cart['init_time'] = time.time()
            cart['partner_id'] = partner_id
            partner = {}
            try:
                api = OdooAPI()
                c = [['id', '=', partner_id]]
                f = ['display_name', 'email']
                res_p = api.search_read('res.partner', c, f, 1)
                if (res_p):
                    partner = res_p[0]
            except Exception as e:
                cart['error_while_saving'] = str(e)
            cart['partner'] = partner
            c_db = CouchDB(arg_db='shop')
            result = c_db.dbc.save(cart)
        except Exception as e:
            result['error'] = str(e)
        return result


    @staticmethod
256
    def registrerCart(cart, partner_id, mode="shop"):
Administrator committed
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
        result = {}
        try:
            cart['submitted_time'] = time.time()
            cart['total'] = "{0:.2f}".format(cart['total'])
            partner = {}
            try:
                api = OdooAPI()
                c = [['id', '=', partner_id]]
                f = ['display_name', 'email']
                res_p = api.search_read('res.partner', c, f, 1)
                if (res_p):
                    partner = res_p[0]
            except Exception as e:
                cart['error_while_saving'] = str(e)
            cart['partner'] = partner
            c_db = CouchDB(arg_db='shop')
            result = c_db.updateDoc(cart)
            if result:
                try:
                    from outils.mail import CagetteMail
277
                    CagetteMail.sendCartValidation(partner['email'], cart, mode)
Administrator committed
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
                except Exception as e:
                    coop_logger.error("Shop, registrerCart : %s, %s", str(e), str(cart))
        except Exception as e:
            result['error'] = str(e)
        return result

    @staticmethod
    def get_cart_products_data(cart):
        import re
        result = {}
        try:
            api = OdooAPI()
            pids = []
            for p in cart['products']:
                pids.append(p['id'])
            c = [['id', 'in', pids]]
            f = ['qty_available', 'shelf_id']
            res_data = api.search_read('product.product', c, f)

            shelfs_sortorder = Shelfs.get_shelfs_sortorder()
            if res_data:
                for line in res_data:
                    shelf = ''
                    if not line['shelf_id'] is False:
                        for so_line in shelfs_sortorder:
                            if so_line['id'] == line['shelf_id'][0]:
                                shelf = so_line['sort_order']
                                if float(shelf) == float(re.sub(r'\..*', '', str(shelf))):
                                    shelf = str(int(shelf))
                    result[line['id']] = {'stock': line['qty_available'], 'shelf': shelf}
        except Exception as e:
            result['error'] = str(e)
        return result

    @staticmethod
    def orderCartProducts(cart, pdts_data):
        """Products will be sorted by shelf value."""
        shelf_pdts = {}
        without_shelf_pdts = []
        ordered_products = []
        for p in cart['products']:
            if p['id'] in pdts_data:
                shelf = pdts_data[p['id']]['shelf']
                p['shelf'] = shelf
                p['stock'] = "{0:.3f}".format(pdts_data[p['id']]['stock'])
                if len(str(shelf)) > 0:
                    if not (shelf in shelf_pdts):
                        shelf_pdts[shelf] = [p]
                    else:
                        shelf_pdts[shelf].append(p)
                else:
                    without_shelf_pdts.append(p)
            else:
                p['shelf'] = p['stock'] = "???"
                without_shelf_pdts.append(p)
        s_keys = sorted(shelf_pdts.keys(), key=float)

        for k in s_keys:
            ordered_products += shelf_pdts[k]
        ordered_products += without_shelf_pdts
        cart['products'] = ordered_products
        return cart

    @staticmethod
    def get_promoted_and_discounted_products():
        pdts = {'discounted': [], 'promoted': []}
        try:
            api = OdooAPI()
            shelf_ids = settings.PROMOTE_SHELFS_IDS + settings.DISCOUNT_SHELFS_IDS
            c = [['shelf_id', 'in', shelf_ids], ['sale_ok', '=', True], ['active', '=', True]]
            p_fields.append('shelf_id')
            if 'categ_id' in p_fields:
                p_fields.remove('categ_id')
            res_pdts = api.search_read('product.product', c, p_fields, order='name ASC')
            for rp in res_pdts:
                rp['qty_available'] = float("{0:.3f}".format(rp['qty_available']))
                if rp['image_small'] is False:
                    rp['image_small'] = ''
                if int(rp['shelf_id'][0]) in settings.PROMOTE_SHELFS_IDS:
                    pdts['promoted'].append(rp)
                else:
                    pdts['discounted'].append(rp)
        except Exception as e:
            pass  #  it doesn't matter
        return pdts

    @staticmethod
    def deleteCartFromCDB(cart_id):
        result = {}
        try:
            c_db = CouchDB(arg_db='shop')
            doc = c_db.getDocById(cart_id)
            result['del_action'] = c_db.delete(doc)
        except Exception as e:
            result['error'] = str(e)
        return result

    @staticmethod
    def destroy_connected_user_cart(request):
        import re
        result = {}
        try:
            # TODO : make function to clean received couchdb id
            cart_id = re.sub(r'[^0-9a-z]', '', request.POST.get('cart_id'))
            connected_mid = request.COOKIES['id']
            c_db = CouchDB(arg_db='shop')
            cart = c_db.getDocById(cart_id)
            if cart and '_id' in cart:
                if str(connected_mid) == str(cart['partner']['id']):
                    result = CagetteShop.deleteCartFromCDB(cart_id)
                else:
                    result['error'] = "Forbidden (detroy other people cart)"
            else:
                result['error'] = "Not found"
        except Exception as e:
            result['error'] = str(e)
        return result

    @staticmethod
    def change_best_date(cart_id, request):
        result = {}
        try:
            connected_mid = request.COOKIES['id']
            c_db = CouchDB(arg_db='shop')
            cart = c_db.getDocById(cart_id)
            if cart and '_id' in cart:
                if str(connected_mid) == str(cart['partner']['id']):
                    cart['best_date'] = request.POST.get('new_date')
                    result['changed'] = c_db.dbc.update([cart])
                else:
                    result['error'] = "Forbidden (detroy other people cart)"
            else:
                result['error'] = "Not found"
        except Exception as e:
            result['error'] = str(e)
        return result


    @staticmethod
    def addCartProductToCart(cart, added_cart):
        result = {}
        try:
            if cart['state'] == 'validating' or cart['state'] == 'init':
                total = float(cart['total']) + float(added_cart['total'])
                cart['total'] = "{0:.3f}".format(total)
                cart['products'] += added_cart['products']
                cart['state'] = 'validating'
                c_db = CouchDB(arg_db='shop')
                result = c_db.dbc.update([cart])
                if result and True in result[0]:
                    result = CagetteShop.deleteCartFromCDB(added_cart['_id'])
            else:
                result['error'] = "Cart status forbidden gathering (" + cart['state'] + ")"
        except Exception as e:
            result['error'] = str(e)
        return result

    @staticmethod
    def fusion_carts(request):
        import re
        result = {}
        try:
            # TODO : make function to clean received couchdb id
            cart_id = re.sub(r'[^0-9a-z]', '', request.POST.get('id'))
            add_id = re.sub(r'[^0-9a-z]', '', request.POST.get('add_id'))
            connected_mid = request.COOKIES['id']
            c_db = CouchDB(arg_db='shop')
            cart = c_db.getDocById(cart_id)
            if cart and '_id' in cart:
                if str(connected_mid) == str(cart['partner']['id']):
                    added_cart = c_db.getDocById(add_id)
                    if added_cart and '_id' in added_cart:
                        result = CagetteShop.addCartProductToCart(cart, added_cart)
                    else:
                        result['error'] = "Forbidden (gather other people carts)"
                else:
                    result['error'] = "Forbidden (gather other people carts)"
            else:
                result['error'] = "Not found"
        except Exception as e:
            result['error'] = str(e)
        return result

    @staticmethod
    def getMaxCartPerSlot():
        max_timeslot_carts = int(settings.DEFAULT_MAX_TIMESLOT_CARTS)
        try:
            f = open(max_timeslots_cart_file, 'r+')
            max_timeslot_carts = int(f.readline())
            f.close()
        except Exception as e:
            if 'No such file or directory' in str(e):
                f = open(max_timeslots_cart_file, 'w')
                f.write(str(max_timeslot_carts))
                f.close()
            else:
                coop_logger.error("Shop, getMaxCartPerSlot : %s", str(e))

        # if shop_settings contains an entry, it's value is returned
        shop_settings = CagetteShop.get_shop_settings()
        try:
            if 'max_timeslot_carts' in shop_settings:
                max_timeslot_carts = int(shop_settings['max_timeslot_carts'])
        except:
            pass
        return max_timeslot_carts

    @staticmethod
    def getSlotSize():
        slot_size = settings.SHOP_SLOT_SIZE

        return slot_size

    @staticmethod
    def get_full_slots():
        max_timeslot_carts = CagetteShop.getMaxCartPerSlot()
        c_db = CouchDB(arg_db='shop')
        all_docs = c_db.getAllDocs()  #  TODO use view /reduce
        slots = {}
        fulled = []
        for doc in all_docs:
            if doc['best_date'] in slots.keys():
                slots[doc['best_date']] += 1
            else:
                slots[doc['best_date']] = 1
        for k in slots:
            if slots[k] >= max_timeslot_carts:
                fulled.append(k)

        return fulled

    @staticmethod
    def isCartRespectingTimeSlotContraints(cart):
        import datetime
        answer = False
        try:
            received_date = datetime.datetime.strptime(cart['best_date'], '%Y-%m-%d %H:%M')
            if received_date.weekday() > 0 and received_date.weekday() < 6:
                # the received date is not a monday nor a sunday
                now_plus_delay = datetime.datetime.now() + datetime.timedelta(hours=settings.MIN_DELAY_FOR_SLOT + 1)
                d_diff = received_date - now_plus_delay
                answer = d_diff > datetime.timedelta(seconds=1)
                if answer is True:  #  else no need to go further verifying time slot
                    full_slots = CagetteShop.get_full_slots()
                    for ts in full_slots:
                        if ts == cart['best_date']:
                            answer = False
        except Exception as e:
            coop_logger.error("Shop, isCartRespectingTimeSlotContraints : %s, %s", str(e), str(cart))
        return answer

    @staticmethod
    def get_orders_by_partner_id(partner_id):
        result = {}
        # TODO : Retrieve orders and send them back
        try:
            c_db = CouchDB(arg_db='shop')
            all_docs = c_db.getAllDocs()  #  TODO use view /reduce
            p_orders = []
            for doc in all_docs:
                # print(str(doc))
                if int(doc['partner']['id']) == int(partner_id):
                    p_orders.append(doc)
            # orders are sorted by ascending best_date

            result['orders'] = sorted(p_orders, key=lambda x: x['best_date'])
        except Exception as e:
            result['error'] = str(e)
        return result

    @staticmethod
    def get_slots():
        slots = {}
        try:
            c_db = CouchDB(arg_db='shop')
            all_docs = c_db.getAllDocs()  #  TODO use view /reduce
            for doc in all_docs:
                d, h = doc['best_date'].split(' ')
                if d in slots.keys():
                    if h in slots[d].keys():
                        slots[d][h] += 1
                    else:
                        slots[d][h] = 1
                else:
                    slots[d] = {h: 1}

        except Exception as e:
            coop_logger.error("Shop, get_slots : %s", str(e))

        # print(str(sorted(slots.keys())))
        return slots

    @staticmethod
    def get_shop_settings():
        """ Get shop admin settings from json config file """
        res = {}
        try:
            with open(shop_admin_settings_file) as json_file:
                res = json.load(json_file)
                # file automatically closed with 'with..as' statement
        except Exception as e:
            res = {}

        return res

    @staticmethod
    def add_shop_closing_date(closing_date):
        """ Add a closing date to shop settings and return settings """
        res = {}
        default_data = CagetteShop.get_default_shop_admin_settings()
        try:
            with open(shop_admin_settings_file) as json_file:
                data = json.load(json_file)
            for k in default_data.keys():
                if k not in data:
                    data[k] = default_data[k]
        except:
            data = default_data

        data['closing_dates'].append(closing_date)
        data['closing_dates'].sort()

        try:
            with open(shop_admin_settings_file, 'w') as outfile:
                json.dump(data, outfile)

            res['shop_settings'] = data
        except Exception as ee:
            res['error'] = str(ee)
            return res

        return res

    @staticmethod
    def remove_shop_closing_date(closing_date):
        """ Remove a closing date from shop settings and return settings """
        res = {}
        data = {}

        try:
            with open(shop_admin_settings_file) as json_file:
                data = json.load(json_file)

            data['closing_dates'].remove(closing_date)

            with open(shop_admin_settings_file, 'w') as outfile:
                json.dump(data, outfile)

            res['shop_settings'] = data
        except Exception as e:
            res['error'] = str(e)

        return res

    @staticmethod
    def save_max_orders_ps(nb):
        res = {}
        default_data = CagetteShop.get_default_shop_admin_settings()
        try:
            with open(shop_admin_settings_file) as json_file:
                data = json.load(json_file)

            for k in default_data.keys():
                if k not in data:
                    data[k] = default_data[k]
        except:
            data = default_data

        data['max_timeslot_carts'] = nb

        try:
            with open(shop_admin_settings_file, 'w') as outfile:
                json.dump(data, outfile)

            res['shop_settings'] = data
        except Exception as ee:
            res['error'] = str(ee)

        return res

    @staticmethod
    def save_capital_message(text):
        # TODO : Factorize with save_max_orders_ps and add_shop_closing_date
        res = {}
        default_data = CagetteShop.get_default_shop_admin_settings()
        try:
            with open(shop_admin_settings_file) as json_file:
                data = json.load(json_file)

            for k in default_data.keys():
                if k not in data:
                    data[k] = default_data[k]
        except:
            data = default_data

        data['capital_message'] = text

        try:
            with open(shop_admin_settings_file, 'w') as outfile:
                json.dump(data, outfile)

            res['shop_settings'] = data
        except Exception as ee:
            res['error'] = str(ee)

        return res

    @staticmethod
    def remove_unused_orders():
        res = {'errors': []}
        try:
            from datetime import datetime
            now_unixts = datetime.timestamp(datetime.now())

            c_db = CouchDB(arg_db='shop')
            all_docs = c_db.getAllDocs()  #  TODO use view /reduce

            for doc in all_docs:
                if (doc['state'] == 'init'):
                    try:
                        diff = doc['init_time'] - now_unixts
                        if abs(diff / 3600) > settings.HOURS_FOR_VALIDATION_SHOP + 2:
                            del_res = CagetteShop.deleteCartFromCDB(doc['_id'])
                            if 'error' in del_res:
                                res['errors'].append({'ctx': 'delete', 'msg': del_res['error']})
                    except Exception as e1:
                        res['errors'].append({'ctx': 'init_doc_loop', 'msg': str(e1)})
                        coop_logger.error("Shop, remove_unused_orders (e1): %s", str(e1))

        except Exception as e2:
            coop_logger.error("Shop, remove_unused_orders (e2) : %s", str(e2))
            res['errors'].append({'ctx': 'main', 'msg': str(e2)})

        return res