Exemplo n.º 1
0
async def get_room_available(request):
    current_tenant = get_current_tenant(request)
    if current_tenant is None or 'error_code' in current_tenant:
        return json(
            {
                'error_code': 'TENANT_UNKNOWN',
                'error_message': 'Thông tin request không xác định'
            },
            status=523)

    tenant_id = current_tenant.get('id')
    now_time = now_timestamp()
    list_room_busy_ids = db.session.query(ContactRoomSession.room_id).filter(
        ContactRoomSession.end_time >= now_time,
        ContactRoomSession.checkout == True,
        ContactRoomSession.tenant_id == tenant_id,
    ).distinct(ContactRoomSession.room_id).all()

    rooms_availabel = db.session.query(Room).filter(
        Room.active == True, ~Room.id.in_(list_room_busy_ids)).all()

    results = []
    for room in rooms_availabel:
        results.append(to_dict(room))
    return json({'results': results}, status=200)
Exemplo n.º 2
0
async def get_list_item(request):
    verify_access(request)
    tenant_id = request.headers.get('tenant_id')

    categories = db.session.query(ItemCategory).filter(and_(ItemCategory.tenant_id == tenant_id,\
                                                            ItemCategory.status == 'active',\
                                                            ItemCategory.deleted == False,\
                                                            ItemCategory.is_show == True)).all()
    result_categories = []
    result_items = MOCK_ITEMS
    for category in categories:
        category_dict = to_dict(category)
        for key in exclude_attrs:
            if key in category_dict:
                del category_dict[key]

        category_dict['items'] = MOCK_ITEMS

        items_of_category = db.session.query(Item).filter(and_(Item.id == ItemCategoryRelation.item_id,\
                                                               ItemCategory.id == ItemCategoryRelation.category_id,\
                                                               ItemCategory.id == category.id,\
                                                               Item.tenant_id == tenant_id,\
                                                               Item.deleted == False,\
                                                               Item.active == True)).all()
        for item in items_of_category:
            item_dict = {
                'id': str(item.id),
                'item_no': item.item_no,
                'item_name': item.item_name,
                'type': item.item_type,
                'thumbnail': item.thumbnail,
                'items': item.images,
                'brief_desc': item.brief_desc,
                'description': item.description,
                'price_list': {},
                'is_trending': item.is_trending,
                'is_product': True,
                'is_service': False,
                'is_combo': False,
                'combo_items': [],
                'toppings': []
            }
            category_dict['items'].append(item_dict)

        result_categories.append(category_dict)

    return json({
        'time': now_timestamp(),
        'categories': result_categories,
        'items': result_items
    })
Exemplo n.º 3
0
async def pre_process_save_booking_spa_item(request, data=None, **kw):
    if data is not None:
        current_tenant = get_current_tenant(request)
        if current_tenant is None or 'error_code' in current_tenant:
            return json(
                {
                    'error_code': 'TENANT_UNKNOWN',
                    'error_message': 'Thông tin request không xác định'
                },
                status=523)

        tenant_id = current_tenant.get('id')
        now_time = now_timestamp()
        if request.method == 'POST':
            # CREATE ITEM FIRST
            new_booking_spa_item = BookingSpaItem()
            for key, value in data.items():
                if key in ['id', 'spa_items']:
                    continue
                if hasattr(new_booking_spa_item,
                           key) and not isinstance(data.get(key),
                                                   (dict, list)):
                    setattr(new_booking_spa_item, key, value)
            new_booking_spa_item.tenant_id = tenant_id
            db.session.add(new_booking_spa_item)
            print('after add')
            db.session.commit()
            data['id'] = str(new_booking_spa_item.id)

        # elif request.method == 'PUT':
        if data.get('spa_items') is not None and isinstance(
                data['spa_items'], list):
            spa_item_ids = []
            for index, _ in enumerate(data['spa_items']):
                # print("id ==================  ", _)
                spa_item_ids.append(_.get('id'))
                # CHECK EXIST
                item = Item.query.filter(and_(Item.tenant_id == tenant_id,\
                Item.id == _.get('id'))).first()
                if item is not None:
                    print("1 : ", index)
                    booking_spa_item_relations = BookingSpaItemRelations()
                    booking_spa_item_relations.item_id = _.get('id')
                    booking_spa_item_relations.spa_booking_id = data.get('id')
                    booking_spa_item_relations.tenant_id = tenant_id
                    booking_spa_item_relations.current_price = _.get(
                        'current_price')
                    db.session.add(booking_spa_item_relations)
                    db.session.flush()
                    db.session.commit()
        return json(data)
Exemplo n.º 4
0
def get_topping(parent_item, tenant_id):
    topping = []
    now_time = now_timestamp()
    categories = db.session.query(ItemCategory).join(ItemCategoryRelation).filter(
        ItemCategoryRelation.item_id == parent_item.get('id'),
        ItemCategory.category_type == 'topping',
        ItemCategory.deleted == False,
        ItemCategory.tenant_id == tenant_id
    ).all()
    active_price_list = PriceList.query.filter(and_(PriceList.tenant_id == tenant_id,\
        or_(and_(PriceList.start_time <= now_time,\
                PriceList.end_time >= now_time),\
            PriceList.is_default == True),\
        PriceList.deleted == False)).order_by(PriceList.is_default.desc()).first()

    for category in categories:
        category_dict = to_dict(category)
        category_dict['items'] = []
        items = db.session.query(Item).join(ItemCategoryRelation).filter(
            ItemCategoryRelation.category_id == category_dict.get('id'),
            Item.item_type == 'topping',
            Item.deleted == False, Item.tenant_id == tenant_id,
            Item.active == True).all()
        for item in items:
            item_dict = to_dict(item)

            if active_price_list is not None:
                # QUERY ITEM PRICE LIST
                item_price_list = ItemPriceList.query.filter(and_(ItemPriceList.tenant_id == tenant_id,\
                                                                ItemPriceList.price_list_id == active_price_list.id,\
                                                                ItemPriceList.item_id == item_dict.get('id'))).first()
                if item_price_list is not None:
                    dict_item_price = to_dict(item_price_list)
                    dict_item_price['id'] = str(dict_item_price['id'])
                    item_dict['price_list'] = dict_item_price

            item_dict['topping'] = []
            category_dict['items'].append(item_dict)

        category_item_relations = db.session.query(ItemCategoryRelation).filter(
            ItemCategoryRelation.item_id == parent_item.get('id'),
            ItemCategoryRelation.category_id == category.id
            ).first()
        category_item_relations_dict = to_dict(category_item_relations)
        del category_item_relations_dict['id']
        del category_item_relations_dict['category_id']
        del category_item_relations_dict['item_id']
        topping.append({**category_dict, **category_item_relations_dict})
    return topping
Exemplo n.º 5
0
async def get_config(request):
    current_tenant = get_current_tenant(request)
    if current_tenant is None or 'error_code' in current_tenant:
        return json(
            {
                'error_code': 'TENANT_UNKNOWN',
                'error_message': 'Thông tin request không xác định'
            },
            status=523)
    # room_id = request.args.get("room_id")
    device_id = request.args.get("device_id")
    # contact_id = request.args.get("contact_id")

    tenant_id = current_tenant.get('id')
    now_time = now_timestamp()
    filters = [
        ContactRoomSession.tenant_id == tenant_id,
        ContactRoomSession.end_time >= now_time,
        ContactRoomSession.start_time <= now_time
    ]

    if device_id is not None:
        device = db.session.query(Device).filter(
            Device.device_id == device_id).first()
        filters.append(ContactRoomSession.room_id == device.room_id)
        contact_room_session = db.session.query(ContactRoomSession).filter(
            *filters).first()
        if contact_room_session is not None:
            contact_room_session = to_dict(contact_room_session)
            contact = db.session.query(Contact).filter(
                Contact.id == contact_room_session.get('contact_id')).first()
            room = db.session.query(Room).filter(
                Room.id == contact_room_session.get('room_id')).first()
            contact_room_session['contact'] = to_dict(contact)
            contact_room_session['room'] = to_dict(room)
            contact_room_session['device'] = to_dict(device)
            return json(contact_room_session, status=200)
        else:
            contact_room_session = ContactRoomSession()
            return json(to_dict(contact_room_session), status=200)
    else:
        return json(
            {
                "error_code": "MISSING PARAMETER",
                "error_message": "Không tìm thấy param device_id"
            },
            status=422)
Exemplo n.º 6
0
async def service_get_catagories(request):
    current_tenant = get_current_tenant(request)
    if current_tenant is None or 'error_code' in current_tenant:
        return json({
            'error_code': 'TENANT_UNKNOWN',
            'error_message': 'Thông tin request không xác định'
        }, status=523)

    tenant_id = current_tenant.get('id')
    now_time = now_timestamp()

    service_no = request.args.get('service_no')
    service_info = db.session.query(Service).filter(Service.service_no == service_no, Service.tenant_id == tenant_id).first()
    providers = service_info.providers
    service_info = to_dict(service_info)
    service_info['providers'] = []
    for provider in providers:
        service_info['providers'].append(to_dict(provider))
    service_info['options'] = get_option_service(service_no)
    return json(service_info, status = 200)
Exemplo n.º 7
0
async def create_contact(request):
    current_tenant = get_current_tenant(request)
    tenant_id = current_tenant.get('id')
    data = request.json
    if data is None:
        return json({'error_code': '', 'error_message': ''}, status=520)

    make_stable_data(request, data)
    # CHECK CONTACT EXIST
    exist_contact = Contact.query.filter(and_(Contact.tenant_id == tenant_id,\
                                              Contact.phone == data.get('phone'))).first()
    if exist_contact is not None:
        return json(
            {
                'error_code': 'RECORD_EXIST',
                'error_message': 'Bản ghi đã tồn tại'
            },
            status=520)

    contact = Contact()
    for key in data:
        if hasattr(contact, key) == True:
            setattr(contact, key, data[key])
        else:
            print(">>>>>> ", key, data[key])

    # GENERATE CONTACT NO
    contact_no_seq = db.session.query(ContactNoSeq).filter(
        ContactNoSeq.id == tenant_id).with_for_update().first()
    if contact_no_seq is None:
        contact_no_seq = ContactNoSeq()
        contact_no_seq.id = tenant_id
        contact_no_seq.current_no = 1
    else:
        contact_no_seq.current_no += 1

    contact.contact_no = contact_no_seq.current_no
    contact.tenant_id = tenant_id
    try:
        db.session.add(contact)
        db.session.commit()
        db.session.add(contact_no_seq)
        db.session.commit()
    except:
        db.session.rollback()

    # TAGS
    if data.get('tags') is not None and isinstance(data['tags'], list):
        for tag in data['tags']:
            # FIND EXIST
            exist_tag = ContactTags.query.filter(and_(ContactTags.tenant_id == tenant_id,\
                                                      ContactTags.id == tag.get('id'))).first()
            contact_tags_id = None
            if exist_tag is None:
                # CREATE NEW TAGS
                new_tag = ContactTags()
                new_tag.tag_label = tag.get('tag_label')
                new_tag.tag_ascii = tag.get('tag_ascii')
                new_tag.tenant_id = tenant_id
                db.session.add(new_tag)
                db.session.commit()
                contact_tags_id = new_tag.id
            else:
                contact_tags_id = exist_tag.id

            # CREATE CONTACT TAGS DETAILS
            new_contact_tags_details = ContactTagsDetails()
            new_contact_tags_details.contact_id = contact.id
            new_contact_tags_details.contact_tags_id = contact_tags_id
            new_contact_tags_details.timestamp = now_timestamp()
            new_contact_tags_details.tenant_id = tenant_id
            db.session.add(new_contact_tags_details)
            db.session.commit()

    return json({'id': str(contact.id)})
Exemplo n.º 8
0
def model_onupdate_listener(mapper, connection, instance):
    instance.created_at = instance.created_at
    instance.updated_at = now_timestamp()
    if instance.deleted is True:
        instance.deleted_at = now_timestamp()
Exemplo n.º 9
0
def model_oncreate_listener(mapper, connection, instance):
    instance.created_at = now_timestamp()
    instance.updated_at = now_timestamp()
Exemplo n.º 10
0
async def get_topping(request):
    current_tenant = get_current_tenant(request)
    if current_tenant is None or 'error_code' in current_tenant:
        return json({
            'error_code': 'TENANT_UNKNOWN',
            'error_message': 'Thông tin request không xác định'
        }, status=523)

    tenant_id = current_tenant.get('id')
    now_time = now_timestamp()

    item_id = request.args.get('item_id')

    topping = []
    active_price_list = PriceList.query.filter(and_(PriceList.tenant_id == tenant_id,\
        or_(and_(PriceList.start_time <= now_time,\
                PriceList.end_time >= now_time),\
            PriceList.is_default == True),\
        PriceList.deleted == False)).order_by(PriceList.is_default.desc()).first()

    categories_ids = db.session.query(ItemCategoryRelation.category_id).filter(
        ItemCategoryRelation.item_id == item_id, 
        ItemCategoryRelation.tenant_id == tenant_id
    ).distinct(ItemCategoryRelation.category_id).all()

    categories = db.session.query(ItemCategory).filter(
        ItemCategory.id.in_(categories_ids),
        ItemCategory.category_type == 'topping',
        ItemCategory.deleted == False,
        ItemCategory.tenant_id == tenant_id
    ).all()

    all_item = db.session.query(Item, ItemCategoryRelation).join(ItemCategoryRelation).filter(
            ItemCategoryRelation.category_id.in_(categories_ids),
            Item.item_type == 'topping',
            Item.deleted == False, Item.tenant_id == tenant_id,
            Item.active == True).all()
    # all_item = []
    all_item_category_relations = db.session.query(ItemCategoryRelation).filter(
            ItemCategoryRelation.item_id == item_id,
            ItemCategoryRelation.tenant_id == tenant_id
            ).all()
    all_item_category_relations_dict = {}
    for item_category in all_item_category_relations:
        all_item_category_relations_dict[item_category.category_id] = to_dict(item_category)
    
    all_item_price_list = ItemPriceList.query.filter(and_(ItemPriceList.tenant_id == tenant_id,\
                                                        ItemPriceList.price_list_id == active_price_list.id,\
                                                        )).all()
    all_item_price_list_dict = {}
    for item_price_list in all_item_price_list:
        all_item_price_list_dict[str(item_price_list.item_id)] = item_price_list

    for category in categories:
        category_dict = to_dict(category)
        category_dict['items'] = []
        
        items = []
        for item, item_relation in all_item:
            if str(item_relation.category_id) == category_dict.get('id'):
                items.append(item)
        # items = []
        for item in items:
            item_dict = to_dict(item)

            if active_price_list is not None:
                # QUERY ITEM PRICE LIST
                # item_price_list = ItemPriceList.query.filter(and_(ItemPriceList.tenant_id == tenant_id,\
                #                                                 ItemPriceList.price_list_id == active_price_list.id,\
                #                                                 ItemPriceList.item_id == item_dict.get('id'))).first()
                # item_price_list = ItemPriceList()
                item_price_list = all_item_price_list_dict.get(item_dict.get('id'))
                if item_price_list is not None:
                    dict_item_price = to_dict(item_price_list)
                    dict_item_price['id'] = str(dict_item_price['id'])
                    item_dict['price_list'] = dict_item_price

            category_dict['items'].append(item_dict)

        # category_item_relations = db.session.query(ItemCategoryRelation).filter(
        #     ItemCategoryRelation.item_id == parent_item.get('id'),
        #     ItemCategoryRelation.category_id == category.id
        #     ).first()
        # category_item_relations_dict = to_dict(category_item_relations)
        category_item_relations_dict = all_item_category_relations_dict.get(category.id)
        
        del category_item_relations_dict['id']
        del category_item_relations_dict['category_id']
        del category_item_relations_dict['item_id']
        topping.append({**category_dict, **category_item_relations_dict})
    
    return json({"categories": topping}, status = 200)
Exemplo n.º 11
0
async def pre_process_save_item(request, data=None, **kw):
    if data is not None:
        current_tenant = get_current_tenant(request)
        if current_tenant is None or 'error_code' in current_tenant:
            return json({
                'error_code': 'TENANT_UNKNOWN',
                'error_message': 'Thông tin request không xác định'
            }, status=523)

        tenant_id = current_tenant.get('id')
        now_time = now_timestamp()

        if request.method == 'POST':
            # CREATE ITEM FIRST
            new_item = Item()
            for key, value in data.items():
                if key in ['id', 'variants', 'categories', 'tenant_id', 'price_lists', 'extra_attributes']:
                    continue
                if hasattr(new_item, key) and not isinstance(data.get(key), (dict)):
                    setattr(new_item, key, value)
            # print(new_item.__dict__.keys())
            new_item.tenant_id = tenant_id
            db.session.add(new_item)
            db.session.commit()
            data['id'] = str(new_item.id)
        elif request.method == 'PUT':
            current_item = db.session.query(Item).filter(and_(Item.tenant_id == tenant_id,\
                                                              Item.id == data.get('id')))
            is_exist = db.session.query(literal(True)).filter(current_item.exists()).scalar()
            if is_exist == True:
                tmp_item = Item()
                update_item = {}
                for key in data:
                    if key in ['id', 'variants', 'categories', 'tenant_id', 'price_lists', 'extra_attributes']:
                        continue
                    if hasattr(tmp_item, key) == True:
                        update_item[key] = data.get(key)

                current_item.update(update_item)
                db.session.commit()

        # CHECK CATEGORY
        if data.get('categories') is not None and isinstance(data['categories'], list):
            item_category_ids = []
            for index, _ in enumerate(data['categories']):
                # print("id ==================  ", _)
                item_category_ids.append(_.get('id'))
                # if _.get('category_type') == 'default':
                #     item_category_ids.append(_.get('id'))
                # CHECK EXIST
                # category_info = db.session.query(ItemCategory).filter(ItemCategory.id == _.get('id')).first()
                # if category_info is not None and category_info.category_type == 'default':
                #     item_category_ids.append(_.get('id'))

                exist_item_category_relation = ItemCategoryRelation.query.filter(and_(ItemCategoryRelation.tenant_id == tenant_id,\
                                                                                      ItemCategoryRelation.category_id == _.get('id'),\
                                                                                      ItemCategoryRelation.item_id == data.get('id'))).first()
                if exist_item_category_relation is None:
                    new_item_category_relation = ItemCategoryRelation()
                    new_item_category_relation.category_id = _.get('id')
                    new_item_category_relation.item_id = data.get('id')
                    new_item_category_relation.tenant_id = tenant_id
                    # new_item_category_relation.extra_data = _.get('extra_data')
                    db.session.add(new_item_category_relation)
                
            db.session.commit()
            # DELETE ALL UNUSE RELATIONS
            db.session.query(ItemCategoryRelation).filter(and_(ItemCategoryRelation.tenant_id == tenant_id,\
                                                               ItemCategoryRelation.item_id == data.get('id'),\
                                                               ~ItemCategoryRelation.category_id.in_(item_category_ids))).delete(synchronize_session=False)
        # PRICE LIST
        active_price_list = None
        if data.get('price_list') is not None and data['price_list'].get('price_list_id') is not None:
            active_price_list = db.session.query(PriceList).filter(and_(PriceList.tenant_id == tenant_id,\
                                                                        PriceList.id == data['price_list'].get('price_list_id'))).first()
        else:
            active_price_list = db.session.query(PriceList).filter(and_(PriceList.tenant_id == tenant_id,\
                                                                        or_(and_(PriceList.start_time <= now_time,\
                                                                                PriceList.end_time >= now_time),\
                                                                            PriceList.is_default == True),\
                                                                        PriceList.deleted == False)).order_by(PriceList.is_default.desc()).first()

        # print ("active_price_list ", active_price_list)
        if active_price_list is not None:
            current_variant_price_list = db.session.query(ItemPriceList).filter(and_(ItemPriceList.tenant_id == tenant_id,\
                                                                                   ItemPriceList.price_list_id == active_price_list.id,\
                                                                                   ItemPriceList.item_id == data.get('id')))

            exist_variant_price_list = db.session.query(literal(True)).filter(current_variant_price_list.exists()).scalar()

            if data.get('price_list') is not None:
                variants = []
                if data['price_list'].get('variants') is not None:
                    variants = data['price_list'].get('variants')

                if isinstance(variants, list) and len(variants) > 0:
                    if exist_variant_price_list == True:
                        current_variant_price_list.update({
                            'variants': variants,
                            'list_price': 0,
                            'delivery_price': 0
                        })
                        db.session.commit()
                    else:
                        new_variant_price_list = ItemPriceList()
                        new_variant_price_list.tenant_id = tenant_id
                        new_variant_price_list.price_list_id = active_price_list.id
                        new_variant_price_list.item_id = data.get('id')
                        new_variant_price_list.variants = variants
                        new_variant_price_list.list_price = 0
                        new_variant_price_list.delivery_price = 0
                        db.session.add(new_variant_price_list)
                        db.session.commit()
                        
                else:
                    if exist_variant_price_list == True:
                        delivery_price = data['price_list'].get('delivery_price', 0)
                        list_price = data['price_list'].get('list_price')
                        current_variant_price_list.update({
                            'variants': None,
                            'list_price': float(list_price) if list_price is not None else 0,
                            'delivery_price': float(delivery_price) if delivery_price is not None else 0
                        })
                        db.session.commit()
                    else:
                        print ("<>><>><><><> CREATE ITEM PRICE LIST")
                        new_variant_price_list = ItemPriceList()
                        new_variant_price_list.tenant_id = tenant_id
                        new_variant_price_list.price_list_id = active_price_list.id
                        new_variant_price_list.item_id = data.get('id')
                        new_variant_price_list.list_price = float(data['price_list'].get('list_price'))
                        new_variant_price_list.delivery_price = float(data['price_list'].get('delivery_price', 0))
                        new_variant_price_list.variants = None
                        db.session.add(new_variant_price_list)
                        db.session.commit()
                        print ("<>><>><><><> DONE ITEM PRICE LIST")

        # VARIANTS
        variants_ids = []
        if data.get('variants') is not None and isinstance(data['variants'], list):
            for index, _ in enumerate(data['variants']):
                variants_ids.append(_.get('id'))
                item_variant = db.session.query(ItemVariants).filter(and_(ItemVariants.tenant_id == tenant_id,\
                                                                          ItemVariants.item_id == data.get('id')))
                is_item_variant_exist = db.session.query(literal(True)).filter(item_variant.exists()).scalar()
                if is_item_variant_exist == True:
                    # UPDATE
                    update_variant = {
                        'variant_name': _.get('variant_name'),
                        'variant_attr': _.get('variant_attr'),
                        'item_id': data.get('id'),
                        'sort_number': index + 1,
                        'variants_details': _.get('variants_details')
                    }
                    item_variant.update(update_variant)
                else:
                    # CREATE
                    new_item_variant = ItemVariants()
                    new_item_variant.variant_name = _.get('variant_name')
                    new_item_variant.variant_attr = _.get('variant_attr')
                    new_item_variant.item_id = data.get('id')
                    new_item_variant.sort_number = index + 1
                    new_item_variant.variants_details = _.get('variants_details')
                    db.session.add(new_item_variant)
                    db.session.flush()

            db.session.commit()
        # DELETE ALL VARIANTS NOT IN LIST
        unuse_variants = db.session.query(ItemVariants).filter(and_(ItemVariants.tenant_id == tenant_id,\
                                                                    ItemVariants.item_id == data.get('id'),\
                                                                    ~ItemVariants.id.in_(variants_ids))).delete(synchronize_session=False)

        if data.get("price_lists") is not None and isinstance(data.get("price_lists"), list):
            for _ in data.get("price_lists"):
                if _.get('item_id') is None:
                    _['item_id'] = data.get('id')
                item_price_list = db.session.query(ItemPriceList).filter(
                    ItemPriceList.item_id == _.get('item_id'),
                    ItemPriceList.price_list_id == _.get('price_list_id')
                )
                item_price_list_exist = db.session.query(literal(True)).filter(item_price_list.exists()).scalar()
                print('--item_price_list_exist---', item_price_list_exist)
                if not item_price_list_exist:
                    new_item_price_list = ItemPriceList()
                    for key, value in _.items():
                        if key in ['id']:
                            continue
                        if hasattr(new_item_price_list, key) and not isinstance(value, (dict, list)):
                            setattr(new_item_price_list, key, value)
                        # if key == 'item_id':
                        #     setattr(new_item_price_list, key, data.get('id'))
                            
                    # print('asdgasgdag', to_dict(new_item_price_list))
                    new_item_price_list.tenant_id = tenant_id
                    db.session.add(new_item_price_list)
                else:
                    item_price_list.update({
                        "list_price": _.get('list_price'),
                        "delivery_price": _.get('delivery_price'),
                        "image": _.get('image'),
                        "variants": _.get('variants'),
                        "note": _.get('note'),
                        "extra_data": _.get('extra_data')
                    })
                db.session.commit()
        return json(data)
Exemplo n.º 12
0
async def post_process_get_item(request, instance_id=None, result=None, **kw):
    current_tenant = get_current_tenant(request)
    if current_tenant is None or 'error_code' in current_tenant:
        return json({
            'error_code': 'TENANT_UNKNOWN',
            'error_message': 'Thông tin request không xác định'
        }, status=523)
    tenant_id = current_tenant.get('id')
    now_time = now_timestamp()
    # GET SINGLE
    if result is not None and result.get('id') is not None:
        # PRICE LIST
        active_price_list = PriceList.query.filter(and_(PriceList.tenant_id == tenant_id,\
                                                        or_(and_(PriceList.start_time <= now_time,\
                                                                PriceList.end_time >= now_time),\
                                                            PriceList.is_default == True),\
                                                        PriceList.deleted == False)).order_by(PriceList.is_default.desc()).first()

        if active_price_list is not None:
            # QUERY ITEM PRICE LIST
            item_price_list = ItemPriceList.query.filter(and_(ItemPriceList.tenant_id == tenant_id,\
                                                               ItemPriceList.price_list_id == active_price_list.id,\
                                                               ItemPriceList.item_id == result.get('id'))).first()
            if item_price_list is not None:
                dict_item_price = to_dict(item_price_list)
                dict_item_price['id'] = str(dict_item_price['id'])
                result['price_list'] = dict_item_price

        # COMBO
        combos = []
        item_combos = db.session.query(ItemCombo).filter(and_(ItemCombo.parent_id == result.get('id'),\
                                                                  ItemCombo.tenant_id == tenant_id)).all()
        if item_combos is not None:
            for _ in item_combos:
                combo_dict = to_dict(_)
                combo_dict['id'] = str(combo_dict['id'])
                combos.append(combo_dict)
        result['combos'] = combos
        # VARIANTS
        variants = []
        item_variants = db.session.query(ItemVariants).filter(and_(ItemVariants.item_id == result.get('id'),\
                                                                  ItemVariants.tenant_id == tenant_id)).all()
        if item_variants is not None:
            for _ in item_variants:
                variant_dict = to_dict(_)
                variant_dict['id'] = str(variant_dict['id'])
                variants.append(variant_dict)
        result['variants'] = variants

        if isinstance(result.get('price_lists'), list) and result.get('price_lists') is not None:
            new_price_lists = []
            for price_list in result.get('price_lists'):
                item_price_list = ItemPriceList.query.filter(and_(ItemPriceList.tenant_id == tenant_id,\
                                                                    ItemPriceList.price_list_id == price_list.get('id'),\
                                                                    ItemPriceList.item_id == result.get('id'))).first()
                item_price_list = to_dict(item_price_list)
                del item_price_list['id']
                price_list = {**price_list, **item_price_list}
                new_price_lists.append(price_list)
            result['price_lists'] = new_price_lists

        # result['categories'] = [] 
        # categories = db.session.query(ItemCategory).join(ItemCategoryRelation, \
        # ItemCategory.id == ItemCategoryRelation.category_id).filter(           \
        #     ItemCategory.category_type == result.get('item_type'),
        #     ItemCategory.tenant_id == tenant_id,
        #     ItemCategory.deleted == False).all()
        # for cate in categories:
        #     result['categories'].append(to_dict(cate))
        if result.get('item_type') == 'default' or result.get('item_type') == 'combo':
            result['topping'] = []

            topping = []
            categories = db.session.query(ItemCategory, ItemCategoryRelation).join(ItemCategoryRelation).filter(
                ItemCategoryRelation.item_id == result.get('id'),
                ItemCategory.category_type == 'topping',
                ItemCategory.deleted == False,
                ItemCategory.tenant_id == tenant_id
            ).all()
            active_price_list = PriceList.query.filter(and_(PriceList.tenant_id == tenant_id,\
                or_(and_(PriceList.start_time <= now_time,\
                        PriceList.end_time >= now_time),\
                    PriceList.is_default == True),\
                PriceList.deleted == False)).order_by(PriceList.is_default.desc()).first()

            for category, item_category_relation in categories:
                category_dict = to_dict(category)
                category_dict['items'] = []
                items = db.session.query(Item).join(ItemCategoryRelation).filter(
                    ItemCategoryRelation.category_id == category_dict.get('id'),
                    Item.item_type == 'topping',
                    Item.deleted == False, Item.tenant_id == tenant_id,
                    Item.active == True).all()
                for item in items:
                    item_dict = to_dict(item)

                    if active_price_list is not None:
                        # QUERY ITEM PRICE LIST
                        item_price_list = ItemPriceList.query.filter(and_(ItemPriceList.tenant_id == tenant_id,\
                                                                        ItemPriceList.price_list_id == active_price_list.id,\
                                                                        ItemPriceList.item_id == item_dict.get('id'))).first()
                        if item_price_list is not None:
                            dict_item_price = to_dict(item_price_list)
                            dict_item_price['id'] = str(dict_item_price['id'])
                            item_dict['price_list'] = dict_item_price

                    item_dict['topping'] = []
                    category_dict['items'].append(item_dict)
                item_category_relation = to_dict(item_category_relation)    
                # del item_category_relation['id']
                del category_dict['id']
                del item_category_relation['item_id']
                category_dict = {**category_dict, **item_category_relation}
                topping.append(to_dict(category_dict))
                result['topping'] = topping

    elif result is not None:
        active_price_list = PriceList.query.filter(and_(PriceList.tenant_id == tenant_id,\
                                                        or_(and_(PriceList.start_time <= now_time,\
                                                                PriceList.end_time >= now_time),\
                                                            PriceList.is_default == True),\
                                                        PriceList.deleted == False)).order_by(PriceList.is_default.desc()).first()
        if isinstance(result.get('objects'), list):
            for index, _ in enumerate(result['objects']):
                # JOIN PRICE LIST
                item_price_list = ItemPriceList.query.filter(and_(ItemPriceList.tenant_id == tenant_id,\
                                                                ItemPriceList.price_list_id == active_price_list.id,\
                                                                ItemPriceList.item_id == _.get('id'))).first()
                if item_price_list is not None:
                    dict_item_price = to_dict(item_price_list)
                    dict_item_price['id'] = str(dict_item_price['id'])
                    result['objects'][index]['price_list'] = dict_item_price
Exemplo n.º 13
0
async def pre_process_save_service(request, data=None, **kw):
    if data is not None:
        current_tenant = get_current_tenant(request)
        if current_tenant is None or 'error_code' in current_tenant:
            return json({
                'error_code': 'TENANT_UNKNOWN',
                'error_message': 'Thông tin request không xác định'
            }, status=523)

        tenant_id = current_tenant.get('id')

        now_time = now_timestamp()

        if request.method == 'POST':
            # CREATE ITEM FIRST
            new_service = Service()
            for key, value in data.items():
                if key in ['id','providers']:
                    continue
                if hasattr(new_service, key) and not isinstance(data.get(key), (dict,list)):
                    setattr(new_service, key, value)
            # print(new_item.__dict__.keys())
            new_service.tenant_id = tenant_id
            db.session.add(new_service)
            db.session.flush()
            data['id'] = str(new_service.id)
        elif request.method == 'PUT':
            current_service = db.session.query(Service).filter(and_(Service.tenant_id == tenant_id,\
                                                              Service.id == data.get('id')))
            is_exist = db.session.query(literal(True)).filter(current_service.exists()).scalar()
            if is_exist == True:
                tmp_item = Service()
                update_item = {}
                for key in data:
                    if key in ['id', 'providers', 'service_no', 'tenant_id']:
                        continue
                    if hasattr(tmp_item, key) == True:
                        update_item[key] = data.get(key)

                current_service.update(update_item)
                db.session.commit()

        # CHECK PROVIDERS
        if data.get('providers') is not None and isinstance(data['providers'], list):
            services_providers_ids = []
            for index, _ in enumerate(data['providers']):
                # print("id ==================  ", _)
                services_providers_ids.append(_.get('id'))
                # CHECK EXIST
                exist_service_provider_relation = ServicesProviders.query.filter(and_(ServicesProviders.tenant_id == tenant_id,\
                                                                                      ServicesProviders.provider_id == _.get('id'),\
                                                                                      ServicesProviders.service_id == data.get('id'))).first()
                if exist_service_provider_relation is None:
                    new_service_provider_relation = ServicesProviders()
                    new_service_provider_relation.provider_id = _.get('id')
                    new_service_provider_relation.service_id = data.get('id')
                    new_service_provider_relation.tenant_id = tenant_id
                    db.session.add(new_service_provider_relation)
            db.session.commit()
            # DELETE ALL UNUSE RELATIONS
            db.session.query(ServicesProviders).filter(and_(ServicesProviders.tenant_id == tenant_id,\
                                                               ServicesProviders.service_id == data.get('id'),\
                                                               ~ServicesProviders.provider_id.in_(services_providers_ids))).delete(synchronize_session=False)
        db.session.commit()
        return json(data)
Exemplo n.º 14
0
async def service_get_catagories(request):
    current_tenant = get_current_tenant(request)
    if current_tenant is None or 'error_code' in current_tenant:
        return json({
            'error_code': 'TENANT_UNKNOWN',
            'error_message': 'Thông tin request không xác định'
        }, status=523)

    tenant_id = current_tenant.get('id')
    now_time = now_timestamp()

    service_no = request.args.get('service_no')
    service_id = db.session.query(Service.id).filter(Service.service_no == service_no, Service.tenant_id == tenant_id).first()
    categories_ids = db.session.query(ItemCategoryRelation.category_id).join(Item).filter(
        Item.service_id == service_id, 
        ItemCategoryRelation.item_id == Item.id,
        Item.item_type == 'default'
    ).distinct(ItemCategoryRelation.category_id).all()

    # print('----categories_ids-----', categories_ids)
    categories = db.session.query(ItemCategory).filter(
        ItemCategory.deleted == False,
        ItemCategory.tenant_id == tenant_id,
        ItemCategory.category_type == 'default',
        ItemCategory.id.in_(categories_ids)
    ).all()

    results = []
    active_price_list = PriceList.query.filter(and_(PriceList.tenant_id == tenant_id,\
                                                        or_(and_(PriceList.start_time <= now_time,\
                                                                PriceList.end_time >= now_time),\
                                                            PriceList.is_default == True),\
                                                        PriceList.deleted == False)).order_by(PriceList.is_default.desc()).first()
    
    if len(categories) != 0:
        for category in categories:
            category_dict = to_dict(category)
            category_dict['items'] = []
            items = db.session.query(Item).join(ItemCategoryRelation).filter(
                ItemCategoryRelation.category_id == category_dict.get('id'),
                Item.item_type == 'default',
                Item.deleted == False, Item.tenant_id == tenant_id,
                Item.active == True).all()
            for item in items:
                item_dict = to_dict(item)

                if active_price_list is not None:
                    # QUERY ITEM PRICE LIST
                    item_price_list = ItemPriceList.query.filter(and_(ItemPriceList.tenant_id == tenant_id,\
                                                                    ItemPriceList.price_list_id == active_price_list.id,\
                                                                    ItemPriceList.item_id == item_dict.get('id'))).first()
                    if item_price_list is not None:
                        dict_item_price = to_dict(item_price_list)
                        dict_item_price['id'] = str(dict_item_price['id'])
                        item_dict['price_list'] = dict_item_price

                # item_dict['topping'] = get_topping(item_dict, tenant_id)
                category_dict['items'].append(item_dict)
            results.append(to_dict(category_dict))
    else:
        category = ItemCategory()
        category_dict = to_dict(category)
        category_dict['items'] = []
        items = db.session.query(Item).filter(
                Item.item_type == 'default',
                Item.service_id == service_id,
                Item.deleted == False, Item.tenant_id == tenant_id,
                Item.active == True).all()
        for item in items:
            item_dict = to_dict(item)
            if active_price_list is not None:
                    # QUERY ITEM PRICE LIST
                item_price_list = ItemPriceList.query.filter(and_(ItemPriceList.tenant_id == tenant_id,\
                                                                ItemPriceList.price_list_id == active_price_list.id,\
                                                                ItemPriceList.item_id == item_dict.get('id'))).first()
                if item_price_list is not None:
                    dict_item_price = to_dict(item_price_list)
                    dict_item_price['id'] = str(dict_item_price['id'])
                    item_dict['price_list'] = dict_item_price
            # item_dict['topping'] = get_topping(item_dict, tenant_id)
            category_dict['items'].append(item_dict)
        results.append(to_dict(category_dict))
    return json({'categories': results, "options": get_option_service(service_no)}, status = 200)
Exemplo n.º 15
0
def get_topping_test(parent_item, tenant_id, active_price_list):
    topping = []
    now_time = now_timestamp()
    # categories = db.session.query(ItemCategory).join(ItemCategoryRelation).filter(
    #     ItemCategoryRelation.item_id == parent_item.get('id'),
    #     ItemCategory.category_type == 'topping',
    #     ItemCategory.deleted == False,
    #     ItemCategory.tenant_id == tenant_id
    # ).all()
    categories_ids = db.session.query(ItemCategoryRelation.category_id).filter(
        ItemCategoryRelation.item_id == parent_item.get('id'), 
        ItemCategoryRelation.tenant_id == tenant_id
    ).distinct(ItemCategoryRelation.category_id).all()

    categories = db.session.query(ItemCategory).filter(
        ItemCategory.id.in_(categories_ids),
        ItemCategory.category_type == 'topping',
        ItemCategory.deleted == False,
        ItemCategory.tenant_id == tenant_id
    ).all()

    all_item = db.session.query(Item, ItemCategoryRelation).join(ItemCategoryRelation).filter(
            ItemCategoryRelation.category_id.in_(categories_ids),
            Item.item_type == 'topping',
            Item.deleted == False, Item.tenant_id == tenant_id,
            Item.active == True).all()
    # all_item = []
    all_item_category_relations = db.session.query(ItemCategoryRelation).filter(
            ItemCategoryRelation.item_id == parent_item.get('id'),
            ItemCategoryRelation.tenant_id == tenant_id
            ).all()
    all_item_category_relations_dict = {}
    for item_category in all_item_category_relations:
        all_item_category_relations_dict[item_category.category_id] = to_dict(item_category)
    
    all_item_price_list = ItemPriceList.query.filter(and_(ItemPriceList.tenant_id == tenant_id,\
                                                        ItemPriceList.price_list_id == active_price_list.id,\
                                                        )).all()
    all_item_price_list_dict = {}
    for item_price_list in all_item_price_list:
        all_item_price_list_dict[str(item_price_list.item_id)] = item_price_list

    for category in categories:
        category_dict = to_dict(category)
        category_dict['items'] = []
        
        items = []
        for item, item_relation in all_item:
            if str(item_relation.category_id) == category_dict.get('id'):
                items.append(item)
        # items = []
        for item in items:
            item_dict = to_dict(item)

            if active_price_list is not None:
                # QUERY ITEM PRICE LIST
                # item_price_list = ItemPriceList.query.filter(and_(ItemPriceList.tenant_id == tenant_id,\
                #                                                 ItemPriceList.price_list_id == active_price_list.id,\
                #                                                 ItemPriceList.item_id == item_dict.get('id'))).first()
                # item_price_list = ItemPriceList()
                item_price_list = all_item_price_list_dict.get(item_dict.get('id'))
                if item_price_list is not None:
                    dict_item_price = to_dict(item_price_list)
                    dict_item_price['id'] = str(dict_item_price['id'])
                    item_dict['price_list'] = dict_item_price

            item_dict['topping'] = []
            category_dict['items'].append(item_dict)

        # category_item_relations = db.session.query(ItemCategoryRelation).filter(
        #     ItemCategoryRelation.item_id == parent_item.get('id'),
        #     ItemCategoryRelation.category_id == category.id
        #     ).first()
        # category_item_relations_dict = to_dict(category_item_relations)
        category_item_relations_dict = all_item_category_relations_dict.get(category.id)
        
        del category_item_relations_dict['id']
        del category_item_relations_dict['category_id']
        del category_item_relations_dict['item_id']
        topping.append({**category_dict, **category_item_relations_dict})
    return topping
Exemplo n.º 16
0
async def pre_process_save_sale_order(request, data=None, **kw):
    if data is not None:
        current_tenant = get_current_tenant(request)
        if current_tenant is None or 'error_code' in current_tenant:
            return json(
                {
                    'error_code': 'TENANT_UNKNOWN',
                    'error_message': 'Thông tin request không xác định'
                },
                status=523)

        tenant_id = current_tenant.get('id')
        now_time = now_timestamp()

        device_info = db.session.query(Device).filter(
            Device.device_id == data.get('device_id')).first()
        room_id = str(device_info.room_id)

        if request.method == 'POST':
            # CREATE ITEM FIRST
            new_sale_order = Salesorder()
            for key, value in data.items():
                if key in ['id', 'salesorder_items', 'forward_status']:
                    continue
                if hasattr(new_sale_order,
                           key) and not isinstance(data.get(key),
                                                   (dict, list)):
                    setattr(new_sale_order, key, value)
            # print(new_item.__dict__.keys())
            new_sale_order.tenant_id = tenant_id

            book_time_obj = datetime.fromtimestamp(
                data.get("book_time") // 1000)
            new_sale_order.book_day = book_time_obj.day
            new_sale_order.book_month = book_time_obj.month
            new_sale_order.book_year = book_time_obj.year
            new_sale_order.book_hour = book_time_obj.hour
            new_sale_order.book_minute = book_time_obj.minute
            new_sale_order.book_day_of_week = book_time_obj.weekday()
            new_sale_order.room_id = room_id

            db.session.add(new_sale_order)
            db.session.commit()
            data['id'] = str(new_sale_order.id)
            await push_socket_to_cms(tenant_id, data)
        elif request.method == 'PUT':
            current_sale_order = db.session.query(Salesorder).filter(and_(Salesorder.tenant_id == tenant_id,\
                                                              Salesorder.id == data.get('id')))
            is_exist = db.session.query(literal(True)).filter(
                current_sale_order.exists()).scalar()
            if is_exist == True:
                tmp_sale_order = Salesorder()
                update_sale_order = {}
                for key in data:
                    if key in [
                            'salesorder_items', 'forward_status', 'room',
                            'service', 'contact', 'provider', 'currency'
                    ]:
                        continue
                    if hasattr(tmp_sale_order, key) == True:
                        update_sale_order[key] = data.get(key)
                        # setattr(update_sale_order, key, data.get(key))
                book_time_obj = datetime.fromtimestamp(
                    data.get("book_time") // 1000)
                update_sale_order["book_day"] = book_time_obj.day
                update_sale_order["book_month"] = book_time_obj.month
                update_sale_order["book_year"] = book_time_obj.year
                update_sale_order["book_hour"] = book_time_obj.hour
                update_sale_order["book_minute"] = book_time_obj.minute
                update_sale_order["book_day_of_week"] = book_time_obj.weekday()
                update_sale_order["room_id"] = room_id
                print(update_sale_order)
                current_sale_order.update(update_sale_order)
                db.session.commit()

        # SAVE SALE ORDER ITEMS
        if data.get("salesorder_items") is not None and isinstance(
                data.get("salesorder_items"), list):
            await insert_saleorders_items(data=data.get("salesorder_items"),
                                          tenant_id=tenant_id,
                                          salesorder_id=data.get("id"),
                                          salesorder_discount_percent=data.get(
                                              "salesorder_discount_percent",
                                              0),
                                          salesorder_discount_amount=data.get(
                                              "salesorder_discount_amount", 0))
        new_sale_order_log = SalesorderLog()
        new_sale_order_log.salesorder_id = data.get("id")
        new_sale_order_log.sostatus = data.get('sostatus', 'wait_confirm')
        new_sale_order_log.status = "done"
        new_sale_order_log.tenant_id = tenant_id
        db.session.add(new_sale_order_log)
        db.session.commit()
        # result = db.session.query(Salesorder).filter(Salesorder.id == data.get('id')).first()
        # result = to_dict(result)

        return json(data)