products.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. """
  2. Product Routes Module
  3. This module defines all API endpoints for product management including:
  4. - Fetching products (all users)
  5. - Creating/editing products (permissions >= 1)
  6. - Deleting products (permissions == 2 only)
  7. Permission levels:
  8. - 0: Regular user (read-only access)
  9. - 1: Manager (can create/edit products)
  10. - 2: Admin (full access including delete)
  11. """
  12. # Standard library imports
  13. from math import prod
  14. from logging import getLogger
  15. from time import time
  16. from typing import Optional
  17. # Third-party imports
  18. from fastapi import APIRouter, Depends, Query
  19. from fastapi.responses import JSONResponse
  20. from h11 import Data
  21. # Local imports
  22. from auth.security import get_current_user
  23. from models import user
  24. from models.items import Product, ProductCreateRequest, ProductEditRequest
  25. from services.data_service import DataServiceFactory
  26. from config.messages import ErrorResponse, SuccessResponse, UserResponse
  27. # Initialize logger for this module
  28. logger = getLogger(__name__)
  29. # Initialize data services for products and users
  30. product_data_service = DataServiceFactory.get_product_service()
  31. user_data_service = DataServiceFactory.get_user_service()
  32. # Create router instance for product-related endpoints
  33. product_router = APIRouter()
  34. def apply_promo_price(product: Product):
  35. """Apply promotional price to a product if applicable."""
  36. #dia de la semana 1-7
  37. day_of_week = time.localtime().tm_wday + 1 # Convert to 1-7 range
  38. if product.promo_id and product.promo_price and product.promo_day == day_of_week:
  39. product.price = product.promo_price
  40. product.id = product.promo_id
  41. return product
  42. @product_router.get("/")
  43. async def get_products(status: Optional[int] = Query(None), current_user = Depends(get_current_user)):
  44. """
  45. Get all products - Available to all authenticated users
  46. Returns:
  47. JSONResponse: List of all products with success message
  48. """
  49. logger.debug(f"Current user: {current_user.email if current_user else 'Anonymous'}")
  50. logger.info("Fetching all products")
  51. # Retrieve all products and convert to dictionary format
  52. all_products = product_data_service.get_all()
  53. all_products = list(map(apply_promo_price, all_products))
  54. all_products = [product.model_dump() for product in all_products]
  55. if status is not None:
  56. # Filter products by status if provided
  57. all_products = [product for product in all_products if product['status'] == status]
  58. return JSONResponse({"products": all_products, "message": SuccessResponse.PRODUCTS_FETCH_SUCCESS})
  59. @product_router.get("/{product_id}")
  60. async def get_product(product_id: int, current_user = Depends(get_current_user)):
  61. """
  62. Get a specific product by ID - Available to all authenticated users
  63. Args:
  64. product_id (int): The ID of the product to retrieve
  65. current_user: Authenticated user (dependency injection)
  66. Returns:
  67. JSONResponse: Product data if found, error message if not found
  68. """
  69. logger.debug(f"Current user: {current_user.email if current_user else 'Anonymous'}")
  70. logger.info(f"Fetching product with ID: {product_id}")
  71. # Attempt to find product by ID
  72. product = product_data_service.get_by_id(product_id)
  73. if product:
  74. return JSONResponse({"product": product.model_dump(), "message": SuccessResponse.PRODUCTS_FETCH_SUCCESS})
  75. # Return 404 if product not found
  76. return JSONResponse({"message": UserResponse.USER_NOT_FOUND.format(user_id=product_id)}, status_code=404)
  77. # MODERATE RISK OPERATIONS - Requires permissions >= 1 (Manager level or above)
  78. @product_router.patch("/{product_id}/edit")
  79. async def edit_product(product_id: int, product: ProductEditRequest, current_user = Depends(get_current_user)):
  80. """
  81. Edit an existing product - Requires manager permissions (level >= 1)
  82. Args:
  83. product (ProductEditRequest): Product data to update
  84. current_user: Authenticated user (dependency injection)
  85. Returns:
  86. JSONResponse: Updated product data or permission denied message
  87. """
  88. logger.debug(f"Current user: {current_user.email if current_user else 'Anonymous'}")
  89. logger.info(f"Editing product: {product_id}")
  90. # Check if user has sufficient permissions (manager level or above)
  91. if user_data_service.permissions(current_user.id) > 0:
  92. # Update product with provided data (excluding unset fields)
  93. product_data_service.update(product_id, **product.model_dump(exclude_unset=True))
  94. # Retrieve updated product to return in response
  95. edited_product = product_data_service.get_by_id(product_id)
  96. if not edited_product:
  97. return JSONResponse({"message": UserResponse.USER_NOT_FOUND.format(user_id=product_id)}, status_code=404)
  98. logger.info(f"Product {product_id} edited successfully")
  99. return JSONResponse({"message": SuccessResponse.PRODUCT_EDIT_SUCCESS, "product": edited_product.model_dump()})
  100. # Return 403 if user lacks permissions
  101. return JSONResponse({"message": UserResponse.NOT_PERMITTED}, status_code=403)
  102. @product_router.post("/create")
  103. async def create_product(product: ProductCreateRequest, current_user = Depends(get_current_user)):
  104. """
  105. Create a new product - Requires manager permissions (level >= 1)
  106. Args:
  107. product (ProductCreateRequest): New product data
  108. current_user: Authenticated user (dependency injection)
  109. Returns:
  110. JSONResponse: Success message or permission denied message
  111. """
  112. logger.debug(f"Current user: {current_user.email if current_user else 'Anonymous'}")
  113. logger.info("Creating a new product")
  114. # Check if user has sufficient permissions (manager level or above)
  115. if user_data_service.permissions(current_user.id) > 0:
  116. # Create new product with provided data
  117. product_data_service.create(**product.model_dump(exclude_unset=True))
  118. return JSONResponse({"message": SuccessResponse.PRODUCT_CREATE_SUCCESS, "product": product.model_dump()}, status_code=201)
  119. # Return 403 if user lacks permissions
  120. return JSONResponse({"message": UserResponse.NOT_PERMITTED}, status_code=403)
  121. @product_router.patch("/{product_id}/swap-status")
  122. async def switch_product_status(product_id: int, current_user = Depends(get_current_user)):
  123. """
  124. Toggle product status between active/inactive - Requires manager permissions (level >= 1)
  125. Args:
  126. product_id (int): ID of the product to update
  127. status (int): New status value (0=inactive, 1=active)
  128. current_user: Authenticated user (dependency injection)
  129. Returns:
  130. JSONResponse: Success message or permission denied message
  131. """
  132. logger.debug(f"Current user: {current_user.email if current_user else 'Anonymous'}")
  133. logger.info(f"Switching status for product with ID: {product_id}")
  134. # Check if user has sufficient permissions (manager level or above)
  135. if user_data_service.permissions(current_user.id) > 0:
  136. # Update only the status field of the specified product
  137. product = product_data_service.get_by_id(product_id)
  138. if not product:
  139. return JSONResponse({"message": ErrorResponse.PRODDUCT_NOT_FOUND.format(product_id=product_id)}, status_code=404)
  140. status = 0 if product.status == 1 else 1
  141. product_data_service.update(product_id, status=status)
  142. return JSONResponse({"message": SuccessResponse.PRODUCT_EDIT_SUCCESS})
  143. # Return 403 if user lacks permissions
  144. return JSONResponse({"message": UserResponse.NOT_PERMITTED}, status_code=403)
  145. # HIGH RISK OPERATIONS - Requires permissions == 2 (Admin level only)
  146. @product_router.delete("/{product_id}")
  147. async def delete_product(product_id: int, current_user = Depends(get_current_user)):
  148. """
  149. Delete a product permanently - Requires admin permissions (level == 2)
  150. This is a high-risk operation that permanently removes product data.
  151. Only users with admin-level permissions can perform this action.
  152. Args:
  153. product_id (int): ID of the product to delete
  154. current_user: Authenticated user (dependency injection)
  155. Returns:
  156. JSONResponse: Success message or permission denied message
  157. """
  158. logger.debug(f"Current user: {current_user.email if current_user else 'Anonymous'}")
  159. logger.info(f"Deleting product with ID: {product_id}")
  160. # Check if user has admin permissions (exactly level 2)
  161. if user_data_service.permissions(current_user.id) == 2:
  162. # Permanently delete the product
  163. product_data_service.delete(product_id)
  164. return JSONResponse({"message": SuccessResponse.PRODUCT_DELETE_SUCCESS})
  165. # Return 403 if user lacks admin permissions
  166. return JSONResponse({"message": UserResponse.NOT_PERMITTED}, status_code=403)