def validate_products(self, value): for product in value: if 'id' not in product or 'qty' not in product: raise serializers.ValidationError( 'Each product must contain "id" and "qty".') product_obj = shop_api.get_product(product['id']) if product_obj is None: raise serializers.ValidationError( 'Product with id "{}" not found.'.format(product['id'])) if product['qty'] <= 0: raise serializers.ValidationError( 'Product quantity must be greater than 0.') return value
def validate_products(self, value): for product in value: if 'id' not in product or 'qty' not in product: raise serializers.ValidationError( 'Each product must contain "id" and "qty".' ) product_obj = shop_api.get_product(product['id']) if product_obj is None: raise serializers.ValidationError( 'Product with id "{}" not found.'.format(product['id']) ) if product['qty'] <= 0: raise serializers.ValidationError( 'Product quantity must be greater than 0.' ) return value
def purchase(account_id, products): """ Products should be a list of tuples containing paiars of product ids and their quantities. If account_id is None, a cash purchase will be made - no account will be assigned to the purchase and the money will be transfered to the cash wallet. """ if account_id is not None: account_obj = Account.objects.get(id=account_id) else: account_obj = None purchase_obj = Purchase.objects.create(account=account_obj) products = [(shop_api.get_product(p), q) for p, q in products] # make sure the quantites are greater than 0 assert all(q > 0 for _, q in products) # make sure that all the products exist assert all(p is not None for p, q in products) for product_obj, qty in products: trx_obj = PurchaseItem.objects.create(purchase=purchase_obj, product_id=product_obj.id, qty=qty, amount=product_obj.price) shop_api.create_product_transaction( product_id=product_obj.id, trx_type=shop_enums.TrxType.PURCHASE, qty=-qty, reference=trx_obj) zero_money = Money(0, settings.DEFAULT_CURRENCY) total_amount = sum((p.price * q for p, q in products), zero_money) if account_id is not None: wallet_api.transfer(debtor_id=account_obj.id, creditor_id=settings.FOOBAR_MAIN_WALLET, amount=total_amount, reference=purchase_obj.id) else: wallet_api.deposit(owner_id=settings.FOOBAR_CASH_WALLET, amount=total_amount, reference=purchase_obj.id) return purchase_obj
def product_ean(self, obj): obj = shop_api.get_product(obj.product_id) if obj: return obj.code
def product_name(self, obj): obj = shop_api.get_product(obj.product_id) if obj: return obj.name
def product(self): return product_api.get_product(self.product_id)