406 lines
15 KiB
Python
406 lines
15 KiB
Python
from datetime import date
|
|
from typing import Optional
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
|
from fastapi.responses import StreamingResponse
|
|
from sqlalchemy import or_
|
|
from sqlalchemy.orm import Session, joinedload
|
|
|
|
from ..core.db import get_db
|
|
from ..core.deps import get_current_user, require_roles
|
|
from ..core.time_utils import effective_today
|
|
from ..models import Asset, Contract, PMSchedule, User, Vendor
|
|
from ..schemas.contracts import (
|
|
ContractCreate,
|
|
ContractHistoryOut,
|
|
ContractListOut,
|
|
ContractOut,
|
|
ContractRenewIn,
|
|
ContractRenewOut,
|
|
ContractStatusFilter,
|
|
ContractType,
|
|
ContractUpdate,
|
|
)
|
|
from ..services.attachment_service import get_attachment_counts
|
|
from ..services.audit import log_audit
|
|
from ..services.bulk_templates import build_contracts_template_xlsx
|
|
from ..services.calculations import coverage_status
|
|
from ..services.permissions import Role
|
|
from ..services.settings_service import get_setting_value
|
|
|
|
router = APIRouter(prefix="/contracts", tags=["contracts"])
|
|
|
|
|
|
def _contract_lead_settings(db: Session) -> tuple[int, int]:
|
|
lead = int(
|
|
get_setting_value(
|
|
db,
|
|
"amc_cmc_lead_days",
|
|
get_setting_value(db, "contract_expiry_alert_days", 30),
|
|
)
|
|
)
|
|
red = int(
|
|
get_setting_value(
|
|
db,
|
|
"contract_critical_alert_days",
|
|
get_setting_value(db, "red_threshold_days", 7),
|
|
)
|
|
)
|
|
return lead, red
|
|
|
|
|
|
def _to_contract_out(
|
|
c: Contract,
|
|
today: date,
|
|
lead_days: int,
|
|
red_days: int,
|
|
att_counts: dict[int, int],
|
|
) -> ContractOut:
|
|
asset = c.asset
|
|
if c.is_superseded:
|
|
st, sev = "superseded", "ok"
|
|
else:
|
|
st, sev = coverage_status(c.start_date, c.end_date, today, lead_days, red_days)
|
|
return ContractOut(
|
|
id=c.id,
|
|
asset_id=c.asset_id,
|
|
asset_code=asset.asset_code,
|
|
asset_name=asset.name,
|
|
department_id=asset.department_id,
|
|
department_name=asset.department.name if asset.department else None,
|
|
contract_type=c.contract_type,
|
|
provider_id=c.provider_id,
|
|
provider_name=c.provider.name if c.provider else None,
|
|
start_date=c.start_date,
|
|
end_date=c.end_date,
|
|
coverage_period_text=c.coverage_period_text,
|
|
renewed_from_id=c.renewed_from_id,
|
|
is_superseded=c.is_superseded,
|
|
status=st,
|
|
severity=sev,
|
|
days_to_expiry=(c.end_date - today).days,
|
|
attachment_count=att_counts.get(c.id, 0),
|
|
remarks=c.remarks,
|
|
created_at=c.created_at,
|
|
)
|
|
|
|
|
|
def _load_contract(db: Session, contract_id: int) -> Contract | None:
|
|
return (
|
|
db.query(Contract)
|
|
.options(
|
|
joinedload(Contract.asset).joinedload(Asset.department),
|
|
joinedload(Contract.provider),
|
|
)
|
|
.filter(Contract.id == contract_id)
|
|
.first()
|
|
)
|
|
|
|
|
|
@router.get("", response_model=ContractListOut)
|
|
def list_contracts(
|
|
q: str = "",
|
|
department_id: Optional[int] = None,
|
|
asset_id: Optional[int] = None,
|
|
provider_id: Optional[int] = None,
|
|
contract_type: Optional[ContractType] = None,
|
|
status_filter: Optional[ContractStatusFilter] = Query(None, alias="status"),
|
|
include_superseded: bool = True,
|
|
page: int = Query(1, ge=1),
|
|
page_size: int = Query(200, ge=1, le=500),
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(get_current_user),
|
|
):
|
|
today = effective_today(db)
|
|
lead_days, red_days = _contract_lead_settings(db)
|
|
|
|
query = (
|
|
db.query(Contract)
|
|
.join(Asset, Contract.asset_id == Asset.id)
|
|
.outerjoin(Vendor, Contract.provider_id == Vendor.id)
|
|
.options(
|
|
joinedload(Contract.asset).joinedload(Asset.department),
|
|
joinedload(Contract.provider),
|
|
)
|
|
)
|
|
if current_user.role == Role.department_user.value:
|
|
query = query.filter(Asset.department_id == current_user.department_id)
|
|
elif department_id is not None:
|
|
query = query.filter(Asset.department_id == department_id)
|
|
|
|
if asset_id is not None:
|
|
query = query.filter(Contract.asset_id == asset_id)
|
|
if provider_id is not None:
|
|
query = query.filter(Contract.provider_id == provider_id)
|
|
if contract_type is not None:
|
|
query = query.filter(Contract.contract_type == contract_type)
|
|
if not include_superseded:
|
|
query = query.filter(Contract.is_superseded.is_(False))
|
|
if q and q.strip():
|
|
like = f"%{q.strip()}%"
|
|
query = query.filter(
|
|
or_(
|
|
Asset.asset_code.ilike(like),
|
|
Asset.name.ilike(like),
|
|
Vendor.name.ilike(like),
|
|
Contract.coverage_period_text.ilike(like),
|
|
Contract.remarks.ilike(like),
|
|
)
|
|
)
|
|
|
|
rows = query.order_by(Contract.is_superseded.asc(), Contract.end_date.asc(), Contract.id.desc()).all()
|
|
att_counts = get_attachment_counts(db, "contract", [r.id for r in rows])
|
|
items_all = [_to_contract_out(r, today, lead_days, red_days, att_counts) for r in rows]
|
|
|
|
if status_filter is not None:
|
|
items_all = [item for item in items_all if item.status == status_filter]
|
|
|
|
total = len(items_all)
|
|
start = (page - 1) * page_size
|
|
return ContractListOut(items=items_all[start : start + page_size], total=total)
|
|
|
|
|
|
@router.get("/history/{asset_id}", response_model=ContractHistoryOut)
|
|
def get_contract_history(
|
|
asset_id: int,
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(get_current_user),
|
|
):
|
|
asset = db.query(Asset).filter(Asset.id == asset_id).first()
|
|
if asset is None:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
|
|
if current_user.role == Role.department_user.value and asset.department_id != current_user.department_id:
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Access denied for another department's asset.")
|
|
|
|
today = effective_today(db)
|
|
lead_days, red_days = _contract_lead_settings(db)
|
|
rows = (
|
|
db.query(Contract)
|
|
.options(
|
|
joinedload(Contract.asset).joinedload(Asset.department),
|
|
joinedload(Contract.provider),
|
|
)
|
|
.filter(Contract.asset_id == asset_id)
|
|
.order_by(Contract.start_date.desc(), Contract.id.desc())
|
|
.all()
|
|
)
|
|
att_counts = get_attachment_counts(db, "contract", [r.id for r in rows])
|
|
return ContractHistoryOut(
|
|
items=[_to_contract_out(r, today, lead_days, red_days, att_counts) for r in rows]
|
|
)
|
|
|
|
|
|
@router.get("/import-template")
|
|
def download_contracts_import_template(
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
|
):
|
|
buf = build_contracts_template_xlsx(db)
|
|
return StreamingResponse(
|
|
buf,
|
|
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
headers={"Content-Disposition": 'attachment; filename="contracts_import_template.xlsx"'},
|
|
)
|
|
|
|
|
|
@router.post("", response_model=ContractOut, status_code=status.HTTP_201_CREATED)
|
|
def create_contract(
|
|
payload: ContractCreate,
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
|
):
|
|
if payload.end_date < payload.start_date:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
detail="end_date cannot be earlier than start_date.",
|
|
)
|
|
if not db.query(Asset.id).filter(Asset.id == payload.asset_id).first():
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
|
|
if not db.query(Vendor.id).filter(Vendor.id == payload.provider_id).first():
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Provider vendor not found.")
|
|
|
|
contract = Contract(
|
|
asset_id=payload.asset_id,
|
|
contract_type=payload.contract_type,
|
|
provider_id=payload.provider_id,
|
|
start_date=payload.start_date,
|
|
end_date=payload.end_date,
|
|
coverage_period_text=payload.coverage_period_text.strip() if payload.coverage_period_text else None,
|
|
renewed_from_id=None,
|
|
is_superseded=False,
|
|
remarks=payload.remarks.strip() if payload.remarks else None,
|
|
created_by_id=current_user.id,
|
|
updated_by_id=current_user.id,
|
|
)
|
|
db.add(contract)
|
|
db.flush()
|
|
|
|
log_audit(
|
|
db,
|
|
entity_type="contract",
|
|
entity_id=contract.id,
|
|
action="create",
|
|
changes={
|
|
"asset_id": payload.asset_id,
|
|
"contract_type": payload.contract_type,
|
|
"provider_id": payload.provider_id,
|
|
"start_date": str(payload.start_date),
|
|
"end_date": str(payload.end_date),
|
|
},
|
|
user_id=current_user.id,
|
|
)
|
|
db.commit()
|
|
|
|
loaded = _load_contract(db, contract.id)
|
|
today = effective_today(db)
|
|
lead_days, red_days = _contract_lead_settings(db)
|
|
att_counts = get_attachment_counts(db, "contract", [contract.id])
|
|
return _to_contract_out(loaded, today, lead_days, red_days, att_counts)
|
|
|
|
|
|
@router.patch("/{contract_id}", response_model=ContractOut)
|
|
def update_contract(
|
|
contract_id: int,
|
|
payload: ContractUpdate,
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
|
):
|
|
contract = db.query(Contract).filter(Contract.id == contract_id).first()
|
|
if contract is None:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Contract not found.")
|
|
|
|
data = payload.model_dump(exclude_unset=True)
|
|
if "provider_id" in data and data["provider_id"] is not None:
|
|
if not db.query(Vendor.id).filter(Vendor.id == data["provider_id"]).first():
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Provider vendor not found.")
|
|
|
|
new_start = data.get("start_date", contract.start_date)
|
|
new_end = data.get("end_date", contract.end_date)
|
|
if new_end < new_start:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
detail="end_date cannot be earlier than start_date.",
|
|
)
|
|
|
|
changes: dict[str, dict[str, object]] = {}
|
|
for k, v in data.items():
|
|
if isinstance(v, str):
|
|
v = v.strip() or None
|
|
old_val = getattr(contract, k)
|
|
if old_val != v:
|
|
changes[k] = {"from": old_val, "to": v}
|
|
setattr(contract, k, v)
|
|
contract.updated_by_id = current_user.id
|
|
|
|
if changes:
|
|
log_audit(
|
|
db,
|
|
entity_type="contract",
|
|
entity_id=contract.id,
|
|
action="update",
|
|
changes=changes,
|
|
user_id=current_user.id,
|
|
)
|
|
db.commit()
|
|
|
|
loaded = _load_contract(db, contract.id)
|
|
today = effective_today(db)
|
|
lead_days, red_days = _contract_lead_settings(db)
|
|
att_counts = get_attachment_counts(db, "contract", [contract.id])
|
|
return _to_contract_out(loaded, today, lead_days, red_days, att_counts)
|
|
|
|
|
|
@router.delete("/{contract_id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
def delete_contract(
|
|
contract_id: int,
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
|
):
|
|
contract = db.query(Contract).filter(Contract.id == contract_id).first()
|
|
if contract is None:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Contract not found.")
|
|
|
|
db.query(Contract).filter(Contract.renewed_from_id == contract.id).update({"renewed_from_id": None})
|
|
db.query(PMSchedule).filter(PMSchedule.contract_id == contract.id).update({"contract_id": None})
|
|
|
|
log_audit(
|
|
db,
|
|
entity_type="contract",
|
|
entity_id=contract.id,
|
|
action="delete",
|
|
changes={"asset_id": contract.asset_id, "contract_type": contract.contract_type},
|
|
user_id=current_user.id,
|
|
)
|
|
db.delete(contract)
|
|
db.commit()
|
|
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
|
|
|
|
|
@router.post("/{contract_id}/renew", response_model=ContractRenewOut)
|
|
def renew_contract(
|
|
contract_id: int,
|
|
payload: ContractRenewIn,
|
|
db: Session = Depends(get_db),
|
|
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
|
):
|
|
old_contract = db.query(Contract).filter(Contract.id == contract_id).first()
|
|
if old_contract is None:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Contract not found.")
|
|
|
|
if payload.end_date < payload.start_date:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
detail="end_date cannot be earlier than start_date.",
|
|
)
|
|
|
|
target_provider_id = payload.provider_id if payload.provider_id is not None else old_contract.provider_id
|
|
if not db.query(Vendor.id).filter(Vendor.id == target_provider_id).first():
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Provider vendor not found.")
|
|
|
|
old_contract.is_superseded = True
|
|
old_contract.updated_by_id = current_user.id
|
|
|
|
new_contract = Contract(
|
|
asset_id=old_contract.asset_id,
|
|
contract_type=payload.contract_type or old_contract.contract_type,
|
|
provider_id=target_provider_id,
|
|
start_date=payload.start_date,
|
|
end_date=payload.end_date,
|
|
coverage_period_text=(
|
|
payload.coverage_period_text.strip()
|
|
if payload.coverage_period_text is not None
|
|
else old_contract.coverage_period_text
|
|
),
|
|
renewed_from_id=old_contract.id,
|
|
is_superseded=False,
|
|
remarks=payload.remarks.strip() if payload.remarks else None,
|
|
created_by_id=current_user.id,
|
|
updated_by_id=current_user.id,
|
|
)
|
|
db.add(new_contract)
|
|
db.flush()
|
|
|
|
log_audit(
|
|
db,
|
|
entity_type="contract",
|
|
entity_id=old_contract.id,
|
|
action="renew",
|
|
changes={
|
|
"superseded_contract_id": old_contract.id,
|
|
"new_contract_id": new_contract.id,
|
|
"start_date": str(payload.start_date),
|
|
"end_date": str(payload.end_date),
|
|
},
|
|
user_id=current_user.id,
|
|
)
|
|
db.commit()
|
|
|
|
today = effective_today(db)
|
|
lead_days, red_days = _contract_lead_settings(db)
|
|
att_counts = get_attachment_counts(db, "contract", [old_contract.id, new_contract.id])
|
|
loaded_old = _load_contract(db, old_contract.id)
|
|
loaded_new = _load_contract(db, new_contract.id)
|
|
return ContractRenewOut(
|
|
old_contract=_to_contract_out(loaded_old, today, lead_days, red_days, att_counts),
|
|
new_contract=_to_contract_out(loaded_new, today, lead_days, red_days, att_counts),
|
|
)
|