from datetime import date from typing import Any, Optional from sqlalchemy.orm import Session, joinedload from ..core.time_utils import effective_today from ..models import Asset, Contract, Vendor, Warranty from .calculations import coverage_status from .settings_service import get_setting_value COVERAGE_TAG_LABELS: dict[str, str] = { "warranty": "Warranty", "cmc": "CMC", "amc": "AMC", "other_contract": "Other Contract", "out_of_contract": "Out of Contract", } _CONTRACT_TYPE_PRIORITY = { "CMC": 1, "AMC": 2, "OTHER": 3, } _CONTRACT_TYPE_TO_TAG = { "CMC": "cmc", "AMC": "amc", "OTHER": "other_contract", } def format_coverage_tag_label(tag: Optional[str]) -> str: if not tag: return "Out of Contract" return COVERAGE_TAG_LABELS.get(tag, tag.replace("_", " ").title()) def format_vendor_contact(vendor: Optional[Vendor]) -> Optional[str]: if vendor is None: return None parts: list[str] = [] if vendor.phone and vendor.phone.strip(): parts.append(vendor.phone.strip()) elif vendor.email and vendor.email.strip(): parts.append(vendor.email.strip()) if vendor.contact_person and vendor.contact_person.strip(): if parts: return f"{vendor.contact_person.strip()} ({parts[0]})" return vendor.contact_person.strip() return parts[0] if parts else None def _lead_and_red_settings(db: Session) -> dict[str, int]: return { "warranty_lead": int(get_setting_value(db, "warranty_expiry_alert_days", 30)), "contract_lead": int(get_setting_value(db, "contract_expiry_alert_days", 30)), "contract_red": int( get_setting_value( db, "contract_critical_alert_days", get_setting_value(db, "red_threshold_days", 7), ) ), "red": int(get_setting_value(db, "red_threshold_days", 7)), } def _compute_from_records( warranties: list[Warranty], contracts: list[Contract], supplier: Optional[Vendor], on_date: date, leads: dict[str, int], ) -> dict[str, Any]: # 1. Active warranties: start_date <= on_date <= end_date active_warranties = [ w for w in warranties if w.start_date <= on_date <= w.end_date ] if active_warranties: active_warranties.sort(key=lambda w: (w.end_date, w.id), reverse=True) w = active_warranties[0] provider = w.provider or supplier _, sev = coverage_status( w.start_date, w.end_date, on_date, leads["warranty_lead"], leads["red"] ) sev_norm = sev if sev in ("ok", "yellow", "red") else "ok" return { "tag": "warranty", "contract_id": None, "warranty_id": w.id, "provider_id": provider.id if provider else w.provider_id, "provider_name": provider.name if provider else None, "provider_contact": format_vendor_contact(provider), "valid_from": w.start_date, "valid_until": w.end_date, "days_left": (w.end_date - on_date).days, "severity": sev_norm, } # 2. Active non-superseded contracts: priority CMC > AMC > OTHER active_contracts = [ c for c in contracts if not c.is_superseded and c.start_date <= on_date <= c.end_date ] if active_contracts: active_contracts.sort( key=lambda c: ( _CONTRACT_TYPE_PRIORITY.get((c.contract_type or "").upper(), 99), -c.end_date.toordinal(), -c.id, ) ) c = active_contracts[0] ctype = (c.contract_type or "OTHER").upper() tag = _CONTRACT_TYPE_TO_TAG.get(ctype, "other_contract") provider = c.provider _, sev = coverage_status( c.start_date, c.end_date, on_date, leads["contract_lead"], leads["contract_red"] ) sev_norm = sev if sev in ("ok", "yellow", "red") else "ok" return { "tag": tag, "contract_id": c.id, "warranty_id": None, "provider_id": c.provider_id, "provider_name": provider.name if provider else None, "provider_contact": format_vendor_contact(provider), "valid_from": c.start_date, "valid_until": c.end_date, "days_left": (c.end_date - on_date).days, "severity": sev_norm, } # 3. Out of contract return { "tag": "out_of_contract", "contract_id": None, "warranty_id": None, "provider_id": None, "provider_name": None, "provider_contact": None, "valid_from": None, "valid_until": None, "days_left": None, "severity": "red", } def get_coverage( db: Session, asset_id: int, on_date: Optional[date] = None, ) -> dict[str, Any]: target_date = on_date or effective_today(db) leads = _lead_and_red_settings(db) asset = ( db.query(Asset) .options(joinedload(Asset.supplier)) .filter(Asset.id == asset_id) .first() ) supplier = asset.supplier if asset else None warranties = ( db.query(Warranty) .options(joinedload(Warranty.provider)) .filter(Warranty.asset_id == asset_id) .all() ) contracts = ( db.query(Contract) .options(joinedload(Contract.provider)) .filter(Contract.asset_id == asset_id, Contract.is_superseded.is_(False)) .all() ) return _compute_from_records(warranties, contracts, supplier, target_date, leads) def get_coverage_map( db: Session, asset_ids: list[int], on_date: Optional[date] = None, ) -> dict[int, dict[str, Any]]: if not asset_ids: return {} unique_ids = list(set(asset_ids)) target_date = on_date or effective_today(db) leads = _lead_and_red_settings(db) assets = ( db.query(Asset) .options(joinedload(Asset.supplier)) .filter(Asset.id.in_(unique_ids)) .all() ) supplier_by_asset: dict[int, Optional[Vendor]] = {a.id: a.supplier for a in assets} warranties_by_asset: dict[int, list[Warranty]] = {aid: [] for aid in unique_ids} for w in ( db.query(Warranty) .options(joinedload(Warranty.provider)) .filter(Warranty.asset_id.in_(unique_ids)) .all() ): warranties_by_asset.setdefault(w.asset_id, []).append(w) contracts_by_asset: dict[int, list[Contract]] = {aid: [] for aid in unique_ids} for c in ( db.query(Contract) .options(joinedload(Contract.provider)) .filter(Contract.asset_id.in_(unique_ids), Contract.is_superseded.is_(False)) .all() ): contracts_by_asset.setdefault(c.asset_id, []).append(c) return { aid: _compute_from_records( warranties_by_asset.get(aid, []), contracts_by_asset.get(aid, []), supplier_by_asset.get(aid), target_date, leads, ) for aid in unique_ids } def get_active_amc_cmc( db: Session, asset_id: int, on_date: Optional[date] = None, ) -> Optional[Contract]: """Return the highest-priority active non-superseded AMC/CMC contract (CMC > AMC).""" target_date = on_date or effective_today(db) contracts = ( db.query(Contract) .filter( Contract.asset_id == asset_id, Contract.is_superseded.is_(False), Contract.contract_type.in_(["CMC", "AMC"]), Contract.start_date <= target_date, Contract.end_date >= target_date, ) .all() ) if not contracts: return None contracts.sort( key=lambda c: ( _CONTRACT_TYPE_PRIORITY.get((c.contract_type or "").upper(), 99), -c.end_date.toordinal(), -c.id, ) ) return contracts[0]