Beispiel #1
0
def create_order(request, transaction_id):
    order = Order()
    checkout_form = CheckoutForm(request.POST, instance=order)
    order = checkout_form.save(commit=False)
    order.transaction_id = transaction_id
    order.ip_address = request.META.get('REMOTE_ADDR')
    order.user = None
    if request.user.is_authenticated:
        order.user = request.user
    order.status = Order.SUBMITTED
    order.save()
    # if the order save succeeded
    if order.pk:
        cart_items = cart.get_cart_items(request)
        for ci in cart_items:
            # create order item for each cart item
            oi = OrderItem()
            oi.order = order
            oi.quantity = ci.quantity
            oi.price = ci.price  # now using @property
            oi.product = ci.product
            oi.save()
        # all set, empty cart
        cart.empty_cart(request)
        # save profile info for future orders
        if request.user.is_authenticated:
            profile.set(request)
    # return the new order object
    return order
    def handle(self, *args, **options):
        path = args[0]

        if path.startswith('http'):
            content = requests.get(path).json()
        else:
            content = json.load(open(path))

        for item in content:
            try:
                order = Order.objects.get(id=int(item['id']))
            except Order.DoesNotExist:
                order = Order(id=int(item['id']))

            order.code = item['code']
            order.net = float(item['amt'])
            order.comment = item.get('comment', '')
            order.created = TIMEZONE.localize(datetime.datetime.fromtimestamp(int(item['cdt'])))
            order.status = STATUSES_MAPPING[item['status']]
            order.payment_type = PAYMENT_MAPPING.get(item.get('payment'))
            order.delivery_cost = int(item.get('dcost', 0))

            try:
                order.delivery = Delivery.objects.get(id=DELIVERY_MAPPINGS.get(item.get('delivery')))
            except Delivery.DoesNotExist:
                pass

            try:
                order.user = User.objects.get(id=int(item['user_id']))
            except User.DoesNotExist:
                try:
                    if not 'email' in item:
                        raise User.DoesNotExist()
                    order.user = User.objects.get(email=item['email'])
                except User.DoesNotExist:
                    pass

            order.save()

            for pitem in item.get('lst', ()):
                product = Product.objects.get(id=int(pitem['item_id']))

                try:
                    order_item = OrderItem.objects.get(order=order, product=product)
                except OrderItem.DoesNotExist:
                    order_item = OrderItem(order=order, product=product)
                order_item.amount = int(pitem['qty'])
                order_item.per_item = float(pitem['price'])
                order_item.save()
Beispiel #3
0
def create_order(request,transaction_id):
    order=Order()
    checkout_form=CheckoutForm(request.POST,instance=order)
    order=checkout_form.save(commit=False)
    order.transaction_id= transaction_id
    order.ip_address = request.META.get('REMOTE_ADDR')
    order.user = None
    order.user = None
    if request.user.is_authenticated():
        order.user=request.user
    order.status = Order.SUBMITTED
    order.save()
    order.status = Order.SUBMITTED
    order.save()
    # if the order save succeeded
    if order.pk:
        cart_items = cart.cart.get_cart_items(request)
        for ci in cart_items:
        # create order item for each cart item
            oi = OrderItem()
            oi.order = order
            oi.quantity = ci.quantity
            oi.price = ci.price # now using @property
            oi.product = ci.product
            oi.save()
    # all set, empty cart
    cart.cart.empty_cart(request)
    #associate orders placed with registered users if they are logged in during the checkout process.
    if request.user.is_authenticated():
        from account import profile
        profile.set(request)
            # return the new order object
    return order
    def create_order(request, transaction_id):
        order = Order()
        checkout_form = CheckoutForm(request.POST, instance=order)
        order = checkout_form.save(commit=False)
        order.transaction_id = transaction_id
        order.ip_address = reqest.META.get('REMOTE_ADDR')
        order.user = None
        if request.user.is_authenticated():
            order.user = request.user
        order.status = Order.SUBMITTED
        order.save()

        # If order save succeeded
        if order.pk:
            cart_items = cart_utils.get_cart_items(request)
            for ci in cart_items:
                # Create order item for each cart item
                oi = OrderItem()
                oi.order = order
                oi.quantity = ci.quantity
                oi.price = ci.price
                oi.product = ci.product
                oi.save()
            # Now we can emty the cart
            cart_utils.empty_cart(request)
        # save profile info for future orders
        if request.user.is_authenticated():
            from accounts import profile
            profile.set(request)
        # Return  the new order object
        return order
Beispiel #5
0
def create_order(request, transaction_id):

    order = Order()
    checkout_form = CheckoutForm(request.POST, instance = order)
    order = checkout_form.save(commit = False)
    order.transaction_id = transaction_id
    order.ip_address = request.META.get('REMOTE_ADDR')
    order.user = None
    if request.user.is_authenticated():
        order.user = request.user
    order.status = Order.SUBMITTED
    order.save()

    if order.pk:
        cart_items = cart.get_cart_items(request)
        for ci in cart_items:
            oi = OrderItem()
            oi.order = order
            oi.quantity = ci.quantity
            oi.price = ci.price
            oi.product = ci.product
            oi.save()
        cart.empty_cart(request)

        if request.user.is_authenticated():
            from accounts import profile
            profile.set(request)

    return order
Beispiel #6
0
def create_order(request):
	order = Order()
	checkout_form = CheckoutForm(request.POST, instance=order)
	order = checkout_form.save(commit=False)
	order.user = None
	if request.user.is_authenticated():
		order.user = request.user
	order.status = Order.SUBMITTED
	print (order.number)
	order.save()
	print (order.number)
	order.number = int(str(order.id) + datetime.today().strftime('%m%d%Y'))
	order.save()
	print (order.number)
	# create order item for each cart item
	if order.pk:
		cart_items = carts.get_cart_items(request)
		for ci in cart_items: 
			oi = OrderItem()
			oi.order = order
			oi.quantity = ci.quantity
			oi.price = ci.product.price
			oi.product = ci.product
			oi.save()
			carts.empty_cart(request)
	return order
def create_order(request, transaction_id):
    """
    if the POST to the payment gateway successfully billed the customer, create a new order
    containing each CartItem instance, save the order with the transaction ID from the gateway,
    and empty the shopping cart

    """
    order = Order()
    checkout_form = CheckoutForm(request.POST, instance=order)
    order = checkout_form.save(commit=False)

    order.transaction_id = transaction_id
    order.ip_address = request.META.get('REMOTE_ADDR')
    order.user = None
    if request.user.is_authenticated():
        order.user = request.user
    order.status = Order.SUBMITTED
    order.save()

    if order.pk:
        """ if the order save succeeded """
        cart_items = carts.get_cart_items(request)
        for ci in cart_items:
            """ create order item for each cart item """
            oi = OrderItem()
            oi.order = order
            oi.quantity = ci.quantity
            oi.price = ci.price  # now using @property
            oi.product = ci.product
            oi.save()
        # all set, clear the cart
        carts.empty_cart(request)

        # save profile info for future orders
        if request.user.is_authenticated():
            from accounts import profile
            profile.set(request)

    return order
Beispiel #8
0
def create_order(request):
    order = Order()
    checkout_form = CheckoutForm(request.POST, instance=order)
    order = checkout_form.save(commit=False)
    order.ip_address = request.META.get('REMOTE_ADDR')
    order.user = None
    if request.user.is_authenticated():
        order.user = request.user
    order.status = Order.SUBMITTED
    order.save()
    # if the order save succeeded
    if order.pk:
        cart_items = cart.get_cart_items(request)
        for ci in cart_items:
            # create order item for each cart item
            oi = OrderItem()
            oi.order = order
            oi.quantity = ci.quantity
            oi.product = ci.product
            oi.save()
        # all set, empty cart
        cart.empty_cart(request)
    # save profile info for future orders
    if request.user.is_authenticated():
        from accounts import profile
        profile.fill(request)
    # mail the managers
    mail_manager_subject = '{0} has been placed!'.format(order)
    mail_manager_message = '{0} has been placed by {1}.\n\nClick here: {2}'.format(
        order, order.user if order.user else 'anonymous',
        request.build_absolute_uri(
            reverse('admin:checkout_order_change', args=(order.pk, ))))
    mail_managers(mail_manager_subject, mail_manager_message)
    # mail the customer
    if order.email:
        # FIXME: someday make templates for these emails
        mail_customer_subject = 'Thank you for placing {0}!'.format(order.name)
        mail_customer_message = '{0} was placed by you.  Click here for more details: {1}\n\nThank you for your order!\n\n{2}'.format(
            order.name, request.build_absolute_uri(order.get_absolute_url()),
            settings.SITE_NAME)
        send_mail(mail_customer_subject, mail_customer_message,
                  settings.DEFAULT_FROM_EMAIL, [order.email])
    # return the new order object
    return order
Beispiel #9
0
def create_order(request):
	order = Order()
	checkout_form = CheckoutForm(request.POST, instance=order)
	order = checkout_form.save(commit=False)
	order.user = None
	if request.user.is_authenticated():
		order.user = request.user
	order.status = Order.SUBMITTED
	order.save()
	order.number = int(str(order.id) + datetime.today().strftime('%m%d%Y'))
	order.save()
	# create order item for each cart item
	if order.pk:
		cart_items = carts.get_cart_items(request)
		for ci in cart_items: 
			oi = OrderItem()
			oi.order = order
			oi.quantity = ci.quantity

			if ci.product.quantity >= ci.quantity:
				ci.product.quantity = ci.product.quantity - ci.quantity
			else:
				ci.product.quantity = 0	
			ci.product.save()

			oi.price = ci.product.price
			oi.product = ci.product
			oi.save()
			carts.empty_cart(request)
	# send_mail('Subject here', 'Here is the message.', '*****@*****.**',
	# ['*****@*****.**'], fail_silently=False)
	items = OrderItem.objects.filter(order = order)
	plaintext = get_template('email.txt')
	htmly = get_template('email.html')
	d = Context({ 'order': order, 'items': items})
	subject, from_email, to = 'Ваш заказ', '*****@*****.**', [order.email]
	text_content = plaintext.render(d)
	html_content = htmly.render(d)
	msg = EmailMultiAlternatives(subject, text_content, from_email, to)
	msg.attach_alternative(html_content, "text/html")
	msg.send()
	print('sent!')
	return order
def create_order(request, transaction_id):
  """ if the POST to the payment gateway successfully billed the customer, create a new order
  containing each CartItem instance, save the order with the transaction ID from the gateway,
  and empty the shopping cart

  """
  order = Order()
  checkout_form = CheckoutForm(request.POST, instance=order)
  order = checkout_form.save(commit=False)

  order.transaction_id = transaction_id
  order.ip_address = request.META.get('REMOTE_ADDR')
  order.user = None
  if request.user.is_authenticated():
    order.user = request.user
  order.status = Order.SUBMITTED
  order.save()

  if order.pk:
    """ if the order save succeeded """
    cart_items = cart.get_cart_items(request)
    for ci in cart_items:
      """ create order item for each cart item """
      oi = OrderItem()
      oi.order = order
      oi.quantity = ci.quantity
      oi.price = ci.price  # now using @property
      oi.product = ci.product
      oi.save()
    # all set, clear the cart
    cart.empty_cart(request)

    # save profile info for future orders
    if request.user.is_authenticated():
      from ecomstore.accounts import profile
      profile.set(request)

  return order
Beispiel #11
0
def create_order(request):
    order = Order()
    checkout_form = CheckoutForm(request.POST, instance=order)
    order = checkout_form.save(commit=False)
    order.ip_address = request.META.get('REMOTE_ADDR')
    order.user = None
    if request.user.is_authenticated():
        order.user = request.user
    order.status = Order.SUBMITTED
    order.save()
    # if the order save succeeded
    if order.pk:
        cart_items = cart.get_cart_items(request)
        for ci in cart_items:
            # create order item for each cart item
            oi = OrderItem()
            oi.order = order
            oi.quantity = ci.quantity
            oi.product = ci.product
            oi.save()
        # all set, empty cart
        cart.empty_cart(request)
    # save profile info for future orders
    if request.user.is_authenticated():
        from accounts import profile
        profile.fill(request)
    # mail the managers
    mail_manager_subject = '{0} has been placed!'.format(order)
    mail_manager_message = '{0} has been placed by {1}.\n\nClick here: {2}'.format(order, order.user if order.user else 'anonymous', request.build_absolute_uri(reverse('admin:checkout_order_change', args=(order.pk,))))
    mail_managers(mail_manager_subject, mail_manager_message)
    # mail the customer
    if order.email:
        # FIXME: someday make templates for these emails
        mail_customer_subject = 'Thank you for placing {0}!'.format(order.name)
        mail_customer_message = '{0} was placed by you.  Click here for more details: {1}\n\nThank you for your order!\n\n{2}'.format(order.name, request.build_absolute_uri(order.get_absolute_url()), settings.SITE_NAME)
        send_mail(mail_customer_subject, mail_customer_message, settings.DEFAULT_FROM_EMAIL, [order.email])
    # return the new order object
    return order
Beispiel #12
0
def checkout(request):

    if request.method == 'GET':
        # request.session['braintree_client_token'] = braintree.ClientToken.generate()
        stripe_customer = stripe.Customer.retrieve(
            request.user.user.stripe_customer_id)
        payment_info = stripe_customer.sources.retrieve(
            stripe_customer.default_source)
        cart = request.session.get('cart', {})
        new_cart = cart.copy()
        item_list = []
        sold_item_list = []
        total_price = 0
        total_shipping = 0
        for id in cart:
            try:
                item = Item.objects.get(pk=id)
                if item.sold == True:
                    sold_item_list.append(item)
                    del new_cart[id]

                else:
                    item_list.append(item)
                    total_price = total_price + item.price
                    total_shipping = total_shipping + item.shipping_price
            except:
                pass

        final_total = total_shipping + total_price
        if sold_item_list:
            request.session['cart'] = new_cart
        return render(
            request, 'checkout/checkout.html', {
                'sold_item_list': sold_item_list,
                'items': item_list,
                'total': final_total,
                'sub_total': total_price,
                'total_shipping': total_shipping,
                'payment_information': payment_info
            })

    else:

        print request.POST
        cart = request.session.get('cart', {})
        new_cart = cart.copy()
        item_list = []
        sold_item_list = []

        total_price = 0
        total_shipping = 0
        final_total = 0
        print cart
        print new_cart

        for id in cart:
            try:
                item = Item.objects.get(pk=id)
                if item.sold == True:
                    sold_item_list.append(item)

                    base_sold_email_template = open(
                        os.path.join(PROJECT_ROOT,
                                     'emails/reminder_email.html')).read()
                    message = sendgrid.Mail(
                        to=item.seller.email,
                        subject='CampusThrift Buyer Reminder',
                        html=base_sold_email_template,
                        text='Body',
                        from_email='*****@*****.**')
                    sg.send(message)

                    del new_cart[id]

                else:
                    item_list.append(item)
                    total_price = total_price + item.price
                    total_shipping = total_shipping + item.shipping_price
            except:
                pass

        final_total = total_shipping + total_price

        if sold_item_list:
            request.session['cart'] = new_cart
            return render(
                request, 'checkout/checkout.html', {
                    'sold_item_list': sold_item_list,
                    'items': item_list,
                    'total': final_total,
                    'sub_total': total_price,
                    'total_shipping': total_shipping
                })
        else:

            new_order = Order()
            new_order.buyer = request.user

            sub_total = 0
            shipping_total = 0
            final_total = 0

            #
            for item in item_list:
                new_order_item = OrderItem()
                new_order_item.order = new_order
                new_order_item.item = item
                new_order_item.seller = item.user
                new_order_item.shipping_method = request.POST[str(item.pk) +
                                                              '_ship_method']
                new_order_item.price = item.price

                if int(request.POST[str(item.pk) + '_ship_method']) == 1:
                    new_order_item.shipping_price = 0.00
                    new_order_item.order_item_total_price = new_order_item.price
                else:

                    new_order_item.shipping_price = item.shipping_price
                    shipping_total = shipping_total + item.shipping_price
                    new_order_item.order_item_total_price = new_order_item.price + new_order_item.shipping_price

                sub_total = sub_total + item.price

                new_order_item.save()

            new_order.shipping_address = request.POST['address']
            new_order.city = request.POST['city']
            new_order.state = request.POST['state']
            new_order.zip = request.POST['zip']

            new_order.final_total = sub_total + shipping_total
            new_order.shipping_total = shipping_total
            new_order.sub_total = sub_total
            new_order.save()

            request.session['order'] = new_order.primary_key

            return redirect('confirm')
Beispiel #13
0
def checkout(request):
    ''' render checkout form and complete order and payment with user provided details '''
    stripe_public_key = settings.STRIPE_PUBLIC_KEY
    stripe_secret_key = settings.STRIPE_SECRET_KEY

    if request.method == 'POST':

        form_data = {
            'first_name': request.POST['first_name'],
            'last_name': request.POST['first_name'],
            'email_address': request.POST['email_address'],
            'phone_number': request.POST['phone_number'],
            'street_address1': request.POST['street_address1'],
            'street_address2': request.POST['street_address2'],
            'town_or_city': request.POST['town_or_city'],
            'postcode': request.POST['postcode'],
            'country': request.POST['country'],
        }
        current_basket = basket_content(request)
        total = current_basket['total']
        order_form = OrderForm(form_data)

        if order_form.is_valid():
            order = order_form.save()
            order.total = total
            order.save()

            if request.user.is_authenticated:

                basket_items = BasketItem.objects.filter(
                    basket__owner=request.user)
                for basket_item in basket_items:
                    order_item = OrderItem(order=order, product=basket_item.product,
                                           quantity=basket_item.quantity, colour=basket_item.colour)
                    order_item.save()

                if 'save' in request.POST:
                    profile = get_object_or_404(Profile, owner=request.user)
                    profile_form = ProfileForm(form_data, instance=profile)
                    if profile_form.is_valid():
                        profile_form.save()

            else:
                basket = request.session.get('basket', {})

                for item in basket:
                    product = Product.objects.get(pk=basket[item]['product'])
                    quantity = basket[item]['quantity']
                    colour = None
                    if Colour.objects.filter(pk=basket[item]['colour']).exists():
                        colour = Colour.objects.get(pk=basket[item]['colour'])

                    order_item = OrderItem(
                        order=order, product=product, quantity=quantity, colour=colour)
                    order_item.save()

            return redirect(reverse('checkout_success', args=[order.order_number]))
        else:
            messages.error(
                request, 'There is an error in your form, please check your data')
            return redirect(reverse('checkout'))

    else:

        if request.user.is_authenticated:
            if BasketItem.objects.filter(basket__owner=request.user).exists():
                basket = Basket.objects.get(owner=request.user)
            else:
                basket = None

            # if details were saved in profile, display them in the form
            if Profile.objects.filter(owner=request.user).exists():
                profile = Profile.objects.get(owner=request.user)

                order_form = OrderForm(initial={
                    'first_name': profile.first_name,
                    'last_name': profile.first_name,
                    'email_address': profile.email_address,
                    'phone_number': profile.phone_number,
                    'street_address1': profile.street_address1,
                    'street_address2': profile.street_address2,
                    'town_or_city': profile.town_or_city,
                    'postcode': profile.postcode,
                    'country': profile.country,
                    })
        else:
            basket = request.session.get('basket', {})
            order_form = OrderForm()

        if not basket:
            messages.error(
                request, "There's nothing in your basket at the moment")
            return redirect(reverse('basket'))

        current_basket = basket_content(request)
        total = current_basket['total']
        stripe_total = round(total * 100)
        stripe.api_key = stripe_secret_key
        intent = stripe.PaymentIntent.create(
            amount=stripe_total,
            currency=settings.STRIPE_CURRENCY,
        )

    
    context = {
        'order_form': order_form,
        'stripe_public_key': stripe_public_key,
        'client_secret': intent.client_secret,
    }

    return render(request, 'checkout.html', context)
def insert_cart(request, product_id):
    context = {}
    nItems = 0
    if 'order_id' in request.session:
        order = Order.objects.get(id=request.session['order_id'])
        orderItem = OrderItem()
        product = Product.objects.get(id=product_id)
        orderItem.order = order
        orderItem.product = product
        orderItem.value = product.value
        orderItem.save()
        # context['order'] = order
        # context['orderItems'] = OrderItem.objects.filter(order__id=order.id)
        request.session['howItems'] = \
        int(request.session['howItems']) + 1

    else:
        order = Order()
        order.user = User.objects.get(id=request.user.id)
        order.save()

        orderItem = OrderItem()
        product = Product.objects.get(id=product_id)
        orderItem.order = order
        orderItem.product = product
        orderItem.value = product.value
        orderItem.save()
        # context['order'] = order
        # context['orderItems'] = OrderItem.objects.filter(order__id=order.id)
        request.session['order_id'] = order.id
        request.session['howItems'] = 1

    return HttpResponseRedirect(resolve_url("/"))
    def save(self):
        self.checkout.storage['is_confirmed'] = True

        order = Order()
        order.user = self.request.user
        order.address = self._get_address()
        order.delivery_date = self._get_delivery_date()
        order.delivery_time = self._get_delivery_time()
        order.shop = self._get_shop()
        order.status = Order.STATUS_RECEIVED
        order.code = '!'

        form = PaymentForm(self.request.POST)
        form.is_valid()
        order.comment = form.cleaned_data.get('comment', self.checkout.storage.get('comment', ''))
        net = self.request.cart.get_total(request=self.request).net

        try:
            order.delivery = Delivery.objects.get(id=self.checkout.storage['delivery'])
        except Delivery.DoesNotExist:
            order.delivery = None
            order.delivery_cost = 0
        else:
            order.delivery_cost = order.delivery.cost(net)
            print 'DELIVERY', order.delivery_id
            if order.delivery_id == Delivery.TYPE_SELF:
                order.payment_type = Order.PAYMENT_CASHPICK

            elif order.delivery_id == Delivery.TYPE_COURIER:
                order.payment_type = Order.PAYMENT_COURIER
                if net > 1000 and (order.address.city == u'Иркутск' or order.address.courier_city_id == 1):  # Иркутск
                    order.delivery_cost = 0
                elif order.address.courier_city:
                    order.delivery_cost = order.address.courier_city.price

            elif order.delivery_id == Delivery.TYPE_RUSSIANPOST:
                order.payment_type = Order.PAYMENT_ROBOKASSA

            elif order.delivery_id == Delivery.TYPE_EXPRESSPOST:
                pass

        order.products_price = self.request.cart.get_total(request=self.request).net
        order.net = self.request.cart.get_total(request=self.request).net + order.delivery_cost
        order.status = Order.STATUS_PAYMENT_WAITING

        order.save()

        for line in self.request.cart:
            item = OrderItem(order=order, product=line.product, amount=line.quantity,
                per_item=line.product.price_for_user(self.request.user) or 0)

            if line.data:
                item.sign = line.data.get('sign')

            item.save()

        coupon = self._get_coupon()
        if coupon:
            diff = self._apply_coupon(order, coupon)
            order.coupon = coupon
            order.net -= diff
            order.save()
            try:
                del self.request.session[Cart.COUPON_KEY]
            except KeyError:
                pass

        self.checkout.storage['order_id'] = order.id
        self.checkout.save()
    def handle(self, *args, **options):
        path = args[0]

        if path.startswith('http'):
            content = requests.get(path).json()
        else:
            content = json.load(open(path))

        for item in content:
            id_ = int(item['id']) + 300  # 260 розничных заказов, плюс небольшой отступ
            try:
                order = Order.objects.get(id=id_)
            except Order.DoesNotExist:
                order = Order(id=id_)

            print 'Processing order %s' % item['id']

            order.code = item['code']
            order.net = float(item['amt'])
            order.comment = item.get('comment', '')
            order.created = TIMEZONE.localize(datetime.datetime.fromtimestamp(int(item['cdt'])))
            order.status = STATUSES_MAPPING[item['status']]
            order.payment_type = PAYMENT_MAPPING.get(item.get('payment'))
            order.delivery_cost = int(item.get('dcost', 0))

            try:
                order.delivery = Delivery.objects.get(id=DELIVERY_MAPPINGS.get(item.get('delivery')))
            except Delivery.DoesNotExist:
                pass

            try:
                order.user = User.objects.get(id=int(item['user_id']))
            except User.DoesNotExist:
                try:
                    if not 'email' in item:
                        raise User.DoesNotExist()
                    order.user = User.objects.get(email=item['email'])
                except User.DoesNotExist:
                    pass

            order.save()

            if order.user:
                try:
                    company = Company.objects.get(user=order.user)
                except Company.DoesNotExist:
                    company = Company(user=order.user)

                company.title = item.get('addr_name') or item.get('company_name', '')
                company.city = item.get('company_city', '')
                company.director = item.get('director', '')
                company.juridical_address = item.get('jaddress', '')
                company.post_address = item.get('address', '')
                company.industry = item.get('company_industry', '')
                company.phone = item.get('phone', '')
                company.inn = item.get('inn', '')
                company.ogrn = item.get('ogrn', '')
                company.save()
            else:
                print 'Order %d cant be linked to user' % order.id

            for pitem in item.get('lst', ()):
                product_id = int(pitem['item_id'])
                try:
                    product = Product.objects.get(wholesale_legacy_id=product_id, is_visible=True)
                    kwargs = {
                        'product': product,
                    }
                except Product.DoesNotExist:
                    print 'Unknown product with id %s' % pitem['item_id']
                    kwargs = {
                        'product_legacy_id': product_id,
                    }
                except Product.MultipleObjectsReturned:
                    print product_id
                    raise

                try:
                    order_item = OrderItem.objects.get(order=order, **kwargs)
                except OrderItem.DoesNotExist:
                    order_item = OrderItem(order=order, **kwargs)
                order_item.product_legacy_id = product_id
                order_item.amount = int(pitem['qty'])
                order_item.per_item = float(pitem['price'])
                order_item.save()