77 lines
2.5 KiB
Python
77 lines
2.5 KiB
Python
"""Suppliers router.
|
|
|
|
GET /api/suppliers
|
|
POST /api/suppliers
|
|
GET /api/suppliers/{id}/performance
|
|
"""
|
|
from typing import List, Optional
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.database import get_db
|
|
from app.models import Supplier, SupplierPerformance
|
|
from app.schemas import SupplierCreate, SupplierOut, SupplierPerformanceOut
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.get("", response_model=List[SupplierOut])
|
|
def list_suppliers(status: Optional[str] = None, db: Session = Depends(get_db)):
|
|
q = db.query(Supplier)
|
|
if status:
|
|
q = q.filter(Supplier.status == status)
|
|
return q.order_by(Supplier.created_at.desc()).all()
|
|
|
|
|
|
@router.post("", response_model=SupplierOut)
|
|
def create_supplier(body: SupplierCreate, db: Session = Depends(get_db)):
|
|
supplier = Supplier(
|
|
name=body.name,
|
|
adapter_type=body.adapter_type,
|
|
api_endpoint=body.api_endpoint,
|
|
account_id=body.account_id,
|
|
fulfillment_caps=body.fulfillment_caps or {},
|
|
shipping_regions=body.shipping_regions or [],
|
|
reliability_score=body.reliability_score,
|
|
status=body.status,
|
|
)
|
|
db.add(supplier)
|
|
db.commit()
|
|
db.refresh(supplier)
|
|
return supplier
|
|
|
|
|
|
@router.get("/{supplier_id}/performance", response_model=SupplierPerformanceOut)
|
|
def supplier_performance(supplier_id, db: Session = Depends(get_db)):
|
|
supplier = db.query(Supplier).filter(Supplier.id == supplier_id).first()
|
|
if supplier is None:
|
|
raise HTTPException(status_code=404, detail="supplier not found")
|
|
|
|
perf = (
|
|
db.query(SupplierPerformance)
|
|
.filter(SupplierPerformance.supplier_id == supplier_id)
|
|
.first()
|
|
)
|
|
if perf is None:
|
|
# synthesize defaults; nothing measured yet
|
|
return SupplierPerformanceOut(
|
|
supplier_id=supplier_id,
|
|
supplier_name=supplier.name,
|
|
fulfillment_rate=100.0,
|
|
avg_shipping_days=None,
|
|
cancellation_rate=0.0,
|
|
stock_accuracy=100.0,
|
|
return_rate=0.0,
|
|
)
|
|
return SupplierPerformanceOut(
|
|
supplier_id=supplier_id,
|
|
supplier_name=supplier.name,
|
|
fulfillment_rate=float(perf.fulfillment_rate or 0),
|
|
avg_shipping_days=float(perf.avg_shipping_days) if perf.avg_shipping_days is not None else None,
|
|
cancellation_rate=float(perf.cancellation_rate or 0),
|
|
stock_accuracy=float(perf.stock_accuracy or 0),
|
|
return_rate=float(perf.return_rate or 0),
|
|
updated_at=perf.updated_at,
|
|
)
|