diff --git a/shop/api/v1/viewsets.py b/shop/api/v1/viewsets.py index b73b0ec..ec33996 100644 --- a/shop/api/v1/viewsets.py +++ b/shop/api/v1/viewsets.py @@ -40,6 +40,7 @@ from shop.models import ( ) from shop.api.v1.permissions import ProductPermissions, ProductPricePermissions +from shop.utils import delete_product_batch class ProductViewSet(ModelViewSet): @@ -107,10 +108,16 @@ class ProductBatchViewSet(ModelViewSet): product.save() def perform_destroy(self, instance): + delete_product_batch(instance) + + def perform_update(self, serializer): + instance = self.get_object() product = instance.product - product.stock = max(product.stock - instance.quantity, 0) + product.stock -= instance.quantity + + updated_batch = serializer.save() + product.stock += updated_batch.quantity product.save() - instance.delete() class CustomerViewSet(ModelViewSet): diff --git a/shop/tests/test_api_product_batches.py b/shop/tests/test_api_product_batches.py index 965095d..04a83f4 100644 --- a/shop/tests/test_api_product_batches.py +++ b/shop/tests/test_api_product_batches.py @@ -51,6 +51,8 @@ class TestProductBatchesAPI(APITestCase, TestUserAuthenticationMixin): pk = response.data.get("id") response = self.client.get(f"/api/v1/shop/product-batches/{pk}/") + self.product.refresh_from_db() + assert self.product.stock == Decimal("5") assert response.status_code == status.HTTP_200_OK def test_create_update_product_batch(self): @@ -73,6 +75,9 @@ class TestProductBatchesAPI(APITestCase, TestUserAuthenticationMixin): response = self.client.get(f"/api/v1/shop/product-batches/{pk}/") assert response.status_code == status.HTTP_200_OK + self.product.refresh_from_db() + assert self.product.stock == Decimal("5") + response = self.client.patch( f"/api/v1/shop/product-batches/{pk}/", { @@ -81,6 +86,9 @@ class TestProductBatchesAPI(APITestCase, TestUserAuthenticationMixin): ) assert response.status_code == status.HTTP_200_OK + self.product.refresh_from_db() + assert self.product.stock == Decimal("10") + response = self.client.get(f"/api/v1/shop/product-batches/{pk}/") assert response.status_code == status.HTTP_200_OK assert Decimal(response.data.get("quantity")) == Decimal("10") diff --git a/shop/utils.py b/shop/utils.py index 9440675..e2c0216 100644 --- a/shop/utils.py +++ b/shop/utils.py @@ -1,6 +1,6 @@ from decimal import Decimal -from shop.models import OrderLine, Product, Order, Customer +from shop.models import OrderLine, Product, Order, Customer, ProductBatch def create_order_line_for_product(product: Product, quantity: Decimal, order: Order): @@ -61,3 +61,10 @@ def create_order( ) return order + + +def delete_product_batch(batch: ProductBatch): + product = batch.product + product.stock = max(product.stock - batch.quantity, 0) + product.save() + batch.delete()