From 593e0a972d5646b7b3eabd82578c436008905a64 Mon Sep 17 00:00:00 2001 From: iFixKart Dev Date: Fri, 6 Nov 2026 14:30:05 +0530 Subject: [PATCH] feat(coupons-discounts): rule-based coupon engine, POS trade discounts and billing ledger --- .gitignore | 1 + app/api/v1/routers/AdminCouponRouter.py | 343 ++++++++++++++ app/api/v1/routers/AdminOrderRouter.py | 41 +- app/api/v1/routers/CartRouter.py | 171 ++++++- app/api/v1/routers/CheckoutRouter.py | 3 +- app/api/v1/routers/CustomerAuthRouter.py | 3 + app/api/v1/routers/SimulationPaymentRouter.py | 149 ++++++ app/core/config/Config.py | 5 + app/core/limiter.py | 6 + app/core/payment_orchestrator.py | 4 + app/main.py | 7 + app/models/CouponModel.py | 63 +++ app/models/OrderModel.py | 7 +- app/services/CouponService.py | 209 +++++++++ app/services/InventoryService.py | 3 + app/services/OrderService.py | 152 +++++- .../migration_engine/migration_worker.py | 9 + scripts/sim/provision_sim_db.py | 433 ++++++++++++++++++ scripts/sim/run_sim_backend.py | 53 +++ scripts/sim/seed_customers.py | 238 ++++++++++ 20 files changed, 1875 insertions(+), 25 deletions(-) create mode 100644 app/api/v1/routers/AdminCouponRouter.py create mode 100644 app/api/v1/routers/SimulationPaymentRouter.py create mode 100644 app/models/CouponModel.py create mode 100644 app/services/CouponService.py create mode 100644 scripts/sim/provision_sim_db.py create mode 100644 scripts/sim/run_sim_backend.py create mode 100644 scripts/sim/seed_customers.py diff --git a/.gitignore b/.gitignore index 6821db1..a69d358 100644 --- a/.gitignore +++ b/.gitignore @@ -71,3 +71,4 @@ test_warranty_flow.py test_zeptomail.py unlock.py update_cashify_exact_images.py +sim-artifacts/ diff --git a/app/api/v1/routers/AdminCouponRouter.py b/app/api/v1/routers/AdminCouponRouter.py new file mode 100644 index 0000000..3396550 --- /dev/null +++ b/app/api/v1/routers/AdminCouponRouter.py @@ -0,0 +1,343 @@ +""" +@router AdminCouponRouter (Backend/app/api/v1/routers/AdminCouponRouter.py) +@purpose CRM Admin management of promotional coupons, rule engines, and usage audits. +""" +from fastapi import APIRouter, Depends, HTTPException, status, Query +from sqlalchemy.orm import Session +from pydantic import BaseModel, Field +from typing import List, Optional, Dict, Any +from datetime import datetime +import json +import ulid + +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.models.CouponModel import Coupon, CouponUsage +from app.services.CouponService import CouponService + +router = APIRouter(prefix="/api/v1/admin/coupons", tags=["Admin Promotional Coupons"]) + +# --- Pydantic Schemas --- + +class CouponCreateRequest(BaseModel): + code: str = Field(..., min_length=2, max_length=50) + description: Optional[str] = None + discount_type: str = Field(..., pattern="^(PERCENT|FIXED)$") + discount_value: float = Field(..., gt=0) + min_order_amount: Optional[float] = 0.0 + max_discount_cap: Optional[float] = None + first_order_only: bool = False + channel_scope: str = Field(default="ALL", pattern="^(ALL|STOREFRONT|STORE_POS)$") + usage_limit_total: Optional[int] = None + usage_limit_per_customer: Optional[int] = 1 + applicable_category_ids: Optional[List[str]] = None + applicable_brand_ids: Optional[List[str]] = None + applicable_model_ids: Optional[List[str]] = None + start_date: Optional[datetime] = None + end_date: Optional[datetime] = None + is_active: bool = True + +class CouponUpdateRequest(BaseModel): + description: Optional[str] = None + discount_type: Optional[str] = Field(None, pattern="^(PERCENT|FIXED)$") + discount_value: Optional[float] = Field(None, gt=0) + min_order_amount: Optional[float] = None + max_discount_cap: Optional[float] = None + first_order_only: Optional[bool] = None + channel_scope: Optional[str] = Field(None, pattern="^(ALL|STOREFRONT|STORE_POS)$") + usage_limit_total: Optional[int] = None + usage_limit_per_customer: Optional[int] = None + applicable_category_ids: Optional[List[str]] = None + applicable_brand_ids: Optional[List[str]] = None + applicable_model_ids: Optional[List[str]] = None + start_date: Optional[datetime] = None + end_date: Optional[datetime] = None + is_active: Optional[bool] = None + +class CouponUsageSummary(BaseModel): + usage_id: str + coupon_id: str + customer_id: str + order_id: str + discount_amount: float + used_at: datetime + +class CouponResponse(BaseModel): + coupon_id: str + code: str + description: Optional[str] + discount_type: str + discount_value: float + min_order_amount: float + max_discount_cap: Optional[float] + first_order_only: bool + channel_scope: str + usage_limit_total: Optional[int] + usage_limit_per_customer: int + current_usage_count: int + applicable_category_ids: Optional[List[str]] + applicable_brand_ids: Optional[List[str]] + applicable_model_ids: Optional[List[str]] + start_date: Optional[datetime] + end_date: Optional[datetime] + is_active: bool + created_at: datetime + updated_at: datetime + +def _normalize_channel_in(val: Optional[str]) -> str: + if not val: + return "OMNICHANNEL" + u = val.strip().upper() + if u in ["STOREFRONT", "ONLINE", "ONLINE_ONLY"]: + return "ONLINE_ONLY" + if u in ["STORE_POS", "POS", "POS_ONLY"]: + return "POS_ONLY" + return "OMNICHANNEL" + +def _normalize_channel_out(val: Optional[str]) -> str: + if not val: + return "ALL" + u = val.strip().upper() + if u == "ONLINE_ONLY": + return "STOREFRONT" + if u == "POS_ONLY": + return "STORE_POS" + return "ALL" + +def _normalize_discount_type_in(val: str) -> str: + u = val.strip().upper() + if u in ["PERCENT", "PERCENTAGE"]: + return "PERCENTAGE" + return "FIXED" + +def _normalize_discount_type_out(val: str) -> str: + u = val.strip().upper() + if u in ["PERCENTAGE", "PERCENT"]: + return "PERCENT" + return "FIXED" + +def _coupon_to_response(coupon: Coupon) -> Dict[str, Any]: + def _parse_json_list(val): + if not val: + return [] + if isinstance(val, list): + return val + try: + return json.loads(val) + except Exception: + return [] + + return { + "coupon_id": coupon.coupon_id, + "code": coupon.code, + "description": coupon.description or coupon.title, + "discount_type": _normalize_discount_type_out(coupon.discount_type), + "discount_value": float(coupon.discount_value), + "min_order_amount": float(coupon.min_order_amount or 0.0), + "max_discount_cap": float(coupon.max_discount_cap) if coupon.max_discount_cap is not None else None, + "first_order_only": bool(coupon.first_order_only), + "channel_scope": _normalize_channel_out(coupon.channel_scope), + "usage_limit_total": coupon.usage_limit_total, + "usage_limit_per_customer": coupon.usage_limit_per_customer or 1, + "current_usage_count": coupon.times_used or 0, + "applicable_category_ids": _parse_json_list(coupon.applicable_category_ids), + "applicable_brand_ids": _parse_json_list(coupon.applicable_brand_ids), + "applicable_model_ids": _parse_json_list(coupon.applicable_model_ids), + "start_date": coupon.valid_from, + "end_date": coupon.valid_to, + "is_active": bool(coupon.is_active), + "created_at": coupon.created_at, + "updated_at": coupon.updated_at + } + +# --- Router Endpoints --- + +@router.get("", response_model=List[CouponResponse]) +def list_coupons( + search: Optional[str] = Query(None, description="Search by code or description"), + channel: Optional[str] = Query(None, description="Filter by channel scope"), + is_active: Optional[bool] = Query(None, description="Filter by active status"), + first_order_only: Optional[bool] = Query(None, description="Filter 1st-time customer rules"), + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db) +): + """ + List all promotion coupons with optional filtering. + """ + query = db.query(Coupon) + if search: + s = f"%{search.strip().upper()}%" + query = query.filter((Coupon.code.like(s)) | (Coupon.description.like(f"%{search.strip()}%")) | (Coupon.title.like(f"%{search.strip()}%"))) + if channel: + norm_chan = _normalize_channel_in(channel) + query = query.filter(Coupon.channel_scope == norm_chan) + if is_active is not None: + query = query.filter(Coupon.is_active == is_active) + if first_order_only is not None: + query = query.filter(Coupon.first_order_only == first_order_only) + + coupons = query.order_by(Coupon.created_at.desc()).all() + return [_coupon_to_response(c) for c in coupons] + +@router.get("/{coupon_id}", response_model=CouponResponse) +def get_coupon( + coupon_id: str, + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db) +): + """ + Get a single coupon by ID. + """ + coupon = db.query(Coupon).filter(Coupon.coupon_id == coupon_id).first() + if not coupon: + raise HTTPException(status_code=404, detail="Coupon not found") + return _coupon_to_response(coupon) + +@router.post("", response_model=CouponResponse, status_code=status.HTTP_201_CREATED) +def create_coupon( + payload: CouponCreateRequest, + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db) +): + """ + Create a new promotional coupon with targeting rules. + """ + clean_code = payload.code.strip().upper() + existing = db.query(Coupon).filter(Coupon.code == clean_code).first() + if existing: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"Coupon code '{clean_code}' already exists" + ) + + now = datetime.now() + valid_from = payload.start_date if payload.start_date else now + valid_to = payload.end_date if payload.end_date else datetime(2035, 12, 31, 23, 59, 59) + + coupon = Coupon( + coupon_id=str(ulid.ULID()), + code=clean_code, + title=payload.description or clean_code, + description=payload.description, + discount_type=_normalize_discount_type_in(payload.discount_type), + discount_value=payload.discount_value, + min_order_amount=payload.min_order_amount or 0.0, + max_discount_cap=payload.max_discount_cap, + first_order_only=payload.first_order_only, + channel_scope=_normalize_channel_in(payload.channel_scope), + usage_limit_total=payload.usage_limit_total, + usage_limit_per_customer=payload.usage_limit_per_customer or 1, + times_used=0, + applicable_category_ids=json.dumps(payload.applicable_category_ids) if payload.applicable_category_ids else None, + applicable_brand_ids=json.dumps(payload.applicable_brand_ids) if payload.applicable_brand_ids else None, + applicable_model_ids=json.dumps(payload.applicable_model_ids) if payload.applicable_model_ids else None, + valid_from=valid_from, + valid_to=valid_to, + is_active=payload.is_active + ) + db.add(coupon) + db.commit() + db.refresh(coupon) + return _coupon_to_response(coupon) + +@router.put("/{coupon_id}", response_model=CouponResponse) +def update_coupon( + coupon_id: str, + payload: CouponUpdateRequest, + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db) +): + """ + Update rules and constraints for an existing coupon. + """ + coupon = db.query(Coupon).filter(Coupon.coupon_id == coupon_id).first() + if not coupon: + raise HTTPException(status_code=404, detail="Coupon not found") + + if payload.description is not None: + coupon.description = payload.description + coupon.title = payload.description or coupon.code + if payload.discount_type is not None: + coupon.discount_type = _normalize_discount_type_in(payload.discount_type) + if payload.discount_value is not None: + coupon.discount_value = payload.discount_value + if payload.min_order_amount is not None: + coupon.min_order_amount = payload.min_order_amount + if payload.max_discount_cap is not None: + coupon.max_discount_cap = payload.max_discount_cap + if payload.first_order_only is not None: + coupon.first_order_only = payload.first_order_only + if payload.channel_scope is not None: + coupon.channel_scope = _normalize_channel_in(payload.channel_scope) + if payload.usage_limit_total is not None: + coupon.usage_limit_total = payload.usage_limit_total + if payload.usage_limit_per_customer is not None: + coupon.usage_limit_per_customer = payload.usage_limit_per_customer + if payload.applicable_category_ids is not None: + coupon.applicable_category_ids = json.dumps(payload.applicable_category_ids) if payload.applicable_category_ids else None + if payload.applicable_brand_ids is not None: + coupon.applicable_brand_ids = json.dumps(payload.applicable_brand_ids) if payload.applicable_brand_ids else None + if payload.applicable_model_ids is not None: + coupon.applicable_model_ids = json.dumps(payload.applicable_model_ids) if payload.applicable_model_ids else None + if payload.start_date is not None: + coupon.valid_from = payload.start_date + if payload.end_date is not None: + coupon.valid_to = payload.end_date + if payload.is_active is not None: + coupon.is_active = payload.is_active + + db.commit() + db.refresh(coupon) + return _coupon_to_response(coupon) + +@router.delete("/{coupon_id}") +def delete_coupon( + coupon_id: str, + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db) +): + """ + Deactivates or permanently deletes a coupon if never used. + """ + coupon = db.query(Coupon).filter(Coupon.coupon_id == coupon_id).first() + if not coupon: + raise HTTPException(status_code=404, detail="Coupon not found") + + usage_count = db.query(CouponUsage).filter(CouponUsage.coupon_id == coupon_id).count() + if usage_count > 0: + # Soft delete / deactivate to preserve historical ledger records + coupon.is_active = False + db.commit() + return {"message": "Coupon has existing redemptions and was deactivated instead of deleted", "coupon_id": coupon_id, "is_active": False} + + db.delete(coupon) + db.commit() + return {"message": "Coupon successfully deleted", "coupon_id": coupon_id} + +@router.get("/{coupon_id}/usages") +def get_coupon_usages( + coupon_id: str, + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db) +): + """ + Audit redemptions for a specific coupon. + """ + usages = db.query(CouponUsage).filter(CouponUsage.coupon_id == coupon_id).order_by(CouponUsage.used_at.desc()).all() + total_savings = sum(float(u.discount_amount or 0.0) for u in usages) + return { + "coupon_id": coupon_id, + "total_usages": len(usages), + "total_discount_given": round(total_savings, 2), + "usages": [ + { + "usage_id": u.usage_id, + "customer_id": u.customer_id, + "order_id": u.order_id, + "discount_amount": float(u.discount_amount), + "used_at": u.used_at + } + for u in usages + ] + } diff --git a/app/api/v1/routers/AdminOrderRouter.py b/app/api/v1/routers/AdminOrderRouter.py index 98b51f3..7374994 100644 --- a/app/api/v1/routers/AdminOrderRouter.py +++ b/app/api/v1/routers/AdminOrderRouter.py @@ -54,6 +54,10 @@ class AdminOrderDetailResponse(BaseModel): customer_name: Optional[str] = None total_amount: float discount_amount: float + is_discounted: bool = False + discount_type: Optional[str] = None + discount_reason: Optional[str] = None + coupon_code: Optional[str] = None tax_amount: float shipping_cost: float final_amount: float @@ -75,6 +79,10 @@ class AdminOrderListResponse(BaseModel): customer_name: Optional[str] = None customer_phone: Optional[str] = None final_amount: float + discount_amount: float = 0.0 + is_discounted: bool = False + discount_type: Optional[str] = None + coupon_code: Optional[str] = None status: str payment_status: str created_at: datetime @@ -90,13 +98,17 @@ class StatusUpdatePayload(BaseModel): @router.get("", response_model=List[AdminOrderListResponse]) def list_all_orders( + is_discounted: Optional[bool] = None, current_user: User = Depends(get_current_user), db: Session = Depends(get_db) ): """ - List all customer orders in the system. + List all customer orders in the system with optional discounted-order filter. """ - orders = db.query(Order).order_by(Order.created_at.desc()).all() + query = db.query(Order) + if is_discounted is not None: + query = query.filter(Order.is_discounted == is_discounted) + orders = query.order_by(Order.created_at.desc()).all() result = [] for o in orders: @@ -124,6 +136,10 @@ def list_all_orders( customer_name=cust_name or "Walk-in Guest", customer_phone=cust_phone or "N/A", final_amount=float(o.final_amount), + discount_amount=float(o.discount_amount or 0.0), + is_discounted=bool(o.is_discounted), + discount_type=o.discount_type, + coupon_code=o.coupon_code, status=o.status, payment_status=o.payment_status, created_at=o.created_at @@ -160,9 +176,13 @@ def get_order_details( customer_email=cust_email, customer_name=cust_name, total_amount=float(order.total_amount), - discount_amount=float(order.discount_amount), - tax_amount=float(order.tax_amount), - shipping_cost=float(order.shipping_cost), + discount_amount=float(order.discount_amount or 0.0), + is_discounted=bool(order.is_discounted), + discount_type=order.discount_type, + discount_reason=order.discount_reason, + coupon_code=order.coupon_code, + tax_amount=float(order.tax_amount or 0.0), + shipping_cost=float(order.shipping_cost or 0.0), final_amount=float(order.final_amount), status=order.status, payment_status=order.payment_status, @@ -404,6 +424,10 @@ class AdminOrderCreateRequest(BaseModel): razorpay_payment_id: Optional[str] = None razorpay_signature: Optional[str] = None notification_channel: Optional[str] = "BOTH" # WHATSAPP, EMAIL, BOTH + discount_amount: Optional[float] = 0.0 + discount_type: Optional[str] = "FIXED" # FIXED or PERCENT + discount_reason: Optional[str] = None + coupon_code: Optional[str] = None class PosRazorpayOrderRequest(BaseModel): amount: float @@ -447,6 +471,7 @@ def create_admin_order( ): """ Directly write a manual/offline store walk-in counter order and auto-generate its Sales Invoice. + Supports point-of-sale item billing, real-time trade discounts, and coupon code redemptions. """ from app.services.OrderService import OrderService items_dicts = [item.dict() for item in payload.items] @@ -467,6 +492,10 @@ def create_admin_order( razorpay_signature=payload.razorpay_signature, actor_email=current_user.email, actor_user_id=current_user.user_id, - notification_channel=payload.notification_channel or "BOTH" + notification_channel=payload.notification_channel or "BOTH", + discount_amount=payload.discount_amount or 0.0, + discount_type=payload.discount_type or "FIXED", + discount_reason=payload.discount_reason, + coupon_code=payload.coupon_code ) diff --git a/app/api/v1/routers/CartRouter.py b/app/api/v1/routers/CartRouter.py index 5c26acf..ac04a31 100644 --- a/app/api/v1/routers/CartRouter.py +++ b/app/api/v1/routers/CartRouter.py @@ -43,6 +43,10 @@ class MergeGuestCartRequest(BaseModel): visitor_id: str +class ApplyCouponRequest(BaseModel): + code: str + + def _ensure_stock(db: Session, variant_id: str, requested_qty: int, sku: Optional[str] = None) -> None: available = get_available_stock(variant_id, db) if requested_qty > available: @@ -79,7 +83,12 @@ def _get_or_create_customer_cart(db: Session, customer_id: str) -> Cart: return cart -def _enrich_and_totals(db: Session, items: List[dict]) -> dict: +def _enrich_and_totals( + db: Session, + items: List[dict], + coupon_code: Optional[str] = None, + customer_id: Optional[str] = None +) -> dict: enriched = [] subtotal = 0.0 for item in items: @@ -103,15 +112,50 @@ def _enrich_and_totals(db: Session, items: List[dict]) -> dict: "total_price": round(line_total, 2), "available_stock": get_available_stock(variant_id, db), }) - tax = round(subtotal * 0.18, 2) + from app.services.DeliveryService import DeliveryService shipping = DeliveryService.calculate_shipping_cost(db, subtotal) if subtotal > 0 else 0.0 + + discount_amount = 0.0 + coupon_info = None + + if coupon_code and subtotal > 0: + from app.services.CouponService import CouponService + c_res = CouponService.validate_coupon( + db=db, + code=coupon_code, + customer_id=customer_id, + items=enriched, + subtotal=subtotal, + channel="ONLINE", + shipping_cost=shipping + ) + if c_res.get("valid"): + discount_amount = float(c_res.get("discount_amount", 0.0)) + if c_res.get("is_free_shipping"): + shipping = 0.0 + coupon_info = { + "coupon_id": c_res["coupon_id"], + "code": c_res["code"], + "title": c_res["title"], + "discount_type": c_res["discount_type"], + "discount_amount": discount_amount, + "message": c_res["message"] + } + + taxable = max(0.0, subtotal - discount_amount) + tax = round(taxable * 0.18, 2) + total_amount = round(taxable + tax + shipping, 2) + return { "items": enriched, "subtotal": round(subtotal, 2), + "coupon_code": coupon_code if coupon_info else None, + "coupon": coupon_info, + "discount_amount": discount_amount, "tax": tax, "shipping": shipping, - "total_amount": round(subtotal + tax + shipping, 2), + "total_amount": total_amount, } @@ -145,7 +189,12 @@ def get_cart( "shipping": 0.0, "total_amount": 0.0, } - totals = _enrich_and_totals(db, _parse_items(cart.items_json)) + totals = _enrich_and_totals( + db=db, + items=_parse_items(cart.items_json), + coupon_code=cart.coupon_code, + customer_id=customer.customer_id + ) return { "cart_id": cart.cart_id, **totals, @@ -175,7 +224,12 @@ def add_to_cart( db.commit() db.refresh(cart) - totals = _enrich_and_totals(db, items) + totals = _enrich_and_totals( + db=db, + items=items, + coupon_code=cart.coupon_code, + customer_id=customer.customer_id + ) return {"message": "Item added to cart", "cart_id": cart.cart_id, **totals} @@ -222,7 +276,12 @@ def set_cart_items( db.commit() db.refresh(cart) - totals = _enrich_and_totals(db, items) + totals = _enrich_and_totals( + db=db, + items=items, + coupon_code=cart.coupon_code, + customer_id=customer.customer_id + ) return {"message": "Cart synchronized", "cart_id": cart.cart_id, **totals} @@ -266,9 +325,107 @@ def merge_guest_cart( perform_guest_cart_merge(db, customer.customer_id, payload.visitor_id) cart = db.query(Cart).filter(Cart.customer_id == customer.customer_id).first() items = _parse_items(cart.items_json) if cart else [] - totals = _enrich_and_totals(db, items) + totals = _enrich_and_totals( + db=db, + items=items, + coupon_code=cart.coupon_code if cart else None, + customer_id=customer.customer_id + ) return { "message": "Guest cart merged successfully", "cart_id": cart.cart_id if cart else None, **totals, } + + +@router.post("/coupon/apply") +def apply_cart_coupon( + payload: ApplyCouponRequest, + customer: EcomCustomer = Depends(get_current_customer), + db: Session = Depends(get_db), +): + """ + Validates a promotional coupon code against the customer cart and attaches it. + Evaluates first-time customer status, min order subtotal, category/brand restrictions, etc. + """ + from app.services.CouponService import CouponService + + cart = _get_or_create_customer_cart(db, customer.customer_id) + items = _parse_items(cart.items_json) + + if not items: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Your cart is empty. Add items before applying a coupon." + ) + + # Initial totals to get subtotal & shipping + totals_preview = _enrich_and_totals(db, items, coupon_code=None, customer_id=customer.customer_id) + subtotal = totals_preview["subtotal"] + shipping = totals_preview["shipping"] + + # Validate coupon via Rule Engine + res = CouponService.validate_coupon( + db=db, + code=payload.code, + customer_id=customer.customer_id, + items=totals_preview["items"], + subtotal=subtotal, + channel="ONLINE", + shipping_cost=shipping + ) + + if not res.get("valid"): + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=res.get("error", "Coupon could not be applied.") + ) + + cart.coupon_code = res["code"] + db.commit() + db.refresh(cart) + + totals = _enrich_and_totals( + db=db, + items=items, + coupon_code=cart.coupon_code, + customer_id=customer.customer_id + ) + + return { + "message": res["message"], + "cart_id": cart.cart_id, + **totals + } + + +@router.delete("/coupon/remove") +def remove_cart_coupon( + customer: EcomCustomer = Depends(get_current_customer), + db: Session = Depends(get_db), +): + """ + Detaches active coupon from the customer's cart and recalculates full totals. + """ + cart = db.query(Cart).filter(Cart.customer_id == customer.customer_id).first() + if not cart or not cart.coupon_code: + return {"message": "No coupon applied to cart"} + + cart.coupon_code = None + db.commit() + db.refresh(cart) + + items = _parse_items(cart.items_json) if cart else [] + totals = _enrich_and_totals( + db=db, + items=items, + coupon_code=None, + customer_id=customer.customer_id + ) + + return { + "message": "Coupon removed successfully", + "cart_id": cart.cart_id if cart else None, + **totals + } + diff --git a/app/api/v1/routers/CheckoutRouter.py b/app/api/v1/routers/CheckoutRouter.py index 3b148f3..2b148ba 100644 --- a/app/api/v1/routers/CheckoutRouter.py +++ b/app/api/v1/routers/CheckoutRouter.py @@ -41,5 +41,6 @@ def create_checkout_order( customer=customer, address_id=payload.address_id, payment_method=payload.payment_method or "RAZORPAY", - use_wallet_credits=payload.use_wallet_credits + use_wallet_credits=payload.use_wallet_credits, + coupon_code=payload.coupon_code ) diff --git a/app/api/v1/routers/CustomerAuthRouter.py b/app/api/v1/routers/CustomerAuthRouter.py index 6624b9a..1332a22 100644 --- a/app/api/v1/routers/CustomerAuthRouter.py +++ b/app/api/v1/routers/CustomerAuthRouter.py @@ -200,6 +200,9 @@ def exchange_google_code_for_identity(code: str, redirect_uri: Optional[str]) -> # --- Routes --- def trigger_customer_login_lead(db: Session, customer: EcomCustomer): + # Simulation logins should not create thousands of CRM leads. + if settings.SIMULATION_MODE: + return try: from app.models.CrmModel import CrmLead import ulid diff --git a/app/api/v1/routers/SimulationPaymentRouter.py b/app/api/v1/routers/SimulationPaymentRouter.py new file mode 100644 index 0000000..263a236 --- /dev/null +++ b/app/api/v1/routers/SimulationPaymentRouter.py @@ -0,0 +1,149 @@ +""" +@router SimulationPaymentRouter +@purpose Environment-gated SIMULATED payment confirmation for the customer swarm. + +This router is only registered when PAYMENT_SIMULATOR_ENABLED=true, and it also +refuses requests unless SIMULATION_MODE=true. It only accepts orders belonging +to seeded simulation customers (email domain from SIM_CUSTOMER_EMAIL_DOMAIN). + +It deliberately reuses OrderService.confirm_ecommerce_payment so simulated +orders follow the exact same stock deduction, invoice, status-history and +payment-ledger path as a real online payment. +""" +from __future__ import annotations + +import json +from typing import Optional + +import ulid +from fastapi import APIRouter, Depends, HTTPException, status +from pydantic import BaseModel +from sqlalchemy.orm import Session + +from app.core.config.Config import settings +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.InvoiceModel import Invoice +from app.models.OrderModel import Order +from app.models.PaymentLedgerModel import PaymentLedger +from app.services.OrderService import OrderService + +router = APIRouter(prefix="/api/v1/payment", tags=["Simulation Payment"]) + + +class SimulatePaymentRequest(BaseModel): + order_id: str + note: Optional[str] = "Swarm simulated payment" + + +def _ensure_simulation_enabled() -> None: + if not settings.PAYMENT_SIMULATOR_ENABLED or not settings.SIMULATION_MODE: + # 404 keeps the endpoint invisible in normal/production deployments. + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found") + + +def _ensure_sim_customer(customer: EcomCustomer) -> None: + domain = (settings.SIM_CUSTOMER_EMAIL_DOMAIN or "@sim.local").lower() + if not (customer.email or "").lower().endswith(domain): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Simulated payment is only available to simulation customers", + ) + + +@router.post("/simulate") +def simulate_payment( + payload: SimulatePaymentRequest, + customer: EcomCustomer = Depends(get_current_customer), + db: Session = Depends(get_db), +): + """ + Capture a payment for a simulation order and finalize it through the real + ecommerce confirmation pipeline (stock deduction + invoice + history). + """ + _ensure_simulation_enabled() + _ensure_sim_customer(customer) + + order = ( + db.query(Order) + .filter(Order.order_id == payload.order_id) + .with_for_update() + .first() + ) + if not order: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Order not found") + if order.customer_id != customer.customer_id: + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Order does not belong to this customer") + if order.status == "CANCELLED": + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot pay a cancelled order") + + existing_invoice = ( + db.query(Invoice).filter(Invoice.order_id == order.order_id).first() + ) + if order.payment_status == "PAYMENT_CAPTURED": + return { + "status": "SUCCESS", + "message": "Payment already captured", + "order_id": order.order_id, + "order_no": order.order_no, + "status": order.status, + "payment_status": order.payment_status, + "invoice_id": existing_invoice.invoice_id if existing_invoice else None, + "invoice_no": existing_invoice.invoice_no if existing_invoice else None, + } + + ledger = ( + db.query(PaymentLedger) + .filter( + PaymentLedger.order_id == order.order_id, + PaymentLedger.provider == "SIMULATED", + ) + .order_by(PaymentLedger.created_at.desc()) + .first() + ) + now_ref = f"SIMPAY-{ulid.ULID()}" + raw = json.dumps( + { + "simulated": True, + "note": payload.note, + "order_no": order.order_no, + "amount": float(order.final_amount), + } + ) + if ledger: + ledger.transaction_ref = now_ref + ledger.amount = order.final_amount + ledger.currency = "INR" + ledger.status = "CAPTURED" + ledger.raw_response_json = raw + else: + ledger = PaymentLedger( + payment_id=str(ulid.ULID()), + order_id=order.order_id, + provider="SIMULATED", + transaction_ref=now_ref, + amount=order.final_amount, + currency="INR", + status="CAPTURED", + raw_response_json=raw, + ) + db.add(ledger) + db.flush() + + invoice = OrderService.confirm_ecommerce_payment(db, order, payment_method="SIMULATED") + db.refresh(order) + + return { + "status": "SUCCESS", + "message": "Simulated payment captured and order confirmed", + "order_id": order.order_id, + "order_no": order.order_no, + "status": order.status, + "payment_status": order.payment_status, + "payment_id": ledger.payment_id, + "transaction_ref": ledger.transaction_ref, + "invoice_id": invoice.invoice_id if invoice else None, + "invoice_no": invoice.invoice_no if invoice else None, + "amount": float(order.final_amount), + } diff --git a/app/core/config/Config.py b/app/core/config/Config.py index 0018cc6..b488807 100644 --- a/app/core/config/Config.py +++ b/app/core/config/Config.py @@ -6,6 +6,11 @@ from pydantic_settings import BaseSettings class Settings(BaseSettings): RUNTIME_ENV: str = "development" ENVIRONMENT: str = "development" + # Simulation/swarm safety switches. Both default off and must be explicitly + # enabled by the isolated simulation launcher (Backend/.env.sim). + SIMULATION_MODE: bool = False + PAYMENT_SIMULATOR_ENABLED: bool = False + SIM_CUSTOMER_EMAIL_DOMAIN: str = "@sim.example.com" DATABASE_URL: str = "mysql+pymysql://Adithiyan:Adithiyan$2025Mysql@127.0.0.1:3306/ifixkartecommerceadmin" CORE_DATABASE_URL: str = "mysql+pymysql://Adithiyan:Adithiyan$2025Mysql@127.0.0.1:3306/ifixkartecommerceadmin" CRM_DATABASE_URL: str = "mysql+pymysql://Adithiyan:Adithiyan$2025Mysql@127.0.0.1:3306/ifixkartcrm" diff --git a/app/core/limiter.py b/app/core/limiter.py index b812681..63eaa6d 100644 --- a/app/core/limiter.py +++ b/app/core/limiter.py @@ -1,8 +1,14 @@ from slowapi import Limiter from slowapi.util import get_remote_address +from app.core.config.Config import settings # Global SlowAPI Limiter instance limiter = Limiter( key_func=get_remote_address, default_limits=["120/minute"] ) + +# A local swarm originates from one IP. Rate limits are a production protection, +# not part of the journey under test, so disable them only in simulation mode. +if settings.SIMULATION_MODE: + limiter.enabled = False diff --git a/app/core/payment_orchestrator.py b/app/core/payment_orchestrator.py index e79c4f1..d1f3afd 100644 --- a/app/core/payment_orchestrator.py +++ b/app/core/payment_orchestrator.py @@ -24,6 +24,8 @@ class PaymentOrchestrator: Initiates a new payment attempt for an e-commerce order. Row-locks the order and verifies status. """ + if settings.SIMULATION_MODE: + return {"error": "Razorpay is disabled in simulation; use /api/v1/payment/simulate", "status_code": 400} order = db.query(Order).filter(Order.order_id == order_id).with_for_update().first() if not order: return {"error": "Order not found", "status_code": 404} @@ -121,6 +123,8 @@ class PaymentOrchestrator: """ Verifies client-side signature + executes secondary server-side fetch from Razorpay API. """ + if settings.SIMULATION_MODE: + return {"error": "Razorpay is disabled in simulation; use /api/v1/payment/simulate", "status_code": 400} order = db.query(Order).filter(Order.order_id == order_id).with_for_update().first() if not order: return {"error": "Order not found", "status_code": 404} diff --git a/app/main.py b/app/main.py index 5899c94..dc1dab1 100644 --- a/app/main.py +++ b/app/main.py @@ -68,6 +68,7 @@ from app.api.v1.routers.NotificationTemplateRouter import router as notification from app.api.v1.routers.CronRouter import router as cron_router from app.api.v1.routers.WarrantyRouter import router as warranty_router from app.api.v1.routers.CreditRouter import router as credit_router +from app.api.v1.routers.AdminCouponRouter import router as admin_coupon_router # Middleware Imports from app.core.middleware.trace_middleware import RequestTraceMiddleware from app.core.middleware.security_middleware import SecurityHeadersMiddleware, RequestSizeLimitMiddleware @@ -274,6 +275,11 @@ app.include_router(cart_router) app.include_router(checkout_router) app.include_router(order_router) app.include_router(payment_router) +# Simulation-only payment capture. The endpoint is not even registered outside +# the isolated simulation environment. +if getattr(settings, 'PAYMENT_SIMULATOR_ENABLED', False) and getattr(settings, 'SIMULATION_MODE', False): + from app.api.v1.routers.SimulationPaymentRouter import router as simulation_payment_router + app.include_router(simulation_payment_router) app.include_router(invoice_router) app.include_router(pos_sync_router) app.include_router(wishlist_router) @@ -302,6 +308,7 @@ app.include_router(role_notification_settings_router) app.include_router(cron_router) app.include_router(warranty_router) app.include_router(credit_router) +app.include_router(admin_coupon_router) # Enterprise Integration Routers from app.api.v1.routers.GoogleAnalyticsRouter import router as ga4_router diff --git a/app/models/CouponModel.py b/app/models/CouponModel.py new file mode 100644 index 0000000..66844c0 --- /dev/null +++ b/app/models/CouponModel.py @@ -0,0 +1,63 @@ +""" +@model CouponModel (Backend/app/models/CouponModel.py) +@purpose Unified database entities for rule-based promotional coupons, first-time buyer incentives, and customer redemption tracking. +""" +import ulid +from datetime import datetime, timezone +from sqlalchemy import Column, String, Boolean, Integer, Numeric, DateTime, JSON, ForeignKey, func +from sqlalchemy.orm import relationship + +from app.core.database.db_session import Base + + +class Coupon(Base): + __tablename__ = "coupons" + + coupon_id = Column(String(26), primary_key=True, default=lambda: str(ulid.ULID())) + code = Column(String(50), nullable=False, unique=True, index=True) + title = Column(String(100), nullable=False) + description = Column(String(255), nullable=True) + + discount_type = Column(String(20), nullable=False, default="PERCENTAGE") # PERCENTAGE, FIXED, FREE_SHIPPING + discount_value = Column(Numeric(10, 2), nullable=False) + max_discount_cap = Column(Numeric(10, 2), nullable=True) + + min_order_amount = Column(Numeric(10, 2), nullable=False, default=0.00) + max_order_amount = Column(Numeric(10, 2), nullable=True) + + # Core E-Commerce Rules + first_order_only = Column(Boolean, nullable=False, default=False, index=True) + channel_scope = Column(String(20), nullable=False, default="OMNICHANNEL") # ONLINE_ONLY, POS_ONLY, OMNICHANNEL + exclude_already_discounted = Column(Boolean, nullable=False, default=False) + + # Catalog Target Filtering (Stored as JSON lists of IDs) + applicable_category_ids = Column(JSON, nullable=True) + applicable_brand_ids = Column(JSON, nullable=True) + applicable_model_ids = Column(JSON, nullable=True) + + # Validity & Caps + valid_from = Column(DateTime, nullable=False) + valid_to = Column(DateTime, nullable=False) + usage_limit_total = Column(Integer, nullable=True) + usage_limit_per_customer = Column(Integer, nullable=False, default=1) + times_used = Column(Integer, nullable=False, default=0) + is_active = Column(Boolean, nullable=False, default=True, index=True) + + created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) + updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc)) + + usages = relationship("CouponUsage", back_populates="coupon", cascade="all, delete-orphan") + + +class CouponUsage(Base): + __tablename__ = "coupon_usages" + + usage_id = Column(String(26), primary_key=True, default=lambda: str(ulid.ULID())) + coupon_id = Column(String(26), ForeignKey("coupons.coupon_id", ondelete="CASCADE"), nullable=False, index=True) + customer_id = Column(String(26), nullable=False, index=True) + order_id = Column(String(26), ForeignKey("orders.order_id", ondelete="CASCADE"), nullable=False, index=True) + discount_amount = Column(Numeric(10, 2), nullable=False) + used_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) + + coupon = relationship("Coupon", back_populates="usages") + order = relationship("Order", backref="coupon_usage") diff --git a/app/models/OrderModel.py b/app/models/OrderModel.py index 7aa9bd1..35994a6 100644 --- a/app/models/OrderModel.py +++ b/app/models/OrderModel.py @@ -1,5 +1,5 @@ import ulid -from sqlalchemy import Column, String, Numeric, DateTime, Integer, ForeignKey, Text, Index, JSON +from sqlalchemy import Column, String, Numeric, DateTime, Integer, ForeignKey, Text, Index, JSON, Boolean from sqlalchemy.sql import func from sqlalchemy.orm import relationship from app.core.database.db_session import Base @@ -12,7 +12,12 @@ class Order(Base): customer_id = Column(String(26), ForeignKey("ecom_customers.customer_id", ondelete="SET NULL"), nullable=True, index=True) total_amount = Column(Numeric(10, 2), nullable=False) + coupon_id = Column(String(26), nullable=True) + coupon_code = Column(String(50), nullable=True, index=True) discount_amount = Column(Numeric(10, 2), default=0.00) + discount_type = Column(String(20), default="FIXED") + discount_reason = Column(String(255), nullable=True) + is_discounted = Column(Boolean, default=False, index=True) tax_amount = Column(Numeric(10, 2), default=0.00) shipping_cost = Column(Numeric(10, 2), default=0.00) final_amount = Column(Numeric(10, 2), nullable=False) diff --git a/app/services/CouponService.py b/app/services/CouponService.py new file mode 100644 index 0000000..eaf4a8b --- /dev/null +++ b/app/services/CouponService.py @@ -0,0 +1,209 @@ +""" +@service CouponService (Backend/app/services/CouponService.py) +@purpose Multi-point rule engine for promotional coupons, first-time buyer checks, catalog restrictions, and usage accounting. +""" +import ulid +from datetime import datetime, timezone +from typing import Dict, Any, List, Optional +from sqlalchemy.orm import Session +from decimal import Decimal + +from app.models.CouponModel import Coupon, CouponUsage +from app.models.OrderModel import Order +from app.models.ProductModel import ProductVariant, Product + + +class CouponService: + + @staticmethod + def validate_coupon( + db: Session, + code: str, + customer_id: Optional[str], + items: List[Dict[str, Any]], + subtotal: float, + channel: str = "ONLINE", + shipping_cost: float = 0.0 + ) -> Dict[str, Any]: + """ + Validates coupon against all configured business rules. + Returns validation status, calculated discount amount, or human-readable rejection reason. + """ + if not code or not code.strip(): + return {"valid": False, "error": "Please enter a valid coupon code."} + + clean_code = code.strip().upper() + coupon = db.query(Coupon).filter(Coupon.code == clean_code).first() + + if not coupon: + return {"valid": False, "error": f"Coupon code '{clean_code}' is invalid."} + + # 1. Active status check + if not coupon.is_active: + return {"valid": False, "error": f"Coupon '{clean_code}' is currently inactive."} + + # 2. Validity date range check + now = datetime.now() + if now < coupon.valid_from: + return {"valid": False, "error": f"Coupon '{clean_code}' will be active starting {coupon.valid_from.strftime('%d %b %Y')}."} + + if now > coupon.valid_to: + return {"valid": False, "error": f"Coupon '{clean_code}' expired on {coupon.valid_to.strftime('%d %b %Y')}."} + + # 3. Global usage cap check + if coupon.usage_limit_total and coupon.times_used >= coupon.usage_limit_total: + return {"valid": False, "error": f"Coupon '{clean_code}' has reached its maximum global redemptions."} + + # 4. Channel scope check (ONLINE_ONLY, POS_ONLY, OMNICHANNEL) + req_channel = channel.upper() + if coupon.channel_scope == "ONLINE_ONLY" and req_channel == "POS": + return {"valid": False, "error": f"Coupon '{clean_code}' is exclusively valid for online store orders."} + if coupon.channel_scope == "POS_ONLY" and req_channel != "POS": + return {"valid": False, "error": f"Coupon '{clean_code}' is exclusively valid for in-store walk-in counter orders."} + + # 5. First-Time Customer Rule check + if coupon.first_order_only: + if not customer_id: + return { + "valid": False, + "error": "Please sign in to your customer account to redeem this first-order welcome offer." + } + + completed_prior_orders = db.query(Order).filter( + Order.customer_id == customer_id, + Order.status.notin_(["CANCELLED", "PAYMENT_FAILED"]) + ).count() + + if completed_prior_orders > 0: + return { + "valid": False, + "error": f"Coupon '{clean_code}' is exclusively for first-time customers on their very first purchase." + } + + # 6. Per-Customer usage limit check + if customer_id and coupon.usage_limit_per_customer: + customer_uses = db.query(CouponUsage).filter( + CouponUsage.coupon_id == coupon.coupon_id, + CouponUsage.customer_id == customer_id + ).count() + + if customer_uses >= coupon.usage_limit_per_customer: + return { + "valid": False, + "error": f"You have already redeemed coupon '{clean_code}' the maximum allowed times ({coupon.usage_limit_per_customer})." + } + + # 7. Minimum order amount check + min_order = float(coupon.min_order_amount or 0.0) + if subtotal < min_order: + shortfall = min_order - subtotal + return { + "valid": False, + "error": f"Add ₹{shortfall:.2f} more to your cart to use coupon '{clean_code}' (Minimum spend: ₹{min_order:.2f})." + } + + # 8. Maximum order amount check (excludes wholesale / bulk from consumer coupons) + if coupon.max_order_amount and subtotal > float(coupon.max_order_amount): + return { + "valid": False, + "error": f"Cart total exceeds the maximum eligible order limit of ₹{float(coupon.max_order_amount):.2f} for this coupon." + } + + # 9. Catalog Target Restrictions (Categories, Brands, Models) + cat_ids = coupon.applicable_category_ids or [] + brand_ids = coupon.applicable_brand_ids or [] + model_ids = coupon.applicable_model_ids or [] + has_catalog_filter = bool(cat_ids or brand_ids or model_ids) + + qualifying_subtotal = 0.0 + if has_catalog_filter and items: + for itm in items: + v_id = itm.get("variant_id") + qty = itm.get("qty") or itm.get("quantity") or 1 + price = itm.get("unit_price") + + variant = db.query(ProductVariant).filter(ProductVariant.variant_id == v_id).first() + if not variant: + continue + + if price is None: + price = float(variant.price) + + product = variant.product + if not product: + continue + + # Category filter + if cat_ids and product.category_id not in cat_ids: + continue + # Brand filter + if brand_ids and product.brand_id not in brand_ids: + continue + # Model filter + if model_ids and product.device_model_id not in model_ids: + continue + + qualifying_subtotal += float(price) * int(qty) + + if qualifying_subtotal <= 0: + return { + "valid": False, + "error": f"Coupon '{clean_code}' is not applicable to the specific items currently in your cart." + } + else: + qualifying_subtotal = subtotal + + # 10. Compute discount amount + base_calc_amount = qualifying_subtotal if has_catalog_filter else subtotal + discount_amount = 0.0 + is_free_shipping = False + + if coupon.discount_type == "PERCENTAGE": + discount_amount = round(base_calc_amount * (float(coupon.discount_value) / 100.0), 2) + if coupon.max_discount_cap: + discount_amount = min(discount_amount, float(coupon.max_discount_cap)) + elif coupon.discount_type == "FIXED": + discount_amount = min(float(coupon.discount_value), base_calc_amount) + elif coupon.discount_type == "FREE_SHIPPING": + discount_amount = float(shipping_cost) + is_free_shipping = True + + discount_amount = round(min(discount_amount, subtotal), 2) + + return { + "valid": True, + "coupon_id": coupon.coupon_id, + "code": coupon.code, + "title": coupon.title, + "discount_type": coupon.discount_type, + "discount_value": float(coupon.discount_value), + "discount_amount": discount_amount, + "is_free_shipping": is_free_shipping, + "message": f"Coupon '{coupon.code}' applied! You saved ₹{discount_amount:.2f}." + } + + @staticmethod + def record_usage( + db: Session, + coupon_id: str, + customer_id: str, + order_id: str, + discount_amount: float + ) -> CouponUsage: + """ + Records verified redemption and increments usage counter atomically. + """ + coupon = db.query(Coupon).filter(Coupon.coupon_id == coupon_id).with_for_update().first() + if coupon: + coupon.times_used = (coupon.times_used or 0) + 1 + + usage = CouponUsage( + usage_id=str(ulid.ULID()), + coupon_id=coupon_id, + customer_id=customer_id, + order_id=order_id, + discount_amount=round(discount_amount, 2), + used_at=datetime.now(timezone.utc) + ) + db.add(usage) + return usage diff --git a/app/services/InventoryService.py b/app/services/InventoryService.py index 1807e5c..96d33a6 100644 --- a/app/services/InventoryService.py +++ b/app/services/InventoryService.py @@ -108,6 +108,9 @@ def record_ledger_entry( # --- INVENTORY_LOW_STOCK check --- if qty < 0: + from app.core.config.Config import settings + if settings.SIMULATION_MODE: + return entry from app.models.ProductModel import ProductVariant variant = db.execute(select(ProductVariant).where(ProductVariant.variant_id == variant_id)).scalar_one_or_none() if variant and getattr(variant, "low_stock_threshold", None) is not None: diff --git a/app/services/OrderService.py b/app/services/OrderService.py index 1d8e067..d56e2a9 100644 --- a/app/services/OrderService.py +++ b/app/services/OrderService.py @@ -17,6 +17,7 @@ from app.models.OrderModel import Order, OrderItem, OrderStatusHistory from app.models.InvoiceModel import Invoice from app.services.InventoryService import get_available_stock, record_ledger_entry from app.services.DeliveryService import DeliveryService +from app.core.config.Config import settings def generate_order_number(db: Session) -> str: today = datetime.now(timezone.utc).strftime("%Y%m%d") @@ -71,7 +72,13 @@ def create_invoice_for_order(order: Order, db: Session) -> Invoice: pdf_path=None, # Enforce dynamic on-the-fly PDF rendering status="GENERATED", ) + db.add(invoice) + db.flush() + return invoice def _dispatch_order_notifications(db: Session, order_id: str, channel: str = "BOTH"): + # Simulation must never send real email / WhatsApp / admin alerts. + if settings.SIMULATION_MODE: + return try: from app.services.NotificationGatewayService import NotificationGatewayService from app.schemas.NotificationGateway import EntityNotificationDispatchCreate @@ -121,7 +128,8 @@ class OrderService: customer: EcomCustomer, address_id: str, payment_method: str = "RAZORPAY", - use_wallet_credits: bool = False + use_wallet_credits: bool = False, + coupon_code: Optional[str] = None ) -> Dict[str, Any]: """ Processes cart validation, stock reservation, order creation with dynamic delivery calculations. @@ -217,17 +225,55 @@ class OrderService: shipping_cost = DeliveryService.calculate_shipping_cost(db, subtotal) + # Coupon validation and calculation + coupon_obj = None + coupon_discount = 0.0 + applied_coupon_code = None + applied_coupon_id = None + if coupon_code and coupon_code.strip(): + from app.services.CouponService import CouponService + cart_items_for_coupon = [ + { + "variant_id": vi["variant"].variant_id, + "product_id": vi["variant"].product_id, + "unit_price": vi["unit_price"], + "qty": vi["qty"], + "category_id": getattr(vi["variant"].product, "category_id", None) if vi["variant"].product else None, + "brand_id": getattr(vi["variant"].product, "brand_id", None) if vi["variant"].product else None, + "model_id": getattr(vi["variant"].product, "model_id", None) if vi["variant"].product else None, + } + for vi in validated_items + ] + valid_res = CouponService.validate_coupon( + db=db, + code=coupon_code.strip(), + customer_id=customer.customer_id, + cart_total=subtotal, + cart_items=cart_items_for_coupon, + channel="STOREFRONT" + ) + if not valid_res.get("valid"): + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"Coupon invalid: {valid_res.get('message', 'Cannot apply coupon')}" + ) + coupon_obj = valid_res["coupon"] + coupon_discount = float(valid_res["discount_amount"]) + applied_coupon_code = coupon_obj.code + applied_coupon_id = coupon_obj.coupon_id + # Credit redemption calculation credits_applied = 0.0 + net_after_coupon = max(0.0, subtotal - coupon_discount) if use_wallet_credits: from app.services.CreditService import CreditService from decimal import Decimal wallet = CreditService.get_or_create_wallet(db, customer.customer_id) if wallet and not wallet.is_locked and wallet.active_balance > Decimal("0.00"): - max_eligible = Decimal(str(round(subtotal + shipping_cost, 2))) + max_eligible = Decimal(str(round(net_after_coupon + shipping_cost, 2))) credits_applied = float(min(wallet.active_balance, max_eligible)) - discount = credits_applied + discount = round(coupon_discount + credits_applied, 2) gross_amount = max(0.0, subtotal - discount) tax_rate = 18.0 taxable_amount = round(gross_amount / (1 + tax_rate / 100.0), 2) @@ -252,7 +298,12 @@ class OrderService: payment_status="PAYMENT_PENDING", fulfillment_status="UNFULFILLED", shipping_address_json=address_json, - billing_address_json=address_json + billing_address_json=address_json, + coupon_id=applied_coupon_id, + coupon_code=applied_coupon_code, + discount_type=coupon_obj.discount_type if coupon_obj else ("STORE_CREDIT" if credits_applied > 0 else None), + discount_reason=f"Promo code {applied_coupon_code}" if applied_coupon_code else ("Store Credits" if credits_applied > 0 else None), + is_discounted=True if discount > 0 else False ) db.add(order) @@ -310,6 +361,17 @@ class OrderService: order.payment_status = "PAYMENT_COMPLETED" invoice = create_invoice_for_order(order, db) + # Record coupon redemption if coupon applied + if coupon_obj and coupon_discount > 0: + from app.services.CouponService import CouponService + CouponService.record_usage( + db=db, + coupon_id=coupon_obj.coupon_id, + customer_id=customer.customer_id, + order_id=order_id, + discount_amount=coupon_discount + ) + cart.items_json = None db.commit() @@ -322,6 +384,8 @@ class OrderService: "total_amount": float(order.total_amount), "discount_amount": float(order.discount_amount), "credits_applied": credits_applied, + "coupon_code": applied_coupon_code, + "is_discounted": bool(order.is_discounted), "tax_amount": float(order.tax_amount), "shipping_cost": float(order.shipping_cost), "final_amount": float(order.final_amount), @@ -350,11 +414,16 @@ class OrderService: razorpay_signature: Optional[str] = None, actor_email: str = "SYSTEM", actor_user_id: Optional[str] = None, - notification_channel: Optional[str] = "BOTH" + notification_channel: Optional[str] = "BOTH", + discount_amount: float = 0.0, + discount_type: str = "FIXED", + discount_reason: Optional[str] = None, + coupon_code: Optional[str] = None ) -> Dict[str, Any]: """ Creates a walk-in / POS counter sale order, deducts stock instantly (POS_SALE), resolves guest details if empty, verifies Razorpay signature if digital/mixed, and generates the Sales Invoice. + Supports rule-based coupon validation and manual cashier trade discounts. """ if not items_payload: raise HTTPException(status_code=400, detail="Order must contain at least one item") @@ -427,10 +496,51 @@ class OrderService: "total_price": total_price }) + # Resolve coupon or manual discount + coupon_id = None + applied_coupon_code = None + if coupon_code and coupon_code.strip(): + from app.services.CouponService import CouponService + cart_items_for_coupon = [ + { + "variant_id": vi["variant"].variant_id, + "product_id": vi["variant"].product_id, + "unit_price": vi["unit_price"], + "qty": vi["qty"], + "category_id": getattr(vi["variant"].product, "category_id", None) if vi["variant"].product else None, + "brand_id": getattr(vi["variant"].product, "brand_id", None) if vi["variant"].product else None, + "model_id": getattr(vi["variant"].product, "model_id", None) if vi["variant"].product else None, + } + for vi in validated_items + ] + valid_res = CouponService.validate_coupon( + db=db, + code=coupon_code.strip(), + customer_id=customer.customer_id, + cart_total=subtotal, + cart_items=cart_items_for_coupon, + channel="STORE_POS" + ) + if not valid_res.get("valid"): + raise HTTPException(status_code=400, detail=f"Invalid coupon: {valid_res.get('message', 'Validation failed')}") + coupon_obj = valid_res["coupon"] + coupon_id = coupon_obj.coupon_id + applied_coupon_code = coupon_obj.code + discount_amount = float(valid_res["discount_amount"]) + discount_type = coupon_obj.discount_type + discount_reason = f"POS Coupon: {applied_coupon_code}" + else: + discount_amount = max(0.0, float(discount_amount or 0.0)) + if discount_amount > 0.0: + discount_type = discount_type or "FIXED" + discount_reason = discount_reason or "POS Manual Trade Discount" + + discount_amount = min(discount_amount, subtotal) + net_after_discount = max(0.0, subtotal - discount_amount) tax_rate = 18.0 - taxable_amount = round(subtotal / (1 + tax_rate / 100.0), 2) - tax_amount = round(subtotal - taxable_amount, 2) - final_amount = round(subtotal) + taxable_amount = round(net_after_discount / (1 + tax_rate / 100.0), 2) + tax_amount = round(net_after_discount - taxable_amount, 2) + final_amount = round(net_after_discount) order_no = generate_order_number(db) order_id = str(ulid.ULID()) @@ -446,7 +556,7 @@ class OrderService: order_no=order_no, customer_id=customer.customer_id, total_amount=subtotal, - discount_amount=0.0, + discount_amount=discount_amount, tax_amount=tax_amount, shipping_cost=0.0, final_amount=final_amount, @@ -454,7 +564,12 @@ class OrderService: payment_status="PAID" if payment_status.upper() == "PAID" else "PAYMENT_PENDING", fulfillment_status="FULFILLED", shipping_address_json=address_json, - billing_address_json=address_json + billing_address_json=address_json, + coupon_id=coupon_id, + coupon_code=applied_coupon_code, + discount_type=discount_type if discount_amount > 0 else None, + discount_reason=discount_reason if discount_amount > 0 else None, + is_discounted=True if discount_amount > 0 else False ) db.add(order) @@ -484,11 +599,24 @@ class OrderService: invoice = create_invoice_for_order(order, db) + # Record coupon usage if coupon applied + if coupon_id and discount_amount > 0: + from app.services.CouponService import CouponService + CouponService.record_usage( + db=db, + coupon_id=coupon_id, + customer_id=customer.customer_id, + order_id=order_id, + discount_amount=discount_amount + ) + # Formulate detail payment log reason if payment_method.upper() == "MIXED_PAYMENT": pay_reason = f"Walk-in order created via Mixed Payment (Cash: ₹{cash_amount:.2f}, {digital_method or 'Digital'}: ₹{digital_amount:.2f}, Rzp ID: {razorpay_payment_id or 'N/A'})" else: pay_reason = f"Walk-in order created (Paid via {payment_method}, Rzp ID: {razorpay_payment_id or 'N/A'})" + if discount_amount > 0: + pay_reason += f" | Discount: ₹{discount_amount:.2f} ({discount_reason})" history = OrderStatusHistory( history_id=str(ulid.ULID()), @@ -529,6 +657,10 @@ class OrderService: "tax_amount": float(order.tax_amount), "shipping_cost": float(order.shipping_cost), "final_amount": float(order.final_amount), + "coupon_code": order.coupon_code, + "discount_type": order.discount_type, + "discount_reason": order.discount_reason, + "is_discounted": bool(order.is_discounted), "status": order.status, "payment_status": order.payment_status, "fulfillment_status": order.fulfillment_status, diff --git a/app/services/migration_engine/migration_worker.py b/app/services/migration_engine/migration_worker.py index 04a2ae3..d198ab9 100644 --- a/app/services/migration_engine/migration_worker.py +++ b/app/services/migration_engine/migration_worker.py @@ -640,6 +640,15 @@ class MigrationWorker: ) db.add(asset) existing_assets[item.sha256] = asset + else: + # Ensure existing asset points to valid active job storage path + if item.storage_path: + ext = os.path.splitext(item.file_name)[1].lower().replace(".", "") + asset.storage_path = item.storage_path + asset.cdn_url = f"/uploads/migrations/{job_id}/media/{item.sha256[:2]}/{item.sha256}.{ext}" + asset.thumbnail_url = asset.cdn_url + if mg and asset.media_group_id != mg.id: + asset.media_group_id = mg.id item.status = MediaItemStatusEnum.REGISTERED diff --git a/scripts/sim/provision_sim_db.py b/scripts/sim/provision_sim_db.py new file mode 100644 index 0000000..d483d25 --- /dev/null +++ b/scripts/sim/provision_sim_db.py @@ -0,0 +1,433 @@ +#!/usr/bin/env python3 +""" +Provision an isolated simulation copy of the IfixKart MySQL schemas. + +What it does +------------ +1. Creates two dedicated databases on the same MySQL server: + _sim (catalog + ecommerce + CRM tables) + _sim (core/admin tables) +2. Clones every table *structure* from the source schemas. +3. Copies only safe reference/catalog data (never customers, orders, payments). +4. Seeds deterministic stock receipts so agents can actually check out. +5. Grants the normal application DB user access to the new schemas. +6. Writes Backend/.env.sim pointing the app at the sim schemas. + +Requires root SSH access to the MySQL host (the same host used by ssh_tunnel.py) +because the application DB user is intentionally not allowed to CREATE DATABASE. + +Usage +----- + cd Backend + ./venv/bin/python scripts/sim/provision_sim_db.py --recreate + ./venv/bin/python scripts/sim/provision_sim_db.py --recreate --stock-per-variant 5000 + +After provisioning: + ./venv/bin/python scripts/sim/seed_customers.py --count 10000 + ./venv/bin/python scripts/sim/run_sim_backend.py +""" +from __future__ import annotations + +import argparse +import json +import os +import re +import shlex +import sys +from datetime import datetime, timezone +from pathlib import Path + +import paramiko +import ulid +from dotenv import load_dotenv +from sqlalchemy import create_engine, text +from sqlalchemy.engine import make_url + +BACKEND_DIR = Path(__file__).resolve().parents[2] +ROOT_DIR = BACKEND_DIR.parent +ENV_FILE = BACKEND_DIR / ".env" +SIM_ENV_FILE = BACKEND_DIR / ".env.sim" +SIM_STATE_DIR = ROOT_DIR / ".sim" + +CORE_COPY_TABLES = [ + "roles", + "permissions", + "departments", + "designations", + "settings", + "countries", + "states", + "cities", + "notification_templates", + "role_permissions", + "user_location_mappings", + "users", + "file_uploads", +] + +COMMERCE_COPY_TABLES = [ + # Catalog / storefront reference data + "attribute_types", + "brands", + "categories", + "device_series", + "device_models", + "device_type_registry", + "brand_device_types", + "products", + "product_variants", + "product_images", + "variant_images", + "variant_attributes", + "tags", + "product_tags", + "collections", + "product_collections", + "seo_metadata", + "storefront_settings", + "storefront_footer_info", + "storefront_contents", + "storefront_catalog_filters", + "storefront_mega_menu", + "service_catalog", + # Lightweight inventory/location reference data (all empty in prod today) + "crm_locations", + "crm_warehouses", + "crm_suppliers", + "product_locations", +] + + +def log(msg: str) -> None: + print(f"[provision] {msg}", flush=True) + + +def load_ssh_credentials() -> tuple[str, str, str]: + """Read SSH host/user/password from ssh_tunnel.py (already part of this repo).""" + host = os.getenv("SIM_SSH_HOST", "") + user = os.getenv("SIM_SSH_USER", "") + password = os.getenv("SIM_SSH_PASS", "") + if host and user and password: + return host, user, password + + tunnel = BACKEND_DIR / "ssh_tunnel.py" + if not tunnel.exists(): + raise SystemExit("ssh_tunnel.py not found and SIM_SSH_* env vars not set") + src = tunnel.read_text() + host = re.search(r'SSH_HOST\s*=\s*"([^"]+)"', src).group(1) + user = re.search(r'SSH_USER\s*=\s*"([^"]+)"', src).group(1) + password = re.search(r'SSH_PASS\s*=\s*"([^"]+)"', src).group(1) + return host, user, password + + +class MySQLAdmin: + def __init__(self, app_user: str | None = None, app_password: str | None = None) -> None: + host, user, password = load_ssh_credentials() + self.host = host + self.app_user = app_user + self.app_password = app_password + self.client = paramiko.SSHClient() + self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + self.client.connect(host, 22, user, password, timeout=20) + + def close(self) -> None: + self.client.close() + + def _run(self, command: str, sql: str) -> str: + stdin, stdout, stderr = self.client.exec_command(command, timeout=1800) + stdin.write(sql) + stdin.channel.shutdown_write() + out = stdout.read().decode(errors="replace") + err = stderr.read().decode(errors="replace") + status = stdout.channel.recv_exit_status() + if status != 0: + raise RuntimeError(f"MySQL command failed ({status}):\n{err[-4000:]}") + return out + err + + def exec_sql(self, sql: str, *, check: bool = True) -> str: + try: + return self._run("mysql -uroot -N --batch --raw", sql) + except RuntimeError: + if check: + raise + return "" + + def exec_as_app(self, sql: str) -> str: + """Run SQL as the application user on localhost (has GRANT OPTION here).""" + if not self.app_user or not self.app_password: + raise RuntimeError("Application DB credentials unavailable for GRANT") + command = ( + f"MYSQL_PWD={shlex.quote(self.app_password)} " + f"mysql -u{shlex.quote(self.app_user)} -N --batch --raw" + ) + return self._run(command, sql) + + def query(self, sql: str) -> list[list[str]]: + raw = self.exec_sql(sql + ";\n") + rows: list[list[str]] = [] + for line in raw.splitlines(): + if not line.strip(): + continue + rows.append(line.split("\t")) + return rows + + +def qident(name: str) -> str: + return "`" + name.replace("`", "``") + "`" + + +def qstr(value: str) -> str: + return "'" + value.replace("\\", "\\\\").replace("'", "''") + "'" + + +def sim_database_url(source_url: str, suffix: str) -> str: + url = make_url(source_url) + new_name = f"{url.database}{suffix}" + # render_as_string is required: str(URL) deliberately masks the password. + return url.set(database=new_name).render_as_string(hide_password=False) + + +def db_name(url: str) -> str: + parsed = make_url(url) + if not parsed.database: + raise SystemExit(f"Database URL has no database name: {url}") + return parsed.database + + +def copy_tables(admin: MySQLAdmin, source_db: str, target_db: str, tables: list[str] | None = None) -> list[str]: + if tables is None: + rows = admin.query( + "SELECT table_name FROM information_schema.tables " + f"WHERE table_schema={qstr(source_db)} AND table_type='BASE TABLE' " + "ORDER BY table_name" + ) + tables = [r[0] for r in rows] + + stmts = ["SET FOREIGN_KEY_CHECKS=0;"] + for table in tables: + stmts.append( + f"CREATE TABLE {qident(target_db)}.{qident(table)} " + f"LIKE {qident(source_db)}.{qident(table)};" + ) + stmts.append("SET FOREIGN_KEY_CHECKS=1;") + admin.exec_sql("\n".join(stmts)) + return tables + + +def copy_data(admin: MySQLAdmin, source_db: str, target_db: str, tables: list[str]) -> None: + stmts = ["SET FOREIGN_KEY_CHECKS=0;"] + for table in tables: + stmts.append( + f"INSERT INTO {qident(target_db)}.{qident(table)} " + f"SELECT * FROM {qident(source_db)}.{qident(table)};" + ) + stmts.append("SET FOREIGN_KEY_CHECKS=1;") + admin.exec_sql("\n".join(stmts)) + + +def seed_inventory(commerce_url: str, stock_per_variant: int) -> int: + engine = create_engine(commerce_url, future=True) + seeded = 0 + with engine.begin() as conn: + exists = conn.execute( + text("SELECT COUNT(*) FROM information_schema.tables " + "WHERE table_schema=DATABASE() AND table_name='inventory_ledger'") + ).scalar() + if not exists: + raise RuntimeError("inventory_ledger table missing in simulation schema") + conn.execute(text("DELETE FROM inventory_ledger")) + variants = [r[0] for r in conn.execute(text("SELECT variant_id FROM product_variants"))] + now = datetime.now(timezone.utc).replace(tzinfo=None) + rows = [ + { + "ledger_id": str(ulid.ULID()), + "variant_id": variant_id, + "event_type": "RECEIPT", + "qty": stock_per_variant, + "reference_id": "SIM_SEED", + "notes": "Simulation opening stock", + "created_at": now, + } + for variant_id in variants + ] + if rows: + conn.execute( + text( + "INSERT INTO inventory_ledger " + "(ledger_id, variant_id, event_type, qty, reference_id, notes, created_at) " + "VALUES (:ledger_id, :variant_id, :event_type, :qty, :reference_id, :notes, :created_at)" + ), + rows, + ) + seeded = len(rows) + return seeded + + +def write_sim_env( + core_url: str, + commerce_url: str, + crm_url: str, + email_domain: str, +) -> None: + # Keep the same credentials/query parameters as production, only swap the DB. + lines = [ + "# Generated by scripts/sim/provision_sim_db.py -- do not commit.", + "ENVIRONMENT=simulation", + "RUNTIME_ENV=simulation", + "SIMULATION_MODE=true", + "PAYMENT_SIMULATOR_ENABLED=true", + f"SIM_CUSTOMER_EMAIL_DOMAIN={email_domain}", + f"DATABASE_URL={core_url}", + f"CORE_DATABASE_URL={core_url}", + f"COMMERCE_DATABASE_URL={commerce_url}", + f"CRM_DATABASE_URL={crm_url}", + "REDIS_URL=redis://127.0.0.1:6379/3", + "RAZORPAY_ENABLED=false", + "SHIPROCKET_ENABLED=false", + "WATI_ENABLED=false", + "KNOWLARITY_ENABLED=false", + "GA4_ENABLED=false", + "META_ENABLED=false", + "SIM_THINK_TIME_SCALE=0.05", + "", + ] + SIM_ENV_FILE.write_text("\n".join(lines)) + try: + SIM_ENV_FILE.chmod(0o600) + except OSError: + pass + + +def ensure_gitignore() -> None: + gi = ROOT_DIR / ".gitignore" + entries = [".env.sim", ".sim/", "Backend/sim-artifacts/"] + existing = gi.read_text().splitlines() if gi.exists() else [] + missing = [e for e in entries if e not in existing] + if missing: + with gi.open("a") as f: + f.write("\n# Simulation runtime (generated, may contain credentials)\n") + for e in missing: + f.write(e + "\n") + + +def main() -> int: + parser = argparse.ArgumentParser(description="Provision isolated IfixKart simulation schemas") + parser.add_argument("--suffix", default="_sim", help="Database name suffix (default: _sim)") + parser.add_argument("--recreate", action="store_true", help="Drop the simulation DBs first") + parser.add_argument("--stock-per-variant", type=int, default=5000, help="Opening stock per active variant") + parser.add_argument("--email-domain", default="@sim.example.com", help="Email domain for simulated customers") + parser.add_argument("--skip-env", action="store_true", help="Do not write Backend/.env.sim") + args = parser.parse_args() + + if not ENV_FILE.exists(): + raise SystemExit(f"Missing {ENV_FILE}") + load_dotenv(ENV_FILE, override=False) + + core_source = os.getenv("CORE_DATABASE_URL") or os.getenv("DATABASE_URL") + commerce_source = os.getenv("COMMERCE_DATABASE_URL") or os.getenv("DATABASE_URL") + crm_source = os.getenv("CRM_DATABASE_URL") or commerce_source + if not core_source or not commerce_source: + raise SystemExit("CORE_DATABASE_URL / COMMERCE_DATABASE_URL are not configured in .env") + + core_sim = sim_database_url(core_source, args.suffix) + commerce_sim = sim_database_url(commerce_source, args.suffix) + crm_sim = sim_database_url(crm_source, args.suffix) + + core_src_db = db_name(core_source) + commerce_src_db = db_name(commerce_source) + crm_src_db = db_name(crm_source) + core_sim_db = db_name(core_sim) + commerce_sim_db = db_name(commerce_sim) + crm_sim_db = db_name(crm_sim) + + app_user = make_url(commerce_source).username + app_password = make_url(commerce_source).password + if not app_user: + raise SystemExit("Could not read the application DB username from .env") + + admin = MySQLAdmin(app_user=app_user, app_password=app_password) + try: + log(f"Connected to MySQL host {admin.host} as admin") + if args.recreate: + log(f"Dropping {core_sim_db}, {commerce_sim_db}, {crm_sim_db}") + admin.exec_sql( + f"DROP DATABASE IF EXISTS {qident(core_sim_db)};\n" + f"DROP DATABASE IF EXISTS {qident(commerce_sim_db)};\n" + f"DROP DATABASE IF EXISTS {qident(crm_sim_db)};\n" + ) + + for name in (core_sim_db, commerce_sim_db, crm_sim_db): + existing = admin.query( + "SELECT COUNT(*) FROM information_schema.tables " + f"WHERE table_schema={qstr(name)}" + ) + count = int(existing[0][0]) if existing else 0 + if count: + raise SystemExit( + f"Simulation database {name} already has {count} tables. " + "Re-run with --recreate to rebuild it." + ) + admin.exec_sql( + f"CREATE DATABASE IF NOT EXISTS {qident(name)} " + "CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" + ) + + log("Cloning table structures") + core_tables = copy_tables(admin, core_src_db, core_sim_db) + commerce_tables = copy_tables(admin, commerce_src_db, commerce_sim_db) + crm_tables = copy_tables(admin, crm_src_db, crm_sim_db) + log( + f" core: {len(core_tables)} tables, commerce: {len(commerce_tables)} tables, " + f"crm: {len(crm_tables)} tables" + ) + + log("Copying reference/catalog data") + core_copy = [t for t in CORE_COPY_TABLES if t in core_tables] + commerce_copy = [t for t in COMMERCE_COPY_TABLES if t in commerce_tables] + copy_data(admin, core_src_db, core_sim_db, core_copy) + copy_data(admin, commerce_src_db, commerce_sim_db, commerce_copy) + # The CRM schema is small (services/repair catalog only). Copy it entirely. + copy_data(admin, crm_src_db, crm_sim_db, crm_tables) + log(f" copied {len(core_copy)} core + {len(commerce_copy)} commerce + {len(crm_tables)} crm tables") + + log(f"Granting {app_user} access to simulation schemas") + for name in (core_sim_db, commerce_sim_db, crm_sim_db): + admin.exec_as_app( + f"GRANT ALL PRIVILEGES ON {qident(name)}.* TO " + f"{qstr(app_user)}@'127.0.0.1';\nFLUSH PRIVILEGES;\n" + ) + finally: + admin.close() + + log("Seeding opening stock") + seeded = seed_inventory(commerce_sim, args.stock_per_variant) + log(f" {seeded} variants x {args.stock_per_variant} units") + + ensure_gitignore() + if not args.skip_env: + write_sim_env(core_sim, commerce_sim, crm_sim, args.email_domain) + log(f"Wrote {SIM_ENV_FILE}") + + SIM_STATE_DIR.mkdir(parents=True, exist_ok=True) + state = { + "provisioned_at": datetime.now(timezone.utc).isoformat(), + "suffix": args.suffix, + "core_db": core_sim_db, + "commerce_db": commerce_sim_db, + "crm_db": crm_sim_db, + "core_source": core_src_db, + "commerce_source": commerce_src_db, + "crm_source": crm_src_db, + "stock_per_variant": args.stock_per_variant, + "core_tables": len(core_tables), + "commerce_tables": len(commerce_tables), + "crm_tables": len(crm_tables), + "catalog_rows": {t: None for t in commerce_copy}, + } + (SIM_STATE_DIR / "provision.json").write_text(json.dumps(state, indent=2)) + log(f"Done. State: {SIM_STATE_DIR / 'provision.json'}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/sim/run_sim_backend.py b/scripts/sim/run_sim_backend.py new file mode 100644 index 0000000..4a7cc57 --- /dev/null +++ b/scripts/sim/run_sim_backend.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +""" +Launch a second IfixKart backend instance pointed at the simulation schemas. + +The normal backend keeps running on :8000 against production data. This process +loads Backend/.env.sim (generated by provision_sim_db.py) and listens on :8001. + +Usage: + cd Backend + ./venv/bin/python scripts/sim/run_sim_backend.py + ./venv/bin/python scripts/sim/run_sim_backend.py --port 8001 --reload +""" +from __future__ import annotations + +import argparse +import os +import sys +from pathlib import Path + +BACKEND_DIR = Path(__file__).resolve().parents[2] +if str(BACKEND_DIR) not in sys.path: + sys.path.insert(0, str(BACKEND_DIR)) +SIM_ENV = BACKEND_DIR / ".env.sim" + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--host", default="127.0.0.1") + parser.add_argument("--port", type=int, default=8001) + parser.add_argument("--reload", action="store_true") + args = parser.parse_args() + + if not SIM_ENV.exists(): + raise SystemExit(f"Missing {SIM_ENV}; run provision_sim_db.py first") + os.chdir(BACKEND_DIR) + # Load before importing the app so pydantic Settings sees these values. + from dotenv import load_dotenv + load_dotenv(SIM_ENV, override=True) + os.environ.setdefault("ENVIRONMENT", "simulation") + + import uvicorn + uvicorn.run( + "app.main:app", + host=args.host, + port=args.port, + reload=args.reload, + log_level="info", + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/sim/seed_customers.py b/scripts/sim/seed_customers.py new file mode 100644 index 0000000..5a03e31 --- /dev/null +++ b/scripts/sim/seed_customers.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +""" +Seed simulation customers and addresses directly into the sim commerce schema. + +The swarm agents then log in through the real /api/v1/customer/auth/login +endpoint, so authentication, JWT issuance, carts, checkout, stock and invoices +all run through the application exactly as they do for a human. + +Usage: + cd Backend + ./venv/bin/python scripts/sim/seed_customers.py --count 10000 + ./venv/bin/python scripts/sim/seed_customers.py --count 100 --run-id demo1 +""" +from __future__ import annotations + +import argparse +import json +import os +import random +import string +import sys +from datetime import datetime, timezone +from pathlib import Path + +import ulid +from dotenv import load_dotenv +from sqlalchemy import insert, select, text + +BACKEND_DIR = Path(__file__).resolve().parents[2] +ROOT_DIR = BACKEND_DIR.parent +if str(BACKEND_DIR) not in sys.path: + sys.path.insert(0, str(BACKEND_DIR)) +SIM_ENV = BACKEND_DIR / ".env.sim" +ARTIFACT_DIR = BACKEND_DIR / "sim-artifacts" + +FIRST_NAMES = [ + "Aarav", "Aditi", "Akhil", "Ananya", "Arjun", "Ayesha", "Bala", "Bhavna", + "Chetan", "Deepa", "Dev", "Divya", "Farhan", "Gaurav", "Harini", "Imran", + "Isha", "Jeevan", "Kabir", "Kavya", "Kiran", "Lakshmi", "Manish", "Meera", + "Mohan", "Nandini", "Naveen", "Neha", "Nikhil", "Pallavi", "Pooja", "Pranav", + "Priya", "Rahul", "Ravi", "Riya", "Rohit", "Sahana", "Sanjay", "Sara", + "Shreya", "Siddharth", "Sneha", "Suresh", "Tanvi", "Uday", "Varun", "Vidya", + "Vikram", "Yash", +] + +LAST_NAMES = [ + "Agarwal", "Bhat", "Chandra", "Das", "Desai", "Gowda", "Gupta", "Hegde", + "Iyer", "Jain", "Joshi", "Kapoor", "Khan", "Krishnan", "Kulkarni", "Kumar", + "Menon", "Mehta", "Mishra", "Nair", "Naidu", "Patel", "Pillai", "Rao", + "Reddy", "Sethi", "Shah", "Sharma", "Shetty", "Singh", "Sinha", "Srinivas", + "Suresh", "Swamy", "Varma", "Verma", +] + +CITIES = [ + ("Bengaluru", "Karnataka", "560001"), + ("Mysuru", "Karnataka", "570001"), + ("Mangaluru", "Karnataka", "575001"), + ("Hyderabad", "Telangana", "500001"), + ("Chennai", "Tamil Nadu", "600001"), + ("Coimbatore", "Tamil Nadu", "641001"), + ("Madurai", "Tamil Nadu", "625001"), + ("Mumbai", "Maharashtra", "400001"), + ("Pune", "Maharashtra", "411001"), + ("Nagpur", "Maharashtra", "440001"), + ("Delhi", "Delhi", "110001"), + ("Noida", "Uttar Pradesh", "201301"), + ("Lucknow", "Uttar Pradesh", "226001"), + ("Jaipur", "Rajasthan", "302001"), + ("Ahmedabad", "Gujarat", "380001"), + ("Surat", "Gujarat", "395001"), + ("Kochi", "Kerala", "682001"), + ("Thiruvananthapuram", "Kerala", "695001"), + ("Kolkata", "West Bengal", "700001"), + ("Bhubaneswar", "Odisha", "751001"), + ("Visakhapatnam", "Andhra Pradesh", "530001"), + ("Vijayawada", "Andhra Pradesh", "520001"), + ("Indore", "Madhya Pradesh", "452001"), + ("Bhopal", "Madhya Pradesh", "462001"), + ("Chandigarh", "Chandigarh", "160001"), + ("Guwahati", "Assam", "781001"), + ("Patna", "Bihar", "800001"), + ("Ranchi", "Jharkhand", "834001"), + ("Raipur", "Chhattisgarh", "492001"), + ("Dehradun", "Uttarakhand", "248001"), +] + +STREETS = [ + "MG Road", "Brigade Road", "Residency Road", "Church Street", "Jayanagar 4th Block", + "Indiranagar 100ft Road", "Koramangala 5th Block", "HSR Layout Sector 2", + "Anna Nagar", "T Nagar", "Adyar", "Banjara Hills", "Jubilee Hills", "Madhapur", + "Salt Lake Sector V", "Park Street", "Connaught Place", "Hauz Khas", + "Koregaon Park", "Baner Road", "Law Garden", "Navrangpura", "Panampilly Nagar", +] + + +def log(msg: str) -> None: + print(f"[seed] {msg}", flush=True) + + +def ensure_artifacts() -> None: + ARTIFACT_DIR.mkdir(parents=True, exist_ok=True) + gi = ROOT_DIR / ".gitignore" + entry = "Backend/sim-artifacts/" + existing = gi.read_text().splitlines() if gi.exists() else [] + if entry not in existing: + with gi.open("a") as f: + f.write(f"\n# Simulation runtime artifacts\n{entry}\n") + + +def main() -> int: + parser = argparse.ArgumentParser(description="Seed simulation customers into the sim DB") + parser.add_argument("--count", type=int, default=1000) + parser.add_argument("--run-id", default="") + parser.add_argument("--password", default="SimSwarm!2026") + parser.add_argument("--email-domain", default="@sim.example.com") + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--batch-size", type=int, default=1000) + args = parser.parse_args() + + if not SIM_ENV.exists(): + raise SystemExit(f"Missing {SIM_ENV}; run provision_sim_db.py first") + load_dotenv(SIM_ENV, override=True) + if os.getenv("SIMULATION_MODE", "").lower() not in ("1", "true", "yes"): + raise SystemExit("Refusing to seed: SIMULATION_MODE is not true in .env.sim") + + # Import after loading .env.sim so the engines point at the sim schemas. + from app.core.config.Config import settings + from app.core.database.db_session import SessionLocal + import app.models.db_base # noqa: F401 (registers all mappers) + from app.models.EcomCustomerModel import EcomCustomer, CustomerAddress + from app.utils.Hash_util import hash_password + + domain = args.email_domain if args.email_domain.startswith("@") else "@" + args.email_domain + run_id = args.run_id or datetime.now(timezone.utc).strftime("%Y%m%d%H%M%S") + run_tag = run_id.lower().replace("-", "").replace("_", "") + if not run_tag: + raise SystemExit("Invalid run id") + rng = random.Random(args.seed) + + ensure_artifacts() + + # Vectorise password hashing: one Argon2 hash reused for the whole sim fleet. + pwd_hash = hash_password(args.password) + now = datetime.now(timezone.utc).replace(tzinfo=None) + run_num = int.from_bytes(run_tag.encode()[-4:].ljust(4, b"0"), "big") % 100000 + rows_customers: list[dict] = [] + rows_addresses: list[dict] = [] + agents: list[dict] = [] + + for i in range(args.count): + customer_id = str(ulid.ULID()) + first = rng.choice(FIRST_NAMES) + last = rng.choice(LAST_NAMES) + email = f"sim.{run_tag}.{i:06d}{domain}" + phone = f"9{run_num:05d}{i:04d}"[-10:] + city, state, pincode = rng.choice(CITIES) + street = f"{rng.randint(1, 240)}, {rng.choice(STREETS)}" + rows_customers.append( + { + "customer_id": customer_id, + "email": email, + "password_hash": pwd_hash, + "first_name": first, + "last_name": last, + "phone": phone, + "is_active": True, + "email_verified": True, + "phone_verified": False, + "failed_login_attempts": 0, + "is_locked": False, + "created_at": now, + "updated_at": now, + } + ) + rows_addresses.append( + { + "address_id": str(ulid.ULID()), + "customer_id": customer_id, + "address_type": "SHIPPING", + "full_name": f"{first} {last}", + "phone": phone, + "street_address": street, + "city": city, + "state": state, + "pincode": pincode, + "is_default": True, + "created_at": now, + } + ) + agents.append( + { + "customer_id": customer_id, + "email": email, + "password": args.password, + "first_name": first, + "last_name": last, + "city": city, + "state": state, + "pincode": pincode, + } + ) + + db = SessionLocal() + try: + existing = db.execute( + select(EcomCustomer.customer_id).where(EcomCustomer.email.in_([a["email"] for a in agents[:50]])) + ).first() + if existing: + raise SystemExit("Some simulated emails already exist; use a different --run-id") + + for start in range(0, len(rows_customers), args.batch_size): + c_batch = rows_customers[start:start + args.batch_size] + a_batch = rows_addresses[start:start + args.batch_size] + db.execute(insert(EcomCustomer), c_batch) + db.execute(insert(CustomerAddress), a_batch) + db.commit() + log(f"seeded {min(start + args.batch_size, len(rows_customers))}/{args.count}") + finally: + db.close() + + artifact = { + "run_id": run_id, + "created_at": datetime.now(timezone.utc).isoformat(), + "count": len(agents), + "email_domain": domain, + "commerce_db": settings.COMMERCE_DATABASE_URL.rsplit("/", 1)[-1], + "agents": agents, + } + out = ARTIFACT_DIR / f"agents-{run_id}.json" + out.write_text(json.dumps(artifact, indent=2)) + (ARTIFACT_DIR / "latest.json").write_text(json.dumps({"run_id": run_id, "file": out.name}, indent=2)) + log(f"wrote {out} ({out.stat().st_size / 1024 / 1024:.1f} MB)") + log(f"password for all seeded customers: {args.password!r} (simulation only)") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())