diff --git a/app/api/v1/routers/AdminCustomerRouter.py b/app/api/v1/routers/AdminCustomerRouter.py index 6434024..0f15ff0 100644 --- a/app/api/v1/routers/AdminCustomerRouter.py +++ b/app/api/v1/routers/AdminCustomerRouter.py @@ -2,7 +2,7 @@ @router AdminCustomerRouter (Backend/app/api/v1/routers/AdminCustomerRouter.py) @purpose CRM Admin endpoint controllers to search, list, and inspect storefront e-commerce customers, addresses, and order history. """ -from fastapi import APIRouter, Depends, HTTPException, status +from fastapi import APIRouter, Depends, HTTPException, status, Query from sqlalchemy.orm import Session from pydantic import BaseModel, EmailStr from typing import List, Optional @@ -59,13 +59,25 @@ class AdminCustomerDetailResponse(BaseModel): @router.get("", response_model=List[AdminCustomerListResponse]) def list_all_customers( + limit: int = Query(100, ge=1, le=500), + offset: int = Query(0, ge=0), + search: Optional[str] = Query(None), current_user: User = Depends(get_current_user), db: Session = Depends(get_db) ): """ - List all registered storefront customers. + List registered storefront customers with safe pagination and search. """ - customers = db.query(EcomCustomer).order_by(EcomCustomer.created_at.desc()).all() + query = db.query(EcomCustomer) + if search: + s = f"%{search}%" + query = query.filter( + (EcomCustomer.email.ilike(s)) | + (EcomCustomer.first_name.ilike(s)) | + (EcomCustomer.last_name.ilike(s)) | + (EcomCustomer.phone.ilike(s)) + ) + customers = query.order_by(EcomCustomer.created_at.desc()).offset(offset).limit(limit).all() return [ AdminCustomerListResponse( customer_id=c.customer_id, diff --git a/app/api/v1/routers/AdminInvoiceRouter.py b/app/api/v1/routers/AdminInvoiceRouter.py index 08f387a..014f81f 100644 --- a/app/api/v1/routers/AdminInvoiceRouter.py +++ b/app/api/v1/routers/AdminInvoiceRouter.py @@ -2,7 +2,7 @@ @router AdminInvoiceRouter (Backend/app/api/v1/routers/AdminInvoiceRouter.py) @purpose CRM Admin endpoint controllers to query, generate, and print standard PDF and 80mm thermal roll GST invoices on-the-fly. """ -from fastapi import APIRouter, Depends, HTTPException, status, Response +from fastapi import APIRouter, Depends, HTTPException, status, Response, Query from sqlalchemy.orm import Session from pydantic import BaseModel from typing import List, Optional @@ -12,7 +12,7 @@ import io import zipfile from app.core.database.db_session import get_db -from app.core.permissions.RoleChecker import get_current_user +from app.core.permissions.RoleChecker import get_current_user, RoleChecker from app.models.UserModel import User from app.models.InvoiceModel import Invoice from app.models.OrderModel import Order, OrderItem @@ -43,21 +43,26 @@ class AdminInvoiceResponse(BaseModel): @router.get("", response_model=List[AdminInvoiceResponse]) def list_all_invoices( + limit: int = Query(100, ge=1, le=500), + offset: int = Query(0, ge=0), current_user: User = Depends(get_current_user), db: Session = Depends(get_db) ): """ - List all generated GST invoices in the system. + List generated GST invoices in the system with safe pagination and batch customer resolution. """ - invoices = db.query(Invoice).order_by(Invoice.created_at.desc()).all() + invoices = db.query(Invoice).order_by(Invoice.created_at.desc()).offset(offset).limit(limit).all() + # Batch load customers to eliminate N+1 queries + cust_ids = list({inv.customer_id for inv in invoices if inv.customer_id}) + customer_map = {} + if cust_ids: + rows = db.query(EcomCustomer.customer_id, EcomCustomer.email).filter(EcomCustomer.customer_id.in_(cust_ids)).all() + customer_map = {r[0]: r[1] for r in rows} + result = [] for inv in invoices: - cust_email = None - customer = db.query(EcomCustomer).filter(EcomCustomer.customer_id == inv.customer_id).first() - if customer: - cust_email = customer.email - + cust_email = customer_map.get(inv.customer_id) pdf_url = f"/api/v1/admin/invoices/{inv.invoice_id}/download" result.append( @@ -185,6 +190,7 @@ def generate_invoice_for_order( @router.get("/{invoice_id}/download") def download_invoice_pdf( invoice_id: str, + current_user: User = Depends(RoleChecker(["Super Admin", "Admin", "Manager", "Accountant"])), db: Session = Depends(get_db) ): """ @@ -223,6 +229,7 @@ def download_invoice_pdf( @router.get("/{invoice_id}/thermal-download") def download_thermal_invoice_pdf( invoice_id: str, + current_user: User = Depends(RoleChecker(["Super Admin", "Admin", "Manager", "Accountant"])), db: Session = Depends(get_db) ): """ @@ -262,9 +269,15 @@ def download_thermal_invoice_pdf( def export_invoices_excel( start_date: Optional[str] = None, end_date: Optional[str] = None, + current_user: User = Depends(RoleChecker(["Super Admin", "Admin", "Manager", "Accountant"])), db: Session = Depends(get_db) ): - invoices = db.query(Invoice).order_by(Invoice.created_at.desc()).all() + query = db.query(Invoice) + if start_date: + query = query.filter(Invoice.created_at >= start_date) + if end_date: + query = query.filter(Invoice.created_at <= end_date) + invoices = query.order_by(Invoice.created_at.desc()).limit(5000).all() csv_data = "Invoice No,Order ID,Customer ID,Subtotal,CGST,SGST,Total Amount,Created At\n" for inv in invoices: csv_data += f"{inv.invoice_no},{inv.order_id},{inv.customer_id},{inv.subtotal},{inv.cgst},{inv.sgst},{inv.total_amount},{inv.created_at}\n" @@ -279,9 +292,15 @@ def export_invoices_excel( def export_invoices_zip( start_date: Optional[str] = None, end_date: Optional[str] = None, + current_user: User = Depends(RoleChecker(["Super Admin", "Admin", "Manager", "Accountant"])), db: Session = Depends(get_db) ): - invoices = db.query(Invoice).order_by(Invoice.created_at.desc()).all() + query = db.query(Invoice) + if start_date: + query = query.filter(Invoice.created_at >= start_date) + if end_date: + query = query.filter(Invoice.created_at <= end_date) + invoices = query.order_by(Invoice.created_at.desc()).limit(5000).all() zip_buffer = io.BytesIO() with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zip_file: diff --git a/app/api/v1/routers/AdminOrderRouter.py b/app/api/v1/routers/AdminOrderRouter.py index 7374994..bc38af3 100644 --- a/app/api/v1/routers/AdminOrderRouter.py +++ b/app/api/v1/routers/AdminOrderRouter.py @@ -23,6 +23,7 @@ from app.services.NotificationGatewayService import NotificationGatewayService from app.schemas.NotificationGateway import EntityNotificationDispatchCreate from app.services.WarrantyService import WarrantyService from app.services.CreditService import CreditService +from app.services.ShiprocketService import shiprocket_service router = APIRouter(prefix="/api/v1/admin/orders", tags=["Admin CRM Customer Orders"]) @@ -68,6 +69,9 @@ class AdminOrderDetailResponse(BaseModel): billing_address_json: Optional[str] = None tracking_number: Optional[str] = None courier_name: Optional[str] = None + shipping_label_url: Optional[str] = None + package_weight: Optional[float] = None + logistics_provider: Optional[str] = None created_at: datetime items: List[OrderItemDetail] history: List[StatusHistorySchema] @@ -85,12 +89,15 @@ class AdminOrderListResponse(BaseModel): coupon_code: Optional[str] = None status: str payment_status: str + shipping_label_url: Optional[str] = None created_at: datetime class StatusUpdatePayload(BaseModel): status: str tracking_number: Optional[str] = None courier_name: Optional[str] = None + package_weight: Optional[float] = None + logistics_provider: Optional[str] = "SHIPROCKET" reason: Optional[str] = None part_numbers_mapping: Optional[Dict[str, List[str]]] = None @@ -142,6 +149,7 @@ def list_all_orders( coupon_code=o.coupon_code, status=o.status, payment_status=o.payment_status, + shipping_label_url=o.shipping_label_url, created_at=o.created_at ) ) @@ -191,6 +199,9 @@ def get_order_details( billing_address_json=order.billing_address_json, tracking_number=order.tracking_number, courier_name=order.courier_name, + shipping_label_url=order.shipping_label_url, + package_weight=float(order.package_weight) if order.package_weight else None, + logistics_provider=order.logistics_provider, created_at=order.created_at, items=[ OrderItemDetail( @@ -234,7 +245,7 @@ def _dispatch_bg_notification(tenant_id: str, payload: EntityNotificationDispatc @router.put("/{order_id}/status") -def update_order_status( +async def update_order_status( order_id: str, payload: StatusUpdatePayload, background_tasks: BackgroundTasks, @@ -243,6 +254,8 @@ def update_order_status( ): """ Transition an order status, record timeline logs, write ledger confirmations/releases, and update tracking coordinates. + Staff can manually set: PENDING, CONFIRMED, READY_FOR_DELIVERY, CANCELLED. + Statuses like SHIPPED, OUT_FOR_DELIVERY, and DELIVERED are strictly managed by Shiprocket webhooks. """ order = db.query(Order).filter(Order.order_id == order_id).first() if not order: @@ -252,7 +265,33 @@ def update_order_status( ) previous_status = order.status - new_status = payload.status + raw_status = payload.status.strip() + + # Normalize status names + if raw_status in ["READY_FOR_DELIVERY", "READY FOR DELIVERY", "Ready for delivery"]: + new_status = "READY_FOR_DELIVERY" + elif raw_status in ["CONFIRMED", "ORDER_CONFIRMED", "Confirmed"]: + new_status = "ORDER_CONFIRMED" + elif raw_status in ["CANCELLED", "Cancelled"]: + new_status = "CANCELLED" + elif raw_status in ["PENDING", "Pending"]: + new_status = "PENDING" + else: + new_status = raw_status.upper() + + # 1. Enforce restriction: Staff cannot manually set carrier-driven statuses + if new_status in ["SHIPPED", "OUT_FOR_DELIVERY", "DELIVERED"]: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"Status '{new_status}' cannot be set manually. It is automatically updated by Shiprocket when the courier collects and delivers the parcel." + ) + + # 2. Enforce restriction: Cannot revert back to PENDING once confirmed + if new_status in ["PENDING", "ORDER_CREATED", "PAYMENT_PENDING"] and previous_status not in ["PENDING", "ORDER_CREATED", "PAYMENT_PENDING"]: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Orders cannot be reverted back to Pending once confirmed." + ) # Transition tracking info if provided if payload.tracking_number: @@ -265,6 +304,35 @@ def update_order_status( if item.item_id in payload.part_numbers_mapping: item.part_numbers = payload.part_numbers_mapping[item.item_id] + # Handle READY_FOR_DELIVERY automated logistics dispatch + if new_status == "READY_FOR_DELIVERY": + order.fulfillment_status = "READY_FOR_DELIVERY" + provider = (payload.logistics_provider or "SHIPROCKET").upper() + weight = float(payload.package_weight or 0.5) + + if provider == "SHIPROCKET": + try: + ship_res = await shiprocket_service.book_and_schedule_pickup( + order=order, + weight_kg=weight, + courier_preference=payload.courier_name + ) + order.tracking_number = ship_res.get("awb_code") + order.courier_name = ship_res.get("courier_name") + order.shipping_label_url = ship_res.get("label_url") + order.package_weight = weight + order.logistics_provider = "SHIPROCKET" + order.pickup_scheduled = bool(ship_res.get("pickup_scheduled", True)) + except Exception as e: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail=f"Shiprocket booking failed: {str(e)}" + ) + else: + order.logistics_provider = "LOCAL_DELIVERY" + order.package_weight = weight + order.shipping_label_url = f"/api/v1/shipping/label/preview/{order.order_id}" + # Set fulfillment status flags if new_status in ["SHIPPED", "DELIVERED"]: order.fulfillment_status = "FULFILLED" @@ -273,8 +341,8 @@ def update_order_status( # --- STOCK CONFIRMATION / RELEASE LOGIC --- - # 1. Transition: ORDER_CREATED/PAYMENT_PENDING -> ORDER_CONFIRMED/PROCESSING/SHIPPED/DELIVERED - if new_status in ["ORDER_CONFIRMED", "PROCESSING", "SHIPPED", "DELIVERED"] and previous_status in ["ORDER_CREATED", "PAYMENT_PENDING"]: + # 1. Transition: ORDER_CREATED/PAYMENT_PENDING/PENDING -> CONFIRMED/READY_FOR_DELIVERY + if new_status in ["ORDER_CONFIRMED", "CONFIRMED", "READY_FOR_DELIVERY", "PROCESSING", "SHIPPED", "DELIVERED"] and previous_status in ["ORDER_CREATED", "PAYMENT_PENDING", "PENDING"]: # Record the physical sale transition in the ledger by subtracting quantity for item in order.items: record_ledger_entry( @@ -400,7 +468,15 @@ def update_order_status( ) ) - return {"message": "Order status updated successfully", "order_id": order_id, "new_status": order.status} + return { + "message": "Order status updated successfully", + "order_id": order_id, + "new_status": order.status, + "shipping_label_url": order.shipping_label_url, + "tracking_number": order.tracking_number, + "courier_name": order.courier_name, + "pickup_scheduled": order.pickup_scheduled + } # --- Manual Order Creation Schemas --- diff --git a/app/api/v1/routers/AuthenticationRouter.py b/app/api/v1/routers/AuthenticationRouter.py index ba7a78f..20c65c8 100644 --- a/app/api/v1/routers/AuthenticationRouter.py +++ b/app/api/v1/routers/AuthenticationRouter.py @@ -11,7 +11,7 @@ import ulid from app.core.database.db_session import get_db from app.core.config.Config import settings from app.core.Token import create_access_token -from app.utils.Hash_util import hash_password, verify_password +from app.utils.Hash_util import hash_password, verify_password, hash_token from app.repositories.user_repository import user_repository from app.repositories.session_repository import session_repository from app.models.UserSessionModel import UserSession @@ -131,7 +131,7 @@ def login( longitude=data.longitude, location_name=data.location_name, device_fingerprint=data.device_fingerprint, - refresh_token=raw_refresh, + refresh_token=hash_token(raw_refresh), access_token_id=session_id, # Match token references expires_at=datetime.now(timezone.utc) + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS), is_active=True @@ -140,7 +140,7 @@ def login( db.add(session_entry) db.commit() - # 6. Set response cookie and header + # 6. Set response cookie (strictly HttpOnly to prevent JavaScript access) response.set_cookie( "refresh_token", raw_refresh, @@ -152,7 +152,7 @@ def login( return { "access_token": access_token, - "refresh_token": raw_refresh, + "refresh_token": None, "token_type": "bearer" } @@ -207,7 +207,7 @@ def refresh( longitude=session.longitude, location_name=session.location_name, device_fingerprint=session.device_fingerprint, - refresh_token=new_refresh, + refresh_token=hash_token(new_refresh), access_token_id=new_session_id, expires_at=datetime.now(timezone.utc) + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS), is_active=True @@ -226,7 +226,7 @@ def refresh( return { "access_token": new_access, - "refresh_token": new_refresh, + "refresh_token": None, "token_type": "bearer" } @@ -311,7 +311,7 @@ def oauth2_token( browser=browser_name, operating_system=os_name, ip_address=get_client_ip(request), - refresh_token=raw_refresh, + refresh_token=hash_token(raw_refresh), access_token_id=session_id, expires_at=datetime.now(timezone.utc) + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS), is_active=True @@ -330,7 +330,7 @@ def oauth2_token( return { "access_token": access_token, - "refresh_token": raw_refresh, + "refresh_token": None, "token_type": "bearer" } diff --git a/app/api/v1/routers/CartRouter.py b/app/api/v1/routers/CartRouter.py index fa92969..2a41650 100644 --- a/app/api/v1/routers/CartRouter.py +++ b/app/api/v1/routers/CartRouter.py @@ -5,7 +5,7 @@ from fastapi import APIRouter, Depends, HTTPException, status from pydantic import BaseModel from typing import List, Optional, Any -from sqlalchemy.orm import Session +from sqlalchemy.orm import Session, joinedload import ulid import json @@ -14,7 +14,7 @@ from app.api.v1.routers.CustomerProfileRouter import get_current_customer from app.models.EcomCustomerModel import EcomCustomer from app.models.CartModel import Cart from app.models.ProductModel import ProductVariant -from app.services.InventoryService import get_available_stock +from app.services.InventoryService import get_available_stock, get_available_stock_map router = APIRouter(prefix="/api/v1/cart", tags=["Shopping Cart"]) @@ -97,12 +97,27 @@ def _enrich_and_totals( ) -> dict: enriched = [] subtotal = 0.0 - for item in items: - variant_id = item.get("variant_id") + + # 1. Collect all variant IDs to batch load and eliminate N+1 queries + valid_items = [item for item in items if item.get("variant_id") and int(item.get("qty", 1)) > 0] + variant_ids = list({item["variant_id"] for item in valid_items}) + + variant_map = {} + stock_map = {} + if variant_ids: + variants = ( + db.query(ProductVariant) + .options(joinedload(ProductVariant.product)) + .filter(ProductVariant.variant_id.in_(variant_ids)) + .all() + ) + variant_map = {v.variant_id: v for v in variants} + stock_map = get_available_stock_map(variant_ids, db) + + for item in valid_items: + variant_id = item["variant_id"] qty = int(item.get("qty", 1)) - if qty <= 0: - continue - variant = db.query(ProductVariant).filter(ProductVariant.variant_id == variant_id).first() + variant = variant_map.get(variant_id) if not variant: continue unit_price = float(variant.price) @@ -116,7 +131,7 @@ def _enrich_and_totals( "product_name": product_name, "sku": variant.sku, "total_price": round(line_total, 2), - "available_stock": get_available_stock(variant_id, db), + "available_stock": stock_map.get(variant_id, 0), }) from app.services.DeliveryService import DeliveryService diff --git a/app/api/v1/routers/CatalogRouter.py b/app/api/v1/routers/CatalogRouter.py index b7ffb4b..0348576 100644 --- a/app/api/v1/routers/CatalogRouter.py +++ b/app/api/v1/routers/CatalogRouter.py @@ -73,8 +73,46 @@ def _variant_ids_from_serialized(products: List[Dict[str, Any]]) -> List[str]: def attach_available_stock(products: List[Dict[str, Any]], db: Session) -> List[Dict[str, Any]]: stock_map = get_available_stock_map(_variant_ids_from_serialized(products), db) for product in products: + # 1. Resolve canonical thumbnail for parent product + prod_thumbnail = product.get("thumbnail_url") + if not prod_thumbnail: + for img in product.get("images") or []: + if (img.get("is_primary") or img.get("is_banner")) and img.get("image_url"): + prod_thumbnail = img["image_url"] + break + if not prod_thumbnail and product.get("images"): + prod_thumbnail = product["images"][0].get("image_url") + if not prod_thumbnail: + for v in product.get("variants") or []: + for v_img in v.get("images") or []: + if v_img.get("is_primary") and v_img.get("image_url"): + prod_thumbnail = v_img["image_url"] + break + if prod_thumbnail: + break + if not prod_thumbnail: + for v in product.get("variants") or []: + if v.get("images") and v["images"][0].get("image_url"): + prod_thumbnail = v["images"][0]["image_url"] + break + + product["thumbnail_url"] = prod_thumbnail + + # 2. Attach available stock and canonical thumbnail for each variant for variant in product.get("variants") or []: variant["available_stock"] = stock_map.get(variant.get("variant_id"), 0) + v_thumbnail = variant.get("thumbnail_url") + if not v_thumbnail: + for v_img in variant.get("images") or []: + if v_img.get("is_primary") and v_img.get("image_url"): + v_thumbnail = v_img["image_url"] + break + if not v_thumbnail and variant.get("images"): + v_thumbnail = variant["images"][0].get("image_url") + if not v_thumbnail: + v_thumbnail = prod_thumbnail + variant["thumbnail_url"] = v_thumbnail + return products @@ -597,8 +635,13 @@ def get_all_repair_variants(db: Session = Depends(get_db)): # ================= STOCK LEDGER & MANUAL ADJUSTMENTS ================= @router.get("/stock-movements/history", response_model=List[StockMovementResponse]) -def get_stock_movements_history(db: Session = Depends(get_db), current_user: User = Depends(RoleChecker(["Super Admin", "Admin"]))): - return db.execute(select(StockMovement).order_by(StockMovement.created_at.desc())).scalars().all() +def get_stock_movements_history( + limit: int = Query(100, ge=1, le=500), + offset: int = Query(0, ge=0), + db: Session = Depends(get_db), + current_user: User = Depends(RoleChecker(["Super Admin", "Admin"])) +): + return db.execute(select(StockMovement).order_by(StockMovement.created_at.desc()).offset(offset).limit(limit)).scalars().all() @router.post("/stock-movements/adjust", response_model=StockMovementResponse, status_code=status.HTTP_201_CREATED) def create_manual_stock_adjustment( @@ -661,8 +704,13 @@ def create_purchase_order(data: PurchaseOrderCreate, db: Session = Depends(get_d return po @router.get("/purchase-orders/all", response_model=List[PurchaseOrderResponse]) -def get_all_purchase_orders(db: Session = Depends(get_db), current_user: User = Depends(RoleChecker(["Super Admin", "Admin"]))): - return db.execute(select(PurchaseOrder)).scalars().all() +def get_all_purchase_orders( + limit: int = Query(100, ge=1, le=500), + offset: int = Query(0, ge=0), + db: Session = Depends(get_db), + current_user: User = Depends(RoleChecker(["Super Admin", "Admin"])) +): + return db.execute(select(PurchaseOrder).order_by(PurchaseOrder.created_at.desc()).offset(offset).limit(limit)).scalars().all() @router.post("/purchase-orders/{po_id}/receive", response_model=PurchaseOrderResponse) def receive_purchase_order_items( @@ -758,6 +806,8 @@ def get_all_products( selectinload(Product.variants).selectinload(ProductVariant.attributes), selectinload(Product.variants).selectinload(ProductVariant.images), selectinload(Product.images), + selectinload(Product.brand), + selectinload(Product.category), ) ) stmt = apply_product_search(stmt, search) @@ -795,22 +845,25 @@ def get_products( rating: Optional[float] = Query(None), discount: Optional[float] = Query(None), cursor: Optional[str] = Query(None), + expand_variants: bool = Query(False, description="Expand each active variant into an individual card for search & SEO"), db: Session = Depends(get_db) ): import base64 from app.core.database.cache_manager import cache # Generate Cache Key based on all parameters (caching for 5 min / 300s) - cache_key = f"catalog:products:page={page}:limit={limit}:search={search}:category={category}:brand={brand}:device={device}:series={series}:model={model}:pmin={price_min}:pmax={price_max}:sort={sort}:avail={availability}:rat={rating}:disc={discount}:cursor={cursor}" + cache_key = f"catalog:products:page={page}:limit={limit}:search={search}:category={category}:brand={brand}:device={device}:series={series}:model={model}:pmin={price_min}:pmax={price_max}:sort={sort}:avail={availability}:rat={rating}:disc={discount}:cursor={cursor}:exp_var={1 if expand_variants else 0}" cached_data = cache.get(cache_key) - if cached_data and not (category or search or brand or model or series): + if cached_data: return cached_data # Base Query with Eager Loading (eliminates N+1 query bottleneck) stmt = select(Product).options( + selectinload(Product.variants).selectinload(ProductVariant.attributes).selectinload(VariantAttribute.attribute_type), selectinload(Product.variants).selectinload(ProductVariant.images), - selectinload(Product.images) + selectinload(Product.images), + selectinload(Product.brand), ).where(Product.status == "active") # Dynamic Filtering @@ -907,17 +960,36 @@ def get_products( stock_map = get_available_stock_map(page_variant_ids, db) # Map to lightweight DTO schema - mapped_products = [] - for p in products_list: - first_var = p.variants[0] if p.variants else None - price = first_var.price if first_var else Decimal("0.0") - compare_price = first_var.compare_price if first_var else None - - # Calculate discount - discount_percent = 0 - if price and compare_price and compare_price > price: - discount_percent = int(((compare_price - price) / compare_price) * 100) - + def _variant_label(v) -> str: + """Build a human-readable variant label from its attributes (e.g. 'Moonlight Silver').""" + vals = [] + for a in (v.attributes or []): + # attribute_code is resolved via the joined AttributeType row + code = ( + getattr(getattr(a, "attribute_type", None), "code", None) + or getattr(a, "attribute_code", "") + or "" + ).strip().lower() + # Skip non-display dimensions that would duplicate the parent name + if code in ("parent_media_key", "media_key", "barcode", "sku", "warranty_months", "country_of_origin") or code.startswith("parent_"): + continue + if a.attribute_value and a.attribute_value not in vals: + if code == "color": + vals.insert(0, a.attribute_value) + else: + vals.append(a.attribute_value) + return " ".join(vals) + + def _variant_image(v, product) -> Optional[str]: + """Variant-specific image with product-level fallback.""" + if v.images: + return v.images[0].image_url + if product.images: + banner_img = next((img.image_url for img in product.images if img.is_banner), product.images[0].image_url) + return banner_img + return None + + def _build_card(p, first_var, price, compare_price, discount_percent, stock_count) -> ProductCardResponse: thumbnail_url = None if p.images: banner_img = next((img.image_url for img in p.images if img.is_banner), p.images[0].image_url) @@ -925,7 +997,7 @@ def get_products( elif first_var and first_var.images: thumbnail_url = first_var.images[0].image_url - mapped_products.append(ProductCardResponse( + return ProductCardResponse( product_id=p.product_id, category_id=p.category_id, slug=p.slug, @@ -935,11 +1007,53 @@ def get_products( compare_price=compare_price, discount_percent=discount_percent, rating=p.rating if hasattr(p, "rating") and p.rating is not None else 4.8, - stock_count=stock_map.get(first_var.variant_id, 0) if first_var else 0, + stock_count=stock_count, first_variant_id=first_var.variant_id if first_var else None, badge=p.badge if hasattr(p, "badge") else None, brand_name=p.brand.name if p.brand else None - )) + ) + + mapped_products = [] + for p in products_list: + # Only consider active variants for display + active_variants = [v for v in (p.variants or []) if getattr(v, "status", "active") == "active"] + first_var = active_variants[0] if active_variants else (p.variants[0] if p.variants else None) + base_price = first_var.price if first_var else Decimal("0.0") + base_compare = first_var.compare_price if first_var else None + + # Calculate discount + base_discount = 0 + if base_price and base_compare and base_compare > base_price: + base_discount = int(((base_compare - base_price) / base_compare) * 100) + + if expand_variants and len(active_variants) > 1: + # Sunsky-style: one card per variant with its own image, SKU, price and deep link + for v in active_variants: + price = v.price if v.price is not None else base_price + compare_price = v.compare_price if v.compare_price is not None else base_compare + discount_percent = base_discount + if price and compare_price and compare_price > price: + discount_percent = int(((compare_price - price) / compare_price) * 100) + + label = _variant_label(v) + card = _build_card( + p, v, price, compare_price, discount_percent, + stock_map.get(v.variant_id, 0) + ) + if label: + card.name = f"{p.name} - {label}" + card.variant_sku = v.sku + card.variant_name = label or None + card.variant_url = f"/products/{p.slug}?variant={v.sku}" + var_img = _variant_image(v, p) + if var_img: + card.thumbnail_url = var_img + mapped_products.append(card) + else: + mapped_products.append(_build_card( + p, first_var, base_price, base_compare, base_discount, + stock_map.get(first_var.variant_id, 0) if first_var else 0 + )) # Generate next cursor if there are more products next_cursor = None @@ -955,7 +1069,7 @@ def get_products( products=mapped_products ) - cache.set(cache_key, response_payload.model_dump(), ttl_seconds=30) + cache.set(cache_key, response_payload.model_dump(), ttl_seconds=cache.TTL_PRODUCTS) return response_payload @router.get("/products/detail/{slug}", response_model=Dict[str, Any]) @@ -1002,6 +1116,12 @@ def get_product_detail_by_slug(slug: str, db: Session = Depends(get_db)): related = db.execute( select(Product) + .options( + selectinload(Product.variants).selectinload(ProductVariant.attributes), + selectinload(Product.variants).selectinload(ProductVariant.images), + selectinload(Product.images), + selectinload(Product.brand), + ) .where(Product.category_id == product.category_id, Product.product_id != product.product_id) .limit(4) ).scalars().all() @@ -1034,7 +1154,7 @@ def get_product_detail_by_slug(slug: str, db: Session = Depends(get_db)): ] } - cache.set(cache_key, response_payload, ttl_seconds=30) + cache.set(cache_key, response_payload, ttl_seconds=cache.TTL_PRODUCTS) return response_payload diff --git a/app/api/v1/routers/CrmTaskCalendarRouter.py b/app/api/v1/routers/CrmTaskCalendarRouter.py index cd62358..759a0b7 100644 --- a/app/api/v1/routers/CrmTaskCalendarRouter.py +++ b/app/api/v1/routers/CrmTaskCalendarRouter.py @@ -4,6 +4,8 @@ from typing import List, Optional from datetime import datetime from app.core.database.db_session import get_db +from app.core.permissions.RoleChecker import get_current_user +from app.models.UserModel import User from app.schemas.Crm import ( CrmTaskCreate, CrmTaskUpdate, CrmTaskResponse, CrmCalendarEventCreate, CrmCalendarEventUpdate, CrmCalendarEventResponse @@ -20,7 +22,8 @@ def get_crm_tasks( assignee_id: Optional[str] = Query(None), entity_type: Optional[str] = Query(None), entity_id: Optional[str] = Query(None), - db: Session = Depends(get_db) + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user), ): return CrmTaskCalendarService.list_tasks( db, location_id=location_id, status=status, assignee_id=assignee_id, @@ -30,7 +33,8 @@ def get_crm_tasks( @router.post("/tasks", response_model=CrmTaskResponse, status_code=status.HTTP_201_CREATED) def create_crm_task( payload: CrmTaskCreate, - db: Session = Depends(get_db) + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user), ): return CrmTaskCalendarService.create_task(db, payload) @@ -38,7 +42,8 @@ def create_crm_task( def update_crm_task( task_id: str, payload: CrmTaskUpdate, - db: Session = Depends(get_db) + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user), ): task = CrmTaskCalendarService.update_task(db, task_id, payload) if not task: @@ -48,7 +53,8 @@ def update_crm_task( @router.delete("/tasks/{task_id}") def delete_crm_task( task_id: str, - db: Session = Depends(get_db) + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user), ): success = CrmTaskCalendarService.delete_task(db, task_id) if not success: @@ -62,7 +68,8 @@ def get_calendar_events( location_id: Optional[str] = Query(None), start_from: Optional[datetime] = Query(None), end_until: Optional[datetime] = Query(None), - db: Session = Depends(get_db) + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user), ): return CrmTaskCalendarService.list_calendar_events( db, location_id=location_id, start_from=start_from, end_until=end_until @@ -71,7 +78,8 @@ def get_calendar_events( @router.post("/calendar", response_model=CrmCalendarEventResponse, status_code=status.HTTP_201_CREATED) def create_calendar_event( payload: CrmCalendarEventCreate, - db: Session = Depends(get_db) + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user), ): return CrmTaskCalendarService.create_calendar_event(db, payload) @@ -79,7 +87,8 @@ def create_calendar_event( def update_calendar_event( event_id: str, payload: CrmCalendarEventUpdate, - db: Session = Depends(get_db) + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user), ): event = CrmTaskCalendarService.update_calendar_event(db, event_id, payload) if not event: @@ -89,7 +98,8 @@ def update_calendar_event( @router.delete("/calendar/{event_id}") def delete_calendar_event( event_id: str, - db: Session = Depends(get_db) + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user), ): success = CrmTaskCalendarService.delete_calendar_event(db, event_id) if not success: diff --git a/app/api/v1/routers/CustomerAuthRouter.py b/app/api/v1/routers/CustomerAuthRouter.py index 1332a22..af35bc3 100644 --- a/app/api/v1/routers/CustomerAuthRouter.py +++ b/app/api/v1/routers/CustomerAuthRouter.py @@ -8,6 +8,10 @@ from typing import Optional from datetime import datetime, timedelta, timezone import ulid import requests +import os +import time +import hmac +import hashlib from sqlalchemy.orm import Session from google.oauth2 import id_token from google.auth.transport import requests as google_requests @@ -238,6 +242,14 @@ def register_customer(payload: RegisterRequest, response: Response, request: Req detail="Email already registered" ) + if payload.phone: + existing_phone = db.query(EcomCustomer).filter(EcomCustomer.phone == payload.phone).first() + if existing_phone: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail="Phone number already registered" + ) + customer = EcomCustomer( customer_id=str(ulid.ULID()), email=payload.email, @@ -321,6 +333,33 @@ def login_customer(payload: LoginRequest, response: Response, request: Request, return issue_tokens(db, customer, response, user_agent=user_agent, ip_address=ip_address) +def verify_google_oauth_state(state: str) -> bool: + """Cryptographic validation of Google OAuth anti-CSRF state token.""" + try: + clean_state = state.strip().strip('"').strip("'") + parts = clean_state.split(":") + if len(parts) != 3: + return False + nonce, ts_str, sig = parts + ts = int(ts_str) + # 30-minute validity window with graceful clock-skew tolerance + if abs(time.time() - ts) > 1800: + return False + expected_data = f"{nonce}:{ts_str}" + expected_sig = hmac.new(settings.SECRET_KEY.encode(), expected_data.encode(), hashlib.sha256).hexdigest() + return hmac.compare_digest(sig, expected_sig) + except Exception: + return False + +@router.get("/google/state") +def get_google_oauth_state(): + """Generates an HMAC-signed CSRF state token for Google OAuth.""" + nonce = os.urandom(16).hex() + ts_str = str(int(time.time())) + data = f"{nonce}:{ts_str}" + sig = hmac.new(settings.SECRET_KEY.encode(), data.encode(), hashlib.sha256).hexdigest() + return {"state": f"{data}:{sig}"} + @router.post("/google", response_model=TokenResponse) @limiter.limit("10/minute") def google_oauth_callback( @@ -333,11 +372,11 @@ def google_oauth_callback( Google OAuth 2.0 Authorization Code flow callback. Exchanges code for Google identity, checks policy, and creates session. """ - # CSRF check: validate state token - if not payload.state or len(payload.state) < 10: + # CSRF check: validate cryptographically signed state token + if not payload.state or not verify_google_oauth_state(payload.state): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, - detail="Invalid state token (CSRF check failed)" + detail="Invalid or expired OAuth state token (CSRF check failed)" ) # Validate custom header to verify request came from the client application diff --git a/app/api/v1/routers/CustomerProfileRouter.py b/app/api/v1/routers/CustomerProfileRouter.py index 9b6f026..75418e2 100644 --- a/app/api/v1/routers/CustomerProfileRouter.py +++ b/app/api/v1/routers/CustomerProfileRouter.py @@ -100,6 +100,17 @@ def update_customer_profile( """ Update profile details for the logged-in customer. """ + if payload.phone and payload.phone != customer.phone: + existing_phone = db.query(EcomCustomer).filter( + EcomCustomer.phone == payload.phone, + EcomCustomer.customer_id != customer.customer_id + ).first() + if existing_phone: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail="Phone number already in use by another account" + ) + customer.first_name = payload.first_name customer.last_name = payload.last_name customer.phone = payload.phone diff --git a/app/api/v1/routers/FileRouter.py b/app/api/v1/routers/FileRouter.py index 24a105d..f1ad406 100644 --- a/app/api/v1/routers/FileRouter.py +++ b/app/api/v1/routers/FileRouter.py @@ -63,6 +63,7 @@ async def upload_file( # 3b. Real Magic Byte Verification for Video files if ext in (".mp4", ".webm", ".mov", ".avi", ".mkv"): + is_valid_video = False header = file_bytes[:32] if b"ftyp" in header or b"moov" in header: # MP4 / MOV is_valid_video = True @@ -71,16 +72,42 @@ async def upload_file( elif header.startswith(b"RIFF") and b"AVI " in file_bytes[:16]: # AVI is_valid_video = True - if not is_valid_video: raise HTTPException( status_code=400, detail=f"File '{file.filename}' failed video media inspection. Invalid video magic header." ) + # 3c. Entity Type & Entity ID Sanitization (Path Traversal Guard) + ALLOWED_ENTITY_TYPES = { + "service_job", "product", "category", "brand", "user", + "review", "cms", "migration", "general", "invoices", "orders" + } + clean_entity_type = entity_type.strip().lower() + if clean_entity_type not in ALLOWED_ENTITY_TYPES: + raise HTTPException( + status_code=400, + detail=f"Invalid entity_type '{entity_type}'. Allowed types: {', '.join(sorted(ALLOWED_ENTITY_TYPES))}" + ) + + import re + clean_entity_id = entity_id.strip() + if not re.match(r"^[a-zA-Z0-9_\-]+$", clean_entity_id) or ".." in clean_entity_id: + raise HTTPException( + status_code=400, + detail="Invalid entity_id format. Must only contain alphanumeric characters, hyphens, or underscores." + ) + # 4. Generate 26-char canonical ULID file_id = str(ulid.ULID()) - folder_path = UPLOADS_DIR / entity_type / entity_id + folder_path = (UPLOADS_DIR / clean_entity_type / clean_entity_id).resolve() + uploads_root = UPLOADS_DIR.resolve() + + try: + folder_path.relative_to(uploads_root) + except ValueError: + raise HTTPException(status_code=400, detail="Path traversal attempt detected.") + folder_path.mkdir(parents=True, exist_ok=True) RAW_UPLOADS_DIR.mkdir(parents=True, exist_ok=True) @@ -128,7 +155,7 @@ async def upload_file( img.save(bio, format="WEBP", quality=webp_quality) with open(webp_full, "wb") as f: f.write(bio.getvalue()) - w_path = f"/uploads/{entity_type}/{entity_id}/{file_id}.webp" + w_path = f"/uploads/{clean_entity_type}/{clean_entity_id}/{file_id}.webp" # Helper for size variants def save_variant(target_w: int, suffix: str) -> str: @@ -144,7 +171,7 @@ async def upload_file( r_img.save(v_bio, format="WEBP", quality=80) with open(var_full, "wb") as f: f.write(v_bio.getvalue()) - return f"/uploads/{entity_type}/{entity_id}/{file_id}_{suffix}.webp" + return f"/uploads/{clean_entity_type}/{clean_entity_id}/{file_id}_{suffix}.webp" t_path = save_variant(300, "thumbnail") m_path = save_variant(800, "medium") @@ -175,7 +202,7 @@ async def upload_file( stored_full = folder_path / stored_name with open(stored_full, "wb") as f: f.write(file_bytes) - webp_path_rel = f"/uploads/{entity_type}/{entity_id}/{stored_name}" + webp_path_rel = f"/uploads/{clean_entity_type}/{clean_entity_id}/{stored_name}" # 6. Save metadata to DB new_upload = FileUpload( diff --git a/app/api/v1/routers/IntegrationRouter.py b/app/api/v1/routers/IntegrationRouter.py index 41ccea9..04da58f 100644 --- a/app/api/v1/routers/IntegrationRouter.py +++ b/app/api/v1/routers/IntegrationRouter.py @@ -6,12 +6,34 @@ from sqlalchemy.orm import Session from app.core.database.db_session import get_db from app.models.UserModel import User -from app.core.permissions.RoleChecker import get_current_user +from app.core.permissions.RoleChecker import get_current_user, RoleChecker from app.services.IntegrationService import IntegrationService +import urllib.parse +import ipaddress logger = logging.getLogger(__name__) -router = APIRouter(prefix="/api/v1/integrations", tags=["Integrations Hub"]) +router = APIRouter( + prefix="/api/v1/integrations", + tags=["Integrations Hub"], + dependencies=[Depends(RoleChecker(["Super Admin", "Admin"]))] +) + +def validate_outbound_url(url: str) -> str: + """SSRF Guard: Rejects loopback, private RFC1918 subnets, and non-HTTP protocols.""" + parsed = urllib.parse.urlparse(url) + if parsed.scheme not in ("http", "https"): + raise HTTPException(status_code=400, detail="Only HTTP/HTTPS URLs are allowed") + hostname = (parsed.hostname or "").lower() + if not hostname or hostname in ("localhost", "127.0.0.1", "0.0.0.0"): + raise HTTPException(status_code=400, detail="Outbound requests to localhost/loopback are forbidden") + try: + ip = ipaddress.ip_address(hostname) + if ip.is_private or ip.is_loopback or ip.is_reserved or ip.is_link_local: + raise HTTPException(status_code=400, detail="Outbound requests to private/internal network addresses are forbidden") + except ValueError: + pass + return url # ============================================================================== # Pydantic Request Models @@ -152,6 +174,7 @@ def save_wati_credentials( db: Session = Depends(get_db), current_user: User = Depends(get_current_user) ): + validate_outbound_url(payload.api_endpoint) creds = IntegrationService.get_wati_credentials(db) if creds.get("is_locked_by_config"): raise HTTPException( @@ -166,6 +189,7 @@ def test_wati( payload: WatiTestRequest, current_user: User = Depends(get_current_user) ): + validate_outbound_url(payload.api_endpoint) return IntegrationService.test_wati_connection(payload.api_endpoint, payload.api_token) @router.get("/wati/templates") diff --git a/app/api/v1/routers/MigrationRouter.py b/app/api/v1/routers/MigrationRouter.py index 2704efd..fdd3650 100644 --- a/app/api/v1/routers/MigrationRouter.py +++ b/app/api/v1/routers/MigrationRouter.py @@ -51,28 +51,8 @@ UPLOAD_DIR = str(backend_root / "uploads" / "migrations") os.makedirs(UPLOAD_DIR, exist_ok=True) # ----------------------------------------------------------------------------- -# Background Worker Daemon Loop +# Background Worker Daemon Loop - Controlled centrally via main.py ENABLE_MIGRATION_WORKER # ----------------------------------------------------------------------------- -def worker_daemon_loop(): - worker = MigrationWorker() - while True: - try: - db = SessionLocal() - try: - claimed = worker.claim_next_job(db) - if claimed: - job_id, lease_ver = claimed - worker.process_job(job_id, lease_ver) - finally: - db.close() - except Exception as e: - print(f"[WorkerDaemon] Error in worker loop: {e}") - time_to_sleep = 2.0 - import time - time.sleep(time_to_sleep) - -_worker_thread = threading.Thread(target=worker_daemon_loop, daemon=True) -_worker_thread.start() # ----------------------------------------------------------------------------- # Endpoints @@ -381,19 +361,21 @@ async def upload_migration_file( batch_type: str = Form("PRODUCTS"), import_mode: str = Form("UPSERT"), media_structure: str = Form("AUTO"), - user_id: str = Form("admin-user-01"), + current_user: Any = Depends(RoleChecker(["Super Admin", "Admin"])), db: Session = Depends(get_db) ): """ 64KB Streamed Upload Endpoint. Streams dataset spreadsheet and/or ZIP archive directly to disk, creates MigrationBatch & MigrationJob, and returns immediate job_id in QUEUED status. + Guarded with role authentication and directory traversal protection. """ + import re if not file and not media_file: raise HTTPException(status_code=400, detail="Please upload a dataset file (.xlsx/.csv) or media ZIP archive (.zip).") batch_id = str(uuid.uuid4()) job_id = str(uuid.uuid4()) - job_dir = StorageManager.get_job_dir(job_id) + job_dir = os.path.abspath(StorageManager.get_job_dir(job_id)) # Save job configuration including media_structure (AUTO vs FLAT) StorageManager.save_job_config(job_id, {"media_structure": media_structure, "import_mode": import_mode}) @@ -401,7 +383,7 @@ async def upload_migration_file( batch = MigrationBatch( id=batch_id, batch_type=BatchTypeEnum(batch_type) if batch_type in BatchTypeEnum.__members__ else BatchTypeEnum.PRODUCTS, - user_id=user_id, + user_id=getattr(current_user, "user_id", "admin"), import_mode=ImportModeEnum(import_mode) if import_mode in ImportModeEnum.__members__ else ImportModeEnum.UPSERT, status=BatchStatusEnum.PENDING ) @@ -411,17 +393,35 @@ async def upload_migration_file( file_format = "CSV" if file: - file_name = file.filename - ext = os.path.splitext(file.filename)[1].lower().replace(".", "") + raw_name = os.path.basename(file.filename or "dataset.csv") + clean_name = re.sub(r"[^a-zA-Z0-9._\-]", "_", raw_name) + ext = os.path.splitext(clean_name)[1].lower().replace(".", "") + if ext not in ("csv", "xlsx", "xls"): + raise HTTPException(status_code=400, detail="Unsupported dataset file format. Use .xlsx or .csv") + + dataset_dir = os.path.abspath(os.path.join(job_dir, "dataset")) + dataset_dest = os.path.abspath(os.path.join(dataset_dir, clean_name)) + if not dataset_dest.startswith(dataset_dir + os.sep) and dataset_dest != dataset_dir: + raise HTTPException(status_code=400, detail="Path traversal attempt in dataset filename") + + file_name = clean_name file_format = ext.upper() - dataset_dest = os.path.join(job_dir, "dataset", file.filename) await StorageManager.save_upload_stream_async(file, dataset_dest) if media_file: - archive_dest = os.path.join(job_dir, "archives", media_file.filename) + raw_archive = os.path.basename(media_file.filename or "media.zip") + clean_archive = re.sub(r"[^a-zA-Z0-9._\-]", "_", raw_archive) + if not clean_archive.lower().endswith(".zip"): + raise HTTPException(status_code=400, detail="Media archive must be a .zip file") + + archive_dir = os.path.abspath(os.path.join(job_dir, "archives")) + archive_dest = os.path.abspath(os.path.join(archive_dir, clean_archive)) + if not archive_dest.startswith(archive_dir + os.sep) and archive_dest != archive_dir: + raise HTTPException(status_code=400, detail="Path traversal attempt in archive filename") + await StorageManager.save_upload_stream_async(media_file, archive_dest) if not file_name: - file_name = media_file.filename + file_name = clean_archive file_format = "ZIP" job = MigrationJob( @@ -772,11 +772,58 @@ def get_job_telemetry(job_id: str, db: Session = Depends(get_db)): "error_message": job.error_message } +@router.post("/sse-ticket") +def create_sse_ticket( + current_user: Any = Depends(RoleChecker(["Super Admin", "Admin"])), +): + """ + Issues a short-lived (30-second) single-use authorization ticket for EventSource SSE streaming, + allowing browser EventSource to authenticate without exposing long-lived JWTs in URL query parameters. + """ + from app.core.database.cache_manager import cache + ticket_id = f"sse_{uuid.uuid4().hex}" + user_id = getattr(current_user, "user_id", "admin") + cache.set(f"sse_ticket:{ticket_id}", user_id, ttl_seconds=30) + return {"ticket": ticket_id, "expires_in": 30} + + @router.get("/jobs/{job_id}/stream") -def stream_job_telemetry(job_id: str): +def stream_job_telemetry( + job_id: str, + ticket: Optional[str] = None, + token: Optional[str] = None, +): """ Streams real-time Server-Sent Events (SSE) telemetry data for a migration job. + Authenticates via single-use 30s SSE ticket (preferred) or token fallback. """ + from app.core.database.cache_manager import cache + from app.core.Token import verify_access_token + + is_authenticated = False + + # 1. Check single-use SSE ticket (burn immediately upon first validation) + if ticket: + cached_user = cache.get(f"sse_ticket:{ticket}") + if cached_user: + cache.delete(f"sse_ticket:{ticket}") + is_authenticated = True + + # 2. Backward compatibility fallback for active sessions + if not is_authenticated and token: + try: + payload = verify_access_token(token) + if payload and payload.get("sub"): + is_authenticated = True + except Exception: + pass + + if not is_authenticated: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Unauthorized SSE connection: Valid ticket or token is required." + ) + def event_generator(): import json, time max_duration = 3600 # Max 1 hour stream safeguard diff --git a/app/api/v1/routers/PaymentRouter.py b/app/api/v1/routers/PaymentRouter.py index 0b9676b..e417e8b 100644 --- a/app/api/v1/routers/PaymentRouter.py +++ b/app/api/v1/routers/PaymentRouter.py @@ -11,6 +11,7 @@ from app.core.database.db_session import get_db from app.api.v1.routers.CustomerProfileRouter import get_current_customer from app.models.EcomCustomerModel import EcomCustomer from app.models.PaymentLedgerModel import PaymentLedger +from app.models.OrderModel import Order from app.core.payment_orchestrator import payment_orchestrator router = APIRouter(prefix="/api/v1/payment", tags=["Razorpay Payment Engine"]) @@ -56,7 +57,7 @@ def initiate_payment( user_agent = request.headers.get("user-agent") result = payment_orchestrator.initiate_payment( - db, payload.order_id, client_ip=client_ip, user_agent=user_agent + db, payload.order_id, client_ip=client_ip, user_agent=user_agent, customer_id=customer.customer_id ) if "error" in result: @@ -78,7 +79,8 @@ def verify_payment( order_id=payload.order_id, rzp_order_id=payload.razorpay_order_id, rzp_payment_id=payload.razorpay_payment_id, - rzp_signature=payload.razorpay_signature + rzp_signature=payload.razorpay_signature, + customer_id=customer.customer_id ) if "error" in result: @@ -96,7 +98,7 @@ def cancel_payment( Cancel pending payment intent and release reserved stock. """ result = payment_orchestrator.cancel_payment( - db, order_id=payload.order_id, reason=payload.reason or "Payment cancelled by user" + db, order_id=payload.order_id, reason=payload.reason or "Payment cancelled by user", customer_id=customer.customer_id ) if "error" in result: @@ -113,6 +115,13 @@ def get_payment_status( """ Returns latest payment ledger status for an order. """ + order = db.query(Order).filter(Order.order_id == order_id).first() + if not order: + raise HTTPException(status_code=404, detail="Order not found") + + if order.customer_id != customer.customer_id: + raise HTTPException(status_code=403, detail="Unauthorized: You do not have permission to view this order") + entry = ( db.query(PaymentLedger) .filter(PaymentLedger.order_id == order_id) diff --git a/app/api/v1/routers/PosSyncRouter.py b/app/api/v1/routers/PosSyncRouter.py index e8d9766..4e1feb7 100644 --- a/app/api/v1/routers/PosSyncRouter.py +++ b/app/api/v1/routers/PosSyncRouter.py @@ -2,18 +2,49 @@ @router PosSyncRouter (Backend/app/api/v1/routers/PosSyncRouter.py) Fully Dynamic Database-Driven POS Synchronization Gateway (Zero Hardcoded Data) """ +import os import ulid from datetime import datetime, date from typing import List, Optional -from fastapi import APIRouter, Depends, HTTPException, status +from fastapi import APIRouter, Depends, HTTPException, status, Header from pydantic import BaseModel from sqlalchemy import select, func, desc from sqlalchemy.orm import Session from app.core.database.db_session import get_db from app.models.POSTerminalModel import POSTerminal, POSTransactionLog +from app.core.permissions.RoleChecker import RoleChecker, get_current_user +from app.models.UserModel import User router = APIRouter(prefix="/api/v1/pos", tags=["Offline POS Synchronization"]) +POS_ROLES = ["Super Admin", "Admin", "Manager", "Cashier", "Staff", "Technician"] +ADMIN_ROLES = ["Super Admin", "Admin", "Manager"] + + +def verify_pos_client_or_staff( + x_pos_key: Optional[str] = Header(None, alias="X-POS-Key"), + db: Session = Depends(get_db), + auth_header: Optional[str] = Header(None, alias="Authorization"), +): + """ + Validates either POS client shared secret OR authenticated staff Bearer token. + """ + configured_key = os.getenv("POS_SYNC_SECRET", "ifixkart-pos-secret-2026") + if x_pos_key and x_pos_key == configured_key: + return {"auth_type": "api_key", "source": "pos_terminal"} + + if auth_header and auth_header.startswith("Bearer "): + from app.core.Token import verify_token + token_str = auth_header.split(" ")[1] + payload = verify_token(token_str) + if payload and payload.get("role") in POS_ROLES: + return {"auth_type": "bearer", "role": payload.get("role"), "user_id": payload.get("sub")} + + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Unauthorized: Valid X-POS-Key header or staff Bearer token is required.", + ) + class POSTransactionItem(BaseModel): variant_id: str @@ -44,7 +75,11 @@ class RegisterTerminalRequest(BaseModel): @router.post("/terminals/register") -def register_pos_terminal(payload: RegisterTerminalRequest, db: Session = Depends(get_db)): +def register_pos_terminal( + payload: RegisterTerminalRequest, + db: Session = Depends(get_db), + auth: dict = Depends(verify_pos_client_or_staff), +): """ Dynamically registers or updates a POS terminal. """ @@ -81,7 +116,11 @@ def register_pos_terminal(payload: RegisterTerminalRequest, db: Session = Depend @router.post("/sync") -def sync_pos_transactions(payload: POSSyncPayload, db: Session = Depends(get_db)): +def sync_pos_transactions( + payload: POSSyncPayload, + db: Session = Depends(get_db), + auth: dict = Depends(verify_pos_client_or_staff), +): """ Idempotent database-persisted synchronization gateway for offline POS transactions. Dynamically registers unknown terminals upon sync submission. @@ -153,7 +192,10 @@ def sync_pos_transactions(payload: POSSyncPayload, db: Session = Depends(get_db) @router.get("/status") -def get_pos_sync_status(db: Session = Depends(get_db)): +def get_pos_sync_status( + db: Session = Depends(get_db), + current_user: User = Depends(RoleChecker(ADMIN_ROLES)), +): """ Returns live health telemetry for offline POS sync gateways and store terminals strictly from MySQL DB. """ @@ -224,7 +266,8 @@ def get_pos_sync_logs( terminal_id: Optional[str] = None, status: Optional[str] = None, limit: int = 50, - db: Session = Depends(get_db) + db: Session = Depends(get_db), + current_user: User = Depends(RoleChecker(ADMIN_ROLES)), ): """ Returns real database audit logs for offline POS sync transaction batches. @@ -258,7 +301,11 @@ def get_pos_sync_logs( @router.post("/terminals/{terminal_id}/reset") -def reset_terminal_sync(terminal_id: str, db: Session = Depends(get_db)): +def reset_terminal_sync( + terminal_id: str, + db: Session = Depends(get_db), + current_user: User = Depends(RoleChecker(ADMIN_ROLES)), +): """ Clears pending sync locks or re-syncs state for a given POS terminal in MySQL database. """ diff --git a/app/api/v1/routers/RazorpayDashboardRouter.py b/app/api/v1/routers/RazorpayDashboardRouter.py index 89c2769..a975e08 100644 --- a/app/api/v1/routers/RazorpayDashboardRouter.py +++ b/app/api/v1/routers/RazorpayDashboardRouter.py @@ -9,10 +9,13 @@ from app.core.config.Config import settings import app.models.db_base from app.models.PaymentLedgerModel import PaymentLedger from app.models.OrderModel import Order +from app.core.permissions.RoleChecker import RoleChecker +from app.models.UserModel import User router = APIRouter( prefix="/api/v1/payments/dashboard", - tags=["Razorpay & Financial Dashboard"] + tags=["Razorpay & Financial Dashboard"], + dependencies=[Depends(RoleChecker(["Super Admin", "Admin", "Manager", "Accountant"]))] ) @router.get("/metrics") diff --git a/app/api/v1/routers/RefundRouter.py b/app/api/v1/routers/RefundRouter.py index 0426f86..4b47fab 100644 --- a/app/api/v1/routers/RefundRouter.py +++ b/app/api/v1/routers/RefundRouter.py @@ -3,7 +3,7 @@ from sqlalchemy.orm import Session from typing import List, Optional, Any from app.core.database.db_session import get_db -from app.core.permissions.RoleChecker import get_current_user +from app.core.permissions.RoleChecker import get_current_user, RoleChecker from app.models.UserModel import User from app.services.RefundService import RefundService from app.schemas.RefundSchema import ( @@ -12,6 +12,8 @@ from app.schemas.RefundSchema import ( router = APIRouter(prefix="/api/v1/refunds", tags=["Refund Management"]) +REFUND_ADMIN_ROLES = ["Super Admin", "Admin", "Manager", "Accountant"] + def get_refund_service(request: Request, db: Session = Depends(get_db)) -> RefundService: tenant_id = getattr(request.state, "tenant_id", "tenant_default") return RefundService(db=db, tenant_id=tenant_id) @@ -32,7 +34,7 @@ def approve_refund( refund_id: str, payload: RefundRequestApprove, svc: RefundService = Depends(get_refund_service), - current_user: User = Depends(get_current_user) + current_user: User = Depends(RoleChecker(REFUND_ADMIN_ROLES)) ) -> Any: """Approves a refund request.""" return svc.approve_refund(refund_id=refund_id, data=payload, user_id=current_user.user_id) @@ -43,7 +45,7 @@ def reject_refund( refund_id: str, payload: RefundRequestReject, svc: RefundService = Depends(get_refund_service), - current_user: User = Depends(get_current_user) + current_user: User = Depends(RoleChecker(REFUND_ADMIN_ROLES)) ) -> Any: """Rejects a refund request.""" return svc.reject_refund(refund_id=refund_id, data=payload, user_id=current_user.user_id) diff --git a/app/api/v1/routers/ReportExportRouter.py b/app/api/v1/routers/ReportExportRouter.py index d65b395..d8d8c2e 100644 --- a/app/api/v1/routers/ReportExportRouter.py +++ b/app/api/v1/routers/ReportExportRouter.py @@ -15,6 +15,7 @@ from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib import colors from app.core.database.db_session import get_db +from app.core.permissions.RoleChecker import RoleChecker import app.models.db_base from app.models.OrderModel import Order from app.models.ProductModel import Product, ProductVariant @@ -128,6 +129,7 @@ def export_report( category: str = Query(..., regex="^(sales|inventory|repairs|logistics|employee_activity)$"), format: str = Query("excel", regex="^(excel|csv|pdf)$"), days: int = Query(30, ge=1, le=365), + current_user: User = Depends(RoleChecker(["Super Admin", "Admin", "Manager", "Accountant"])), db: Session = Depends(get_db) ): """Universal multi-category report exporter supporting Excel (.xlsx), CSV, and PDF.""" diff --git a/app/api/v1/routers/ServiceJobRouter.py b/app/api/v1/routers/ServiceJobRouter.py index 8da98bf..fa27716 100644 --- a/app/api/v1/routers/ServiceJobRouter.py +++ b/app/api/v1/routers/ServiceJobRouter.py @@ -93,6 +93,18 @@ def get_optional_actor( pass return None +def get_required_actor( + credentials: Optional[HTTPAuthorizationCredentials] = Depends(security), + db: Session = Depends(get_db) +) -> dict: + actor = get_optional_actor(credentials, db) + if not actor: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Authentication required to access service job records" + ) + return actor + router = APIRouter(prefix="/api/v1/service", tags=["Repairs & Scheduling Services"]) job_service = ServiceJobService() @@ -261,7 +273,7 @@ def reschedule_active_appointment( @router.get("/jobs/{job_id}") def get_service_job_details( job_id: str, - actor: Optional[dict] = Depends(get_optional_actor), + actor: dict = Depends(get_required_actor), db: Session = Depends(get_db) ): """Retrieve service job, current appointment, timeline events, active quotes, and media proof.""" @@ -269,7 +281,13 @@ def get_service_job_details( if not job: raise HTTPException(status_code=404, detail="Service job not found") - if actor and actor["type"] == "customer" and job.customer_id and job.customer_id != actor["obj"].customer_id: + if actor["type"] == "customer": + if not job.customer_id or job.customer_id != actor["obj"].customer_id: + raise HTTPException(status_code=403, detail="Not authorized to view this job") + elif actor["type"] == "admin": + if actor["obj"].role not in ["Super Admin", "Admin", "Manager", "Technician"]: + raise HTTPException(status_code=403, detail="Not authorized to view this job") + else: raise HTTPException(status_code=403, detail="Not authorized to view this job") from app.models.ServiceModel import ServiceAppointment, ServiceJobEvent @@ -515,10 +533,24 @@ def attach_service_job_media( def get_service_job_media( job_id: str, category: Optional[str] = Query(None), + actor: dict = Depends(get_required_actor), db: Session = Depends(get_db) ): """Get media proof uploaded for a service job.""" - return inspection_service.get_job_media(db, job_id, category) + job = db.get(ServiceJob, job_id) or db.query(ServiceJob).filter(ServiceJob.job_no == job_id).first() + if not job: + raise HTTPException(status_code=404, detail="Service job not found") + + if actor["type"] == "customer": + if not job.customer_id or job.customer_id != actor["obj"].customer_id: + raise HTTPException(status_code=403, detail="Not authorized to view media for this job") + elif actor["type"] == "admin": + if actor["obj"].role not in ["Super Admin", "Admin", "Manager", "Technician"]: + raise HTTPException(status_code=403, detail="Not authorized to view media for this job") + else: + raise HTTPException(status_code=403, detail="Not authorized to view media for this job") + + return inspection_service.get_job_media(db, job.job_id, category) @router.post("/jobs/{job_id}/status") def update_service_job_status_admin( diff --git a/app/api/v1/routers/ShiprocketRouter.py b/app/api/v1/routers/ShiprocketRouter.py index e105502..c7c4127 100644 --- a/app/api/v1/routers/ShiprocketRouter.py +++ b/app/api/v1/routers/ShiprocketRouter.py @@ -1,6 +1,16 @@ -from fastapi import APIRouter, Depends, Query, HTTPException -from typing import Dict, Any, List +from fastapi import APIRouter, Depends, Query, HTTPException, Request, Response, BackgroundTasks +from fastapi.responses import HTMLResponse +from sqlalchemy.orm import Session +from typing import Dict, Any, List, Optional +import json +import ulid +from datetime import datetime + from app.core.config.Config import settings +from app.core.database.db_session import get_db +from app.models.OrderModel import Order, OrderStatusHistory +from app.services.ShiprocketService import shiprocket_service +from app.services.WarrantyService import WarrantyService router = APIRouter( prefix="/api/v1/shipping", @@ -15,7 +25,7 @@ def get_shipping_status(): "mode": settings.SHIPROCKET_MODE, "pickup_location": settings.SHIPROCKET_PICKUP_LOCATION, "pickup_pincode": settings.SHIPROCKET_PICKUP_PIN, - "notice": "Safe sandbox mode active. Live API dispatch disabled per user setting." + "notice": "Safe sandbox mode active. Live API dispatch disabled per user setting." if not settings.SHIPROCKET_ENABLED else "Live Shiprocket dispatch enabled." } @router.get("/dashboard") @@ -66,3 +76,269 @@ def calculate_shipping_rates( "cod_available": True } } + +@router.get("/label/preview/{order_id}", response_class=HTMLResponse) +def get_printable_label(order_id: str, db: Session = Depends(get_db)): + """ + Renders an official, print-ready thermal/A4 shipping label with barcode, addresses, and parcel metadata. + """ + order = db.query(Order).filter(Order.order_id == order_id).first() + if not order: + raise HTTPException(status_code=404, detail="Order not found") + + addr = {} + if order.shipping_address_json: + try: + addr = json.loads(order.shipping_address_json) + except Exception: + pass + + cust_name = addr.get("name") or addr.get("full_name") or "Valued Customer" + cust_phone = addr.get("phone") or "N/A" + address_line = addr.get("address_line1") or addr.get("address") or "Customer Address" + city = addr.get("city") or "New Delhi" + state = addr.get("state") or "Delhi" + pincode = addr.get("pincode") or addr.get("postal_code") or addr.get("pin") or "110001" + + awb = order.tracking_number or f"SF{int(datetime.now().timestamp())}" + courier = order.courier_name or "BlueDart Surface" + weight = float(order.package_weight or 0.5) + pay_mode = "PREPAID" if order.payment_status == "PAYMENT_CAPTURED" else "COD" + + items_html = "" + for item in order.items: + items_html += f"{item.product_name}{item.quantity}₹{float(item.unit_price):.2f}" + + html = f""" + + + + Shipping Slip - {order.order_no} + + + +
+ +
+
+
+
+
iFixKart Logistics
+
Unified Tech & Commerce
+
+
+ {pay_mode} +
Wt: {weight:.2f} kg
+
+
+ +
+
Courier: {courier}
+
*{awb}*
+
AWB: {awb}
+
+ +
+
Deliver To:
+
{cust_name}
+
{address_line}
+
{city}, {state} - {pincode}
+
Ph: {cust_phone}
+
+ +
+
From / Return Address:
+
iFixKart Warehouse ({settings.SHIPROCKET_PICKUP_LOCATION})
+
PIN: {settings.SHIPROCKET_PICKUP_PIN or '110001'}
+
+ +
+
+ Order No: {order.order_no} + Total: ₹{float(order.final_amount):.2f} +
+ + + + + + {items_html} + +
ItemQtyAmt
+
+
+ + +""" + return HTMLResponse(content=html) + + +@router.post("/webhook") +async def handle_shiprocket_webhook( + request: Request, + background_tasks: BackgroundTasks, + db: Session = Depends(get_db) +): + """ + Autonomous webhook listener that ingests status updates directly from Shiprocket: + - PICKED UP / IN TRANSIT -> Order automatically updates to SHIPPED + - OUT FOR DELIVERY -> Order automatically updates to OUT_FOR_DELIVERY + - DELIVERED -> Order automatically updates to DELIVERED + - RTO_INITIATED -> Order automatically updates to RTO_INITIATED + """ + try: + body = await request.body() + payload = json.loads(body.decode("utf-8")) if body else {} + except Exception as e: + raise HTTPException(status_code=400, detail=f"Invalid webhook JSON: {str(e)}") + + awb = payload.get("awb") or payload.get("awb_code") or payload.get("tracking_number") + raw_status = (payload.get("current_status") or payload.get("shipment_status") or payload.get("status") or "").upper().strip() + order_no = payload.get("order_id") or payload.get("order_no") + + if not awb and not order_no: + return {"ok": False, "message": "No AWB or order identifier provided in webhook"} + + # Find matching order + order = None + if awb: + order = db.query(Order).filter(Order.tracking_number == awb).first() + if not order and order_no: + order = db.query(Order).filter(Order.order_no == order_no).first() + + if not order: + return {"ok": False, "message": f"Order not found for AWB: {awb} / Order: {order_no}"} + + previous_status = order.status + new_status = None + reason = f"Automated Shiprocket update: {raw_status} (AWB: {awb})" + + # Map Shiprocket statuses to internal order statuses + if any(k in raw_status for k in ["PICKED UP", "IN TRANSIT", "SHIPPED", "REACHED AT DESTINATION"]): + if previous_status in ["READY_FOR_DELIVERY", "CONFIRMED", "PROCESSING"]: + new_status = "SHIPPED" + order.fulfillment_status = "FULFILLED" + elif "OUT FOR DELIVERY" in raw_status: + new_status = "OUT_FOR_DELIVERY" + elif "DELIVERED" in raw_status: + new_status = "DELIVERED" + order.fulfillment_status = "FULFILLED" + WarrantyService.generate_warranty_for_order(db, order.order_id) + elif "RTO" in raw_status or "RETURN" in raw_status: + new_status = "RTO_INITIATED" + + order.last_logistics_status = raw_status + + if new_status and new_status != previous_status: + order.status = new_status + history = OrderStatusHistory( + history_id=str(ulid.ULID()), + order_id=order.order_id, + previous_status=previous_status, + new_status=new_status, + changed_by="SHIPROCKET_WEBHOOK", + reason=reason + ) + db.add(history) + db.commit() + return {"ok": True, "updated": True, "order_no": order.order_no, "new_status": new_status} + + db.commit() + return {"ok": True, "updated": False, "current_status": order.status, "logistics_status": raw_status} + + +@router.post("/orders/{order_id}/sync-tracking") +async def sync_order_tracking( + order_id: str, + db: Session = Depends(get_db) +): + """ + Manually or cron-triggered tracking sync with Shiprocket. + """ + order = db.query(Order).filter(Order.order_id == order_id).first() + if not order: + raise HTTPException(status_code=404, detail="Order not found") + + if not order.tracking_number: + return {"ok": False, "message": "No AWB tracking number assigned to this order yet"} + + return { + "ok": True, + "order_id": order.order_id, + "order_no": order.order_no, + "status": order.status, + "tracking_number": order.tracking_number, + "courier_name": order.courier_name, + "shipping_label_url": order.shipping_label_url, + "last_logistics_status": order.last_logistics_status + } diff --git a/app/api/v1/routers/SocialMediaRouter.py b/app/api/v1/routers/SocialMediaRouter.py index 467b7db..e2517fa 100644 --- a/app/api/v1/routers/SocialMediaRouter.py +++ b/app/api/v1/routers/SocialMediaRouter.py @@ -10,12 +10,15 @@ from pydantic import BaseModel from app.core.config.Config import settings from app.core.integrations.meta_graph_service import meta_service, UPLOAD_DIR +from app.core.permissions.RoleChecker import RoleChecker +from app.models.UserModel import User logger = logging.getLogger(__name__) router = APIRouter( prefix="/api/v1/social/meta", - tags=["Social Media Management"] + tags=["Social Media Management"], + dependencies=[Depends(RoleChecker(["Super Admin", "Admin", "Marketing"]))] ) class SocialPublishRequest(BaseModel): diff --git a/app/api/v1/routers/admin_storefront.py b/app/api/v1/routers/admin_storefront.py index f190275..bf1d10b 100644 --- a/app/api/v1/routers/admin_storefront.py +++ b/app/api/v1/routers/admin_storefront.py @@ -173,7 +173,7 @@ def create_cms_content(data: ContentCreatePayload, db: Session = Depends(get_db) return content @router.post("/content/bulk-save") -def bulk_save_cms_content(payload: BulkSavePayload, db: Session = Depends(get_db)): +def bulk_save_cms_content(payload: BulkSavePayload, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): saved_ids = [] for data in payload.items: existing = None @@ -239,7 +239,11 @@ def bulk_save_cms_content(payload: BulkSavePayload, db: Session = Depends(get_db return {"message": "Bulk CMS content saved and storefront cache invalidated", "count": len(payload.items)} @router.delete("/content/{content_id}") -def delete_cms_content(content_id: str, db: Session = Depends(get_db)): +def delete_cms_content( + content_id: str, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user), +): item = db.query(StorefrontContent).filter(StorefrontContent.content_id == content_id).first() if not item: raise HTTPException(status_code=404, detail="Content not found") @@ -269,7 +273,10 @@ from typing import Any as _Any @router.get("/cms/footer-info") -def admin_get_footer_info(db: Session = Depends(get_db)): +def admin_get_footer_info( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user), +): """Admin: Fetch current footer info.""" return StorefrontCmsService(db).get_footer_info() @@ -285,7 +292,10 @@ def admin_update_footer_info( @router.get("/cms/settings") -def admin_get_settings(db: Session = Depends(get_db)): +def admin_get_settings( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user), +): """Admin: Fetch all storefront settings (branding, advance_percent, etc.).""" return StorefrontCmsService(db).get_settings() @@ -301,7 +311,10 @@ def admin_update_settings( @router.get("/cms/mega-menu") -def admin_get_mega_menu(db: Session = Depends(get_db)): +def admin_get_mega_menu( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user), +): """Admin: Fetch all three mega menu configs (shop, deals, products).""" return StorefrontCmsService(db).get_mega_menu() @@ -317,7 +330,10 @@ def admin_update_mega_menu( @router.get("/cms/catalog-filters") -def admin_get_catalog_filters(db: Session = Depends(get_db)): +def admin_get_catalog_filters( + db: Session = Depends(get_db), + current_user: User = Depends(get_current_user), +): """Admin: Fetch catalog filter configuration.""" return StorefrontCmsService(db).get_catalog_filters() diff --git a/app/api/v1/routers/storefront.py b/app/api/v1/routers/storefront.py index 9977122..524d457 100644 --- a/app/api/v1/routers/storefront.py +++ b/app/api/v1/routers/storefront.py @@ -11,7 +11,7 @@ from pydantic import BaseModel from app.core.database.db_session import get_db from app.services.StorefrontService import StorefrontService from app.services.CatalogSearchService import apply_product_search -from app.models.ProductModel import Product, ProductVariant +from app.models.ProductModel import Product, ProductVariant, VariantAttribute from app.models.CategoryModel import Category from app.models.BrandModel import Brand from app.models.DeviceCatalogModel import ServiceType @@ -42,6 +42,7 @@ def live_search( .options( selectinload(Product.images), selectinload(Product.variants).selectinload(ProductVariant.images), + selectinload(Product.variants).selectinload(ProductVariant.attributes).selectinload(VariantAttribute.attribute_type), ) .where(Product.status == "active") ) @@ -52,6 +53,82 @@ def live_search( stmt = apply_product_search(stmt, q).order_by(Product.created_at.desc()).limit(8) products = db.execute(stmt).scalars().all() + def _variant_label(v) -> str: + vals = [] + for a in (v.attributes or []): + code = ( + getattr(getattr(a, "attribute_type", None), "code", None) + or getattr(a, "attribute_code", "") + or "" + ).strip().lower() + if code in ("parent_media_key", "media_key", "barcode", "sku", "warranty_months", "country_of_origin") or code.startswith("parent_"): + continue + if a.attribute_value and a.attribute_value not in vals: + if code == "color": + vals.insert(0, a.attribute_value) + else: + vals.append(a.attribute_value) + return " ".join(vals) + + expanded_products = [] + for p in products: + active_variants = [v for v in (p.variants or []) if getattr(v, "status", "active") == "active"] + if len(active_variants) > 1: + for v in active_variants: + label = _variant_label(v) + v_name = f"{p.name} - {label}" if label else p.name + v_img = v.images[0].image_url if v.images else (p.images[0].image_url if p.images else None) + v_price = float(v.price) if v.price is not None else 0.0 + expanded_products.append({ + "product_id": p.product_id, + "category_id": p.category_id, + "name": v_name, + "slug": p.slug, + "variant_sku": v.sku, + "variant_name": label or None, + "variant_url": f"/products/{p.slug}?variant={v.sku}", + "price": v_price, + "compare_price": float(v.compare_price) if v.compare_price is not None else None, + "thumbnail_url": v_img, + "images": [{"image_url": v_img}] if v_img else [], + "variants": [{ + "variant_id": v.variant_id, + "product_id": p.product_id, + "sku": v.sku, + "price": v_price, + "status": "active", + }] + }) + else: + first_v = active_variants[0] if active_variants else (p.variants[0] if p.variants else None) + v_img = (p.images[0].image_url if p.images else (first_v.images[0].image_url if first_v and first_v.images else None)) + if not v_img and p.variants: + for alt_v in p.variants: + if alt_v.images: + v_img = alt_v.images[0].image_url + break + price_val = float(first_v.price) if first_v and first_v.price is not None else 0.0 + expanded_products.append({ + "product_id": p.product_id, + "category_id": p.category_id, + "name": p.name, + "slug": p.slug, + "variant_sku": first_v.sku if first_v else None, + "variant_name": None, + "variant_url": f"/products/{p.slug}", + "price": price_val, + "compare_price": float(first_v.compare_price) if first_v and first_v.compare_price is not None else None, + "thumbnail_url": v_img, + "images": [{"image_url": v_img}] if v_img else [], + "variants": [{ + "variant_id": first_v.variant_id if first_v else p.product_id, + "product_id": p.product_id, + "sku": first_v.sku if first_v else "", + "price": price_val, + "status": "active", + }] if first_v else [] + }) + term = f"%{q.strip()}%" categories = db.execute( select(Category).where(Category.is_active == True, Category.name.ilike(term)).limit(5) @@ -64,7 +141,7 @@ def live_search( ).scalars().all() payload = { - "products": [ProductResponse.model_validate(p).model_dump(mode="json") for p in products], + "products": expanded_products, "categories": [ { "category_id": c.category_id, diff --git a/app/core/database/cache_manager.py b/app/core/database/cache_manager.py index 7f8dbac..fbcd568 100644 --- a/app/core/database/cache_manager.py +++ b/app/core/database/cache_manager.py @@ -100,12 +100,23 @@ class CacheManager: logger.error(f"Redis delete failed: {e}") self.memory_cache.delete(key) + # Recommended TTL Constants for Hot Caching + TTL_SETTINGS = 1800 # 30 minutes for storefront settings, footer-info, mega-menu, catalog filters + TTL_CATALOG = 900 # 15 minutes for categories tree & brands + TTL_PRODUCTS = 300 # 5 minutes for hot product collections + def invalidate_prefix(self, prefix: str) -> None: + """Non-blocking cursor-based prefix invalidation using Redis SCAN to prevent event loop stalls.""" if self.redis_client: try: - keys = self.redis_client.keys(f"{prefix}*") - if keys: - self.redis_client.delete(*keys) + batch = [] + for key in self.redis_client.scan_iter(match=f"{prefix}*", count=100): + batch.append(key) + if len(batch) >= 100: + self.redis_client.delete(*batch) + batch = [] + if batch: + self.redis_client.delete(*batch) except Exception as e: logger.error(f"Redis prefix invalidation failed: {e}") self.memory_cache.invalidate_prefix(prefix) diff --git a/app/core/database/db_session.py b/app/core/database/db_session.py index 22b26b1..7a1ebcb 100644 --- a/app/core/database/db_session.py +++ b/app/core/database/db_session.py @@ -10,18 +10,21 @@ core_url = settings.CORE_DATABASE_URL or settings.DATABASE_URL crm_url = settings.CRM_DATABASE_URL or settings.DATABASE_URL commerce_url = settings.COMMERCE_DATABASE_URL or settings.DATABASE_URL -# Pool sizing is environment-configurable so the simulation backend can raise -# it (DB_POOL_SIZE / DB_MAX_OVERFLOW in .env.sim); production keeps defaults. -_pool_size = int(os.getenv("DB_POOL_SIZE", "5")) +# Calibrated connection pool limits: +# 4 workers * 3 engines * (10 pool + 10 overflow) = 240 max connections +# (safely under MySQL max_connections = 500) +_pool_size = int(os.getenv("DB_POOL_SIZE", "10")) _max_overflow = int(os.getenv("DB_MAX_OVERFLOW", "10")) +_pool_recycle = int(os.getenv("DB_POOL_RECYCLE", "1800")) -# 2. Engines configuration with connection pooling +# 2. Engines configuration with connection pooling and stale socket recycling engine_core = create_engine( core_url, future=True, pool_pre_ping=True, pool_size=_pool_size, max_overflow=_max_overflow, + pool_recycle=_pool_recycle, connect_args={"init_command": "SET time_zone='+00:00'"} ) @@ -31,6 +34,7 @@ engine_crm = create_engine( pool_pre_ping=True, pool_size=_pool_size, max_overflow=_max_overflow, + pool_recycle=_pool_recycle, connect_args={"init_command": "SET time_zone='+00:00'"} ) @@ -40,6 +44,7 @@ engine_commerce = create_engine( pool_pre_ping=True, pool_size=_pool_size, max_overflow=_max_overflow, + pool_recycle=_pool_recycle, connect_args={"init_command": "SET time_zone='+00:00'"} ) diff --git a/app/core/limiter.py b/app/core/limiter.py index 63eaa6d..b28028f 100644 --- a/app/core/limiter.py +++ b/app/core/limiter.py @@ -1,11 +1,43 @@ +import os from slowapi import Limiter -from slowapi.util import get_remote_address +from starlette.requests import Request from app.core.config.Config import settings -# Global SlowAPI Limiter instance +def get_real_client_ip(request: Request) -> str: + """ + Extracts the true client IP address, safely prioritizing X-Forwarded-For + and X-Real-IP headers set by upstream trusted reverse proxies (e.g. Nginx). + """ + forwarded_for = request.headers.get("x-forwarded-for") or request.headers.get("X-Forwarded-For") + if forwarded_for: + client_ip = forwarded_for.split(",")[0].strip() + if client_ip: + return client_ip + + real_ip = request.headers.get("x-real-ip") or request.headers.get("X-Real-IP") + if real_ip: + return real_ip.strip() + + if request.client and request.client.host: + return request.client.host + + return "127.0.0.1" + +# Shared Redis storage backend for SlowAPI across all multi-worker processes +# Uses DB index 1 to keep rate limit keys separate from general cache (DB 0) +redis_rate_limit_url = os.getenv("RATE_LIMIT_REDIS_URL", "redis://127.0.0.1:6379/1") +try: + import redis + _r = redis.from_url(redis_rate_limit_url, socket_connect_timeout=1) + _r.ping() + _storage_uri = redis_rate_limit_url +except Exception: + _storage_uri = "memory://" + limiter = Limiter( - key_func=get_remote_address, - default_limits=["120/minute"] + key_func=get_real_client_ip, + default_limits=["120/minute"], + storage_uri=_storage_uri ) # A local swarm originates from one IP. Rate limits are a production protection, diff --git a/app/core/middleware/kill_switch_middleware.py b/app/core/middleware/kill_switch_middleware.py index 80002a5..073fda1 100644 --- a/app/core/middleware/kill_switch_middleware.py +++ b/app/core/middleware/kill_switch_middleware.py @@ -1,3 +1,4 @@ +import time from fastapi import Request from starlette.middleware.base import BaseHTTPMiddleware from starlette.responses import JSONResponse @@ -8,6 +9,9 @@ from jose import jwt, JWTError from app.core.config.Config import settings, load_public_key_bytes MASTER_ADMIN_EMAIL = "adithiyan.elan@gmail.com" +_cached_global_disable = False +_last_check_time = 0.0 +_CACHE_TTL_SECONDS = 5.0 class KillSwitchMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next): @@ -15,26 +19,25 @@ class KillSwitchMiddleware(BaseHTTPMiddleware): if request.url.path in ["/docs", "/redoc", "/openapi.json"]: return await call_next(request) - # Open db session safely - db: Session = SessionLocal() - global_disable = False - try: - # Query the GLOBAL_DISABLE setting key - item = db.query(Setting).filter(Setting.setting_key == "GLOBAL_DISABLE").first() - if item: - # Expecting value like {"enabled": true} - val = item.setting_value - if isinstance(val, dict) and val.get("enabled") is True: - global_disable = True - except Exception: - # If database lookup fails, fail secure or run normally? - # Let's run normally to prevent site breakdown during DB connection blips, - # but log the failure in real setups. - pass - finally: - db.close() + global _cached_global_disable, _last_check_time + now = time.time() - if not global_disable: + # Refresh cached setting every 5 seconds to eliminate per-request DB round-trips + if (now - _last_check_time) > _CACHE_TTL_SECONDS: + db: Session = SessionLocal() + try: + item = db.query(Setting).filter(Setting.setting_key == "GLOBAL_DISABLE").first() + if item and isinstance(item.setting_value, dict): + _cached_global_disable = bool(item.setting_value.get("enabled", False)) + else: + _cached_global_disable = False + _last_check_time = now + except Exception: + pass + finally: + db.close() + + if not _cached_global_disable: return await call_next(request) # Bypass check for MASTER ADMIN diff --git a/app/core/middleware/security_middleware.py b/app/core/middleware/security_middleware.py index 7faa7c2..a5ce1b4 100644 --- a/app/core/middleware/security_middleware.py +++ b/app/core/middleware/security_middleware.py @@ -44,15 +44,15 @@ class RequestSizeLimitMiddleware(BaseHTTPMiddleware): self.large_paths = large_paths async def dispatch(self, request: Request, call_next): - # Read content length header + # Determine limit based on endpoint path + is_large_path = any(request.url.path.startswith(prefix) for prefix in self.large_paths) + limit = self.large_paths_max_bytes if is_large_path else self.max_bytes + + # 1. Content-Length Header Guard content_length = request.headers.get("content-length") if content_length: try: length = int(content_length) - # Determine limit based on endpoint path - is_large_path = any(request.url.path.startswith(prefix) for prefix in self.large_paths) - limit = self.large_paths_max_bytes if is_large_path else self.max_bytes - if length > limit: max_mb = limit // (1024 * 1024) return JSONResponse( @@ -61,6 +61,35 @@ class RequestSizeLimitMiddleware(BaseHTTPMiddleware): ) except ValueError: pass - - # Also limit reading chunks if chunked transfer encoding is used - return await call_next(request) + + # 2. Chunked Transfer-Encoding Streaming Guard + transfer_encoding = (request.headers.get("transfer-encoding") or "").lower() + if "chunked" in transfer_encoding or not content_length: + bytes_received = 0 + original_receive = request._receive + + async def custom_receive(): + nonlocal bytes_received + message = await original_receive() + if message.get("type") == "http.request": + body = message.get("body", b"") + bytes_received += len(body) + if bytes_received > limit: + max_mb = limit // (1024 * 1024) + raise HTTPException( + status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, + detail=f"Payload too large. Streaming transfer exceeded maximum limit of {max_mb}MB." + ) + return message + + request._receive = custom_receive + + try: + return await call_next(request) + except HTTPException as exc: + if exc.status_code == status.HTTP_413_REQUEST_ENTITY_TOO_LARGE: + return JSONResponse( + status_code=exc.status_code, + content={"detail": exc.detail} + ) + raise diff --git a/app/core/payment_orchestrator.py b/app/core/payment_orchestrator.py index d1f3afd..c4adb2e 100644 --- a/app/core/payment_orchestrator.py +++ b/app/core/payment_orchestrator.py @@ -19,10 +19,10 @@ logger = logging.getLogger("app.payment_orchestrator") class PaymentOrchestrator: - def initiate_payment(self, db: Session, order_id: str, client_ip: str = None, user_agent: str = None) -> Dict[str, Any]: + def initiate_payment(self, db: Session, order_id: str, client_ip: str = None, user_agent: str = None, customer_id: Optional[str] = None) -> Dict[str, Any]: """ Initiates a new payment attempt for an e-commerce order. - Row-locks the order and verifies status. + Row-locks the order and verifies status and ownership. """ if settings.SIMULATION_MODE: return {"error": "Razorpay is disabled in simulation; use /api/v1/payment/simulate", "status_code": 400} @@ -30,6 +30,9 @@ class PaymentOrchestrator: if not order: return {"error": "Order not found", "status_code": 404} + if customer_id and order.customer_id != customer_id: + return {"error": "Unauthorized: You do not own this order", "status_code": 403} + if order.payment_status == "PAYMENT_CAPTURED": return {"error": "Order is already paid", "status_code": 400} @@ -95,7 +98,7 @@ class PaymentOrchestrator: "status_code": 200 } - def cancel_payment(self, db: Session, order_id: str, reason: str = "Payment cancelled by user") -> Dict[str, Any]: + def cancel_payment(self, db: Session, order_id: str, reason: str = "Payment cancelled by user", customer_id: Optional[str] = None) -> Dict[str, Any]: """ Cancels pending order payment and releases reserved stock. """ @@ -103,6 +106,9 @@ class PaymentOrchestrator: if not order: return {"error": "Order not found", "status_code": 404} + if customer_id and order.customer_id != customer_id: + return {"error": "Unauthorized: You do not own this order", "status_code": 403} + cancelled_order = OrderService.cancel_ecommerce_order(db, order, reason=reason) return { "status": "SUCCESS", @@ -118,7 +124,8 @@ class PaymentOrchestrator: order_id: str, rzp_order_id: str, rzp_payment_id: str, - rzp_signature: str + rzp_signature: str, + customer_id: Optional[str] = None ) -> Dict[str, Any]: """ Verifies client-side signature + executes secondary server-side fetch from Razorpay API. @@ -129,6 +136,9 @@ class PaymentOrchestrator: if not order: return {"error": "Order not found", "status_code": 404} + if customer_id and order.customer_id != customer_id: + return {"error": "Unauthorized: You do not own this order", "status_code": 403} + if order.payment_status == "PAYMENT_CAPTURED": return {"status": "SUCCESS", "message": "Payment already captured"} @@ -221,15 +231,30 @@ class PaymentOrchestrator: rzp_payment_id = entity.get("id") if rzp_order_id: - payment_entry = db.query(PaymentLedger).filter(PaymentLedger.razorpay_order_id == rzp_order_id).first() + # Row-level lock on PaymentLedger and Order to prevent race conditions with /verify endpoint + payment_entry = ( + db.query(PaymentLedger) + .filter(PaymentLedger.razorpay_order_id == rzp_order_id) + .with_for_update() + .first() + ) if payment_entry and payment_entry.status != "CAPTURED": - order = db.query(Order).filter(Order.order_id == payment_entry.order_id).first() - if order: + order = ( + db.query(Order) + .filter(Order.order_id == payment_entry.order_id) + .with_for_update() + .first() + ) + if order and order.payment_status != "PAYMENT_CAPTURED": payment_entry.transaction_ref = rzp_payment_id payment_entry.status = "CAPTURED" payment_entry.raw_response_json = json.dumps(entity) OrderService.confirm_ecommerce_payment(db, order, payment_method="RAZORPAY") receipt.processing_result = "CAPTURED_CONFIRMED" + else: + receipt.processing_result = "ORDER_ALREADY_CONFIRMED" + else: + receipt.processing_result = "PAYMENT_ALREADY_CAPTURED" receipt.processed_at = datetime.now(timezone.utc) db.commit() diff --git a/app/core/permissions/RoleChecker.py b/app/core/permissions/RoleChecker.py index 5d4a40c..80b3b12 100644 --- a/app/core/permissions/RoleChecker.py +++ b/app/core/permissions/RoleChecker.py @@ -60,7 +60,9 @@ def get_current_user( if not token: - token = request.query_params.get("token") or request.cookies.get("access_token") + # Strict token source: Bearer header (via oauth2_scheme) or secure cookie. + # URL query-parameters (?token=...) are explicitly disabled to prevent token leakage in logs and referrer headers. + token = request.cookies.get("access_token") if not token: raise HTTPException( diff --git a/app/main.py b/app/main.py index b386550..e34800f 100644 --- a/app/main.py +++ b/app/main.py @@ -74,16 +74,24 @@ from app.core.middleware.trace_middleware import RequestTraceMiddleware from app.core.middleware.security_middleware import SecurityHeadersMiddleware, RequestSizeLimitMiddleware from app.core.middleware.kill_switch_middleware import KillSwitchMiddleware from app.core.Exception import AppException +from sqlalchemy.exc import IntegrityError + +is_prod = str(getattr(settings, "ENVIRONMENT", "")).lower() in ["production", "prod"] +docs_enabled = os.getenv("ENABLE_DOCS", "0" if is_prod else "1") == "1" app = FastAPI( title=settings.PROJECT_NAME, description="iFixKart Enterprise ERP/CRM/E-commerce Platform Backend Core Foundation", - version="1.0.0" + version="1.0.0", + docs_url="/docs" if docs_enabled else None, + redoc_url="/redoc" if docs_enabled else None, + openapi_url="/openapi.json" if docs_enabled else None, ) -# Mount Uploads directory for media serving with fallback to production server for missing local files +# Mount Uploads directory for media serving with transparent upstream cache for missing local files from pathlib import Path -from fastapi.responses import FileResponse, RedirectResponse +import urllib.request +from fastapi.responses import FileResponse, Response uploads_path = str(Path(__file__).resolve().parents[1] / "uploads") os.makedirs(uploads_path, exist_ok=True) @@ -93,26 +101,50 @@ def serve_upload_file(file_path: str): local_file = os.path.abspath(os.path.join(uploads_path, file_path)) if os.path.isfile(local_file) and local_file.startswith(uploads_path): return FileResponse(local_file) - return RedirectResponse( - url=f"https://ifixkartbe.trionixsolution.com/uploads/{file_path}", - status_code=307 - ) -# 1. CORS Configuration + # Transparent Upstream Fallback with Auto-Caching + # Prevents 307 redirects that trigger browser CORB/ORB cross-origin blocking + try: + remote_url = f"https://ifixkartbe.trionixsolution.com/uploads/{file_path}" + req = urllib.request.Request(remote_url, headers={"User-Agent": "FastAPILocalProxy/1.0"}) + with urllib.request.urlopen(req, timeout=8) as resp: + if resp.status == 200: + content = resp.read() + content_type = resp.headers.get_content_type() or "application/octet-stream" + # Cache to disk for instant zero-latency future hits + try: + os.makedirs(os.path.dirname(local_file), exist_ok=True) + with open(local_file, "wb") as f: + f.write(content) + return FileResponse(local_file, media_type=content_type) + except Exception: + return Response(content=content, media_type=content_type) + except Exception: + pass + + return Response(content=b"Media file not found", status_code=404, media_type="text/plain") + +# 1. CORS Configuration - Single Source of Truth +ALLOWED_ORIGINS = [ + "https://ifixkartdev.trionixsolution.com", + "https://ifixkart.trionixsolution.com", + "https://ifixkartbe.trionixsolution.com", + "http://localhost:3000", + "http://localhost:3021", + "http://localhost:3022", + "http://localhost:8000", + "http://localhost:8010", + "http://127.0.0.1:3000", + "http://127.0.0.1:3021", + "http://127.0.0.1:3022", + "http://127.0.0.1:8000", + "http://127.0.0.1:8010", +] +ALLOWED_ORIGINS_SET = set(ALLOWED_ORIGINS) + app.add_middleware( CORSMiddleware, - allow_origins=[ - "https://ifixkartdev.trionixsolution.com", - "https://ifixkart.trionixsolution.com", - "https://ifixkartbe.trionixsolution.com", - "http://localhost:3021", - "http://localhost:3022", - "http://localhost:8000", - "http://127.0.0.1:3021", - "http://127.0.0.1:3022", - "http://127.0.0.1:8000", - ], - allow_origin_regex=r"^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?$", + allow_origins=ALLOWED_ORIGINS, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], @@ -205,6 +237,14 @@ app.add_middleware(RequestTraceMiddleware) from fastapi.exceptions import RequestValidationError from starlette.exceptions import HTTPException as StarletteHTTPException +def append_cors_headers(response: JSONResponse, request: Request): + origin = request.headers.get("origin") + if origin and origin in ALLOWED_ORIGINS_SET: + response.headers["Access-Control-Allow-Origin"] = origin + response.headers["Access-Control-Allow-Credentials"] = "true" + response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS, PATCH" + response.headers["Access-Control-Allow-Headers"] = "Authorization, Content-Type, X-Requested-With, X-API-KEY, X-POS-Key" + # 3. Register Global Handlers for Custom AppException with CORS safety @app.exception_handler(AppException) def app_exception_handler(request: Request, exc: AppException): @@ -213,11 +253,7 @@ def app_exception_handler(request: Request, exc: AppException): status_code=exc.status_code, content={"detail": exc.detail, "request_id": req_id} ) - # Explicitly append CORS headers so browser doesn't block cross-origin error responses - origin = request.headers.get("origin") - if origin: - response.headers["Access-Control-Allow-Origin"] = origin - response.headers["Access-Control-Allow-Credentials"] = "true" + append_cors_headers(response, request) return response @app.exception_handler(StarletteHTTPException) @@ -226,10 +262,7 @@ def http_exception_handler(request: Request, exc: StarletteHTTPException): status_code=exc.status_code, content={"detail": exc.detail} ) - origin = request.headers.get("origin") - if origin: - response.headers["Access-Control-Allow-Origin"] = origin - response.headers["Access-Control-Allow-Credentials"] = "true" + append_cors_headers(response, request) return response from fastapi.encoders import jsonable_encoder @@ -240,24 +273,39 @@ def validation_exception_handler(request: Request, exc: RequestValidationError): status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content={"detail": jsonable_encoder(exc.errors())} ) - origin = request.headers.get("origin") - if origin: - response.headers["Access-Control-Allow-Origin"] = origin - response.headers["Access-Control-Allow-Credentials"] = "true" + append_cors_headers(response, request) + return response + +@app.exception_handler(IntegrityError) +def integrity_error_handler(request: Request, exc: IntegrityError): + orig_msg = str(exc.orig) if hasattr(exc, "orig") else str(exc) + detail = "A database integrity conflict occurred." + if "Duplicate entry" in orig_msg: + if "phone" in orig_msg.lower(): + detail = "Phone number is already registered or in use." + elif "email" in orig_msg.lower(): + detail = "Email address is already registered or in use." + else: + detail = "A record with this identifier already exists." + response = JSONResponse( + status_code=status.HTTP_409_CONFLICT, + content={"detail": detail} + ) + append_cors_headers(response, request) return response @app.exception_handler(Exception) def generic_exception_handler(request: Request, exc: Exception): import traceback traceback.print_exc() + req_id = getattr(request.state, "request_id", "unknown") + # Mask internal exception details from untrusted clients to prevent database schema/credential leaks + error_msg = str(exc) if settings.ENVIRONMENT == "development" else "Internal server error occurred. Please contact support." response = JSONResponse( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - content={"detail": "Internal server error occurred", "error": str(exc)} + content={"detail": "Internal server error", "request_id": req_id, "error": error_msg} ) - origin = request.headers.get("origin") - if origin: - response.headers["Access-Control-Allow-Origin"] = origin - response.headers["Access-Control-Allow-Credentials"] = "true" + append_cors_headers(response, request) return response # 4. Register Router Endpoints @@ -399,32 +447,38 @@ def startup_event(): time.sleep(300) # Check every 5 minutes - worker_thread = threading.Thread(target=run_media_background_worker, daemon=True, name="MediaWorkerThread") - worker_thread.start() - print("Media Async Garbage Collector & Reconciliation Worker thread started.") + # Centralized background worker thread gating: + # In multi-worker Gunicorn setups, only the designated worker or sidecar process (ENABLE_MIGRATION_WORKER=1) + # spawns the database polling threads, preventing N-worker connection pool exhaustion. + if os.getenv("ENABLE_MIGRATION_WORKER", "0") == "1": + worker_thread = threading.Thread(target=run_media_background_worker, daemon=True, name="MediaWorkerThread") + worker_thread.start() + print("Media Async Garbage Collector & Reconciliation Worker thread started.") - # Start Persistent Migration Worker Background Thread - from app.services.migration_engine.migration_worker import MigrationWorker + # Start Persistent Migration Worker Background Thread + from app.services.migration_engine.migration_worker import MigrationWorker - def run_migration_background_worker(): - worker = MigrationWorker() - print(f"[{worker.worker_id}] Migration Worker daemon initialized and listening for queued jobs...") - while True: - try: - db = SessionLocal() + def run_migration_background_worker(): + worker = MigrationWorker() + print(f"[{worker.worker_id}] Migration Worker daemon initialized and listening for queued jobs...") + while True: try: - res = worker.claim_next_job(db) - if res: - job_id, lease_version = res - worker.process_job(job_id, lease_version) - finally: - db.close() - except Exception as err: - print(f"Error in Migration Worker loop: {err}") - time.sleep(2) + db = SessionLocal() + try: + res = worker.claim_next_job(db) + if res: + job_id, lease_version = res + worker.process_job(job_id, lease_version) + finally: + db.close() + except Exception as err: + print(f"Error in Migration Worker loop: {err}") + time.sleep(2) - mig_thread = threading.Thread(target=run_migration_background_worker, daemon=True, name="MigrationWorkerThread") - mig_thread.start() - print("Persistent Migration Worker background thread started.") + mig_thread = threading.Thread(target=run_migration_background_worker, daemon=True, name="MigrationWorkerThread") + mig_thread.start() + print("Persistent Migration Worker background thread started.") + else: + print("Background poller threads skipped on this worker (ENABLE_MIGRATION_WORKER != 1).") diff --git a/app/models/OrderModel.py b/app/models/OrderModel.py index 35994a6..de4b5c7 100644 --- a/app/models/OrderModel.py +++ b/app/models/OrderModel.py @@ -30,6 +30,11 @@ class Order(Base): billing_address_json = Column(Text, nullable=True) tracking_number = Column(String(100), nullable=True) courier_name = Column(String(100), nullable=True) + shipping_label_url = Column(String(500), nullable=True) + package_weight = Column(Numeric(6, 3), nullable=True) + logistics_provider = Column(String(50), default="SHIPROCKET") + pickup_scheduled = Column(Boolean, default=False) + last_logistics_status = Column(String(50), nullable=True) created_at = Column(DateTime, server_default=func.now(), index=True) updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now()) diff --git a/app/repositories/session_repository.py b/app/repositories/session_repository.py index a3c25ea..c1f1c81 100644 --- a/app/repositories/session_repository.py +++ b/app/repositories/session_repository.py @@ -9,8 +9,19 @@ class SessionRepository(BaseRepository[UserSession]): super().__init__(UserSession) def get_by_refresh_token(self, db: Session, token: str) -> Optional[UserSession]: - stmt = select(UserSession).where(UserSession.refresh_token == token, UserSession.is_active.is_(True)) - return db.execute(stmt).scalar_one_or_none() + from app.utils.Hash_util import hash_token + from sqlalchemy import or_ + hashed = hash_token(token) + stmt = select(UserSession).where( + or_(UserSession.refresh_token == hashed, UserSession.refresh_token == token), + UserSession.is_active.is_(True) + ) + session = db.execute(stmt).scalar_one_or_none() + # Zero-downtime auto-upgrade: if matched on legacy plaintext token, re-hash in-place + if session and session.refresh_token == token and token != hashed: + session.refresh_token = hashed + db.commit() + return session def get_active_sessions_by_user(self, db: Session, user_id: str) -> List[UserSession]: stmt = select(UserSession).where(UserSession.user_id == user_id, UserSession.is_active.is_(True)) diff --git a/app/schemas/Auth.py b/app/schemas/Auth.py index 29baa52..3ff7cbe 100644 --- a/app/schemas/Auth.py +++ b/app/schemas/Auth.py @@ -11,7 +11,7 @@ class LoginSchema(BaseModel): class TokenResponseSchema(BaseModel): access_token: str - refresh_token: str + refresh_token: Optional[str] = None token_type: str = "bearer" class PasswordResetRequest(BaseModel): diff --git a/app/schemas/Catalog.py b/app/schemas/Catalog.py index 1c38dc4..202cdd8 100644 --- a/app/schemas/Catalog.py +++ b/app/schemas/Catalog.py @@ -530,6 +530,18 @@ class ProductVariantResponse(BaseModel): available_stock: int = 0 attributes: List[VariantAttributeResponse] = [] images: List[VariantImageResponse] = [] + thumbnail_url: Optional[str] = None + + @model_validator(mode="after") + def populate_variant_thumbnail(self) -> 'ProductVariantResponse': + if not self.thumbnail_url and self.images: + for img in self.images: + if getattr(img, 'is_primary', False) and img.image_url: + self.thumbnail_url = img.image_url + break + if not self.thumbnail_url and self.images[0].image_url: + self.thumbnail_url = self.images[0].image_url + return self class Config: from_attributes = True @@ -604,22 +616,47 @@ class ProductResponse(BaseModel): images: List[ProductImageResponse] = [] variants: List[ProductVariantResponse] = [] locations: List[ProductLocationResponse] = [] + thumbnail_url: Optional[str] = None @model_validator(mode="after") def populate_images(self) -> 'ProductResponse': + # 1. If images is empty, search ALL variants for images if not self.images and self.variants: - first_var = self.variants[0] - if first_var.images: - self.images = [ - ProductImageResponse( - image_id=vi.image_id, - product_id=self.product_id, - image_url=vi.image_url, - alt_text=self.name, - sort_order=vi.sort_order, - is_banner=vi.is_primary - ) for vi in first_var.images - ] + for v in self.variants: + if v.images: + self.images = [ + ProductImageResponse( + image_id=vi.image_id, + product_id=self.product_id, + image_url=vi.image_url, + alt_text=self.name, + sort_order=vi.sort_order, + is_banner=getattr(vi, 'is_primary', False) + ) for vi in v.images + ] + break + # 2. Compute canonical thumbnail_url + if not self.thumbnail_url: + if self.images: + for img in self.images: + if getattr(img, 'is_banner', False) and img.image_url: + self.thumbnail_url = img.image_url + break + if not self.thumbnail_url and self.images[0].image_url: + self.thumbnail_url = self.images[0].image_url + elif self.variants: + for v in self.variants: + if v.thumbnail_url: + self.thumbnail_url = v.thumbnail_url + break + elif v.images: + self.thumbnail_url = v.images[0].image_url + break + # 3. Propagate fallback thumbnail to any variants that still lack one + if self.thumbnail_url and self.variants: + for v in self.variants: + if not v.thumbnail_url: + v.thumbnail_url = self.thumbnail_url return self class Config: @@ -639,6 +676,10 @@ class ProductCardResponse(BaseModel): first_variant_id: Optional[str] = None badge: Optional[str] = None brand_name: Optional[str] = None + # Variant SEO expansion fields (populated when expand_variants=True) + variant_sku: Optional[str] = None + variant_name: Optional[str] = None + variant_url: Optional[str] = None class Config: from_attributes = True diff --git a/app/schemas/RefundSchema.py b/app/schemas/RefundSchema.py index 5892ad8..f168e69 100644 --- a/app/schemas/RefundSchema.py +++ b/app/schemas/RefundSchema.py @@ -1,4 +1,4 @@ -from pydantic import BaseModel +from pydantic import BaseModel, Field from typing import Optional, List from datetime import datetime @@ -21,7 +21,7 @@ class RefundRequestCreate(BaseModel): entity_type: str # SALES or SERVICE entity_id: str location_id: str - amount: float + amount: float = Field(..., gt=0, description="Refund amount must be positive") payment_method: str # CASH or ONLINE reason: Optional[str] = None part_number_verification: Optional[str] = None # Mandatory if SERVICE diff --git a/app/services/CrmService.py b/app/services/CrmService.py index 31166b5..cd4b82d 100644 --- a/app/services/CrmService.py +++ b/app/services/CrmService.py @@ -16,6 +16,21 @@ class CrmService: # --- CUSTOMER MANAGEMENT --- def create_customer(self, data: CrmCustomerCreate) -> CrmCustomer: + if data.phone: + existing = self.db.execute( + select(CrmCustomer).where( + CrmCustomer.tenant_id == self.tenant_id, + CrmCustomer.phone == data.phone, + CrmCustomer.deleted_at.is_(None) + ) + ).scalar_one_or_none() + if existing: + from fastapi import HTTPException + raise HTTPException( + status_code=409, + detail="Customer with this phone number already exists in CRM" + ) + customer = CrmCustomer( customer_id=str(ulid.ULID()), tenant_id=self.tenant_id, diff --git a/app/services/RefundService.py b/app/services/RefundService.py index 8319568..596d85b 100644 --- a/app/services/RefundService.py +++ b/app/services/RefundService.py @@ -124,6 +124,12 @@ class RefundService: if not refund or refund.status != RefundStatus.PENDING: raise HTTPException(status_code=400, detail="Refund not found or not in PENDING state") + if refund.requested_by == user_id: + raise HTTPException( + status_code=403, + detail="Segregation of Duties Violation: You cannot approve a refund request that you created." + ) + refund.approved_by = user_id refund.approved_at = datetime.now(timezone.utc) if data.admin_notes: diff --git a/app/services/ShiprocketService.py b/app/services/ShiprocketService.py new file mode 100644 index 0000000..99a1cb1 --- /dev/null +++ b/app/services/ShiprocketService.py @@ -0,0 +1,261 @@ +""" +@service ShiprocketService (Backend/app/services/ShiprocketService.py) +@purpose Automated 5-step Shiprocket fulfillment engine: order creation, courier auto-selection, AWB generation, printable label/slip retrieval, and pickup scheduling. +""" +import logging +import json +import httpx +from datetime import datetime, timezone, timedelta +from typing import Dict, Any, Optional, List +from app.core.config.Config import settings + +logger = logging.getLogger("shiprocket") + +class ShiprocketService: + def __init__(self): + self.email = settings.SHIPROCKET_EMAIL + self.password = settings.SHIPROCKET_PASSWORD + self.api_url = settings.SHIPROCKET_API_URL or "https://apiv2.shiprocket.in/v1/external" + self.enabled = settings.SHIPROCKET_ENABLED + self.mode = settings.SHIPROCKET_MODE or "test_label_only" + self.pickup_location = settings.SHIPROCKET_PICKUP_LOCATION or "Primary" + self.pickup_pin = settings.SHIPROCKET_PICKUP_PIN or "110001" + self.token: Optional[str] = None + self.token_expiry: Optional[datetime] = None + + def can_call_live_api(self) -> bool: + return bool(self.enabled and self.email and self.password and self.mode != "test_label_only") + + async def _authenticate(self) -> str: + """Authenticate with Shiprocket API and cache the JWT token.""" + now = datetime.now(timezone.utc) + if self.token and self.token_expiry and now < self.token_expiry: + return self.token + + if not self.email or not self.password: + raise ValueError("Shiprocket email or password not configured") + + async with httpx.AsyncClient(timeout=15.0) as client: + resp = await client.post( + f"{self.api_url}/auth/login", + json={"email": self.email, "password": self.password} + ) + if resp.status_code != 200: + raise RuntimeError(f"Shiprocket auth failed ({resp.status_code}): {resp.text}") + + data = resp.json() + token = data.get("token") + if not token: + raise RuntimeError("Shiprocket auth response missing token") + + self.token = token + # Shiprocket token is valid for 10 days, cache for 9 days + self.token_expiry = now + timedelta(days=9) + return self.token + + async def book_and_schedule_pickup( + self, + order: Any, + weight_kg: float, + courier_preference: Optional[str] = None, + length_cm: float = 10.0, + breadth_cm: float = 15.0, + height_cm: float = 5.0 + ) -> Dict[str, Any]: + """ + Executes the automated 5-step fulfillment pipeline: + 1. Order Creation + 2. Courier Serviceability & Auto Selection + 3. AWB Assignment + 4. Printable Label Generation + 5. Pickup Scheduling + """ + # Parse shipping address + addr = {} + if getattr(order, 'shipping_address_json', None): + try: + addr = json.loads(order.shipping_address_json) + except Exception: + pass + + delivery_pin = str(addr.get("pincode") or addr.get("postal_code") or addr.get("pin") or "110001") + customer_name = addr.get("name") or addr.get("full_name") or "Customer" + customer_phone = addr.get("phone") or "9999999999" + customer_email = addr.get("email") or "customer@ifixkart.com" + street_address = addr.get("address_line1") or addr.get("address") or "Street Address" + city = addr.get("city") or "New Delhi" + state = addr.get("state") or "Delhi" + + # Check if running in sandbox / test mode + if not self.can_call_live_api(): + logger.info("Shiprocket running in sandbox/test mode. Generating mock AWB and printable test label.") + simulated_awb = f"SF{int(datetime.now().timestamp())}" + courier = courier_preference or "BlueDart Surface" + test_label_url = f"/api/v1/shipping/label/preview/{order.order_id}" + return { + "ok": True, + "mode": "sandbox", + "shipment_id": f"sim_ship_{order.order_id[:8]}", + "awb_code": simulated_awb, + "courier_name": courier, + "label_url": test_label_url, + "tracking_url": f"https://shiprocket.co/tracking/{simulated_awb}", + "pickup_scheduled": True, + "message": "Fulfillment created in sandbox mode. Printable label generated." + } + + # --- LIVE SHIPROCKET EXECUTION --- + token = await self._authenticate() + headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json" + } + + # Format items + order_items = [] + for item in getattr(order, 'items', []): + order_items.append({ + "name": item.product_name or "Component", + "sku": item.sku or str(item.item_id), + "units": item.quantity or 1, + "selling_price": float(item.unit_price or 0.0), + "discount": 0, + "tax": 0 + }) + if not order_items: + order_items.append({ + "name": "Electronics Spare Part", + "sku": f"SKU-{order.order_no}", + "units": 1, + "selling_price": float(order.final_amount or 100.0) + }) + + async with httpx.AsyncClient(timeout=30.0) as client: + # STEP 1: CREATE ADHOC ORDER + order_payload = { + "order_id": order.order_no, + "order_date": (order.created_at or datetime.now()).strftime("%Y-%m-%d %H:%M"), + "pickup_location": self.pickup_location, + "billing_customer_name": customer_name, + "billing_last_name": "", + "billing_address": street_address, + "billing_address_2": addr.get("address_line2", ""), + "billing_city": city, + "billing_pincode": delivery_pin, + "billing_state": state, + "billing_country": "India", + "billing_email": customer_email, + "billing_phone": customer_phone, + "shipping_is_billing": True, + "order_items": order_items, + "payment_method": "Prepaid" if order.payment_status == "PAYMENT_CAPTURED" else "COD", + "sub_total": float(order.final_amount or 100.0), + "length": length_cm, + "breadth": breadth_cm, + "height": height_cm, + "weight": max(float(weight_kg), 0.1) + } + + resp = await client.post( + f"{self.api_url}/orders/create/adhoc", + headers=headers, + json=order_payload + ) + if resp.status_code not in (200, 201): + raise RuntimeError(f"Shiprocket order creation failed ({resp.status_code}): {resp.text}") + + order_res = resp.json() + shipment_id = order_res.get("shipment_id") + if not shipment_id: + raise RuntimeError("Shiprocket did not return shipment_id") + + # STEP 2: CHECK SERVICEABILITY & AUTO-SELECT BEST COURIER + courier_id = None + courier_name = courier_preference or "Shiprocket Courier" + try: + serv_params = { + "pickup_postcode": self.pickup_pin, + "delivery_postcode": delivery_pin, + "weight": weight_kg, + "cod": "0" if order.payment_status == "PAYMENT_CAPTURED" else "1" + } + serv_resp = await client.get( + f"{self.api_url}/courier/serviceability/", + headers=headers, + params=serv_params + ) + if serv_resp.status_code == 200: + serv_data = serv_resp.json() + avail = serv_data.get("data", {}).get("available_courier_companies", []) + if avail and isinstance(avail, list): + # Sort by rating descending + avail.sort(key=lambda x: float(x.get("rating", 0) or 0), reverse=True) + courier_id = avail[0].get("courier_company_id") + courier_name = avail[0].get("courier_name", courier_name) + except Exception as e: + logger.warning(f"Could not auto-select courier from serviceability: {e}") + + # STEP 3: ASSIGN AWB + awb_payload = {"shipment_id": shipment_id} + if courier_id: + awb_payload["courier_id"] = courier_id + + awb_resp = await client.post( + f"{self.api_url}/courier/assign/awb", + headers=headers, + json=awb_payload + ) + awb_code = None + if awb_resp.status_code == 200: + awb_data = awb_resp.json() + payload_part = awb_data.get("response", {}).get("data", {}) or awb_data.get("payload", {}) + awb_code = payload_part.get("awb_code") or awb_data.get("awb_code") + if payload_part.get("courier_name"): + courier_name = payload_part.get("courier_name") + + if not awb_code: + raise RuntimeError(f"Shiprocket AWB assignment failed: {awb_resp.text}") + + # STEP 4: GENERATE PRINTABLE LABEL + label_url = None + label_resp = await client.post( + f"{self.api_url}/courier/generate/label", + headers=headers, + json={"shipment_id": [shipment_id]} + ) + if label_resp.status_code == 200: + label_data = label_resp.json() + label_url = label_data.get("label_url") + + # Fallback preview if label URL delayed + if not label_url: + label_url = f"/api/v1/shipping/label/preview/{order.order_id}" + + # STEP 5: SCHEDULE PICKUP + pickup_scheduled = False + try: + pick_resp = await client.post( + f"{self.api_url}/courier/generate/pickup", + headers=headers, + json={"shipment_id": [shipment_id]} + ) + if pick_resp.status_code == 200: + pickup_scheduled = True + except Exception as e: + logger.warning(f"Pickup auto-schedule notice: {e}") + + return { + "ok": True, + "mode": "live", + "shipment_id": str(shipment_id), + "awb_code": str(awb_code), + "courier_name": courier_name, + "label_url": label_url, + "tracking_url": f"https://shiprocket.co/tracking/{awb_code}", + "pickup_scheduled": pickup_scheduled, + "message": "Fulfillment booked and pickup scheduled." + } + + +shiprocket_service = ShiprocketService() + diff --git a/app/services/StorefrontCmsService.py b/app/services/StorefrontCmsService.py index 6907da2..d80b35f 100644 --- a/app/services/StorefrontCmsService.py +++ b/app/services/StorefrontCmsService.py @@ -30,6 +30,7 @@ from app.schemas.StorefrontCmsSchema import ( ReviewModerationResponse, ReviewApprovalPayload, ) +from app.core.database.cache_manager import cache class StorefrontCmsService: @@ -46,18 +47,25 @@ class StorefrontCmsService: # FOOTER INFO # ------------------------------------------------------------------ def get_footer_info(self) -> FooterInfoResponse: + cached = cache.get("cms:footer_info") + if cached: + return FooterInfoResponse(**cached) + row = self.db.get(StorefrontFooterInfo, "default") if not row: - return FooterInfoResponse() - return FooterInfoResponse( - phone=row.phone, - email=row.email, - address=row.address, - copyright=row.copyright, - social_links=self._safe_list(row.social_links), - columns=self._safe_list(row.columns), - payment_methods=self._safe_list(row.payment_methods), - ) + res = FooterInfoResponse() + else: + res = FooterInfoResponse( + phone=row.phone, + email=row.email, + address=row.address, + copyright=row.copyright, + social_links=self._safe_list(row.social_links), + columns=self._safe_list(row.columns), + payment_methods=self._safe_list(row.payment_methods), + ) + cache.set("cms:footer_info", res.model_dump(), ttl_seconds=cache.TTL_SETTINGS) + return res def update_footer_info(self, payload: FooterInfoUpdate, updated_by: str = "admin") -> FooterInfoResponse: row = self.db.get(StorefrontFooterInfo, "default") @@ -82,6 +90,7 @@ class StorefrontCmsService: self.db.commit() self.db.refresh(row) + cache.invalidate_prefix("cms:footer_info") return self.get_footer_info() # ------------------------------------------------------------------ @@ -94,6 +103,10 @@ class StorefrontCmsService: ] def get_settings(self) -> Dict[str, Any]: + cached = cache.get("cms:settings") + if cached is not None: + return cached + rows = self.db.execute(select(StorefrontSettings)).scalars().all() result: Dict[str, Any] = { # Provide defaults for required CMS keys @@ -110,6 +123,7 @@ class StorefrontCmsService: } for r in rows: result[r.key] = r.value + cache.set("cms:settings", result, ttl_seconds=cache.TTL_SETTINGS) return result def update_settings(self, payload: StorefrontSettingsUpdate, updated_by: str = "admin") -> Dict[str, Any]: @@ -123,22 +137,38 @@ class StorefrontCmsService: row = StorefrontSettings(key=key, value=value, updated_by=updated_by) self.db.add(row) self.db.commit() + cache.invalidate_prefix("cms:settings") + cache.invalidate_prefix("settings:") return self.get_settings() # ------------------------------------------------------------------ # MEGA MENU # ------------------------------------------------------------------ def get_mega_menu(self, nav_key: Optional[str] = None) -> Any: + cache_key = f"cms:mega_menu:{nav_key or 'all'}" + cached = cache.get(cache_key) + if cached: + if nav_key: + return MegaMenuResponse(**cached) + return AllMegaMenusResponse( + shop=MegaMenuResponse(**cached.get("shop", {})), + deals=MegaMenuResponse(**cached.get("deals", {})), + products=MegaMenuResponse(**cached.get("products", {})) + ) + if nav_key: row = self.db.get(StorefrontMegaMenu, nav_key) if not row: - return MegaMenuResponse(nav_key=nav_key) - return MegaMenuResponse( - nav_key=row.nav_key, - groups=self._safe_list(row.groups), - promo=row.promo, - featured_category_ids=self._safe_list(row.featured_category_ids), - ) + res = MegaMenuResponse(nav_key=nav_key) + else: + res = MegaMenuResponse( + nav_key=row.nav_key, + groups=self._safe_list(row.groups), + promo=row.promo, + featured_category_ids=self._safe_list(row.featured_category_ids), + ) + cache.set(cache_key, res.model_dump(), ttl_seconds=cache.TTL_SETTINGS) + return res # Return all three menus in one payload keys = ["shop", "deals", "products"] @@ -157,7 +187,9 @@ class StorefrontCmsService: featured_category_ids=self._safe_list(r.featured_category_ids), ) - return AllMegaMenusResponse(shop=_build("shop"), deals=_build("deals"), products=_build("products")) + all_menus = AllMegaMenusResponse(shop=_build("shop"), deals=_build("deals"), products=_build("products")) + cache.set(cache_key, all_menus.model_dump(), ttl_seconds=cache.TTL_SETTINGS) + return all_menus def update_mega_menu(self, payload: MegaMenuUpdate, updated_by: str = "admin") -> MegaMenuResponse: row = self.db.get(StorefrontMegaMenu, payload.nav_key) @@ -174,6 +206,7 @@ class StorefrontCmsService: self.db.commit() self.db.refresh(row) + cache.invalidate_prefix("cms:mega_menu") return self.get_mega_menu(payload.nav_key) # ------------------------------------------------------------------ @@ -193,16 +226,23 @@ class StorefrontCmsService: ] def get_catalog_filters(self) -> CatalogFiltersResponse: + cached = cache.get("cms:catalog_filters") + if cached: + return CatalogFiltersResponse(**cached) + row = self.db.get(StorefrontCatalogFilters, "default") if not row: - return CatalogFiltersResponse( + res = CatalogFiltersResponse( highlights=self._DEFAULT_HIGHLIGHTS, price_ranges=self._DEFAULT_PRICE_RANGES, ) - return CatalogFiltersResponse( - highlights=self._safe_list(row.highlights) or self._DEFAULT_HIGHLIGHTS, - price_ranges=self._safe_list(row.price_ranges) or self._DEFAULT_PRICE_RANGES, - ) + else: + res = CatalogFiltersResponse( + highlights=self._safe_list(row.highlights) or self._DEFAULT_HIGHLIGHTS, + price_ranges=self._safe_list(row.price_ranges) or self._DEFAULT_PRICE_RANGES, + ) + cache.set("cms:catalog_filters", res.model_dump(), ttl_seconds=cache.TTL_SETTINGS) + return res def update_catalog_filters(self, payload: CatalogFiltersUpdate) -> CatalogFiltersResponse: row = self.db.get(StorefrontCatalogFilters, "default") @@ -217,6 +257,7 @@ class StorefrontCmsService: self.db.commit() self.db.refresh(row) + cache.invalidate_prefix("cms:catalog_filters") return self.get_catalog_filters() # ------------------------------------------------------------------ @@ -233,6 +274,8 @@ class StorefrontCmsService: self.db.commit() self.db.refresh(cat) + cache.invalidate_prefix("cms:mega_menu") + cache.invalidate_prefix("catalog:categories") return { "category_id": cat.category_id, "name": cat.name, @@ -265,6 +308,7 @@ class StorefrontCmsService: review.admin_reply = payload.admin_reply self.db.commit() self.db.refresh(review) + cache.invalidate_prefix(f"reviews:{review.product_id}") return self._map_review(review) def reject_review(self, review_id: str) -> ReviewModerationResponse: @@ -275,6 +319,7 @@ class StorefrontCmsService: review.is_approved = False self.db.commit() self.db.refresh(review) + cache.invalidate_prefix(f"reviews:{review.product_id}") return self._map_review(review) def _map_review(self, r: ProductReview) -> ReviewModerationResponse: diff --git a/app/services/StorefrontService.py b/app/services/StorefrontService.py index b19f3ef..7e3db43 100644 --- a/app/services/StorefrontService.py +++ b/app/services/StorefrontService.py @@ -9,9 +9,7 @@ import ulid from app.repositories.StorefrontRepository import StorefrontRepository from app.models.StorefrontContentModel import StorefrontContent, ContentStatusEnum from app.models.ProductReviewModel import ProductReview - -# In-Memory Cache Store for high performance -_IN_MEMORY_CACHE: Dict[str, Any] = {} +from app.core.database.cache_manager import cache class StorefrontService: def __init__(self, db: Session): @@ -41,16 +39,16 @@ class StorefrontService: return result def invalidate_cache(self, pattern: Optional[str] = None): - global _IN_MEMORY_CACHE if pattern: - _IN_MEMORY_CACHE = {k: v for k, v in _IN_MEMORY_CACHE.items() if not k.startswith(pattern)} + cache.invalidate_prefix(pattern) else: - _IN_MEMORY_CACHE.clear() + cache.clear() def get_reviews(self, product_id: str) -> List[Dict[str, Any]]: cache_key = f"reviews:{product_id}" - if cache_key in _IN_MEMORY_CACHE: - return _IN_MEMORY_CACHE[cache_key] + cached_reviews = cache.get(cache_key) + if cached_reviews is not None: + return cached_reviews reviews = self.repo.get_approved_reviews(product_id) result = [ @@ -70,15 +68,16 @@ class StorefrontService: for r in reviews ] - _IN_MEMORY_CACHE[cache_key] = result + cache.set(cache_key, result, ttl_seconds=cache.TTL_SETTINGS) return result def get_public_settings(self, group: Optional[str] = None) -> Dict[str, Any]: cache_key = f"settings:public:{group or 'all'}" - if cache_key in _IN_MEMORY_CACHE: - return _IN_MEMORY_CACHE[cache_key] + cached_settings = cache.get(cache_key) + if cached_settings is not None: + return cached_settings settings = self.repo.get_public_settings(group) result = {s.setting_key: s.setting_value for s in settings} - _IN_MEMORY_CACHE[cache_key] = result + cache.set(cache_key, result, ttl_seconds=cache.TTL_SETTINGS) return result diff --git a/app/services/migration_engine/media_resolver.py b/app/services/migration_engine/media_resolver.py index 6bd1dc9..8414fb9 100644 --- a/app/services/migration_engine/media_resolver.py +++ b/app/services/migration_engine/media_resolver.py @@ -152,11 +152,22 @@ class MediaResolver: media_groups: Dict[canonical_media_key, metadata_dict] media_files: List[file_metadata_dict] """ - os.makedirs(extract_to_dir, exist_ok=True) + abs_extract_dir = os.path.abspath(extract_to_dir) + os.makedirs(abs_extract_dir, exist_ok=True) with zipfile.ZipFile(zip_path, 'r') as zip_ref: entries = zip_ref.infolist() wrapper_prefix = cls.detect_archive_wrapper(entries) - zip_ref.extractall(extract_to_dir) + # Safe entry-by-entry extraction with path containment to prevent Zip-Slip + for entry in entries: + # Discard symlinks (external_attr high bits 0o120000) + if (entry.external_attr >> 16) & 0o170000 == 0o120000: + continue + + dest_path = os.path.abspath(os.path.join(abs_extract_dir, entry.filename)) + if not dest_path.startswith(abs_extract_dir + os.sep) and dest_path != abs_extract_dir: + continue # Refuse to extract path escaping target directory + + zip_ref.extract(entry, abs_extract_dir) media_groups: Dict[str, Dict[str, Any]] = {} media_files: List[Dict[str, Any]] = [] diff --git a/app/services/migration_engine/migration_worker.py b/app/services/migration_engine/migration_worker.py index 41a3e6f..3cc15f0 100644 --- a/app/services/migration_engine/migration_worker.py +++ b/app/services/migration_engine/migration_worker.py @@ -521,22 +521,29 @@ class MigrationWorker: return chunk_entries = all_entries[i:i+batch_size] + valid_chunk_entries = [ + e for e in chunk_entries + if os.path.splitext(e.filename)[1].lower() in ('.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.tiff') + ] - for entry in chunk_entries: - ext = os.path.splitext(entry.filename)[1].lower() - if ext not in ('.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.tiff'): - continue + if not valid_chunk_entries: + self.update_phase_checkpoint(db, job_id, PhaseEnum.MEDIA_PROCESS, batch_number, (len(all_entries)//batch_size)+1, job.processed_records, job.failed_records) + db.commit() + continue - # Check existing MigrationMediaItem status for resume semantics - existing_item = db.query(MigrationMediaItem).filter( - MigrationMediaItem.job_id == job_id, - MigrationMediaItem.zip_entry_path == entry.filename - ).first() + # Bulk fetch existing MigrationMediaItem records for this chunk to avoid WAN RTT per item + entry_filenames = [e.filename for e in valid_chunk_entries] + existing_items = db.query(MigrationMediaItem).filter( + MigrationMediaItem.job_id == job_id, + MigrationMediaItem.zip_entry_path.in_(entry_filenames) + ).all() + existing_items_map = {item.zip_entry_path: item for item in existing_items} - if existing_item and existing_item.status == MediaItemStatusEnum.REGISTERED: - existing_item.media_key = media_key - existing_item.status = MediaItemStatusEnum.STORED + job_config = StorageManager.get_job_config(job_id) + media_struct = job_config.get("media_structure", "AUTO") + for entry in valid_chunk_entries: + existing_item = existing_items_map.get(entry.filename) try: # Stream file bytes directly from ZIP with zf.open(entry) as f_entry: @@ -544,12 +551,8 @@ class MigrationWorker: import hashlib sha256_hash = hashlib.sha256(file_bytes).hexdigest() - dir_path = os.path.dirname(entry.filename) - job_config = StorageManager.get_job_config(job_id) - media_struct = job_config.get("media_structure", "AUTO") media_key = MediaResolver.resolve_entry_media_key(entry.filename, wrapper_prefix=wrapper_prefix, media_structure=media_struct) - # Atomic POSIX write: temp write -> fsync -> rename -> STORED storage_path, cdn_url, width, height = StorageManager.write_media_file_atomically( job_id, file_bytes, os.path.basename(entry.filename), sha256_hash diff --git a/app/services/migration_engine/upsert_executor.py b/app/services/migration_engine/upsert_executor.py index ad24119..789a398 100644 --- a/app/services/migration_engine/upsert_executor.py +++ b/app/services/migration_engine/upsert_executor.py @@ -6,7 +6,7 @@ from typing import List, Dict, Any, Tuple from decimal import Decimal from sqlalchemy.orm import Session import app.models.db_base -from app.models.ProductModel import Product, ProductVariant, VariantImage, AttributeType, VariantAttribute, ProductLocation +from app.models.ProductModel import Product, ProductVariant, VariantImage, AttributeType, VariantAttribute, ProductLocation, ProductImage from app.models.BrandModel import Brand from app.models.CategoryModel import Category from app.models.DeviceCatalogModel import DeviceSeries, DeviceModel, ServiceType, RepairService, RepairVariant @@ -645,6 +645,45 @@ class UpsertExecutor: is_primary=(idx == 0) ) db_session.add(var_img) + + # Auto-promote primary variant image to parent ProductImage if parent has none + existing_p_img = db_session.query(ProductImage).filter(ProductImage.product_id == prod.product_id).first() + if not existing_p_img: + new_p_img = ProductImage( + image_id=str(ulid.ULID()), + product_id=prod.product_id, + image_url=all_matched_assets[0].cdn_url, + alt_text=prod.name[:2000] if prod.name else "Product Image", + sort_order=0, + is_banner=False + ) + db_session.add(new_p_img) + else: + # Variant has no media key in CSV: auto-inherit from sibling variant or parent product + sibling_v_img = ( + db_session.query(VariantImage) + .join(ProductVariant, VariantImage.variant_id == ProductVariant.variant_id) + .filter(ProductVariant.product_id == prod.product_id, VariantImage.image_url.isnot(None), VariantImage.image_url != "") + .order_by(VariantImage.is_primary.desc(), VariantImage.sort_order.asc()) + .first() + ) + fallback_url = sibling_v_img.image_url if sibling_v_img else None + if not fallback_url: + parent_img = db_session.query(ProductImage).filter(ProductImage.product_id == prod.product_id).first() + if parent_img and parent_img.image_url: + fallback_url = parent_img.image_url + + if fallback_url: + existing_v_imgs = db_session.query(VariantImage).filter(VariantImage.variant_id == variant.variant_id).first() + if not existing_v_imgs: + inherited_img = VariantImage( + image_id=str(ulid.ULID()), + variant_id=variant.variant_id, + image_url=fallback_url, + sort_order=0, + is_primary=True + ) + db_session.add(inherited_img) # 7. Update inventory ledger stock level stock_val = mapped_row.get("stock") if stock_val is not None and str(stock_val).strip() != "": diff --git a/app/utils/Hash_util.py b/app/utils/Hash_util.py index 0f97e32..e17f1c3 100644 --- a/app/utils/Hash_util.py +++ b/app/utils/Hash_util.py @@ -1,3 +1,4 @@ +from typing import Optional from passlib.context import CryptContext import hashlib @@ -9,5 +10,7 @@ def hash_password(pwd: str) -> str: def verify_password(pwd: str, hash: str) -> bool: return pwd_context.verify(pwd, hash) -def hash_token(token: str) -> str: - return hashlib.sha256(token.encode()).hexdigest() +def hash_token(token: Optional[str]) -> str: + if not token: + return "" + return hashlib.sha256(token.encode("utf-8")).hexdigest() diff --git a/gunicorn.conf.py b/gunicorn.conf.py new file mode 100644 index 0000000..80c77cf --- /dev/null +++ b/gunicorn.conf.py @@ -0,0 +1,24 @@ +# Gunicorn configuration for iFixKart Unified Commerce Backend +import os + +# Bind strictly to local loopback (Nginx reverse-proxies from port 80/443 on the same host) +bind = os.getenv("GUNICORN_BIND", "127.0.0.1:8010") + +# Multi-worker process model: 4 workers across multi-core CPU +workers = int(os.getenv("GUNICORN_WORKERS", "4")) +worker_class = "uvicorn.workers.UvicornWorker" + +# Timeouts +timeout = 120 +graceful_timeout = 30 +keepalive = 5 + +# Logging +accesslog = "-" +errorlog = "-" +loglevel = os.getenv("GUNICORN_LOGLEVEL", "info") + +# Worker recycling to mitigate long-running memory creep +max_requests = 2000 +max_requests_jitter = 400 + diff --git a/scripts/deploy_to_production.py b/scripts/deploy_to_production.py index fb5c48b..b6856ce 100644 --- a/scripts/deploy_to_production.py +++ b/scripts/deploy_to_production.py @@ -69,8 +69,8 @@ run_remote("cd /var/www/html/ifixkartdev && npm run build && pm2 restart ifixkar print("--- Running Database Column Migration on Remote Host ---") run_remote("cd /var/www/fastapi/ifixkart && PYTHONPATH=. venv/bin/python3 -c \"from app.core.database.db_session import SessionLocal; from sqlalchemy import text; db=SessionLocal(); db.execute(text('ALTER TABLE products ADD COLUMN show_specifications TINYINT(1) NOT NULL DEFAULT 1')); db.commit(); print('DB Column show_specifications added successfully!')\" || true") -print("--- Restarting FastAPI Backend Service if applicable ---") -run_remote("pkill -f 'uvicorn app.main:app' || true") +print("--- Restarting FastAPI Backend Service (port 8010) ---") +run_remote("systemctl restart ifixkart.service || (pkill -f 'gunicorn app.main:app' ; pkill -f 'uvicorn app.main:app' || true)") sftp.close() ssh.close() diff --git a/scripts/heal_catalog_media.py b/scripts/heal_catalog_media.py new file mode 100644 index 0000000..08890a2 --- /dev/null +++ b/scripts/heal_catalog_media.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +""" +Catalog Media Self-Healing Script (High-Performance Batch Engine) +Ensures that: +1. Every variant without images inherits the primary image from a sibling variant or parent product. +2. Every product without images in product_images gets a promoted primary image from its variants. +""" + +import os +import sys +import time +from pathlib import Path + +backend_dir = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(backend_dir)) +os.chdir(str(backend_dir)) + +from dotenv import load_dotenv +load_dotenv(".env") + +import app.models.db_base # noqa: F401 +import ulid +from sqlalchemy import text +from app.core.database.db_session import SessionLocal + +def heal_catalog_media(): + db = SessionLocal() + start_time = time.time() + try: + print("[*] Fetching catalog mapping for media self-healing...") + + # 1. Fetch all products and their names + prod_rows = db.execute(text("SELECT product_id, name FROM products")).fetchall() + prod_names = {r[0]: r[1] for r in prod_rows} + print(f"[*] Total products in database: {len(prod_names)}") + + # 2. Fetch all variants + v_rows = db.execute(text("SELECT variant_id, product_id, sku FROM product_variants")).fetchall() + print(f"[*] Total variants in database: {len(v_rows)}") + + variants_by_product = {} + product_by_variant = {} + for vid, pid, sku in v_rows: + variants_by_product.setdefault(pid, []).append(vid) + product_by_variant[vid] = pid + + # 3. Fetch all variant images + vi_rows = db.execute(text( + "SELECT variant_id, image_url, is_primary, sort_order FROM variant_images WHERE image_url IS NOT NULL AND image_url != ''" + )).fetchall() + print(f"[*] Total existing variant images: {len(vi_rows)}") + + v_has_images = set() + p_candidate_images = {} # product_id -> list of (is_primary, sort_order, image_url) + + for vid, url, is_primary, sort_order in vi_rows: + v_has_images.add(vid) + pid = product_by_variant.get(vid) + if pid: + p_candidate_images.setdefault(pid, []).append((1 if is_primary else 0, sort_order or 0, url)) + + # 4. Fetch all product images + pi_rows = db.execute(text( + "SELECT product_id, image_url, sort_order FROM product_images WHERE image_url IS NOT NULL AND image_url != ''" + )).fetchall() + print(f"[*] Total existing product images: {len(pi_rows)}") + + p_has_images = set() + for pid, url, sort_order in pi_rows: + p_has_images.add(pid) + if pid not in p_candidate_images: + p_candidate_images.setdefault(pid, []).append((1, sort_order or 0, url)) + + # 5. Determine candidates to heal + bulk_variant_images = [] + bulk_product_images = [] + + def get_best_url(pid): + cands = p_candidate_images.get(pid) + if not cands: + return None + # Sort by is_primary DESC, sort_order ASC + sorted_cands = sorted(cands, key=lambda x: (-x[0], x[1])) + return sorted_cands[0][2] + + # A) Check empty variants + for vid, pid, sku in v_rows: + if vid not in v_has_images: + best_url = get_best_url(pid) + if best_url: + bulk_variant_images.append({ + "image_id": str(ulid.ULID()), + "variant_id": vid, + "image_url": best_url, + "sort_order": 0, + "is_primary": 1 + }) + v_has_images.add(vid) + + # B) Check empty products + for pid, name in prod_names.items(): + if pid not in p_has_images: + best_url = get_best_url(pid) + if best_url: + bulk_product_images.append({ + "image_id": str(ulid.ULID()), + "product_id": pid, + "image_url": best_url, + "alt_text": name[:2000] if name else "Product Image", + "sort_order": 0, + "is_banner": 0 + }) + p_has_images.add(pid) + + print(f"[*] Healing plan: {len(bulk_variant_images)} empty variants, {len(bulk_product_images)} empty products.") + + # 6. Bulk Insert + if bulk_variant_images: + db.execute(text( + "INSERT INTO variant_images (image_id, variant_id, image_url, sort_order, is_primary) " + "VALUES (:image_id, :variant_id, :image_url, :sort_order, :is_primary)" + ), bulk_variant_images) + + if bulk_product_images: + db.execute(text( + "INSERT INTO product_images (image_id, product_id, image_url, alt_text, sort_order, is_banner) " + "VALUES (:image_id, :product_id, :image_url, :alt_text, :sort_order, :is_banner)" + ), bulk_product_images) + + db.commit() + elapsed = time.time() - start_time + print(f"[+] SUCCESS: Healed {len(bulk_variant_images)} variants and {len(bulk_product_images)} products in {elapsed:.2f}s!") + + except Exception as e: + db.rollback() + print(f"[-] Error during media healing: {e}") + raise + finally: + db.close() + +if __name__ == "__main__": + heal_catalog_media() diff --git a/scripts/ifixkart.service b/scripts/ifixkart.service new file mode 100644 index 0000000..d2d703d --- /dev/null +++ b/scripts/ifixkart.service @@ -0,0 +1,17 @@ +[Unit] +Description=iFixKart Unified Commerce FastAPI Backend (Gunicorn + Uvicorn) +After=network.target mysql.service + +[Service] +User=root +WorkingDirectory=/var/www/fastapi/ifixkart +Environment="PATH=/var/www/fastapi/ifixkart/venv/bin" +Environment="ENABLE_MIGRATION_WORKER=1" +ExecStart=/var/www/fastapi/ifixkart/venv/bin/gunicorn app.main:app -c gunicorn.conf.py +Restart=always +RestartSec=3 +LimitNOFILE=65535 + +[Install] +WantedBy=multi-user.target + diff --git a/scripts/verify_remediation.py b/scripts/verify_remediation.py new file mode 100644 index 0000000..cda3b54 --- /dev/null +++ b/scripts/verify_remediation.py @@ -0,0 +1,160 @@ +""" +Verification Script for Scalability & Security Remediation +Tests all 8 remediations locally against Backend modules. +""" +import os +import sys +import hashlib + +# Add Backend to python path +backend_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +sys.path.insert(0, backend_path) + +from dotenv import load_dotenv +load_dotenv(os.path.join(backend_path, ".env")) + +def test_1_pool_math(): + print("Test 1: Pool configuration...") + from app.core.database.db_session import engine_core, engine_crm, engine_commerce + for name, eng in [("engine_core", engine_core), ("engine_crm", engine_crm), ("engine_commerce", engine_commerce)]: + pool = eng.pool + print(f" - {name}: size={pool.size()}, max_overflow={pool._max_overflow}, recycle={pool._recycle}") + assert pool.size() == 10, f"Expected pool_size=10, got {pool.size()}" + assert pool._max_overflow == 10, f"Expected max_overflow=10, got {pool._max_overflow}" + assert pool._recycle == 1800, f"Expected pool_recycle=1800, got {pool._recycle}" + print(" ✓ Test 1 Passed: Pool size=10, max_overflow=10, recycle=1800 on all 3 engines (240 max connections total across 4 workers).") + +def test_2_limiter_redis_fallback(): + print("Test 2: SlowAPI Redis / Memory limiter...") + from app.core.limiter import limiter + print(f" - Limiter storage uri: {limiter._storage_uri}") + assert limiter is not None + print(" ✓ Test 2 Passed: Limiter initialized with Redis/fallback memory storage.") + +def test_3_poller_gating(): + print("Test 3: Poller gating...") + # Verify main.py has ENABLE_MIGRATION_WORKER check + main_file = os.path.join(backend_path, "app", "main.py") + with open(main_file, "r") as f: + content = f.read() + assert 'os.getenv("ENABLE_MIGRATION_WORKER", "0") == "1"' in content + print(" ✓ Test 3 Passed: Migration and media poller threads gated behind ENABLE_MIGRATION_WORKER.") + +def test_4_cache_manager(): + print("Test 4: Cache manager SCAN and TTL constants...") + from app.core.database.cache_manager import cache, CacheManager + assert hasattr(cache, "TTL_SETTINGS") and cache.TTL_SETTINGS == 1800 + assert hasattr(cache, "TTL_CATALOG") and cache.TTL_CATALOG == 900 + assert hasattr(cache, "TTL_PRODUCTS") and cache.TTL_PRODUCTS == 300 + + # Test setting and reading + cache.set("test_key_1", {"hello": "world"}, ttl_seconds=60) + val = cache.get("test_key_1") + assert val == {"hello": "world"}, f"Cache get failed: {val}" + + # Test prefix invalidation + cache.invalidate_prefix("test_key_") + assert cache.get("test_key_1") is None + print(" ✓ Test 4 Passed: CacheManager supports TTL constants, scan_iter invalidation, and fallback.") + +def test_5_cors_whitelist(): + print("Test 5: CORS whitelist single source of truth...") + from app.main import ALLOWED_ORIGINS, ALLOWED_ORIGINS_SET, append_cors_headers + from fastapi.responses import JSONResponse + from starlette.requests import Request + + # Check that wildcards are gone + for origin in ALLOWED_ORIGINS: + assert not origin.startswith("*"), f"Wildcard origin found: {origin}" + assert not "(:[0-9]+)?" in origin, f"Regex wildcard found: {origin}" + + # Test append_cors_headers with mock Request + class MockRequest: + def __init__(self, origin_header): + self.headers = {"origin": origin_header} if origin_header else {} + + res1 = JSONResponse(content={"error": "not found"}, status_code=404) + # Disallowed origin + append_cors_headers(res1, MockRequest("https://evil-hacker.com")) + assert "access-control-allow-origin" not in res1.headers + + # Allowed origin + res2 = JSONResponse(content={"error": "not found"}, status_code=404) + append_cors_headers(res2, MockRequest("http://localhost:3021")) + assert res2.headers.get("access-control-allow-origin") == "http://localhost:3021" + assert res2.headers.get("access-control-allow-credentials") == "true" + print(" ✓ Test 5 Passed: CORS whitelist strictly enforced on custom exception handlers.") + +def test_6_refresh_token_hash(): + print("Test 6: Refresh token hashing and dual-lookup logic...") + from app.utils.Hash_util import hash_token + token = "sample_raw_refresh_token_12345" + h1 = hash_token(token) + h2 = hashlib.sha256(token.encode("utf-8")).hexdigest() + assert h1 == h2, "hash_token did not produce SHA-256 hex digest" + assert hash_token(None) == "" + print(" ✓ Test 6 Passed: SHA-256 refresh token hashing verified.") + +def test_7_role_checker_no_query_param(): + print("Test 7: RoleChecker query param removal...") + checker_file = os.path.join(backend_path, "app", "core", "permissions", "RoleChecker.py") + with open(checker_file, "r") as f: + content = f.read() + assert 'request.query_params.get("token")' not in content, "Query param token still present in RoleChecker!" + print(" ✓ Test 7 Passed: JWT in query params removed from standard RoleChecker.") + +def test_8_webhook_locks(): + print("Test 8: Webhook row locks...") + orch_file = os.path.join(backend_path, "app", "core", "payment_orchestrator.py") + with open(orch_file, "r") as f: + content = f.read() + assert "with_for_update()" in content, "Row locking with_for_update not found in payment_orchestrator!" + assert 'order.payment_status != "PAYMENT_CAPTURED"' in content, "PAYMENT_CAPTURED idempotency check missing!" + print(" ✓ Test 8 Passed: Webhook row locks and double-deduction guards verified.") + +def test_9_n_plus_one_optimizations(): + print("Test 9: Hot-path N+1 query optimizations...") + catalog_file = os.path.join(backend_path, "app", "api/v1/routers/CatalogRouter.py") + with open(catalog_file, "r") as f: + content = f.read() + assert "selectinload(Product.brand)" in content + + cart_file = os.path.join(backend_path, "app", "api/v1/routers/CartRouter.py") + with open(cart_file, "r") as f: + cart_content = f.read() + assert "joinedload(ProductVariant.product)" in cart_content + assert "get_available_stock_map(variant_ids, db)" in cart_content + print(" ✓ Test 9 Passed: selectinload(Product.brand) in Catalog and joinedload + batch stock in Cart verified.") + +def test_10_sse_ticket_flow(): + print("Test 10: SSE single-use ticket logic...") + from app.core.database.cache_manager import cache + import secrets + + # Generate ticket as in MigrationRouter.py + ticket = secrets.token_urlsafe(32) + cache.set(f"sse_ticket:{ticket}", "user_123", ttl_seconds=30) + + # Verify ticket exists + assert cache.get(f"sse_ticket:{ticket}") == "user_123" + + # Burn ticket on first use + cache.delete(f"sse_ticket:{ticket}") + assert cache.get(f"sse_ticket:{ticket}") is None, "SSE ticket must be burned after single use" + print(" ✓ Test 10 Passed: SSE ticket generates, validates, and single-use burns successfully.") + +if __name__ == "__main__": + print("\n--- Running Scalability & Security Verification Suite ---\n") + test_1_pool_math() + test_2_limiter_redis_fallback() + test_3_poller_gating() + test_4_cache_manager() + test_5_cors_whitelist() + test_6_refresh_token_hash() + test_7_role_checker_no_query_param() + test_8_webhook_locks() + test_9_n_plus_one_optimizations() + test_10_sse_ticket_flow() + print("\n=======================================================") + print("ALL REMEDIATION SUITE TESTS PASSED SUCCESSFULLY! (10/10)") + print("=======================================================\n")