orders.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. import time
  2. from logging import getLogger
  3. from threading import Thread
  4. from uuid import uuid4
  5. from enums.locations import Locations
  6. from fastapi import HTTPException, APIRouter, Depends
  7. from fastapi.responses import JSONResponse
  8. from fudo import fudo
  9. from models.sales import ItemWeb, OrderWeb
  10. from models.items import Item, Order
  11. from models.user import User
  12. from services.fudo_service import add_product_to_fudo
  13. from services.email_service import get_email_sender
  14. import services.print_service as ps
  15. from services.data_service import DataServiceFactory
  16. from config.mails import PRINTER_DISCONNECTED_MAIL
  17. from config.messages import ErrorResponse, SuccessResponse, UserResponse
  18. from config.settings import DEVELOPMENT
  19. from auth.security import get_current_user
  20. from data.product_category import CAT_ITEMS
  21. logger = getLogger(__name__)
  22. # Data services initialization
  23. user_data_service = DataServiceFactory.get_user_service()
  24. product_data_service = DataServiceFactory.get_product_service()
  25. sale_data_service = DataServiceFactory.get_sales_service()
  26. # Global variables
  27. printer_orders = []
  28. order_router = APIRouter()
  29. name_promo = "Shop"
  30. @order_router.post("/send")
  31. async def printer_order(order: OrderWeb, current_user: User = Depends(get_current_user)):
  32. """Process printer order"""
  33. logger.info(f"Printer order received from user {current_user.email} for table {order.table}")
  34. # Extract order data
  35. items = order.items
  36. table = order.table
  37. # Input validation
  38. if not items or not table:
  39. logger.warning(f"Invalid order data from user {current_user.email}: missing items or table")
  40. return JSONResponse(status_code=400, content={"message": ErrorResponse.MISSING_FIELDS})
  41. if not isinstance(table, int):
  42. logger.warning(f"Invalid table type from user {current_user.email}: {type(table)}")
  43. return JSONResponse(status_code=400, content={"message": ErrorResponse.INVALID_TABLE_TYPE})
  44. logger.info(f"Processing order for table {table} with {len(items)} items")
  45. # Get products data
  46. try:
  47. products = product_data_service.get_products([item.id for item in items])
  48. logger.info(f"Retrieved {len(products)} products from database")
  49. except Exception as e:
  50. error_msg = f"Error retrieving products: {e}"
  51. logger.error(error_msg)
  52. return JSONResponse(status_code=500, content={"message": "Error interno del servidor"})
  53. types = set([CAT_ITEMS[product.type or ""] for product in products])
  54. # Printer status validation
  55. if not DEVELOPMENT:
  56. try:
  57. printer_status = filter(lambda x: x == False, [ps.get_status(loc) for loc in types])
  58. if not printer_status:
  59. logger.error(f"Printer is not connected. Order from user {current_user.email} cannot be processed.")
  60. # Send notification email to admins
  61. email_thread = Thread(
  62. target=get_email_sender().send_email,
  63. args=(
  64. PRINTER_DISCONNECTED_MAIL["subject"],
  65. PRINTER_DISCONNECTED_MAIL["body"].format(location=", ".join([loc.value for loc in printer_status])), #type: ignore
  66. ["erwinjacimino2003@gmail.com", "mompyn@gmail.com"]
  67. ),
  68. daemon=True
  69. )
  70. email_thread.start()
  71. return JSONResponse(status_code=424, content={"message": ErrorResponse.PRINTER_DISCONNECTED})
  72. except Exception as e:
  73. logger.error(f"Error checking printer status: {e}")
  74. return JSONResponse(status_code=500, content={"message": "Error interno del servidor"})
  75. # Input validation
  76. # Add products to Fudo
  77. product_errors = []
  78. beers_for_promo = 0
  79. try:
  80. fudo.get_token()
  81. logger.info("Fudo token obtained successfully")
  82. for item, product in zip(items, products):
  83. try:
  84. # Si es dia de promo
  85. if time.localtime().tm_wday + 1 == product.promo_day and product.promo_id:
  86. logger.info(f"Applying promotion for product {product.id} on table {table}")
  87. fudo_product = add_product_to_fudo(product.promo_id, item.quantity, table)
  88. #en caso contrario
  89. else:
  90. if product.type == name_promo:
  91. beers_for_promo += item.quantity
  92. logger.debug(f"Added {item.quantity} beers for promotion calculation")
  93. fudo_product = add_product_to_fudo(item.id, item.quantity, table)
  94. logger.info(f"Added product {item.id} to table {table} with quantity {item.quantity} in fudo")
  95. if not fudo_product:
  96. error_msg = f"Error adding product {item.id} to table {table}."
  97. product_errors.append(error_msg)
  98. logger.error(error_msg)
  99. except Exception as e:
  100. error_msg = f"Error processing product {item.id}: {e}"
  101. logger.error(error_msg)
  102. product_errors.append(error_msg)
  103. except Exception as e:
  104. error_msg = f"Error with Fudo integration: {e}"
  105. logger.error(error_msg)
  106. return JSONResponse(status_code=500, content={"message": "Error interno del servidor"})
  107. if product_errors:
  108. logger.error(f"Product errors occurred: {product_errors}")
  109. return JSONResponse(
  110. status_code=424,
  111. content={"message": ErrorResponse.PRODUCT_ADD_ERROR, "errors": product_errors}
  112. )
  113. # User validation
  114. try:
  115. user = user_data_service.get_by_id(order.customerId)
  116. if not user:
  117. logger.warning(f"User not found: {order.customerId}")
  118. return JSONResponse(status_code=404, content={"message": UserResponse.USER_NOT_FOUND.format(user_id=order.customerId)})
  119. logger.info(f"Order customer validated: {user.email}")
  120. except Exception as e:
  121. error_msg = f"Error validating user {order.customerId}: {e}"
  122. logger.error(error_msg)
  123. return JSONResponse(status_code=500, content={"message": "Error interno del servidor"})
  124. # Get active sale
  125. try:
  126. active_sale_id = fudo.get_active_sale(fudo.get_table(table))
  127. if not active_sale_id:
  128. error_msg = f"No active sale found for table {table}"
  129. logger.error(error_msg)
  130. raise HTTPException(status_code=404, detail=error_msg)
  131. active_sale_id = active_sale_id['id']
  132. logger.info(f"Active sale found for table {table}: {active_sale_id}")
  133. except HTTPException:
  134. raise
  135. except Exception as e:
  136. error_msg = f"Error retrieving active sale for table {table}: {e}"
  137. logger.error(error_msg)
  138. raise HTTPException(status_code=500, detail="Error interno del servidor")
  139. # Update user reward progress
  140. try:
  141. new_progress = user.reward_progress + beers_for_promo * 10
  142. user_data_service.set_reward_progress(user.id, new_progress)
  143. logger.info(f"Updated reward progress for user {user.email}: {user.reward_progress} -> {new_progress}")
  144. except Exception as e:
  145. error_msg = f"Error updating reward progress for user {user.id}: {e}"
  146. logger.error(error_msg)
  147. # Don't fail the order for this, just log it
  148. new_progress = user.reward_progress
  149. # Create sale record
  150. try:
  151. sale = sale_data_service.create(
  152. order.customerId,
  153. active_sale_id or uuid4().hex,
  154. order.totalAmount,
  155. order.table,
  156. [item.id for item in items],
  157. [item.quantity for item in items]
  158. )
  159. if sale > 0:
  160. logger.info(f"Sale created successfully: ID {sale}")
  161. else:
  162. error_msg = "Failed to create sale record"
  163. logger.error(error_msg)
  164. return JSONResponse(status_code=500, content={"message": "Error interno del servidor"})
  165. except Exception as e:
  166. error_msg = f"Error creating sale record: {e}"
  167. logger.error(error_msg)
  168. return JSONResponse(status_code=500, content={"message": "Error interno del servidor"})
  169. # Print order
  170. try:
  171. pizza_items = [ Item(name=product.name, price=product.price, quantity=item.quantity, comment=item.comment) for item, product in zip(items, products) if CAT_ITEMS.get(product.type) == Locations.PIZZAS]#type: ignore
  172. burger_items = [ Item(name=product.name, price=product.price, quantity=item.quantity, comment=item.comment) for item, product in zip(items, products) if CAT_ITEMS.get(product.type) == Locations.BURGUER]#type: ignore
  173. bar_items = [ Item(name=product.name, price=product.price, quantity=item.quantity, comment=item.comment) for item, product in zip(items, products) if CAT_ITEMS.get(product.type) == Locations.BAR]#type: ignore
  174. coctelery_items = [ Item(name=product.name, price=product.price, quantity=item.quantity, comment=item.comment) for item, product in zip(items, products) if CAT_ITEMS.get(product.type) == Locations.COCTELERY]#type: ignore
  175. if pizza_items:
  176. ps.print_order(Order(table=table, items=pizza_items, customerName=user.name, totalAmount=order.totalAmount, orderDate=order.orderDate), location=Locations.PIZZAS)
  177. logger.info(f"Order pizza printed successfully for table {table}")
  178. if burger_items:
  179. ps.print_order(Order(table=table, items=burger_items, customerName=user.name, totalAmount=order.totalAmount, orderDate=order.orderDate), location=Locations.BURGUER)
  180. logger.info(f"Order burger printed successfully for table {table}")
  181. if bar_items:
  182. ps.print_order(Order(table=table, items=bar_items, customerName=user.name, totalAmount=order.totalAmount, orderDate=order.orderDate), location=Locations.BAR)
  183. logger.info(f"Order bar printed successfully for table {table}")
  184. if coctelery_items:
  185. ps.print_order(Order(table=table, items=coctelery_items, customerName=user.name, totalAmount=order.totalAmount, orderDate=order.orderDate), location=Locations.COCTELERY)
  186. logger.info(f"Order coctelery printed successfully for table {table}")
  187. logger.info(f"Order printed successfully for table {table}")
  188. except Exception as e:
  189. error_msg = f"Error printing order for table {table}: {e}"
  190. logger.error(error_msg)
  191. return JSONResponse(status_code=500, content={"message": "Error interno del servidor"})
  192. # Don't fail the order for print issues, just log it
  193. logger.info(f"Logging order for table {table} with sale ID {sale}, products= {[(product.name, item.quantity) for product, item in zip(products, items)]}")
  194. logger.info(f"Order processing completed successfully for table {table}, sale ID: {sale}")
  195. return JSONResponse({"message": SuccessResponse.ORDER_SUCCESS, "new_progress": new_progress})