Exemplo n.º 1
0
def make_order(request, chip_id):
    chip = Chip.objects.all().filter(tag=chip_id)
    if chip.exists():
        old_order = Order.objects.all().filter(chip__tag=chip_id, status=OrderStatusOptions.PENDING).order_by(
            '-created')
        new_order = Order(
                chip=chip[0]
        )

        save_new = True
        if len(old_order) >= 0:
            order = old_order[0]
            order_id = order.id

            now_ts = datetime.datetime.now().timestamp()
            create_ts = order.created.timestamp()
            t = now_ts - create_ts
            if t < 5 * 60:
                save_new = False
                order.created = datetime.datetime.now()
                order.save()

        if save_new:
            new_order.save()
            order_id = new_order.id

        return HttpResponse('{ "order" : ' + str(order_id) + '}')
    else:
        return HttpResponse('{ "order" : -1 }')
Exemplo n.º 2
0
def place_order(request):
    if request.method == 'POST':
        search_form = OrderForm(request.POST)
        if search_form.is_valid():
            unique_flight_id = request.POST['unique_flight_id']
            first_name = search_form.cleaned_data['first_name']
            last_name = search_form.cleaned_data['last_name']
            document_id = search_form.cleaned_data['document_id']
            birth_day = search_form.cleaned_data['birth_day']
            email = search_form.cleaned_data['email']
            class_of_service = request.POST['class_of_service']

            order = Order(unique_flight_id=unique_flight_id,
                          first_name=first_name,
                          last_name=last_name,
                          document_id=document_id,
                          birth_day=birth_day,
                          email=email,
                          order_hash=uuid.uuid1().hex,
                          booking_id=uuid.uuid1().hex[:7].upper(),
                          class_of_service=class_of_service)

            if order.unique_flight.try_take_seat(class_of_service):
                order.save()
                send_order(order)
                return render_to_response('status.html', {'status': 'Order created, link sent to you by email'},
                                          context_instance=RequestContext(request))
            else:
                return render_to_response('status.html', {
                    'status': 'We are sorry, but there are no free places of class you have chosen'},
                                          context_instance=RequestContext(request))
    else:
        return redirect('/search/')
Exemplo n.º 3
0
def recommend_engineer(request):
    if request.method=='GET':
        area_id = int(request.GET.get('area_id',1))
        accountname = request.GET.get('accountname')
        
        order = Order()
        order.creator = request.user.username
        order.accountname = accountname
        
        dd = {}
        
        staff = executive_helper(order)
        
        if staff:
            # 优先级 1:'紧急',2:'普通'
            dd['priority_level'] = 1
        else:
            staff = designate_engineer(area_id)
            dd['priority_level'] = 2
        
        comment = ''
        if staff:
            comment = u"系统推荐:" + staff.area.name + ' ' + staff.realname
            dd['comment'] = comment
            dd['id'] = staff.id
            dd['area_id'] = staff.area.id
        else:
            comment = u"此区域没有对应的IT工程师"
            dd['comment'] = comment
            
        return HttpResponse(json.dumps(dd))
    else:
        return  HttpResponseBadRequest(u"错误请求")
Exemplo n.º 4
0
def order(request):
        if request.method == 'POST':
            form = OrderForm(request.POST)
            if form.is_valid():
                _customerid  =   form.cleaned_data['customerid']
                _voltage     =   form.cleaned_data['voltage']
                _current     =   form.cleaned_data['current']
                _width       =   form.cleaned_data['width']
                _height      =   form.cleaned_data['height']
                _status      =   form.cleaned_data['status']

                job = Order(customerid=_customerid, voltage=_voltage, current=_current, width=_width, height=_height, status=_status, order_ts=timezone.now())
                job.save()

                return HttpResponse("thank you!")
            
            else:
                form = OrderForm()
                render(request, 'order.html', {
                        'form': form,
                        })

        else: 
            form = OrderForm()
            return render(request, 'order.html', {
               'form': form,
               })
Exemplo n.º 5
0
def generate(request):
    if request.POST:
        cart = ShoppingCartForm(request)
        address_id = request.POST.get('address', '')
        if not address_id:
            messages.error(request, u'请选择一个送货地址。')
            return shortcuts.redirect(reverse('order-generate'))
        address = shortcuts.get_object_or_404(ContactAddress, id=address_id, user=request.user)
        
        with transaction.commit_on_success():
            order = Order(owner=request.user,
                          address=str(address),
                          description=request.POST.get('description', ''),
                          amount=cart.amount)
            order.save()
            
            for pid, p in cart.products.iteritems():
                OrderItem(order=order,
                           product=shortcuts.get_object_or_404(Product, id=pid),
                           price=p['price'],
                           count=p['count']
                           ).save()
                           
            cart.delete(request)
            messages.success(request, u'下单成功!请等待系统确认。')
            return shortcuts.redirect(reverse('order-detail', args=[order.id]))
    
    addresses = ContactAddress.objects.filter(user=request.user)
    if not addresses:
        messages.error(request, u'你还没有送货地址,请创建至少一个送货地址。')
        return shortcuts.redirect(reverse('account-address-add'))
    
    return shortcuts.render_to_response('order/generate.html',
                    {'addresses': addresses},
                    context_instance=RequestContext(request))
Exemplo n.º 6
0
    def post(self, request):
        order = Order()
        order.cart_id = request.session.get(CART_ID)
        order.address = request.POST.get('address')
        order.phone = request.POST.get('phone')
        order.name = request.POST.get('name')
        order.processed = False
        order.comment = request.POST.get('comment')
        if request.user.is_authenticated():
            order.customer = request.user
        order.save()

        cart = CartService(request)
        cart.checkout()

        params = {
            "phone": unicode(request.POST.get('phone')),
            "name": None,
            "customer": request.user,
            "comment": order.comment,
            "orderno": order.id,
            "orderdt": order.checkout_date,
            "orderaddr": order.address,
            "ordercart": cart,
        }

        send_notification("order_notice", params)

        return render(request, 'cart/after_order.html')
Exemplo n.º 7
0
 def create_order(self):
     order = Order()
     for step in self.steps:
         step.add_to_order(order)
     if self.request.user.is_authenticated():
         order.user = self.request.user
         order.anonymous_user_email = ''
     order.save()
     return order
Exemplo n.º 8
0
 def create(self, validated_data):
     customer_id = self.context['request'].user.customer.id
     counter = Counter.objects.filter(saldo__gte = validated_data.get('purchase'))
     turn = OrderTurn.objects.get(pk=1).turn
     order = Order()
     order.customer = Customer.objects.get(pk=customer_id)
     order.counter = counter[turn]
     order.purchase = validated_data.get('purchase')
     order.phone_number = validated_data.get('phone_number')
     return order
Exemplo n.º 9
0
 def add_order(cls, *, cus_phone, bar_phone=None, time_=None, accepted=None, hairstyle=None, remark=None):
     try:
         Checker.phone(cus_phone)
         order = Order()
         order.ord_cus_id = Customer.objects.get(cus_phone=cus_phone)
         if bar_phone:
             Checker.phone(bar_phone)
             order.ord_barber_id = Barber.objects.get(barber_phone=bar_phone)
         if time_:
             Checker.appt_time(time_)  #
             order.ord_time = time_
         if accepted is not None:
             order.ord_is_acc = accepted
         if hairstyle:
             order.ord_hairstyle_id = Hairstyle.objects.get(hairstyle_name=hairstyle)
         if remark:
             order.ord_remark = remark
         order.save()
         return OrderProxy.get_by_object(order)
     except Customer.DoesNotExist:
         raise CustomerDoesNotExistError
     except Barber.DoesNotExist:
         raise BarberDoesNotExistError
     except Hairstyle.DoesNotExist:
         raise HairstyleDoesNotExistError
Exemplo n.º 10
0
 def try_take_seat_by_class(self, class_of_service):
     order = Order.objects.create(unique_flight=self.unique_flight, class_of_service=class_of_service)
     free_seats = Order.get_free_seats(self.unique_flight.id, self.unique_flight.flight.aircraft, class_of_service)
     self.assertEqual(len(free_seats), 10)
     taken_seat = free_seats[0]
     order.try_take_seat(taken_seat)
     free_seats = Order.get_free_seats(self.unique_flight.id, self.unique_flight.flight.aircraft,
                                       class_of_service)
     self.assertEqual(len(free_seats), 9)
     self.assertNotIn(taken_seat, free_seats)
     order.delete()
Exemplo n.º 11
0
def admin_order():
    startdate = request.args.get('startdate')
    enddate = request.args.get('enddate')
    username = request.args.get('username')
    users = User.load_all()

    if username:
        # pprint.pprint(username)
        orders = Order.load_user(username)
        # pprint.pprint(orders)
    elif startdate:
        # pprint.pprint(startdate)
        x = datetime.utcfromtimestamp(float(startdate[0:10]))
        y = datetime.utcfromtimestamp(float(enddate[0:10]))
        orders = Order.filter_date(x, y,'')
    else:
        orders = Order.load_all()
    return render_template("admin/admin_order.html", orders=orders,users=users)
Exemplo n.º 12
0
def filtrate_date():
    startdate = request.args.get('startdate')[0:10]
    enddate = request.args.get('enddate')[0:10]

    x = datetime.utcfromtimestamp(float(startdate))
    y = datetime.utcfromtimestamp(float(enddate))
    
    orders_with_filter = Order.filter_date(x, y, session['username'])

    return render_template("account.html",orders=orders_with_filter)
Exemplo n.º 13
0
def importData(dataStr):
    CLIENT = "家和"
    data = fixGlassCSV(dataStr)
    data = data.strip() 
    lines = data.split("\n")
    lastLine = ""
    lastOrder = Order.create(CLIENT)
    lastOrder.save()
    for i in range(len(lines)):
        l = lines[i]
        logger.info(i)
        if not l or "\n" == l:
            if not lastLine: # two block line a raw
                continue
            # block line mean a new order
            order = Order.create(CLIENT)
            logger.info("create a new order"+str(i+1))
            order.save()
            lastOrder = order
        else:
            #l = l.replace("\r\n", "")
            l = l.strip()
            data = l.split(",")
            if (len(data) != 6):
                raise Exception("data format wrong :" + data)
            mode = int(data[0])
            glassType = data[1]
            width = float(data[2])
            height = float(data[3])
            quantity = int(data[4])
            rub = data[5]
            unitPrice = findPriceByGlassType(glassType) if (mode!=0) else 0
            glassName = getGlassNameByGlassType(glassType)
            row = GlassRow.create(name=glassName, quantity=quantity,
                                  unitPrice=unitPrice, orderId=lastOrder,
                                  width=width, height=height,
                                  rate=1.2, rubEdge=rub, rubEdgeUnitPrice=0.8,
                                  extra="", extraCost=0)
            logger.info("create a row " + str(row))
            row.save()
            lastLine = l
    return lines
Exemplo n.º 14
0
def create(request):
    if request.method == 'GET':
        return render_to_response('order/create.html', {})
    elif request.method == "POST":
        client = request.POST.get("order-client", "")
        phone = request.POST.get("order-phone", "0")
        note = request.POST.get("order-note", "")
        price = request.POST.get("order-price", "")
        cash = request.POST.get("order-cash", "")
        order = Order(client=client, phone=phone, date=datetime.datetime.now(),
                      price=price, cash=cash, status=0, note=note)
        logger.info("create a new order")
        order.save() # create a order
        data = []
        # get row form POST data
        for i in range(1,1000):
            if not request.POST.has_key('glass-width-'+str(i)):
                break # end of loop
            width = request.POST['glass-width-'+str(i)]
            if not width:
                continue
            name = request.POST['glass-name-'+str(i)]
            height = request.POST['glass-height-'+str(i)]
            quantity = request.POST['glass-quantity-'+str(i)]
            rate = request.POST['glass-rate-'+str(i)]
            unitPrice = request.POST['glass-unitPrice-'+str(i)]
            rubEdge = request.POST['glass-rubEdge-'+str(i)]
            extra = request.POST['glass-extra-'+str(i)]
            extraCost = request.POST['glass-extraCost-'+str(i)]
            if width and height and quantity and rate and unitPrice and rubEdge:
                width = float(width)
                height = float(height)
                quantity = int(quantity)
                rate = float(rate) if rate > 1.0 else 1.2
                unitPrice = float(unitPrice)
            extraCost = float(extraCost) if extraCost else 0
            data.append([name, width, height, quantity, rate, unitPrice, rubEdge, extra, extraCost])
        # fix input data
        data = fixData(data)
        saveOrderData(order, data)
        glassRow = order.glassrow_set.all()
        return render_to_response('order/createOrderResult.html', locals())
Exemplo n.º 15
0
Arquivo: views.py Projeto: ulexy/ulexy
def submitOrder(request):
    address_id = request.POST.get("address_id",'')
    cart_goods_list = request.POST.get("cart_goods_list",'')
    try:
        address_id = int(address_id)
    except ValueError:
        raise Http404

    uid = request.session.get('uid', None)
    if not uid:
        return HttpResponse(json.dumps({'status':'FAIL',"error":"用户未登录"},ensure_ascii = False))

    try:
        cart=Cart_customer.objects.get(uid=uid)
    except:
        return HttpResponse(json.dumps({'status':'FAIL',"error":"没有对应购物车信息"},ensure_ascii = False))

    cartGoodsList = Cart_goods.objects.filter(cart_id=cart.id ,goods_cart_type = 0)
    goodsInfo = []
    total_money = 0;
    for goods in cartGoodsList:
        if str(goods.cart_goods_id) in cart_goods_list:
            tmp = {}
            tmp['goods_no'] = goods.goods_no
            tmp['goods_num'] = goods.goods_num
            goods.goods_cart_type = 1;
            goods.save()

            goods_no = Goods_no.objects.get(goods_no = tmp['goods_no'])
            goods_no.goods_num_saled = goods_no.goods_num_saled + tmp['goods_num']
            tmp['goods_price'] = goods_no.goods_price
            goods_no.save()
            goodsInfo.append(tmp)
            total_money += tmp['goods_num'] * tmp['goods_price']
    order = Order(customer_id = uid, address_id = address_id,order_status=3,delivery_status=2,order_currency_value = total_money)
    order.save()

    for goods in goodsInfo:
        order_goods = Order_goods(order_id = order.order_id, goods_no = goods['goods_no'],goods_num = goods['goods_num'] )
        order_goods.save()

    return HttpResponse(json.dumps({'status':'SUCCESS',"order_id":order.order_id},ensure_ascii = False))
Exemplo n.º 16
0
def ql_flagged_content(request, parts, ql_object):

    cmd             = parts[1]
    content_type    = parts[2]
    record_id       = parts[3]
    message = (
        'Content has been unflagged and is now visible on the site.'
        if cmd == 'unflag' else
        'Content has been removed from site and replaced by a moderated message'
        if cmd == 'remove' else
        'Unknown command [%s].  No action taken' % cmd
    )
    Order.unflag_content(cmd, content_type, record_id)
    return render_to_response(
        "quick/flagged-content",
        {
            # "type"      : "price_update_notification", # Does this really need to be here? Stupid c/p ...
            "message"   : message,
        },
        context_instance=RequestContext(request)
    )
Exemplo n.º 17
0
def add_info(request):
     if request.method == 'POST':
        postdata = request.POST.copy()
        comment = postdata.get('comment')
        delivery = postdata.get('delivery')
        cart_id = postdata.get('cart_id')
        form = FormPerson(request.POST)
        if form.is_valid():
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']
            email = form.cleaned_data['email']
            tel_namb = form.cleaned_data['tel_namb']
            city = form.cleaned_data['city']
            x = Person.objects.create(
                first_name = first_name,
                last_name = last_name,
                email = email,
                tel_namb = tel_namb,
                comment = comment,
                city = city,
                )
        delivery = Delivery.objects.get(type_delivery=delivery)
        person = Person.objects.get(id = x.id)
        order1 = CartItem.objects.get(cart_id=cart_id)
        ord = Order()
        ord.delivery = delivery
        ord.person = person
        ord.order = order1
        ord.save()
        send_email(request, delivery, person, order1, comment, email, ord.id)
        return redirect('http://127.0.0.1:8000/index/')
Exemplo n.º 18
0
def add(request):
    model = Order()
    if request.POST:
        group = get_object_or_404(Group, pk=request.POST.get('group'))
        restaurant = get_object_or_404(Restaurant, pk=request.POST.get('restaurant'))
        time = request.POST.get('hours')+':'+request.POST.get('minutes')
        order_date = datetime.datetime.strptime(request.POST.get('date')+' '+time, '%d-%m-%Y %H:%M')
        model.name = request.POST.get('name')
        model.user = request.user
        model.group = group
        model.restaurant = restaurant
        model.order_time = order_date
        model.save()
        messages.success(request, 'Order created')
        return redirect('order:details', model.id)
Exemplo n.º 19
0
    def testGlassRow(self):
        order = Order(client="test-order", phone=0, date=datetime.now(), price=0, cash=0, status=0, note="");
        order.save()
        orderInDb = Order.objects.get(id=order.id)
        self.assertEquals(order.id, orderInDb.id)
        print Order.objects.all()

        # test insert row
        row = GlassRow.create(name='testrow', quantity=2, unitPrice=45, orderId=order, width=162, height=517, rate=1.2, rubEdge='22', rubEdgeUnitPrice=1, extra="", extraCost=0)
        row.save()
        rowInDb = GlassRow.objects.get(id=row.id)
        self.assertEquals(row.id, rowInDb.id)
        print GlassRow.objects.all()

        # test cal
        width = 382
        height = 1490
        quantity = 2
        unitPrice = 50
        expectPrice = 74.292
        row2 = GlassRow.create(name="testrow", quantity=quantity, unitPrice=unitPrice, orderId=order, width=width, height=height, rate=1.2, rubEdge="22", rubEdgeUnitPrice=0.8, extra="", extraCost=0)
        self.assertEquals(68.3016, row2.glassPrice)
        self.assertEquals(5.9904, row2.rubEdgeCost)
        self.assertTrue(expectPrice - row2.price < 0.01) # 
Exemplo n.º 20
0
def show_order(request, order_id, order_hash):
    try:
        order = Order.objects.get(pk=order_id, order_hash=order_hash)
    except Order.DoesNotExist:
        raise Http404
    diff = int((order.unique_flight.departure_datetime - datetime.datetime.now()).total_seconds() / 60)
    if 30 < diff < 360:
        aircraft = order.unique_flight.flight.aircraft
        free_seats = Order.get_free_seats(order.unique_flight.id, aircraft, order.class_of_service)
        return render_to_response('show_order.html', {'order': order,
                                                      'price': order.unique_flight.get_price(order.class_of_service),
                                                      'free_seats': free_seats,
                                                      'order_id': order_id}, context_instance=RequestContext(request))
    else:
        return render_to_response('status.html', {'status': 'It is not time for registration yet'},
                                  context_instance=RequestContext(request))
Exemplo n.º 21
0
    def post(self, request):
        cart = Cart()
        cart.save()
        item = Item()
        item.cart = cart
        item.quantity = int(request.POST.get("quantity", 1))
        item.product_id = int(request.POST["product_id"])
        item.save()

        order = Order()
        order.cart_id = cart.id
        order.address = "Уточнить у клиента"
        order.phone = request.POST.get('phone')
        order.name = request.POST.get('name')
        order.comment = "Заказ в один клик"
        if request.user.is_authenticated():
            order.customer = request.user
        order.save()

        cart_service = CartService(request, cart)

        params = {
            "phone": unicode(request.POST["phone"]),
            "name": unicode(request.POST["name"]),
            "customer": request.user,
            "comment": order.comment,
            "orderno": order.id,
            "orderdt": order.checkout_date,
            "orderaddr": order.address,
            "ordercart": cart_service,
        }

        send_notification("order_notice", params)
        response = HttpResponse(json.dumps({"order_id": order.id, "ok": 1}),
                                content_type="application/json")
        return response
Exemplo n.º 22
0
 def test_extra_similar_sides(self):
     """Test cumulative quantities for similar side dishes."""
     # Add two separate extra compote order items for 'Tracy'
     member = Member.objects.filter(lastname='Tracy')[0]
     client = Client.objects.get(member=member.id)
     order = Order.objects.get(client=client.id, delivery_date=self.today)
     order.add_item(
         'meal_component',
         component_group='compote',
         total_quantity=1,
         remark='no sugar')
     order.add_item(
         'meal_component',
         component_group='compote',
         total_quantity=1,
         remark='no sugar')
     mile_end_id = Route.objects.get(name='Mile-End').id
     route_list = Order.get_delivery_list(self.today, mile_end_id)
     self.assertTrue('Tracy' in repr(route_list))
Exemplo n.º 23
0
def SangpumOrderOkFunc(request):  # 주문하기
    # 주문 테이블에 저장
    Order(ord_cname=request.POST['name'],
          ord_addr=request.POST['addr'],
          ord_phone=request.POST['phone'],
          ord_quantity=request.POST['q'],
          state=0,
          ord_date=datetime.now(),
          ord_cid=Customer.objects.get(cus_mail=request.session['name']),
          ord_pid=Stock.objects.get(id=request.POST['pid'])).save()

    # 최근 주소지 저장
    CusAddr(
        ca_name=request.POST['name'],
        ca_addr=request.POST['addr'],
        ca_phone=request.POST['phone'],
        ca_mail=Customer.objects.get(cus_mail=request.session['name'])).save()

    # 재고량 변화
    sdata = Stock.objects.get(id=request.POST['pid'])
    sdata.st_quantity -= int(request.POST['q'])
    sdata.save()

    return HttpResponseRedirect("/")
Exemplo n.º 24
0
def uploadscan(request):
    data = {'success': False, 'message': None}
    if request.method == 'POST':
        rawImageUrl = request.POST.get('rawImageUrl', '').strip()
        orderid = request.POST.get('orderid', '').strip()
        airbnb = request.POST.get('airbnb', '').strip()
        google_drive = request.POST.get('google_drive', '').strip()
        imageUrl = ''

        if rawImageUrl:
            imageUrl = rawImageUrl
        elif airbnb:
            imageUrl = airbnb
        elif google_drive:
            imageUrl = google_drive
        print(rawImageUrl)
        if imageUrl == '':

            data = {'success': False, 'message': None}
            return JsonResponse(data)
        order = Order.get_order(orderid)
        scan, created = ScanTable.objects.get_or_create(order=order)
        if order.product_type == 0 or order.product_type == 1:
            order.status = 1
            order.save()

        if rawImageUrl:
            scan.scanImageRaw = Photo.objects.get(title=imageUrl).file
            scan.scanImageUrl = settings.BASE_URL + imageUrl
        else:
            scan.scanImageUrl = imageUrl

        scan.save()
        data = {'success': True, 'message': 'scan has uploaded successfully'}

    return JsonResponse(data)
Exemplo n.º 25
0
 def handle(self, *args, **options):
     """Create orders and order items"""
     start_datetime = "01.01.2018 09:00"
     orders_count = options['orders_count'][0]
     Order.objects.bulk_create([
         Order(
             number=ind + 1,
             created_date=datetime.strptime(start_datetime, "%m.%d.%Y %H:%M") + timedelta(hours=ind)
         )
         for ind in range(orders_count)
     ])
     for order in Order.objects.all():
         OrderItem.objects.bulk_create([
             OrderItem(
                 order=order,
                 product_name=f"Товар-{randint(1, 100)}",
                 product_price=randint(100, 9999),
                 amount=randint(1, 10)
             )
             for i in range(randint(1, 5))
         ])
     self.stdout.write(self.style.SUCCESS(
         f"Successfully created {orders_count} orders"
     ))
Exemplo n.º 26
0
    def post(self, request):
        u_redirect = email_and_search(request, 'cart')
        if u_redirect is not None:
            return u_redirect

        request.session['_coupon'] = request.POST.get('coupon')

        post = request.POST
        user = request.user
        items = models.CartItem.objects.filter(user=user)

        for key, value in post.items():  # updating items in cart
            if key[:5] == 'clear':
                items.delete()

            if key[:6] == 'delete':
                item = Item.objects.get(name=key[7:])
                models.CartItem.objects.get(user=user, item=item).delete()

            if key[:6] == 'amount':
                item = Item.objects.get(name=key[7:])
                add_item = models.CartItem.objects.get(user=user, item=item)
                add_item.amount = value if int(value) <= 20 else 20

                add_item.save()

            if key[:4] == 'make':
                order = Order(user=user)
                order.save()
                for item in items:
                    order_item = OrderItem(item=item.item, amount=item.amount)
                    order_item.save()
                    order.items.add(order_item.id)
                    order.save()
                items.delete()
                return redirect('checkout')
        try:
            models.Coupon.objects.get(name=request.session.get('_coupon'))
            messages.success(request, 'Coupon applied')
        except models.Coupon.DoesNotExist:
            pass

        return redirect('cart')
Exemplo n.º 27
0
def html(request):
    id = request.GET.get('id', '')
    n = int(request.GET.get('n', '1'))
    address = request.GET.get('address', '1 Memorial Drive Cambridge MA 02142')
    debug = request.GET.get('debug', '')
    account = get_object_or_404(Account, pk=id)
    order = Order()
    try:
        response = order.get_order(account, n, debug, address)
    except:
        try:
            response = order.get_order(account, n, debug, address)
        except:
            try:
                response = order.get_order(account, n, debug, address)
            except:
                raise Http404

    order.save()
    response['order']['id'] = order.id

    menu_name = []
    for item in response['food']:
        if item['menu_name'] not in menu_name:
            menu_name.append(item['menu_name'])

    ordered_food = []
    for menu in menu_name:
        for item in response['food']:
            if item['menu_name'] == menu:
                item['extra_count'] = len(item['extras'])
                ordered_food.append(item)
    response['ordered_food'] = {}
    response['ordered_food']['menu'] = menu_name
    response['ordered_food']['food'] = ordered_food

    return render(request, 'index.html', response)
Exemplo n.º 28
0
    def setUp(self):
        """ Create a user object to be used by the tests """
        time_mock = datetime.datetime(2017, 4, 10, 12, 00, tzinfo=pytz.utc)
        with mock.patch('django.utils.timezone.now') as mock_time:
            mock_time.return_value = time_mock
            self.user = CustomUser(id=111, email='*****@*****.**', password='******', first_name='fname',
                                   middle_name='mname',
                                   last_name='lname')
            self.user.save()
            self.user_free = CustomUser(id=222, email='*****@*****.**', password='******', first_name='2fname',
                                        middle_name='2mname',
                                        last_name='2lname')
            self.user_free.save()

            self.author1 = Author(id=101, name="author1", surname="s1", patronymic="p1")
            self.author1.save()

            self.author2 = Author(id=102, name="author2", surname="s2", patronymic="p2")
            self.author2.save()

            self.book1 = Book(id=101, name="book1", description="description1", count=1)
            self.book1.save()
            self.book1.authors.add(self.author1)
            self.book1.save()

            self.book2 = Book(id=102, name="book2", description="description2")
            self.book2.save()
            self.book2.authors.add(self.author2)
            self.book2.save()

            self.book3 = Book(id=103, name="book3", description="description3")
            self.book3.save()
            self.book3.authors.add(self.author1)
            self.book3.authors.add(self.author2)
            self.book3.save()

            self.order1 = Order(id=101, user=self.user, book=self.book1, plated_end_at=TEST_DATE)
            self.order1.save()
            self.order2 = Order(id=102, user=self.user, book=self.book2, plated_end_at=TEST_DATE)
            self.order2.save()
            self.order3 = Order(id=103, user=self.user, book=self.book3, end_at=TEST_DATE_END, plated_end_at=TEST_DATE)
            self.order3.save()
Exemplo n.º 29
0
def cart_confirm_form(request: HttpRequest):
    """Confirm an order form"""
    user = request.user
    if user.is_authenticated:
        address_id = request.POST.get('address')
        payment_method_id = request.POST.get('payment_method')

        try:
            cart = ShoppingCart.objects.get(owner=user)
            address = DeliveryAddress.objects.get(id=address_id)
            payment_method = PaymentMethod.objects.get(id=payment_method_id)
        except ShoppingCart.DoesNotExist:
            # If user hasn't shopping cart, he cannot make order
            return HttpResponseRedirect(reverse('index_page'))
        except DeliveryAddress.DoesNotExist:
            # Bad address
            return cart_page(request, True)
        except PaymentMethod.DoesNotExist:
            # Bad payment_method
            return cart_page(request, True)

        new_order = Order(
            customer=user,
            address=address,
            status=0,  # «new»
            payment_method=payment_method,
            creation_datetime=datetime.now(),
        )
        new_order.save()

        # Add products from cart to order
        for product_in_cart in cart.products.all():
            new_order.products.add(product_in_cart)
        new_order.save()

        # Clear cart by redirected
        return HttpResponseRedirect(reverse('cart_clean_form'))
    else:
        return HttpResponseRedirect(reverse('index_page'))
Exemplo n.º 30
0
def place_order(request):
    cart_proxy = CartProxy(request)
    cart_grouped = cart_proxy.get_formatted_cart()
    customer, contact = __get_customer_contact(request)
    total_amount = cart_proxy.calculate_total()
    if ('order_group' in request.session):
        # delete the other that existed in memory and has not been paid
        try:
            previous_order_group = OrderGroup.objects.get(
                pk=request.session['order_group'])
            if previous_order_group.get_payment_status() not in [
                    'PAYMENT RECEIVED',
            ]:
                previous_order_group.delete()
        except OrderGroup.DoesNotExist:
            logging.warning('Order group {} does not exist'.format(
                request.session['order_group']))
            pass
    # create order group
    order_group = OrderGroup(customer=customer,
                             contact=contact,
                             total_amount=total_amount)
    order_group.save()
    request.session['order_group'] = order_group.pk
    for vendor, cart in cart_grouped.items():
        order = Order(order_group=order_group, vendor=vendor)
        order.save()
        order.place_order(
            cart['items'],
            {
                # shipping details
                'type': cart['shipping'].name,
                'cost': cart['shipping'].price,
                'details': request.POST.get('shipping_details', False),
                'status': 'just created',
                'contact': contact
            })
    # redirect to
    return process_payment(request, order_group)
Exemplo n.º 31
0
def order_mobile_redirect(request):
	order_id=request.GET.get('order_id')
	cart_id=request.GET.get('cart_id')
	cart_items=Cart.objects.filter(cart_id=cart_id)
	for item in cart_items:
		item.order_flag=True
		item.save()
	item_price=request.GET.get('item_price')
	delivery_price=request.GET.get('delivery_price')
	total_price=request.GET.get('total_price')
	pay_price=request.GET.get('pay_price')
	point_price=request.GET.get('point_price')
	coupon_price=request.GET.get('coupon_price')
	point_made=request.GET.get('point_made')
	name=request.GET.get('name')
	email=request.GET.get('email')
	postcode=request.GET.get('postcode')
	address=request.GET.get('address')
	address_detail=request.GET.get('address_detail')
	phone=request.GET.get('phone')
	postscript=request.GET.get('postscript')
	mypage_check=request.GET.get('mypage_check')
	username=request.GET.get('username')
	#아임포트 정보 가져오기
	imp_uid=request.GET.get('imp_uid')
	imp_success=request.GET.get('imp_success')

	#토큰 얻기
	data = urllib.parse.urlencode({"imp_key":IMP_KEY,"imp_secret":IMP_SECRET})
	data = data.encode('UTF-8')
	f = urllib.request.urlopen('https://api.iamport.kr/users/getToken/',data)
	result = f.read().decode('UTF-8')
	result_json=json.loads(result)
	access_token=result_json['response']['access_token']

	#imp_uid로 요청
	url = 'https://api.iamport.kr/payments/'+imp_uid
	request2 = urllib.request.Request(url)
	request2.add_header("X-ImpTokenHeader",access_token)
	response = urllib.request.urlopen(request2)
	result2 = response.read().decode('UTF-8')
	result2_json=json.loads(result2)
	#결과 받기
	pay_amount = result2_json['response']['amount']#int로 들어옴
	pay_status = result2_json['response']['status']
	pay_method = result2_json['response']['pay_method']

	if pay_status == 'paid' and str(pay_amount) == pay_price:
		message='주문이 완료되었습니다. 주문번호는'+order_id+'입니다.'
	elif pay_status == 'ready' and pay_method == 'vbank':
		message='주문이 완료되었습니다. 주문번호는'+order_id+'입니다.'
	else:
		message='주문이 실패하였습니다. 주문번호 : '+order_id
		return render(request, "order/order_complete.html", {
			'order_id':order_id,
			'brands':get_brands(),
		})
	status='결제'
#회원, 비회원 구분
	try:
		user = User.objects.get(username=username)
		new_order = Order(
			order_id=order_id,
			cart_id=cart_id,
			user=user,
			item_price=item_price,
			delivery_price=delivery_price,
			total_price=total_price,
			pay_price=pay_price,
			point_price=point_price,
			coupon_price=coupon_price,
			point_made=point_made,
			name=name,
			email=email,
			postcode=postcode,
			address=address,
			address_detail=address_detail,
			phone=phone,
			postscript=postscript,
			status=status,
			)
		#포인트처리
		changed_point = int(user.profile.point)-int(point_price)+int(point_made)
		user.profile.point = str(changed_point)
		point_history = PointHistory(
			user = user,
			kindof = '구매',
			record = int(total_price),
			amount = int(point_made),
			content = '주문번호 ' + order_id + ' 구매로 발생',
			)
		point_history.save()
		#쿠폰처리
		if not (selected_coupon_id == 'nocoupon' ):
			renew_coupon = Coupon.objects.get(coupon_id=selected_coupon_id)
			renew_coupon.used = True
			renew_coupon.save()
		if(mypage_check):
			user.first_name=name
			user.save()
			user.email=email
			user.profile.postcode=postcode
			user.profile.address=address
			user.profile.address_detail=address_detail
			user.profile.phone=phone
		user.profile.save()
	except:
		new_order = Order(
			order_id=order_id,
			cart_id=cart_id,
			item_price=item_price,
			delivery_price=delivery_price,
			total_price=total_price,
			pay_price=pay_price,
			point_price=point_price,
			coupon_price=coupon_price,
			name=name,
			email=email,
			postcode=postcode,
			address=address,
			address_detail=address_detail,
			phone=phone,
			postscript=postscript,
			status=status,
			)
	new_order.save()
	return render(request, "order/order_complete.html", {
		'order_id':order_id,
		'brands':get_brands(),
	})
Exemplo n.º 32
0
    def test_create_negative_limit_book(self):
        """ Positive Test of the CustomUser.create method TEST_DATE_END"""

        order = Order.create(self.user_free, self.book1, TEST_DATE_END)
        self.assertIsNone(order)
Exemplo n.º 33
0
 def test_get_not_returned_books(self):
     """ Positive Test of the CustomUser.create method TEST_DATE_END"""
     orders = Order.get_not_returned_books()
     self.assertListEqual(orders, [self.order1, self.order2])
Exemplo n.º 34
0
 def test_delete_by_id_positive(self):
     """ Test of the CustomUser.delete_by_id() method """
     self.assertTrue(Order.delete_by_id(103))
     self.assertRaises(Order.DoesNotExist, Order.objects.get, pk=103)
     self.assertEqual(self.book3, Book.objects.get(id=103))
     self.assertEqual(self.user, CustomUser.objects.get(id=111))
Exemplo n.º 35
0
class TestOrderModel(TestCase):
    """Class for CustomUser Model test"""
    def setUp(self):
        """ Create a user object to be used by the tests """
        time_mock = datetime.datetime(2017, 4, 10, 12, 00, tzinfo=pytz.utc)
        with mock.patch('django.utils.timezone.now') as mock_time:
            mock_time.return_value = time_mock
            self.user = CustomUser(id=111,
                                   email='*****@*****.**',
                                   password='******',
                                   first_name='fname',
                                   middle_name='mname',
                                   last_name='lname')
            self.user.save()
            self.user_free = CustomUser(id=222,
                                        email='*****@*****.**',
                                        password='******',
                                        first_name='2fname',
                                        middle_name='2mname',
                                        last_name='2lname')
            self.user_free.save()

            self.author1 = Author(id=101,
                                  name="author1",
                                  surname="s1",
                                  patronymic="p1")
            self.author1.save()

            self.author2 = Author(id=102,
                                  name="author2",
                                  surname="s2",
                                  patronymic="p2")
            self.author2.save()

            self.book1 = Book(id=101,
                              name="book1",
                              description="description1",
                              count=1)
            self.book1.save()
            self.book1.authors.add(self.author1)
            self.book1.save()

            self.book2 = Book(id=102, name="book2", description="description2")
            self.book2.save()
            self.book2.authors.add(self.author2)
            self.book2.save()

            self.book3 = Book(id=103, name="book3", description="description3")
            self.book3.save()
            self.book3.authors.add(self.author1)
            self.book3.authors.add(self.author2)
            self.book3.save()

            self.order1 = Order(id=101,
                                user=self.user,
                                book=self.book1,
                                plated_end_at=TEST_DATE)
            self.order1.save()
            self.order2 = Order(id=102,
                                user=self.user,
                                book=self.book2,
                                plated_end_at=TEST_DATE)
            self.order2.save()
            self.order3 = Order(id=103,
                                user=self.user,
                                book=self.book3,
                                end_at=TEST_DATE_END,
                                plated_end_at=TEST_DATE)
            self.order3.save()

    def test__str__end_at_is_None(self):
        """Test of the CustomUser.__str__() method"""
        order_returned = str(Order.objects.get(id=101))
        order_to_expect = "'id': 101, " \
                          "'user': CustomUser(id=111), " \
                          "'book': Book(id=101), " \
                          "'created_at': '2017-04-10 12:00:00+00:00', " \
                          "'end_at': None, " \
                          "'plated_end_at': '2017-04-10 12:00:00+00:00'"

        self.assertEqual(order_returned, order_to_expect)

    def test__str__end_at_is_not_None(self):
        """Test of the CustomUser.__str__() method"""
        order = str(Order.objects.get(id=103))
        order_to_expect = "'id': 103, " \
                          "'user': CustomUser(id=111), " \
                          "'book': Book(id=103), " \
                          "'created_at': '2017-04-10 12:00:00+00:00', " \
                          "'end_at': '2017-04-25 12:00:00+00:00', " \
                          "'plated_end_at': '2017-04-10 12:00:00+00:00'"

        self.assertEqual(order, order_to_expect)

    def test__repr__(self):
        """Test of the CustomUser.__repr__() method"""
        user_returned = repr(Order.objects.get(id=102))
        user_to_expect = "Order(id=102)"

        self.assertEqual(user_returned, user_to_expect)

    def test_get_by_id_positive(self):
        """Positive test of the CustomUser.get_by_id() method"""
        order = Order.get_by_id(101)
        self.assertEqual(order.id, 101)
        self.assertEqual(order.user, self.user)
        self.assertEqual(order.book, self.book1)
        self.assertEqual(order.created_at, TEST_DATE)
        self.assertEqual(order.end_at, None)
        self.assertEqual(order.plated_end_at, TEST_DATE)

    def test_get_by_id_negative(self):
        """Negative test of the CustomUser.get_by_id() method"""
        order = Order.get_by_id(55)
        self.assertIsNone(order)

    def test_delete_by_id_positive(self):
        """ Test of the CustomUser.delete_by_id() method """
        self.assertTrue(Order.delete_by_id(103))
        self.assertRaises(Order.DoesNotExist, Order.objects.get, pk=103)
        self.assertEqual(self.book3, Book.objects.get(id=103))
        self.assertEqual(self.user, CustomUser.objects.get(id=111))

    def test_delete_by_id_negative(self):
        """ Test of the CustomUser.delete_by_id() method """
        self.assertFalse(Order.delete_by_id(999))

    def test_create_positive(self):
        """ Positive Test of the CustomUser.create method """
        time_mock = datetime.datetime(2017, 4, 10, 12, 00, tzinfo=pytz.utc)
        with mock.patch('django.utils.timezone.now') as mock_time:
            mock_time.return_value = time_mock
            order = Order.create(self.user_free, self.book2, TEST_DATE_END)
            self.assertIsInstance(order, Order)
            self.assertEqual(order.user, self.user_free)
            self.assertEqual(order.book, self.book2)
            self.assertEqual(order.created_at, TEST_DATE)
            self.assertIsNone(order.end_at)
            self.assertEqual(order.plated_end_at, TEST_DATE_END)

    def test_create_negative_not_saved_user(self):
        """ Positive Test of the CustomUser.create method TEST_DATE_END"""
        user = CustomUser()
        order = Order.create(user, self.book2, TEST_DATE_END)
        self.assertIsNone(order)

    def test_create_negative_limit_book(self):
        """ Positive Test of the CustomUser.create method TEST_DATE_END"""

        order = Order.create(self.user_free, self.book1, TEST_DATE_END)
        self.assertIsNone(order)

    def test_get_all(self):
        """ Positive Test of the CustomUser.create method TEST_DATE_END"""
        orders = Order.get_all()
        self.assertListEqual(orders, [self.order1, self.order2, self.order3])

    def test_get_not_returned_books(self):
        """ Positive Test of the CustomUser.create method TEST_DATE_END"""
        orders = Order.get_not_returned_books()
        self.assertListEqual(orders, [self.order1, self.order2])

    def test_update_plated_end_at(self):
        order = Order.objects.get(id=101)
        new_date = TEST_DATE_END + datetime.timedelta(days=4)
        order.update(plated_end_at=new_date)

        order = Order.objects.get(id=101)
        self.assertEqual(order.id, 101)
        self.assertEqual(order.user, self.user)
        self.assertEqual(order.book, self.book1)
        self.assertEqual(order.created_at, TEST_DATE)
        self.assertEqual(order.end_at, None)
        self.assertEqual(order.plated_end_at, new_date)

    def test_update_end_at(self):
        order = Order.objects.get(id=101)
        new_date = TEST_DATE_END + datetime.timedelta(days=4)
        order.update(end_at=new_date)

        order = Order.objects.get(id=101)
        self.assertEqual(order.id, 101)
        self.assertEqual(order.user, self.user)
        self.assertEqual(order.book, self.book1)
        self.assertEqual(order.created_at, TEST_DATE)
        self.assertEqual(order.end_at, new_date)
        self.assertEqual(order.plated_end_at, TEST_DATE)
Exemplo n.º 36
0
def buy(request, id):
    # print(request.path_info.split("/buy/")[0]+"/buy/",type(request.path_info),'------------')

    ids = request.GET['id_str']
    id_li = ids.split(" ")
    account_id = request.session.get('user_id', None)
    account = get_object_or_404(Account, id=account_id)
    schedule = get_object_or_404(Schedule, id=id)
    seats = [get_object_or_404(Seat, id=int(seat_id)) for seat_id in id_li]

    if request.method == 'POST':

        with transaction.atomic():
            save_id = transaction.savepoint()

            order = Order()
            money = len(seats) * schedule.ticket_money
            order.money = money
            order.schedule = schedule
            order.account = account

            order.save()

            for seat in seats:
                if seat.order_set.all():
                    if seat.order_set.filter(schedule=schedule):
                        # print('=-=---===========================')
                        transaction.savepoint_rollback(save_id)
                        # raise
                        # return JsonResponse({'res':5, 'errmsg':'错误'})
                        messages.info(request, "您选的座位已被购买,请重选!")
                        return redirect(
                            reverse('ticket_seat', args=(schedule.id, )))

                # seat.status = True
                seat.save()

                schedule.ticket_counts -= 1
                schedule.save()
                order.seats.add(seat)
            order.save()
            schedule.save()

            # ticket = Ticket(schedule=schedule, seat=seat, order=order)
            # ticket.save()
            transaction.savepoint_commit(save_id)

            return render(request, 'ticket/ok.html')

    # order_time = (datetime.datetime.now() + datetime.timedelta(minutes=1)).replace(tzinfo=pytz.timezone('UTC'))
    # print(order_time,'-----')
    # request.session['order_time'] = datetime.datetime.now()
    # request.session.set_expiry(60)
    return render(
        request,
        'ticket/order.html',
        context={
            'schedule': schedule,
            'seats': seats,
            'ids': ids
            # 'order_time':order_time
        })
Exemplo n.º 37
0
 def test_sub_total(self):
     order_id = Order(id=1, total=9.99)
     order_id.save()
     sub_total = OrderItem(quantity=2, price=9.99, order=order_id)
     sub_total.save()
     self.assertEqual(sub_total.quantity * sub_total.price, 19.98)
Exemplo n.º 38
0
def buyProduct(request, product_id):
    amount = request.POST.get('amount', 1)

    try:
        product = Product.objects.get(id=product_id)
        order = Order()
        order.client = request.META["REMOTE_ADDR"]
        order.details = "is buying the product " + product.name + " in MINITRADE"
        order.total = product.price * int(amount)
        order.status = "created"
        order.save()

        orderProduct = OrderProduct()
        orderProduct.product = product
        orderProduct.order = order
        orderProduct.amount = amount
        orderProduct.total = product.price * int(amount)
        orderProduct.save()

        callback_url = "https://{0}/finish_buy/{1}/".format(request.get_host(), order.id)
        response = createPayRequest(order, callback_url)
        order.token = response['token']
        order.status = response['status']
        order.save()

        return HttpResponse(json.dumps({
            "url": response['url'] 
        }), status=200)
    except Exception as e:
        # import traceback
        # traceback.print_exc()
        return HttpResponse(json.dumps({
            "error": str(e),
            "message": "The transaction could not be created!"
        }), status=500)
Exemplo n.º 39
0
def orderproduct(request):
    category = Category.objects.all()
    setting = Setting.objects.get(pk=1)
    current_user = request.user
    shop_cart = ShopCart.objects.filter(user_id=current_user.id)
    total = 0
    for rs in shop_cart:
        total += rs.product.price * rs.quantity

    if request.method == 'POST':
        form = OrderForm(request.POST)
        if form.is_valid():
            data = Order()
            data.first_name = form.cleaned_data['first_name']
            data.last_name = form.cleaned_data['last_name']
            data.address = form.cleaned_data['address']
            data.city = form.cleaned_data['city']
            data.phone = form.cleaned_data['phone']
            data.user_id = current_user.id
            data.total = total
            data.ip = request.META.get('REMOTE_ADDR')
            ordercode = get_random_string(5).upper()
            data.code = ordercode
            data.save()

            shop_cart = ShopCart.objects.filter(user_id=current_user.id)
            for rs in shop_cart:
                detail = OrderProduct()
                detail.order_id = data.id
                detail.product_id = rs.product_id
                detail.user_id = current_user.id
                detail.quantity = rs.quantity
                product = Product.objects.get(id=rs.product_id)
                product.amount -= rs.quantity
                product.save()
                detail.price = rs.product.price
                detail.amount = rs.amount
                detail.save()
            ShopCart.objects.filter(user_id=current_user.id).delete()
            request.session['cart_items'] = 0
            messages.success(request, "Siparisiniz tamamlanmıştır. Tesekkürler..")
            return render(request, 'Order_Completed.html', {'ordercode': ordercode, 'category': category})
        else:
            messages.warning(request, form.errors)
            return HttpResponseRedirect("/order/orderproduct")
    form = OrderForm()
    profile = UserProfile.objects.get(user_id=current_user.id)
    context = {
        'setting': setting,
        'shop_cart': shop_cart,
        'category': category,
        'total': total,
        'form': form,
        'profile': profile,
    }
    return render(request, 'Order_Form.html', context)
Exemplo n.º 40
0
def create_order_from_direct_paypal(nvp_dict):
    """
    Create order in DB with ordered items
    """
    #create order
    #create items
    #return order object
    """
    <QueryDict:
    {u'l_paymentrequest_0_number0': [4],
     u's_countrycode': [u'AX'],
     u'b_state': [u'sdf'],
     u'card_first_name': [u'sdf'],
     u's_last_name': [u'sdf'],
     u's_street': [u'sdf'],
     u'acct': [u'4239530610456015'],
     u'l_paymentrequest_0_amt0': [32],
     u'l_paymentrequest_0_name0': [u'Raw Edge Design Letters Print Black Polyester VEST'],
     u's_city': [u'sdf'],
     u's_state': [u'sdf'],
     u'version': [u'116.0'],
     u's_countryname': [u'Aland Islands'],
     u'build': [u'16770825'],
     u'cvv2': [u'123'],
     u'b_street': [u'dd'],
     u'email': [u'*****@*****.**'],
     u'l_paymentrequest_0_qty0': [2],
     u'b_countrycode': [u'AU'],
     u'b_countryname': [u'Afghanistan'],
     u'timestamp': [u'2015-06-14T10:22:07Z'],
     u'currencycode': [u'USD'],
     u'card_last_name': [u'sdf'],
     u's_zip': [u'dsf'],
     u'paymentrequest_0_amt': [64.0],
     u'phone': [u'sdf'],
     u'b_country': [u'1'],
     u'cardyear': [u'2020'],
     u'transactionid': [u'06M899763J781091D'],
     u'amt': [u'64.00'],
     u's_first_name': [u'sdf'],
     u'cvv2match': [u'M'],
     u'cardmonth': [u'05'],
     u'ack': [u'Success'],
     u'b_city': [u'sdf'],
     u'creditcardtype': [u'visa'],
     u'b_last_name': [u'dddddd'],
     u'b_zip': [u'sdf'],
     u'avscode': [u'X'],
     u'b_first_name': [u'sads'],
     u'correlationid': [u'dba9b733e476']}>
    """

    order = Order()
    order.email = nvp_dict.get('email')
    order.phone = nvp_dict.get('phone', "")

    order.b_first_name = nvp_dict.get('b_first_name')
    order.b_last_name = nvp_dict.get('b_last_name')
    order.b_address_countryname = nvp_dict.get('b_countryname')
    order.b_address_countrycode = nvp_dict.get('b_countrycode')
    order.b_address_zip = nvp_dict.get('b_zip')
    order.b_address_state = nvp_dict.get('b_state')
    order.b_address_city = nvp_dict.get('b_city')
    order.b_address_street = nvp_dict.get('b_street')

    order.s_first_name = nvp_dict.get('s_first_name', "")
    order.s_last_name = nvp_dict.get('s_last_name', "")
    order.s_address_countryname = nvp_dict.get('s_countryname', "")
    order.s_address_countrycode = nvp_dict.get('s_countrycode', "")
    order.s_address_zip = nvp_dict.get('s_zip', "")
    order.s_address_state = nvp_dict.get('s_state', "")
    order.s_address_city = nvp_dict.get('s_city', "")
    order.s_address_street = nvp_dict.get('s_street', "")

    order.status = order.NEW_ORDER
    order.paypal_transaction_id = nvp_dict.get('transactionid')
    order.save()

    item_ids = [(key, value) for key, value in nvp_dict.iteritems()
                if key.startswith("l_paymentrequest_0_number")]

    #print item_ids

    for index, i in enumerate(item_ids):
        product = Prize.objects.get(pk=i[1])

        order_item = OrderItem()
        order_item.order_id = order.id
        order_item.product = product
        order_item.number = product.number
        order_item.amount = nvp_dict.get('l_paymentrequest_0_amt' + str(index))
        order_item.quantity = nvp_dict.get('l_paymentrequest_0_qty' +
                                           str(index))
        order_item.save()

    return order
Exemplo n.º 41
0
def orderproduct(request):
    category = Category.objects.all()
    current_user = request.user
    schopcart = ShopCart.objects.filter(user_id=current_user.id)
    total = 0
    for rs in schopcart:
        total += rs.product.price * rs.quantity

    if request.method == 'POST':  # if there is a post
        form = OrderForm(request.POST)
        # return HttpResponse(request.POST.items())
        if form.is_valid():
            # Send Credit card to bank,  If the bank responds ok, continue, if not, show the error
            # ..............

            data = Order()
            data.first_name = form.cleaned_data['first_name']  # get product quantity from form
            data.last_name = form.cleaned_data['last_name']
            data.address = form.cleaned_data['address']
            data.city = form.cleaned_data['city']
            data.phone = form.cleaned_data['phone']
            data.user_id = current_user.id
            data.total = total
            data.ip = request.META.get('REMOTE_ADDR')
            ordercode = get_random_string(5).upper()  # random cod
            data.code = ordercode
            data.save()  #

            schopcart = ShopCart.objects.filter(user_id=current_user.id)
            for rs in schopcart:
                detail = OrderProduct()
                detail.order_id = data.id  # Order Id
                detail.product_id = rs.product_id
                detail.user_id = current_user.id
                detail.quantity = rs.quantity
                detail.price = rs.product.price
                detail.amount = rs.amount
                detail.save()
                # ***Reduce quantity of sold product from Amount of Product
                product = Product.objects.get(id=rs.product_id)
                product.amount -= rs.quantity
                product.save()

            ShopCart.objects.filter(user_id=current_user.id).delete()  # Clear & Delete shopcart
            request.session['cart_items'] = 0
            messages.success(request, "Your Order has been completed. Thank you ")
            return render(request, 'Order_Completed.html', {'ordercode': ordercode, 'category': category})
        else:
            messages.warning(request, form.errors)
            return HttpResponseRedirect("/order/orderproduct")

    form = OrderForm()
    profile = UserProfile.objects.get(user_id=current_user.id)
    context = {'schopcart': schopcart,
               'category': category,
               'total': total,
               'form': form,
               'profile': profile,
               }
    return render(request, 'Order_Form.html', context)
Exemplo n.º 42
0
def create_order_from_express_paypal(nvp_dict):
    """
    Create order in DB with ordered items
    """
    #create order
    #create items
    #return order object

    order = Order()
    order.email = nvp_dict.get('email')
    order.b_first_name = nvp_dict.get('firstname')
    order.b_last_name = nvp_dict.get('lastname')

    order.b_address_countryname = nvp_dict.get('shiptocountryname')
    order.b_address_countrycode = nvp_dict.get('shiptocountrycode')
    order.b_address_zip = nvp_dict.get('shiptozip')
    order.b_address_state = nvp_dict.get('shiptostate')
    order.b_address_city = nvp_dict.get('shiptocity')
    order.b_address_street = nvp_dict.get('shiptostreet') \
                        + nvp_dict.get('shiptostreet2', "")
    order.shipping_address_flag = False

    order.status = order.NEW_ORDER
    order.paypal_transaction_id = nvp_dict.get('transactionid')
    order.save()

    item_ids = [(key, value) for key, value in nvp_dict.iteritems()
                if key.startswith("l_paymentrequest_0_number")]

    print item_ids

    for index, i in enumerate(item_ids):
        product = Prize.objects.get(pk=i[1])

        order_item = OrderItem()
        order_item.order_id = order.id
        order_item.product = product
        order_item.number = product.number
        order_item.amount = nvp_dict.get('l_paymentrequest_0_amt' + str(index))
        order_item.quantity = nvp_dict.get('l_paymentrequest_0_qty' +
                                           str(index))

        order_item.save()

    return order
Exemplo n.º 43
0
 def test_create_order(self):
     self.assertEqual(Order.objects.count(),0)
     order = Order(user = user,total_price=10000,supplier=supplier,takeout = 'Take Out',date = datetime.now)
     self.assertEqual(Order.objects.count(),1)
     self.assertEqual(order.total_price,10000)
Exemplo n.º 44
0
def order_update(request):
	order_id=request.POST.get('order_id')
	cart_id=request.POST.get('cart_id')
	cart_items=Cart.objects.filter(cart_id=cart_id)
	for item in cart_items:
		item.order_flag=True
		item.save()
	item_price=request.POST.get('item_price')
	delivery_price=request.POST.get('delivery_price')
	total_price=request.POST.get('total_price')
	pay_price=request.POST.get('pay_price')
	point_price=request.POST.get('point_price')
	coupon_price=request.POST.get('coupon_price')
	selected_coupon_id=request.POST.get('selected_coupon_id')
	point_made=request.POST.get('point_made')
	name=request.POST.get('name')
	email=request.POST.get('email')
	postcode=request.POST.get('postcode')
	address=request.POST.get('address')
	address_detail=request.POST.get('address_detail')
	phone=request.POST.get('phone')
	postscript=request.POST.get('postscript')
	mypage_check=request.POST.get('mypage_check',False)
	status='결제'
	message='주문이 완료되었습니다. 주문번호는'+order_id+'입니다.'
	if request.user.is_authenticated():
		new_order = Order(
			order_id=order_id,
			cart_id=cart_id,
			user=request.user,
			item_price=item_price,
			delivery_price=delivery_price,
			total_price=total_price,
			pay_price=pay_price,
			point_price=point_price,
			coupon_price=coupon_price,
			point_made=point_made,
			name=name,
			email=email,
			postcode=postcode,
			address=address,
			address_detail=address_detail,
			phone=phone,
			postscript=postscript,
			status=status,
			)
		user=request.user
		#포인트 처리
		changed_point = int(user.profile.point)-int(point_price)+int(point_made)
		user.profile.point = str(changed_point)
		point_history = PointHistory(
			user = user,
			kindof = '구매',
			record = int(total_price),
			amount = int(point_made),
			content = '주문번호 ' + order_id + ' 구매로 발생',
			)
		point_history.save()
		#쿠폰처리
		if not (selected_coupon_id == 'nocoupon' ):
			renew_coupon = Coupon.objects.get(coupon_id=selected_coupon_id)
			renew_coupon.used = True
			renew_coupon.save()
		if(mypage_check):
			user.first_name=name
			user.save()
			user.email=email
			user.profile.postcode=postcode
			user.profile.address=address
			user.profile.address_detail=address_detail
			user.profile.phone=phone
		user.profile.save()
	else:
		new_order = Order(
			order_id=order_id,
			cart_id=cart_id,
			item_price=item_price,
			delivery_price=delivery_price,
			total_price=total_price,
			pay_price=pay_price,
			point_price=point_price,
			coupon_price=coupon_price,
			name=name,
			email=email,
			postcode=postcode,
			address=address,
			address_detail=address_detail,
			phone=phone,
			postscript=postscript,
			status=status,
			)
	new_order.save()
	return render(request, "order/order_complete.html", {
		'order_id':order_id,
		'new_order':new_order,
		'cart_items':cart_items,
		'brands':get_brands(),
	})
Exemplo n.º 45
0
def orderproductviews(request):
    category = Category.objects.all()
    current_user = request.user
    shopcart = ShopCart.objects.filter(user_id=current_user.id)
    total = 0
    for rs in shopcart:
        total += rs.product.discount_price * rs.quantity

    if request.method == 'POST':
        form = OrderForm(request.POST)

        if form.is_valid():
            data = Order()
            data.first_name = form.cleaned_data['first_name']
            data.last_name = form.cleaned_data['last_name']
            data.phone = form.cleaned_data['phone']
            data.region = form.cleaned_data['region']
            data.district = form.cleaned_data['district']
            data.street_address = form.cleaned_data['street_address']
            data.apartment_address = form.cleaned_data['apartment_address']
            data.user_id = current_user.id
            data.total = total
            data.ip = request.META.get('REMOTE_ADDR')
            ordercode = get_random_string(5).upper()
            data.code = ordercode
            data.save()

            shopcart = ShopCart.objects.filter(user_id=current_user.id)
            for rs in shopcart:
                detail = OrderProduct()
                detail.order_id = data.id
                detail.product_id = rs.product_id
                detail.user_id = current_user.id
                detail.quantity = rs.quantity
                detail.color = rs.color
                detail.size = rs.size
                detail.price = rs.product.price
                detail.save()

            ShopCart.objects.filter(user_id=current_user.id).delete()
            request.session['cart_items'] = 0
            messages.success(request, "Your Oder has been completed. Thank you")
            context = {'category': category,
                       'ordercode': ordercode
                       }
            return render(request, 'order_completed.html', context)
            #return redirect('/order/payment/')
        else:
            messages.warning(request, form.errors)
            return HttpResponseRedirect("/order/orderproduct/")

    form = OrderForm()
    profile = UserProfile.objects.get(user_id=current_user.id)
    context = {'shopcart': shopcart,
               'category': category,
               'total': total,
               'form': form,
               'profile': profile
               }
    return render(request, 'check-out.html', context)
Exemplo n.º 46
0
def shop_cart_checkout(request):
    current_user = request.user
    shopcart = ShopCart.objects.all().filter(user_id=current_user.id)
    carttotal = 0
    for rs in shopcart:
        carttotal += rs.quantity * rs.product.price

    if request.method == 'POST':
        data = Order()
        data.name = request.POST['name']
        data.surname = request.POST['surname']
        data.address = request.POST['address']
        data.city = request.POST['city']
        data.phone = request.POST['phone']
        data.user_id = current_user.id
        data.total = carttotal
        data.save()

        for rs in shopcart:
            detail = OrderDetail()
            detail.order_id = data.id
            detail.product_id = rs.product_id
            detail.user_id = current_user.id
            detail.quantity = rs.quantity
            detail.price = rs.product.price
            detail.total = rs.amount
            detail.save()

        ShopCart.objects.filter(user_id=current_user.id).delete()
        request.session['cart_items'] = 0
        return HttpResponseRedirect("/order")

    context = {
        'page': 'checkout',
        'shopcart': shopcart,
        'carttotal': carttotal,
    }
    return render(request, 'shop_cart_checkout.html', context)
Exemplo n.º 47
0
 def create_order(self, user_id: int, total_price: float) -> Order:
     user = User.objects.get(id=user_id)
     order = Order(user=user, total_price=total_price)
     return self.__command_manager.execute(
         OrderCommand.order_service(self.__create_order_service, order))
Exemplo n.º 48
0
def orderproduct(request):
    category = Category.objects.all()
    current_user = request.user
    shopcart = ShopCart.objects.filter(user_id=current_user.id)
    profilepro = ProfilePro.objects.filter(user_id=current_user.id)
    total = 0
    for rs in shopcart:
        if rs.product.variant == 'None':
            total += rs.quantity * (rs.product.price-(rs.product.price*(rs.product.remise/100)))
        else:
            total += rs.variant.price * rs.quantity

    if request.method == 'POST':
        form = OrderForm(request.POST)
        if form.is_valid():

            # Send Credit card information to bank and get result
            # If payment accepted continue else send payment error to checkout page

            data=Order()
            data.note = form.cleaned_data['note']
            data.user_id = current_user.id
            data.total = total
            data.ip = request.META.get('REMOTE_ADDR')
            ordercode = get_random_string(5).upper()
            data.code = ordercode
            data.save()

            # Save Shopcart items to Order detail items
            shopcart = ShopCart.objects.filter(user_id=current_user.id)
            for rs in shopcart:
                detail = OrderProduct()
                detail.order_id     = data.id # Order Id
                detail.compte = profilepro.compte  # Order Id
                detail.product_id   = rs.product_id
                detail.user_id      = current_user.id
                detail.quantity     = rs.quantity
                if rs.product.variant == 'None':
                    detail.price        = rs.product.price
                else:
                    detail.price = rs.variant.price
                detail.variant_id        = rs.variant_id
                detail.remise = rs.product.remise
                detail.amount = rs.amount
                detail.order_amount = data.total
                detail.note = data.note
                detail.save()
                #  Reduce product Amount  (quantity)

                if rs.product.variant=='None':
                    product = Product.objects.get(id=rs.product_id)
                    product.amount -= rs.quantity
                    product.save()
                else:
                    variant = Variants.objects.get(id=rs.product_id)
                    variant.quantity -= rs.quantity
                    variant.save()


            ShopCart.objects.filter(user_id=current_user.id).delete() # Clear & Delete shopcart
            request.session['cart_items']=0
            messages.success(request, "Your order has been completed. Thank You ")
            return render(request, 'Order_Completed.html',{'ordercode':ordercode, 'category':category})
        else:
            messages.warning(request, form.errors)
            return HttpResponseRedirect("/order/orderproduct")
    form = OrderForm()
    shopcart = ShopCart.objects.filter(user_id=current_user.id)
    profile = UserProfile.objects.get(user_id=current_user.id)
    context = {'shopcart': shopcart,
               'category': category,
               'total': total,
               'form': form,
               'profile': profile,
               'profilepro': profilepro,
               }
    return render(request, 'Order_Form.html', context)
Exemplo n.º 49
0
 def test_place_order(self):
     order = Order(total=20.00, emailAddress="*****@*****.**")
     order.save()
     self.assertEqual(order.total, 20.00)
     self.assertEqual(order.emailAddress, "*****@*****.**")
Exemplo n.º 50
0
def submit(request):
    # 输入
    person_rules = [
        ('name', 'person_name',           lambda v: (v if 2<=len(v)<=10 else None), '请填写正确的姓名'),
        ('mobile', 'person_phone',         lambda v: (v if utils.is_mobile(v) else None ), '请填写正确的手机号'),
        ('cert_type', 'credentials_type', lambda v: (int(v) if int(v) == 1 else None), '证件类型错误'),
        ('cert', 'credentials_no',        lambda v: (v if utils.checkIdcard(v)[0] else None), '请填写正确的证件号'),
        ('sex', 'person_sex',             lambda v: (v if v in ['f', 'm'] else None), '请选择性别'),
        ('birthday', 'person_birthday',   lambda v: (utils.date_strp(v)), '请填写正确的生日'),
    ]
    try:
        session_id = int(request.POST.get('session_id'))
        num_apply = int(request.POST.get('num_apply'))
        assert num_apply > 0
    except:
        raise errors.ApiError('订单有误')

    # 场次操作
    session = Session.objects.select_for_update().filter(id=session_id)
    if session:
        session = session[0]
    else:
        raise errors.ApiError('您报名的活动场次不存在')

    if session.start_dt <= datetime.date.today():
        raise errors.ApiError('您报名的活动场次已过期')

    #if session.event.places < session.num_apply + num_apply:
    #    raise errors.ApiError('该场次剩余名额为%d,名额不足' % session.event.places - session.num_apply)

    session.num_apply += num_apply
    session.save()

    # 表单信息获取校验
    persons = []
    for i in xrange(1, num_apply+1):
        p = {}
        for bname, fname, transf, errmsg in person_rules:
            try:
                p[bname] = transf( request.POST.get('%s_%d'%(fname, i), '').strip() )
                assert p[bname]
            except Exception as e:
                raise errors.ApiError(errmsg)

        persons.append(p)

    contacts_name = request.POST.get('contacts_name', '').strip()
    if not (2<=len(contacts_name) <=10) :
        raise errors.ApiError('请填写正确的性名')
    contacts_mobile = request.POST.get('contacts_mobile', '').strip()
    if not utils.is_mobile(contacts_mobile):
        raise errors.ApiError('请填写正确的手机号')
    comment = request.POST.get('postscript', '')

    # 装备操作
    equipments = session.event.equipments.select_for_update().all()
    equip_rent = {}
    for eqpmnt in equipments:
        rent_cnt = request.POST.get('equipment_%d' % eqpmnt.id, '0')
        rent_cnt = utils.parseInt(rent_cnt) or 0
        if rent_cnt < 0:
            raise errors.ApiError('订单有误')

        equip_rent[eqpmnt.id] = rent_cnt

        #if eqpmnt.storage < eqpmnt.num_out + rent_cnt:
        #    raise errors.ApiError('装备【%s】剩余数量为%d,数量不足' % (eqpmnt.name, eqpmnt.storage - eqpmnt.num_out))
        # eqpmnt.num_out += rent_cnt
        # eqpmnt.save()

    # 订单创建
    uid = request.session.get('uid')
    user = User.objects.get(id=uid)
    apply_fee = get_event_fee(session.event, persons)
    equipment_rent = get_equipment_rent(equipments, equip_rent)
    order_status = 3 if session.auto else 1
    order_status = 5 if session.num_apply > session.event.places else order_status

    order = Order(user = user,
                  session = session,
                  number = num_apply,
                  contact_name = contacts_name,
                  contact_mobile = contacts_mobile,
                  comment = comment,
                  apply_fee = apply_fee,
                  equipment_rent = equipment_rent,
                  total = apply_fee + equipment_rent,
                  status = order_status)

    order.save()

    for p in persons:
        ordermember = OrderMember(order = order,
                                  name = p['name'],
                                  mobile = p['mobile'],
                                  cert_type = p['cert_type'],
                                  cert = p['cert'],
                                  sex = p['sex'],
                                  birthday = p['birthday'])
        ordermember.save()

    for eqpmnt in equipments:
        if equip_rent[eqpmnt.id] > 0:
            orderequipment = OrderEquipment(order = order,
                                equipment = eqpmnt,
                                number = equip_rent[eqpmnt.id],
                                start_dt = session.start_dt,
                                end_dt = utils.date_add(session.start_dt, session.event.days),
            )
            orderequipment.save()

    # 保存常用联系人
    save_frequent_members(user, persons)

    if order_status == 3:
        return {'url': '/order/confirm/%d/' % order.id}
    else:
        return {'url': '/user/myorders/'}
Exemplo n.º 51
0
 def test_get_by_id_negative(self):
     """Negative test of the CustomUser.get_by_id() method"""
     order = Order.get_by_id(55)
     self.assertIsNone(order)
Exemplo n.º 52
0
def orderproduct(request):
    category = Category.objects.all()
    current_user = request.user
    shopcart = ShopCart.objects.filter(user_id=current_user.id)
    # profile = UserProfile.objects.get(user_id=current_user.id)
    total_quantity = 0
    total = 0
    for rs in shopcart:
        total += rs.product.price * rs.quantity
        total_quantity += rs.quantity
    # return HttpResponse(str(total))

    if request.method == 'POST':  # if there is a post
        form = OrderForm(request.POST)
        if form.is_valid():

            data = Order()
            data.first_name = form.cleaned_data['first_name']  # get product quantity from form
            data.last_name = form.cleaned_data['last_name']
            data.address = form.cleaned_data['address']
            data.city = form.cleaned_data['city']
            data.phone = form.cleaned_data['phone']
            data.user_id = current_user.id
            data.total = total
            data.total_quantity = total_quantity
            data.ip = request.META.get('REMOTE_ADDR')
            ordercode = get_random_string(10).upper()  # random code
            data.code = ordercode
            data.save()

            # Move Shopcart items to Order Product items
            shopcart = ShopCart.objects.filter(user_id=current_user.id)
            for rs in shopcart:
                detail = OrderProduct()
                detail.order_id = data.id  # Order id
                detail.product_id = rs.product_id
                detail.user_id = current_user.id
                detail.quantity = rs.quantity
                detail.price = rs.product.price
                detail.amount = rs.amount
                detail.save()
                # Reduce quantity of sold product from Amount of Product
                product = Product.objects.get(id=rs.product_id)
                product.amount -= rs.quantity
                product.save()

            ShopCart.objects.filter(user_id=current_user.id).delete()
            request.session['cart_items'] = 0
            messages.success(request, "Your Order Has Been Completed! Thank you!")
            return render(request, 'ordercomplete.html', {'ordercode': ordercode, 'category': category})
        else:
            messages.warning(request, form.errors)
            return HttpResponseRedirect("/order/orderproduct")

    form = OrderForm
    shopcart = ShopCart.objects.filter(user_id=current_user.id)
    profile = UserProfile.objects.get(user_id=current_user.id)
    context = {
        'shopcart': shopcart,
        'category': category,
        'total': total,
        'total_quantity': total_quantity,
        'profile': profile,
        'form': form,
    }

    return render(request, 'orderproduct.html', context)
Exemplo n.º 53
0
 def test_delete_by_id_negative(self):
     """ Test of the CustomUser.delete_by_id() method """
     self.assertFalse(Order.delete_by_id(999))
Exemplo n.º 54
0
def create_order_from_express_paypal(nvp_dict):
    """
    Create order in DB with ordered items
    """
    #create order
    #create items
    #return order object

    order = Order()
    order.email = nvp_dict.get('email')
    order.b_first_name = nvp_dict.get('firstname')
    order.b_last_name = nvp_dict.get('lastname')

    order.b_address_countryname = nvp_dict.get('shiptocountryname')
    order.b_address_countrycode = nvp_dict.get('shiptocountrycode')
    order.b_address_zip = nvp_dict.get('shiptozip')
    order.b_address_state = nvp_dict.get('shiptostate')
    order.b_address_city = nvp_dict.get('shiptocity')
    order.b_address_street = nvp_dict.get('shiptostreet') \
                        + nvp_dict.get('shiptostreet2', "")

    order.status = order.NEW_ORDER
    order.paypal_transaction_id = nvp_dict.get('transactionid')
    order.save()

    save_order_items(nvp_dict, order)

    return order
Exemplo n.º 55
0
 def test_create_negative_not_saved_user(self):
     """ Positive Test of the CustomUser.create method TEST_DATE_END"""
     user = CustomUser()
     order = Order.create(user, self.book2, TEST_DATE_END)
     self.assertIsNone(order)
Exemplo n.º 56
0
def create_order_from_direct_paypal(nvp_dict):
    """
    Create order in DB with ordered items
    """
    #create order
    #create items
    #return order object
    """
    <QueryDict:
    {u'l_paymentrequest_0_number0': [4],
     u's_countrycode': [u'AX'],
     u'b_state': [u'sdf'],
     u'card_first_name': [u'sdf'],
     u's_last_name': [u'sdf'],
     u's_street': [u'sdf'],
     u'acct': [u'4239530610456015'],
     u'l_paymentrequest_0_amt0': [32],
     u'l_paymentrequest_0_name0': [u'Raw Edge Design Letters Print Black Polyester VEST'],
     u's_city': [u'sdf'],
     u's_state': [u'sdf'],
     u'version': [u'116.0'],
     u's_countryname': [u'Aland Islands'],
     u'build': [u'16770825'],
     u'cvv2': [u'123'],
     u'b_street': [u'dd'],
     u'email': [u'*****@*****.**'],
     u'l_paymentrequest_0_qty0': [2],
     u'b_countrycode': [u'AU'],
     u'b_countryname': [u'Afghanistan'],
     u'timestamp': [u'2015-06-14T10:22:07Z'],
     u'currencycode': [u'USD'],
     u'card_last_name': [u'sdf'],
     u's_zip': [u'dsf'],
     u'paymentrequest_0_amt': [64.0],
     u'phone': [u'sdf'],
     u'b_country': [u'1'],
     u'cardyear': [u'2020'],
     u'transactionid': [u'06M899763J781091D'],
     u'amt': [u'64.00'],
     u's_first_name': [u'sdf'],
     u'cvv2match': [u'M'],
     u'cardmonth': [u'05'],
     u'ack': [u'Success'],
     u'b_city': [u'sdf'],
     u'creditcardtype': [u'visa'],
     u'b_last_name': [u'dddddd'],
     u'b_zip': [u'sdf'],
     u'avscode': [u'X'],
     u'b_first_name': [u'sads'],
     u'correlationid': [u'dba9b733e476']}>
    """

    order = Order()
    order.email = nvp_dict.get('email')
    order.phone = nvp_dict.get('phone', "")

    order.b_first_name = nvp_dict.get('b_first_name')
    order.b_last_name = nvp_dict.get('b_last_name')
    order.b_address_countryname = nvp_dict.get('b_countryname')
    order.b_address_countrycode = nvp_dict.get('b_countrycode')
    order.b_address_zip = nvp_dict.get('b_zip')
    order.b_address_state = nvp_dict.get('b_state')
    order.b_address_city = nvp_dict.get('b_city')
    order.b_address_street = nvp_dict.get('b_street')

    order.status = order.NEW_ORDER
    order.paypal_transaction_id = nvp_dict.get('transactionid')
    order.save()

    save_order_items(nvp_dict, order)

    return order
Exemplo n.º 57
0
 def test_get_all(self):
     """ Positive Test of the CustomUser.create method TEST_DATE_END"""
     orders = Order.get_all()
     self.assertListEqual(orders, [self.order1, self.order2, self.order3])
Exemplo n.º 58
0
def get_history():
    username = session['username']
    orders = Order.load_user(username)
    return render_template("account.html", orders=orders)
Exemplo n.º 59
0
def create_order_from_direct_paypal(nvp_dict):
    """
    Create order in DB with ordered items
    """
    #create order
    #create items
    #return order object
    """
    <QueryDict:
    {u'l_paymentrequest_0_number0': [4],
     u's_countrycode': [u'AX'],
     u'b_state': [u'sdf'],
     u'card_first_name': [u'sdf'],
     u's_last_name': [u'sdf'],
     u's_street': [u'sdf'],
     u'acct': [u'4239530610456015'],
     u'l_paymentrequest_0_amt0': [32],
     u'l_paymentrequest_0_name0': [u'Raw Edge Design Letters Print Black Polyester VEST'],
     u's_city': [u'sdf'],
     u's_state': [u'sdf'],
     u'version': [u'116.0'],
     u's_countryname': [u'Aland Islands'],
     u'build': [u'16770825'],
     u'cvv2': [u'123'],
     u'b_street': [u'dd'],
     u'email': [u'*****@*****.**'],
     u'l_paymentrequest_0_qty0': [2],
     u'b_countrycode': [u'AU'],
     u'b_countryname': [u'Afghanistan'],
     u'timestamp': [u'2015-06-14T10:22:07Z'],
     u'currencycode': [u'USD'],
     u'card_last_name': [u'sdf'],
     u's_zip': [u'dsf'],
     u'paymentrequest_0_amt': [64.0],
     u'phone': [u'sdf'],
     u'b_country': [u'1'],
     u'cardyear': [u'2020'],
     u'transactionid': [u'06M899763J781091D'],
     u'amt': [u'64.00'],
     u's_first_name': [u'sdf'],
     u'cvv2match': [u'M'],
     u'cardmonth': [u'05'],
     u'ack': [u'Success'],
     u'b_city': [u'sdf'],
     u'creditcardtype': [u'visa'],
     u'b_last_name': [u'dddddd'],
     u'b_zip': [u'sdf'],
     u'avscode': [u'X'],
     u'b_first_name': [u'sads'],
     u'correlationid': [u'dba9b733e476']}>
    """

    order = Order()
    order.email = nvp_dict.get('email')
    order.phone = nvp_dict.get('phone', "")

    order.b_first_name = nvp_dict.get('b_first_name')
    order.b_last_name = nvp_dict.get('b_last_name')
    order.b_address_countryname = nvp_dict.get('b_countryname')
    order.b_address_countrycode = nvp_dict.get('b_countrycode')
    order.b_address_zip = nvp_dict.get('b_zip')
    order.b_address_state = nvp_dict.get('b_state')
    order.b_address_city = nvp_dict.get('b_city')
    order.b_address_street = nvp_dict.get('b_street')

    order.s_first_name = nvp_dict.get('s_first_name', "")
    order.s_last_name = nvp_dict.get('s_last_name', "")
    order.s_address_countryname = nvp_dict.get('s_countryname', "")
    order.s_address_countrycode = nvp_dict.get('s_countrycode', "")
    order.s_address_zip = nvp_dict.get('s_zip', "")
    order.s_address_state = nvp_dict.get('s_state', "")
    order.s_address_city = nvp_dict.get('s_city', "")
    order.s_address_street = nvp_dict.get('s_street', "")

    order.status = order.NEW_ORDER
    order.paypal_transaction_id = nvp_dict.get('transactionid')
    order.save()

    item_ids = [(key, value) for key, value in nvp_dict.iteritems() if key.startswith("l_paymentrequest_0_number")]

    #print item_ids

    for index, i in enumerate(item_ids):
        product = Prize.objects.get(pk=i[1])

        order_item = OrderItem()
        order_item.order_id = order.id
        order_item.product = product
        order_item.number = product.number
        order_item.amount = nvp_dict.get('l_paymentrequest_0_amt' + str(index))
        order_item.quantity = nvp_dict.get('l_paymentrequest_0_qty' + str(index))
        order_item.save()

    return order
Exemplo n.º 60
0
def create_order_from_express_paypal(nvp_dict):
    """
    Create order in DB with ordered items
    """
    #create order
    #create items
    #return order object

    order = Order()
    order.email = nvp_dict.get('email')
    order.b_first_name = nvp_dict.get('firstname')
    order.b_last_name = nvp_dict.get('lastname')

    order.b_address_countryname = nvp_dict.get('shiptocountryname')
    order.b_address_countrycode = nvp_dict.get('shiptocountrycode')
    order.b_address_zip = nvp_dict.get('shiptozip')
    order.b_address_state = nvp_dict.get('shiptostate')
    order.b_address_city = nvp_dict.get('shiptocity')
    order.b_address_street = nvp_dict.get('shiptostreet') \
                        + nvp_dict.get('shiptostreet2', "")
    order.shipping_address_flag = False

    order.status = order.NEW_ORDER
    order.paypal_transaction_id = nvp_dict.get('transactionid')
    order.save()

    item_ids = [(key, value) for key, value in nvp_dict.iteritems() if key.startswith("l_paymentrequest_0_number")]

    print item_ids

    for index, i in enumerate(item_ids):
        product = Prize.objects.get(pk=i[1])

        order_item = OrderItem()
        order_item.order_id = order.id
        order_item.product = product
        order_item.number = product.number
        order_item.amount = nvp_dict.get('l_paymentrequest_0_amt' + str(index))
        order_item.quantity = nvp_dict.get('l_paymentrequest_0_qty' + str(index))



        order_item.save()

    return order