Beispiel #1
0
def user_create_order():
    '''
    Creates order.
    Accepts order details in payload
    Returns JSON
    '''
    with OrderValidator(request) as validator:
        if not validator.validate():
            return Response(f"Couldn't create an Order\n{validator.errors}",
                            status=409)

    payload = request.get_json()
    result = {}
    shipping = Shipping.query.get(payload['shipping'])
    country = Country.query.get(payload['country'])
    with db.session.no_autoflush:
        order = Order(user=current_user,
                      customer_name=payload['customer_name'],
                      address=payload['address'],
                      country_id=payload['country'],
                      country=country,
                      zip=payload['zip'],
                      shipping=shipping,
                      phone=payload['phone'],
                      comment=payload['comment'],
                      subtotal_krw=0,
                      status=OrderStatus.pending,
                      when_created=datetime.now())
        if 'draft' in payload.keys() and payload['draft']:
            order = _set_draft(order)

        order.attach_orders(payload.get('attached_orders'))
        db.session.add(order)
        # order_products = []
        errors = []
        # ordertotal_weight = 0
        add_suborders(order, payload['suborders'], errors)
        try:
            order.update_total()
        except NoShippingRateError:
            abort(Response("No shipping rate available", status=409))

    try:
        # db.session.commit()
        db.session.commit()
        result = {
            'status': 'warning' if len(errors) > 0 else 'success',
            'order_id': order.id,
            'message': errors
        }
    except DataError as ex:
        db.session.rollback()
        message = ex.orig.args[1]
        table = re.search('INSERT INTO (.+?) ', ex.statement).groups()[0]
        if table:
            if table == 'subcustomers':
                message = "Subcustomer error: " + message + " " + str(
                    ex.params[2:5])
        result = {
            'status':
            'error',
            'message':
            f"""Couldn't add order due to input error. Check your form and try again.
                           {message}"""
        }
    except (IntegrityError, OperationalError) as ex:
        db.session.rollback()
        result = {
            'status':
            'error',
            'message':
            f"""Couldn't add order due to input error. Check your form and try again.
                           {str(ex.args)}"""
        }
    return jsonify(result)
Beispiel #2
0
 def test_postponed_orders(self):
     postpone_shipping = PostponeShipping()
     postponed_order = Order(shipping=postpone_shipping,
                             user=self.user,
                             status=OrderStatus.pending)
     suborder = Suborder(order=postponed_order)
     self.try_add_entities([
         postpone_shipping, postponed_order, suborder,
         OrderProduct(suborder=suborder,
                      product_id='0000',
                      price=10,
                      quantity=10)
     ])
     postponed_order1 = Order(shipping=postpone_shipping,
                              user=self.user,
                              status=OrderStatus.pending)
     suborder1 = Suborder(order=postponed_order1)
     self.try_add_entities([
         postponed_order1, suborder1,
         OrderProduct(suborder=suborder1,
                      product_id='0000',
                      price=10,
                      quantity=10)
     ])
     postponed_order.update_total()
     postponed_order1.update_total()
     res = self.try_admin_operation(
         admin_only=True,
         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": "100"
                     }]
                 }],
                 "attached_orders": [postponed_order.id]
             }))
     self.assertEqual(res.status_code, 200)
     order = Order.query.get(res.json['order_id'])
     self.assertEqual(order.attached_orders.count(), 1)
     self.assertEqual(order.shipping_krw, 200)
     self.assertEqual(order.total_krw, 3700)
     res = self.client.post(f'/api/v1/order/{order.id}',
                            json={
                                'address':
                                'Address1',
                                'country':
                                'c1',
                                'customer_name':
                                "User1",
                                'phone':
                                '1',
                                'zip':
                                '0000',
                                'shipping':
                                '1',
                                "attached_orders":
                                [postponed_order.id, postponed_order1.id],
                                "suborders": [{
                                    "subcustomer":
                                    "A000, Subcustomer1, P@ssw0rd",
                                    "items": [{
                                        "item_code": "0000",
                                        "quantity": "100"
                                    }]
                                }]
                            })
     self.assertEqual(order.attached_orders.count(), 2)
     self.assertEqual(order.shipping_krw, 200)
     self.assertEqual(order.total_krw, 3700)