ifixkart-backend/app/api/v1/routers/DeduplicationRouter.py

74 lines
2.9 KiB
Python

from fastapi import APIRouter, Depends, status, Request
from sqlalchemy.orm import Session
from sqlalchemy import select, func
from pydantic import BaseModel
from typing import Optional, List, Any
from app.core.database.db_session import get_db
from app.core.permissions.RoleChecker import get_current_user
from app.models.UserModel import User
from app.models.ProductModel import Product, ProductLocation
from app.models.DeviceCatalogModel import RepairService
from app.models.SystemConfigModel import CrmLocation
router = APIRouter(prefix="/api/v1/catalog", tags=["Catalog Deduplication & Verification"])
class DeduplicationCheckPayload(BaseModel):
item_type: str # "PRODUCT" or "SERVICE"
name: str
category_id: Optional[str] = None
brand_id: Optional[str] = None
device_model_id: Optional[str] = None
@router.post("/check-duplicate")
def check_item_duplicate(
payload: DeduplicationCheckPayload,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
) -> Any:
"""Case-insensitive deduplication check for Products and Services."""
normalized_input = payload.name.strip().lower()
if payload.item_type.upper() == "PRODUCT":
stmt = select(Product).where(
func.lower(func.trim(Product.name)) == normalized_input,
Product.deleted_at.is_(None)
)
if payload.category_id:
stmt = stmt.where(Product.category_id == payload.category_id)
if payload.brand_id:
stmt = stmt.where(Product.brand_id == payload.brand_id)
product = db.execute(stmt).scalars().first()
if product:
# Fetch existing mapped location names
loc_stmt = select(CrmLocation.name).join(
ProductLocation, ProductLocation.location_id == CrmLocation.location_id
).where(ProductLocation.product_id == product.product_id)
loc_names = list(db.execute(loc_stmt).scalars().all())
return {
"is_duplicate": True,
"item_id": product.product_id,
"name": product.name,
"sku": product.sku,
"existing_locations": loc_names or ["Central Warehouse"]
}
elif payload.item_type.upper() == "SERVICE":
stmt = select(RepairService).where(
func.lower(func.trim(RepairService.name)) == normalized_input
)
if payload.brand_id:
stmt = stmt.where(RepairService.brand_id == payload.brand_id)
service = db.execute(stmt).scalars().first()
if service:
return {
"is_duplicate": True,
"item_id": service.repair_service_id,
"name": service.name,
"existing_locations": ["All Branches"]
}
return {"is_duplicate": False, "item_id": None, "existing_locations": []}