Exemplo n.º 1
0
def add_products(request):
    
    data = request.json

    pro = Products.objects(name=data['name'])
    
    if len(pro) == 0:
        newProduct = Products(name= data['name'], description=data['description'], precio=data['precio'])
        newProduct.save()

    return response.json({
        "data": data
    })
Exemplo n.º 2
0
def update_products(request, id):
    data = request.json
    update = Products.objects(id=id)[0]
    update.name = data['name']
    update.description = data['description']
    # update.precio = data['precio']
    update.save()

    return response.json(update.to_json())
Exemplo n.º 3
0
    def _set_tabs(self):
        """
        Метод заполнения полей таблицы Тест
        """
        category_1 = Category(name='Полуфабрикаты', is_active=True)
        category_2 = Category(name='Бакалея', is_active=True)
        category_3 = Category(name='Мороженое', is_active=True)

        product_1 = Products(name='Вареники(Фирменные)', title='ТМ Геркулес 400 гр',
                             price=542.01, quantity=12, is_active=True, category=category_1)
        product_2 = Products(name='Пельмени(Домашние)', title='ТМ Вкуснотеево 450 гр',
                             price=322.5, quantity=23, is_active=True, category=category_1)
        product_3 = Products(name='Колбаса(Докторская)', title='ТМ Доброе 500 гр',
                             price=420, quantity=15, is_active=True, category=category_2)
        product_4 = Products(name='Сосиски(Молочные)', title='ТМ Веселые 700 гр',
                             price=312.56, quantity=36, is_active=True, category=category_2)
        product_5 = Products(name='Пьяная вишня', title='ТМ Молочный берег 50 гр',
                             price=75, quantity=102, is_active=True, category=category_3)
        product_6 = Products(name='Пломбир класический', title='ТМ Молочный берег 100 гр',
                             price=80, quantity=12, is_active=True, category=category_3)
        session = self.__session()
        session.add_all([category_1, category_2, category_3])
        session.add_all(
            [product_1, product_2, product_3, product_4, product_5, product_6])

        session.commit()
        session.close()
Exemplo n.º 4
0
def init_products():
    # 判斷資料庫是否存在
    result = init_db()
    if result:
        init_data = [Products(name='芒果炒雞柳',
                              product_image_url='https://i.imgur.com/SBDmHrJ.jpg',
                              price=300,
                              description='炒雞柳好吃!'),
                     Products(name='東坡肉',
                              product_image_url='https://i.imgur.com/JCBXVEq.jpg',
                              price=310,
                              description='東坡肉好吃!'),
                     Products(name='嫩煎牛排',
                              product_image_url='https://i.imgur.com/gGhxvM6.jpg',
                              price=320,
                              description='牛排好吃!'),
                     Products(name='蒜泥白玉蒸蝦',
                              product_image_url='https://i.imgur.com/MhAb8nA.jpg',
                              price=330,
                              description='蝦子好吃!'),
                     Products(name='橙汁魚排',
                              product_image_url='https://i.imgur.com/t1svMMN.png',
                              price=290,
                              description='魚排好吃!'),
                     Products(name='蒜苗炒松阪牛',
                              product_image_url='https://i.imgur.com/JZssJkM.jpg',
                              price=340,
                              description='松阪牛好吃!')
                     ]
        db_session.bulk_save_objects(init_data)
        db_session.commit()
Exemplo n.º 5
0
def init_products():
    # init db
    result = init_db()
    if result:
        init_data = [
            Products(name='Coffee',
                     product_image_url='https://i.imgur.com/DKzbk3l.jpg',
                     price=150,
                     description=
                     'nascetur ridiculus mus. Donec quam felis, ultricies'),
            Products(
                name='Tea',
                product_image_url='https://i.imgur.com/PRTxyhq.jpg',
                price=120,
                description='adipiscing elit. Aenean commodo ligula eget dolor'
            ),
            Products(name='Cake',
                     price=180,
                     product_image_url='https://i.imgur.com/PRm22i8.jpg',
                     description='Aenean massa. Cum sociis natoque penatibus')
        ]
        db_session.bulk_save_objects(init_data)
        db_session.commit()
Exemplo n.º 6
0
def handle_image_message(event):
    print(event)
    # 從event裡面取得用戶id
    user_id = event.source.user_id
    # 想辦法抓出圖片網址裡的action
    message_json = json.loads(str(event.message))
    message_url = str(message_json['contentProvider']['originalContentUrl'])
    message_url_args = message_url.split('?')[1].split('&')
    args_dic = {}
    for x in message_url_args:
        args_dic[x.split("=")[0]] = x.split("=")[1]
    # 從event裡面取得reply_token
    reply_token = event.reply_token
    # 從資料庫取得送出postback的用戶資料
    query = User.query.filter_by(id=user_id).first()
    args_dic['name'] = query.user_name_custom
    args_dic['phone_number'] = query.phone_number
    args_dic['userid'] = user_id
    if args_dic['action'] == 'booking':
        # 老師說的對,先不要用UUID先用日期檔老師一下
        # 等之後再修回來
        # # 用uuid創一個訂單編號
        # booking_id = uuid.uuid4().hex
        booking_id = str(datetime.today().strftime('%Y%m%d%H%M%S'))

        # 存入字典
        args_dic['id'] = booking_id
        date_string = args_dic['date'] + " " + args_dic['time'] + ":01"
        date_time = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
        booking = Booking(id=booking_id,
                          book_time=date_time,
                          is_confirm=0,
                          user_id=user_id,
                          people_num=args_dic['number'])
        db_session.add(booking)
        db_session.commit()
        line_bot_api_server.push_message('U47eb075cc6756bf9075f79c91a9925a0',
                                         AllMessage.confirmMessage(args_dic))
        line_bot_api_server.push_message('Uf172bde17bf332ad7060a417db99f1c2',
                                         AllMessage.confirmMessage(args_dic)),
        line_bot_api_server.push_message('U3f7562b0d0e0ffc22f3b82fa90af5a27',
                                         AllMessage.confirmMessage(args_dic))
        print(args_dic)
        return

    if args_dic['action'] == 'order':
        line_bot_api.reply_message(reply_token, TextSendMessage(text="好的," + args_dic["table"] + "是嗎?\n以下是我們的菜單!"))
        line_bot_api.push_message(user_id, Products.list_all())
Exemplo n.º 7
0
def get_products(request):
    results_redis = redis.get(list_products_redis)
    if not results_redis:
        data = []

        productos = Products.objects()

        if len(productos) > 0:
            for producto in productos:
                _id = producto.id

                data.append({"_id": str(_id), "name": producto.name, "description": producto.description})
                redis.setex(list_products_redis, 10 , str(data))
        
            return response.json({ "data": data})
    else:
        return response.json({ "data": json.loads(results_redis)})
Exemplo n.º 8
0
#!/usr/bin/python3
from models.category import Category
from models.tags import Tag
from models.user import User
from models.product import Products
CAT = Category()
CAT.label = "a8888"
TA = Tag()
TA.label = "azzzabi"
PRO = Products()
US = User()
US.email = "AZEAZEAZEAZEAZEAZE"
US.password = "******"
PRO.user_id = US.id
tag_id = TA.id
category_id = CAT.id
title = "zazazaz"
description = "hjdbfjfe"
CAT.save()
TA.save()
US.save()
PRO.save()

print(CAT.to_dict())
print(TA.to_dict())
print(US.to_dict())
print(PRO.to_dict())
Exemplo n.º 9
0
def handler_postback(event):
    # 把postback裡面的資料轉成字典
    data = dict(parse_qsl(event.postback.data))
    # 再取出action裡面的值
    action = data.get('action')
    # 從event裡面取得用戶id
    user_id = event.source.user_id
    # 從event裡面取得reply_token
    reply_token = event.reply_token
    # 建立一個購物車物件
    cart = Cart(user_id=user_id)
    # 從資料庫取得送出postback的用戶資料
    query = User.query.filter_by(id=user_id).first()
    print(event.postback.data)
    # 點擊加入會員
    if event.postback.data in ['join_us', '加入會員']:
        # 資料庫該使用者狀態改為註冊中
        # Updata data
        print('註冊中')
        query.is_signup = True
        db_session.commit()
        line_bot_api.link_rich_menu_to_user(user_id, richmenu_list.RichMenu_ID.richmenu_02)
        line_bot_api.push_message(user_id, AllMessage.sign_cellphone())
    # 點擊取消輸入之類的
    elif event.postback.data in ['exit']:
        query.is_signup = False
        query.edit_user_name = False
        query.edit_home_address = False
        query.edit_company_address = False
        db_session.commit()
        if not query.is_member:
            line_bot_api.link_rich_menu_to_user(user_id, richmenu_list.RichMenu_ID.richmenu_01)
        line_bot_api.push_message(user_id, TextSendMessage(text='好的,歡迎您再來找我聊聊天喔!'))
    # 點擊會員中心
    elif event.postback.data in ['會員中心']:
        line_bot_api.reply_message(reply_token, TextSendMessage(text='這是專屬於你的會員中心', sender=Sender(
            name='會員中心管理員結衣',
            icon_url='https://i.imgur.com/S7SHmup.png'
        )))
        line_bot_api.push_message(user_id, AllMessage.member_center(query))
    # 觸發點餐相關事件
    elif event.postback.data in ['當日外帶', 'add', '點餐']:
        # 先跳出選擇內用外帶
        line_bot_api.reply_message(reply_token, TemplateSendMessage(alt_text="請問您要內用還是外帶呢?",
                                                                    sender=Sender(
                                                                        name='服務員結衣',
                                                                        icon_url='https://i.imgur.com/S7SHmup.png'
                                                                    ),
                                                                    template=ConfirmTemplate(
                                                                        text="請問您要內用還是外帶呢?",
                                                                        actions=[
                                                                            PostbackAction(
                                                                                label="內用",
                                                                                text="內用",
                                                                                data="here"
                                                                            ),
                                                                            PostbackAction(
                                                                                label="外帶",
                                                                                text="外帶",
                                                                                data="out"
                                                                            )
                                                                        ]
                                                                    )))
    # 外帶事件
    elif event.postback.data in ['out']:
        line_bot_api.reply_message(reply_token, Products.list_all())
    # 內用事件
    elif event.postback.data in ['here']:
        line_bot_api.reply_message(reply_token, TemplateSendMessage(alt_text="請掃描桌上的QRCODE",
                                                                    sender=Sender(
                                                                        name='服務員結衣',
                                                                        icon_url='https://i.imgur.com/S7SHmup.png'
                                                                    ),
                                                                    template=ButtonsTemplate(
                                                                        text='請掃描桌上的QRCode點餐',
                                                                        actions=[
                                                                            URIAction(
                                                                                type='uri',
                                                                                label='點我掃描',
                                                                                uri="https://liff.line.me/1654280234-Wabazm3B"
                                                                            )
                                                                        ]
                                                                    )))
    # 觸發確認訂單事件
    elif event.postback.data in ['待補', '確認訂單']:
        if cart.bucket():
            line_bot_api.reply_message(reply_token, cart.display())
        else:
            line_bot_api.reply_message(reply_token, TextSendMessage(text='你的購物車目前沒東西喔'))
    # 觸發清空購物車事件
    elif event.postback.data in ['Empty Cart']:
        cart.reset()
        line_bot_api.reply_message(reply_token, TextSendMessage(text="你的購物車已經被清空了"))
    # 如果action為check則執行結帳動作
    elif action == 'checkout':
        if not cart.bucket():
            line_bot_api.reply_message(reply_token,
                                       TextSendMessage(text='你的購物車是空的'))
            return 'OK'

        # 透過uuid來建立訂單id,它可以幫我們建立一個獨一無二的值
        order_id = uuid.uuid4().hex
        # 訂單總金額
        total = 0
        # 訂單內容物的陣列
        items = []

        for product_name, num in cart.bucket().items():
            product = db_session.query(Products).filter(Products.name.ilike(product_name)).first()

            print(product.id)
            item = Items(product_id=product.id,
                         product_name=product.name,
                         product_price=product.price,
                         order_id=order_id,
                         quantity=num)

            items.append(item)

            total += product.price * int(num)

        cart.reset()

        line_pay = LinePay()
        # 傳送這些資訊過去他會回我們一個json
        # 自己試試看把info印出來或是用postman看看裡面的結構
        info = line_pay.pay(product_name='OrderBot 點吧',
                            amount=total,
                            order_id=order_id,
                            product_image_url=Config.STORE_IMAGE_URL)

        # 從info裡面擷取付款連結跟transactionid
        pay_web_url = info['paymentUrl']['web']
        transaction_id = info['transactionId']

        # 產生訂單
        order = Orders(id=order_id,
                       transaction_id=transaction_id,
                       is_pay=False,
                       amount=total,
                       user_id=user_id)

        db_session.add(order)

        for item in items:
            db_session.add(item)

        db_session.commit()

        message = TemplateSendMessage(
            alt_text='差一點點就完成訂購囉~',
            template=ButtonsTemplate(
                text='差一點點就完成訂購囉~',
                actions=[
                    URIAction(label='Pay NT${}'.format(order.amount),
                              uri='{liff_url}?redirect_url={url}'.format(
                                  liff_url=Config.LIFF_URL,
                                  url=pay_web_url))
                ]))
        line_bot_api.reply_message(reply_token, message)

    # 訂單管理
    elif event.postback.data in ['訂單管理']:
        line_bot_api.reply_message(reply_token, Booking.list_all_user(user_id))

    # 取消訂單
    elif '取消訂位' in event.postback.data:
        line_bot_api.reply_message(reply_token, TextSendMessage(text="您的訂單已取消",
                                                                sender=Sender(
                                                                    name='會員中心管理員結衣',
                                                                    icon_url='https://i.imgur.com/S7SHmup.png'
                                                                )))
        book_id = str(event.postback.data)[4:]
        db_session.query(Booking).filter_by(id=book_id).first().is_confirm = -2
        db_session.commit()

    return 'OK'
Exemplo n.º 10
0
def handle_message(event):

    get_or_create_user(event.source.user_id)

    message_text = str(event.message.text).lower()

    cart = Cart(user_id=event.source.user_id)

    message = None

    if message_text in ["what is your story?", "story"]:
        message = [
            ImageSendMessage(
                original_content_url='https://i.imgur.com/DKzbk3l.jpg',
                preview_image_url='https://i.imgur.com/DKzbk3l.jpg'),
            StickerSendMessage(package_id='11537', sticker_id='52002734')
        ]

    elif message_text in ['i am ready to order.', 'add']:
        message = Products.list_all()

    elif "i'd like to have" in message_text:

        product_name = message_text.split(',')[0]
        num_item = message_text.rsplit(':')[1]

        product = db_session.query(Products).filter(
            Products.name.ilike(product_name)).first()

        if product:

            cart.add(product=product_name, num=num_item)

            confirm_template = ConfirmTemplate(
                text='Sure, {} {}, anything else?'.format(
                    num_item, product_name),
                actions=[
                    MessageAction(label='Add', text='add'),
                    MessageAction(label="That's it", text="That's it")
                ])

            message = TemplateSendMessage(alt_text='anything else?',
                                          template=confirm_template)

        else:
            message = TextSendMessage(
                text="Sorry, We don't have {}.".format(product_name))

        print(cart.bucket())

    elif message_text in ['my cart', 'cart', "that's it"]:

        if cart.bucket():
            message = cart.display()
        else:
            message = TextSendMessage(text='Your cart is empty now.')

    elif message_text == 'empty cart':

        cart.reset()

        message = TextSendMessage(text='Your cart is empty now.')

    if message:
        line_bot_api.reply_message(event.reply_token, message)
Exemplo n.º 11
0
def remove_products(request, id):
    Products.objects(id=id).delete()
    return response.json({
    })