Răsfoiți Sursa

Deploy desde script deploy.sh

latapp 9 luni în urmă
părinte
comite
65738fd9f0
5 a modificat fișierele cu 65 adăugiri și 15 ștergeri
  1. 4 0
      models/items.py
  2. 2 0
      models/user.py
  3. 1 0
      routes/orders.py
  4. 16 2
      routes/products.py
  5. 42 13
      services/data_service.py

+ 4 - 0
models/items.py

@@ -25,6 +25,10 @@ class Product(BaseModel):
     image: Optional[str] = None
     status: int = 1  # 0: Inactive, 1: Active
     quantity: Optional[int] = 1  # Optional quantity for the product
+    promo_id: Optional[int] = None  # ID of the promotional offer if applicable
+    promo_price: Optional[int] = None  # Promotional price if applicable
+    promo_day: Optional[int] = None  # Day of the week for promo (1-7)
+
 
 class ProductEditRequest(BaseModel):
     """Request model for editing a product"""

+ 2 - 0
models/user.py

@@ -21,6 +21,8 @@ class User(BaseModel):
     pin_hash: str
     kleincoins: str
     created_at: str
+    permissions: Optional[int] = 0  # Default to normal user
+    reward_progress:int
 
 
 class LoginRequest(BaseModel):

+ 1 - 0
routes/orders.py

@@ -72,6 +72,7 @@ async def printer_order(order: OrderWeb):
         logger.error(f"Error: No active sale found for table {table}.")
         raise HTTPException(status_code=404)
     active_sale_id = active_sale_id['id']
+    user_data_service.set_reward_progress(user.id, user.reward_progress + 10)  # Increment reward progress by 10%
     products = product_data_service.get_products([item.id for item in items])
 
     sale = sale_data_service.create(

+ 16 - 2
routes/products.py

@@ -15,6 +15,7 @@ Permission levels:
 # Standard library imports
 from math import prod
 from logging import getLogger
+from time import time
 from typing import Optional
 
 # Third-party imports
@@ -25,7 +26,7 @@ from h11 import Data
 # Local imports
 from auth.security import get_current_user
 from models import user
-from models.items import ProductCreateRequest, ProductEditRequest
+from models.items import Product, ProductCreateRequest, ProductEditRequest
 from services.data_service import DataServiceFactory
 from config.messages import ErrorResponse, SuccessResponse, UserResponse
 
@@ -39,6 +40,16 @@ user_data_service = DataServiceFactory.get_user_service()
 # Create router instance for product-related endpoints
 product_router = APIRouter()
 
+def apply_promo_price(product: Product):
+    """Apply promotional price to a product if applicable."""
+    #dia de la semana 1-7
+    day_of_week = time.localtime().tm_wday + 1  # Convert to 1-7 range
+    if product.promo_id and product.promo_price and product.promo_day == day_of_week:
+        product.price = product.promo_price
+        product.id = product.promo_id
+    return product
+    
+
 @product_router.get("/")
 async def get_products(status: Optional[int] = Query(None), current_user = Depends(get_current_user)):
     """
@@ -51,7 +62,10 @@ async def get_products(status: Optional[int] = Query(None), current_user = Depen
     logger.info("Fetching all products")
     
     # Retrieve all products and convert to dictionary format
-    all_products = list(map(lambda p: p.model_dump(), product_data_service.get_all()))
+    all_products =  product_data_service.get_all()
+    all_products = list(map(apply_promo_price, all_products))
+    all_products = [product.model_dump() for product in all_products]   
+
 
     if status is not None:
         # Filter products by status if provided

+ 42 - 13
services/data_service.py

@@ -34,6 +34,7 @@ ESQUEMA DE BASE DE DATOS SQLITE (data.db)
 - pin_hash     TEXT NOT NULL (encriptado)
 - kleincoins   TEXT NOT NULL (encriptado, valor por defecto "0")
 - created_at   TEXT NOT NULL (fecha de creación en formato ISO 8601)
+- reward_progress INTEGER DEFAULT 0 NOT NULL CHECK (reward_progress >= 0 AND reward_progress <= 100)
 (Guarda la información del usuario con su pin hasheado y kleincoins encriptadas)
 
 2. Tabla: products
@@ -135,10 +136,10 @@ class UserDataService(BaseDataService):
             )
             conn.commit()
 
-            user_id = cursor.fetchone()[0]
+            user_id = cursor.fetchone()
             if user_id:
-                logger.info(f"User added with ID: {user_id}")
-                return user_id
+                logger.info(f"User added with ID: {user_id[0]}")
+                return user_id[0]
             else:
                 logger.error("Failed to add user.")
                 return -1
@@ -164,7 +165,9 @@ class UserDataService(BaseDataService):
                 rut=user[3],
                 pin_hash=fernet.decrypt(user[4].encode()).decode(),
                 kleincoins=fernet.decrypt(user[5].encode()).decode(),
-                created_at=user[6]
+                created_at=user[6],
+                permissions=user[7],
+                reward_progress=user[8]
             ) for user in users
         ]
     
@@ -183,7 +186,9 @@ class UserDataService(BaseDataService):
                 rut=user[3],
                 pin_hash=fernet.decrypt(user[4].encode()).decode(),
                 kleincoins=fernet.decrypt(user[5].encode()).decode(),
-                created_at=user[6]
+                created_at=user[6],
+                permissions=user[7],
+                reward_progress=user[8]
             )
         return None
     
@@ -203,7 +208,9 @@ class UserDataService(BaseDataService):
                 rut=user[3],
                 pin_hash=user[4],
                 kleincoins=fernet.decrypt(user[5].encode()).decode(),
-                created_at=user[6]
+                created_at=user[6],
+                permissions=user[7],
+                reward_progress=user[8]
             )
         return None
     
@@ -226,12 +233,30 @@ class UserDataService(BaseDataService):
         if not result:
             logger.error(f"User with ID {user_id} not found.")
             return 0
+        logger.info(f"userID: {user_id}, permissions: {result[0]}")
         result = result[0]
         conn.close()
         if result:
             return result[0]
         return 0
 
+    def set_reward_progress(self, user_id: int, progress: int) -> bool:
+        """Add progress to user's reward"""
+        conn = self._get_connection()
+        cursor = conn.cursor()
+        try:
+            cursor.execute("UPDATE users SET reward_progress = %s WHERE id = %s", (progress, user_id))
+            conn.commit()
+            success = cursor.rowcount > 0
+            if success:
+                logger.info(f"Reward progress updated for user {user_id}: {progress}")
+            return success
+        except psycopg2.IntegrityError as e:
+            logger.error(f"Failed to update reward progress: {e}")
+            return False
+        finally:
+            conn.close()
+
     def get_by_rut(self, rut: str) -> Optional[User]:
         """Get user by RUT"""
         conn = self._get_connection()
@@ -252,7 +277,9 @@ class UserDataService(BaseDataService):
                 rut=user[3],
                 pin_hash=fernet.decrypt(user[4].encode()).decode(),
                 kleincoins=fernet.decrypt(user[5].encode()).decode(),
-                created_at=user[6]
+                created_at=user[6],
+                permissions=user[7],
+                reward_progress=user[8]
             )
         return None
     #endregion
@@ -356,10 +383,10 @@ class BlacklistDataService(BaseDataService):
         try:
             cursor.execute("INSERT INTO blacklist (user_id) VALUES (%s) RETURNING id", (user_id,))
             conn.commit()
-            blacklist_id = cursor.fetchone()[0]
+            blacklist_id = cursor.fetchone()
             if blacklist_id:
-                logger.info(f"User with ID {user_id} added to blacklist.")
-                return blacklist_id
+                logger.info(f"User with ID {blacklist_id[0]} added to blacklist.")
+                return blacklist_id[0]
             else:
                 logger.error(f"Failed to add user with ID {user_id} to blacklist.")
                 return -1
@@ -487,10 +514,10 @@ class ProductDataService(BaseDataService):
                 (id, name, type, description, price, image, status)
             )
             conn.commit()
-            product_id = cursor.fetchone()[0]
+            product_id = cursor.fetchone()
             if product_id:
-                logger.info(f"Product added with ID: {product_id}")
-                return product_id
+                logger.info(f"Product added with ID: {product_id[0]}")
+                return product_id[0]
             else:
                 logger.error("Failed to add product.")
                 return -1
@@ -1257,6 +1284,8 @@ def initialize_db():
         kleincoins TEXT NOT NULL,
         created_at TEXT NOT NULL,
         permissions INTEGER DEFAULT 0 NOT NULL CHECK (permissions IN (0, 1, 2)) -- 0: Usuario normal, 1: Administrador, 2: Superusuario
+                   
+        reward_progress INTEGER DEFAULT 0 NOT NULL CHECK (reward_progress >= 0 AND reward_progress <= 100) -- Progreso de recompensas
     );
     """)