diff --git a/README.md b/README.md index 5b4973e..3014dd9 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,7 @@ docker compose up --build - Admin Master Lists CRUD (`/masters`: Departments, Locations, Categories, Vendors, Users) and Audit Log Viewer (`/audit-logs`, `system_admin` only with entity/user/action/date filters and JSON diff modal) - Typed System Settings (`/settings`) and TopBar "As of Date" Demo Clock (`POST /api/settings/demo-date`) + Admin `"Run alert check now"` (`POST /api/alerts/run`) - Live Global Quick Search in TopBar (`GET /api/search?q=`) returning grouped Assets & Complaints with `department_user` scoping -- Asset Register (`/assets` & `/assets/:id`): full CRUD with duplicate asset code check (`409`), department scoping, coordinator field-level edit restrictions, 8-tab Asset Detail Overview, and audit logging +- Asset Register (`/assets` & `/assets/:id`): full CRUD with duplicate asset code check (`409`), department scoping, coordinator field-level edit restrictions, 8-tab Asset Detail Overview, audit logging, and Bulk Asset Import (`GET /api/assets/import-template` Excel template with `Master Reference` sheet + `POST /api/assets/bulk-import` dry-run validation preview & skip-invalid option) - Breakdown & Complaint Register (`/complaints` & `/complaints/:id`): sequential complaint numbering, `AssetPicker` raise modal with multi-file attachments, response time & ongoing/milestone downtime calculations, assign/attend/restore/close/reopen workflow with asset status sync, event timeline, admin timestamp correction, and role-enforced technical/CE/spares section (`FORBIDDEN_TECHNICAL_FIELDS` 403 + read-only lock banner) - Preventive Maintenance (`/pm`): in-house & outsourced PM schedules (`/api/pm/schedules`), dynamic read-time `upcoming`/`due`/`overdue`/`completed`/`rescheduled` status & severity evaluation against `effective_today()`, KPI summary strip, Table View & 7-column Mon–Sun Month Calendar View, Complete (auto-advancing next cycle via `add_months`) and Reschedule workflows, plus Asset Detail PM tab actions - Calibration (`/calibration`): single & bulk calibration plan creation (`/api/calibration/plans/from-asset/:assetId`, `/bulk-from-assets`), management/admin/coordinator-gated frequency edit & approval (`FORBIDDEN_CALIBRATION_APPROVAL` 403 for biomedical), dynamic read-time status/severity computation, completion with certificate file upload (`calibration_record` attachments) and auto-generated next due cycle, plus Asset Detail Calibration tab wiring @@ -93,11 +93,11 @@ docker compose up --build - Department Visits (`/visits`): biomedical/admin round logs with management read access (403 for `department_user` and `coordinator`), department-filtered multi-asset checklist, observations, and complaint creation/linking (`POST /api/visits/:id/link-complaint`) - Alert Engine, Scheduler & Notifications (`/notifications` + TopBar Bell & Calibration Login Pop-up): APScheduler `06:00 Asia/Kolkata` daily job using short-lived `get_scheduler_db()`, deduplicated 7-type alerts (`amc_expiry`, `calibration_due`, `pm_due`, `insurance_expiry`, `warranty_expiry`, `demo_overdue`, `critical_complaint`) evaluated against `effective_today()`/`effective_now_utc()`, per-user `NotificationRead` state with `department_user` entity-department filtering, 60s bell polling with live toast alerts, and once-per-login `CalibrationReminderModal` - Hospital Operations Dashboard (`/`): role-aware `department_scope` banner, 7 clickable KPI cards, 4 Recharts visualizations (Complaints by Status, Complaints by Department, 6-month `clip_downtime_to_month` Downtime Trend, PM Planned vs Completed), `"Needs Attention"` red alerts panel, and `"Recent Complaints"` table -- 8 Operational Reports & Exports (`/reports` & `/reports/:reportKey`): Monthly Maintenance (with `clip_downtime_to_month` uptime/downtime hours, `"How this is calculated"` `formula_info` panel, and Recharts BarChart + PieChart), Monthly Department, Daily Department Visit (403 for `department_user` & `coordinator`), Breakdown & Complaints, PM Compliance, Calibration Due, AMC/CMC & Warranty, and Demo Equipment reports; tailored filters, styled openpyxl Excel (`.xlsx`) & UTF-8 BOM CSV (`.csv`) exports (`/api/reports/{report_key}/export`), and A4 `@media print` styles (`no-print` / `print-header`) +- 8 Operational Reports & Excel Exports (`/reports` & `/reports/:reportKey`): Monthly Maintenance (with `clip_downtime_to_month` uptime/downtime hours, `"How this is calculated"` `formula_info` panel, and Recharts BarChart + PieChart), Monthly Department, Daily Department Visit (403 for `department_user` & `coordinator`), Breakdown & Complaints, PM Compliance, Calibration Due, AMC/CMC & Warranty, and Demo Equipment reports; tailored filters, styled openpyxl Excel (`.xlsx`) report exports (`/api/reports/{report_key}/export`), Excel (`.xlsx`) table exports across all `DataTable` views, and A4 `@media print` styles (`no-print` / `print-header`) - Reusable `AssetPicker` (`/api/assets/lookup`) with warranty/condemned status badges - Secure Document Attachments (`/api/attachments`: JPG/PNG/PDF validation with magic-byte check, 10 MB limit, authenticated preview/download, role-based upload/delete) - Idempotent deterministic seed script (`python -m app.seed.seed`) populating realistic hospital demo data -- Responsive React + TypeScript frontend app shell (mobile slide-over navigation, accessible ``, role-filtered sidebar, route guards, DataTable, Tailwind CSS + shadcn/ui) +- Responsive React + TypeScript frontend app shell across `360px+` mobile, `768px+` tablet, and `1280px+` desktop (wrapping TopBar, `lg:` drawer Sidebar, responsive modals & tabs, accessible ``, DataTable with Excel `.xlsx` export, Tailwind CSS + shadcn/ui) - Docker packaging (`docker-compose.yml`, `backend/Dockerfile`, `frontend/Dockerfile`, `frontend/nginx.conf`, `.env.example`) & `Makefile` ## Modules (Phases 0–8 Complete) diff --git a/backend/app/routers/assets.py b/backend/app/routers/assets.py index a8db01b..65b078e 100644 --- a/backend/app/routers/assets.py +++ b/backend/app/routers/assets.py @@ -1,6 +1,7 @@ from datetime import date from typing import Any, Optional -from fastapi import APIRouter, Depends, HTTPException, Query, status +from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile, status +from fastapi.responses import StreamingResponse from sqlalchemy import or_ from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session, joinedload @@ -44,6 +45,7 @@ from ..schemas.assets import ( PMScheduleSummaryOut, WarrantySummaryOut, ) +from ..services.asset_import import build_import_template_xlsx, process_asset_import from ..services.audit import log_audit from ..services.calculations import compute_schedule_status, coverage_status from ..services.permissions import Role @@ -506,6 +508,40 @@ def create_asset( return _to_asset_out(loaded, rels, effective_today(db), _lead_settings(db)) +@router.get("/import-template") +def download_asset_import_template( + db: Session = Depends(get_db), + _user: User = Depends(require_roles(Role.system_admin, Role.biomedical)), +): + buf = build_import_template_xlsx(db) + return StreamingResponse( + buf, + media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + headers={ + "Content-Disposition": 'attachment; filename="asset_import_template.xlsx"', + }, + ) + + +@router.post("/bulk-import") +def bulk_import_assets( + file: UploadFile = File(...), + dry_run: bool = Query(False), + skip_invalid: bool = Query(False), + db: Session = Depends(get_db), + current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)), +): + content = file.file.read() + return process_asset_import( + db=db, + filename=file.filename or "upload.xlsx", + content=content, + user_id=current_user.id, + dry_run=dry_run, + skip_invalid=skip_invalid, + ) + + @router.get("/{asset_id}", response_model=AssetOut) def get_asset( asset_id: int, diff --git a/backend/app/seed/seed.py b/backend/app/seed/seed.py index 9ebef2d..ede908b 100644 --- a/backend/app/seed/seed.py +++ b/backend/app/seed/seed.py @@ -89,6 +89,7 @@ def seed_database(db: Session, upload_dir: Path | None = None) -> dict[str, int] except Exception: pass db.flush() + db.expunge_all() # 2. Settings (14 keys) ensure_default_settings(db) diff --git a/backend/app/services/asset_import.py b/backend/app/services/asset_import.py new file mode 100644 index 0000000..63b1fbb --- /dev/null +++ b/backend/app/services/asset_import.py @@ -0,0 +1,475 @@ +import csv +from datetime import date, datetime +from io import BytesIO, StringIO +from pathlib import Path +from typing import Any + +import openpyxl +from openpyxl.styles import Font, PatternFill +from openpyxl.utils import get_column_letter +from sqlalchemy.orm import Session + +from ..core.exceptions import CodedHTTPException +from ..models import Asset, Category, Department, Location, Vendor +from .audit import log_audit + +IMPORT_COLUMNS = [ + "asset_code", + "serial_no", + "name", + "category", + "department", + "location", + "supplier", + "purchase_value", + "purchase_date", + "installation_date", + "status", + "criticality", + "requires_calibration", + "insurance_applicable", + "remarks", +] + +VALID_STATUSES = ("in_service", "under_repair", "out_of_service", "condemned") +VALID_CRITICALITIES = ("critical", "non_critical") + +_HEADER_FILL = PatternFill(start_color="1E3A8A", end_color="1E3A8A", fill_type="solid") +_HEADER_FONT = Font(color="FFFFFF", bold=True) + + +def _auto_fit_columns(ws, max_width: int = 42) -> None: + for col_idx in range(1, ws.max_column + 1): + max_len = 0 + for row_idx in range(1, ws.max_row + 1): + val = ws.cell(row=row_idx, column=col_idx).value + if val is not None: + max_len = max(max_len, len(str(val))) + ws.column_dimensions[get_column_letter(col_idx)].width = min(max(max_len + 4, 14), max_width) + + +def build_import_template_xlsx(db: Session) -> BytesIO: + wb = openpyxl.Workbook() + ws = wb.active + ws.title = "Assets" + + for col_idx, col_name in enumerate(IMPORT_COLUMNS, start=1): + cell = ws.cell(row=1, column=col_idx, value=col_name) + cell.fill = _HEADER_FILL + cell.font = _HEADER_FONT + ws.freeze_panes = "A2" + + departments = ( + db.query(Department) + .filter(Department.is_active.is_(True)) + .order_by(Department.code.asc()) + .all() + ) + locations = ( + db.query(Location) + .join(Department, Location.department_id == Department.id) + .filter(Location.is_active.is_(True), Department.is_active.is_(True)) + .order_by(Department.code.asc(), Location.name.asc()) + .all() + ) + categories = ( + db.query(Category) + .filter(Category.is_active.is_(True)) + .order_by(Category.name.asc()) + .all() + ) + vendors = ( + db.query(Vendor) + .filter(Vendor.is_active.is_(True)) + .order_by(Vendor.name.asc()) + .all() + ) + + sample_dept = departments[0] if departments else None + sample_loc = ( + next((loc for loc in locations if sample_dept and loc.department_id == sample_dept.id), None) + or (locations[0] if locations else None) + ) + sample_cat = categories[0] if categories else None + sample_sup = vendors[0] if vendors else None + + sample_row = [ + "PHRC-ICU-0901", + "SN-DEMO-901", + "Infusion Pump", + sample_cat.name if sample_cat else "Infusion Pump", + sample_dept.code if sample_dept else "ICU", + sample_loc.name if sample_loc else "ICU Bay 1", + sample_sup.name if sample_sup else "", + 125000, + "2025-01-15", + "2025-01-20", + "in_service", + "critical", + "true", + "false", + "Sample row - replace or remove before import", + ] + for col_idx, val in enumerate(sample_row, start=1): + ws.cell(row=2, column=col_idx, value=val) + _auto_fit_columns(ws) + + # Sheet 2: Master Reference + ref = wb.create_sheet(title="Master Reference") + headers_map = [ + (1, "Department Code"), + (2, "Department Name"), + (4, "Department Code"), + (5, "Location Name"), + (7, "Category Name"), + (9, "Supplier Name"), + (11, "Valid Statuses"), + (13, "Valid Criticality"), + ] + for col_idx, label in headers_map: + c = ref.cell(row=1, column=col_idx, value=label) + c.fill = _HEADER_FILL + c.font = _HEADER_FONT + ref.freeze_panes = "A2" + + dept_by_id = {d.id: d for d in departments} + for idx, d in enumerate(departments, start=2): + ref.cell(row=idx, column=1, value=d.code) + ref.cell(row=idx, column=2, value=d.name) + + for idx, loc in enumerate(locations, start=2): + d = dept_by_id.get(loc.department_id) + ref.cell(row=idx, column=4, value=d.code if d else "") + ref.cell(row=idx, column=5, value=loc.name) + + for idx, cat in enumerate(categories, start=2): + ref.cell(row=idx, column=7, value=cat.name) + + for idx, v in enumerate(vendors, start=2): + ref.cell(row=idx, column=9, value=v.name) + + for idx, st in enumerate(VALID_STATUSES, start=2): + ref.cell(row=idx, column=11, value=st) + + for idx, crit in enumerate(VALID_CRITICALITIES, start=2): + ref.cell(row=idx, column=13, value=crit) + + _auto_fit_columns(ref) + + buf = BytesIO() + wb.save(buf) + buf.seek(0) + return buf + + +def _clean_str(val: Any) -> str: + if val is None: + return "" + return str(val).strip() + + +def _parse_optional_date(val: Any, field_name: str) -> tuple[date | None, str | None]: + if val is None or (isinstance(val, str) and not val.strip()): + return None, None + if isinstance(val, datetime): + return val.date(), None + if isinstance(val, date): + return val, None + text = str(val).strip() + for fmt in ("%Y-%m-%d", "%d-%b-%Y"): + try: + return datetime.strptime(text, fmt).date(), None + except ValueError: + continue + return None, f"Invalid {field_name} '{text}' (expected YYYY-MM-DD or DD-MMM-YYYY)" + + +def _parse_bool(val: Any, field_name: str) -> tuple[bool, str | None]: + if val is None or (isinstance(val, str) and not val.strip()): + return False, None + if isinstance(val, bool): + return val, None + if isinstance(val, (int, float)) and val in (0, 1): + return bool(val), None + text = str(val).strip().lower() + if text in ("true", "yes", "1", "y"): + return True, None + if text in ("false", "no", "0", "n"): + return False, None + return False, f"Invalid {field_name} '{val}' (use true/false or yes/no)" + + +def _parse_optional_float(val: Any, field_name: str) -> tuple[float | None, str | None]: + if val is None or (isinstance(val, str) and not val.strip()): + return None, None + try: + parsed = float(val) + except (TypeError, ValueError): + return None, f"Invalid {field_name} '{val}' (must be a number)" + if parsed < 0: + return None, f"{field_name} cannot be negative" + return parsed, None + + +def _extract_rows(filename: str, content: bytes) -> list[tuple[int, dict[str, Any]]]: + ext = Path(filename or "").suffix.lower() + if ext not in (".xlsx", ".csv"): + raise CodedHTTPException( + status_code=400, + detail="Unsupported file type. Please upload an .xlsx or .csv file.", + code="INVALID_FILE_TYPE", + ) + + rows_out: list[tuple[int, dict[str, Any]]] = [] + if ext == ".xlsx": + try: + wb = openpyxl.load_workbook(BytesIO(content), data_only=True) + except Exception as exc: + raise CodedHTTPException( + status_code=400, + detail="Invalid Excel file. Please download and use the import template.", + code="INVALID_FILE_TYPE", + ) from exc + ws = wb["Assets"] if "Assets" in wb.sheetnames else wb.active + header_cells = next(ws.iter_rows(min_row=1, max_row=1, values_only=True), None) + if not header_cells: + return [] + headers = [_clean_str(h).lower().replace(" ", "_") for h in header_cells] + for row_idx, row_vals in enumerate(ws.iter_rows(min_row=2, values_only=True), start=2): + if all(v is None or _clean_str(v) == "" for v in row_vals): + continue + row_dict = { + headers[i]: (row_vals[i] if i < len(row_vals) else None) + for i in range(len(headers)) + if headers[i] + } + rows_out.append((row_idx, row_dict)) + else: + try: + decoded = content.decode("utf-8-sig") + except UnicodeDecodeError: + decoded = content.decode("latin-1") + reader = csv.reader(StringIO(decoded)) + header_row = next(reader, None) + if not header_row: + return [] + headers = [_clean_str(h).lower().replace(" ", "_") for h in header_row] + for row_idx, row_vals in enumerate(reader, start=2): + if all(_clean_str(v) == "" for v in row_vals): + continue + row_dict = { + headers[i]: (row_vals[i] if i < len(row_vals) else None) + for i in range(len(headers)) + if headers[i] + } + rows_out.append((row_idx, row_dict)) + return rows_out + + +def process_asset_import( + db: Session, + filename: str, + content: bytes, + user_id: int, + dry_run: bool = False, + skip_invalid: bool = False, +) -> dict[str, Any]: + raw_rows = _extract_rows(filename, content) + + departments = db.query(Department).filter(Department.is_active.is_(True)).all() + dept_lookup: dict[str, Department] = {} + for d in departments: + dept_lookup[d.code.strip().lower()] = d + dept_lookup[d.name.strip().lower()] = d + + locations = db.query(Location).filter(Location.is_active.is_(True)).all() + loc_lookup: dict[tuple[int, str], Location] = { + (loc.department_id, loc.name.strip().lower()): loc for loc in locations + } + + categories = db.query(Category).filter(Category.is_active.is_(True)).all() + cat_lookup: dict[str, Category] = {c.name.strip().lower(): c for c in categories} + + vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).all() + vendor_lookup: dict[str, Vendor] = {v.name.strip().lower(): v for v in vendors} + + existing_codes = { + code.strip().lower() for (code,) in db.query(Asset.asset_code).all() if code + } + seen_codes: set[str] = set() + + errors: list[dict[str, Any]] = [] + preview_rows: list[dict[str, Any]] = [] + valid_assets: list[Asset] = [] + + for row_idx, row_dict in raw_rows: + row_errors: list[str] = [] + + asset_code = _clean_str(row_dict.get("asset_code")) + serial_no = _clean_str(row_dict.get("serial_no")) + name = _clean_str(row_dict.get("name")) + cat_raw = _clean_str(row_dict.get("category")) + dept_raw = _clean_str(row_dict.get("department")) + loc_raw = _clean_str(row_dict.get("location")) + sup_raw = _clean_str(row_dict.get("supplier")) + remarks = _clean_str(row_dict.get("remarks")) or None + + for req_label, req_val in ( + ("asset_code", asset_code), + ("serial_no", serial_no), + ("name", name), + ("category", cat_raw), + ("department", dept_raw), + ("location", loc_raw), + ): + if not req_val: + row_errors.append(f"Missing required field '{req_label}'") + + if asset_code: + code_norm = asset_code.lower() + if code_norm in existing_codes: + row_errors.append(f"Duplicate asset_code '{asset_code}' already exists in database") + elif code_norm in seen_codes: + row_errors.append(f"Duplicate asset_code '{asset_code}' within import file") + seen_codes.add(code_norm) + + dept_obj = dept_lookup.get(dept_raw.lower()) if dept_raw else None + if dept_raw and dept_obj is None: + row_errors.append(f"Unknown active department '{dept_raw}'") + + loc_obj = None + if loc_raw and dept_obj is not None: + loc_obj = loc_lookup.get((dept_obj.id, loc_raw.lower())) + if loc_obj is None: + row_errors.append( + f"Unknown active location '{loc_raw}' in department '{dept_obj.name}'" + ) + + cat_obj = cat_lookup.get(cat_raw.lower()) if cat_raw else None + if cat_raw and cat_obj is None: + row_errors.append(f"Unknown active category '{cat_raw}'") + + sup_obj = None + if sup_raw: + sup_obj = vendor_lookup.get(sup_raw.lower()) + if sup_obj is None: + row_errors.append(f"Unknown active supplier '{sup_raw}'") + + purchase_value, val_err = _parse_optional_float(row_dict.get("purchase_value"), "purchase_value") + if val_err: + row_errors.append(val_err) + + purchase_date, pdate_err = _parse_optional_date(row_dict.get("purchase_date"), "purchase_date") + if pdate_err: + row_errors.append(pdate_err) + + installation_date, idate_err = _parse_optional_date( + row_dict.get("installation_date"), "installation_date" + ) + if idate_err: + row_errors.append(idate_err) + + status_raw = _clean_str(row_dict.get("status")) + status_val = status_raw.lower().replace(" ", "_") if status_raw else "in_service" + if status_val not in VALID_STATUSES: + row_errors.append(f"Invalid status '{status_raw}' (valid: {', '.join(VALID_STATUSES)})") + + crit_raw = _clean_str(row_dict.get("criticality")) + crit_val = crit_raw.lower().replace(" ", "_") if crit_raw else "non_critical" + if crit_val not in VALID_CRITICALITIES: + row_errors.append( + f"Invalid criticality '{crit_raw}' (valid: {', '.join(VALID_CRITICALITIES)})" + ) + + req_cal, cal_err = _parse_bool(row_dict.get("requires_calibration"), "requires_calibration") + if cal_err: + row_errors.append(cal_err) + + ins_app, ins_err = _parse_bool(row_dict.get("insurance_applicable"), "insurance_applicable") + if ins_err: + row_errors.append(ins_err) + + is_valid = len(row_errors) == 0 + err_text = "; ".join(row_errors) if row_errors else None + if not is_valid: + errors.append( + { + "row": row_idx, + "asset_code": asset_code or None, + "error": err_text, + } + ) + else: + valid_assets.append( + Asset( + asset_code=asset_code, + serial_no=serial_no, + name=name, + category_id=cat_obj.id, + department_id=dept_obj.id, + location_id=loc_obj.id, + supplier_id=sup_obj.id if sup_obj else None, + purchase_value=purchase_value, + purchase_date=purchase_date, + installation_date=installation_date, + status=status_val, + criticality=crit_val, + requires_calibration=req_cal, + insurance_applicable=ins_app, + remarks=remarks, + created_by_id=user_id, + updated_by_id=user_id, + ) + ) + + preview_rows.append( + { + "row": row_idx, + "asset_code": asset_code or None, + "serial_no": serial_no or None, + "name": name or None, + "category_name": cat_obj.name if cat_obj else (cat_raw or None), + "department_name": dept_obj.name if dept_obj else (dept_raw or None), + "location_name": loc_obj.name if loc_obj else (loc_raw or None), + "status": status_val, + "valid": is_valid, + "error": err_text, + } + ) + + created_count = 0 + if not dry_run: + if errors and not skip_invalid: + raise CodedHTTPException( + status_code=400, + detail=f"{len(errors)} row(s) failed validation.", + code="IMPORT_VALIDATION_ERRORS", + ) + if valid_assets: + db.add_all(valid_assets) + db.flush() + for a in valid_assets: + log_audit( + db, + entity_type="asset", + entity_id=a.id, + action="bulk_import", + changes={ + "asset_code": a.asset_code, + "name": a.name, + "department_id": a.department_id, + }, + user_id=user_id, + ) + db.commit() + created_count = len(valid_assets) + + return { + "dry_run": dry_run, + "total_rows": len(raw_rows), + "valid_count": len(valid_assets), + "error_count": len(errors), + "created_count": created_count, + "errors": errors, + "preview_rows": preview_rows, + } diff --git a/backend/tests/test_asset_bulk_import.py b/backend/tests/test_asset_bulk_import.py new file mode 100644 index 0000000..741b383 --- /dev/null +++ b/backend/tests/test_asset_bulk_import.py @@ -0,0 +1,227 @@ +from io import BytesIO + +import openpyxl +import pytest + +from app.models import Asset, AuditLog +from app.seed.seed import seed_database + + +@pytest.fixture(scope="module", autouse=True) +def seeded_bulk_import_db(db, tmp_path_factory): + upload_dir = tmp_path_factory.mktemp("bulk_import_test_uploads") + seed_database(db, upload_dir=upload_dir) + return upload_dir + + +def _auth_headers(client, email: str) -> dict[str, str]: + res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"}) + assert res.status_code == 200, res.text + return {"Authorization": f"Bearer {res.json()['access_token']}"} + + +def _make_xlsx_bytes(headers: list[str], rows: list[list[object]]) -> bytes: + wb = openpyxl.Workbook() + ws = wb.active + ws.title = "Assets" + ws.append(headers) + for r in rows: + ws.append(r) + buf = BytesIO() + wb.save(buf) + return buf.getvalue() + + +def test_import_template_download_and_rbac(client): + bio_headers = _auth_headers(client, "bio@poona.demo") + admin_headers = _auth_headers(client, "admin@poona.demo") + + for email in ("dept@poona.demo", "coord@poona.demo", "mgmt@poona.demo"): + h = _auth_headers(client, email) + assert client.get("/api/assets/import-template", headers=h).status_code == 403 + assert ( + client.post( + "/api/assets/bulk-import", + headers=h, + files={"file": ("assets.csv", b"asset_code\n", "text/csv")}, + ).status_code + == 403 + ) + + res = client.get("/api/assets/import-template", headers=bio_headers) + assert res.status_code == 200 + assert "spreadsheetml.sheet" in res.headers["content-type"] + assert 'filename="asset_import_template.xlsx"' in res.headers["content-disposition"] + + wb = openpyxl.load_workbook(BytesIO(res.content)) + assert "Assets" in wb.sheetnames + assert "Master Reference" in wb.sheetnames + ws = wb["Assets"] + headers = [ws.cell(row=1, column=i).value for i in range(1, 16)] + assert headers[:6] == ["asset_code", "serial_no", "name", "category", "department", "location"] + assert ws.freeze_panes == "A2" + + # Admin also allowed + assert client.get("/api/assets/import-template", headers=admin_headers).status_code == 200 + + +def test_bulk_import_dry_run_validation_and_commit(client, db): + bio_headers = _auth_headers(client, "bio@poona.demo") + + # Read a valid sample from template so we match real seeded department/location/category + tmpl_res = client.get("/api/assets/import-template", headers=bio_headers) + wb_tmpl = openpyxl.load_workbook(BytesIO(tmpl_res.content)) + ws_tmpl = wb_tmpl["Assets"] + headers = [ws_tmpl.cell(row=1, column=i).value for i in range(1, 16)] + cat_name = ws_tmpl.cell(row=2, column=4).value + dept_code = ws_tmpl.cell(row=2, column=5).value + loc_name = ws_tmpl.cell(row=2, column=6).value + sup_name = ws_tmpl.cell(row=2, column=7).value + + initial_count = db.query(Asset).count() + + # Mix: 2 valid rows + 1 invalid row (unknown department) + rows = [ + [ + "BLK-IMP-001", + "BLK-SN-001", + "Bulk Infusion Pump", + cat_name, + dept_code, + loc_name, + sup_name, + 95000, + "2025-02-01", + "2025-02-05", + "in_service", + "critical", + "yes", + "no", + "Dry run test row 1", + ], + [ + "BLK-IMP-002", + "BLK-SN-002", + "Bulk Syringe Pump", + cat_name, + dept_code, + loc_name, + "", + 45000, + "15-Feb-2025", + "", + "in_service", + "non_critical", + "false", + "true", + "Dry run test row 2", + ], + [ + "BLK-IMP-BAD", + "BLK-SN-BAD", + "Invalid Dept Equipment", + cat_name, + "NO_SUCH_DEPT", + loc_name, + "", + 10000, + "", + "", + "in_service", + "non_critical", + "false", + "false", + "", + ], + ] + xlsx_bytes = _make_xlsx_bytes(headers, rows) + + # 1. dry_run=true validates all 3 without inserting into DB + dry_res = client.post( + "/api/assets/bulk-import?dry_run=true", + headers=bio_headers, + files={ + "file": ( + "bulk_assets.xlsx", + xlsx_bytes, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ) + }, + ) + assert dry_res.status_code == 200, dry_res.text + dry_data = dry_res.json() + assert dry_data["dry_run"] is True + assert dry_data["total_rows"] == 3 + assert dry_data["valid_count"] == 2 + assert dry_data["error_count"] == 1 + assert dry_data["created_count"] == 0 + assert dry_data["errors"][0]["row"] == 4 + assert db.query(Asset).count() == initial_count + + # 2. dry_run=false & skip_invalid=false rejects with 400 IMPORT_VALIDATION_ERRORS + strict_res = client.post( + "/api/assets/bulk-import?dry_run=false&skip_invalid=false", + headers=bio_headers, + files={ + "file": ( + "bulk_assets.xlsx", + xlsx_bytes, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ) + }, + ) + assert strict_res.status_code == 400 + assert strict_res.json()["code"] == "IMPORT_VALIDATION_ERRORS" + assert db.query(Asset).count() == initial_count + + # 3. dry_run=false & skip_invalid=true imports the 2 valid rows and logs audit entries + skip_res = client.post( + "/api/assets/bulk-import?dry_run=false&skip_invalid=true", + headers=bio_headers, + files={ + "file": ( + "bulk_assets.xlsx", + xlsx_bytes, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ) + }, + ) + assert skip_res.status_code == 200, skip_res.text + skip_data = skip_res.json() + assert skip_data["created_count"] == 2 + assert skip_data["error_count"] == 1 + assert db.query(Asset).count() == initial_count + 2 + + created_asset = db.query(Asset).filter(Asset.asset_code == "BLK-IMP-001").first() + assert created_asset is not None + audit = ( + db.query(AuditLog) + .filter( + AuditLog.entity_type == "asset", + AuditLog.entity_id == created_asset.id, + AuditLog.action == "bulk_import", + ) + .first() + ) + assert audit is not None + + # 4. CSV import (all valid) + unsupported extension rejected + csv_bytes = ( + "asset_code,serial_no,name,category,department,location\n" + f"BLK-CSV-003,SN-CSV-003,CSV Patient Monitor,{cat_name},{dept_code},{loc_name}\n" + ).encode("utf-8") + csv_res = client.post( + "/api/assets/bulk-import?dry_run=false", + headers=bio_headers, + files={"file": ("assets.csv", csv_bytes, "text/csv")}, + ) + assert csv_res.status_code == 200, csv_res.text + assert csv_res.json()["created_count"] == 1 + + bad_ext = client.post( + "/api/assets/bulk-import", + headers=bio_headers, + files={"file": ("assets.txt", b"hello", "text/plain")}, + ) + assert bad_ext.status_code == 400 + assert bad_ext.json()["code"] == "INVALID_FILE_TYPE" diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 5f63bdd..ec8e509 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -33,6 +33,7 @@ "react-router-dom": "^6.28.0", "recharts": "^2.13.3", "tailwind-merge": "^2.5.4", + "xlsx": "^0.18.5", "zod": "^3.23.8", "zustand": "^4.5.5" }, @@ -3505,6 +3506,15 @@ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, + "node_modules/adler-32": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/adler-32/-/adler-32-1.3.1.tgz", + "integrity": "sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, "node_modules/agent-base": { "version": "7.1.4", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", @@ -3840,6 +3850,19 @@ ], "license": "CC-BY-4.0" }, + "node_modules/cfb": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cfb/-/cfb-1.2.2.tgz", + "integrity": "sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==", + "license": "Apache-2.0", + "dependencies": { + "adler-32": "~1.3.0", + "crc-32": "~1.2.0" + }, + "engines": { + "node": ">=0.8" + } + }, "node_modules/chai": { "version": "5.3.3", "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz", @@ -3943,6 +3966,15 @@ "node": ">=6" } }, + "node_modules/codepage": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/codepage/-/codepage-1.15.0.tgz", + "integrity": "sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", @@ -4000,6 +4032,18 @@ "dev": true, "license": "MIT" }, + "node_modules/crc-32": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz", + "integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==", + "license": "Apache-2.0", + "bin": { + "crc32": "bin/crc32.njs" + }, + "engines": { + "node": ">=0.8" + } + }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", @@ -4835,6 +4879,15 @@ "node": ">= 6" } }, + "node_modules/frac": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/frac/-/frac-1.1.2.tgz", + "integrity": "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, "node_modules/fraction.js": { "version": "4.3.7", "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz", @@ -6541,6 +6594,18 @@ "node": ">=0.10.0" } }, + "node_modules/ssf": { + "version": "0.11.2", + "resolved": "https://registry.npmjs.org/ssf/-/ssf-0.11.2.tgz", + "integrity": "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==", + "license": "Apache-2.0", + "dependencies": { + "frac": "~1.1.2" + }, + "engines": { + "node": ">=0.8" + } + }, "node_modules/stackback": { "version": "0.0.2", "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", @@ -7283,6 +7348,24 @@ "node": ">=8" } }, + "node_modules/wmf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wmf/-/wmf-1.0.2.tgz", + "integrity": "sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/word": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/word/-/word-0.3.0.tgz", + "integrity": "sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, "node_modules/word-wrap": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", @@ -7315,6 +7398,27 @@ } } }, + "node_modules/xlsx": { + "version": "0.18.5", + "resolved": "https://registry.npmjs.org/xlsx/-/xlsx-0.18.5.tgz", + "integrity": "sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==", + "license": "Apache-2.0", + "dependencies": { + "adler-32": "~1.3.0", + "cfb": "~1.2.1", + "codepage": "~1.15.0", + "crc-32": "~1.2.1", + "ssf": "~0.11.2", + "wmf": "~1.0.1", + "word": "~0.3.0" + }, + "bin": { + "xlsx": "bin/xlsx.njs" + }, + "engines": { + "node": ">=0.8" + } + }, "node_modules/xml-name-validator": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", diff --git a/frontend/package.json b/frontend/package.json index c8fc0fe..61d91f7 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -36,6 +36,7 @@ "react-router-dom": "^6.28.0", "recharts": "^2.13.3", "tailwind-merge": "^2.5.4", + "xlsx": "^0.18.5", "zod": "^3.23.8", "zustand": "^4.5.5" }, diff --git a/frontend/src/api/assets.ts b/frontend/src/api/assets.ts index f0cb4c6..51564aa 100644 --- a/frontend/src/api/assets.ts +++ b/frontend/src/api/assets.ts @@ -225,6 +225,35 @@ export interface AssetCreatePayload { export type AssetUpdatePayload = Partial; +export interface BulkImportErrorItem { + row: number; + asset_code: string | null; + error: string; +} + +export interface BulkImportPreviewRow { + row: number; + asset_code: string | null; + serial_no: string | null; + name: string | null; + category_name: string | null; + department_name: string | null; + location_name: string | null; + status: string | null; + valid: boolean; + error: string | null; +} + +export interface BulkImportResult { + dry_run: boolean; + total_rows: number; + valid_count: number; + error_count: number; + created_count: number; + errors: BulkImportErrorItem[]; + preview_rows: BulkImportPreviewRow[]; +} + export const assetsApi = { list: (params: AssetListParams = {}) => { const qs = new URLSearchParams(); @@ -251,4 +280,23 @@ export const assetsApi = { overview: (id: number) => api.get(`/assets/${id}/overview`), create: (data: AssetCreatePayload) => api.post("/assets", data), update: (id: number, data: AssetUpdatePayload) => api.patch(`/assets/${id}`, data), + downloadImportTemplate: async () => { + const { blob } = await api.downloadBlob("/assets/import-template"); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = "asset_import_template.xlsx"; + document.body.appendChild(a); + a.click(); + a.remove(); + URL.revokeObjectURL(url); + }, + bulkImport: (file: File, dryRun: boolean, skipInvalid: boolean) => { + const formData = new FormData(); + formData.append("file", file); + return api.upload( + `/assets/bulk-import?dry_run=${dryRun}&skip_invalid=${skipInvalid}`, + formData + ); + }, }; diff --git a/frontend/src/components/BulkAssetImportModal.tsx b/frontend/src/components/BulkAssetImportModal.tsx new file mode 100644 index 0000000..4972187 --- /dev/null +++ b/frontend/src/components/BulkAssetImportModal.tsx @@ -0,0 +1,373 @@ +import { useRef, useState } from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import { + Download, + FileSpreadsheet, + Upload, + CheckCircle2, + AlertCircle, + X, +} from "lucide-react"; +import { assetsApi, type BulkImportResult } from "@/api/assets"; +import { ApiError } from "@/api/client"; +import { Modal } from "@/components/ui/dialog"; +import { Button } from "@/components/ui/button"; +import { toast } from "@/components/ToastProvider"; +import { cn } from "@/lib/utils"; + +interface BulkAssetImportModalProps { + open: boolean; + onClose: () => void; +} + +const ACCEPTED_EXTS = [".xlsx", ".xls", ".csv"]; + +export function BulkAssetImportModal({ open, onClose }: BulkAssetImportModalProps) { + const qc = useQueryClient(); + const fileInputRef = useRef(null); + + const [selectedFile, setSelectedFile] = useState(null); + const [dragActive, setDragActive] = useState(false); + const [downloadingTemplate, setDownloadingTemplate] = useState(false); + const [validating, setValidating] = useState(false); + const [importing, setImporting] = useState(false); + const [skipInvalid, setSkipInvalid] = useState(false); + const [preview, setPreview] = useState(null); + const [errorMsg, setErrorMsg] = useState(null); + + function resetState() { + setSelectedFile(null); + setPreview(null); + setErrorMsg(null); + setSkipInvalid(false); + setValidating(false); + setImporting(false); + if (fileInputRef.current) fileInputRef.current.value = ""; + } + + function handleClose() { + if (importing) return; + resetState(); + onClose(); + } + + async function handleDownloadTemplate() { + setDownloadingTemplate(true); + setErrorMsg(null); + try { + await assetsApi.downloadImportTemplate(); + toast.success("Downloaded asset_import_template.xlsx"); + } catch (err) { + const msg = + err instanceof ApiError + ? err.detail + : "Failed to download import template."; + setErrorMsg(msg); + toast.error(msg); + } finally { + setDownloadingTemplate(false); + } + } + + async function handleFileSelect(files: FileList | null) { + if (!files || files.length === 0) return; + const file = files[0]; + const lower = file.name.toLowerCase(); + if (!ACCEPTED_EXTS.some((ext) => lower.endsWith(ext))) { + setErrorMsg("Unsupported file type. Please upload an .xlsx, .xls, or .csv file."); + setSelectedFile(null); + setPreview(null); + return; + } + + setSelectedFile(file); + setErrorMsg(null); + setPreview(null); + setSkipInvalid(false); + setValidating(true); + + try { + const result = await assetsApi.bulkImport(file, true, false); + setPreview(result); + } catch (err) { + const msg = + err instanceof ApiError + ? err.detail + : "Failed to validate import file."; + setErrorMsg(msg); + } finally { + setValidating(false); + } + } + + async function handleConfirmImport() { + if (!selectedFile || !preview) return; + setImporting(true); + setErrorMsg(null); + try { + const result = await assetsApi.bulkImport(selectedFile, false, skipInvalid); + await Promise.all([ + qc.invalidateQueries({ queryKey: ["assets"] }), + qc.invalidateQueries({ queryKey: ["dashboard"] }), + ]); + toast.success( + `Imported ${result.created_count} asset${result.created_count === 1 ? "" : "s"}` + ); + resetState(); + onClose(); + } catch (err) { + const msg = + err instanceof ApiError ? err.detail : "Bulk asset import failed."; + setErrorMsg(msg); + toast.error(msg); + } finally { + setImporting(false); + } + } + + const canImport = + Boolean(selectedFile && preview) && + !validating && + !importing && + preview!.valid_count > 0 && + (preview!.error_count === 0 || skipInvalid); + + return ( + { + if (!next) handleClose(); + }} + title="Bulk Import Assets" + description="Upload an Excel (.xlsx/.xls) or CSV spreadsheet to register multiple hospital assets at once." + className="max-w-4xl" + > +
+ {/* Step 1: Template Download */} +
+
+ +
+
+ Step 1: Download the Excel Template +
+

+ Fill equipment rows in the Assets sheet and check valid + departments, locations, categories, and suppliers in the{" "} + Master Reference sheet. +

+
+
+ +
+ + {/* Step 2: File Picker / Dropzone */} +
{ + e.preventDefault(); + setDragActive(true); + }} + onDragLeave={() => setDragActive(false)} + onDrop={(e) => { + e.preventDefault(); + setDragActive(false); + void handleFileSelect(e.dataTransfer.files); + }} + className={cn( + "border-2 border-dashed rounded-lg p-5 text-center transition-colors", + dragActive + ? "border-[#1e3a8a] bg-blue-50" + : "border-gray-300 bg-gray-50/60 hover:bg-gray-50" + )} + > + void handleFileSelect(e.target.files)} + className="hidden" + /> + +

+ {selectedFile ? selectedFile.name : "Drop your spreadsheet here, or browse"} +

+

+ Accepts .xlsx, .xls, or .csv — automatically validates rows before importing. +

+
+ + {selectedFile && ( + + )} +
+
+ + {validating && ( +
+ Validating rows against hospital masters... +
+ )} + + {errorMsg && ( +
+ + {errorMsg} +
+ )} + + {/* Step 3: Dry-run Validation Preview */} + {preview && ( +
+
+
+ + Total Rows: {preview.total_rows} + + + + Valid: {preview.valid_count} + + 0 + ? "bg-red-100 text-red-800 border-red-200" + : "bg-gray-100 text-gray-600 border-gray-200" + )} + > + + Errors: {preview.error_count} + +
+ + {preview.error_count > 0 && preview.valid_count > 0 && ( + + )} +
+ +
+
+ + + + + + + + + + + + + {preview.preview_rows.length === 0 ? ( + + + + ) : ( + preview.preview_rows.map((r) => ( + + + + + + + + + )) + )} + +
RowAsset CodeNameDepartmentLocationValidation
+ No data rows found in spreadsheet. +
{r.row} + {r.asset_code || "—"} + {r.name || "—"} + {r.department_name || "—"} + + {r.location_name || "—"} + + {r.valid ? ( + + + Ready + + ) : ( + + + {r.error || "Invalid row"} + + )} +
+
+
+
+ )} + + {/* Footer */} +
+ + +
+
+
+ ); +} diff --git a/frontend/src/components/DataTable/DataTable.test.tsx b/frontend/src/components/DataTable/DataTable.test.tsx index e8244e5..af44ca4 100644 --- a/frontend/src/components/DataTable/DataTable.test.tsx +++ b/frontend/src/components/DataTable/DataTable.test.tsx @@ -1,8 +1,17 @@ -import { describe, it, expect } from "vitest"; +import { describe, it, expect, vi, beforeEach } from "vitest"; import { render, screen, fireEvent } from "@testing-library/react"; import { ColumnDef } from "@tanstack/react-table"; +import * as XLSX from "xlsx"; import { DataTable } from "./DataTable"; +vi.mock("xlsx", async () => { + const actual = await vi.importActual("xlsx"); + return { + ...actual, + writeFile: vi.fn(), + }; +}); + interface RowItem { code: string; name: string; @@ -19,8 +28,19 @@ const data: RowItem[] = [ ]; describe("DataTable", () => { - it("renders rows and filters globally", () => { - render(); + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("renders rows, filters globally, and exports visible rows to Excel (.xlsx)", () => { + render( + + ); expect(screen.getByText("Ventilator")).toBeInTheDocument(); expect(screen.getByText("Monitor")).toBeInTheDocument(); @@ -29,5 +49,17 @@ describe("DataTable", () => { expect(screen.getByText("Ventilator")).toBeInTheDocument(); expect(screen.queryByText("Monitor")).not.toBeInTheDocument(); + + const exportBtn = screen.getByRole("button", { + name: /Export current view to Excel/i, + }); + expect(exportBtn).toHaveTextContent("Export Excel (.xlsx)"); + fireEvent.click(exportBtn); + + expect(XLSX.writeFile).toHaveBeenCalledTimes(1); + expect(XLSX.writeFile).toHaveBeenCalledWith( + expect.objectContaining({ SheetNames: ["Data"] }), + "test-assets.xlsx" + ); }); }); diff --git a/frontend/src/components/DataTable/DataTable.tsx b/frontend/src/components/DataTable/DataTable.tsx index 85258fc..b3eaad7 100644 --- a/frontend/src/components/DataTable/DataTable.tsx +++ b/frontend/src/components/DataTable/DataTable.tsx @@ -11,9 +11,18 @@ import { VisibilityState, PaginationState, FilterFn, + type Table as TanStackTable, } from "@tanstack/react-table"; -import { useState, useMemo } from "react"; -import { ChevronUp, ChevronDown, ChevronsUpDown, Download, Eye, Search } from "lucide-react"; +import { useState } from "react"; +import * as XLSX from "xlsx"; +import { + ChevronUp, + ChevronDown, + ChevronsUpDown, + FileSpreadsheet, + Eye, + Search, +} from "lucide-react"; import { cn } from "@/lib/utils"; import { Button } from "@/components/ui/button"; @@ -29,20 +38,39 @@ interface DataTableProps { exportFilename?: string; } -function exportToCsv(data: TData[], filename: string) { - if (!data.length) return; - const headers = Object.keys(data[0] as object); - const rows = data.map((row) => - headers.map((h) => JSON.stringify((row as Record)[h] ?? "")).join(",") - ); - const csv = [headers.join(","), ...rows].join("\n"); - const blob = new Blob([csv], { type: "text/csv" }); - const url = URL.createObjectURL(blob); - const a = document.createElement("a"); - a.href = url; - a.download = `${filename}.csv`; - a.click(); - URL.revokeObjectURL(url); +function formatExcelCell(val: unknown): string | number { + if (val === null || val === undefined) return ""; + if (typeof val === "boolean") return val ? "Yes" : "No"; + if (typeof val === "number") return Number.isFinite(val) ? val : ""; + if (typeof val === "string") return val; + return JSON.stringify(val); +} + +function exportToExcel(table: TanStackTable, filename: string) { + const rows = table.getPrePaginationRowModel().rows; + if (!rows.length) return; + + const visibleCols = table + .getVisibleLeafColumns() + .filter((col) => col.id !== "actions"); + if (!visibleCols.length) return; + + const exportRows = rows.map((row) => { + const record: Record = {}; + for (const col of visibleCols) { + const headerLabel = + typeof col.columnDef.header === "string" + ? col.columnDef.header + : col.id; + record[headerLabel] = formatExcelCell(row.getValue(col.id)); + } + return record; + }); + + const ws = XLSX.utils.json_to_sheet(exportRows); + const wb = XLSX.utils.book_new(); + XLSX.utils.book_append_sheet(wb, ws, "Data"); + XLSX.writeFile(wb, `${filename}.xlsx`); } export function DataTable({ @@ -88,47 +116,53 @@ export function DataTable({ const visibleRows = table.getRowModel().rows; const filteredRows = table.getFilteredRowModel().rows; - const allFilteredData = useMemo( - () => filteredRows.map((r) => r.original), - [filteredRows] - ); return (
{/* Toolbar */} -
-
+
+
setGlobalFilter(e.target.value)} placeholder={globalFilterPlaceholder} + aria-label={globalFilterPlaceholder} className="w-full pl-9 pr-4 py-1.5 text-sm border border-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" />
-
- + {showColVis && ( +
+ {table.getAllLeafColumns().map((col) => ( + + ))} +
+ )} +
+ - {showColVis && ( -
- {table.getAllLeafColumns().map((col) => ( - - ))} -
- )}
-
{/* Table */} @@ -139,7 +173,7 @@ export function DataTable({ {table.getHeaderGroups().map((hg) => ( {hg.headers.map((header) => ( - + {header.isPlaceholder ? null : (
{/* Sortable header */} @@ -184,7 +218,7 @@ export function DataTable({ [...Array(5)].map((_, i) => ( {columns.map((_, j) => ( - +
))} @@ -211,7 +245,7 @@ export function DataTable({ onClick={() => onRowClick?.(row.original)} > {row.getVisibleCells().map((cell) => ( - + {flexRender(cell.column.columnDef.cell, cell.getContext())} ))} @@ -224,7 +258,7 @@ export function DataTable({ {/* Pagination */} {!loading && visibleRows.length > 0 && ( -
+
{filteredRows.length} record{filteredRows.length !== 1 ? "s" : ""} {globalFilter || columnFilters.length ? " (filtered)" : ""} diff --git a/frontend/src/components/layout/AppShell.tsx b/frontend/src/components/layout/AppShell.tsx index 80dbf7c..bded685 100644 --- a/frontend/src/components/layout/AppShell.tsx +++ b/frontend/src/components/layout/AppShell.tsx @@ -15,7 +15,7 @@ export function AppShell() { />
setMobileNavOpen(true)} /> -
+
diff --git a/frontend/src/components/layout/Sidebar.tsx b/frontend/src/components/layout/Sidebar.tsx index eb47250..c518453 100644 --- a/frontend/src/components/layout/Sidebar.tsx +++ b/frontend/src/components/layout/Sidebar.tsx @@ -104,7 +104,7 @@ export function Sidebar({ mobileOpen, onClose }: SidebarProps = {}) { type="button" onClick={onClose} aria-label="Close navigation menu" - className="md:hidden absolute right-2 top-2 p-1 rounded text-blue-200 hover:text-white hover:bg-blue-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white" + className="lg:hidden absolute right-2 top-2 p-1 rounded text-blue-200 hover:text-white hover:bg-blue-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white" > @@ -159,9 +159,9 @@ export function Sidebar({ mobileOpen, onClose }: SidebarProps = {}) { return ( <> -
{asideContent}
+
{asideContent}
{mobileOpen && ( -
+
- {/* Mobile nav toggle */} +
+ {/* Mobile/tablet nav toggle */} {onMenuClick && ( @@ -253,7 +253,10 @@ export function TopBar({ title, onMenuClick }: TopBarProps) { {/* Live Global Quick Search */}
+
As of Date: @@ -451,8 +454,10 @@ export function TopBar({ title, onMenuClick }: TopBarProps) {
)} - {/* Live Notification Bell & Dropdown */} -
+ {/* Right utility cluster (Bell + User Menu) */} +
+ {/* Live Notification Bell & Dropdown */} +
)} +
); diff --git a/frontend/src/components/ui/dialog.tsx b/frontend/src/components/ui/dialog.tsx index aef2f0c..ae3d915 100644 --- a/frontend/src/components/ui/dialog.tsx +++ b/frontend/src/components/ui/dialog.tsx @@ -25,7 +25,7 @@ export function Modal({ diff --git a/frontend/src/pages/AssetsPage.tsx b/frontend/src/pages/AssetsPage.tsx index 49e44ab..a176e7c 100644 --- a/frontend/src/pages/AssetsPage.tsx +++ b/frontend/src/pages/AssetsPage.tsx @@ -2,7 +2,7 @@ import { useState } from "react"; import { useNavigate } from "react-router-dom"; import { useQuery } from "@tanstack/react-query"; import type { ColumnDef } from "@tanstack/react-table"; -import { Plus } from "lucide-react"; +import { Plus, Upload } from "lucide-react"; import { assetsApi, type AssetItem, type AssetStatus } from "@/api/assets"; import { departmentsApi } from "@/api/masters"; import { useAuthStore } from "@/hooks/useAuth"; @@ -15,6 +15,7 @@ import { CalibrationBadge, } from "@/components/StatusBadge"; import { AssetFormModal } from "@/components/AssetFormModal"; +import { BulkAssetImportModal } from "@/components/BulkAssetImportModal"; const STATUS_CHIPS: { value: AssetStatus | ""; label: string }[] = [ { value: "", label: "All Statuses" }, @@ -34,6 +35,7 @@ export function AssetsPage() { const [selectedDeptId, setSelectedDeptId] = useState(undefined); const [selectedStatus, setSelectedStatus] = useState(""); const [createOpen, setCreateOpen] = useState(false); + const [bulkOpen, setBulkOpen] = useState(false); const deptsQuery = useQuery({ queryKey: ["departments", "active-only"], @@ -133,7 +135,7 @@ export function AssetsPage() { return (
-
+

Asset Register

@@ -143,10 +145,16 @@ export function AssetsPage() {

{canCreate && ( - +
+ + +
)}
@@ -213,7 +221,10 @@ export function AssetsPage() { /> {canCreate && ( - setCreateOpen(false)} /> + <> + setCreateOpen(false)} /> + setBulkOpen(false)} /> + )}
); diff --git a/frontend/src/pages/CalibrationPage.tsx b/frontend/src/pages/CalibrationPage.tsx index 6eb0921..611641a 100644 --- a/frontend/src/pages/CalibrationPage.tsx +++ b/frontend/src/pages/CalibrationPage.tsx @@ -393,7 +393,7 @@ export function CalibrationPage() {
{/* Tabs */} -
+
{/* Tabs */} -
+
{/* View Tabs */} -
+
{( [ { key: "active", label: "Active & Overdue" }, diff --git a/frontend/src/pages/PMPage.tsx b/frontend/src/pages/PMPage.tsx index 24e1ae5..cd913bb 100644 --- a/frontend/src/pages/PMPage.tsx +++ b/frontend/src/pages/PMPage.tsx @@ -565,15 +565,17 @@ export function PMPage() {
-
- {["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].map((d) => ( -
- {d} +
+
+
+ {["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].map((d) => ( +
+ {d} +
+ ))}
- ))} -
-
+
{calendarCells.map((cell, idx) => { const items = cell.dateStr ? recordsByDate.get(cell.dateStr) ?? [] : []; return ( @@ -608,6 +610,8 @@ export function PMPage() {
); })} +
+
)} diff --git a/frontend/src/pages/ReportDetailPage.tsx b/frontend/src/pages/ReportDetailPage.tsx index 4762813..2107b71 100644 --- a/frontend/src/pages/ReportDetailPage.tsx +++ b/frontend/src/pages/ReportDetailPage.tsx @@ -17,7 +17,6 @@ import { } from "recharts"; import { ArrowLeft, - Download, FileSpreadsheet, Printer, HelpCircle, @@ -350,16 +349,6 @@ export function ReportDetailPage() { How this is calculated )} -