Explorar o código

add history table in shopping cart

latapp hai 9 meses
pai
achega
962dbfa276
Modificáronse 4 ficheiros con 163 adicións e 0 borrados
  1. 36 0
      models/sales.py
  2. 42 0
      public/main/js/service/user.js
  3. 59 0
      public/main/js/utils/shoppingCart.js
  4. 26 0
      routes/sales.py

+ 36 - 0
models/sales.py

@@ -0,0 +1,36 @@
+from typing import List, Optional
+from pydantic import BaseModel
+
+class ItemWeb(BaseModel):
+    id: int
+    quantity: int
+
+class OrderWeb(BaseModel):
+    customerId: int
+    items: List[ItemWeb]
+    totalAmount: float
+    orderDate: str
+    table: int
+
+class Product(BaseModel):
+    """Legacy Product model - use models.items.Product instead"""
+    id: int
+    name: str
+    price: float
+    type: str
+    
+    description: str
+    image: str
+    status: int  # 0: inactive, 1: active
+    quantity: Optional[int] = 1  # Optional quantity for the product
+
+class Sale(BaseModel):
+    """Sale model matching the database schema"""
+    id: int
+    user_id: int
+    total: float
+    fudo_id: str
+    fecha: str
+    table: int
+    user_name: Optional[str] = None
+    user_email: Optional[str] = None

+ 42 - 0
public/main/js/service/user.js

@@ -0,0 +1,42 @@
+import { showError } from "../utils/error.js";
+
+
+async function fetchUserSales(userId, token) {
+  try {
+    const response = await fetch(`/api/sales/user/${userId}`, {
+        headers: {
+            'Content-Type': 'application/json',
+            'Authorization': `Bearer ${token}`
+        }
+    });
+    if (response.status === 404) {
+      showError("No se encontraron ventas para este usuario.");
+      return [];
+    } else if (response.status === 401) {
+      showError("No autorizado. Verifica tu sesión.");
+      throw new Error("Unauthorized access");
+    } else if (response.status === 429) {
+      showError("Demasiados intentos. Intenta más tarde.");
+      throw new Error("Too many requests");
+    } else if (response.status === 500) {
+      showError("Error interno del servidor. Intenta más tarde.");
+      throw new Error("Internal server error");
+    } else if (response.status === 403) {
+      showError("Acceso prohibido. Verifica tus permisos.");
+      throw new Error("Forbidden access");
+    }
+
+    
+    if (response.status !== 200) {
+        showError(response.message);
+      throw new Error(`Error fetching user sales: ${response.statusText}`);
+    }
+    const sales = await response.json();
+    return sales.sales;
+  } catch (error) {
+    console.error('Error fetching user sales:', error);
+    throw error;
+  }
+}
+
+export { fetchUserSales };

+ 59 - 0
public/main/js/utils/shoppingCart.js

@@ -0,0 +1,59 @@
+import { fetchUserSales } from "../service/user.js";
+
+const table = document.getElementById('historyTable');
+const rowTemplate = document.getElementById('historyRowTemplate');
+const cartHistoryTotal = document.getElementById('cartHistoryTotal');
+
+function setHistoryTable(tableData) {
+  if (!tableData || tableData.length === 0) {
+    console.warn("No hay datos para mostrar en el historial de compras.");
+    table.querySelector('tbody').innerHTML = '<tr><td colspan="3" class="text-center text-gray-500">No hay historial de compras.</td></tr>';
+    return;
+  }
+    table.querySelector('tbody').innerHTML = ''; // Clear existing rows
+    tableData.forEach(item => {
+      addHistoryRow(item.quantity, item.productName, item.price);
+    });
+}   
+
+
+function addHistoryRow(quantity, productName, price) {
+  const newRow = rowTemplate.content.cloneNode(true);
+  newRow.querySelector('.list-element-quantity').textContent = quantity;
+  newRow.querySelector('.list-element-name').textContent = productName;
+  newRow.querySelector('.list-element-price').textContent = `$${price.toFixed(2)}`;
+
+    addCartHistoryTotal(price);
+
+  table.querySelector('tbody').appendChild(newRow);
+}
+
+function addCartHistoryTotal(price) {
+  const currentTotal = getHistoryTotal();
+  const newTotal = currentTotal + Number(price);
+  updateCartHistoryTotal(newTotal);
+}
+
+function updateCartHistoryTotal(total) {
+  cartHistoryTotal.textContent = `$${total.toFixed(2)}`;
+}
+
+function getHistoryTotal() {
+    return Number(cartHistoryTotal.textContent.replace(/[$,]/g, ''));
+}
+
+async function setupShoppingCart(userID, userToken, userName) {
+  const name = document.querySelector('#usernameTable');
+  if (name) {
+    name.textContent = `Pedidos de: ${userName}`;
+  }else{
+    console.warn("No se encontró el elemento de nombre en la tabla de historial.");
+  }
+  const sales = await fetchUserSales(userID, userToken);
+  if (sales){
+    setHistoryTable(sales);
+  }
+}
+
+
+export { setupShoppingCart, setHistoryTable, addHistoryRow, updateCartHistoryTotal, getHistoryTotal };

+ 26 - 0
routes/sales.py

@@ -0,0 +1,26 @@
+from csv import Error
+from tkinter import E
+from fastapi.responses import JSONResponse
+from pydantic import BaseModel
+from config.messages import ErrorResponse
+from models import sales
+from services.data_service import SalesDataService
+from fastapi import APIRouter, Depends
+from models.sales import Sale
+sale_data_service = SalesDataService()
+
+
+sales_router = APIRouter()
+
+@sales_router.get("/user/{user_id}", response_model=list[Sale])
+def get_user_sales(user_id: int):
+    sales = sale_data_service.get_by_user(user_id)
+    if not sales:
+        return JSONResponse(
+            status_code=404,
+            content={"message": ErrorResponse.SALE_NOT_FOUND}
+        )
+    return JSONResponse(
+        status_code=200,
+        content={"sales": sales, "message": "Ventas obtenidas correctamente."}
+    )