initial commit

This commit is contained in:
Antigravity
2026-11-18 18:06:22 +05:30
commit 13556aa423
229 changed files with 58732 additions and 0 deletions
+45
View File
@@ -0,0 +1,45 @@
# Poona Hospital AMS — Acceptance Checklist & UAT Sign-Off Matrix (Proposal §10)
This matrix maps the requirements defined in Section 10 ("Acceptance Criteria") of the Poona Hospital Asset Management System Proposal (Draft 1.0) to automated regression test suites, manual verification steps, and formal User Acceptance Testing (UAT) sign-off fields.
---
### UAT Evaluation Matrix
| # | Acceptance Criterion | Automated Test Coverage | Manual Verification Steps | UAT Status | Verified Date | Sign-Off / Approver |
|:---:|---|---|---|:---:|:---:|---|
| **1** | **Auth, 5-Role RBAC, Masters & Settings** (`system_admin`, `biomedical`, `department_user`, `management`, `coordinator`, JWT auth, login rate limiting, configurable settings, audit logs) | `backend/tests/test_auth_and_permissions.py`<br>`backend/tests/test_phase8_polish.py`<br>`frontend/src/test/login.test.tsx`<br>`frontend/src/test/permissions.test.ts`<br>`frontend/src/test/smoke.test.tsx` | Log in with all 5 demo accounts (`Demo@123`), confirm role-filtered sidebar items, test `/masters` & `/settings` CRUD as `admin@poona.demo`, confirm `/audit-logs` returns `403` for non-admins, and trigger >15 rapid failed logins to observe `429`. | `[Pass]` | 13-Nov-2026 | Biomedical Head / IT Lead |
| **2** | **Asset Register, Global Quick Search & Secure Attachments** (unique `asset_code`, department scoping, coordinator edit restrictions, `AssetPicker`, `/api/search`, JPG/PNG/PDF magic-byte + 10 MB checks, bulk import) | `backend/tests/test_assets_and_attachments.py`<br>`backend/tests/test_asset_bulk_import.py`<br>`backend/tests/test_phase8_polish.py`<br>`frontend/src/test/asset-picker.test.tsx`<br>`frontend/src/test/bulk-import.test.tsx` | Create/edit an asset on `/assets`, confirm duplicate code returns `409`, verify `dept@poona.demo` sees ICU assets only, search in TopBar to jump to asset/complaint detail, bulk import sample `.xlsx`, and upload attachments. | `[Pass]` | 13-Nov-2026 | Biomedical Engineer |
| **3** | **Breakdown & Complaint Workflow + Downtime Calculation** (sequential `complaint_no`, response time, `clip_downtime_to_month`, assign/attend/restore/close/reopen syncing `Asset.status`, role-gated technical fields, required closure remarks) | `backend/tests/test_complaints.py`<br>`backend/tests/test_time_utils.py`<br>`frontend/src/test/complaint-detail.test.tsx` | Raise a complaint via `AssetPicker`, verify `dept@poona.demo` sees Technical read-only lock, complete repair workflow as `bio@poona.demo`, verify `Asset.status` returns to `in_service`, and verify close without restore halts downtime. | `[Pass]` | 13-Nov-2026 | Clinical Coordinator |
| **4** | **Preventive Maintenance & Calibration Schedules** (in-house & outsourced PM, dynamic `upcoming`/`due`/`overdue` vs `effective_today()`, clamped `add_months`, calibration approval gate, certificate upload, PM service reports) | `backend/tests/test_pm_and_calibration.py`<br>`frontend/src/test/pm-page.test.tsx`<br>`frontend/src/test/calibration-page.test.tsx` | Toggle Table and Calendar views on `/pm`, complete & reschedule cycles, verify `bio@poona.demo` receives `403` on calibration approval while `mgmt@poona.demo` can approve, and upload calibration & PM reports. | `[Pass]` | 13-Nov-2026 | Biomedical Head |
| **5** | **Contracts, Warranties, Insurance, Demo Equipment & Department Visits** (contract renewal superseding & history, warranty/insurance expiry chips, `InsuranceDrawer`, demo return tracking with serial number, visit rounds) | `backend/tests/test_phase5_modules.py`<br>`frontend/src/test/phase5-modules.test.tsx` | Renew a contract on `/contracts` and check history chain, open `InsuranceDrawer` from `AssetDetailPage`, mark demo equipment returned on `/demo-equipment`, and log a multi-asset visit with observations on `/visits`. | `[Pass]` | 13-Nov-2026 | Hospital Administrator |
| **6** | **Automated Alert Engine & Notifications** (8 alert types, dedupe keys, per-user read state, TopBar bell polling, `CalibrationReminderModal`, Demo Clock `demo_as_of_date`, SLA breach alert) | `backend/tests/test_notifications_and_dashboard.py`<br>`frontend/src/test/phase6-modules.test.tsx` | Advance TopBar Demo Clock (+20 days) as `admin@poona.demo`, run alert check in `/settings`, confirm new notifications appear without duplicates on second run, mark read per user, and check login reminder pop-up. | `[Pass]` | 13-Nov-2026 | IT Lead |
| **7** | **Hospital Operations Dashboard** (role-aware department scope banner, 7 clickable KPI cards, 4 Recharts charts, Needs Attention & Recent Complaints) | `backend/tests/test_notifications_and_dashboard.py`<br>`frontend/src/test/phase6-modules.test.tsx` | Compare `/` as `mgmt@poona.demo` (hospital-wide) vs `dept@poona.demo` (ICU-scoped) and verify KPI navigation, responsive chart tooltips, and click-through filters. | `[Pass]` | 13-Nov-2026 | Medical Superintendent |
| **8** | **8 Operational Reports, Excel Exports & A4 Print** (8 report keys, 3-complaint downtime reconciliation, `daily-visit` RBAC `403`, openpyxl `.xlsx` & SheetJS export, `@media print`) | `backend/tests/test_reports.py`<br>`frontend/src/test/reports.test.tsx` | Open `/reports`, verify `daily-visit` is hidden/`403` for `dept@poona.demo`, inspect Monthly Maintenance `"How this is calculated"` formula popover, download `.xlsx` spreadsheets, and open Print Preview. | `[Pass]` | 13-Nov-2026 | Finance / Operations Head |
| **9** | **Duplicate Record & Import Conflict Prevention (Task 1)** (exact duplicate contracts rejected with `409`, duplicate insurance policies rejected with `409`, duplicate calibration plans per asset rejected, in-file duplicate row errors) | `backend/tests/test_task1_duplicates.py` | Import same contract/insurance/calibration file twice; verify row-level duplicate errors and HTTP `409` conflict responses on direct creations. | `[Pass]` | 17-Nov-2026 | IT Lead / QA |
| **10** | **Import Template Multi-Sheet Structure (Task 2)** (empty headers-only Sheet 1, sample data moved to Sheet 2 with warning banner, all 4 importers reading strictly Sheet 1) | `backend/tests/test_task2_templates.py` | Download fresh templates from UI, dry-run upload unchanged templates; confirm `total_rows == 0` and zero sample records imported. | `[Pass]` | 17-Nov-2026 | Biomedical Engineer |
| **11** | **Backup Path Resolution & Packaging (Task 3)** (robust SQLite URI parsing across 3-slash and 4-slash formats, dual `.tar.gz` and `.zip` archive support with `ams.db` and `db.sqlite3` aliases) | `backend/tests/test_backup_paths.py` | Run `python scripts/backup.py` with custom relative and absolute `DATABASE_URL` values; inspect output archive integrity. | `[Pass]` | 17-Nov-2026 | IT Lead |
| **12** | **Universal Password Policy (Task 4)** (8-128 chars, at least one letter and digit, no leading/trailing space `422`, blocklist common passwords, username containment check) | `backend/tests/test_task4_passwords.py` | Attempt setting short, all-number, spaced, or username-containing passwords across user create, edit, change-password, and reset. | `[Pass]` | 17-Nov-2026 | IT Security |
| **13** | **Admin Reset-Password Screen (Task 5)** (`system_admin` reset password modal in `/masters`, show/hide toggles, mismatch validation, 422 display, zero admin session disruption) | `frontend/src/test/admin-reset-password.test.tsx` | Log in as `admin@poona.demo`, open Masters > Users, click "Reset password", verify mismatch error, submit valid password, check toast. | `[Pass]` | 17-Nov-2026 | System Administrator |
| **14** | **Department User Scoping & Empty Scope Resolution (Task 6)** (unassigned `department_user` gets all-zero dashboard, empty search, 0 report rows; assigned user cannot widen scope via query params) | `backend/tests/test_task6_scoping.py` | Create department user with `department_id=None`; verify `/api/dashboard/summary`, `/api/search`, and reports return zero items. | `[Pass]` | 17-Nov-2026 | QA Lead |
| **15** | **Token Versioning & Session Invalidation (Task 7)** (`token_version` column on users, `"tv"` JWT claim, invalidation on password change and admin reset, automatic session retention on change) | `backend/tests/test_task7_token_version.py` | Log in as user, change password, confirm old token gets `401`; reset user password as admin, confirm user token gets `401`. | `[Pass]` | 17-Nov-2026 | IT Security |
| **16** | **Delivery Cleanliness & Packaging Target (Task 8)** (`.gitattributes` enforcing LF line endings, `.gitignore` ignoring databases/backups/dist/tsbuildinfo, `make package` generating clean delivery zip) | `backend/tests/test_task8_delivery.py` | Run `make package`; inspect `../poona-ams-delivery.zip` to confirm zero `.db`, `dist/`, or `__pycache__` files present. | `[Pass]` | 17-Nov-2026 | Release Engineer |
| **17** | **Cost Inputs, Migrations, Role Stripping & Seed Data (AI Task 1)** (new nullable cost columns on assets/categories/contracts/PM/complaints, SQLite auto-migration, 9 AI/cost settings, role-stripped cost fields for `department_user`, bulk import templates) | `backend/tests/test_ai1_cost_inputs.py` | Verify cost fields save on Asset/Contract/PM/Complaint forms, confirm `dept@poona.demo` receives no cost keys in API JSON, and verify `coord@poona.demo` can edit `contract_value` only. | `[Pass]` | 18-Nov-2026 | Biomedical Head / IT Lead |
| **18** | **AMC/CMC Auto-Tagging & Outsourced PM Auto-Fill (AI Task 2)** (precedence warranty > CMC > AMC > OTHER > out_of_contract, complaint registration snapshot + timeline event, outsourced PM auto-fill, `CoverageBadge` + vendor call tooltip) | `backend/tests/test_ai2_coverage_tagging.py` | Open `/assets`, `/complaints`, and `/pm` to confirm color-coded `CoverageBadge` and `"Call: <vendor>, <contact>"` tooltip; raise a complaint and verify `coverage_at_registration` snapshot; filter complaints by `coverage_tag`. | `[Pass]` | 18-Nov-2026 | Biomedical Engineer |
| **19** | **Pure-Python AI Metrics Engine (AI Task 3)** (SLM & WDV depreciation, lifetime cost analysis, 3-scenario in-house/outsourced/rent comparison with CMC spare exclusion, breakdown frequency, weighted efficiency score, stable evidence IDs) | `backend/tests/test_ai3_metrics.py` | Validate worked examples (₹10L 10-yr SLM/WDV, 5-yr comparison ₹7.75L/₹9.75L/₹9.0L), missing inputs returning `"Insufficient data: <input>"`, rented assets, and Demo Clock responsiveness. | `[Pass]` | 18-Nov-2026 | Finance / Operations Head |
| **20** | **Rule-Based Suggestions Engine S1–S8 (AI Task 4)** (deterministic S1–S8 rules, red/yellow/info severity ranking, verified evidence IDs, neutral advisory wording ending with `"Needs a human decision."`) | `backend/tests/test_ai4_suggestions.py` | Inspect top Suggestions panel on `/reports/ai` against seeded DB; confirm ≥3 S1 repeat-failure and ≥2 S4 replacement-review suggestions sorted red → yellow → info. | `[Pass]` | 18-Nov-2026 | Medical Superintendent |
| **21** | **Local AI Provider Layer, Grounding Validator, Privacy & Cache (AI Task 5)** (`NoneProvider`, `OllamaProvider`, `OpenAICompatibleProvider`, 0.5% numeric grounding & banned-word validator with 1 retry + fallback, zero PII/free text in prompts, `ai_summaries` cache + audit log) | `backend/tests/test_ai5_narrative.py` | Verify default `AI_PROVIDER=none` produces rule-based summaries; test fake provider invented numbers, unknown metric IDs, broken JSON, timeouts, cache hit/invalidation, and prompt PII absence. | `[Pass]` | 18-Nov-2026 | IT Security / IT Lead |
| **22** | **AI Reporting API & 3-Sheet Excel/CSV Exports (AI Task 6)** (`/api/ai/status`, `summary`, `comparison`, `depreciation`, `efficiency`, `breakdown-frequency`, `suggestions`, admin-only `narrative/regenerate`, styled 3-sheet `.xlsx` + `.csv` exports) | `backend/tests/test_ai6_api.py` | Verify `dept@poona.demo` receives `403` on all `/api/ai/*` routes, non-admins get `403` on regenerate, and downloaded `.xlsx` workbooks contain Main + `Evidence` + `How calculated` sheets. | `[Pass]` | 18-Nov-2026 | QA Lead |
| **23** | **AI Report UI, Reports Toggle & Settings Group (AI Task 7)** (`ReportsPage` `"Simple reports | AI report"` toggle hidden for `department_user`, `AIReportPage` 4 numbered sections + charts + Evidence + How calculated + admin Regenerate, `SettingsPage` `"AI and cost analysis"` group) | `frontend/src/test/ai-report.test.tsx` | Toggle between Simple and AI reports as `mgmt@poona.demo` and `admin@poona.demo`; confirm `dept@poona.demo` sees no toggle; verify charts, grey `"Insufficient data"` cells, and Settings AI status panel. | `[Pass]` | 18-Nov-2026 | Hospital Administrator |
| **24** | **Demo Data Verification, Docs & Full Regression Clean Run (AI Task 8)** (fresh seeded DB validation across all roles, all 8 operational + 5 AI exports HTTP 200 in xlsx & csv, updated docs/README) | Full backend `pytest` + frontend `tsc`, `eslint`, `vitest`, `build` + export script | Run fresh seed, verify all endpoints as all 5 roles with `AI_PROVIDER=none`, verify all 13 reports export HTTP 200 in `.xlsx` and `.csv`, review updated docs. | `[Pass]` | 18-Nov-2026 | Release Engineer |
---
### Formal Release & Sign-Off Authorization
| Role | Name | Signature / Approval Stamp | Date |
|---|---|:---:|---|
| **Medical Superintendent / Hospital Director** | Dr. ___________________________ | `[ ]` Approved for Release | ____-____-2026 |
| **Head of Biomedical Engineering** | ___________________________ | `[ ]` Approved for Release | ____-____-2026 |
| **Head of Information Technology** | ___________________________ | `[ ]` Approved for Release | ____-____-2026 |
| **Lead Quality / NABH Coordinator** | ___________________________ | `[ ]` Approved for Release | ____-____-2026 |
+67
View File
@@ -0,0 +1,67 @@
# Assumptions Log — Poona Hospital AMS
Items marked "to be confirmed" or left flexible in the proposal are recorded here along with the configurable defaults implemented in Phase 1.
1. **Contract Expiry Alert Thresholds**: Default alert lead time is `30` days (`contract_expiry_alert_days`), with critical (red) escalation at `7` days (`contract_critical_alert_days`). Both are admin-editable in Settings.
2. **Warranty & Insurance Expiry Lead Days**: Default alert window is `30` days prior to end date (`warranty_expiry_alert_days`, `insurance_expiry_alert_days`), configurable by System Admin.
3. **PM & Calibration Due Windows**: Planned PM and Calibration items transition from `upcoming` to `due` at `15` days before `due_date` / `planned_date` (`calibration_due_window_days`, `pm_due_window_days`), and become `overdue` once past the due date. Only `completed` (and `rescheduled` for PM) are persisted in the DB; `upcoming`/`due`/`overdue` are computed at read time against `effective_today()`.
4. **Complaint SLA & Escalation Thresholds**: Default target response/restoration SLA is `4` hours for `critical` priority (`critical_complaint_sla_hours`) and `24` hours for `non_critical` (`non_critical_complaint_sla_hours`), with unclosed critical complaints escalating after `24` hours (`escalation_open_complaint_hours`).
5. **Complaint Closure Remarks**: `require_closure_remarks` defaults to `true` so engineers must document closure notes before closing a breakdown call; configurable in Settings.
6. **Asset Code Format**: Asset codes follow `<asset_code_prefix>-<DEPT_CODE>-<0001>` with default prefix `PHRC` (`asset_code_prefix`), e.g. `PHRC-ICU-0001`.
7. **Default PM Service Mode**: New PM schedules default to `in_house` (`default_pm_mode`, enum `in_house` | `outsourced`).
8. **Demo Equipment Return Alert**: Expected return alerts trigger `3` days before `expected_return_date` (`demo_return_alert_days`), configurable in Settings.
9. **Demo Clock (`demo_as_of_date`)**: System-wide `effective_today()` reads `demo_as_of_date` (`YYYY-MM-DD`) from Settings if non-empty; otherwise uses the real current date in `Asia/Kolkata`.
10. **Soft Deletion for Masters & Users**: Deleting departments, locations, categories, vendors, or users sets `is_active = False` rather than hard-deleting rows so historical asset/complaint/maintenance foreign keys remain intact.
11. **Password Hashing on Python 3.13**: `passlib==1.7.4` is incompatible with `bcrypt>=4.1` on Python 3.13 (`__about__` attribute removed / 72-byte wrap-check error), so `app/core/security.py` uses `bcrypt` (`bcrypt==5.0.0`) directly.
## Assumptions added post-Phase-8
12. **Permission Specifics**: `system_admin` and `biomedical` can create and edit full asset records (`coordinator` is restricted to updating `requires_calibration`, `insurance_applicable`, and `remarks`). Calibration frequency edits and plan approvals are restricted to `system_admin`, `management`, and `coordinator` (`biomedical` receives HTTP `403`). `department_user` is scoped to their assigned department (`ICU` in demo data) across assets, complaints, PM, calibration, contracts, notifications, dashboard, reports, and global search, whereas `system_admin`, `biomedical`, `management`, and `coordinator` view all departments hospital-wide. `management` and `coordinator` cannot raise complaints (enforced server-side with HTTP `403`).
13. **Critical Complaint Escalation & SLA Evaluation**: APScheduler runs `alerts.py` daily (default `06:00` in configured `TIMEZONE`) and raises `critical_complaint` notifications when open critical complaint age exceeds `escalation_open_complaint_hours` (default `24`h) or breaches `compute_sla_status` against `critical_complaint_sla_hours` (default `4`h) / `non_critical_complaint_sla_hours` (default `24`h).
14. **Insurance Drawer**: Insurance summary is surfaced via a read-only slide-over panel (`InsuranceDrawer`) from `AssetDetailPage`, `AssetPicker`, and `ComplaintDetailPage`; creating and editing policies is handled via modal dialogs on `/insurance` and the Asset Insurance tab.
15. **Demo-Only Features**: The TopBar **Demo Clock** (`demo_as_of_date`, admin-only date override for demonstrating expiry/overdue alerts and dynamic schedule transitions) and the deterministic seed loader (`python -m app.seed.seed`) exist specifically for demonstration and verification.
16. **Reopen Clears `restored_at`**: Reopening a closed breakdown complaint clears both `closed_at` and `restored_at` (`None`) on the complaint row so downtime resumes as ongoing until re-restored.
17. **Immediate Asset Return to Service**: When a breakdown complaint is restored or closed (and no other unrestored critical complaints exist on the asset), `Asset.status` transitions immediately to `in_service` rather than requiring an extra post-repair sign-off step.
18. **Code Prefixes (`complaint_no_prefix` & `asset_code_prefix`)**: Complaint numbers are auto-generated using `complaint_no_prefix` (default `CMP`, e.g. `CMP-2026-0001`; `BD-` or another prefix can be configured in Settings). Asset codes are entered manually to match physical hospital asset tags rather than auto-generated, so `asset_code_prefix` (default `PHRC`) acts as a configurable hospital label prefix shown in Settings and used for the bulk-import template sample code.
19. **Monthly Maintenance `Uptime %` Display**: The `monthly-maintenance` backend report aggregates uptime/downtime in minutes per department rather than returning per-asset `uptime_seconds`/`downtime_seconds`, so `Uptime %` (`uptime / (uptime + downtime) * 100`, 1 decimal place) is computed on the frontend in `ReportDetailPage.tsx` (falling back to `100 - downtime_pct`) and highlighted in the summary strip and table.
20. **Attachment & Data Retention Policy (§4.9, §8)**: In accordance with NABH digital hospital management standards and Indian statutory medical equipment documentation regulations, all equipment service history, breakdown complaint logs, preventive maintenance records, calibration certificates, and uploaded files (PDF/JPG/PNG up to 10 MB) are retained for a minimum mandatory period of **7 years** from creation. Condemned and decommissioned equipment records are permanently maintained in read-only archive status and are never hard-deleted, ensuring unbroken historical auditability. Attachments are stored under `backend/data/uploads/` with UUID filenames and served strictly through authenticated, role-gated download endpoints. Automated backups (`backend/scripts/backup.py`) bundle both the database and attachments into timestamped archives with configurable rolling retention (default: 7 copies).
21. **Master Enums vs Editable Tables (§8)**: Critical operational dimensions — complaint `priority` (`critical`, `non_critical`), complaint `call_status` (`open`, `in_progress`, `closed`), equipment `status` (`in_service`, `under_repair`, `condemned`, `out_of_service`), and contract types (`AMC`, `CMC`, `OTHER`) — are intentionally implemented as strict code-enforced Python/TypeScript enums rather than dynamically editable master tables. This design protects the business calculation engine (downtime/uptime percentages, SLA timers, asset status transitions) against data corruption or undefined states that arbitrary user renames could cause.
22. **Client Sign-Off & Default Thresholds (§4.3, §4.8, §5, §6)**: The hospital administration configures and approves operational thresholds via the `/settings` management console:
- `critical_complaint_sla_hours`: default 4 hours.
- `non_critical_complaint_sla_hours`: default 24 hours.
- `escalation_open_complaint_hours`: default 24 hours.
- `contract_expiry_alert_days`: default 30 days (red critical threshold: 7 days).
- `calibration_due_window_days`: default 15 days.
- `pm_inhouse_lead_days`: default 7 days; `pm_outsourced_lead_days`: default 15 days.
- `require_closure_remarks`: default True.
- `downtime_milestone`: default `restoration` (downtime terminates when equipment is restored).
23. **Alert Recurrence & Notification Re-trigger Policy (§6)**: The alert engine runs daily at 06:00 Asia/Kolkata and employs deterministic deduplication keys (`dedupe_key`) to prevent duplicate in-app notifications on consecutive days while a condition remains active. Overdue alerts escalate in severity to `red`, and an optional repeat reminder interval (`alert_repeat_days`, default 3 days) re-notifies coordinators and biomedical teams until the underlying task (PM, calibration, contract renewal, or breakdown) is addressed. SMTP email dispatch can be enabled in settings when hospital IT confirms mail server credentials.
24. **Duplicate Record & Import Conflict Prevention (Task 1)**:
- **Contracts**: A duplicate contract is defined by `(asset_id, contract_type, start_date, end_date)` matching any existing contract in the database (including superseded ones). `POST /api/contracts` rejects exact duplicates with HTTP 409 (`A contract with the same asset, type and dates already exists.`). Contract renewals via `POST /api/contracts/{id}/renew` remain unaffected. In bulk import, in-file duplicate rows receive `Duplicate of row N in this file.` and rows duplicating database records receive `Already exists in the system.`.
- **Insurance Policies**: A duplicate insurance policy is defined by trimmed, case-insensitive `policy_no` matching any existing policy in the database. `POST /api/insurance` rejects duplicates with HTTP 409 (`Policy number already exists.`). In bulk import, in-file duplicate rows receive `Duplicate of row N in this file.` and rows duplicating database records receive `Already exists in the system.`.
- **Calibration Plans**: Each asset can have at most one calibration plan. In bulk import, rows for assets that already have a calibration plan in the database receive `Asset already has a calibration plan.`, while rows repeating an earlier row for the same asset in the same upload file receive `Duplicate of row N in this file.`. Dry run previews surface these validation errors identically.
25. **Import Template Multi-Sheet Structure (Task 2)**: All four bulk-import templates (Assets, Contracts, Calibration Plans, Insurance Policies) feature an empty data template on Sheet 1 (containing only styled headers), an 'Example' reference on Sheet 2 (with warning banner 'Example only - this sheet is ignored on import' in Row 1 and sample values in Row 2), and 'Master Reference' lookup tables on Sheet 3. All four importers read strictly the first worksheet (`wb.worksheets[0]`), ensuring sample rows and reference sheets are never accidentally imported.
26. **Backup Script Path Resolution & Dual Archive Packaging (Task 3)**: `backend/scripts/backup.py` exposes `get_db_path(db_url, backend_dir)` to accurately resolve SQLite file paths from `DATABASE_URL` across relative paths (`sqlite:///./data/ams.db`, `sqlite:///data/ams.db`), absolute POSIX/Windows paths (`sqlite:////app/data/ams.db`, `sqlite:////tmp/x/custom.db`), and in-memory or fallback scenarios. `create_backup()` supports both `.tar.gz` and `.zip` archives and packages SQLite database files under both `db.sqlite3` and `ams.db` member names for cross-environment compatibility.
27. **Universal Password Policy (Task 4)**: A unified validation rule (`validate_password`) is enforced across user registration, profile updates, self-service password changes, and administrator resets:
- Length: 8 to 128 characters.
- Character composition: at least one letter and at least one digit (case-insensitive; special characters permitted).
- Whitespace: leading and trailing spaces are strictly prohibited and rejected with HTTP 422 (never silently trimmed).
- Prohibited passwords: blocklist of common passwords (`123456`, `12345678`, `password`, `password1`, `qwerty123`, `admin123`, `welcome1`), while preserving `demo@123` for seeded testing environments.
- Username containment: cannot contain the user's email username (local part before `@`) if 4 or more characters.
- Password changes additionally require that the new password is not identical to the current password.
28. **Admin Reset Password Interface (Task 5)**: `frontend/src/api/users.ts` and `frontend/src/pages/MastersPage.tsx` expose an administrator password reset modal for users with role `system_admin`. The dialog features password masking toggles, client-side mismatch validation (`Passwords do not match`), universal password policy helper instructions, and displays backend 422 validation errors inline. Successful resets trigger a notification toast and close the modal without affecting the active administrator session.
29. **Department User Scoping & Empty Scope Resolution (Task 6)**: `backend/app/services/scoping.py` implements `resolve_department_scope(user, requested_dept_id)`. Non-department roles are unconstrained and may optionally filter by `requested_dept_id`. Assigned `department_user` accounts are strictly bound to `user.department_id`, ignoring any client-requested department parameter. Unassigned `department_user` accounts (`department_id=None`) resolve to `is_empty=True`, immediately returning 0 counters on Dashboard summary, empty results on global search, and empty row lists across all accessible report endpoints without running hospital-wide queries. Report key aliases are registered to support both canonical paths and audit identifiers (e.g., `equipment-inventory`, `condemned-equipment`, `pm-schedule`).
30. **Token Versioning & Session Invalidation (Task 7)**: A `token_version` integer column (default 0, not null) is added to `users` and reconciled automatically via `run_sqlite_migrations`. Access tokens encode the user's `token_version` in claim `"tv"`. `get_current_user` rejects tokens with mismatched `"tv"` with HTTP 401 (`Token has been invalidated. Please log in again.`). Password changes and administrator password resets increment `user.token_version`, invalidating previous tokens. `POST /api/auth/change-password` returns a renewed access token, and `ChangePasswordModal.tsx` stores the new token in the active auth store to keep the user's session active without re-login.
31. **Delivery Cleanliness, Line Endings & Packaging (Task 8)**: `.gitattributes` enforces standard LF line endings across the repository (`* text=auto eol=lf`). `.gitignore` excludes all SQLite databases (`*.db`), backups, volatile uploads, frontend dist artifacts, and build info files. The `make package` target generates `../poona-ams-delivery.zip` using `git archive` to ensure zero uncommitted, ignored, or temporary files leak into handoff archives.
32. **Cost Fields & Role-Based Stripping (AI Task 1)**: The fields `purchase_value`, `monthly_rent`, `contract_value`, `cost_per_visit`, `repair_cost`, and `spare_cost_estimate` are classified as cost fields. For `department_user`, these keys are completely stripped from JSON responses across `/api/assets`, `/api/contracts`, `/api/pm/schedules`, and `/api/complaints` via `maybe_strip_costs_response`. For contract bulk imports, both the canonical `contract_value` header and legacy `cost` alias are accepted for backward compatibility. `settings_service` supports a typed `float` setting type for `default_salvage_pct` (0–50) and `replacement_review_ratio` (0.05–2.0).
33. **AMC/CMC Auto-Tagging & Outsourced PM Auto-Fill (AI Task 2)**: Coverage precedence is strictly `active warranty > active CMC > active AMC > active OTHER contract > out_of_contract` where active means `start_date <= on_date <= end_date` and `is_superseded == False`. When registering a complaint, coverage is snapshotted as of `effective_today(db)` into `coverage_tag`, `coverage_contract_id`, and `coverage_provider_id` so historical registration coverage remains immutable even after contracts expire, while `coverage_now` always reflects live coverage. Creating an outsourced PM schedule without `provider_id`/`contract_id` auto-fills them from the asset's highest-priority active AMC/CMC contract (CMC over AMC); if none exists, the schedule is still created with empty provider/contract and `"no_active_contract": true` warning (replacing the legacy 422 rejection).
34. **Metrics Engine Formulas & Edge Cases (AI Task 3)**:
- *Depreciation*: Uses `years_elapsed = max(0, (as_of - (installation_date or purchase_date)).days / 365.25)`. For `written_down` with `salvage_pct == 0`, an effective salvage floor ratio of `0.01` is used to compute the declining-balance rate while clamping book value at 0. Rented assets return `applicable=False, reason="rented"`.
- *Scenario Comparison*: For 1-year contracts spanning 364–366 days inclusive, `contract_years = 1.0` so annual contract cost equals the contract value cleanly without leap-day distortion. When the latest contract is `CMC`, `spare_cost_estimate` is excluded from Scenario B's annual breakdown cost while `repair_cost` is retained (CMC covers spare parts). Missing required inputs mark that scenario `"Insufficient data: <input>"` and never coerce to zero. **"Latest equipment"** is defined as the top `latest_equipment_count` assets (default `10`, configurable 3–50) ordered by most recent `installation_date` (falling back to `purchase_date`) within the active department/category filter.
- *Efficiency*: Weights are centralized in `EFFICIENCY_WEIGHTS` (`uptime=0.50, pm_compliance=0.20, response=0.15, repeat_free=0.15`). Condemned assets are excluded from operational efficiency (matching Monthly Maintenance). When an asset has zero PM records due in the selected period or zero attended complaints, its PM compliance or response sub-score defaults to 100.0 so assets without scheduled PM or breakdowns are not penalized. Department and category efficiency scores are weighted averages of their assets weighted by scheduled operating minutes.
35. **AI Provider Layer, Grounding Validation, Privacy & Caching (AI Task 5)**:
- *Privacy*: `build_prompt()` strictly whitelists only structured metric fields (`id`, `label`, `value`, `unit`, `formatted`) and structured suggestion fields (`id`, `rule`, `severity`, `asset_codes`, `evidence_metric_ids`, `action_for_human`), stripping any extra keys and redacting email patterns so user names, emails, complaint descriptions, and free-text remarks are never transmitted to any model. Prompts and responses are never logged at `INFO` level.
- *Number Grounding Check*: Before extracting numeric values from model output for 0.5% tolerance verification against evidence, known asset codes (`PHRC-DEPT-0001`), metric IDs (`m_...`), and rule codes (`S1`–`S8`) are stripped so identifier digits are not misclassified as invented numbers.
- *Cache Key*: `ai_summaries` caches narratives keyed by `(section, filters_hash, data_hash)` where `filters_hash` incorporates the active AI mode/provider/model so toggling `ai_enabled` or switching local models automatically refreshes narratives without stale cross-mode hits. Every write creates an `AuditLog` entry (`entity_type="ai_summary"`).
36. **AI Reporting API & 3-Sheet Excel Exports (AI Task 6)**: All `/api/ai/*` endpoints enforce role access via `require_roles(system_admin, biomedical, management, coordinator)` so `department_user` receives HTTP 403 across all AI routes (including status and exports), while `POST /api/ai/narrative/regenerate` is restricted strictly to `system_admin`. Both hyphenated (`breakdown-frequency`) and underscored (`breakdown_frequency`) section keys are accepted on regenerate and export endpoints. Excel exports reuse `services/exports.py` styling and `_sanitize_sheet_title` to produce 3 sheets: the main report sheet, `"Evidence"`, and `"How calculated"`.
37. **AI Report UI Navigation, Asset Links & Settings Grouping (AI Task 7)**: Sidebar retains a single `Reports` navigation entry; switching between Simple reports and AI report is handled via a segmented toggle on `ReportsPage` and `AIReportPage` (hidden for `department_user`, with `/reports/ai` guarded by `RoleGuard capability="view_ai_reports"`). Suggestion asset code badges link directly to `/assets/:id` when the asset is present in loaded section rows, falling back to `/assets?search=<code>`. On `SettingsPage`, the 9 cost/AI settings are grouped under `"AI and cost analysis"` alongside a read-only runtime status banner fetched from `/api/ai/status`.
+77
View File
@@ -0,0 +1,77 @@
# Poona Hospital AMS — 10-Minute End-to-End Demo Script
**Prerequisites**:
1. Run `python -m app.seed.seed` inside `backend/` to load realistic hospital demo data (60 assets, 30 complaints, 45 PM schedules, 20 calibration plans, 35 contracts, 20 warranties, 25 insurance policies, 3 demo items, 12 department visits, and 26 alerts).
2. Start backend (`uvicorn app.main:app --port 8000`) and frontend (`npm run dev` on `http://localhost:5173`), or run `docker compose up --build`.
3. All demo accounts use password **`Demo@123`**:
- **System Admin**: `admin@poona.demo`
- **Biomedical Engineer**: `bio@poona.demo`
- **Department User (ICU)**: `dept@poona.demo`
- **Management**: `mgmt@poona.demo`
- **Coordinator**: `coord@poona.demo`
---
## Step 1 — Login, Role Overview & Calibration Pop-up (1 min)
1. Open `http://localhost:5173/login`. Use Quick Demo Login or sign in as **Biomedical** (`bio@poona.demo` / `Demo@123`).
2. Observe the **Calibration Reminder Pop-up** (`CalibrationReminderModal`) surfacing upcoming/due/overdue calibrations once per login. Click **Go to Calibration** or dismiss it.
3. Point out the role-filtered sidebar (no Masters/Settings/Audit Log for Biomedical).
## Step 2 — Hospital Operations Dashboard & Global Quick Search (1 min)
1. On `/` (`DashboardPage`), review the 7 clickable KPI cards, the 4 Recharts visualizations (Complaints by Status, Complaints by Department, 6-Month Downtime Trend, PM Planned vs Completed), **Needs Attention**, and **Recent Complaints**.
2. In the TopBar search box, type `PHRC` or `Ventilator`. Observe the grouped **Assets** and **Complaints** dropdown; click an asset to jump directly to `/assets/:id`.
## Step 3 — Asset Register, 8-Tab Detail & Insurance Drawer (1 min)
1. Navigate to `/assets` and open an ICU asset (`/assets/:id`).
2. Walk through the tabs (**Overview**, **Contracts**, **Warranty**, **Insurance**, **PM**, **Calibration**, **Complaints**, **Documents**).
3. Click **View Insurance** to slide open `InsuranceDrawer` showing policy coverage in INR and attached policy PDF.
## Step 4 — Breakdown Complaint Lifecycle & Department Scoping (1.5 min)
1. Sign out and log in as **Department User (ICU)** (`dept@poona.demo` / `Demo@123`).
- Notice the ICU-scoped dashboard banner and asset/complaint lists limited to ICU.
- Click **Raise Complaint** (`/complaints`), select an ICU asset using `AssetPicker` (note warranty/coverage badge), enter a breakdown description, attach an image/PDF, and submit.
- Open a complaint detail (`/complaints/:id`) and point out the **read-only lock banner** on the Technical / CE / Spares section (`FORBIDDEN_TECHNICAL_FIELDS` for non-biomedical/admin roles).
2. Switch to **Biomedical** (`bio@poona.demo`), open the newly raised complaint, assign/attend/restore it, enter technical action & spares, and close it with closure remarks—confirm `Asset.status` syncs back to `in_service` and downtime is calculated in IST.
## Step 5 — Preventive Maintenance Table & Calendar Views (1 min)
1. Open `/pm` (`PMPage`). Review the KPI strip and toggle between **Table View** and the **7-column Mon–Sun Month Calendar View**.
2. Complete a due PM item (auto-advances next cycle using clamped `add_months`) or reschedule an upcoming PM item.
## Step 6 — Calibration Plan Approval Gate (1 min)
1. Open `/calibration` (`CalibrationPage`) as **Biomedical** (`bio@poona.demo`). Note that creating/completing calibrations (with certificate PDF upload) is enabled, whereas frequency approval controls are gated (`FORBIDDEN_CALIBRATION_APPROVAL`).
2. Switch to **Management** (`mgmt@poona.demo`) or **Coordinator** (`coord@poona.demo`) to approve a calibration plan's frequency.
## Step 7 — Contracts Renewal Chain, Warranties, Demo Equipment & Visits (1 min)
1. Open `/contracts` (`/contracts`) and renew an expiring AMC/CMC contract—observe the superseded badge on the prior contract and the intact renewal history chain.
2. Open `/demo-equipment` to view active vs overdue trial equipment and log a return.
3. Open `/visits` as **Biomedical** (`bio@poona.demo`) to review/log a department round linked to multiple assets and complaints; verify `dept@poona.demo` / `coord@poona.demo` cannot access `/visits`.
## Step 8 — Demo Clock ("As of Date") & Live Alert Engine (1 min)
1. Log in as **System Admin** (`admin@poona.demo`).
2. Use the TopBar **"As of Date"** Demo Clock to advance the date by +20 days.
3. Click **Run alert check now** in `/settings` (or `/notifications`), watch new deduplicated notifications appear in the TopBar bell counter and `/notifications` inbox, then reset Demo Date back to real time.
## Step 9 — 8 Operational Reports, Formula Transparency & Excel/CSV/Print (1 min)
1. Open `/reports` (`ReportsPage`) and click **Monthly Maintenance Summary** (`/reports/monthly-maintenance`).
2. Inspect the **"How this is calculated"** formula popover (`scheduled_hours_per_day`, `downtime_end_milestone`, `clip_downtime_to_month`), Recharts BarChart/PieChart, export `.xlsx` and `.csv`, and trigger **Print (A4)** preview.
## Step 10 — Audit Log Viewer & Rate-Limit Protection (0.5 min)
1. As **System Admin** (`admin@poona.demo`), open `/audit-logs` (`AuditLogsPage`) to filter historical entity mutations by Entity Type, User, Action, Date Range, and search query, and inspect the JSON diff modal.
2. Confirm `/audit-logs` is restricted to `system_admin` only (`403` for other roles) and `POST /api/auth/login` enforces sliding-window rate limiting (`429 RATE_LIMITED`).
---
## Step 11 — AI Report, Cost Analysis & AMC/CMC Auto-Tagging (2 min)
1. **Coverage Tag on a New Complaint (25 sec)**:
- Open `/complaints`, click **Raise Complaint**, and pick an ICU asset in `AssetPicker` (e.g. `PHRC-ICU-0001`).
- Point out the live **Coverage Badge** (`Under Warranty`, `Under CMC`, `Under AMC`, or `Out of Contract`) and hover to show `"Call: <vendor>, <contact>"`. Submit the complaint and show that the coverage tag is snapshotted on the complaint detail page and timeline.
2. **Switch to AI Report (15 sec)**:
- Open `/reports` as **Management** (`mgmt@poona.demo`) or **System Admin** (`admin@poona.demo`) and click the **"AI report"** side of the `"Simple reports | AI report"` segmented toggle (note that `dept@poona.demo` does not see this toggle).
- Point out the top status chip (`Rule-based summary` by default, or `AI: local model <name>` when Ollama is active).
3. **Repeat-Failure & Replacement Suggestions (25 sec)**:
- Scroll to the top **Suggestions** panel. Highlight a red **S1 Repeat Failure** card and an **S4 Replacement Review** card, expand **Supporting evidence** to show the exact metric IDs and values, click an asset code link, and note that every suggestion ends with `"Needs a human decision."`.
4. **Comparison Table (25 sec)**:
- Scroll to **1. Comparison: in-house vs outsourced vs rent**. Show the 10 latest equipment rows comparing 5-year In-House vs Outsourced (AMC/CMC) vs Rent costs in INR, the highlighted lowest-cost option, difference vs next option, and any grey `"Insufficient data: <input>"` cells.
5. **Depreciation Example & Rule-Based vs AI Summary (30 sec)**:
- Scroll to **2. Depreciated price and cost analysis**. Click an asset row to display its Book Value curve over useful life and point out red maintenance-ratio flags (≥ 40%).
- Open **Evidence** and **How this is calculated** on any section, and demonstrate the **Rule-based summary** badge (plus **Regenerate summary** as `admin@poona.demo`, and if Ollama is enabled in `/settings`, show an `AI summary` badge or automatic fallback). Export Excel (`.xlsx`) to show the 3 sheets: main report, `Evidence`, and `How calculated`.
+30
View File
@@ -0,0 +1,30 @@
# Poona Hospital AMS — Implementation Plan Summary
**Status:** Phases 0–8 complete, plus Excel exports / bulk import / responsive layout as of commit `22fad38`.
For local development, Docker Compose, seeding, and test commands, see [README.md](../README.md).
## Tech Stack
| Layer | Technology |
|---|---|
| Backend API | FastAPI + Pydantic v2 (`Python 3.13`, `uvicorn`) |
| Database & ORM | SQLAlchemy 2.0 (`SQLite` with indexed 19-table schema) |
| Authentication & Security | JWT (`python-jose`), `bcrypt`, 5-role RBAC, sliding-window login rate limiter |
| Background Scheduler | `APScheduler` (`06:00` daily alert evaluation job) |
| Exports & Bulk Import | `openpyxl` (styled `.xlsx` reports & 2-sheet import template), `csv`, SheetJS (`xlsx`) |
| Frontend UI | React 18, TypeScript, Vite, Tailwind CSS, shadcn/ui, TanStack Query & Table, Recharts |
| Packaging & Docs | Docker, Nginx reverse proxy, `docker-compose.yml`, Demo Script & Acceptance Checklist |
| Testing | `pytest` + `httpx` (`ASGITransport`), `Vitest` + React Testing Library |
## Phases Overview (0–8)
- **Phase 0 — Scaffold:** Project layout, FastAPI health endpoint, React + Vite + Tailwind + shadcn/ui shell, Makefile.
- **Phase 1 — Auth, Masters & Settings:** JWT login/me, 5-role RBAC matrix, Admin Master Lists CRUD, typed System Settings, and `seed.py`.
- **Phase 2 — Asset Register & Attachments:** Full Asset CRUD (`409` duplicate check), `AssetPicker`, department scoping, magic-byte validated attachments.
- **Phase 3 — Breakdown & Complaint Lifecycle:** Sequential `complaint_no`, IST response/downtime calculations (`clip_downtime_to_month`), workflow transitions & technical-field locks.
- **Phase 4 — Preventive Maintenance & Calibration:** In-house/outsourced PM table & 7-column calendar views, clamped `add_months`, gated calibration approval & certificates.
- **Phase 5 — Contracts, Warranties, Insurance, Demo & Visits:** Contract renewal chain (`is_superseded`), warranties, insurance drawer, overdue demo equipment, department visit rounds.
- **Phase 6 — Notifications, Alerts & Dashboard:** Daily `APScheduler` 7-type deduplicated alerts, TopBar Demo Clock, calibration login modal, and role-scoped Recharts dashboard.
- **Phase 7 — Operational Reports & Exports:** 8 operational reports with formula transparency, `daily-visit` RBAC, server-side `.xlsx`/`.csv` exports, and A4 `@media print`.
- **Phase 8 — Polish & Packaging:** Global quick search (`/api/search`), Admin audit log viewer (`/api/audit-logs`), DB indexes, login rate limiting, Docker Compose, and demo/acceptance docs.
+136
View File
@@ -0,0 +1,136 @@
# Poona Hospital AMS — Role-Based User Guide
Welcome to the Poona Hospital Asset Management & Maintenance System. This quick-start guide details the day-to-day operations, permissions, and typical workflows for each user role.
All demo accounts share the password: `Demo@123`
---
## 1. System Administrator (`admin@poona.demo`)
The System Administrator oversees system security, reference masters, user access, and global configuration.
### Key Capabilities
- **Master Data Management (`/masters`)**: Maintain active Departments, Physical Locations, Equipment Categories, Vendors/Suppliers, and System Users. Masters use soft deletion to preserve historical linkage.
- **Admin Password Reset**: Admins can click "Reset password" on any user row on the Users tab to set a new password directly from the UI. Resetting invalidates all existing active sessions of that user immediately via token versioning.
- **Universal Password Policy**: Passwords must be 8–128 characters, contain at least one letter and one number, have no leading/trailing spaces, avoid common blocklisted passwords, and cannot contain the user's email username.
- **System Settings (`/settings`)**: Configure hospital-wide business rules:
- SLA thresholds (`critical_complaint_sla_hours`, `non_critical_complaint_sla_hours`)
- Alert lead times for Contracts, PM, Calibration, Insurance, and Demo Equipment
- Mandatory closure remarks toggle (`require_closure_remarks`)
- Downtime calculation milestone (`attendance`, `restoration`, or `closure`)
- Demo Clock (`demo_as_of_date`) to simulate future dates for testing alerts
- **Audit Logs (`/audit-logs`)**: Search, filter, and inspect detailed JSON diffs of all system mutations and user actions.
- **Bulk Imports & Duplicate Prevention**:
- Download official templates for Assets, Contracts, Calibration Plans, and Insurance Policies (templates include empty headers on Sheet 1 and example rows on Sheet 2).
- Exact duplicates in file uploads or direct creations (duplicate contracts with matching asset/type/dates, duplicate insurance policy numbers, or duplicate calibration plans per asset) are rejected with clear line-item error messages or HTTP 409 status.
- **Database Backup & Recovery**: Execute `python scripts/backup.py` to create a safe online snapshot (.tar.gz or .zip) of the database and uploaded attachments.
---
## 2. Biomedical Engineer (`bio@poona.demo`)
Biomedical Engineers handle physical medical assets, breakdown repairs, preventative maintenance schedules, and rounds.
### Key Workflows
- **Asset Registration & Maintenance (`/assets`)**:
- Register new medical equipment with full technical, procurement, warranty, and vendor details.
- View comprehensive 8-tab overview for any asset (PM, Calibration, Contracts, Insurance, History).
- **Breakdown Complaint Management (`/complaints`)**:
- Attend assigned complaints and log attendance timestamps.
- Document technical actions: Company Engineer (CE) details, action taken, spare parts required, root cause, and corrective action.
- Mark equipment as **Restored** when functioning (automatically returning asset to `in_service`).
- Close complaints with mandatory closure remarks.
- **Preventive Maintenance (`/pm`)**:
- View planned PM in Table or 7-column Calendar views.
- Execute PM records, attach vendor service reports/job sheets, and automatically advance next planned cycle.
- **Department Rounds (`/visits`)**:
- Conduct daily/weekly rounds, inspect equipment by department, log observations, note new equipment requirements, and link or spawn breakdown complaints directly from the visit sheet.
---
## 3. Department User (`dept@poona.demo` — ICU)
Department Users (Nurses, In-charges, Technicians) raise and monitor breakdown calls for their own department.
### Key Workflows
- **Scoped View**: Automatically restricted to seeing only assets and complaints belonging to their assigned department (e.g., ICU).
- If a department user account is created without an assigned department (`department_id=None`), the user is scoped to an empty dataset by default (seeing zero assets, zero complaints, and zero dashboard metrics) to prevent unintended access to hospital-wide data.
- **Raising Complaints (`/complaints`)**:
- Click **Raise Complaint**, search for the faulty equipment using `AssetPicker` (which highlights warranty and condemnation status), choose Priority (`Critical` or `Non-Critical`), and enter the problem description.
- Attach photos or fault screenshots directly.
- **Tracking Progress**:
- Monitor real-time status chips (`Open`, `In Progress`, `Closed`).
- View assignment details and attendance timestamps.
- Technical engineering fields, spare parts costs, and master configurations are safely locked (read-only).
---
## 4. Management (`mgmt@poona.demo`)
Hospital Management (Medical Superintendent, Directors, Quality Heads) review operational performance, KPIs, and reports.
### Key Capabilities
- **Hospital Operations Dashboard (`/`)**:
- High-level KPI summary: Total Assets, Equipment Under Repair, Open Complaints, Critical Breakdown Calls, and PM Compliance rate.
- Interactive charts: Complaints by Status, Complaints by Department, 6-Month Downtime Trend, and PM Performance.
- Clickable "Needs Attention" list highlighting urgent overdue items.
- **Calibration Plan Approvals (`/calibration`)**:
- Review and approve calibration frequencies set on critical biomedical equipment (gated specifically to Management and Administration).
- **8 Operational Reports (`/reports`)**:
- Monthly Maintenance Summary with downtime minutes and Uptime % calculations.
- Monthly Department Performance, PM Compliance, Calibration Due, AMC/CMC Validity, and Breakdown Analytics.
- One-click Excel spreadsheet (`.xlsx`) export and print-ready A4 landscape layouts.
---
## 5. Clinical Coordinator (`coord@poona.demo`)
Coordinators manage legal contracts, equipment warranties, insurance coverage, and loaner/demo devices.
### Key Workflows
- **Contracts & Warranties (`/contracts`)**:
- Register AMC and CMC service agreements, coverage periods, and vendor contacts.
- Upload signed contract PDFs or warranty certificates.
- Renew expiring contracts with automatic superseding of prior contracts and full history chain retention.
- **Asset Insurance (`/insurance`)**:
- Record policy numbers, insurance companies, coverage sums in INR, and effective dates.
- Quick-access **Insurance Drawer** lets users inspect policy details directly from any asset or breakdown record.
- **Demo & Trial Equipment (`/demo-equipment`)**:
- Track evaluation and trial machines on loan from vendors.
- Record serial numbers, trial durations, expected return dates, and log official returns.
- **Notifications & Expiry Alerts (`/notifications`)**:
- Receive automated 30-day advance alerts for expiring contracts, warranties, and insurance policies.
---
## 6. Cost Inputs, AMC/CMC Auto-Tagging & AI Report
### Cost Fields & Role Visibility
- Assets support `acquisition_mode` (`purchased` or `rented`), `monthly_rent` (INR/month), `useful_life_years`, `salvage_pct` (0–50%), and `depreciation_method` (`straight_line` or `written_down`). Categories support `default_useful_life_years`, Contracts store `contract_value` (INR), PM schedules store `cost_per_visit` (INR), and Breakdown Complaints store `repair_cost` (INR, restricted to Biomedical and System Admin alongside technical fields).
- **Role Access**: Cost fields are visible to `system_admin`, `biomedical`, `management`, and `coordinator`, and are automatically stripped from all API responses for `department_user`. Editing cost fields is restricted to `system_admin` and `biomedical` (`coordinator` may edit `contract_value` on contracts only).
### AMC / CMC Auto-Tagging
- Every asset, breakdown complaint, and PM schedule automatically displays a color-coded **Coverage Badge** (`Under Warranty` blue, `Under CMC` green, `Under AMC` teal, `Other Contract` grey, `Out of Contract` red) with a hover tooltip showing `"Call: <vendor>, <contact>"`.
- Precedence is strictly: **Active Warranty > Active CMC > Active AMC > Active OTHER Contract > Out of Contract**.
- When a breakdown complaint is registered, the live coverage tag, contract, and provider are snapshotted onto the complaint and logged to its event timeline. Creating an outsourced PM schedule auto-fills the active AMC/CMC contract and service provider (or surfaces a `"No active contract"` warning if none exists).
### AI Report & Cost Analysis (`/reports/ai`)
- Available via the **"Simple reports | AI report"** toggle on `/reports` for `system_admin`, `biomedical`, `management`, and `coordinator` (`department_user` gets HTTP `403` and sees no toggle).
- All numbers are computed deterministically by Python code; any connected language model only writes narrative words about pre-computed evidence and is strictly checked against the underlying numbers and banned decision words.
- Includes a top **Suggestions** panel (rules `S1`–`S8` with red/yellow/info severity and `"Needs a human decision."`) and four numbered sections:
1. **Comparison: in-house vs outsourced vs rent** (latest equipment cost table, grouped bar chart, grey `"Insufficient data: ..."` cells).
2. **Depreciated price and cost analysis** (book value, accumulated depreciation, maintenance ratio highlighted red above threshold, lifetime cost, interactive book-value curve).
3. **Efficiency** (uptime %, MTTR, MTBF, PM compliance %, composite 0–100 score, stacked department chart).
4. **Breakdown frequency and average breakdowns** (total breakdowns, average per equipment, repeat-failure count, top-10 table, monthly trend & department/category bar chart).
- Every section includes a narrative card (`Rule-based summary` or `AI summary`), an **Evidence** accordion, a **How this is calculated** formula popover, styled 3-sheet Excel (`.xlsx`) & CSV exports (main sheet, `Evidence`, `How calculated`), and A4 Print support. `system_admin` also sees a **Regenerate summary** button.
### Enabling an Optional Local AI Model
- By default (`AI_PROVIDER=none`), the application uses fast, deterministic rule-based summaries with zero external dependencies.
- To enable local AI narratives on hospital-controlled infrastructure:
1. Run a local model server such as [Ollama](https://ollama.com) (`ollama pull llama3.2`) or a local OpenAI-compatible endpoint.
2. Set `AI_PROVIDER=ollama` (or `openai_compatible`), `AI_BASE_URL=http://localhost:11434`, and `AI_MODEL=<installed-model>` in `.env` (or `docker-compose.yml`) and restart the backend.
3. Log in as `system_admin`, open `/settings`, scroll to **AI and cost analysis**, confirm **Provider Reachable** shows `Yes`, toggle **Enable AI Narrative (`ai_enabled`)** on, and save.
4. If the local server stops, times out, or produces an ungrounded number, the app automatically falls back to the rule-based summary and displays a small rejection warning without failing the page.