예제 #1
0
def create_order():
    user_id = int(request.get_json().get("user_id"))
    order = request.get_json().get("order")
    address_id = request.get_json().get("address_id")
    freight = order["freight"]
    cost = order["cost"]
    detail = order["detail"]
    address = Address.query.filter_by(id=address_id).first()
    order = Order(
        freight=freight,
        cost=cost,
        status=1,
        name=address.name,
        phone=address.phone,
        postcode=address.postcode,
        location=address.location,
        user_id=user_id,
        create_time=(datetime.utcnow() +
                     timedelta(hours=8)).strftime('%Y-%m-%d %H:%M:%S'))
    db.session.add(order)
    db.session.commit()
    order.number = (datetime.utcnow() +
                    timedelta(hours=8)).strftime('%Y%m%d%H%M%S') + str(
                        order.id)
    db.session.add(order)
    db.session.commit()
    for d in detail:
        _detail = Detail(count=d["count"],
                         cost=d["sumup"],
                         order_id=order.id,
                         book_id=d["book_id"])
        db.session.add(_detail)
        db.session.commit()
    return jsonify({"order_id": order.id})
    def test_customer_orders_relationship(self):
        cust = Customer(username="******",
                        email="*****@*****.**",
                        first_name="first_test",
                        last_name="last_test",
                        middle_name="middle_test",
                        phone_number="123456789",
                        gender="M",
                        marital_status="Married")
        cust.set_password('test_pass')

        order = Order()
        order2 = Order()
        order3 = Order()

        order_item = Order_Item(quantity=5)
        order_item2 = Order_Item(quantity=10)
        order_item3 = Order_Item(quantity=15)

        product = Product(name="Spatula")
        product2 = Product(name="Spoon")
        product3 = Product(name="Spork")

        cust.orders.append(order)
        order.order_items.append(order_item)
        product.order_items.append(order_item)

        db.session.add(cust)
        db.session.add(order)
        db.session.add(product)
        db.session.add(order_item)
        db.session.commit()
예제 #3
0
 def post(self):
     parsed_args = reqparse.parse_args()
     order = Order(customer=parsed_args['customer'])
     order.normalized = normalizer(order.customer)
     db.session.add(order)
     db.session.commit()
     return order, 201
예제 #4
0
 def test_find_by_customer_name(self):
     Order(0, "Tom", "200").save()
     Order(0, "Bob", "300").save()
     orders = Order.find_by_customer_name("Bob")
     self.assertNotEqual(len(orders), 0)
     self.assertEqual(orders[0].amount_paid, "300")
     self.assertEqual(orders[0].customer_name, "Bob")
예제 #5
0
def get_user_orders(id=None):
    page, per_page = get_page_from_args()
    sort_by = request.args.get('sort_by')
    is_desc = parse_int(request.args.get('is_desc'))
    user_id = parse_int(request.args.get('user_id'))
    # order_id = parse_int(request.args.get('order_id'))
    status_id = parse_int(request.args.get('status'))

    if user_id:
        items = Order.get_items(user_id=user_id,
                                status_id=status_id,
                                page=page,
                                per_page=per_page,
                                sort_by=sort_by,
                                is_desc=is_desc)
        return res([item.as_dict() for item in items])

    elif id:
        items = [Order.query.get(id)] if id else Order.get_items(
            user_id=user_id,
            status_id=status_id,
            page=page,
            per_page=per_page,
            sort_by=sort_by,
            is_desc=is_desc)
        return res([item.as_dict() for item in items][0])
    else:
        return Responses.OPERATION_FAILED()
예제 #6
0
def PlaceOrder(id):
	user = User.query.get_or_404(id)
	data = request.get_json() or {}
	order = Order()
	order.store_id = id
	for field in ['address', 'city', 'email', 'country', 'phone', 'comment', 'province', 'postal_code', 'name']:
		if not field in data:
			return BadRequest('Field {} is missing.'.format(field))
		else:
			setattr(order, field, data[field])
	if not 'products' in data:
		return BadRequest('Field products is missing.')
	products_sku = [x.strip() for x in data['products'].split(',') if x.strip() != '']
	products_sku = Counter(products_sku)
	orderProducts = list()
	for sku in products_sku:
		p = Product.query.filter(Product.sku == sku, Product.store_id == id).first()
		if p is None:
			return BadRequest('Wrong product sku {}.'.format(sku))
		op = OrderProducts (count=products_sku[sku], price=p.price, sku=sku, title=p.title, picture=p.picture, description=p.description)
		db.session.add(op)
		orderProducts.append(op)
	order.products = orderProducts
	db.session.add(order)
	db.session.commit()
	return jsonify(order.ToDict())
예제 #7
0
    def post(self, supply_id):
        r = request.json
        o = Order(**r)
        param = {}

        supply_id = r.get('supply_id', None)
        try:
            int(supply_id)
        except (ValueError, TypeError):
            return dict(), 400
        param['supply_id'] = supply_id

        order_id = r.get('order_id', None)
        if not order_id:
            return dict(), 400
        param['order_id'] = str(order_id)

        status = r.get('status', None)
        try:
            bool(status)
        except (ValueError, TypeError):
            return dict(), 400
        param['status'] = bool(status)

        timestamp = r.get('timestamp', None)
        if timestamp is not None:
            timestamp = datetime.utcfromtimestamp(timestamp)
            param['timestamp'] = timestamp

        o = Order(**param)
        db.session.add(o)
        db.session.commit()

        param['timestamp'] = param['timestamp'].ctime()
        return param, 201
예제 #8
0
def orderCreate():
    body = request.get_json()
    customer = Customer.objects().filter(id=body['customer']).first().to_json()
    customer = json.loads(customer)
    req = Notifications.SendUser(customer['notification'])
    items = Order(**body).save()
    return Response(items.to_json(), mimetype="application/json", status=200)
예제 #9
0
def new_customer_order(id):
    customer = Customer.query.get_or_404(id)
    order = Order(customer=customer)
    order.import_data(request.json)
    db.session.add(order)
    db.session.commit()
    return jsonify({}), 201, {'Location': order.get_url()}
예제 #10
0
    def test_non_dict_raises_error(self):
        """ Pass invalid data structure deserialize """
        data = [1,2,3]
        order = Order()

        with self.assertRaises(DataValidationError):
            order.deserialize(data)
예제 #11
0
 def test_find_by_availability(self):
     """ Find a Order by Availability """
     Order(0, "fido", "dog", False).save()
     Order(0, "kitty", "cat", True).save()
     orders = Order.find_by_availability(True)
     self.assertEqual(len(orders), 1)
     self.assertEqual(orders[0].name, "kitty")
예제 #12
0
 def test_find_order(self):
     Order(0, "Tom", '200').save()
     Order(0, "Bob", '300').save()
     order = Order.find(2)
     self.assertIsNot(order, None)
     self.assertEqual(order.id, 2)
     self.assertEqual(order.customer_name, "Bob")
예제 #13
0
def randomize_last_command_orders():
    ''' update order for each commands '''
    command = Command.last().empty_orders()
    employees = Employee.query.all()
    orders = []

    foods = command.shop.foods.filter_by(extra=False).all()
    foods_extra = command.shop.foods.filter_by(extra=True).all()
    extra_count = random.randint(
        0, (math.floor(Employee.query.count() * RATE_EXTRA_ORDER) + 1))

    for employee in employees:
        employee_count = random.randint(RATE_EMPLOYEE_COMMANDED_MIN,
                                        RATE_EMPLOYEE_COMMANDED_MAX)
        orders += [
            Order(food=random.choice(foods),
                  command=command,
                  employee=employee) for _ in range(employee_count)
        ]

    for food_extra in foods_extra:
        extra_count = random.randint(RATE_EXTRA_COMMANDED_MIN,
                                     RATE_EXTRA_COMMANDED_MAX)
        orders += [
            Order(food=food_extra, command=command) for _ in range(extra_count)
        ]

    db.session.add_all(orders)
    db.session.commit()
예제 #14
0
def cart():
    form = OrderForm()

    my_cart = session.get('cart', [])
    title = f"Блюд в корзине: {len(my_cart)}" if my_cart else "Ваша корзина пуста"
    products = [Meal.query.get(product_id) for product_id in my_cart]
    total_amount = sum(product.price for product in products)
    total_amount_msg = f"Всего товаров на {total_amount} рублей"
    if request.method == 'GET' and current_user.is_authenticated:
        form.username.data = current_user.username
        form.email.data = current_user.email
        if current_user.address:
            form.address.data = current_user.address

    if form.validate_on_submit():
        new_order = Order()
        new_order.amount = total_amount
        new_order.state = OrderState.query.filter(
            OrderState.title == 'новый').first()
        new_order.user = current_user
        db.session.add(new_order)
        for item in my_cart:
            meal = Meal.query.get(item)
            new_order.meals.append(meal)
        db.session.commit()
        session['cart'] = []
        return redirect('/ordered/')
    return render_template('cart.html',
                           form=form,
                           products=products,
                           title=title,
                           total_amount=total_amount_msg)
예제 #15
0
def processEdit(id, eventName, discountPercent, discountAmount, contact,
                rooms):
    """Save the form data into a booking"""
    b = Booking.select().where(Booking.id == id).get()
    food = {}
    for field in request.form:
        if field.startswith('dish_'):
            food[int(field.replace('dish_', ''))] = int(request.form[field])
    b.eventName = eventName
    b.discountPercent = discountPercent
    b.discountAmount = discountAmount
    b.contact_id = contact
    rooms = Room.select().where(Room.id << rooms).execute()
    if Room.areRoomsFree(rooms, b.startTime, b.endTime, id):
        BookingRoom.delete().where(BookingRoom.booking == b).execute()
        for room in rooms:
            br = BookingRoom(booking=b, room=room)
            br.save()
        Order.delete().where(Order.booking == b).execute()
        for f in food:
            if food[f] > 0:
                Order(dish=Dish.get(Dish.id == int(f)),
                      booking=b,
                      quantity=food[f]).save()
        b.calculateTotal()
        b.save()
    else:
        flash(
            'A room that you selected is no longer available.  Please select a new room.',
            'error')
        return redirect(request.referrer)
    flash('Booking Updated', 'success')
    return redirect(url_for('bookings.index'))
예제 #16
0
def buy():
    if current_user.is_anonymous:
        flash("Not Logged In")
        return redirect(url_for('index'))
    p = 0
    # a = Cart.query.filter_by(customer_id = current_user.id).all()
    o = Order(price=0, status="placed", cust_id=current_user.id)
    db.session.add(o)
    db.engine.execute("delete from cart where customer_id = " +
                      str(current_user.id))
    a = OrderList.query.filter_by(c_id=current_user.id).filter_by(
        used=False).all()
    if a is None:
        flash("Cart is empty")
        return redirect(url_for("index"))
    for i in a:
        print(i)
        i.order_id = o.id
        i.used = True
        print("I oid", i.order_id)
        price = Product.query.filter_by(id=i.p_id).first()
        p += price.price

    o.price = p
    db.session.commit()
    flash("Order Placed")
    return redirect(url_for('index'))
예제 #17
0
def place_order():
    form = OrderForm()
    engineer_id = request.args.get('engineer_id', 0, type=int)
    if form.validate_on_submit():
        order = Order(title=form.title.data,
                      description=form.description.data,
                      working_hours=form.working_hours.data,
                      state_id=Code.wait,
                      begin_time=form.begin_time.data,
                      project=Project.query.get(form.project.data),
                      sales=current_user)
        if engineer_id == 0:
            if not order.polling():
                flash('该工单入场时间段内无可用工程师')
                db.session.rollback()
                return redirect('sales.index')
        else:
            order.engineer = User.query.get(engineer_id)
        db.session.add(order)
        for i in request.form.getlist('products'):
            p = Products(order=order, product=Product.query.get(int(i)))
            db.session.add(p)
        db.session.commit()
        flash('已将工单派发给工程师{}'.format(order.engineer.name))
        return redirect(url_for('sales.orders'))
    if engineer_id != 0:
        user = User.query.get(engineer_id)
        form.engineer.choices = [(user.id, user.name)]
    return render_template('sales/place_order.html', title='派工', form=form)
예제 #18
0
 def test_deserialize_an_order(self):
     """ Test deserialization of an order """
     order_items = [{
         'product_id': 1,
         'name': 'Protein Bar (12 Count)',
         'quantity': 3,
         'price': 18.45,
     }, {
         'product_id': 2,
         'name': 'AirPods',
         'quantity': 1,
         'price': 159,
     }]
     data = {
         'customer_id': 1,
         'status': OrderStatus.RECEIVED,
         'order_items': order_items
     }
     order = Order()
     order.deserialize(data)
     self.assertIsNotNone(order)
     self.assertIsNone(order.id)
     self.assertEqual(order.order_items[0].quantity, 3)
     self.assertEqual(order.order_items[0].total, 55.35)
     self.assertEqual(order.customer_id, 1)
     self.assertEqual(order.order_items[1].name, 'AirPods')
     self.assertEqual(order.order_items[1].price, 159)
     self.assertEqual(order.total, 214.35)
def create_new_order():
    current_cust = Customer.query.filter_by(
        username=get_jwt_identity()).first()
    data = request.get_json()

    try:
        jobsite_address_data = data["jobsite_address"]
    except KeyError as e:
        return make_response("No attribute %s exists" % e, 400)

    order = Order(cust_id=current_cust.id)
    db.session.add(order)

    jobsite_address = Jobsite_Address(
        street_address_1=jobsite_address_data['street_address_1'],
        street_address_2=jobsite_address_data['street_address_2'],
        zip_code=jobsite_address_data['zip_code'],
        city=jobsite_address_data['city'],
        state=jobsite_address_data['state'],
        country=jobsite_address_data['country'],
        order_id=order.id)
    db.session.add(jobsite_address)
    order.jobsite_address = jobsite_address
    db.session.commit()

    return order.get_attributes()
예제 #20
0
def checkout():
    form = Checkout()

    products, grand_total, grand_total_plus_shipping, quantity_total = handle_cart(
    )

    if form.validate_on_submit():

        order = Order()
        form.populate_obj(order)
        order.reference = ''.join([random.choice('ABCDE') for _ in range(5)])
        order.status = 'PENDING'

        for product in products:
            order_item = Order_Item(quantity=product['quantity'],
                                    product_id=product['id'])
            order.items.append(order_item)

            product = Product.query.filter_by(id=product['id']).update(
                {'stock': Product.stock - product['quantity']})

        db.session.add(order)
        db.session.commit()

        session['cart'] = []
        session.modified = True

        return (redirect(url_for('index')))

    return (render_template(
        'checkout.html',
        form=form,
        grand_total=grand_total,
        grand_total_plus_shipping=grand_total_plus_shipping,
        quantity_total=quantity_total))
예제 #21
0
    def test_serialize_an_order(self):
        """ Test serialization of an order """
        order_items = [{
            'product_id': 1,
            'name': 'Protein Bar (12 Count)',
            'quantity': 3,
            'price': 18.45,
        }, {
            'product_id': 2,
            'name': 'AirPods',
            'quantity': 1,
            'price': 159,
        }]
        order = Order(customer_id=1, status=OrderStatus.RECEIVED)
        for order_item in order_items:
            order.order_items.append(
                OrderItem(product_id=order_item['product_id'],
                          name=order_item['name'],
                          quantity=order_item['quantity'],
                          price=order_item['price']))

        data = order.serialize()
        self.assertIsNotNone(data)
        self.assertIn('id', data)
        self.assertIsNone(data['id'])
        self.assertIn('order_items', data)
        self.assertEqual(data['order_items'][0]['name'],
                         'Protein Bar (12 Count)')
        self.assertEqual(data['order_items'][0]['quantity'], 3)
        self.assertEqual(data['order_items'][0]['price'], 18.45)

        self.assertEqual(data['order_items'][1]['name'], 'AirPods')
        self.assertEqual(data['order_items'][1]['quantity'], 1)
        self.assertIn('customer_id', data)
        self.assertEqual(data['customer_id'], 1)
예제 #22
0
def create(order_number, trad_no, invoice_titile, invoice_company,
           invoice_content, consignee_address, order_price, pay_status,
           is_send, user_id, goods):
    if Order.query.filter(or_(Order.order_number == order_number)).first():
        return ValidationErrorResult(message='Order已存在')
    order = Order(order_number=order_number,
                  trad_no=trad_no,
                  invoice_titile=invoice_titile,
                  invoice_company=invoice_company,
                  invoice_content=invoice_content,
                  consignee_address=consignee_address,
                  order_price=order_price,
                  pay_status=pay_status,
                  is_send=is_send)

    user = User.query.filter(User.id == user_id).one()
    if user:
        user.orders.append(order)
        order.user_id = user_id
    if goods:
        for good in goods:
            gd = Good.query.filter(Good.id == good['id']).one()
            if gd:
                order.goods.append(gd)
    db.session.add(order)
    db.session.flush()
    return jsonify(schemas.order_schema.dump(order)), 201
예제 #23
0
    def post(self, request):
        # Create order
        body = parse_body(request)
        user = User.objects.get(id=body['user'])
        products = [{
            "instance": Product.objects.get(id=product["id"]),
            "options": product["options"],
        } for product in body["products"]]
        order = Order(user=user, )
        order.save()
        for product in products:
            order.products.add(product["instance"])
        payment = Payment(
            order=order,
            method='Credit card',
            value=self.sum_products_prices(products),
        )
        payment.save()
        charge = stripe.Charge.create(
            amount=self.format_price(self.sum_products_prices(products)),
            currency='usd',
            description='Order #' + str(order.id),
            customer=user.creditcard.customer_id,
        )
        response = {"id": order.id, "total": payment.value}

        return JsonResponse(response, status=201)
예제 #24
0
    def test_repr(self):
        """ Test that string representation is correct """
        date = datetime.now()
        order = Order(customer_id=1, date=date, status = 'processing')
        order.save()

        self.assertEqual(order.__repr__(), "<Order>")
예제 #25
0
파일: __init__.py 프로젝트: bevkololi/BAM
    def myorders():
        auth_header = request.headers.get('Authorization')
        access_token = auth_header.split(" ")[1]

        if access_token:
            user_id = User.decode_token(access_token)
            if not isinstance(user_id, str):
                if request.method == "POST":
                    meal = str(request.data.get('meal', ''))
                    quantity = str(request.data.get('quantity', ''))
                    ordered_by = Order.ordered_by
                    if quantity:
                        int(quantity)
                    else:
                        return {"message": "Quantity should be a number"}, 200
                    if meal:
                        order = Order(meal=meal,
                                      quantity=quantity,
                                      ordered_by=user_id)
                        order.save()
                        response = jsonify({
                            'id': order.id,
                            'meal': order.meal,
                            'time_ordered': order.time_ordered,
                            'quantity': order.quantity,
                            'ordered_by': user_id
                        })

                        return make_response(response), 201
                    else:
                        return jsonify({
                            'message':
                            'Please input the meal name and quantity'
                        })

                else:
                    orders = Order.get_all(user_id)
                    results = []

                    for order in orders:
                        obj = {
                            'id': order.id,
                            'meal': order.meal,
                            'time_ordered': order.time_ordered,
                            'quantity': order.quantity,
                            'ordered_by': order.ordered_by
                        }
                        results.append(obj)

                    return make_response(jsonify(results)), 200
            else:
                # user is not legit, so the payload is an error message
                message = user_id
                response = {'message': message}
                return make_response(jsonify(response)), 401

        else:
            response = {'message': 'Please input access token'}
            return make_response(jsonify(response)), 401
예제 #26
0
 def test_find_by_time(self):
     """ Find a Order by Time """
     Order(0, "fido", "dog").save()
     Order(0, "kitty", "cat").save()
     orders = Order.find_by_time("cat")
     self.assertNotEqual(len(orders), 0)
     self.assertEqual(orders[0].time, "cat")
     self.assertEqual(orders[0].name, "kitty")
예제 #27
0
 def test_deserialize_a_order(self):
     data = {"id": 1, "customer_name": "Bob", "amount_paid": '300'}
     order = Order(data['id'])
     order.deserialize(data)
     self.assertNotEqual(order, None)
     self.assertEqual(order.id, 1)
     self.assertEqual(order.customer_name, "Bob")
     self.assertEqual(order.amount_paid, '300')
예제 #28
0
    def test_invalid_key_raises_error(self):
        """ Try to pass invalid key """
        date = datetime.now()
        data = {"id": 1, "date": date, "status": 'processing'}

        with self.assertRaises(DataValidationError):
            order = Order()
            order.deserialize(data)
예제 #29
0
 def test_find_order(self):
     """ Find a Order by id """
     Order(0, "fido", "dog").save()
     Order(0, "kitty", "cat").save()
     order = Order.find(2)
     self.assertIsNot(order, None)
     self.assertEqual(order.id, 2)
     self.assertEqual(order.name, "kitty")
예제 #30
0
def PlaceOrder():
    flashMessages = list()
    status = False
    orderMarkup = ''
    form = PlaceOrderForm()
    if form.validate_on_submit():
        try:
            products_sku = [
                x.strip() for x in form.products.data.split(',')
                if x.strip() != ''
            ]
            products_sku = Counter(products_sku)
            vendor = User.query.filter(
                User.vendor_id == form.vendor_id.data).first()
            if vendor is None:
                flashMessages.append('Несуществующий поставщик.')
                raise OrderException()
            order = Order(store_id=current_user.id,
                          address=form.address.data,
                          city=form.city.data,
                          email=form.email.data,
                          country=form.country.data,
                          phone=form.phone.data,
                          province=form.province.data,
                          comment=form.comment.data,
                          postal_code=form.postal_code.data,
                          name=form.name.data)
            orderProducts = list()
            for sku in products_sku:
                p = Product.query.filter(
                    Product.sku == sku,
                    Product.store_id == current_user.id).first()
                if p is None:
                    flashMessages.append('Некорректные артикулы.')
                    raise OrderException()
                op = OrderProducts(count=products_sku[sku],
                                   price=p.price,
                                   sku=sku,
                                   title=p.title,
                                   picture=p.picture,
                                   description=p.description)
                db.session.add(op)
                orderProducts.append(op)
            order.products = orderProducts
            db.session.add(order)
            db.session.commit()
            flashMessages.append('Заказ успешно размещён.')
            status = True
            orderMarkup = render_template('_order.html',
                                          order=order,
                                          removeOrderForm=RemoveOrderForm())
        except:
            flashMessages.append('Не удалось разместить заказ.')
    return jsonify({
        'status': status,
        'flash': flashMessages,
        'orderMarkup': orderMarkup
    })
예제 #31
0
def buy(request):
    form = PurchaseForm(request.POST or None)
    if request.POST and form.is_valid():
            order = Order()
            order.num_shares = form.cleaned_data.get('num_shares')
            order.buyer = request.user.consumer_set.all()[0]
            order.shop = form.cleaned_data.get('shop')
            order.save()
            return HttpResponseRedirect(reverse('buy'))
    return render(request, "buy.html", {'form': form})
예제 #32
0
    def post(self, request, *args, **kwargs):
        complete_json_order = request.body

        complete_order_dict = json.loads(complete_json_order)

        customer_username = complete_order_dict["customer"]
        order_type = complete_order_dict["type"]
        product_items = complete_order_dict["productItems"]
        products_id_quantity = complete_order_dict["products"]
        date_fulfillment_scheduled = complete_order_dict["dateFulfilmentScheduled"]
        #dateFulfilmentScheduled

        order = Order()
        order.customer = User.objects.get(username=customer_username)
        order.date_initiated = datetime.now()
        order.date_fulfillment_scheduled = datetime.strptime(date_fulfillment_scheduled, '%d/%m/%Y')
        order.attendant_staff = request.user
        order.type = order_type

        if order.type == 'B':
            order.bulk_plan = BulkPlan.objects.get(owner__username=customer_username)

        if order.type == 'N':
            #calculate order price
            total_price = Decimal(0.0)
            for product in products_id_quantity:
                price = Product.objects.get(id=product["id"]).price
                total_this_product = price * product["quantity"]
                total_price += total_this_product

            order.amount = total_price
            order.amount_discount = 0
            order.amount_payable = order.amount - order.amount_discount

        order.order_number = OrderOperations.generate_order_number(order)
        order.save()

        action = OrderAction(order=order, action='C', actor=request.user,)
        action.save()

        # create order products
        for product in product_items:
            product_id = product["id"]
            product_serial = product["serialNumber"]
            product_items = product["items"]

            order_product = OrderProduct(order=order)
            order_product.product = Product.objects.get(id=product_id)
            order_product.serial_number = product_serial
            order_product.product_name = order_product.product.name
            order_product.product_price = order_product.product.price

            order_product.save()

            # create and add orderitems to order product
            for item in product_items:
                item_serial = item["serialNumber"]
                item_id = item["id"]
                item_colour_id = item["colourId"]
                item_alteration_id = item["alterationId"]

                item_model = ProductItem.objects.get(id=item_id).item

                order_item = OrderItem(order_product=order_product, serial_number=item_serial, item=item_model,)

                if item_colour_id:
                    order_item.colour = Colour.objects.get(id=item_colour_id)

                if item_alteration_id:
                    order_item.alteration = Alteration.objects.get(id=item_alteration_id)
                
                order_item.item_name = item_model.name
                order_item.item_tag = OrderOperations.generate_item_tag(order.order_number, product_serial, item_serial)

                order_item.save()
        
        # send order email
        to_email = order.customer.email
        logging.error(to_email,)
        if to_email:
            context_dictionary = dict()

            context_dictionary['company'] = General.get_company_information()
            context_dictionary['order'] = order

            invoice_email = Notifications.generate_email('invoice.htm', context_dictionary)
            response = Notifications.send_email(invoice_email, "New Fullers Haven Order", to_email,) 

        # send order SMS
        to_phone = order.customer.profile.phone if order.customer.profile else None
        logging.error(to_phone,)

        if to_phone:
            context_data = {'order_number': order.order_number, 
                            'number_of_items': order.number_of_items, 
                            'collection_date': GlobalOperations.get_date_as_text(order.date_fulfillment_scheduled, False)
                            }
            response = Notifications.send_smssolutions_sms('sms/new_order.txt', context_data, "234{0}".format(to_phone[1:]),)

        logging.debug("Good boy",)
        return Response({'order_id' : order.id}, status=status.HTTP_201_CREATED)
예제 #33
0
def process_order(request):
    print "placing order"

    try:
        phone_number = request.POST.get("phone_number")
        user_name = request.POST.get("userName")
        email = request.POST.get("email")
        app_version = request.POST.get("app_version")
        device_id = request.POST.get("device_id")
        app_id = request.POST.get("app_id")
        bring_change_of = int(request.POST.get("bring_change_of", "0"))
        address_str = request.POST.get("address")
        landmark = request.POST.get("landmark")
        location_show = request.POST.get("location_show")
        location_id = request.POST.get("location_id")
        api_key = request.POST.get("api_key")
        products = request.POST.get("products")
        tomorrow = request.POST.get("tomorrow")
        delivery_time = request.POST.get("delivery_time")
        # print request
        coupon_id = int(request.POST.get("coupon_id", "0"))

        coupon = None

        print "coupon"
        print phone_number
        user = User.objects.get(username=phone_number)
        if user:
            user.email = email
            user.first_name = user_name.title()
            user.save()
            user_profile = user.userprofile
            user_profile.app_version = app_version
            user_profile.app_id = app_id
            user_profile.device_id = device_id
            user_profile.save()
            if user.api_key.key != api_key:
                print "api key is not valid"
                data = simplejson.dumps({"status": "Not Valid Request"})
                return HttpResponse(data, content_type="application/json", status=403)
        else:
            print "User not found"
            data = simplejson.dumps({"status": "Not Valid Request"})
            return HttpResponse(data, content_type="application/json", status=403)

        print "user obj created"
        print coupon_id

        if coupon_id > 0:
            coupon = Coupon.objects.get(pk=coupon_id)
            coupon.used_count += 1
            coupon.save()
            print coupon
            prev_order = Order.objects.filter(coupon_applied=coupon, user=user)
            print user
            if prev_order:
                if prev_order[0].status != 1:
                    print "coupon invalidation1"
                    coupon = None
            print coupon
        print "check for coupon"
        location = Location.objects.get(pk=location_id)
        address = Address.objects.filter(user=user, address=address_str, landmark=landmark)
        if address:
            address = address[0]
            address.location = location
            address.save()
        else:
            address = Address(
                user=user, address=address_str, landmark=landmark, location_show=location_show, location=location
            )
            address.save()
        print "address done"

        # print products
        products = products.split(",")
        product_ids = map(lambda x: x.split("::")[0], products)
        product_qns = map(lambda x: x.split("::")[1], products)
        print product_ids
        print product_qns
        order = Order(user=user, total_amount=0, address=address, status=3)
        if tomorrow == "1":
            print delivery_time
            if dt.datetime.now().hour > 20:
                order.delivery_time = dt.datetime.strptime(
                    str((dt.datetime.now() + dt.timedelta(days=1)).date()) + " " + delivery_time, "%Y-%m-%d %I:%M %p"
                )
            else:
                order.delivery_time = dt.datetime.strptime(
                    str(dt.datetime.now().date()) + " " + delivery_time, "%Y-%m-%d %I:%M %p"
                )
        else:
            order.delivery_time = dt.datetime.now() + dt.timedelta(hours=1)
        if bring_change_of:
            order.change_requested = bring_change_of
        order.save()
        invoice = Invoice(order=order, product_json="")
        invoice.save()
        print "order obj saved"
        total_amount = 0
        index = 0

        ordered_services = {}
        products_json = []
        for p_id in product_ids:
            prd = StoreProductMapping.objects.get(pk=p_id)
            products_json.append(
                {
                    "spid": prd.id,
                    "pid": prd.product.product.id,
                    "name": prd.product.product.name,
                    "price": prd.price,
                    "discount": prd.discount,
                    "qn": product_qns[index],
                    "size_id": prd.product.size.id,
                }
            )
            service = prd.product.product.category.service
            if "offer" in service.name.lower():
                OfferDeviceId(device_id=device_id).save()
                OfferProductOrderMapping(
                    device_id=device_id, order=order, offer_product=prd.offerproductmapping_set.all()[0]
                ).save()
            if str(service.id) not in ordered_services:
                ordered_services[str(service.id)] = 0
            total_amount += int(product_qns[index]) * (prd.price - prd.discount)
            ordered_services[str(service.id)] += int(product_qns[index]) * (prd.price - prd.discount)
            store = prd.store
            cart = Cart.objects.filter(order=order, store=store)
            if cart:
                cart = cart[0]
            else:
                cart = Cart(order=order, store=store)
                cart.save()

            OrderedProduct(product=prd, cart=cart, quantity=product_qns[index]).save()
            index += 1
        products_json = simplejson.dumps(products_json)
        invoice.product_json = products_json
        invoice.save()

        service_amount_ordered = []
        for key in ordered_services:
            service_amount_ordered.append(str(key) + ":" + str(ordered_services[key]))
        service_amount_ordered = ";;".join(service_amount_ordered)
        print total_amount

        final_amount = total_amount

        if coupon:
            if total_amount >= coupon.min_total:
                order.coupon_applied = coupon
                print "found coupon"
                print coupon.code
                print coupon
                print user
                print location_id
                print int(app_version)
                print final_amount
                print service_amount_ordered
                discount = verify_coupon(
                    coupon, user, location_id, int(app_version), final_amount, service_amount_ordered
                )["discount"]
                print "discount" + str(discount)
                final_amount -= discount

        print "passed coupon part"

        delivery_charges = {}
        for key in ordered_services:
            service = Service.objects.get(pk=key)
            lsm = LocationServiceMapping.objects.filter(service=service, location=location)
            if lsm:
                lsm = lsm[0]
                stl = StoreTimingInLocation.objects.filter(store__is_active=True, is_active=True, lsm=lsm)
                print "done"
                if stl:
                    stl = stl[0]
                    if key not in delivery_charges:
                        delivery_charges[key] = {"delivery_charges": 0, "delivery_amount_min": stl.delivery_min_amount}
                    if ordered_services[key] < stl.delivery_min_amount:
                        final_amount += -stl.delivery_charges
                        total_amount += stl.delivery_charges
                        delivery_charges[key]["delivery_charges"] = stl.delivery_charges
                else:
                    delivery_charges[key] = {"delivery_charges": 0, "delivery_amount_min": 0}
            else:
                delivery_charges[key] = {"delivery_charges": 0, "delivery_amount_min": 0}

        print "passed delivery part"

        order.total_amount = total_amount
        order.final_amount = final_amount
        order.delivery_charges = simplejson.dumps(delivery_charges)
        order.save()
        OrderActivity(order=order, user=order.user, actions=0, comment=" ").save()

        data = simplejson.dumps({"status": "done"})
        return HttpResponse(data, content_type="application/json", status=201)
    except Exception as process_order_function_error:
        print "process_order: " + str(process_order_function_error)
        data = simplejson.dumps({"status": "Server Error"})
        send_mail(
            "Order placing Error " + str(process_order_function_error),
            str(request) + "\n\n\n" + str(simplejson.dumps(request.POST)),
            "*****@*****.**",
            ["*****@*****.**"],
            fail_silently=False,
        )
        return HttpResponse(data, content_type="application/json", status=500)
예제 #34
0
    def obj_create(self, bundle, request=None, **kwargs):
        # data={'status':'cant place order'}
        # return HttpResponse(data, content_type='application/json')
        print bundle.data
        phone_number =  bundle.data['phone_number']
        userName =  bundle.data['userName']
        email =  bundle.data['email']
        app_version =  bundle.data['app_version']
        device_id =  bundle.data['device_id']
        app_id =  bundle.data['app_id']
        bring_change_of =  int(bundle.data['bring_change_of'])

        address_str = bundle.data['address']
        landmark = bundle.data['landmark']
        location_show = bundle.data['location_show']
        location_id = bundle.data['location_id']
        coupon_id =""
        try:
            coupon_id = int(bundle.data['coupon_id'])
        except:
            pass

        coupon=None

        print 'coupon'
        print phone_number
        user = User.objects.filter(username=phone_number)
        print user
        print '----'
        if user:
            user=user[0]
            user.email = email
            user.first_name=userName.title()
            user.save()
            print 'user saved'
            userProfile =UserProfile.objects.filter(user=user)
            print 'userprofile'
            print userProfile
            print '----'
            if userProfile:
                userProfile = userProfile[0]
                userProfile.app_version=app_version
                userProfile.app_id=app_id
                userProfile.device_id=device_id
                userProfile.save()
            else:
                UserProfile(user=user,contact=int(phone_number),app_id=app_id,app_version=app_version,device_id=device_id).save()
        else:
            user=User.objects.create_user(phone_number,email,phone_number)
            user.first_name=userName.title()
            user.save()
            UserProfile(user=user,contact=int(phone_number),app_id=app_id,app_version=app_version,device_id=device_id).save()
        print 'user obj created'
        print coupon_id
        if coupon_id>0:
            coupon = Coupon.objects.get(pk=coupon_id)
            coupon.used_count+=1
            coupon.save()
            print coupon
            prev_order = Order.objects.filter(coupon_applied=coupon,user=user)
            print user
            if prev_order:
                if prev_order[0].status!=1:
                    print 'coupon invalidation1'
                    coupon=None
            print coupon
        print 'check for coupon'
        location = Location.objects.get(pk=location_id)
        address  = Address.objects.filter(user =user ,address=address_str,landmark=landmark)
        if address:
            address=address[0]
        else:
            address  = Address(user =user ,address=address_str,landmark=landmark,location_show=location_show,location=location )
            address.save()
        print 'address done'
        products = bundle.data['products']
        # print products
        products = products.split(',')
        product_ids = map(lambda x:x.split('::')[0],products)
        product_qns = map(lambda x:x.split('::')[1],products)
        print product_ids
        print product_qns
        order = Order(user = user,total_amount=0,address=address,status=3)
        order.delivery_time=dt.datetime.now()+dt.timedelta(hours=1)
        order.save()
        print 'order obj saved'
        total_amount = 0
        index=0

        ordered_services={}
        products_json=[]
        for p_id in product_ids:
            prd = StoreProductMapping.objects.get(pk=p_id)
            products_json.append({'spid':prd.id,'pid':prd.product.product.id,'name':prd.product.product.name,'price':prd.price,'discount':prd.discount,'qn':product_qns[index],'size_id':prd.product.size.id})
            service = prd.product.product.category.service
            if 'offer' in service.name.lower():
                OfferProductOrderMapping(device_id=device_id,order=order,offer_product=prd.offerproductmapping_set.all()[0]).save()
                OfferDeviceId(device_id=device_id).save()
            if str(service.id) not in ordered_services:
                ordered_services[str(service.id)]= 0
            total_amount+= int(product_qns[index])*(prd.price- prd.discount)
            ordered_services[str(service.id)]+= int(product_qns[index])*(prd.price- prd.discount)
            store = prd.store
            cart = Cart.objects.filter(order=order,store=store)
            if cart:
                cart=cart[0]
            else:
                cart = Cart(order=order,store=store)
                cart.save()

            OrderedProduct(product=prd,cart=cart,quantity=product_qns[index]).save()
            index+=1
        service_amount_ordered=[]
        for key in ordered_services:
            service_amount_ordered.append(str(key)+":"+str(ordered_services[key]))
        service_amount_ordered=';;'.join(service_amount_ordered)
        print total_amount

        final_amount=total_amount
        if coupon:
            if total_amount>=coupon.min_total:
                order.coupon_applied=coupon
                print 'found coupon'
                print coupon.code
                print coupon
                print user
                print location_id
                print int(app_version)
                print final_amount
                print service_amount_ordered
                discount = verify_coupon(coupon,user,location_id,int(app_version),final_amount,service_amount_ordered)['discount']
                print "discount" + str(discount)
                final_amount-=discount
        print "passed coupon part"
        delivery_charges = 0
        delivery_charges_to_save_in_order={}
        for key in ordered_services:
            service=Service.objects.get(pk=key)
            lsm = LocationServiceMapping.objects.filter(service=service,location=location)
            if lsm:
                lsm=lsm[0]
                stl = StoreTimingInLocation.objects.filter(store__is_active=True,is_active=True,lsm=lsm)
                print 'done'
                if stl:
                    stl=stl[0]
                    # print 'done1'
                    if key not in delivery_charges_to_save_in_order:
                        # print 'done10'
                        delivery_charges_to_save_in_order[key]={'delivery_charges':0,'delivery_amount_min':stl.delivery_min_amount}
                        # print 'done11'
                    if ordered_services[key]<stl.delivery_min_amount:
                        # print 'done20'
                        final_amount+=-stl.delivery_charges
                        total_amount+=stl.delivery_charges
                        # print 'done21'
                        delivery_charges_to_save_in_order[key]['delivery_charges']=stl.delivery_charges
                        # print 'done22'
                else:
                    delivery_charges_to_save_in_order[key]={'delivery_charges':0,'delivery_amount_min':0}
            else:
                delivery_charges_to_save_in_order[key]={'delivery_charges':0,'delivery_amount_min':0}
        print "passed delivery part"
        order.total_amount=total_amount
        order.final_amount=final_amount
        if bring_change_of:
            order.change_requested=bring_change_of
        order.delivery_charges = simplejson.dumps(delivery_charges_to_save_in_order)
        order.save()
        products_json=simplejson.dumps(products_json)
        Invoice(order=order,product_json=products_json).save()
        bundle.obj=order
        OrderActivity(order=order,user=order.user,actions=0,comment=" ").save()
        print bundle
        return bundle