Esempio n. 1
0
 def test_set_order_product_unavailable(self):
     gen_id = f'{__name__}-{int(datetime.now().timestamp())}'
     op_id = datetime.now().microsecond
     order = Order(id=gen_id, user=self.user)
     self.try_add_entities([
         Product(id='0000', name='Test product', price=10, weight=10),
         Product(id='0001', name='Test product 1', price=10, weight=10)
     ])
     self.try_add_entities([
         order,
         Suborder(id=op_id, order=order),
         OrderProduct(id=op_id,
                      suborder_id=op_id,
                      product_id='0000',
                      price=10,
                      quantity=10),
         OrderProduct(id=op_id + 1,
                      suborder_id=op_id,
                      product_id='0001',
                      price=10,
                      quantity=1)
     ])
     self.try_admin_operation(lambda: self.client.post(
         f'/api/v1/admin/order/product/{op_id + 1}/status/unavailable'))
     order = Order.query.get(gen_id)
     self.assertEqual(order.subtotal_krw, 2600)
Esempio n. 2
0
 def test_finish_order_with_unfinished_products(self):
     gen_id = f'{__name__}-{int(datetime.now().timestamp())}'
     self.try_add_entities([
         Product(id='0001', name='Product 1', price=10, weight=10),
         Product(id='0002', name='Product 2', price=10, weight=10),
         Product(id='0003', name='Product 3', price=10, weight=10),
         Order(id=gen_id)
     ])
     self.try_add_entities([
         Suborder(id=gen_id, order_id=gen_id),
         OrderProduct(suborder_id=gen_id,
                      product_id='0001',
                      quantity=1,
                      status=OrderProductStatus.pending),
         OrderProduct(suborder_id=gen_id,
                      product_id='0002',
                      quantity=1,
                      status=OrderProductStatus.pending),
         OrderProduct(suborder_id=gen_id,
                      product_id='0003',
                      quantity=1,
                      status=OrderProductStatus.pending)
     ])
     res = self.try_admin_operation(lambda: self.client.post(
         f'/api/v1/admin/order/{gen_id}', json={'status': 'shipped'}))
     self.assertEqual(res.status_code, 409)
Esempio n. 3
0
    def setUp(self):
        super().setUp()
        db.create_all()

        admin_role = Role(name='admin')
        self.user = User(
            username='******',
            email='*****@*****.**',
            password_hash=
            'pbkdf2:sha256:150000$bwYY0rIO$320d11e791b3a0f1d0742038ceebf879b8182898cbefee7bf0e55b9c9e9e5576',
            enabled=True)
        self.admin = User(
            username='******',
            email='*****@*****.**',
            password_hash=
            'pbkdf2:sha256:150000$bwYY0rIO$320d11e791b3a0f1d0742038ceebf879b8182898cbefee7bf0e55b9c9e9e5576',
            enabled=True,
            roles=[admin_role])
        self.try_add_entities([
            self.user, self.admin, admin_role,
            Currency(code='USD', rate=0.5),
            Currency(code='RUR', rate=0.5),
            Country(id='c1', name='country1'),
            Product(id='0000', name='Test product', price=10, weight=10)
        ])
Esempio n. 4
0
 def test_search_product(self):
     self.try_add_entities([
         Product(id='0001',
                 name='Korean name 1',
                 name_english='English name',
                 name_russian='Russian name',
                 price=1,
                 available=True)
     ])
     res = self.try_user_operation(
         lambda: self.client.get('/api/v1/product/search/0001'))
     self.assertEqual(res.json, [{
         'id': '0001',
         'name': 'Korean name 1',
         'name_english': 'English name',
         'name_russian': 'Russian name',
         'points': 0,
         'price': 1,
         'weight': 0,
         'separate_shipping': False,
         'available': True,
         'synchronize': True,
         'purchase': True,
         'color': None
     }])
Esempio n. 5
0
 def test_handle_wrong_subcustomer_data(self):
     self.try_add_entities(
         [Product(id='0001', name='Product 1', price=10, weight=10)])
     res = self.try_user_operation(lambda: self.client.post(
         '/api/v1/order',
         json={
             "customer_name":
             "User1",
             "address":
             "Address1",
             "country":
             "c1",
             'zip':
             '0000',
             "shipping":
             "1",
             "phone":
             "1",
             "comment":
             "",
             "suborders": [{
                 "subcustomer":
                 "A000, Subcustomer1, " + "P@ssw0rd" * 5,
                 "items": [{
                     "item_code": "0000",
                     "quantity": "1"
                 }, {
                     "item_code": "1",
                     "quantity": "1"
                 }]
             }]
         }))
     self.assertEqual(res.status_code, 400)
Esempio n. 6
0
def seed_products():
    products_count = db.session.query(func.count(Product.id)).all()[0][0]
    products_to_seed = 13
    sys.stdout.write('[+] Seeding %d products\n' % products_to_seed)
    quality = ['origine', 'adaptable']
    # tag_ids = [tag[0] for tag in db.session.query(Tag.id).all()]
    # category_ids = [categories[0] for categories in db.session.query(Category.id).all()]
    for i in range(products_count, products_to_seed):
        product = Product(name=fake.sentence(),
                          slug=fake.slug(),
                          description=fake.text(max_nb_chars=200),
                          availability=True,
                          quality=random.choice(quality),
                          price=fake.random_int(min=50, max=2500),
                          stock=fake.random_int(min=5, max=500),
                          rating=fake.random_int(min=0, max=5),
                          seller_id=random.choice(sellers_id),
                          manufacturer=fake.sentence(),
                          publish_on=random_date)
        categories_for_product = []
        category_to_add = random.choice(categories)
        if category_to_add.id not in categories_for_product:
            product.categories.append(category_to_add)
            categories_for_product.append(category_to_add.id)
        for i in range(0, random.randint(1, 2)):
            product_image = generate_image(ProductImage)
            product.images.append(product_image)
        db.session.add(product)
        db.session.commit()
Esempio n. 7
0
 def test_postpone_order_product(self):
     op_id = datetime.now().microsecond
     self.try_add_entities([
         Product(id='0000', name='Test product', price=10, weight=10),
         Product(id='0001', name='Test product 1', price=10, weight=10),
         Country(id='c1', name='country1'),
         Shipping(id=1, name='Shipping1'),
         PostponeShipping(),
         ShippingRate(shipping_method_id=1,
                      destination='c1',
                      weight=1000,
                      rate=100),
         ShippingRate(shipping_method_id=1,
                      destination='c1',
                      weight=10000,
                      rate=200),
     ])
     order1 = Order(user=self.user, shipping_method_id=1, country_id='c1')
     self.try_add_entity(order1)
     order2 = Order(user=self.user, shipping_method_id=1, country_id='c1')
     self.try_add_entity(order2)
     suborder = Suborder(order=order1, subcustomer=Subcustomer())
     suborder1 = Suborder(order=order2, subcustomer=Subcustomer())
     self.try_add_entities([
         OrderProduct(suborder=suborder, product_id='0000', quantity=1),
         OrderProduct(id=op_id,
                      suborder=suborder,
                      product_id='0001',
                      quantity=1),
         OrderProduct(id=op_id + 1,
                      suborder=suborder1,
                      product_id='0001',
                      quantity=1)
     ])
     res = self.try_user_operation(lambda: self.client.post(
         f'/api/v1/order/product/{op_id}/postpone'))
     self.assertEqual(res.status_code, 200)
     orders = Order.query.all()
     self.assertEqual(len(orders), 3)
     self.assertEqual(orders[0].total_krw, 2610)
     self.assertEqual(orders[2].total_krw, 2510)
     self.client.post(f'/api/v1/order/product/{op_id + 1}/postpone')
     orders = Order.query.all()
     self.assertEqual(len(orders), 3)
     self.assertEqual(orders[0].total_krw, 2610)
     self.assertEqual(orders[2].total_krw, 5020)
Esempio n. 8
0
def product(app):
    with app.app_context():
        product = Product(name="fake-product",
                          price=1,
                          description="this",
                          refundable=True)
        db.session.add(product)
        db.session.commit()
        return product
Esempio n. 9
0
 def test_finish_order_with_unavailable_products(self):
     gen_id = f'{__name__}-{int(datetime.now().timestamp())}'
     self.try_add_entities([
         Product(id='0001',
                 name='Product 1',
                 price=10,
                 weight=10,
                 points=10),
         Product(id='0002',
                 name='Product 2',
                 price=10,
                 weight=10,
                 points=10),
         Product(id='0003',
                 name='Product 3',
                 price=10,
                 weight=10,
                 points=10),
         Order(id=gen_id,
               country_id='c1',
               shipping_method_id=1,
               user=self.user)
     ])
     self.try_add_entities([
         Suborder(id=gen_id, order_id=gen_id),
         OrderProduct(suborder_id=gen_id,
                      product_id='0001',
                      quantity=1,
                      status=OrderProductStatus.purchased),
         OrderProduct(suborder_id=gen_id,
                      product_id='0002',
                      quantity=1,
                      status=OrderProductStatus.purchased),
         OrderProduct(suborder_id=gen_id,
                      product_id='0003',
                      quantity=1,
                      status=OrderProductStatus.unavailable)
     ])
     res = self.try_admin_operation(lambda: self.client.post(
         f'/api/v1/admin/order/{gen_id}', json={'status': 'shipped'}))
     self.assertEqual(res.status_code, 200)
     order = Order.query.get(gen_id)
     self.assertEqual(order.total_krw, 2620)
     self.assertEqual(order.get_total_points(), 20)
Esempio n. 10
0
 def test_get_invoice_excel(self):
     gen_id = f'{__name__}-{int(datetime.now().timestamp())}'
     self.try_add_entities([
         Product(id=gen_id, weight=1),
         Invoice(id=gen_id, country_id='c1'),
         Order(id=gen_id, invoice_id=gen_id, country_id='c1'),
         InvoiceItem(invoice_id=gen_id, product_id=gen_id, price=1, quantity=1)
     ])
     self.try_admin_operation(
         lambda: self.client.get(f'/api/v1/admin/invoice/{gen_id}/excel'))
Esempio n. 11
0
 def test_get_invoice_cumulative_excel(self):
     gen_id = f'{__name__}-{int(datetime.now().timestamp())}'
     self.try_add_entities([
         Product(id=gen_id, weight=1),
         Invoice(id=gen_id, country_id='c1'),
         Order(id=gen_id, invoice_id=gen_id, country_id='c1'),
         InvoiceItem(invoice_id=gen_id, product_id=gen_id, price=1, quantity=1)
     ])
     res = self.try_admin_operation(
         lambda: self.client.get(f'/api/v1/admin/invoice/excel?invoices={gen_id}&invoices={gen_id}'))
     self.assertTrue(res.status_code, 200)
Esempio n. 12
0
 def test_delete_product(self):
     gen_id = f'{__name__}-{int(datetime.now().timestamp())}'
     self.try_add_entities([
         Product(id=gen_id,
                 name='Korean name 1',
                 name_english='English name',
                 name_russian='Russian name',
                 price=1,
                 available=True)
     ])
     res = self.try_admin_operation(
         lambda: self.client.delete(f'/api/v1/admin/product/{gen_id}'))
Esempio n. 13
0
def product(app):
    with app.app_context():
        product = Product(name="fake-product",
                          image="url",
                          price=1,
                          weight=5.5,
                          description="holiiii",
                          refundable=True,
                          category_id=1)
        db.session.add(product)
        db.session.commit()
        return product
Esempio n. 14
0
def save_product(product_id):
    '''Saves updates in product or creates new product'''
    payload = request.get_json()
    if product_id is None:
        if not payload.get('id'):
            abort(Response('No product ID is provided', status=400))
        else:
            product_id = payload['id']

    product = Product.query.get(product_id)
    if not product:
        product = Product()
        product.id = product_id
        db.session.add(product)
    if 'shipping' in payload.keys():
        product.available_shipping = []
        if len(payload['shipping']) < Shipping.query.count():
            product.available_shipping = \
                Shipping.query.filter(Shipping.id.in_(payload['shipping']))
    editable_attributes = [
        'name', 'name_english', 'name_russian', 'price', 'points', 'weight',
        'available', 'separate_shipping', 'synchronize', 'purchase', 'color'
    ]
    modify_object(product, payload, editable_attributes)

    db.session.commit()

    return jsonify(product.to_dict(details=True))
Esempio n. 15
0
 def test_cancel_order_product(self):
     self.try_add_entities([
         Product(id='0000', name='Test product', price=10, weight=10),
         Product(id='0001', name='Test product 1', price=10, weight=10),
         Country(id='c1', name='country1'),
         Shipping(id=1, name='Shipping1'),
         PostponeShipping(),
         ShippingRate(shipping_method_id=1,
                      destination='c1',
                      weight=1000,
                      rate=100),
         ShippingRate(shipping_method_id=1,
                      destination='c1',
                      weight=10000,
                      rate=200),
     ])
     op_id = datetime.now().microsecond
     order = Order(user=self.user, shipping_method_id=1, country_id='c1')
     suborder = Suborder(order=order)
     op1 = OrderProduct(suborder=suborder,
                        product_id='0000',
                        quantity=75,
                        price=10,
                        status=OrderProductStatus.pending)
     op2 = OrderProduct(id=op_id,
                        suborder=suborder,
                        product_id='0001',
                        quantity=10,
                        price=10,
                        status=OrderProductStatus.pending)
     self.try_add_entities(
         [Product(id='0001', name='Test product 1', price=10, weight=100)])
     self.try_add_entities([order, suborder, op1, op2])
     res = self.try_user_operation(
         lambda: self.client.delete(f'/api/v1/order/product/{op_id}'))
     self.assertEqual(res.status_code, 200)
     op = OrderProduct.query.get(op_id)
     self.assertEqual(op, None)
Esempio n. 16
0
 def test_set_order_product_status(self):
     gen_id = f'{__name__}-{int(datetime.now().timestamp())}'
     op_id = datetime.now().microsecond
     order = Order(id=gen_id, user=self.user)
     self.try_add_entities(
         [Product(id='0000', name='Test product', price=10, weight=10)])
     self.try_add_entities([
         order,
         Suborder(id=op_id, order=order),
         OrderProduct(id=op_id,
                      suborder_id=op_id,
                      product_id='0000',
                      price=10,
                      quantity=10)
     ])
     self.try_user_operation(lambda: self.client.post(
         f'/api/v1/admin/order/product/{op_id}/status/pending'))
Esempio n. 17
0
 def test_create_invoice_item(self):
     gen_id = f'{__name__}-{int(datetime.now().timestamp())}'
     order = Order(id=gen_id)
     self.try_add_entities([
         Product(id=gen_id, name='Product 1')
     ])
     self.try_add_entities([
         order,
         Suborder(id=gen_id, order=order),
         OrderProduct(suborder_id=gen_id, product_id=gen_id, price=10, quantity=10),
         Invoice(id=gen_id, order_id=gen_id)
     ])
     self.try_admin_operation(
         lambda: self.client.post(f'/api/v1/admin/invoice/{gen_id}/item/new')
     )
     res = self.client.post(f'/api/v1/admin/invoice/{gen_id}/item/new',
         json={'invoice_id': gen_id, 'product_id': gen_id, 'price': 10, 'quantity': 10})
     self.assertTrue(res.status_code, 200)
Esempio n. 18
0
 def setUp(self):
     super().setUp()
     db.create_all()
     
     admin_role = Role(id=10, name='admin')
     self.try_add_entities([
         User(username='******', email='*****@*****.**',
             password_hash='pbkdf2:sha256:150000$bwYY0rIO$320d11e791b3a0f1d0742038ceebf879b8182898cbefee7bf0e55b9c9e9e5576',
             enabled=True, roles=[admin_role]),
         User(id=10, username='******', email='*****@*****.**',
             password_hash='pbkdf2:sha256:150000$bwYY0rIO$320d11e791b3a0f1d0742038ceebf879b8182898cbefee7bf0e55b9c9e9e5576', 
             enabled=True),
         admin_role,
         Country(id='c1', name='country1'),
         Currency(code='USD', rate=0.5),
         Product(id='SHIPPING', name='Shipping', weight=0, available=False,
             synchronize=False, separate_shipping=False, purchase=False)
     ])
Esempio n. 19
0
 def test_get_old_invoice(self):
     gen_id = f'{__name__}-{int(datetime.now().timestamp())}'
     self.try_add_entities([
         Product(id=gen_id, name='Product 1', weight=10),
         Invoice(id=gen_id,
                 country_id='c1',
                 when_created=datetime(2020, 1, 1, 1, 0, 0),
                 when_changed=datetime(2020, 1, 1, 1, 0, 0)),
         Order(id=gen_id, invoice_id=gen_id, country_id='c1')
     ])
     suborder = Suborder(order_id=gen_id)
     self.try_add_entities([
         suborder,
         OrderProduct(suborder=suborder, product_id=gen_id, price=10, quantity=1)
     ])
     res = self.try_admin_operation(
         lambda: self.client.get(f'/api/v1/admin/invoice/{gen_id}'))
     self.assertEqual(res.status_code, 200)
     self.assertEqual(len(res.json), 1)
     self.assertEqual(res.json[0], {
         'address': None,
         'country': 'country1',
         'customer': None,
         'payee': None,
         'id': gen_id,
         'invoice_items': [{
             'id': 1,
             'invoice_id': gen_id,
             'product_id': gen_id,
             'product': 'Product 1',
             'price': 5.0,
             'weight': 10,
             'quantity': 1,
             'subtotal': 5.0,
             'when_created': None,
             'when_changed': None
         }],
         'orders': [gen_id],
         'phone': None,
         'total': 5.0,
         'weight': 10,
         'when_changed': '2020-01-01 01:00:00',
         'when_created': '2020-01-01 01:00:00'
     })
Esempio n. 20
0
File: api.py Progetto: ralfeus/order
def add_order_product(suborder, item, errors):
    # with db.session.no_autoflush:
    try:
        product = Product.get_product_by_id(item['item_code'])
        if product:
            order_product = OrderProduct(suborder=suborder,
                                         product=product,
                                         price=product.price,
                                         quantity=int(item['quantity']),
                                         status=OrderProductStatus.pending)
            # db.session.add(order_product)
            suborder.order_products.append(order_product)
            suborder.order.total_weight += product.weight * order_product.quantity
            suborder.order.subtotal_krw += product.price * order_product.quantity
            return order_product
        raise ProductNotFoundError(item['item_code'])
    except Exception as ex:
        errors.append(ex.args)
        raise ex
Esempio n. 21
0
    def test_delete_last_order_item_in_suborder(self):
        gen_id = f'{__name__}-{int(datetime.now().timestamp())}'
        self.try_add_entities([
            Product(id='0001',
                    name='Product 1',
                    price=10,
                    weight=10,
                    points=10),
            Order(id=gen_id,
                  country_id='c1',
                  shipping_method_id=1,
                  user=self.user)
        ])
        self.try_add_entities([
            Suborder(id=gen_id, order_id=gen_id),
            OrderProduct(suborder_id=gen_id,
                         product_id='0001',
                         quantity=1,
                         status=OrderProductStatus.pending),
            Suborder(id=gen_id + "2", order_id=gen_id),
            OrderProduct(suborder_id=gen_id + "2",
                         product_id='0001',
                         quantity=1,
                         status=OrderProductStatus.pending)
        ])

        res = self.try_admin_operation(
            admin_only=True,
            operation=lambda: self.client.post(
                f'/api/v1/order/{gen_id}',
                json={
                    "suborders": [{
                        'subcustomer':
                        'A001, Subcustomer1, P@ssw0rd',
                        "items": [{
                            'item_code': '0001',
                            'quantity': 1
                        }]
                    }]
                }))
        self.assertEqual(res.status_code, 200)
        order = Order.query.get(gen_id)
        self.assertEqual(order.suborders.count(), 1)
Esempio n. 22
0
 def test_edit_product(self):
     gen_id = f'{__name__}-{int(datetime.now().timestamp())}'
     self.try_add_entities([
         Product(id='0001',
                 name='Korean name 1',
                 name_english='English name',
                 name_russian='Russian name',
                 price=1,
                 available=True)
     ])
     res = self.try_admin_operation(
         lambda: self.client.post(f'/api/v1/admin/product/{gen_id}',
                                  json={
                                      'id': gen_id,
                                      'name': 'Test product'
                                  }))
     self.assertEqual(res.status_code, 200)
     product = Product.query.get(gen_id)
     self.assertIsNotNone(product)
     self.assertEqual(product.name, 'Test product')
Esempio n. 23
0
 def test_delete_invoice_item(self):
     gen_id = f'{__name__}-{int(datetime.now().timestamp())}'
     order = Order(id=gen_id)
     self.try_add_entities([
         Product(id=gen_id, name='Product 1')
     ])
     self.try_add_entities([
         order,
         Suborder(id=gen_id, order=order),
         OrderProduct(suborder_id=gen_id, product_id=gen_id, price=10, quantity=10),
         Invoice(id=gen_id, order_id=gen_id),
         InvoiceItem(id=10, invoice_id=gen_id, product_id=gen_id, price=10, 
             quantity=10)
     ])
     res = self.try_admin_operation(
         lambda: self.client.delete(f'/api/v1/admin/invoice/{gen_id}/item/10')
     )
     self.assertEqual(res.status_code, 200)
     invoice_item = InvoiceItem.query.get(10)
     self.assertEqual(invoice_item, None)
Esempio n. 24
0
 def test_get_invoices(self):
     self.try_add_entities([
         Product(id='0001', name='Product 1', name_english='P1', weight=10),
         Invoice(id='INV-2020-00-00',
                 country_id='c1',
                 customer='Customer 1',
                 when_created=datetime(2020, 1, 1, 1, 0, 0),
                 when_changed=datetime(2020, 1, 1, 1, 0, 0)),
         InvoiceItem(invoice_id='INV-2020-00-00', product_id='0001', price=10, quantity=1),
         Order(id=__name__ + '-1', invoice_id='INV-2020-00-00', country_id='c1',
               customer_name='Customer 1')
     ])
     self.try_admin_operation(
         lambda: self.client.get('/api/v1/admin/invoice'))
     res = self.client.get('/api/v1/admin/invoice/INV-2020-00-00')
     self.assertEqual(len(res.json), 1)
     self.assertEqual(res.json[0], {
         'address': None,
         'country': 'country1',
         'customer': 'Customer 1',
         'payee': None,
         'id': 'INV-2020-00-00',
         'invoice_items': [{
             'id': 1,
             'invoice_id': 'INV-2020-00-00',
             'product_id': '0001',
             'product': 'P1',
             'price': 10.0,
             'weight': 10,
             'quantity': 1,
             'subtotal': 10.0,
             'when_created': None,
             'when_changed': None
         }],
         'orders': [__name__ + '-1'],
         'phone': None,
         'total': 10.0,
         'weight': 10,
         'when_changed': '2020-01-01 01:00:00',
         'when_created': '2020-01-01 01:00:00'
     })
Esempio n. 25
0
 def test_create_invoice(self):
     gen_id = f'{__name__}-{int(datetime.now().timestamp())}'
     id_prefix = datetime.now().strftime('INV-%Y-%m-')
     self.try_add_entities([
         Product(id=gen_id, name='Product 1', price=1)
     ])
     order = Order(id=gen_id)
     suborder = Suborder(order=order)
     self.try_add_entities([
         order, suborder,
         OrderProduct(suborder=suborder, product_id=gen_id, quantity=1, price=1)
     ])
     res = self.try_admin_operation(
         lambda: self.client.post('/api/v1/admin/invoice/new/0.5',
         json={
             'order_ids': [gen_id]
         })
     )
     self.assertEqual(res.json['invoice_id'], f'{id_prefix}0001')
     invoice = Invoice.query.get(res.json['invoice_id'])
     self.assertEqual(len(invoice.orders), 1)
     self.assertEqual(invoice.invoice_items_count, 2)
Esempio n. 26
0
 def test_create_order(self):
     self.try_add_entities(
         [Product(id='0001', name='Product 1', price=10, weight=10)])
     res = self.try_user_operation(
         lambda: self.client.post('/api/v1/order',
                                  json={
                                      "customer_name":
                                      "User1",
                                      "address":
                                      "Address1",
                                      "country":
                                      "c1",
                                      'zip':
                                      '0000',
                                      "shipping":
                                      "1",
                                      "phone":
                                      "1",
                                      "comment":
                                      "",
                                      "suborders": [{
                                          "subcustomer":
                                          "A000, Subcustomer1, P@ssw0rd",
                                          "items": [{
                                              "item_code": "0000",
                                              "quantity": "1"
                                          }, {
                                              "item_code": "1",
                                              "quantity": "1"
                                          }]
                                      }]
                                  }))
     self.assertEqual(res.status_code, 200)
     created_order_id = res.json['order_id']
     order = Order.query.get(created_order_id)
     self.assertEqual(order.total_krw, 2620)
     self.assertEqual(order.shipping.name, 'Shipping1')
Esempio n. 27
0
 def test_get_order(self):
     gen_id = f'{__name__}-{int(datetime.now().timestamp())}'
     order = Order(id=gen_id, user=self.user)
     suborder = Suborder(order=order)
     self.try_add_entities([Product(id=gen_id, price=10, weight=10)])
     self.try_add_entities([
         order, suborder,
         OrderProduct(suborder=suborder,
                      product_id=gen_id,
                      price=10,
                      quantity=10),
         Order(id=gen_id + '1', user=self.user, status=OrderStatus.pending)
     ])
     res = self.try_user_operation(
         lambda: self.client.get(f'/api/v1/order/{gen_id}'))
     self.assertEqual(res.json['total'], 2600)
     self.assertEqual(res.json['total_rur'], 1300.0)
     self.assertEqual(res.json['total_usd'], 1300.0)
     self.assertEqual(res.json['user'], self.user.username)
     self.assertEqual(len(res.json['order_products']), 1)
     res = self.client.get('/api/v1/order')
     self.assertEqual(len(res.json), 2)
     res = self.client.get('/api/v1/order?status=pending')
     self.assertEqual(res.json[0]['status'], 'pending')
Esempio n. 28
0
 def test_create_order_over_10_products(self):
     self.try_add_entities([
         Product(id='0001', name='Product 1', price=10, weight=10),
         Product(id='0002', name='Product 2', price=10, weight=10),
         Product(id='0003', name='Product 3', price=10, weight=10),
         Product(id='0004', name='Product 4', price=10, weight=10),
         Product(id='0005', name='Product 5', price=10, weight=10),
         Product(id='0006', name='Product 6', price=10, weight=10),
         Product(id='0007', name='Product 7', price=10, weight=10),
         Product(id='0008', name='Product 8', price=10, weight=10),
         Product(id='0009', name='Product 9', price=10, weight=10),
         Product(id='0010', name='Product 10', price=10, weight=10),
         Product(id='0011', name='Product 11', price=10, weight=10),
         Product(id='0012', name='Product 12', price=10, weight=10),
         Product(id='0013', name='Product 13', price=10, weight=10),
         Product(id='0014', name='Product 14', price=10, weight=10),
         Product(id='0015', name='Product 15', price=10, weight=10),
         Product(id='0016', name='Product 16', price=10, weight=10),
         Product(id='0017', name='Product 17', price=10, weight=10),
         Product(id='0018', name='Product 18', price=10, weight=10),
         Product(id='0019', name='Product 19', price=10, weight=10),
         Product(id='0020', name='Product 20', price=10, weight=10)
     ])
     res = self.try_user_operation(
         lambda: self.client.post('/api/v1/order',
                                  json={
                                      "customer_name":
                                      "User1",
                                      "address":
                                      "Address1",
                                      "country":
                                      "c1",
                                      'zip':
                                      '0000',
                                      "shipping":
                                      "1",
                                      "phone":
                                      "1",
                                      "comment":
                                      "",
                                      "suborders": [{
                                          "subcustomer":
                                          "A000, Subcustomer1, P@ssw0rd",
                                          "items": [{
                                              "item_code": "0000",
                                              "quantity": "1"
                                          }, {
                                              "item_code": "1",
                                              "quantity": "1"
                                          }, {
                                              "item_code": "2",
                                              "quantity": "1"
                                          }, {
                                              "item_code": "3",
                                              "quantity": "1"
                                          }, {
                                              "item_code": "4",
                                              "quantity": "1"
                                          }, {
                                              "item_code": "5",
                                              "quantity": "1"
                                          }, {
                                              "item_code": "6",
                                              "quantity": "1"
                                          }, {
                                              "item_code": "7",
                                              "quantity": "1"
                                          }, {
                                              "item_code": "8",
                                              "quantity": "1"
                                          }, {
                                              "item_code": "9",
                                              "quantity": "1"
                                          }, {
                                              "item_code": "10",
                                              "quantity": "1"
                                          }, {
                                              "item_code": "11",
                                              "quantity": "1"
                                          }, {
                                              "item_code": "12",
                                              "quantity": "1"
                                          }, {
                                              "item_code": "13",
                                              "quantity": "1"
                                          }, {
                                              "item_code": "14",
                                              "quantity": "1"
                                          }, {
                                              "item_code": "15",
                                              "quantity": "1"
                                          }, {
                                              "item_code": "16",
                                              "quantity": "1"
                                          }, {
                                              "item_code": "17",
                                              "quantity": "1"
                                          }, {
                                              "item_code": "18",
                                              "quantity": "1"
                                          }, {
                                              "item_code": "19",
                                              "quantity": "1"
                                          }, {
                                              "item_code": "20",
                                              "quantity": "1"
                                          }]
                                      }]
                                  }))
     self.assertEqual(res.status_code, 200)
     created_order_id = res.json['order_id']
     order = Order.query.get(created_order_id)
     self.assertEqual(len(order.order_products), 21)
     self.assertEqual(order.suborders.count(), 3)
Esempio n. 29
0
def api():
    """
    Endpoint to converse with chatbot.
    Chat context is maintained by exchanging the payload between client and bot.

    sample input/output payload =>

    {
      "currentNode": "",
      "complete": false,
      "parameters": [],
      "extractedParameters": {},
      "missingParameters": [],
      "intent": {
      },
      "context": {},
      "input": "hello",
      "speechResponse": [
      ]
    }

    :param json:
    :return json:
    """
    request_json = request.get_json(silent=True)
    result_json = request_json

    if request_json:

        context = {}
        context["context"] = request_json["context"]

        if app.config["DEFAULT_WELCOME_INTENT_NAME"] in request_json.get(
                "input"):
            intent = Intent.objects(
                intentId=app.config["DEFAULT_WELCOME_INTENT_NAME"]).first()
            result_json["complete"] = True
            result_json["intent"]["intentId"] = intent.intentId
            result_json["intent"]["id"] = str(intent.id)
            result_json["input"] = request_json.get("input")
            template = Template(intent.speechResponse,
                                undefined=SilentUndefined)
            result_json["speechResponse"] = split_sentence(
                template.render(**context))

            logger.info(request_json.get("input"), extra=result_json)
            return build_response.build_json(result_json)

        intent_id, confidence, suggetions = predict(request_json.get("input"))
        app.logger.info("Suggetions => %s" % suggetions)
        intent = Intent.objects.get(id=ObjectId(intent_id))

        if intent.parameters:
            parameters = intent.parameters
        else:
            parameters = []

        if ((request_json.get("complete") is None)
                or (request_json.get("complete") is True)):
            result_json["intent"] = {
                "name": intent.name,
                "confidence": confidence,
                "id": str(intent.id)
            }

            if parameters:
                # Extract NER entities
                extracted_parameters = entity_extraction.predict(
                    intent_id, request_json.get("input"))

                missing_parameters = []
                result_json["missingParameters"] = []
                result_json["extractedParameters"] = {}
                result_json["parameters"] = []
                for parameter in parameters:
                    result_json["parameters"].append({
                        "name":
                        parameter.name,
                        "type":
                        parameter.type,
                        "required":
                        parameter.required
                    })

                    if parameter.required:
                        if parameter.name not in extracted_parameters.keys():
                            result_json["missingParameters"].append(
                                parameter.name)
                            missing_parameters.append(parameter)

                result_json["extractedParameters"] = extracted_parameters

                if missing_parameters:
                    result_json["complete"] = False
                    current_node = missing_parameters[0]
                    result_json["currentNode"] = current_node["name"]
                    result_json["speechResponse"] = split_sentence(
                        current_node["prompt"])
                else:
                    result_json["complete"] = True
                    context["parameters"] = extracted_parameters
            else:
                result_json["complete"] = True

        elif request_json.get("complete") is False:
            if "cancel" not in intent.name:
                intent_id = request_json["intent"]["id"]
                intent = Intent.objects.get(id=ObjectId(intent_id))

                extracted_parameter = entity_extraction.replace_synonyms({
                    request_json.get("currentNode"):
                    request_json.get("input")
                })

                # replace synonyms for entity values
                result_json["extractedParameters"].update(extracted_parameter)

                result_json["missingParameters"].remove(
                    request_json.get("currentNode"))

                if len(result_json["missingParameters"]) == 0:
                    result_json["complete"] = True
                    context = {}
                    context["parameters"] = result_json["extractedParameters"]
                    context["context"] = request_json["context"]
                else:
                    missing_parameter = result_json["missingParameters"][0]
                    result_json["complete"] = False
                    current_node = [
                        node for node in intent.parameters
                        if missing_parameter in node.name
                    ][0]
                    result_json["currentNode"] = current_node.name
                    result_json["speechResponse"] = split_sentence(
                        current_node.prompt)
            else:
                result_json["currentNode"] = None
                result_json["missingParameters"] = []
                result_json["parameters"] = {}
                result_json["intent"] = {}
                result_json["complete"] = True

        if result_json["complete"]:
            if intent.apiTrigger:
                isJson = False
                parameters = result_json["extractedParameters"]
                headers = intent.apiDetails.get_headers()
                app.logger.info("headers %s" % headers)
                url_template = Template(intent.apiDetails.url,
                                        undefined=SilentUndefined)
                rendered_url = url_template.render(**context)
                if intent.apiDetails.isJson:
                    isJson = True
                    request_template = Template(intent.apiDetails.jsonData,
                                                undefined=SilentUndefined)
                    parameters = json.loads(request_template.render(**context))

                try:
                    result = call_api(rendered_url,
                                      intent.apiDetails.requestType, headers,
                                      parameters, isJson)
                except Exception as e:
                    app.logger.warn("API call failed", e)
                    result_json["speechResponse"] = [
                        "Service is not available. Please try again later."
                    ]
                else:
                    context["result"] = result
                    template = Template(intent.speechResponse,
                                        undefined=SilentUndefined)
                    result_json["speechResponse"] = split_sentence(
                        template.render(**context))
            else:
                context["result"] = {}
                template = Template(intent.speechResponse,
                                    undefined=SilentUndefined)
                result_json["speechResponse"] = split_sentence(
                    template.render(**context))
        logger.info(request_json.get("input"), extra=result_json)
        index = 0
        for response in result_json["speechResponse"]:
            index += 1
            token = "on sale"
            if token in response:
                products = Product.objects(onSale=True).limit(5)
                if (products != None):
                    for item in products:
                        app.logger.info("item %s" % item)
                        result_json["speechResponse"].insert(
                            index, item['product'])

        return build_response.build_json(result_json)
    else:
        return abort(400)
Esempio n. 30
0
def import_products():
    from app.import_products import get_atomy_products
    from app.products.models import Product
    
    logger = get_task_logger('import_products')
    logger.info("Starting products import")
    products = Product.query.all()
    same = new = modified = ignored = 0
    vendor_products = get_atomy_products()
    logger.info("Got %d products", len(vendor_products))
    if len(vendor_products) == 0: # Something went wrong
        logger.warning("Something went wrong. Didn't get any products from vendor. Exiting...")
        return
    for atomy_product in vendor_products:
        try:
            product = next(p for p in products
                           if p.id.lstrip('0') == atomy_product['id'].lstrip('0'))
            if product.synchronize:
                logger.debug('Synchronizing product %s', atomy_product['id'])
                is_dirty = False
                if product.name != atomy_product['name']:
                    logger.debug('\tname(%s): vendor(%s) != local(%s)', 
                        atomy_product['id'], atomy_product['name'], product.name)
                    product.name = atomy_product['name']
                    is_dirty = True
                if product.price != int(atomy_product['price']):
                    logger.debug('\tprice(%s): vendor(%s) != local(%s)', 
                        atomy_product['id'], atomy_product['price'], product.price)
                    product.price = int(atomy_product['price'])
                    is_dirty = True
                if product.points != int(atomy_product['points']):
                    logger.debug('\tpoints(%s): vendor(%s) != local(%s)', 
                        atomy_product['id'], atomy_product['points'], product.points)
                    product.points = int(atomy_product['points'])
                    is_dirty = True
                if product.available != atomy_product['available']:
                    logger.debug('\tavailable(%s): vendor(%s) != local(%s)', 
                        atomy_product['id'], atomy_product['available'], product.available)
                    product.available = atomy_product['available']
                    is_dirty = True
                if is_dirty:
                    logger.debug('\t%s: MODIFIED', atomy_product['id'])
                    product.when_changed = datetime.now()
                    modified += 1
                else:
                    logger.debug('\t%s: SAME', atomy_product['id'])
                    same += 1
            else:
                logger.debug('\t%s: IGNORED', product.id)
                ignored += 1

            products.remove(product)
        except StopIteration:
            logger.debug('%s: No local product found. ADDING', atomy_product['id'])
            product = Product(
                id=atomy_product['id'],
                name=atomy_product['name'],
                price=atomy_product['price'],
                points=atomy_product['points'],
                weight=0,
                available=atomy_product['available'],
                when_created=datetime.now()
            )
            new += 1
            db.session.add(product)
    logger.debug('%d local products left without matching vendor\'s ones. Will be disabled',
        len(products))
    for product in products:
        if product.synchronize:
            logger.debug("%s: should be synchronized. DISABLED", product.id)
            product.available = False
            modified += 1
        else:
            logger.debug("%s: should NOT be synchronized. IGNORED", product.id)
            ignored += 1
    logger.info(
        "Product synchronization result: same: %d, new: %d, modified: %d, ignored: %d",
        same, new, modified, ignored)
    db.session.commit()