feat(backend): implement Shiprocket autonomous logistics, Ready for Delivery lifecycle, and concurrency optimizations
This commit is contained in:
parent
75f103a42a
commit
7632685a63
49 changed files with 2126 additions and 316 deletions
|
|
@ -2,7 +2,7 @@
|
||||||
@router AdminCustomerRouter (Backend/app/api/v1/routers/AdminCustomerRouter.py)
|
@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.
|
@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 sqlalchemy.orm import Session
|
||||||
from pydantic import BaseModel, EmailStr
|
from pydantic import BaseModel, EmailStr
|
||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
|
|
@ -59,13 +59,25 @@ class AdminCustomerDetailResponse(BaseModel):
|
||||||
|
|
||||||
@router.get("", response_model=List[AdminCustomerListResponse])
|
@router.get("", response_model=List[AdminCustomerListResponse])
|
||||||
def list_all_customers(
|
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),
|
current_user: User = Depends(get_current_user),
|
||||||
db: Session = Depends(get_db)
|
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 [
|
return [
|
||||||
AdminCustomerListResponse(
|
AdminCustomerListResponse(
|
||||||
customer_id=c.customer_id,
|
customer_id=c.customer_id,
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
@router AdminInvoiceRouter (Backend/app/api/v1/routers/AdminInvoiceRouter.py)
|
@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.
|
@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 sqlalchemy.orm import Session
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
|
|
@ -12,7 +12,7 @@ import io
|
||||||
import zipfile
|
import zipfile
|
||||||
|
|
||||||
from app.core.database.db_session import get_db
|
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.UserModel import User
|
||||||
from app.models.InvoiceModel import Invoice
|
from app.models.InvoiceModel import Invoice
|
||||||
from app.models.OrderModel import Order, OrderItem
|
from app.models.OrderModel import Order, OrderItem
|
||||||
|
|
@ -43,21 +43,26 @@ class AdminInvoiceResponse(BaseModel):
|
||||||
|
|
||||||
@router.get("", response_model=List[AdminInvoiceResponse])
|
@router.get("", response_model=List[AdminInvoiceResponse])
|
||||||
def list_all_invoices(
|
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),
|
current_user: User = Depends(get_current_user),
|
||||||
db: Session = Depends(get_db)
|
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 = []
|
result = []
|
||||||
for inv in invoices:
|
for inv in invoices:
|
||||||
cust_email = None
|
cust_email = customer_map.get(inv.customer_id)
|
||||||
customer = db.query(EcomCustomer).filter(EcomCustomer.customer_id == inv.customer_id).first()
|
|
||||||
if customer:
|
|
||||||
cust_email = customer.email
|
|
||||||
|
|
||||||
pdf_url = f"/api/v1/admin/invoices/{inv.invoice_id}/download"
|
pdf_url = f"/api/v1/admin/invoices/{inv.invoice_id}/download"
|
||||||
|
|
||||||
result.append(
|
result.append(
|
||||||
|
|
@ -185,6 +190,7 @@ def generate_invoice_for_order(
|
||||||
@router.get("/{invoice_id}/download")
|
@router.get("/{invoice_id}/download")
|
||||||
def download_invoice_pdf(
|
def download_invoice_pdf(
|
||||||
invoice_id: str,
|
invoice_id: str,
|
||||||
|
current_user: User = Depends(RoleChecker(["Super Admin", "Admin", "Manager", "Accountant"])),
|
||||||
db: Session = Depends(get_db)
|
db: Session = Depends(get_db)
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
|
|
@ -223,6 +229,7 @@ def download_invoice_pdf(
|
||||||
@router.get("/{invoice_id}/thermal-download")
|
@router.get("/{invoice_id}/thermal-download")
|
||||||
def download_thermal_invoice_pdf(
|
def download_thermal_invoice_pdf(
|
||||||
invoice_id: str,
|
invoice_id: str,
|
||||||
|
current_user: User = Depends(RoleChecker(["Super Admin", "Admin", "Manager", "Accountant"])),
|
||||||
db: Session = Depends(get_db)
|
db: Session = Depends(get_db)
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
|
|
@ -262,9 +269,15 @@ def download_thermal_invoice_pdf(
|
||||||
def export_invoices_excel(
|
def export_invoices_excel(
|
||||||
start_date: Optional[str] = None,
|
start_date: Optional[str] = None,
|
||||||
end_date: Optional[str] = None,
|
end_date: Optional[str] = None,
|
||||||
|
current_user: User = Depends(RoleChecker(["Super Admin", "Admin", "Manager", "Accountant"])),
|
||||||
db: Session = Depends(get_db)
|
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"
|
csv_data = "Invoice No,Order ID,Customer ID,Subtotal,CGST,SGST,Total Amount,Created At\n"
|
||||||
for inv in invoices:
|
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"
|
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(
|
def export_invoices_zip(
|
||||||
start_date: Optional[str] = None,
|
start_date: Optional[str] = None,
|
||||||
end_date: Optional[str] = None,
|
end_date: Optional[str] = None,
|
||||||
|
current_user: User = Depends(RoleChecker(["Super Admin", "Admin", "Manager", "Accountant"])),
|
||||||
db: Session = Depends(get_db)
|
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()
|
zip_buffer = io.BytesIO()
|
||||||
with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zip_file:
|
with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zip_file:
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,7 @@ from app.services.NotificationGatewayService import NotificationGatewayService
|
||||||
from app.schemas.NotificationGateway import EntityNotificationDispatchCreate
|
from app.schemas.NotificationGateway import EntityNotificationDispatchCreate
|
||||||
from app.services.WarrantyService import WarrantyService
|
from app.services.WarrantyService import WarrantyService
|
||||||
from app.services.CreditService import CreditService
|
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"])
|
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
|
billing_address_json: Optional[str] = None
|
||||||
tracking_number: Optional[str] = None
|
tracking_number: Optional[str] = None
|
||||||
courier_name: 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
|
created_at: datetime
|
||||||
items: List[OrderItemDetail]
|
items: List[OrderItemDetail]
|
||||||
history: List[StatusHistorySchema]
|
history: List[StatusHistorySchema]
|
||||||
|
|
@ -85,12 +89,15 @@ class AdminOrderListResponse(BaseModel):
|
||||||
coupon_code: Optional[str] = None
|
coupon_code: Optional[str] = None
|
||||||
status: str
|
status: str
|
||||||
payment_status: str
|
payment_status: str
|
||||||
|
shipping_label_url: Optional[str] = None
|
||||||
created_at: datetime
|
created_at: datetime
|
||||||
|
|
||||||
class StatusUpdatePayload(BaseModel):
|
class StatusUpdatePayload(BaseModel):
|
||||||
status: str
|
status: str
|
||||||
tracking_number: Optional[str] = None
|
tracking_number: Optional[str] = None
|
||||||
courier_name: Optional[str] = None
|
courier_name: Optional[str] = None
|
||||||
|
package_weight: Optional[float] = None
|
||||||
|
logistics_provider: Optional[str] = "SHIPROCKET"
|
||||||
reason: Optional[str] = None
|
reason: Optional[str] = None
|
||||||
part_numbers_mapping: Optional[Dict[str, List[str]]] = None
|
part_numbers_mapping: Optional[Dict[str, List[str]]] = None
|
||||||
|
|
||||||
|
|
@ -142,6 +149,7 @@ def list_all_orders(
|
||||||
coupon_code=o.coupon_code,
|
coupon_code=o.coupon_code,
|
||||||
status=o.status,
|
status=o.status,
|
||||||
payment_status=o.payment_status,
|
payment_status=o.payment_status,
|
||||||
|
shipping_label_url=o.shipping_label_url,
|
||||||
created_at=o.created_at
|
created_at=o.created_at
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
@ -191,6 +199,9 @@ def get_order_details(
|
||||||
billing_address_json=order.billing_address_json,
|
billing_address_json=order.billing_address_json,
|
||||||
tracking_number=order.tracking_number,
|
tracking_number=order.tracking_number,
|
||||||
courier_name=order.courier_name,
|
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,
|
created_at=order.created_at,
|
||||||
items=[
|
items=[
|
||||||
OrderItemDetail(
|
OrderItemDetail(
|
||||||
|
|
@ -234,7 +245,7 @@ def _dispatch_bg_notification(tenant_id: str, payload: EntityNotificationDispatc
|
||||||
|
|
||||||
|
|
||||||
@router.put("/{order_id}/status")
|
@router.put("/{order_id}/status")
|
||||||
def update_order_status(
|
async def update_order_status(
|
||||||
order_id: str,
|
order_id: str,
|
||||||
payload: StatusUpdatePayload,
|
payload: StatusUpdatePayload,
|
||||||
background_tasks: BackgroundTasks,
|
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.
|
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()
|
order = db.query(Order).filter(Order.order_id == order_id).first()
|
||||||
if not order:
|
if not order:
|
||||||
|
|
@ -252,7 +265,33 @@ def update_order_status(
|
||||||
)
|
)
|
||||||
|
|
||||||
previous_status = 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
|
# Transition tracking info if provided
|
||||||
if payload.tracking_number:
|
if payload.tracking_number:
|
||||||
|
|
@ -265,6 +304,35 @@ def update_order_status(
|
||||||
if item.item_id in payload.part_numbers_mapping:
|
if item.item_id in payload.part_numbers_mapping:
|
||||||
item.part_numbers = payload.part_numbers_mapping[item.item_id]
|
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
|
# Set fulfillment status flags
|
||||||
if new_status in ["SHIPPED", "DELIVERED"]:
|
if new_status in ["SHIPPED", "DELIVERED"]:
|
||||||
order.fulfillment_status = "FULFILLED"
|
order.fulfillment_status = "FULFILLED"
|
||||||
|
|
@ -273,8 +341,8 @@ def update_order_status(
|
||||||
|
|
||||||
# --- STOCK CONFIRMATION / RELEASE LOGIC ---
|
# --- STOCK CONFIRMATION / RELEASE LOGIC ---
|
||||||
|
|
||||||
# 1. Transition: ORDER_CREATED/PAYMENT_PENDING -> ORDER_CONFIRMED/PROCESSING/SHIPPED/DELIVERED
|
# 1. Transition: ORDER_CREATED/PAYMENT_PENDING/PENDING -> CONFIRMED/READY_FOR_DELIVERY
|
||||||
if new_status in ["ORDER_CONFIRMED", "PROCESSING", "SHIPPED", "DELIVERED"] and previous_status in ["ORDER_CREATED", "PAYMENT_PENDING"]:
|
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
|
# Record the physical sale transition in the ledger by subtracting quantity
|
||||||
for item in order.items:
|
for item in order.items:
|
||||||
record_ledger_entry(
|
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 ---
|
# --- Manual Order Creation Schemas ---
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ import ulid
|
||||||
from app.core.database.db_session import get_db
|
from app.core.database.db_session import get_db
|
||||||
from app.core.config.Config import settings
|
from app.core.config.Config import settings
|
||||||
from app.core.Token import create_access_token
|
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.user_repository import user_repository
|
||||||
from app.repositories.session_repository import session_repository
|
from app.repositories.session_repository import session_repository
|
||||||
from app.models.UserSessionModel import UserSession
|
from app.models.UserSessionModel import UserSession
|
||||||
|
|
@ -131,7 +131,7 @@ def login(
|
||||||
longitude=data.longitude,
|
longitude=data.longitude,
|
||||||
location_name=data.location_name,
|
location_name=data.location_name,
|
||||||
device_fingerprint=data.device_fingerprint,
|
device_fingerprint=data.device_fingerprint,
|
||||||
refresh_token=raw_refresh,
|
refresh_token=hash_token(raw_refresh),
|
||||||
access_token_id=session_id, # Match token references
|
access_token_id=session_id, # Match token references
|
||||||
expires_at=datetime.now(timezone.utc) + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS),
|
expires_at=datetime.now(timezone.utc) + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS),
|
||||||
is_active=True
|
is_active=True
|
||||||
|
|
@ -140,7 +140,7 @@ def login(
|
||||||
db.add(session_entry)
|
db.add(session_entry)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|
||||||
# 6. Set response cookie and header
|
# 6. Set response cookie (strictly HttpOnly to prevent JavaScript access)
|
||||||
response.set_cookie(
|
response.set_cookie(
|
||||||
"refresh_token",
|
"refresh_token",
|
||||||
raw_refresh,
|
raw_refresh,
|
||||||
|
|
@ -152,7 +152,7 @@ def login(
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"access_token": access_token,
|
"access_token": access_token,
|
||||||
"refresh_token": raw_refresh,
|
"refresh_token": None,
|
||||||
"token_type": "bearer"
|
"token_type": "bearer"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -207,7 +207,7 @@ def refresh(
|
||||||
longitude=session.longitude,
|
longitude=session.longitude,
|
||||||
location_name=session.location_name,
|
location_name=session.location_name,
|
||||||
device_fingerprint=session.device_fingerprint,
|
device_fingerprint=session.device_fingerprint,
|
||||||
refresh_token=new_refresh,
|
refresh_token=hash_token(new_refresh),
|
||||||
access_token_id=new_session_id,
|
access_token_id=new_session_id,
|
||||||
expires_at=datetime.now(timezone.utc) + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS),
|
expires_at=datetime.now(timezone.utc) + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS),
|
||||||
is_active=True
|
is_active=True
|
||||||
|
|
@ -226,7 +226,7 @@ def refresh(
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"access_token": new_access,
|
"access_token": new_access,
|
||||||
"refresh_token": new_refresh,
|
"refresh_token": None,
|
||||||
"token_type": "bearer"
|
"token_type": "bearer"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -311,7 +311,7 @@ def oauth2_token(
|
||||||
browser=browser_name,
|
browser=browser_name,
|
||||||
operating_system=os_name,
|
operating_system=os_name,
|
||||||
ip_address=get_client_ip(request),
|
ip_address=get_client_ip(request),
|
||||||
refresh_token=raw_refresh,
|
refresh_token=hash_token(raw_refresh),
|
||||||
access_token_id=session_id,
|
access_token_id=session_id,
|
||||||
expires_at=datetime.now(timezone.utc) + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS),
|
expires_at=datetime.now(timezone.utc) + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS),
|
||||||
is_active=True
|
is_active=True
|
||||||
|
|
@ -330,7 +330,7 @@ def oauth2_token(
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"access_token": access_token,
|
"access_token": access_token,
|
||||||
"refresh_token": raw_refresh,
|
"refresh_token": None,
|
||||||
"token_type": "bearer"
|
"token_type": "bearer"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@
|
||||||
from fastapi import APIRouter, Depends, HTTPException, status
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from typing import List, Optional, Any
|
from typing import List, Optional, Any
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session, joinedload
|
||||||
import ulid
|
import ulid
|
||||||
import json
|
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.EcomCustomerModel import EcomCustomer
|
||||||
from app.models.CartModel import Cart
|
from app.models.CartModel import Cart
|
||||||
from app.models.ProductModel import ProductVariant
|
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"])
|
router = APIRouter(prefix="/api/v1/cart", tags=["Shopping Cart"])
|
||||||
|
|
||||||
|
|
@ -97,12 +97,27 @@ def _enrich_and_totals(
|
||||||
) -> dict:
|
) -> dict:
|
||||||
enriched = []
|
enriched = []
|
||||||
subtotal = 0.0
|
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))
|
qty = int(item.get("qty", 1))
|
||||||
if qty <= 0:
|
variant = variant_map.get(variant_id)
|
||||||
continue
|
|
||||||
variant = db.query(ProductVariant).filter(ProductVariant.variant_id == variant_id).first()
|
|
||||||
if not variant:
|
if not variant:
|
||||||
continue
|
continue
|
||||||
unit_price = float(variant.price)
|
unit_price = float(variant.price)
|
||||||
|
|
@ -116,7 +131,7 @@ def _enrich_and_totals(
|
||||||
"product_name": product_name,
|
"product_name": product_name,
|
||||||
"sku": variant.sku,
|
"sku": variant.sku,
|
||||||
"total_price": round(line_total, 2),
|
"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
|
from app.services.DeliveryService import DeliveryService
|
||||||
|
|
|
||||||
|
|
@ -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]]:
|
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)
|
stock_map = get_available_stock_map(_variant_ids_from_serialized(products), db)
|
||||||
for product in products:
|
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 []:
|
for variant in product.get("variants") or []:
|
||||||
variant["available_stock"] = stock_map.get(variant.get("variant_id"), 0)
|
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
|
return products
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -597,8 +635,13 @@ def get_all_repair_variants(db: Session = Depends(get_db)):
|
||||||
|
|
||||||
# ================= STOCK LEDGER & MANUAL ADJUSTMENTS =================
|
# ================= STOCK LEDGER & MANUAL ADJUSTMENTS =================
|
||||||
@router.get("/stock-movements/history", response_model=List[StockMovementResponse])
|
@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"]))):
|
def get_stock_movements_history(
|
||||||
return db.execute(select(StockMovement).order_by(StockMovement.created_at.desc())).scalars().all()
|
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)
|
@router.post("/stock-movements/adjust", response_model=StockMovementResponse, status_code=status.HTTP_201_CREATED)
|
||||||
def create_manual_stock_adjustment(
|
def create_manual_stock_adjustment(
|
||||||
|
|
@ -661,8 +704,13 @@ def create_purchase_order(data: PurchaseOrderCreate, db: Session = Depends(get_d
|
||||||
return po
|
return po
|
||||||
|
|
||||||
@router.get("/purchase-orders/all", response_model=List[PurchaseOrderResponse])
|
@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"]))):
|
def get_all_purchase_orders(
|
||||||
return db.execute(select(PurchaseOrder)).scalars().all()
|
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)
|
@router.post("/purchase-orders/{po_id}/receive", response_model=PurchaseOrderResponse)
|
||||||
def receive_purchase_order_items(
|
def receive_purchase_order_items(
|
||||||
|
|
@ -758,6 +806,8 @@ def get_all_products(
|
||||||
selectinload(Product.variants).selectinload(ProductVariant.attributes),
|
selectinload(Product.variants).selectinload(ProductVariant.attributes),
|
||||||
selectinload(Product.variants).selectinload(ProductVariant.images),
|
selectinload(Product.variants).selectinload(ProductVariant.images),
|
||||||
selectinload(Product.images),
|
selectinload(Product.images),
|
||||||
|
selectinload(Product.brand),
|
||||||
|
selectinload(Product.category),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
stmt = apply_product_search(stmt, search)
|
stmt = apply_product_search(stmt, search)
|
||||||
|
|
@ -795,22 +845,25 @@ def get_products(
|
||||||
rating: Optional[float] = Query(None),
|
rating: Optional[float] = Query(None),
|
||||||
discount: Optional[float] = Query(None),
|
discount: Optional[float] = Query(None),
|
||||||
cursor: Optional[str] = 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)
|
db: Session = Depends(get_db)
|
||||||
):
|
):
|
||||||
import base64
|
import base64
|
||||||
from app.core.database.cache_manager import cache
|
from app.core.database.cache_manager import cache
|
||||||
|
|
||||||
# Generate Cache Key based on all parameters (caching for 5 min / 300s)
|
# 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)
|
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
|
return cached_data
|
||||||
|
|
||||||
# Base Query with Eager Loading (eliminates N+1 query bottleneck)
|
# Base Query with Eager Loading (eliminates N+1 query bottleneck)
|
||||||
stmt = select(Product).options(
|
stmt = select(Product).options(
|
||||||
|
selectinload(Product.variants).selectinload(ProductVariant.attributes).selectinload(VariantAttribute.attribute_type),
|
||||||
selectinload(Product.variants).selectinload(ProductVariant.images),
|
selectinload(Product.variants).selectinload(ProductVariant.images),
|
||||||
selectinload(Product.images)
|
selectinload(Product.images),
|
||||||
|
selectinload(Product.brand),
|
||||||
).where(Product.status == "active")
|
).where(Product.status == "active")
|
||||||
|
|
||||||
# Dynamic Filtering
|
# Dynamic Filtering
|
||||||
|
|
@ -907,17 +960,36 @@ def get_products(
|
||||||
stock_map = get_available_stock_map(page_variant_ids, db)
|
stock_map = get_available_stock_map(page_variant_ids, db)
|
||||||
|
|
||||||
# Map to lightweight DTO schema
|
# Map to lightweight DTO schema
|
||||||
mapped_products = []
|
def _variant_label(v) -> str:
|
||||||
for p in products_list:
|
"""Build a human-readable variant label from its attributes (e.g. 'Moonlight Silver')."""
|
||||||
first_var = p.variants[0] if p.variants else None
|
vals = []
|
||||||
price = first_var.price if first_var else Decimal("0.0")
|
for a in (v.attributes or []):
|
||||||
compare_price = first_var.compare_price if first_var else None
|
# 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)
|
||||||
|
|
||||||
# Calculate discount
|
def _variant_image(v, product) -> Optional[str]:
|
||||||
discount_percent = 0
|
"""Variant-specific image with product-level fallback."""
|
||||||
if price and compare_price and compare_price > price:
|
if v.images:
|
||||||
discount_percent = int(((compare_price - price) / compare_price) * 100)
|
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
|
thumbnail_url = None
|
||||||
if p.images:
|
if p.images:
|
||||||
banner_img = next((img.image_url for img in p.images if img.is_banner), p.images[0].image_url)
|
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:
|
elif first_var and first_var.images:
|
||||||
thumbnail_url = first_var.images[0].image_url
|
thumbnail_url = first_var.images[0].image_url
|
||||||
|
|
||||||
mapped_products.append(ProductCardResponse(
|
return ProductCardResponse(
|
||||||
product_id=p.product_id,
|
product_id=p.product_id,
|
||||||
category_id=p.category_id,
|
category_id=p.category_id,
|
||||||
slug=p.slug,
|
slug=p.slug,
|
||||||
|
|
@ -935,11 +1007,53 @@ def get_products(
|
||||||
compare_price=compare_price,
|
compare_price=compare_price,
|
||||||
discount_percent=discount_percent,
|
discount_percent=discount_percent,
|
||||||
rating=p.rating if hasattr(p, "rating") and p.rating is not None else 4.8,
|
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,
|
first_variant_id=first_var.variant_id if first_var else None,
|
||||||
badge=p.badge if hasattr(p, "badge") else None,
|
badge=p.badge if hasattr(p, "badge") else None,
|
||||||
brand_name=p.brand.name if p.brand 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
|
# Generate next cursor if there are more products
|
||||||
next_cursor = None
|
next_cursor = None
|
||||||
|
|
@ -955,7 +1069,7 @@ def get_products(
|
||||||
products=mapped_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
|
return response_payload
|
||||||
|
|
||||||
@router.get("/products/detail/{slug}", response_model=Dict[str, Any])
|
@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(
|
related = db.execute(
|
||||||
select(Product)
|
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)
|
.where(Product.category_id == product.category_id, Product.product_id != product.product_id)
|
||||||
.limit(4)
|
.limit(4)
|
||||||
).scalars().all()
|
).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
|
return response_payload
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,8 @@ from typing import List, Optional
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from app.core.database.db_session import get_db
|
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 (
|
from app.schemas.Crm import (
|
||||||
CrmTaskCreate, CrmTaskUpdate, CrmTaskResponse,
|
CrmTaskCreate, CrmTaskUpdate, CrmTaskResponse,
|
||||||
CrmCalendarEventCreate, CrmCalendarEventUpdate, CrmCalendarEventResponse
|
CrmCalendarEventCreate, CrmCalendarEventUpdate, CrmCalendarEventResponse
|
||||||
|
|
@ -20,7 +22,8 @@ def get_crm_tasks(
|
||||||
assignee_id: Optional[str] = Query(None),
|
assignee_id: Optional[str] = Query(None),
|
||||||
entity_type: Optional[str] = Query(None),
|
entity_type: Optional[str] = Query(None),
|
||||||
entity_id: 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(
|
return CrmTaskCalendarService.list_tasks(
|
||||||
db, location_id=location_id, status=status, assignee_id=assignee_id,
|
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)
|
@router.post("/tasks", response_model=CrmTaskResponse, status_code=status.HTTP_201_CREATED)
|
||||||
def create_crm_task(
|
def create_crm_task(
|
||||||
payload: CrmTaskCreate,
|
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)
|
return CrmTaskCalendarService.create_task(db, payload)
|
||||||
|
|
||||||
|
|
@ -38,7 +42,8 @@ def create_crm_task(
|
||||||
def update_crm_task(
|
def update_crm_task(
|
||||||
task_id: str,
|
task_id: str,
|
||||||
payload: CrmTaskUpdate,
|
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)
|
task = CrmTaskCalendarService.update_task(db, task_id, payload)
|
||||||
if not task:
|
if not task:
|
||||||
|
|
@ -48,7 +53,8 @@ def update_crm_task(
|
||||||
@router.delete("/tasks/{task_id}")
|
@router.delete("/tasks/{task_id}")
|
||||||
def delete_crm_task(
|
def delete_crm_task(
|
||||||
task_id: str,
|
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)
|
success = CrmTaskCalendarService.delete_task(db, task_id)
|
||||||
if not success:
|
if not success:
|
||||||
|
|
@ -62,7 +68,8 @@ def get_calendar_events(
|
||||||
location_id: Optional[str] = Query(None),
|
location_id: Optional[str] = Query(None),
|
||||||
start_from: Optional[datetime] = Query(None),
|
start_from: Optional[datetime] = Query(None),
|
||||||
end_until: 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(
|
return CrmTaskCalendarService.list_calendar_events(
|
||||||
db, location_id=location_id, start_from=start_from, end_until=end_until
|
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)
|
@router.post("/calendar", response_model=CrmCalendarEventResponse, status_code=status.HTTP_201_CREATED)
|
||||||
def create_calendar_event(
|
def create_calendar_event(
|
||||||
payload: CrmCalendarEventCreate,
|
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)
|
return CrmTaskCalendarService.create_calendar_event(db, payload)
|
||||||
|
|
||||||
|
|
@ -79,7 +87,8 @@ def create_calendar_event(
|
||||||
def update_calendar_event(
|
def update_calendar_event(
|
||||||
event_id: str,
|
event_id: str,
|
||||||
payload: CrmCalendarEventUpdate,
|
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)
|
event = CrmTaskCalendarService.update_calendar_event(db, event_id, payload)
|
||||||
if not event:
|
if not event:
|
||||||
|
|
@ -89,7 +98,8 @@ def update_calendar_event(
|
||||||
@router.delete("/calendar/{event_id}")
|
@router.delete("/calendar/{event_id}")
|
||||||
def delete_calendar_event(
|
def delete_calendar_event(
|
||||||
event_id: str,
|
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)
|
success = CrmTaskCalendarService.delete_calendar_event(db, event_id)
|
||||||
if not success:
|
if not success:
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,10 @@ from typing import Optional
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
import ulid
|
import ulid
|
||||||
import requests
|
import requests
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
import hmac
|
||||||
|
import hashlib
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from google.oauth2 import id_token
|
from google.oauth2 import id_token
|
||||||
from google.auth.transport import requests as google_requests
|
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"
|
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 = EcomCustomer(
|
||||||
customer_id=str(ulid.ULID()),
|
customer_id=str(ulid.ULID()),
|
||||||
email=payload.email,
|
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)
|
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)
|
@router.post("/google", response_model=TokenResponse)
|
||||||
@limiter.limit("10/minute")
|
@limiter.limit("10/minute")
|
||||||
def google_oauth_callback(
|
def google_oauth_callback(
|
||||||
|
|
@ -333,11 +372,11 @@ def google_oauth_callback(
|
||||||
Google OAuth 2.0 Authorization Code flow callback.
|
Google OAuth 2.0 Authorization Code flow callback.
|
||||||
Exchanges code for Google identity, checks policy, and creates session.
|
Exchanges code for Google identity, checks policy, and creates session.
|
||||||
"""
|
"""
|
||||||
# CSRF check: validate state token
|
# CSRF check: validate cryptographically signed state token
|
||||||
if not payload.state or len(payload.state) < 10:
|
if not payload.state or not verify_google_oauth_state(payload.state):
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_400_BAD_REQUEST,
|
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
|
# Validate custom header to verify request came from the client application
|
||||||
|
|
|
||||||
|
|
@ -100,6 +100,17 @@ def update_customer_profile(
|
||||||
"""
|
"""
|
||||||
Update profile details for the logged-in customer.
|
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.first_name = payload.first_name
|
||||||
customer.last_name = payload.last_name
|
customer.last_name = payload.last_name
|
||||||
customer.phone = payload.phone
|
customer.phone = payload.phone
|
||||||
|
|
|
||||||
|
|
@ -63,6 +63,7 @@ async def upload_file(
|
||||||
|
|
||||||
# 3b. Real Magic Byte Verification for Video files
|
# 3b. Real Magic Byte Verification for Video files
|
||||||
if ext in (".mp4", ".webm", ".mov", ".avi", ".mkv"):
|
if ext in (".mp4", ".webm", ".mov", ".avi", ".mkv"):
|
||||||
|
is_valid_video = False
|
||||||
header = file_bytes[:32]
|
header = file_bytes[:32]
|
||||||
if b"ftyp" in header or b"moov" in header: # MP4 / MOV
|
if b"ftyp" in header or b"moov" in header: # MP4 / MOV
|
||||||
is_valid_video = True
|
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
|
elif header.startswith(b"RIFF") and b"AVI " in file_bytes[:16]: # AVI
|
||||||
is_valid_video = True
|
is_valid_video = True
|
||||||
|
|
||||||
|
|
||||||
if not is_valid_video:
|
if not is_valid_video:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=400,
|
status_code=400,
|
||||||
detail=f"File '{file.filename}' failed video media inspection. Invalid video magic header."
|
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
|
# 4. Generate 26-char canonical ULID
|
||||||
file_id = str(ulid.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)
|
folder_path.mkdir(parents=True, exist_ok=True)
|
||||||
RAW_UPLOADS_DIR.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)
|
img.save(bio, format="WEBP", quality=webp_quality)
|
||||||
with open(webp_full, "wb") as f:
|
with open(webp_full, "wb") as f:
|
||||||
f.write(bio.getvalue())
|
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
|
# Helper for size variants
|
||||||
def save_variant(target_w: int, suffix: str) -> str:
|
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)
|
r_img.save(v_bio, format="WEBP", quality=80)
|
||||||
with open(var_full, "wb") as f:
|
with open(var_full, "wb") as f:
|
||||||
f.write(v_bio.getvalue())
|
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")
|
t_path = save_variant(300, "thumbnail")
|
||||||
m_path = save_variant(800, "medium")
|
m_path = save_variant(800, "medium")
|
||||||
|
|
@ -175,7 +202,7 @@ async def upload_file(
|
||||||
stored_full = folder_path / stored_name
|
stored_full = folder_path / stored_name
|
||||||
with open(stored_full, "wb") as f:
|
with open(stored_full, "wb") as f:
|
||||||
f.write(file_bytes)
|
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
|
# 6. Save metadata to DB
|
||||||
new_upload = FileUpload(
|
new_upload = FileUpload(
|
||||||
|
|
|
||||||
|
|
@ -6,12 +6,34 @@ from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from app.core.database.db_session import get_db
|
from app.core.database.db_session import get_db
|
||||||
from app.models.UserModel import User
|
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
|
from app.services.IntegrationService import IntegrationService
|
||||||
|
import urllib.parse
|
||||||
|
import ipaddress
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
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
|
# Pydantic Request Models
|
||||||
|
|
@ -152,6 +174,7 @@ def save_wati_credentials(
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
current_user: User = Depends(get_current_user)
|
current_user: User = Depends(get_current_user)
|
||||||
):
|
):
|
||||||
|
validate_outbound_url(payload.api_endpoint)
|
||||||
creds = IntegrationService.get_wati_credentials(db)
|
creds = IntegrationService.get_wati_credentials(db)
|
||||||
if creds.get("is_locked_by_config"):
|
if creds.get("is_locked_by_config"):
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
|
|
@ -166,6 +189,7 @@ def test_wati(
|
||||||
payload: WatiTestRequest,
|
payload: WatiTestRequest,
|
||||||
current_user: User = Depends(get_current_user)
|
current_user: User = Depends(get_current_user)
|
||||||
):
|
):
|
||||||
|
validate_outbound_url(payload.api_endpoint)
|
||||||
return IntegrationService.test_wati_connection(payload.api_endpoint, payload.api_token)
|
return IntegrationService.test_wati_connection(payload.api_endpoint, payload.api_token)
|
||||||
|
|
||||||
@router.get("/wati/templates")
|
@router.get("/wati/templates")
|
||||||
|
|
|
||||||
|
|
@ -51,28 +51,8 @@ UPLOAD_DIR = str(backend_root / "uploads" / "migrations")
|
||||||
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
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
|
# Endpoints
|
||||||
|
|
@ -381,19 +361,21 @@ async def upload_migration_file(
|
||||||
batch_type: str = Form("PRODUCTS"),
|
batch_type: str = Form("PRODUCTS"),
|
||||||
import_mode: str = Form("UPSERT"),
|
import_mode: str = Form("UPSERT"),
|
||||||
media_structure: str = Form("AUTO"),
|
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)
|
db: Session = Depends(get_db)
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
64KB Streamed Upload Endpoint. Streams dataset spreadsheet and/or ZIP archive directly to disk,
|
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.
|
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:
|
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).")
|
raise HTTPException(status_code=400, detail="Please upload a dataset file (.xlsx/.csv) or media ZIP archive (.zip).")
|
||||||
|
|
||||||
batch_id = str(uuid.uuid4())
|
batch_id = str(uuid.uuid4())
|
||||||
job_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)
|
# Save job configuration including media_structure (AUTO vs FLAT)
|
||||||
StorageManager.save_job_config(job_id, {"media_structure": media_structure, "import_mode": import_mode})
|
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(
|
batch = MigrationBatch(
|
||||||
id=batch_id,
|
id=batch_id,
|
||||||
batch_type=BatchTypeEnum(batch_type) if batch_type in BatchTypeEnum.__members__ else BatchTypeEnum.PRODUCTS,
|
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,
|
import_mode=ImportModeEnum(import_mode) if import_mode in ImportModeEnum.__members__ else ImportModeEnum.UPSERT,
|
||||||
status=BatchStatusEnum.PENDING
|
status=BatchStatusEnum.PENDING
|
||||||
)
|
)
|
||||||
|
|
@ -411,17 +393,35 @@ async def upload_migration_file(
|
||||||
file_format = "CSV"
|
file_format = "CSV"
|
||||||
|
|
||||||
if file:
|
if file:
|
||||||
file_name = file.filename
|
raw_name = os.path.basename(file.filename or "dataset.csv")
|
||||||
ext = os.path.splitext(file.filename)[1].lower().replace(".", "")
|
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()
|
file_format = ext.upper()
|
||||||
dataset_dest = os.path.join(job_dir, "dataset", file.filename)
|
|
||||||
await StorageManager.save_upload_stream_async(file, dataset_dest)
|
await StorageManager.save_upload_stream_async(file, dataset_dest)
|
||||||
|
|
||||||
if media_file:
|
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)
|
await StorageManager.save_upload_stream_async(media_file, archive_dest)
|
||||||
if not file_name:
|
if not file_name:
|
||||||
file_name = media_file.filename
|
file_name = clean_archive
|
||||||
file_format = "ZIP"
|
file_format = "ZIP"
|
||||||
|
|
||||||
job = MigrationJob(
|
job = MigrationJob(
|
||||||
|
|
@ -772,11 +772,58 @@ def get_job_telemetry(job_id: str, db: Session = Depends(get_db)):
|
||||||
"error_message": job.error_message
|
"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")
|
@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.
|
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():
|
def event_generator():
|
||||||
import json, time
|
import json, time
|
||||||
max_duration = 3600 # Max 1 hour stream safeguard
|
max_duration = 3600 # Max 1 hour stream safeguard
|
||||||
|
|
|
||||||
|
|
@ -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.api.v1.routers.CustomerProfileRouter import get_current_customer
|
||||||
from app.models.EcomCustomerModel import EcomCustomer
|
from app.models.EcomCustomerModel import EcomCustomer
|
||||||
from app.models.PaymentLedgerModel import PaymentLedger
|
from app.models.PaymentLedgerModel import PaymentLedger
|
||||||
|
from app.models.OrderModel import Order
|
||||||
from app.core.payment_orchestrator import payment_orchestrator
|
from app.core.payment_orchestrator import payment_orchestrator
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/v1/payment", tags=["Razorpay Payment Engine"])
|
router = APIRouter(prefix="/api/v1/payment", tags=["Razorpay Payment Engine"])
|
||||||
|
|
@ -56,7 +57,7 @@ def initiate_payment(
|
||||||
user_agent = request.headers.get("user-agent")
|
user_agent = request.headers.get("user-agent")
|
||||||
|
|
||||||
result = payment_orchestrator.initiate_payment(
|
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:
|
if "error" in result:
|
||||||
|
|
@ -78,7 +79,8 @@ def verify_payment(
|
||||||
order_id=payload.order_id,
|
order_id=payload.order_id,
|
||||||
rzp_order_id=payload.razorpay_order_id,
|
rzp_order_id=payload.razorpay_order_id,
|
||||||
rzp_payment_id=payload.razorpay_payment_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:
|
if "error" in result:
|
||||||
|
|
@ -96,7 +98,7 @@ def cancel_payment(
|
||||||
Cancel pending payment intent and release reserved stock.
|
Cancel pending payment intent and release reserved stock.
|
||||||
"""
|
"""
|
||||||
result = payment_orchestrator.cancel_payment(
|
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:
|
if "error" in result:
|
||||||
|
|
@ -113,6 +115,13 @@ def get_payment_status(
|
||||||
"""
|
"""
|
||||||
Returns latest payment ledger status for an order.
|
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 = (
|
entry = (
|
||||||
db.query(PaymentLedger)
|
db.query(PaymentLedger)
|
||||||
.filter(PaymentLedger.order_id == order_id)
|
.filter(PaymentLedger.order_id == order_id)
|
||||||
|
|
|
||||||
|
|
@ -2,18 +2,49 @@
|
||||||
@router PosSyncRouter (Backend/app/api/v1/routers/PosSyncRouter.py)
|
@router PosSyncRouter (Backend/app/api/v1/routers/PosSyncRouter.py)
|
||||||
Fully Dynamic Database-Driven POS Synchronization Gateway (Zero Hardcoded Data)
|
Fully Dynamic Database-Driven POS Synchronization Gateway (Zero Hardcoded Data)
|
||||||
"""
|
"""
|
||||||
|
import os
|
||||||
import ulid
|
import ulid
|
||||||
from datetime import datetime, date
|
from datetime import datetime, date
|
||||||
from typing import List, Optional
|
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 pydantic import BaseModel
|
||||||
from sqlalchemy import select, func, desc
|
from sqlalchemy import select, func, desc
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from app.core.database.db_session import get_db
|
from app.core.database.db_session import get_db
|
||||||
from app.models.POSTerminalModel import POSTerminal, POSTransactionLog
|
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"])
|
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):
|
class POSTransactionItem(BaseModel):
|
||||||
variant_id: str
|
variant_id: str
|
||||||
|
|
@ -44,7 +75,11 @@ class RegisterTerminalRequest(BaseModel):
|
||||||
|
|
||||||
|
|
||||||
@router.post("/terminals/register")
|
@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.
|
Dynamically registers or updates a POS terminal.
|
||||||
"""
|
"""
|
||||||
|
|
@ -81,7 +116,11 @@ def register_pos_terminal(payload: RegisterTerminalRequest, db: Session = Depend
|
||||||
|
|
||||||
|
|
||||||
@router.post("/sync")
|
@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.
|
Idempotent database-persisted synchronization gateway for offline POS transactions.
|
||||||
Dynamically registers unknown terminals upon sync submission.
|
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")
|
@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.
|
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,
|
terminal_id: Optional[str] = None,
|
||||||
status: Optional[str] = None,
|
status: Optional[str] = None,
|
||||||
limit: int = 50,
|
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.
|
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")
|
@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.
|
Clears pending sync locks or re-syncs state for a given POS terminal in MySQL database.
|
||||||
"""
|
"""
|
||||||
|
|
|
||||||
|
|
@ -9,10 +9,13 @@ from app.core.config.Config import settings
|
||||||
import app.models.db_base
|
import app.models.db_base
|
||||||
from app.models.PaymentLedgerModel import PaymentLedger
|
from app.models.PaymentLedgerModel import PaymentLedger
|
||||||
from app.models.OrderModel import Order
|
from app.models.OrderModel import Order
|
||||||
|
from app.core.permissions.RoleChecker import RoleChecker
|
||||||
|
from app.models.UserModel import User
|
||||||
|
|
||||||
router = APIRouter(
|
router = APIRouter(
|
||||||
prefix="/api/v1/payments/dashboard",
|
prefix="/api/v1/payments/dashboard",
|
||||||
tags=["Razorpay & Financial Dashboard"]
|
tags=["Razorpay & Financial Dashboard"],
|
||||||
|
dependencies=[Depends(RoleChecker(["Super Admin", "Admin", "Manager", "Accountant"]))]
|
||||||
)
|
)
|
||||||
|
|
||||||
@router.get("/metrics")
|
@router.get("/metrics")
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@ from sqlalchemy.orm import Session
|
||||||
from typing import List, Optional, Any
|
from typing import List, Optional, Any
|
||||||
|
|
||||||
from app.core.database.db_session import get_db
|
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.UserModel import User
|
||||||
from app.services.RefundService import RefundService
|
from app.services.RefundService import RefundService
|
||||||
from app.schemas.RefundSchema import (
|
from app.schemas.RefundSchema import (
|
||||||
|
|
@ -12,6 +12,8 @@ from app.schemas.RefundSchema import (
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/v1/refunds", tags=["Refund Management"])
|
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:
|
def get_refund_service(request: Request, db: Session = Depends(get_db)) -> RefundService:
|
||||||
tenant_id = getattr(request.state, "tenant_id", "tenant_default")
|
tenant_id = getattr(request.state, "tenant_id", "tenant_default")
|
||||||
return RefundService(db=db, tenant_id=tenant_id)
|
return RefundService(db=db, tenant_id=tenant_id)
|
||||||
|
|
@ -32,7 +34,7 @@ def approve_refund(
|
||||||
refund_id: str,
|
refund_id: str,
|
||||||
payload: RefundRequestApprove,
|
payload: RefundRequestApprove,
|
||||||
svc: RefundService = Depends(get_refund_service),
|
svc: RefundService = Depends(get_refund_service),
|
||||||
current_user: User = Depends(get_current_user)
|
current_user: User = Depends(RoleChecker(REFUND_ADMIN_ROLES))
|
||||||
) -> Any:
|
) -> Any:
|
||||||
"""Approves a refund request."""
|
"""Approves a refund request."""
|
||||||
return svc.approve_refund(refund_id=refund_id, data=payload, user_id=current_user.user_id)
|
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,
|
refund_id: str,
|
||||||
payload: RefundRequestReject,
|
payload: RefundRequestReject,
|
||||||
svc: RefundService = Depends(get_refund_service),
|
svc: RefundService = Depends(get_refund_service),
|
||||||
current_user: User = Depends(get_current_user)
|
current_user: User = Depends(RoleChecker(REFUND_ADMIN_ROLES))
|
||||||
) -> Any:
|
) -> Any:
|
||||||
"""Rejects a refund request."""
|
"""Rejects a refund request."""
|
||||||
return svc.reject_refund(refund_id=refund_id, data=payload, user_id=current_user.user_id)
|
return svc.reject_refund(refund_id=refund_id, data=payload, user_id=current_user.user_id)
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,7 @@ from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
||||||
from reportlab.lib import colors
|
from reportlab.lib import colors
|
||||||
|
|
||||||
from app.core.database.db_session import get_db
|
from app.core.database.db_session import get_db
|
||||||
|
from app.core.permissions.RoleChecker import RoleChecker
|
||||||
import app.models.db_base
|
import app.models.db_base
|
||||||
from app.models.OrderModel import Order
|
from app.models.OrderModel import Order
|
||||||
from app.models.ProductModel import Product, ProductVariant
|
from app.models.ProductModel import Product, ProductVariant
|
||||||
|
|
@ -128,6 +129,7 @@ def export_report(
|
||||||
category: str = Query(..., regex="^(sales|inventory|repairs|logistics|employee_activity)$"),
|
category: str = Query(..., regex="^(sales|inventory|repairs|logistics|employee_activity)$"),
|
||||||
format: str = Query("excel", regex="^(excel|csv|pdf)$"),
|
format: str = Query("excel", regex="^(excel|csv|pdf)$"),
|
||||||
days: int = Query(30, ge=1, le=365),
|
days: int = Query(30, ge=1, le=365),
|
||||||
|
current_user: User = Depends(RoleChecker(["Super Admin", "Admin", "Manager", "Accountant"])),
|
||||||
db: Session = Depends(get_db)
|
db: Session = Depends(get_db)
|
||||||
):
|
):
|
||||||
"""Universal multi-category report exporter supporting Excel (.xlsx), CSV, and PDF."""
|
"""Universal multi-category report exporter supporting Excel (.xlsx), CSV, and PDF."""
|
||||||
|
|
|
||||||
|
|
@ -93,6 +93,18 @@ def get_optional_actor(
|
||||||
pass
|
pass
|
||||||
return None
|
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"])
|
router = APIRouter(prefix="/api/v1/service", tags=["Repairs & Scheduling Services"])
|
||||||
|
|
||||||
job_service = ServiceJobService()
|
job_service = ServiceJobService()
|
||||||
|
|
@ -261,7 +273,7 @@ def reschedule_active_appointment(
|
||||||
@router.get("/jobs/{job_id}")
|
@router.get("/jobs/{job_id}")
|
||||||
def get_service_job_details(
|
def get_service_job_details(
|
||||||
job_id: str,
|
job_id: str,
|
||||||
actor: Optional[dict] = Depends(get_optional_actor),
|
actor: dict = Depends(get_required_actor),
|
||||||
db: Session = Depends(get_db)
|
db: Session = Depends(get_db)
|
||||||
):
|
):
|
||||||
"""Retrieve service job, current appointment, timeline events, active quotes, and media proof."""
|
"""Retrieve service job, current appointment, timeline events, active quotes, and media proof."""
|
||||||
|
|
@ -269,7 +281,13 @@ def get_service_job_details(
|
||||||
if not job:
|
if not job:
|
||||||
raise HTTPException(status_code=404, detail="Service job not found")
|
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")
|
raise HTTPException(status_code=403, detail="Not authorized to view this job")
|
||||||
|
|
||||||
from app.models.ServiceModel import ServiceAppointment, ServiceJobEvent
|
from app.models.ServiceModel import ServiceAppointment, ServiceJobEvent
|
||||||
|
|
@ -515,10 +533,24 @@ def attach_service_job_media(
|
||||||
def get_service_job_media(
|
def get_service_job_media(
|
||||||
job_id: str,
|
job_id: str,
|
||||||
category: Optional[str] = Query(None),
|
category: Optional[str] = Query(None),
|
||||||
|
actor: dict = Depends(get_required_actor),
|
||||||
db: Session = Depends(get_db)
|
db: Session = Depends(get_db)
|
||||||
):
|
):
|
||||||
"""Get media proof uploaded for a service job."""
|
"""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")
|
@router.post("/jobs/{job_id}/status")
|
||||||
def update_service_job_status_admin(
|
def update_service_job_status_admin(
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,16 @@
|
||||||
from fastapi import APIRouter, Depends, Query, HTTPException
|
from fastapi import APIRouter, Depends, Query, HTTPException, Request, Response, BackgroundTasks
|
||||||
from typing import Dict, Any, List
|
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.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(
|
router = APIRouter(
|
||||||
prefix="/api/v1/shipping",
|
prefix="/api/v1/shipping",
|
||||||
|
|
@ -15,7 +25,7 @@ def get_shipping_status():
|
||||||
"mode": settings.SHIPROCKET_MODE,
|
"mode": settings.SHIPROCKET_MODE,
|
||||||
"pickup_location": settings.SHIPROCKET_PICKUP_LOCATION,
|
"pickup_location": settings.SHIPROCKET_PICKUP_LOCATION,
|
||||||
"pickup_pincode": settings.SHIPROCKET_PICKUP_PIN,
|
"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")
|
@router.get("/dashboard")
|
||||||
|
|
@ -66,3 +76,269 @@ def calculate_shipping_rates(
|
||||||
"cod_available": True
|
"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"<tr><td>{item.product_name}</td><td style='text-align:center;'>{item.quantity}</td><td style='text-align:right;'>₹{float(item.unit_price):.2f}</td></tr>"
|
||||||
|
|
||||||
|
html = f"""<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Shipping Slip - {order.order_no}</title>
|
||||||
|
<style>
|
||||||
|
@page {{ size: 4in 6in; margin: 5mm; }}
|
||||||
|
@media print {{
|
||||||
|
body {{ margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; }}
|
||||||
|
.no-print {{ display: none; }}
|
||||||
|
}}
|
||||||
|
body {{
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||||
|
font-size: 11px;
|
||||||
|
color: #000;
|
||||||
|
background: #fff;
|
||||||
|
padding: 10px;
|
||||||
|
max-width: 380px;
|
||||||
|
margin: 0 auto;
|
||||||
|
}}
|
||||||
|
.box {{
|
||||||
|
border: 2px solid #000;
|
||||||
|
padding: 8px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}}
|
||||||
|
.header {{
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
border-bottom: 2px solid #000;
|
||||||
|
padding-bottom: 6px;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
}}
|
||||||
|
.title {{ font-size: 16px; font-weight: 900; letter-spacing: 0.5px; }}
|
||||||
|
.barcode-box {{
|
||||||
|
text-align: center;
|
||||||
|
padding: 6px 0;
|
||||||
|
border-bottom: 1px dashed #666;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
}}
|
||||||
|
.barcode {{
|
||||||
|
font-family: 'Courier New', monospace;
|
||||||
|
font-size: 20px;
|
||||||
|
font-weight: 900;
|
||||||
|
letter-spacing: 4px;
|
||||||
|
background: #f0f0f0;
|
||||||
|
padding: 4px 8px;
|
||||||
|
display: inline-block;
|
||||||
|
border: 1px solid #333;
|
||||||
|
}}
|
||||||
|
table {{ width: 100%; border-collapse: collapse; font-size: 10px; margin-top: 4px; }}
|
||||||
|
th, td {{ border: 1px solid #ccc; padding: 3px 5px; }}
|
||||||
|
th {{ background: #f5f5f5; text-align: left; }}
|
||||||
|
.tag {{
|
||||||
|
display: inline-block;
|
||||||
|
padding: 2px 6px;
|
||||||
|
font-weight: bold;
|
||||||
|
border: 1px solid #000;
|
||||||
|
border-radius: 3px;
|
||||||
|
}}
|
||||||
|
.btn {{
|
||||||
|
background: #0066cc;
|
||||||
|
color: #fff;
|
||||||
|
border: none;
|
||||||
|
padding: 8px 16px;
|
||||||
|
font-weight: bold;
|
||||||
|
cursor: pointer;
|
||||||
|
border-radius: 4px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
width: 100%;
|
||||||
|
}}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="no-print">
|
||||||
|
<button class="btn" onclick="window.print()">🖨️ Print Slip</button>
|
||||||
|
</div>
|
||||||
|
<div class="box">
|
||||||
|
<div class="header">
|
||||||
|
<div>
|
||||||
|
<div class="title">iFixKart Logistics</div>
|
||||||
|
<div style="font-size: 9px; color: #555;">Unified Tech & Commerce</div>
|
||||||
|
</div>
|
||||||
|
<div style="text-align: right;">
|
||||||
|
<span class="tag">{pay_mode}</span>
|
||||||
|
<div style="font-size: 9px; margin-top: 2px;">Wt: {weight:.2f} kg</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="barcode-box">
|
||||||
|
<div style="font-size: 9px; text-transform: uppercase; font-weight: bold; color: #555;">Courier: {courier}</div>
|
||||||
|
<div class="barcode">*{awb}*</div>
|
||||||
|
<div style="font-size: 10px; font-weight: bold; margin-top: 2px;">AWB: {awb}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="margin-bottom: 6px;">
|
||||||
|
<div style="font-weight: bold; font-size: 9px; text-transform: uppercase; color: #555;">Deliver To:</div>
|
||||||
|
<div style="font-weight: bold; font-size: 12px;">{cust_name}</div>
|
||||||
|
<div>{address_line}</div>
|
||||||
|
<div>{city}, {state} - <strong>{pincode}</strong></div>
|
||||||
|
<div>Ph: {cust_phone}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="border-top: 1px dashed #666; padding-top: 4px; margin-bottom: 6px;">
|
||||||
|
<div style="font-weight: bold; font-size: 9px; text-transform: uppercase; color: #555;">From / Return Address:</div>
|
||||||
|
<div><strong>iFixKart Warehouse</strong> ({settings.SHIPROCKET_PICKUP_LOCATION})</div>
|
||||||
|
<div>PIN: {settings.SHIPROCKET_PICKUP_PIN or '110001'}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="border-top: 1px solid #000; padding-top: 4px;">
|
||||||
|
<div style="display: flex; justify-content: space-between; font-weight: bold;">
|
||||||
|
<span>Order No: {order.order_no}</span>
|
||||||
|
<span>Total: ₹{float(order.final_amount):.2f}</span>
|
||||||
|
</div>
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr><th>Item</th><th style="text-align:center;">Qty</th><th style="text-align:right;">Amt</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{items_html}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
window.addEventListener('load', () => {{
|
||||||
|
// Auto trigger print when loaded directly
|
||||||
|
setTimeout(() => window.print(), 300);
|
||||||
|
}});
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>"""
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -10,12 +10,15 @@ from pydantic import BaseModel
|
||||||
|
|
||||||
from app.core.config.Config import settings
|
from app.core.config.Config import settings
|
||||||
from app.core.integrations.meta_graph_service import meta_service, UPLOAD_DIR
|
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__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
router = APIRouter(
|
router = APIRouter(
|
||||||
prefix="/api/v1/social/meta",
|
prefix="/api/v1/social/meta",
|
||||||
tags=["Social Media Management"]
|
tags=["Social Media Management"],
|
||||||
|
dependencies=[Depends(RoleChecker(["Super Admin", "Admin", "Marketing"]))]
|
||||||
)
|
)
|
||||||
|
|
||||||
class SocialPublishRequest(BaseModel):
|
class SocialPublishRequest(BaseModel):
|
||||||
|
|
|
||||||
|
|
@ -173,7 +173,7 @@ def create_cms_content(data: ContentCreatePayload, db: Session = Depends(get_db)
|
||||||
return content
|
return content
|
||||||
|
|
||||||
@router.post("/content/bulk-save")
|
@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 = []
|
saved_ids = []
|
||||||
for data in payload.items:
|
for data in payload.items:
|
||||||
existing = None
|
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)}
|
return {"message": "Bulk CMS content saved and storefront cache invalidated", "count": len(payload.items)}
|
||||||
|
|
||||||
@router.delete("/content/{content_id}")
|
@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()
|
item = db.query(StorefrontContent).filter(StorefrontContent.content_id == content_id).first()
|
||||||
if not item:
|
if not item:
|
||||||
raise HTTPException(status_code=404, detail="Content not found")
|
raise HTTPException(status_code=404, detail="Content not found")
|
||||||
|
|
@ -269,7 +273,10 @@ from typing import Any as _Any
|
||||||
|
|
||||||
|
|
||||||
@router.get("/cms/footer-info")
|
@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."""
|
"""Admin: Fetch current footer info."""
|
||||||
return StorefrontCmsService(db).get_footer_info()
|
return StorefrontCmsService(db).get_footer_info()
|
||||||
|
|
||||||
|
|
@ -285,7 +292,10 @@ def admin_update_footer_info(
|
||||||
|
|
||||||
|
|
||||||
@router.get("/cms/settings")
|
@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.)."""
|
"""Admin: Fetch all storefront settings (branding, advance_percent, etc.)."""
|
||||||
return StorefrontCmsService(db).get_settings()
|
return StorefrontCmsService(db).get_settings()
|
||||||
|
|
||||||
|
|
@ -301,7 +311,10 @@ def admin_update_settings(
|
||||||
|
|
||||||
|
|
||||||
@router.get("/cms/mega-menu")
|
@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)."""
|
"""Admin: Fetch all three mega menu configs (shop, deals, products)."""
|
||||||
return StorefrontCmsService(db).get_mega_menu()
|
return StorefrontCmsService(db).get_mega_menu()
|
||||||
|
|
||||||
|
|
@ -317,7 +330,10 @@ def admin_update_mega_menu(
|
||||||
|
|
||||||
|
|
||||||
@router.get("/cms/catalog-filters")
|
@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."""
|
"""Admin: Fetch catalog filter configuration."""
|
||||||
return StorefrontCmsService(db).get_catalog_filters()
|
return StorefrontCmsService(db).get_catalog_filters()
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ from pydantic import BaseModel
|
||||||
from app.core.database.db_session import get_db
|
from app.core.database.db_session import get_db
|
||||||
from app.services.StorefrontService import StorefrontService
|
from app.services.StorefrontService import StorefrontService
|
||||||
from app.services.CatalogSearchService import apply_product_search
|
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.CategoryModel import Category
|
||||||
from app.models.BrandModel import Brand
|
from app.models.BrandModel import Brand
|
||||||
from app.models.DeviceCatalogModel import ServiceType
|
from app.models.DeviceCatalogModel import ServiceType
|
||||||
|
|
@ -42,6 +42,7 @@ def live_search(
|
||||||
.options(
|
.options(
|
||||||
selectinload(Product.images),
|
selectinload(Product.images),
|
||||||
selectinload(Product.variants).selectinload(ProductVariant.images),
|
selectinload(Product.variants).selectinload(ProductVariant.images),
|
||||||
|
selectinload(Product.variants).selectinload(ProductVariant.attributes).selectinload(VariantAttribute.attribute_type),
|
||||||
)
|
)
|
||||||
.where(Product.status == "active")
|
.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)
|
stmt = apply_product_search(stmt, q).order_by(Product.created_at.desc()).limit(8)
|
||||||
products = db.execute(stmt).scalars().all()
|
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()}%"
|
term = f"%{q.strip()}%"
|
||||||
categories = db.execute(
|
categories = db.execute(
|
||||||
select(Category).where(Category.is_active == True, Category.name.ilike(term)).limit(5)
|
select(Category).where(Category.is_active == True, Category.name.ilike(term)).limit(5)
|
||||||
|
|
@ -64,7 +141,7 @@ def live_search(
|
||||||
).scalars().all()
|
).scalars().all()
|
||||||
|
|
||||||
payload = {
|
payload = {
|
||||||
"products": [ProductResponse.model_validate(p).model_dump(mode="json") for p in products],
|
"products": expanded_products,
|
||||||
"categories": [
|
"categories": [
|
||||||
{
|
{
|
||||||
"category_id": c.category_id,
|
"category_id": c.category_id,
|
||||||
|
|
|
||||||
|
|
@ -100,12 +100,23 @@ class CacheManager:
|
||||||
logger.error(f"Redis delete failed: {e}")
|
logger.error(f"Redis delete failed: {e}")
|
||||||
self.memory_cache.delete(key)
|
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:
|
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:
|
if self.redis_client:
|
||||||
try:
|
try:
|
||||||
keys = self.redis_client.keys(f"{prefix}*")
|
batch = []
|
||||||
if keys:
|
for key in self.redis_client.scan_iter(match=f"{prefix}*", count=100):
|
||||||
self.redis_client.delete(*keys)
|
batch.append(key)
|
||||||
|
if len(batch) >= 100:
|
||||||
|
self.redis_client.delete(*batch)
|
||||||
|
batch = []
|
||||||
|
if batch:
|
||||||
|
self.redis_client.delete(*batch)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Redis prefix invalidation failed: {e}")
|
logger.error(f"Redis prefix invalidation failed: {e}")
|
||||||
self.memory_cache.invalidate_prefix(prefix)
|
self.memory_cache.invalidate_prefix(prefix)
|
||||||
|
|
|
||||||
|
|
@ -10,18 +10,21 @@ core_url = settings.CORE_DATABASE_URL or settings.DATABASE_URL
|
||||||
crm_url = settings.CRM_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
|
commerce_url = settings.COMMERCE_DATABASE_URL or settings.DATABASE_URL
|
||||||
|
|
||||||
# Pool sizing is environment-configurable so the simulation backend can raise
|
# Calibrated connection pool limits:
|
||||||
# it (DB_POOL_SIZE / DB_MAX_OVERFLOW in .env.sim); production keeps defaults.
|
# 4 workers * 3 engines * (10 pool + 10 overflow) = 240 max connections
|
||||||
_pool_size = int(os.getenv("DB_POOL_SIZE", "5"))
|
# (safely under MySQL max_connections = 500)
|
||||||
|
_pool_size = int(os.getenv("DB_POOL_SIZE", "10"))
|
||||||
_max_overflow = int(os.getenv("DB_MAX_OVERFLOW", "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(
|
engine_core = create_engine(
|
||||||
core_url,
|
core_url,
|
||||||
future=True,
|
future=True,
|
||||||
pool_pre_ping=True,
|
pool_pre_ping=True,
|
||||||
pool_size=_pool_size,
|
pool_size=_pool_size,
|
||||||
max_overflow=_max_overflow,
|
max_overflow=_max_overflow,
|
||||||
|
pool_recycle=_pool_recycle,
|
||||||
connect_args={"init_command": "SET time_zone='+00:00'"}
|
connect_args={"init_command": "SET time_zone='+00:00'"}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -31,6 +34,7 @@ engine_crm = create_engine(
|
||||||
pool_pre_ping=True,
|
pool_pre_ping=True,
|
||||||
pool_size=_pool_size,
|
pool_size=_pool_size,
|
||||||
max_overflow=_max_overflow,
|
max_overflow=_max_overflow,
|
||||||
|
pool_recycle=_pool_recycle,
|
||||||
connect_args={"init_command": "SET time_zone='+00:00'"}
|
connect_args={"init_command": "SET time_zone='+00:00'"}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -40,6 +44,7 @@ engine_commerce = create_engine(
|
||||||
pool_pre_ping=True,
|
pool_pre_ping=True,
|
||||||
pool_size=_pool_size,
|
pool_size=_pool_size,
|
||||||
max_overflow=_max_overflow,
|
max_overflow=_max_overflow,
|
||||||
|
pool_recycle=_pool_recycle,
|
||||||
connect_args={"init_command": "SET time_zone='+00:00'"}
|
connect_args={"init_command": "SET time_zone='+00:00'"}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,43 @@
|
||||||
|
import os
|
||||||
from slowapi import Limiter
|
from slowapi import Limiter
|
||||||
from slowapi.util import get_remote_address
|
from starlette.requests import Request
|
||||||
from app.core.config.Config import settings
|
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(
|
limiter = Limiter(
|
||||||
key_func=get_remote_address,
|
key_func=get_real_client_ip,
|
||||||
default_limits=["120/minute"]
|
default_limits=["120/minute"],
|
||||||
|
storage_uri=_storage_uri
|
||||||
)
|
)
|
||||||
|
|
||||||
# A local swarm originates from one IP. Rate limits are a production protection,
|
# A local swarm originates from one IP. Rate limits are a production protection,
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,4 @@
|
||||||
|
import time
|
||||||
from fastapi import Request
|
from fastapi import Request
|
||||||
from starlette.middleware.base import BaseHTTPMiddleware
|
from starlette.middleware.base import BaseHTTPMiddleware
|
||||||
from starlette.responses import JSONResponse
|
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
|
from app.core.config.Config import settings, load_public_key_bytes
|
||||||
|
|
||||||
MASTER_ADMIN_EMAIL = "adithiyan.elan@gmail.com"
|
MASTER_ADMIN_EMAIL = "adithiyan.elan@gmail.com"
|
||||||
|
_cached_global_disable = False
|
||||||
|
_last_check_time = 0.0
|
||||||
|
_CACHE_TTL_SECONDS = 5.0
|
||||||
|
|
||||||
class KillSwitchMiddleware(BaseHTTPMiddleware):
|
class KillSwitchMiddleware(BaseHTTPMiddleware):
|
||||||
async def dispatch(self, request: Request, call_next):
|
async def dispatch(self, request: Request, call_next):
|
||||||
|
|
@ -15,26 +19,25 @@ class KillSwitchMiddleware(BaseHTTPMiddleware):
|
||||||
if request.url.path in ["/docs", "/redoc", "/openapi.json"]:
|
if request.url.path in ["/docs", "/redoc", "/openapi.json"]:
|
||||||
return await call_next(request)
|
return await call_next(request)
|
||||||
|
|
||||||
# Open db session safely
|
global _cached_global_disable, _last_check_time
|
||||||
db: Session = SessionLocal()
|
now = time.time()
|
||||||
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()
|
|
||||||
|
|
||||||
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)
|
return await call_next(request)
|
||||||
|
|
||||||
# Bypass check for MASTER ADMIN
|
# Bypass check for MASTER ADMIN
|
||||||
|
|
|
||||||
|
|
@ -44,15 +44,15 @@ class RequestSizeLimitMiddleware(BaseHTTPMiddleware):
|
||||||
self.large_paths = large_paths
|
self.large_paths = large_paths
|
||||||
|
|
||||||
async def dispatch(self, request: Request, call_next):
|
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")
|
content_length = request.headers.get("content-length")
|
||||||
if content_length:
|
if content_length:
|
||||||
try:
|
try:
|
||||||
length = int(content_length)
|
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:
|
if length > limit:
|
||||||
max_mb = limit // (1024 * 1024)
|
max_mb = limit // (1024 * 1024)
|
||||||
return JSONResponse(
|
return JSONResponse(
|
||||||
|
|
@ -62,5 +62,34 @@ class RequestSizeLimitMiddleware(BaseHTTPMiddleware):
|
||||||
except ValueError:
|
except ValueError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# Also limit reading chunks if chunked transfer encoding is used
|
# 2. Chunked Transfer-Encoding Streaming Guard
|
||||||
return await call_next(request)
|
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
|
||||||
|
|
|
||||||
|
|
@ -19,10 +19,10 @@ logger = logging.getLogger("app.payment_orchestrator")
|
||||||
|
|
||||||
class PaymentOrchestrator:
|
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.
|
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:
|
if settings.SIMULATION_MODE:
|
||||||
return {"error": "Razorpay is disabled in simulation; use /api/v1/payment/simulate", "status_code": 400}
|
return {"error": "Razorpay is disabled in simulation; use /api/v1/payment/simulate", "status_code": 400}
|
||||||
|
|
@ -30,6 +30,9 @@ class PaymentOrchestrator:
|
||||||
if not order:
|
if not order:
|
||||||
return {"error": "Order not found", "status_code": 404}
|
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":
|
if order.payment_status == "PAYMENT_CAPTURED":
|
||||||
return {"error": "Order is already paid", "status_code": 400}
|
return {"error": "Order is already paid", "status_code": 400}
|
||||||
|
|
||||||
|
|
@ -95,7 +98,7 @@ class PaymentOrchestrator:
|
||||||
"status_code": 200
|
"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.
|
Cancels pending order payment and releases reserved stock.
|
||||||
"""
|
"""
|
||||||
|
|
@ -103,6 +106,9 @@ class PaymentOrchestrator:
|
||||||
if not order:
|
if not order:
|
||||||
return {"error": "Order not found", "status_code": 404}
|
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)
|
cancelled_order = OrderService.cancel_ecommerce_order(db, order, reason=reason)
|
||||||
return {
|
return {
|
||||||
"status": "SUCCESS",
|
"status": "SUCCESS",
|
||||||
|
|
@ -118,7 +124,8 @@ class PaymentOrchestrator:
|
||||||
order_id: str,
|
order_id: str,
|
||||||
rzp_order_id: str,
|
rzp_order_id: str,
|
||||||
rzp_payment_id: str,
|
rzp_payment_id: str,
|
||||||
rzp_signature: str
|
rzp_signature: str,
|
||||||
|
customer_id: Optional[str] = None
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
Verifies client-side signature + executes secondary server-side fetch from Razorpay API.
|
Verifies client-side signature + executes secondary server-side fetch from Razorpay API.
|
||||||
|
|
@ -129,6 +136,9 @@ class PaymentOrchestrator:
|
||||||
if not order:
|
if not order:
|
||||||
return {"error": "Order not found", "status_code": 404}
|
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":
|
if order.payment_status == "PAYMENT_CAPTURED":
|
||||||
return {"status": "SUCCESS", "message": "Payment already captured"}
|
return {"status": "SUCCESS", "message": "Payment already captured"}
|
||||||
|
|
||||||
|
|
@ -221,15 +231,30 @@ class PaymentOrchestrator:
|
||||||
rzp_payment_id = entity.get("id")
|
rzp_payment_id = entity.get("id")
|
||||||
|
|
||||||
if rzp_order_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":
|
if payment_entry and payment_entry.status != "CAPTURED":
|
||||||
order = db.query(Order).filter(Order.order_id == payment_entry.order_id).first()
|
order = (
|
||||||
if 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.transaction_ref = rzp_payment_id
|
||||||
payment_entry.status = "CAPTURED"
|
payment_entry.status = "CAPTURED"
|
||||||
payment_entry.raw_response_json = json.dumps(entity)
|
payment_entry.raw_response_json = json.dumps(entity)
|
||||||
OrderService.confirm_ecommerce_payment(db, order, payment_method="RAZORPAY")
|
OrderService.confirm_ecommerce_payment(db, order, payment_method="RAZORPAY")
|
||||||
receipt.processing_result = "CAPTURED_CONFIRMED"
|
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)
|
receipt.processed_at = datetime.now(timezone.utc)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|
|
||||||
|
|
@ -60,7 +60,9 @@ def get_current_user(
|
||||||
|
|
||||||
|
|
||||||
if not token:
|
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:
|
if not token:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
|
|
|
||||||
176
app/main.py
176
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.security_middleware import SecurityHeadersMiddleware, RequestSizeLimitMiddleware
|
||||||
from app.core.middleware.kill_switch_middleware import KillSwitchMiddleware
|
from app.core.middleware.kill_switch_middleware import KillSwitchMiddleware
|
||||||
from app.core.Exception import AppException
|
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(
|
app = FastAPI(
|
||||||
title=settings.PROJECT_NAME,
|
title=settings.PROJECT_NAME,
|
||||||
description="iFixKart Enterprise ERP/CRM/E-commerce Platform Backend Core Foundation",
|
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 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")
|
uploads_path = str(Path(__file__).resolve().parents[1] / "uploads")
|
||||||
os.makedirs(uploads_path, exist_ok=True)
|
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))
|
local_file = os.path.abspath(os.path.join(uploads_path, file_path))
|
||||||
if os.path.isfile(local_file) and local_file.startswith(uploads_path):
|
if os.path.isfile(local_file) and local_file.startswith(uploads_path):
|
||||||
return FileResponse(local_file)
|
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(
|
app.add_middleware(
|
||||||
CORSMiddleware,
|
CORSMiddleware,
|
||||||
allow_origins=[
|
allow_origins=ALLOWED_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_credentials=True,
|
allow_credentials=True,
|
||||||
allow_methods=["*"],
|
allow_methods=["*"],
|
||||||
allow_headers=["*"],
|
allow_headers=["*"],
|
||||||
|
|
@ -205,6 +237,14 @@ app.add_middleware(RequestTraceMiddleware)
|
||||||
from fastapi.exceptions import RequestValidationError
|
from fastapi.exceptions import RequestValidationError
|
||||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
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
|
# 3. Register Global Handlers for Custom AppException with CORS safety
|
||||||
@app.exception_handler(AppException)
|
@app.exception_handler(AppException)
|
||||||
def app_exception_handler(request: Request, exc: 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,
|
status_code=exc.status_code,
|
||||||
content={"detail": exc.detail, "request_id": req_id}
|
content={"detail": exc.detail, "request_id": req_id}
|
||||||
)
|
)
|
||||||
# Explicitly append CORS headers so browser doesn't block cross-origin error responses
|
append_cors_headers(response, request)
|
||||||
origin = request.headers.get("origin")
|
|
||||||
if origin:
|
|
||||||
response.headers["Access-Control-Allow-Origin"] = origin
|
|
||||||
response.headers["Access-Control-Allow-Credentials"] = "true"
|
|
||||||
return response
|
return response
|
||||||
|
|
||||||
@app.exception_handler(StarletteHTTPException)
|
@app.exception_handler(StarletteHTTPException)
|
||||||
|
|
@ -226,10 +262,7 @@ def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
||||||
status_code=exc.status_code,
|
status_code=exc.status_code,
|
||||||
content={"detail": exc.detail}
|
content={"detail": exc.detail}
|
||||||
)
|
)
|
||||||
origin = request.headers.get("origin")
|
append_cors_headers(response, request)
|
||||||
if origin:
|
|
||||||
response.headers["Access-Control-Allow-Origin"] = origin
|
|
||||||
response.headers["Access-Control-Allow-Credentials"] = "true"
|
|
||||||
return response
|
return response
|
||||||
|
|
||||||
from fastapi.encoders import jsonable_encoder
|
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,
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||||
content={"detail": jsonable_encoder(exc.errors())}
|
content={"detail": jsonable_encoder(exc.errors())}
|
||||||
)
|
)
|
||||||
origin = request.headers.get("origin")
|
append_cors_headers(response, request)
|
||||||
if origin:
|
return response
|
||||||
response.headers["Access-Control-Allow-Origin"] = origin
|
|
||||||
response.headers["Access-Control-Allow-Credentials"] = "true"
|
@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
|
return response
|
||||||
|
|
||||||
@app.exception_handler(Exception)
|
@app.exception_handler(Exception)
|
||||||
def generic_exception_handler(request: Request, exc: Exception):
|
def generic_exception_handler(request: Request, exc: Exception):
|
||||||
import traceback
|
import traceback
|
||||||
traceback.print_exc()
|
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(
|
response = JSONResponse(
|
||||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
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")
|
append_cors_headers(response, request)
|
||||||
if origin:
|
|
||||||
response.headers["Access-Control-Allow-Origin"] = origin
|
|
||||||
response.headers["Access-Control-Allow-Credentials"] = "true"
|
|
||||||
return response
|
return response
|
||||||
|
|
||||||
# 4. Register Router Endpoints
|
# 4. Register Router Endpoints
|
||||||
|
|
@ -399,32 +447,38 @@ def startup_event():
|
||||||
|
|
||||||
time.sleep(300) # Check every 5 minutes
|
time.sleep(300) # Check every 5 minutes
|
||||||
|
|
||||||
worker_thread = threading.Thread(target=run_media_background_worker, daemon=True, name="MediaWorkerThread")
|
# Centralized background worker thread gating:
|
||||||
worker_thread.start()
|
# In multi-worker Gunicorn setups, only the designated worker or sidecar process (ENABLE_MIGRATION_WORKER=1)
|
||||||
print("Media Async Garbage Collector & Reconciliation Worker thread started.")
|
# 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
|
# Start Persistent Migration Worker Background Thread
|
||||||
from app.services.migration_engine.migration_worker import MigrationWorker
|
from app.services.migration_engine.migration_worker import MigrationWorker
|
||||||
|
|
||||||
def run_migration_background_worker():
|
def run_migration_background_worker():
|
||||||
worker = MigrationWorker()
|
worker = MigrationWorker()
|
||||||
print(f"[{worker.worker_id}] Migration Worker daemon initialized and listening for queued jobs...")
|
print(f"[{worker.worker_id}] Migration Worker daemon initialized and listening for queued jobs...")
|
||||||
while True:
|
while True:
|
||||||
try:
|
|
||||||
db = SessionLocal()
|
|
||||||
try:
|
try:
|
||||||
res = worker.claim_next_job(db)
|
db = SessionLocal()
|
||||||
if res:
|
try:
|
||||||
job_id, lease_version = res
|
res = worker.claim_next_job(db)
|
||||||
worker.process_job(job_id, lease_version)
|
if res:
|
||||||
finally:
|
job_id, lease_version = res
|
||||||
db.close()
|
worker.process_job(job_id, lease_version)
|
||||||
except Exception as err:
|
finally:
|
||||||
print(f"Error in Migration Worker loop: {err}")
|
db.close()
|
||||||
time.sleep(2)
|
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 = threading.Thread(target=run_migration_background_worker, daemon=True, name="MigrationWorkerThread")
|
||||||
mig_thread.start()
|
mig_thread.start()
|
||||||
print("Persistent Migration Worker background thread started.")
|
print("Persistent Migration Worker background thread started.")
|
||||||
|
else:
|
||||||
|
print("Background poller threads skipped on this worker (ENABLE_MIGRATION_WORKER != 1).")
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -30,6 +30,11 @@ class Order(Base):
|
||||||
billing_address_json = Column(Text, nullable=True)
|
billing_address_json = Column(Text, nullable=True)
|
||||||
tracking_number = Column(String(100), nullable=True)
|
tracking_number = Column(String(100), nullable=True)
|
||||||
courier_name = 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)
|
created_at = Column(DateTime, server_default=func.now(), index=True)
|
||||||
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())
|
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())
|
||||||
|
|
|
||||||
|
|
@ -9,8 +9,19 @@ class SessionRepository(BaseRepository[UserSession]):
|
||||||
super().__init__(UserSession)
|
super().__init__(UserSession)
|
||||||
|
|
||||||
def get_by_refresh_token(self, db: Session, token: str) -> Optional[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))
|
from app.utils.Hash_util import hash_token
|
||||||
return db.execute(stmt).scalar_one_or_none()
|
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]:
|
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))
|
stmt = select(UserSession).where(UserSession.user_id == user_id, UserSession.is_active.is_(True))
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ class LoginSchema(BaseModel):
|
||||||
|
|
||||||
class TokenResponseSchema(BaseModel):
|
class TokenResponseSchema(BaseModel):
|
||||||
access_token: str
|
access_token: str
|
||||||
refresh_token: str
|
refresh_token: Optional[str] = None
|
||||||
token_type: str = "bearer"
|
token_type: str = "bearer"
|
||||||
|
|
||||||
class PasswordResetRequest(BaseModel):
|
class PasswordResetRequest(BaseModel):
|
||||||
|
|
|
||||||
|
|
@ -530,6 +530,18 @@ class ProductVariantResponse(BaseModel):
|
||||||
available_stock: int = 0
|
available_stock: int = 0
|
||||||
attributes: List[VariantAttributeResponse] = []
|
attributes: List[VariantAttributeResponse] = []
|
||||||
images: List[VariantImageResponse] = []
|
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:
|
class Config:
|
||||||
from_attributes = True
|
from_attributes = True
|
||||||
|
|
@ -604,22 +616,47 @@ class ProductResponse(BaseModel):
|
||||||
images: List[ProductImageResponse] = []
|
images: List[ProductImageResponse] = []
|
||||||
variants: List[ProductVariantResponse] = []
|
variants: List[ProductVariantResponse] = []
|
||||||
locations: List[ProductLocationResponse] = []
|
locations: List[ProductLocationResponse] = []
|
||||||
|
thumbnail_url: Optional[str] = None
|
||||||
|
|
||||||
@model_validator(mode="after")
|
@model_validator(mode="after")
|
||||||
def populate_images(self) -> 'ProductResponse':
|
def populate_images(self) -> 'ProductResponse':
|
||||||
|
# 1. If images is empty, search ALL variants for images
|
||||||
if not self.images and self.variants:
|
if not self.images and self.variants:
|
||||||
first_var = self.variants[0]
|
for v in self.variants:
|
||||||
if first_var.images:
|
if v.images:
|
||||||
self.images = [
|
self.images = [
|
||||||
ProductImageResponse(
|
ProductImageResponse(
|
||||||
image_id=vi.image_id,
|
image_id=vi.image_id,
|
||||||
product_id=self.product_id,
|
product_id=self.product_id,
|
||||||
image_url=vi.image_url,
|
image_url=vi.image_url,
|
||||||
alt_text=self.name,
|
alt_text=self.name,
|
||||||
sort_order=vi.sort_order,
|
sort_order=vi.sort_order,
|
||||||
is_banner=vi.is_primary
|
is_banner=getattr(vi, 'is_primary', False)
|
||||||
) for vi in first_var.images
|
) 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
|
return self
|
||||||
|
|
||||||
class Config:
|
class Config:
|
||||||
|
|
@ -639,6 +676,10 @@ class ProductCardResponse(BaseModel):
|
||||||
first_variant_id: Optional[str] = None
|
first_variant_id: Optional[str] = None
|
||||||
badge: Optional[str] = None
|
badge: Optional[str] = None
|
||||||
brand_name: 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:
|
class Config:
|
||||||
from_attributes = True
|
from_attributes = True
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel, Field
|
||||||
from typing import Optional, List
|
from typing import Optional, List
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
|
|
@ -21,7 +21,7 @@ class RefundRequestCreate(BaseModel):
|
||||||
entity_type: str # SALES or SERVICE
|
entity_type: str # SALES or SERVICE
|
||||||
entity_id: str
|
entity_id: str
|
||||||
location_id: str
|
location_id: str
|
||||||
amount: float
|
amount: float = Field(..., gt=0, description="Refund amount must be positive")
|
||||||
payment_method: str # CASH or ONLINE
|
payment_method: str # CASH or ONLINE
|
||||||
reason: Optional[str] = None
|
reason: Optional[str] = None
|
||||||
part_number_verification: Optional[str] = None # Mandatory if SERVICE
|
part_number_verification: Optional[str] = None # Mandatory if SERVICE
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,21 @@ class CrmService:
|
||||||
|
|
||||||
# --- CUSTOMER MANAGEMENT ---
|
# --- CUSTOMER MANAGEMENT ---
|
||||||
def create_customer(self, data: CrmCustomerCreate) -> CrmCustomer:
|
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 = CrmCustomer(
|
||||||
customer_id=str(ulid.ULID()),
|
customer_id=str(ulid.ULID()),
|
||||||
tenant_id=self.tenant_id,
|
tenant_id=self.tenant_id,
|
||||||
|
|
|
||||||
|
|
@ -124,6 +124,12 @@ class RefundService:
|
||||||
if not refund or refund.status != RefundStatus.PENDING:
|
if not refund or refund.status != RefundStatus.PENDING:
|
||||||
raise HTTPException(status_code=400, detail="Refund not found or not in PENDING state")
|
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_by = user_id
|
||||||
refund.approved_at = datetime.now(timezone.utc)
|
refund.approved_at = datetime.now(timezone.utc)
|
||||||
if data.admin_notes:
|
if data.admin_notes:
|
||||||
|
|
|
||||||
261
app/services/ShiprocketService.py
Normal file
261
app/services/ShiprocketService.py
Normal file
|
|
@ -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()
|
||||||
|
|
||||||
|
|
@ -30,6 +30,7 @@ from app.schemas.StorefrontCmsSchema import (
|
||||||
ReviewModerationResponse,
|
ReviewModerationResponse,
|
||||||
ReviewApprovalPayload,
|
ReviewApprovalPayload,
|
||||||
)
|
)
|
||||||
|
from app.core.database.cache_manager import cache
|
||||||
|
|
||||||
|
|
||||||
class StorefrontCmsService:
|
class StorefrontCmsService:
|
||||||
|
|
@ -46,18 +47,25 @@ class StorefrontCmsService:
|
||||||
# FOOTER INFO
|
# FOOTER INFO
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
def get_footer_info(self) -> FooterInfoResponse:
|
def get_footer_info(self) -> FooterInfoResponse:
|
||||||
|
cached = cache.get("cms:footer_info")
|
||||||
|
if cached:
|
||||||
|
return FooterInfoResponse(**cached)
|
||||||
|
|
||||||
row = self.db.get(StorefrontFooterInfo, "default")
|
row = self.db.get(StorefrontFooterInfo, "default")
|
||||||
if not row:
|
if not row:
|
||||||
return FooterInfoResponse()
|
res = FooterInfoResponse()
|
||||||
return FooterInfoResponse(
|
else:
|
||||||
phone=row.phone,
|
res = FooterInfoResponse(
|
||||||
email=row.email,
|
phone=row.phone,
|
||||||
address=row.address,
|
email=row.email,
|
||||||
copyright=row.copyright,
|
address=row.address,
|
||||||
social_links=self._safe_list(row.social_links),
|
copyright=row.copyright,
|
||||||
columns=self._safe_list(row.columns),
|
social_links=self._safe_list(row.social_links),
|
||||||
payment_methods=self._safe_list(row.payment_methods),
|
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:
|
def update_footer_info(self, payload: FooterInfoUpdate, updated_by: str = "admin") -> FooterInfoResponse:
|
||||||
row = self.db.get(StorefrontFooterInfo, "default")
|
row = self.db.get(StorefrontFooterInfo, "default")
|
||||||
|
|
@ -82,6 +90,7 @@ class StorefrontCmsService:
|
||||||
|
|
||||||
self.db.commit()
|
self.db.commit()
|
||||||
self.db.refresh(row)
|
self.db.refresh(row)
|
||||||
|
cache.invalidate_prefix("cms:footer_info")
|
||||||
return self.get_footer_info()
|
return self.get_footer_info()
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
|
|
@ -94,6 +103,10 @@ class StorefrontCmsService:
|
||||||
]
|
]
|
||||||
|
|
||||||
def get_settings(self) -> Dict[str, Any]:
|
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()
|
rows = self.db.execute(select(StorefrontSettings)).scalars().all()
|
||||||
result: Dict[str, Any] = {
|
result: Dict[str, Any] = {
|
||||||
# Provide defaults for required CMS keys
|
# Provide defaults for required CMS keys
|
||||||
|
|
@ -110,6 +123,7 @@ class StorefrontCmsService:
|
||||||
}
|
}
|
||||||
for r in rows:
|
for r in rows:
|
||||||
result[r.key] = r.value
|
result[r.key] = r.value
|
||||||
|
cache.set("cms:settings", result, ttl_seconds=cache.TTL_SETTINGS)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
def update_settings(self, payload: StorefrontSettingsUpdate, updated_by: str = "admin") -> Dict[str, Any]:
|
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)
|
row = StorefrontSettings(key=key, value=value, updated_by=updated_by)
|
||||||
self.db.add(row)
|
self.db.add(row)
|
||||||
self.db.commit()
|
self.db.commit()
|
||||||
|
cache.invalidate_prefix("cms:settings")
|
||||||
|
cache.invalidate_prefix("settings:")
|
||||||
return self.get_settings()
|
return self.get_settings()
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
# MEGA MENU
|
# MEGA MENU
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
def get_mega_menu(self, nav_key: Optional[str] = None) -> Any:
|
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:
|
if nav_key:
|
||||||
row = self.db.get(StorefrontMegaMenu, nav_key)
|
row = self.db.get(StorefrontMegaMenu, nav_key)
|
||||||
if not row:
|
if not row:
|
||||||
return MegaMenuResponse(nav_key=nav_key)
|
res = MegaMenuResponse(nav_key=nav_key)
|
||||||
return MegaMenuResponse(
|
else:
|
||||||
nav_key=row.nav_key,
|
res = MegaMenuResponse(
|
||||||
groups=self._safe_list(row.groups),
|
nav_key=row.nav_key,
|
||||||
promo=row.promo,
|
groups=self._safe_list(row.groups),
|
||||||
featured_category_ids=self._safe_list(row.featured_category_ids),
|
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
|
# Return all three menus in one payload
|
||||||
keys = ["shop", "deals", "products"]
|
keys = ["shop", "deals", "products"]
|
||||||
|
|
@ -157,7 +187,9 @@ class StorefrontCmsService:
|
||||||
featured_category_ids=self._safe_list(r.featured_category_ids),
|
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:
|
def update_mega_menu(self, payload: MegaMenuUpdate, updated_by: str = "admin") -> MegaMenuResponse:
|
||||||
row = self.db.get(StorefrontMegaMenu, payload.nav_key)
|
row = self.db.get(StorefrontMegaMenu, payload.nav_key)
|
||||||
|
|
@ -174,6 +206,7 @@ class StorefrontCmsService:
|
||||||
|
|
||||||
self.db.commit()
|
self.db.commit()
|
||||||
self.db.refresh(row)
|
self.db.refresh(row)
|
||||||
|
cache.invalidate_prefix("cms:mega_menu")
|
||||||
return self.get_mega_menu(payload.nav_key)
|
return self.get_mega_menu(payload.nav_key)
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
|
|
@ -193,16 +226,23 @@ class StorefrontCmsService:
|
||||||
]
|
]
|
||||||
|
|
||||||
def get_catalog_filters(self) -> CatalogFiltersResponse:
|
def get_catalog_filters(self) -> CatalogFiltersResponse:
|
||||||
|
cached = cache.get("cms:catalog_filters")
|
||||||
|
if cached:
|
||||||
|
return CatalogFiltersResponse(**cached)
|
||||||
|
|
||||||
row = self.db.get(StorefrontCatalogFilters, "default")
|
row = self.db.get(StorefrontCatalogFilters, "default")
|
||||||
if not row:
|
if not row:
|
||||||
return CatalogFiltersResponse(
|
res = CatalogFiltersResponse(
|
||||||
highlights=self._DEFAULT_HIGHLIGHTS,
|
highlights=self._DEFAULT_HIGHLIGHTS,
|
||||||
price_ranges=self._DEFAULT_PRICE_RANGES,
|
price_ranges=self._DEFAULT_PRICE_RANGES,
|
||||||
)
|
)
|
||||||
return CatalogFiltersResponse(
|
else:
|
||||||
highlights=self._safe_list(row.highlights) or self._DEFAULT_HIGHLIGHTS,
|
res = CatalogFiltersResponse(
|
||||||
price_ranges=self._safe_list(row.price_ranges) or self._DEFAULT_PRICE_RANGES,
|
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:
|
def update_catalog_filters(self, payload: CatalogFiltersUpdate) -> CatalogFiltersResponse:
|
||||||
row = self.db.get(StorefrontCatalogFilters, "default")
|
row = self.db.get(StorefrontCatalogFilters, "default")
|
||||||
|
|
@ -217,6 +257,7 @@ class StorefrontCmsService:
|
||||||
|
|
||||||
self.db.commit()
|
self.db.commit()
|
||||||
self.db.refresh(row)
|
self.db.refresh(row)
|
||||||
|
cache.invalidate_prefix("cms:catalog_filters")
|
||||||
return self.get_catalog_filters()
|
return self.get_catalog_filters()
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
|
|
@ -233,6 +274,8 @@ class StorefrontCmsService:
|
||||||
|
|
||||||
self.db.commit()
|
self.db.commit()
|
||||||
self.db.refresh(cat)
|
self.db.refresh(cat)
|
||||||
|
cache.invalidate_prefix("cms:mega_menu")
|
||||||
|
cache.invalidate_prefix("catalog:categories")
|
||||||
return {
|
return {
|
||||||
"category_id": cat.category_id,
|
"category_id": cat.category_id,
|
||||||
"name": cat.name,
|
"name": cat.name,
|
||||||
|
|
@ -265,6 +308,7 @@ class StorefrontCmsService:
|
||||||
review.admin_reply = payload.admin_reply
|
review.admin_reply = payload.admin_reply
|
||||||
self.db.commit()
|
self.db.commit()
|
||||||
self.db.refresh(review)
|
self.db.refresh(review)
|
||||||
|
cache.invalidate_prefix(f"reviews:{review.product_id}")
|
||||||
return self._map_review(review)
|
return self._map_review(review)
|
||||||
|
|
||||||
def reject_review(self, review_id: str) -> ReviewModerationResponse:
|
def reject_review(self, review_id: str) -> ReviewModerationResponse:
|
||||||
|
|
@ -275,6 +319,7 @@ class StorefrontCmsService:
|
||||||
review.is_approved = False
|
review.is_approved = False
|
||||||
self.db.commit()
|
self.db.commit()
|
||||||
self.db.refresh(review)
|
self.db.refresh(review)
|
||||||
|
cache.invalidate_prefix(f"reviews:{review.product_id}")
|
||||||
return self._map_review(review)
|
return self._map_review(review)
|
||||||
|
|
||||||
def _map_review(self, r: ProductReview) -> ReviewModerationResponse:
|
def _map_review(self, r: ProductReview) -> ReviewModerationResponse:
|
||||||
|
|
|
||||||
|
|
@ -9,9 +9,7 @@ import ulid
|
||||||
from app.repositories.StorefrontRepository import StorefrontRepository
|
from app.repositories.StorefrontRepository import StorefrontRepository
|
||||||
from app.models.StorefrontContentModel import StorefrontContent, ContentStatusEnum
|
from app.models.StorefrontContentModel import StorefrontContent, ContentStatusEnum
|
||||||
from app.models.ProductReviewModel import ProductReview
|
from app.models.ProductReviewModel import ProductReview
|
||||||
|
from app.core.database.cache_manager import cache
|
||||||
# In-Memory Cache Store for high performance
|
|
||||||
_IN_MEMORY_CACHE: Dict[str, Any] = {}
|
|
||||||
|
|
||||||
class StorefrontService:
|
class StorefrontService:
|
||||||
def __init__(self, db: Session):
|
def __init__(self, db: Session):
|
||||||
|
|
@ -41,16 +39,16 @@ class StorefrontService:
|
||||||
return result
|
return result
|
||||||
|
|
||||||
def invalidate_cache(self, pattern: Optional[str] = None):
|
def invalidate_cache(self, pattern: Optional[str] = None):
|
||||||
global _IN_MEMORY_CACHE
|
|
||||||
if pattern:
|
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:
|
else:
|
||||||
_IN_MEMORY_CACHE.clear()
|
cache.clear()
|
||||||
|
|
||||||
def get_reviews(self, product_id: str) -> List[Dict[str, Any]]:
|
def get_reviews(self, product_id: str) -> List[Dict[str, Any]]:
|
||||||
cache_key = f"reviews:{product_id}"
|
cache_key = f"reviews:{product_id}"
|
||||||
if cache_key in _IN_MEMORY_CACHE:
|
cached_reviews = cache.get(cache_key)
|
||||||
return _IN_MEMORY_CACHE[cache_key]
|
if cached_reviews is not None:
|
||||||
|
return cached_reviews
|
||||||
|
|
||||||
reviews = self.repo.get_approved_reviews(product_id)
|
reviews = self.repo.get_approved_reviews(product_id)
|
||||||
result = [
|
result = [
|
||||||
|
|
@ -70,15 +68,16 @@ class StorefrontService:
|
||||||
for r in reviews
|
for r in reviews
|
||||||
]
|
]
|
||||||
|
|
||||||
_IN_MEMORY_CACHE[cache_key] = result
|
cache.set(cache_key, result, ttl_seconds=cache.TTL_SETTINGS)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
def get_public_settings(self, group: Optional[str] = None) -> Dict[str, Any]:
|
def get_public_settings(self, group: Optional[str] = None) -> Dict[str, Any]:
|
||||||
cache_key = f"settings:public:{group or 'all'}"
|
cache_key = f"settings:public:{group or 'all'}"
|
||||||
if cache_key in _IN_MEMORY_CACHE:
|
cached_settings = cache.get(cache_key)
|
||||||
return _IN_MEMORY_CACHE[cache_key]
|
if cached_settings is not None:
|
||||||
|
return cached_settings
|
||||||
|
|
||||||
settings = self.repo.get_public_settings(group)
|
settings = self.repo.get_public_settings(group)
|
||||||
result = {s.setting_key: s.setting_value for s in settings}
|
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
|
return result
|
||||||
|
|
|
||||||
|
|
@ -152,11 +152,22 @@ class MediaResolver:
|
||||||
media_groups: Dict[canonical_media_key, metadata_dict]
|
media_groups: Dict[canonical_media_key, metadata_dict]
|
||||||
media_files: List[file_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:
|
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
|
||||||
entries = zip_ref.infolist()
|
entries = zip_ref.infolist()
|
||||||
wrapper_prefix = cls.detect_archive_wrapper(entries)
|
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_groups: Dict[str, Dict[str, Any]] = {}
|
||||||
media_files: List[Dict[str, Any]] = []
|
media_files: List[Dict[str, Any]] = []
|
||||||
|
|
|
||||||
|
|
@ -521,22 +521,29 @@ class MigrationWorker:
|
||||||
return
|
return
|
||||||
|
|
||||||
chunk_entries = all_entries[i:i+batch_size]
|
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:
|
if not valid_chunk_entries:
|
||||||
ext = os.path.splitext(entry.filename)[1].lower()
|
self.update_phase_checkpoint(db, job_id, PhaseEnum.MEDIA_PROCESS, batch_number, (len(all_entries)//batch_size)+1, job.processed_records, job.failed_records)
|
||||||
if ext not in ('.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.tiff'):
|
db.commit()
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Check existing MigrationMediaItem status for resume semantics
|
# Bulk fetch existing MigrationMediaItem records for this chunk to avoid WAN RTT per item
|
||||||
existing_item = db.query(MigrationMediaItem).filter(
|
entry_filenames = [e.filename for e in valid_chunk_entries]
|
||||||
MigrationMediaItem.job_id == job_id,
|
existing_items = db.query(MigrationMediaItem).filter(
|
||||||
MigrationMediaItem.zip_entry_path == entry.filename
|
MigrationMediaItem.job_id == job_id,
|
||||||
).first()
|
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:
|
job_config = StorageManager.get_job_config(job_id)
|
||||||
existing_item.media_key = media_key
|
media_struct = job_config.get("media_structure", "AUTO")
|
||||||
existing_item.status = MediaItemStatusEnum.STORED
|
|
||||||
|
|
||||||
|
for entry in valid_chunk_entries:
|
||||||
|
existing_item = existing_items_map.get(entry.filename)
|
||||||
try:
|
try:
|
||||||
# Stream file bytes directly from ZIP
|
# Stream file bytes directly from ZIP
|
||||||
with zf.open(entry) as f_entry:
|
with zf.open(entry) as f_entry:
|
||||||
|
|
@ -544,12 +551,8 @@ class MigrationWorker:
|
||||||
|
|
||||||
import hashlib
|
import hashlib
|
||||||
sha256_hash = hashlib.sha256(file_bytes).hexdigest()
|
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)
|
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
|
# Atomic POSIX write: temp write -> fsync -> rename -> STORED
|
||||||
storage_path, cdn_url, width, height = StorageManager.write_media_file_atomically(
|
storage_path, cdn_url, width, height = StorageManager.write_media_file_atomically(
|
||||||
job_id, file_bytes, os.path.basename(entry.filename), sha256_hash
|
job_id, file_bytes, os.path.basename(entry.filename), sha256_hash
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ from typing import List, Dict, Any, Tuple
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
import app.models.db_base
|
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.BrandModel import Brand
|
||||||
from app.models.CategoryModel import Category
|
from app.models.CategoryModel import Category
|
||||||
from app.models.DeviceCatalogModel import DeviceSeries, DeviceModel, ServiceType, RepairService, RepairVariant
|
from app.models.DeviceCatalogModel import DeviceSeries, DeviceModel, ServiceType, RepairService, RepairVariant
|
||||||
|
|
@ -645,6 +645,45 @@ class UpsertExecutor:
|
||||||
is_primary=(idx == 0)
|
is_primary=(idx == 0)
|
||||||
)
|
)
|
||||||
db_session.add(var_img)
|
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
|
# 7. Update inventory ledger stock level
|
||||||
stock_val = mapped_row.get("stock")
|
stock_val = mapped_row.get("stock")
|
||||||
if stock_val is not None and str(stock_val).strip() != "":
|
if stock_val is not None and str(stock_val).strip() != "":
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,4 @@
|
||||||
|
from typing import Optional
|
||||||
from passlib.context import CryptContext
|
from passlib.context import CryptContext
|
||||||
import hashlib
|
import hashlib
|
||||||
|
|
||||||
|
|
@ -9,5 +10,7 @@ def hash_password(pwd: str) -> str:
|
||||||
def verify_password(pwd: str, hash: str) -> bool:
|
def verify_password(pwd: str, hash: str) -> bool:
|
||||||
return pwd_context.verify(pwd, hash)
|
return pwd_context.verify(pwd, hash)
|
||||||
|
|
||||||
def hash_token(token: str) -> str:
|
def hash_token(token: Optional[str]) -> str:
|
||||||
return hashlib.sha256(token.encode()).hexdigest()
|
if not token:
|
||||||
|
return ""
|
||||||
|
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||||
|
|
|
||||||
24
gunicorn.conf.py
Normal file
24
gunicorn.conf.py
Normal file
|
|
@ -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
|
||||||
|
|
||||||
|
|
@ -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 ---")
|
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")
|
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 ---")
|
print("--- Restarting FastAPI Backend Service (port 8010) ---")
|
||||||
run_remote("pkill -f 'uvicorn app.main:app' || true")
|
run_remote("systemctl restart ifixkart.service || (pkill -f 'gunicorn app.main:app' ; pkill -f 'uvicorn app.main:app' || true)")
|
||||||
|
|
||||||
sftp.close()
|
sftp.close()
|
||||||
ssh.close()
|
ssh.close()
|
||||||
|
|
|
||||||
142
scripts/heal_catalog_media.py
Normal file
142
scripts/heal_catalog_media.py
Normal file
|
|
@ -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()
|
||||||
17
scripts/ifixkart.service
Normal file
17
scripts/ifixkart.service
Normal file
|
|
@ -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
|
||||||
|
|
||||||
160
scripts/verify_remediation.py
Normal file
160
scripts/verify_remediation.py
Normal file
|
|
@ -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")
|
||||||
Loading…
Reference in a new issue