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()
    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()