Coverage for src/shopping_bags/services.py: 93%
15 statements
« prev ^ index » next coverage.py v7.9.2, created at 2025-09-21 16:24 +0300
« prev ^ index » next coverage.py v7.9.2, created at 2025-09-21 16:24 +0300
1from rest_framework.exceptions import ValidationError
3from src.shopping_bags.models import ShoppingBag
4from src.common.services import UserIdentificationService
5from src.shopping_bags.constants import ShoppingBagErrorMessages
8class ShoppingBagService:
9 """
10 This class encapsulates all business logic related to shopping bag functionality,
11 including user identification, inventory validation, and quantity management.
13 Key Responsibilities:
14 - Inventory object retrieval and validation
15 - Stock quantity validation
16 - Atomic database operations for inventory updates
17 - Shopping bag item creation and retrieval
18 """
20 @staticmethod
21 def get_user_identifier(request):
22 return UserIdentificationService.get_user_identifier(request)
24 @staticmethod
25 def validate_inventory_quantity(inventory_obj, required_quantity):
26 if required_quantity > inventory_obj.quantity:
27 raise ValidationError(
28 {
29 'quantity': ShoppingBagErrorMessages.INSUFFICIENT_STOCK.format(
30 quantity=inventory_obj.quantity
31 )
32 }
33 )
35 @staticmethod
36 def get_or_create_bag_item(filters, defaults):
37 return ShoppingBag.objects.get_or_create(**filters, defaults=defaults)