feat: excel exports, bulk asset import, and responsive layout improvements
This commit is contained in:
@@ -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)
|
- 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`)
|
- 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
|
- 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)
|
- 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
|
- 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
|
- 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`)
|
- 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`
|
- 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
|
- 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
|
- 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)
|
- 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
|
- 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 `<ConfirmDialog />`, 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 `<ConfirmDialog />`, DataTable with Excel `.xlsx` export, Tailwind CSS + shadcn/ui)
|
||||||
- Docker packaging (`docker-compose.yml`, `backend/Dockerfile`, `frontend/Dockerfile`, `frontend/nginx.conf`, `.env.example`) & `Makefile`
|
- Docker packaging (`docker-compose.yml`, `backend/Dockerfile`, `frontend/Dockerfile`, `frontend/nginx.conf`, `.env.example`) & `Makefile`
|
||||||
|
|
||||||
## Modules (Phases 0–8 Complete)
|
## Modules (Phases 0–8 Complete)
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from datetime import date
|
from datetime import date
|
||||||
from typing import Any, Optional
|
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 import or_
|
||||||
from sqlalchemy.exc import IntegrityError
|
from sqlalchemy.exc import IntegrityError
|
||||||
from sqlalchemy.orm import Session, joinedload
|
from sqlalchemy.orm import Session, joinedload
|
||||||
@@ -44,6 +45,7 @@ from ..schemas.assets import (
|
|||||||
PMScheduleSummaryOut,
|
PMScheduleSummaryOut,
|
||||||
WarrantySummaryOut,
|
WarrantySummaryOut,
|
||||||
)
|
)
|
||||||
|
from ..services.asset_import import build_import_template_xlsx, process_asset_import
|
||||||
from ..services.audit import log_audit
|
from ..services.audit import log_audit
|
||||||
from ..services.calculations import compute_schedule_status, coverage_status
|
from ..services.calculations import compute_schedule_status, coverage_status
|
||||||
from ..services.permissions import Role
|
from ..services.permissions import Role
|
||||||
@@ -506,6 +508,40 @@ def create_asset(
|
|||||||
return _to_asset_out(loaded, rels, effective_today(db), _lead_settings(db))
|
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)
|
@router.get("/{asset_id}", response_model=AssetOut)
|
||||||
def get_asset(
|
def get_asset(
|
||||||
asset_id: int,
|
asset_id: int,
|
||||||
|
|||||||
@@ -89,6 +89,7 @@ def seed_database(db: Session, upload_dir: Path | None = None) -> dict[str, int]
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
db.flush()
|
db.flush()
|
||||||
|
db.expunge_all()
|
||||||
|
|
||||||
# 2. Settings (14 keys)
|
# 2. Settings (14 keys)
|
||||||
ensure_default_settings(db)
|
ensure_default_settings(db)
|
||||||
|
|||||||
@@ -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,
|
||||||
|
}
|
||||||
@@ -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"
|
||||||
Generated
+104
@@ -33,6 +33,7 @@
|
|||||||
"react-router-dom": "^6.28.0",
|
"react-router-dom": "^6.28.0",
|
||||||
"recharts": "^2.13.3",
|
"recharts": "^2.13.3",
|
||||||
"tailwind-merge": "^2.5.4",
|
"tailwind-merge": "^2.5.4",
|
||||||
|
"xlsx": "^0.18.5",
|
||||||
"zod": "^3.23.8",
|
"zod": "^3.23.8",
|
||||||
"zustand": "^4.5.5"
|
"zustand": "^4.5.5"
|
||||||
},
|
},
|
||||||
@@ -3505,6 +3506,15 @@
|
|||||||
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
"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": {
|
"node_modules/agent-base": {
|
||||||
"version": "7.1.4",
|
"version": "7.1.4",
|
||||||
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
|
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
|
||||||
@@ -3840,6 +3850,19 @@
|
|||||||
],
|
],
|
||||||
"license": "CC-BY-4.0"
|
"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": {
|
"node_modules/chai": {
|
||||||
"version": "5.3.3",
|
"version": "5.3.3",
|
||||||
"resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",
|
"resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",
|
||||||
@@ -3943,6 +3966,15 @@
|
|||||||
"node": ">=6"
|
"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": {
|
"node_modules/color-convert": {
|
||||||
"version": "2.0.1",
|
"version": "2.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
|
||||||
@@ -4000,6 +4032,18 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"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": {
|
"node_modules/cross-spawn": {
|
||||||
"version": "7.0.6",
|
"version": "7.0.6",
|
||||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
||||||
@@ -4835,6 +4879,15 @@
|
|||||||
"node": ">= 6"
|
"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": {
|
"node_modules/fraction.js": {
|
||||||
"version": "4.3.7",
|
"version": "4.3.7",
|
||||||
"resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz",
|
"resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz",
|
||||||
@@ -6541,6 +6594,18 @@
|
|||||||
"node": ">=0.10.0"
|
"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": {
|
"node_modules/stackback": {
|
||||||
"version": "0.0.2",
|
"version": "0.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
|
||||||
@@ -7283,6 +7348,24 @@
|
|||||||
"node": ">=8"
|
"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": {
|
"node_modules/word-wrap": {
|
||||||
"version": "1.2.5",
|
"version": "1.2.5",
|
||||||
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",
|
"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": {
|
"node_modules/xml-name-validator": {
|
||||||
"version": "5.0.0",
|
"version": "5.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
|
||||||
|
|||||||
@@ -36,6 +36,7 @@
|
|||||||
"react-router-dom": "^6.28.0",
|
"react-router-dom": "^6.28.0",
|
||||||
"recharts": "^2.13.3",
|
"recharts": "^2.13.3",
|
||||||
"tailwind-merge": "^2.5.4",
|
"tailwind-merge": "^2.5.4",
|
||||||
|
"xlsx": "^0.18.5",
|
||||||
"zod": "^3.23.8",
|
"zod": "^3.23.8",
|
||||||
"zustand": "^4.5.5"
|
"zustand": "^4.5.5"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -225,6 +225,35 @@ export interface AssetCreatePayload {
|
|||||||
|
|
||||||
export type AssetUpdatePayload = Partial<AssetCreatePayload>;
|
export type AssetUpdatePayload = Partial<AssetCreatePayload>;
|
||||||
|
|
||||||
|
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 = {
|
export const assetsApi = {
|
||||||
list: (params: AssetListParams = {}) => {
|
list: (params: AssetListParams = {}) => {
|
||||||
const qs = new URLSearchParams();
|
const qs = new URLSearchParams();
|
||||||
@@ -251,4 +280,23 @@ export const assetsApi = {
|
|||||||
overview: (id: number) => api.get<AssetOverview>(`/assets/${id}/overview`),
|
overview: (id: number) => api.get<AssetOverview>(`/assets/${id}/overview`),
|
||||||
create: (data: AssetCreatePayload) => api.post<AssetItem>("/assets", data),
|
create: (data: AssetCreatePayload) => api.post<AssetItem>("/assets", data),
|
||||||
update: (id: number, data: AssetUpdatePayload) => api.patch<AssetItem>(`/assets/${id}`, data),
|
update: (id: number, data: AssetUpdatePayload) => api.patch<AssetItem>(`/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<BulkImportResult>(
|
||||||
|
`/assets/bulk-import?dry_run=${dryRun}&skip_invalid=${skipInvalid}`,
|
||||||
|
formData
|
||||||
|
);
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -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<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
const [selectedFile, setSelectedFile] = useState<File | null>(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<BulkImportResult | null>(null);
|
||||||
|
const [errorMsg, setErrorMsg] = useState<string | null>(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 (
|
||||||
|
<Modal
|
||||||
|
open={open}
|
||||||
|
onOpenChange={(next) => {
|
||||||
|
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"
|
||||||
|
>
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* Step 1: Template Download */}
|
||||||
|
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 rounded-lg border border-blue-200 bg-blue-50/70 p-3.5">
|
||||||
|
<div className="flex items-start gap-2.5 text-xs text-blue-950">
|
||||||
|
<FileSpreadsheet className="h-5 w-5 text-[#1e3a8a] shrink-0 mt-0.5" />
|
||||||
|
<div>
|
||||||
|
<div className="font-semibold text-sm text-[#1e3a8a]">
|
||||||
|
Step 1: Download the Excel Template
|
||||||
|
</div>
|
||||||
|
<p className="mt-0.5 text-blue-900/90">
|
||||||
|
Fill equipment rows in the <strong>Assets</strong> sheet and check valid
|
||||||
|
departments, locations, categories, and suppliers in the{" "}
|
||||||
|
<strong>Master Reference</strong> sheet.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
loading={downloadingTemplate}
|
||||||
|
onClick={handleDownloadTemplate}
|
||||||
|
className="shrink-0 bg-white"
|
||||||
|
>
|
||||||
|
<Download className="h-4 w-4 mr-1.5" />
|
||||||
|
Download Template (.xlsx)
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Step 2: File Picker / Dropzone */}
|
||||||
|
<div
|
||||||
|
onDragOver={(e) => {
|
||||||
|
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"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
type="file"
|
||||||
|
accept=".xlsx,.xls,.csv"
|
||||||
|
aria-label="Upload asset spreadsheet"
|
||||||
|
onChange={(e) => void handleFileSelect(e.target.files)}
|
||||||
|
className="hidden"
|
||||||
|
/>
|
||||||
|
<Upload className="h-7 w-7 text-gray-400 mx-auto mb-2" />
|
||||||
|
<p className="text-sm font-medium text-gray-800">
|
||||||
|
{selectedFile ? selectedFile.name : "Drop your spreadsheet here, or browse"}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-gray-500 mt-1">
|
||||||
|
Accepts <code>.xlsx</code>, <code>.xls</code>, or <code>.csv</code> — automatically validates rows before importing.
|
||||||
|
</p>
|
||||||
|
<div className="mt-3 flex items-center justify-center gap-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={validating || importing}
|
||||||
|
onClick={() => fileInputRef.current?.click()}
|
||||||
|
>
|
||||||
|
{selectedFile ? "Choose Another File" : "Select Spreadsheet"}
|
||||||
|
</Button>
|
||||||
|
{selectedFile && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
disabled={validating || importing}
|
||||||
|
onClick={resetState}
|
||||||
|
>
|
||||||
|
<X className="h-3.5 w-3.5 mr-1" />
|
||||||
|
Clear
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{validating && (
|
||||||
|
<div className="rounded-md border border-blue-200 bg-blue-50 px-3.5 py-2.5 text-xs text-blue-900">
|
||||||
|
Validating rows against hospital masters...
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{errorMsg && (
|
||||||
|
<div
|
||||||
|
role="alert"
|
||||||
|
className="flex items-start gap-2 rounded-md border border-red-200 bg-red-50 px-3.5 py-2.5 text-xs text-red-800"
|
||||||
|
>
|
||||||
|
<AlertCircle className="h-4 w-4 text-red-600 shrink-0 mt-0.5" />
|
||||||
|
<span>{errorMsg}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Step 3: Dry-run Validation Preview */}
|
||||||
|
{preview && (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-700 border border-gray-200">
|
||||||
|
Total Rows: {preview.total_rows}
|
||||||
|
</span>
|
||||||
|
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800 border border-green-200">
|
||||||
|
<CheckCircle2 className="h-3.5 w-3.5" />
|
||||||
|
Valid: {preview.valid_count}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium border",
|
||||||
|
preview.error_count > 0
|
||||||
|
? "bg-red-100 text-red-800 border-red-200"
|
||||||
|
: "bg-gray-100 text-gray-600 border-gray-200"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<AlertCircle className="h-3.5 w-3.5" />
|
||||||
|
Errors: {preview.error_count}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{preview.error_count > 0 && preview.valid_count > 0 && (
|
||||||
|
<label className="inline-flex items-center gap-2 text-xs font-medium text-gray-700 cursor-pointer">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={skipInvalid}
|
||||||
|
onChange={(e) => setSkipInvalid(e.target.checked)}
|
||||||
|
className="rounded border-gray-300 text-[#1e3a8a] focus:ring-blue-500"
|
||||||
|
/>
|
||||||
|
Skip invalid rows and import valid rows only
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="border border-gray-200 rounded-lg overflow-hidden">
|
||||||
|
<div className="max-h-64 overflow-auto">
|
||||||
|
<table className="w-full text-xs">
|
||||||
|
<thead className="bg-gray-50 border-b border-gray-200 sticky top-0">
|
||||||
|
<tr>
|
||||||
|
<th className="px-3 py-2 text-left font-medium text-gray-600">Row</th>
|
||||||
|
<th className="px-3 py-2 text-left font-medium text-gray-600">Asset Code</th>
|
||||||
|
<th className="px-3 py-2 text-left font-medium text-gray-600">Name</th>
|
||||||
|
<th className="px-3 py-2 text-left font-medium text-gray-600">Department</th>
|
||||||
|
<th className="px-3 py-2 text-left font-medium text-gray-600">Location</th>
|
||||||
|
<th className="px-3 py-2 text-left font-medium text-gray-600">Validation</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-gray-100 bg-white">
|
||||||
|
{preview.preview_rows.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={6} className="px-3 py-6 text-center text-gray-400">
|
||||||
|
No data rows found in spreadsheet.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : (
|
||||||
|
preview.preview_rows.map((r) => (
|
||||||
|
<tr
|
||||||
|
key={r.row}
|
||||||
|
className={r.valid ? "bg-white" : "bg-red-50/60"}
|
||||||
|
>
|
||||||
|
<td className="px-3 py-2 font-mono text-gray-500">{r.row}</td>
|
||||||
|
<td className="px-3 py-2 font-mono font-medium text-gray-900">
|
||||||
|
{r.asset_code || "—"}
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-2 text-gray-800">{r.name || "—"}</td>
|
||||||
|
<td className="px-3 py-2 text-gray-700">
|
||||||
|
{r.department_name || "—"}
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-2 text-gray-700">
|
||||||
|
{r.location_name || "—"}
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-2">
|
||||||
|
{r.valid ? (
|
||||||
|
<span className="inline-flex items-center gap-1 text-green-700 font-medium">
|
||||||
|
<CheckCircle2 className="h-3.5 w-3.5" />
|
||||||
|
Ready
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="inline-flex items-start gap-1 text-red-700">
|
||||||
|
<AlertCircle className="h-3.5 w-3.5 shrink-0 mt-0.5" />
|
||||||
|
<span>{r.error || "Invalid row"}</span>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Footer */}
|
||||||
|
<div className="flex flex-col-reverse sm:flex-row sm:items-center justify-end gap-2 pt-2 border-t border-gray-100">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={importing}
|
||||||
|
onClick={handleClose}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
loading={importing}
|
||||||
|
disabled={!canImport}
|
||||||
|
onClick={handleConfirmImport}
|
||||||
|
>
|
||||||
|
<Upload className="h-4 w-4 mr-1.5" />
|
||||||
|
Import {preview?.valid_count ?? 0} Asset
|
||||||
|
{(preview?.valid_count ?? 0) === 1 ? "" : "s"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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 { render, screen, fireEvent } from "@testing-library/react";
|
||||||
import { ColumnDef } from "@tanstack/react-table";
|
import { ColumnDef } from "@tanstack/react-table";
|
||||||
|
import * as XLSX from "xlsx";
|
||||||
import { DataTable } from "./DataTable";
|
import { DataTable } from "./DataTable";
|
||||||
|
|
||||||
|
vi.mock("xlsx", async () => {
|
||||||
|
const actual = await vi.importActual<typeof import("xlsx")>("xlsx");
|
||||||
|
return {
|
||||||
|
...actual,
|
||||||
|
writeFile: vi.fn(),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
interface RowItem {
|
interface RowItem {
|
||||||
code: string;
|
code: string;
|
||||||
name: string;
|
name: string;
|
||||||
@@ -19,8 +28,19 @@ const data: RowItem[] = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
describe("DataTable", () => {
|
describe("DataTable", () => {
|
||||||
it("renders rows and filters globally", () => {
|
beforeEach(() => {
|
||||||
render(<DataTable data={data} columns={columns} globalFilterPlaceholder="Search..." />);
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders rows, filters globally, and exports visible rows to Excel (.xlsx)", () => {
|
||||||
|
render(
|
||||||
|
<DataTable
|
||||||
|
data={data}
|
||||||
|
columns={columns}
|
||||||
|
globalFilterPlaceholder="Search..."
|
||||||
|
exportFilename="test-assets"
|
||||||
|
/>
|
||||||
|
);
|
||||||
expect(screen.getByText("Ventilator")).toBeInTheDocument();
|
expect(screen.getByText("Ventilator")).toBeInTheDocument();
|
||||||
expect(screen.getByText("Monitor")).toBeInTheDocument();
|
expect(screen.getByText("Monitor")).toBeInTheDocument();
|
||||||
|
|
||||||
@@ -29,5 +49,17 @@ describe("DataTable", () => {
|
|||||||
|
|
||||||
expect(screen.getByText("Ventilator")).toBeInTheDocument();
|
expect(screen.getByText("Ventilator")).toBeInTheDocument();
|
||||||
expect(screen.queryByText("Monitor")).not.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"
|
||||||
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -11,9 +11,18 @@ import {
|
|||||||
VisibilityState,
|
VisibilityState,
|
||||||
PaginationState,
|
PaginationState,
|
||||||
FilterFn,
|
FilterFn,
|
||||||
|
type Table as TanStackTable,
|
||||||
} from "@tanstack/react-table";
|
} from "@tanstack/react-table";
|
||||||
import { useState, useMemo } from "react";
|
import { useState } from "react";
|
||||||
import { ChevronUp, ChevronDown, ChevronsUpDown, Download, Eye, Search } from "lucide-react";
|
import * as XLSX from "xlsx";
|
||||||
|
import {
|
||||||
|
ChevronUp,
|
||||||
|
ChevronDown,
|
||||||
|
ChevronsUpDown,
|
||||||
|
FileSpreadsheet,
|
||||||
|
Eye,
|
||||||
|
Search,
|
||||||
|
} from "lucide-react";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
@@ -29,20 +38,39 @@ interface DataTableProps<TData> {
|
|||||||
exportFilename?: string;
|
exportFilename?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
function exportToCsv<TData>(data: TData[], filename: string) {
|
function formatExcelCell(val: unknown): string | number {
|
||||||
if (!data.length) return;
|
if (val === null || val === undefined) return "";
|
||||||
const headers = Object.keys(data[0] as object);
|
if (typeof val === "boolean") return val ? "Yes" : "No";
|
||||||
const rows = data.map((row) =>
|
if (typeof val === "number") return Number.isFinite(val) ? val : "";
|
||||||
headers.map((h) => JSON.stringify((row as Record<string, unknown>)[h] ?? "")).join(",")
|
if (typeof val === "string") return val;
|
||||||
);
|
return JSON.stringify(val);
|
||||||
const csv = [headers.join(","), ...rows].join("\n");
|
}
|
||||||
const blob = new Blob([csv], { type: "text/csv" });
|
|
||||||
const url = URL.createObjectURL(blob);
|
function exportToExcel<TData>(table: TanStackTable<TData>, filename: string) {
|
||||||
const a = document.createElement("a");
|
const rows = table.getPrePaginationRowModel().rows;
|
||||||
a.href = url;
|
if (!rows.length) return;
|
||||||
a.download = `${filename}.csv`;
|
|
||||||
a.click();
|
const visibleCols = table
|
||||||
URL.revokeObjectURL(url);
|
.getVisibleLeafColumns()
|
||||||
|
.filter((col) => col.id !== "actions");
|
||||||
|
if (!visibleCols.length) return;
|
||||||
|
|
||||||
|
const exportRows = rows.map((row) => {
|
||||||
|
const record: Record<string, string | number> = {};
|
||||||
|
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<TData>({
|
export function DataTable<TData>({
|
||||||
@@ -88,47 +116,53 @@ export function DataTable<TData>({
|
|||||||
|
|
||||||
const visibleRows = table.getRowModel().rows;
|
const visibleRows = table.getRowModel().rows;
|
||||||
const filteredRows = table.getFilteredRowModel().rows;
|
const filteredRows = table.getFilteredRowModel().rows;
|
||||||
const allFilteredData = useMemo(
|
|
||||||
() => filteredRows.map((r) => r.original),
|
|
||||||
[filteredRows]
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
{/* Toolbar */}
|
{/* Toolbar */}
|
||||||
<div className="flex items-center gap-2 flex-wrap">
|
<div className="flex flex-col sm:flex-row sm:items-center gap-2">
|
||||||
<div className="relative flex-1 min-w-48">
|
<div className="relative flex-1 min-w-0">
|
||||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
|
||||||
<input
|
<input
|
||||||
value={globalFilter}
|
value={globalFilter}
|
||||||
onChange={(e) => setGlobalFilter(e.target.value)}
|
onChange={(e) => setGlobalFilter(e.target.value)}
|
||||||
placeholder={globalFilterPlaceholder}
|
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"
|
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"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="relative">
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
<Button variant="outline" size="sm" onClick={() => setShowColVis(!showColVis)}>
|
<div className="relative">
|
||||||
<Eye className="h-4 w-4 mr-1" /> Columns
|
<Button variant="outline" size="sm" onClick={() => setShowColVis(!showColVis)}>
|
||||||
|
<Eye className="h-4 w-4 mr-1" /> Columns
|
||||||
|
</Button>
|
||||||
|
{showColVis && (
|
||||||
|
<div className="absolute right-0 mt-1 w-48 bg-white border border-gray-200 rounded-md shadow-lg z-20 p-2">
|
||||||
|
{table.getAllLeafColumns().map((col) => (
|
||||||
|
<label key={col.id} className="flex items-center gap-2 px-2 py-1 hover:bg-gray-50 rounded cursor-pointer text-sm">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={col.getIsVisible()}
|
||||||
|
onChange={col.getToggleVisibilityHandler()}
|
||||||
|
className="rounded"
|
||||||
|
/>
|
||||||
|
{typeof col.columnDef.header === "string"
|
||||||
|
? col.columnDef.header
|
||||||
|
: col.id}
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
aria-label="Export current view to Excel"
|
||||||
|
onClick={() => exportToExcel(table, exportFilename)}
|
||||||
|
>
|
||||||
|
<FileSpreadsheet className="h-4 w-4 mr-1" /> Export Excel (.xlsx)
|
||||||
</Button>
|
</Button>
|
||||||
{showColVis && (
|
|
||||||
<div className="absolute right-0 mt-1 w-48 bg-white border border-gray-200 rounded-md shadow-lg z-20 p-2">
|
|
||||||
{table.getAllLeafColumns().map((col) => (
|
|
||||||
<label key={col.id} className="flex items-center gap-2 px-2 py-1 hover:bg-gray-50 rounded cursor-pointer text-sm">
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={col.getIsVisible()}
|
|
||||||
onChange={col.getToggleVisibilityHandler()}
|
|
||||||
className="rounded"
|
|
||||||
/>
|
|
||||||
{String(col.columnDef.header ?? col.id)}
|
|
||||||
</label>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
<Button variant="outline" size="sm" onClick={() => exportToCsv(allFilteredData, exportFilename)}>
|
|
||||||
<Download className="h-4 w-4 mr-1" /> CSV (current view)
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Table */}
|
{/* Table */}
|
||||||
@@ -139,7 +173,7 @@ export function DataTable<TData>({
|
|||||||
{table.getHeaderGroups().map((hg) => (
|
{table.getHeaderGroups().map((hg) => (
|
||||||
<tr key={hg.id}>
|
<tr key={hg.id}>
|
||||||
{hg.headers.map((header) => (
|
{hg.headers.map((header) => (
|
||||||
<th key={header.id} className="text-left font-medium text-gray-600 px-4 py-3">
|
<th key={header.id} className="text-left font-medium text-gray-600 px-2.5 py-2 sm:px-4 sm:py-3">
|
||||||
{header.isPlaceholder ? null : (
|
{header.isPlaceholder ? null : (
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
{/* Sortable header */}
|
{/* Sortable header */}
|
||||||
@@ -184,7 +218,7 @@ export function DataTable<TData>({
|
|||||||
[...Array(5)].map((_, i) => (
|
[...Array(5)].map((_, i) => (
|
||||||
<tr key={i}>
|
<tr key={i}>
|
||||||
{columns.map((_, j) => (
|
{columns.map((_, j) => (
|
||||||
<td key={j} className="px-4 py-3">
|
<td key={j} className="px-2.5 py-2 sm:px-4 sm:py-3">
|
||||||
<div className="h-4 bg-gray-100 rounded animate-pulse" />
|
<div className="h-4 bg-gray-100 rounded animate-pulse" />
|
||||||
</td>
|
</td>
|
||||||
))}
|
))}
|
||||||
@@ -211,7 +245,7 @@ export function DataTable<TData>({
|
|||||||
onClick={() => onRowClick?.(row.original)}
|
onClick={() => onRowClick?.(row.original)}
|
||||||
>
|
>
|
||||||
{row.getVisibleCells().map((cell) => (
|
{row.getVisibleCells().map((cell) => (
|
||||||
<td key={cell.id} className="px-4 py-3 text-gray-700">
|
<td key={cell.id} className="px-2.5 py-2 sm:px-4 sm:py-3 text-gray-700">
|
||||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||||
</td>
|
</td>
|
||||||
))}
|
))}
|
||||||
@@ -224,7 +258,7 @@ export function DataTable<TData>({
|
|||||||
|
|
||||||
{/* Pagination */}
|
{/* Pagination */}
|
||||||
{!loading && visibleRows.length > 0 && (
|
{!loading && visibleRows.length > 0 && (
|
||||||
<div className="flex items-center justify-between px-4 py-3 border-t border-gray-200 bg-gray-50 text-sm text-gray-600">
|
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 px-3 sm:px-4 py-3 border-t border-gray-200 bg-gray-50 text-sm text-gray-600">
|
||||||
<span>
|
<span>
|
||||||
{filteredRows.length} record{filteredRows.length !== 1 ? "s" : ""}
|
{filteredRows.length} record{filteredRows.length !== 1 ? "s" : ""}
|
||||||
{globalFilter || columnFilters.length ? " (filtered)" : ""}
|
{globalFilter || columnFilters.length ? " (filtered)" : ""}
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ export function AppShell() {
|
|||||||
/>
|
/>
|
||||||
<div className="flex-1 flex flex-col min-w-0">
|
<div className="flex-1 flex flex-col min-w-0">
|
||||||
<TopBar onMenuClick={() => setMobileNavOpen(true)} />
|
<TopBar onMenuClick={() => setMobileNavOpen(true)} />
|
||||||
<main className="flex-1 p-6 overflow-auto">
|
<main className="flex-1 p-3 sm:p-4 lg:p-6 overflow-auto">
|
||||||
<Outlet />
|
<Outlet />
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -104,7 +104,7 @@ export function Sidebar({ mobileOpen, onClose }: SidebarProps = {}) {
|
|||||||
type="button"
|
type="button"
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
aria-label="Close navigation menu"
|
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"
|
||||||
>
|
>
|
||||||
<X className="h-4 w-4" />
|
<X className="h-4 w-4" />
|
||||||
</button>
|
</button>
|
||||||
@@ -159,9 +159,9 @@ export function Sidebar({ mobileOpen, onClose }: SidebarProps = {}) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="hidden md:flex shrink-0">{asideContent}</div>
|
<div className="hidden lg:flex shrink-0">{asideContent}</div>
|
||||||
{mobileOpen && (
|
{mobileOpen && (
|
||||||
<div className="fixed inset-0 z-40 flex md:hidden">
|
<div className="fixed inset-0 z-40 flex lg:hidden">
|
||||||
<div
|
<div
|
||||||
className="fixed inset-0 bg-black/40"
|
className="fixed inset-0 bg-black/40"
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
|
|||||||
@@ -230,14 +230,14 @@ export function TopBar({ title, onMenuClick }: TopBarProps) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<header className="min-h-14 bg-white border-b border-gray-200 flex items-center flex-wrap px-4 py-2 gap-3 sticky top-0 z-10">
|
<header className="min-h-14 bg-white border-b border-gray-200 flex items-center flex-wrap px-3 sm:px-4 py-2 gap-2 sm:gap-3 sticky top-0 z-10">
|
||||||
{/* Mobile nav toggle */}
|
{/* Mobile/tablet nav toggle */}
|
||||||
{onMenuClick && (
|
{onMenuClick && (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={onMenuClick}
|
onClick={onMenuClick}
|
||||||
aria-label="Open navigation menu"
|
aria-label="Open navigation menu"
|
||||||
className="md:hidden p-1.5 rounded-md text-gray-600 hover:bg-gray-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
className="lg:hidden p-1.5 rounded-md text-gray-600 hover:bg-gray-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
||||||
>
|
>
|
||||||
<Menu className="h-5 w-5" />
|
<Menu className="h-5 w-5" />
|
||||||
</button>
|
</button>
|
||||||
@@ -253,7 +253,10 @@ export function TopBar({ title, onMenuClick }: TopBarProps) {
|
|||||||
{/* Live Global Quick Search */}
|
{/* Live Global Quick Search */}
|
||||||
<div
|
<div
|
||||||
ref={searchContainerRef}
|
ref={searchContainerRef}
|
||||||
className={cn("relative", title ? "w-64 sm:w-80" : "flex-1 max-w-xs sm:max-w-md")}
|
className={cn(
|
||||||
|
"relative order-last lg:order-none w-full lg:w-auto",
|
||||||
|
title ? "lg:w-72" : "lg:flex-1 lg:max-w-md"
|
||||||
|
)}
|
||||||
>
|
>
|
||||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
|
||||||
<input
|
<input
|
||||||
@@ -407,7 +410,7 @@ export function TopBar({ title, onMenuClick }: TopBarProps) {
|
|||||||
|
|
||||||
{/* Admin Demo Clock Picker + Run Alert Check */}
|
{/* Admin Demo Clock Picker + Run Alert Check */}
|
||||||
{isAdmin && (
|
{isAdmin && (
|
||||||
<div className="flex items-center gap-1.5 bg-gray-50 border border-gray-200 rounded-md px-2 py-1 text-xs flex-wrap">
|
<div className="w-full xl:w-auto order-last xl:order-none flex items-center gap-1.5 bg-gray-50 border border-gray-200 rounded-md px-2 py-1 text-xs flex-wrap">
|
||||||
<span className="text-gray-500 font-medium hidden md:inline">
|
<span className="text-gray-500 font-medium hidden md:inline">
|
||||||
As of Date:
|
As of Date:
|
||||||
</span>
|
</span>
|
||||||
@@ -451,8 +454,10 @@ export function TopBar({ title, onMenuClick }: TopBarProps) {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Live Notification Bell & Dropdown */}
|
{/* Right utility cluster (Bell + User Menu) */}
|
||||||
<div ref={bellContainerRef} className="relative ml-auto">
|
<div className="ml-auto flex items-center gap-1.5 sm:gap-2">
|
||||||
|
{/* Live Notification Bell & Dropdown */}
|
||||||
|
<div ref={bellContainerRef} className="relative">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setBellOpen((o) => !o)}
|
onClick={() => setBellOpen((o) => !o)}
|
||||||
@@ -600,6 +605,7 @@ export function TopBar({ title, onMenuClick }: TopBarProps) {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ export function Modal({
|
|||||||
<DialogPrimitive.Overlay className="fixed inset-0 z-40 bg-black/40 backdrop-blur-[1px]" />
|
<DialogPrimitive.Overlay className="fixed inset-0 z-40 bg-black/40 backdrop-blur-[1px]" />
|
||||||
<DialogPrimitive.Content
|
<DialogPrimitive.Content
|
||||||
className={cn(
|
className={cn(
|
||||||
"fixed left-1/2 top-1/2 z-50 w-full max-w-lg -translate-x-1/2 -translate-y-1/2 rounded-lg bg-white p-6 shadow-xl border border-gray-200 max-h-[90vh] overflow-y-auto",
|
"fixed left-1/2 top-1/2 z-50 w-[95vw] sm:w-full max-w-lg -translate-x-1/2 -translate-y-1/2 rounded-lg bg-white p-4 sm:p-6 shadow-xl border border-gray-200 max-h-[90vh] overflow-y-auto",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { useState } from "react";
|
|||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import type { ColumnDef } from "@tanstack/react-table";
|
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 { assetsApi, type AssetItem, type AssetStatus } from "@/api/assets";
|
||||||
import { departmentsApi } from "@/api/masters";
|
import { departmentsApi } from "@/api/masters";
|
||||||
import { useAuthStore } from "@/hooks/useAuth";
|
import { useAuthStore } from "@/hooks/useAuth";
|
||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
CalibrationBadge,
|
CalibrationBadge,
|
||||||
} from "@/components/StatusBadge";
|
} from "@/components/StatusBadge";
|
||||||
import { AssetFormModal } from "@/components/AssetFormModal";
|
import { AssetFormModal } from "@/components/AssetFormModal";
|
||||||
|
import { BulkAssetImportModal } from "@/components/BulkAssetImportModal";
|
||||||
|
|
||||||
const STATUS_CHIPS: { value: AssetStatus | ""; label: string }[] = [
|
const STATUS_CHIPS: { value: AssetStatus | ""; label: string }[] = [
|
||||||
{ value: "", label: "All Statuses" },
|
{ value: "", label: "All Statuses" },
|
||||||
@@ -34,6 +35,7 @@ export function AssetsPage() {
|
|||||||
const [selectedDeptId, setSelectedDeptId] = useState<number | undefined>(undefined);
|
const [selectedDeptId, setSelectedDeptId] = useState<number | undefined>(undefined);
|
||||||
const [selectedStatus, setSelectedStatus] = useState<AssetStatus | "">("");
|
const [selectedStatus, setSelectedStatus] = useState<AssetStatus | "">("");
|
||||||
const [createOpen, setCreateOpen] = useState(false);
|
const [createOpen, setCreateOpen] = useState(false);
|
||||||
|
const [bulkOpen, setBulkOpen] = useState(false);
|
||||||
|
|
||||||
const deptsQuery = useQuery({
|
const deptsQuery = useQuery({
|
||||||
queryKey: ["departments", "active-only"],
|
queryKey: ["departments", "active-only"],
|
||||||
@@ -133,7 +135,7 @@ export function AssetsPage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Asset Register</h1>
|
<h1 className="text-2xl font-bold text-gray-900">Asset Register</h1>
|
||||||
<p className="text-sm text-gray-500 mt-0.5">
|
<p className="text-sm text-gray-500 mt-0.5">
|
||||||
@@ -143,10 +145,16 @@ export function AssetsPage() {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
{canCreate && (
|
{canCreate && (
|
||||||
<Button onClick={() => setCreateOpen(true)}>
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
<Plus className="h-4 w-4 mr-1.5" />
|
<Button variant="outline" onClick={() => setBulkOpen(true)}>
|
||||||
Add Asset
|
<Upload className="h-4 w-4 mr-1.5" />
|
||||||
</Button>
|
Bulk Import
|
||||||
|
</Button>
|
||||||
|
<Button onClick={() => setCreateOpen(true)}>
|
||||||
|
<Plus className="h-4 w-4 mr-1.5" />
|
||||||
|
Add Asset
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -213,7 +221,10 @@ export function AssetsPage() {
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
{canCreate && (
|
{canCreate && (
|
||||||
<AssetFormModal open={createOpen} onClose={() => setCreateOpen(false)} />
|
<>
|
||||||
|
<AssetFormModal open={createOpen} onClose={() => setCreateOpen(false)} />
|
||||||
|
<BulkAssetImportModal open={bulkOpen} onClose={() => setBulkOpen(false)} />
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -393,7 +393,7 @@ export function CalibrationPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Tabs */}
|
{/* Tabs */}
|
||||||
<div className="border-b border-gray-200 flex gap-1">
|
<div className="border-b border-gray-200 flex gap-1 overflow-x-auto whitespace-nowrap">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setTab("records")}
|
onClick={() => setTab("records")}
|
||||||
|
|||||||
@@ -487,7 +487,7 @@ export function ContractsPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Tabs */}
|
{/* Tabs */}
|
||||||
<div className="flex gap-1 border-b border-gray-200">
|
<div className="flex gap-1 border-b border-gray-200 overflow-x-auto whitespace-nowrap">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
|
|||||||
@@ -272,7 +272,7 @@ export function DemoEquipmentPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* View Tabs */}
|
{/* View Tabs */}
|
||||||
<div className="flex gap-1 border-b border-gray-200">
|
<div className="flex gap-1 border-b border-gray-200 overflow-x-auto whitespace-nowrap">
|
||||||
{(
|
{(
|
||||||
[
|
[
|
||||||
{ key: "active", label: "Active & Overdue" },
|
{ key: "active", label: "Active & Overdue" },
|
||||||
|
|||||||
@@ -565,15 +565,17 @@ export function PMPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid grid-cols-7 gap-1 text-center text-xs font-semibold text-gray-500 pb-1">
|
<div className="overflow-x-auto">
|
||||||
{["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].map((d) => (
|
<div className="min-w-[640px]">
|
||||||
<div key={d} className="py-1">
|
<div className="grid grid-cols-7 gap-1 text-center text-xs font-semibold text-gray-500 pb-1">
|
||||||
{d}
|
{["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].map((d) => (
|
||||||
|
<div key={d} className="py-1">
|
||||||
|
{d}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-7 gap-1">
|
<div className="grid grid-cols-7 gap-1">
|
||||||
{calendarCells.map((cell, idx) => {
|
{calendarCells.map((cell, idx) => {
|
||||||
const items = cell.dateStr ? recordsByDate.get(cell.dateStr) ?? [] : [];
|
const items = cell.dateStr ? recordsByDate.get(cell.dateStr) ?? [] : [];
|
||||||
return (
|
return (
|
||||||
@@ -608,6 +610,8 @@ export function PMPage() {
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ import {
|
|||||||
} from "recharts";
|
} from "recharts";
|
||||||
import {
|
import {
|
||||||
ArrowLeft,
|
ArrowLeft,
|
||||||
Download,
|
|
||||||
FileSpreadsheet,
|
FileSpreadsheet,
|
||||||
Printer,
|
Printer,
|
||||||
HelpCircle,
|
HelpCircle,
|
||||||
@@ -350,16 +349,6 @@ export function ReportDetailPage() {
|
|||||||
How this is calculated
|
How this is calculated
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
loading={exporting === "csv"}
|
|
||||||
onClick={() => handleExport("csv")}
|
|
||||||
>
|
|
||||||
<Download className="h-4 w-4 mr-1.5" />
|
|
||||||
Export CSV (.csv)
|
|
||||||
</Button>
|
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
size="sm"
|
size="sm"
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||||
|
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||||
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
import { BulkAssetImportModal } from "@/components/BulkAssetImportModal";
|
||||||
|
import { ToastProvider } from "@/components/ToastProvider";
|
||||||
|
import * as assetsModule from "@/api/assets";
|
||||||
|
|
||||||
|
function renderModal(onClose = vi.fn()) {
|
||||||
|
const qc = new QueryClient({
|
||||||
|
defaultOptions: { queries: { retry: false } },
|
||||||
|
});
|
||||||
|
return render(
|
||||||
|
<QueryClientProvider client={qc}>
|
||||||
|
<ToastProvider>
|
||||||
|
<BulkAssetImportModal open={true} onClose={onClose} />
|
||||||
|
</ToastProvider>
|
||||||
|
</QueryClientProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("BulkAssetImportModal", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders template download, previews validation rows on upload, and imports valid rows", async () => {
|
||||||
|
const templateSpy = vi
|
||||||
|
.spyOn(assetsModule.assetsApi, "downloadImportTemplate")
|
||||||
|
.mockResolvedValue(undefined);
|
||||||
|
|
||||||
|
const bulkImportSpy = vi
|
||||||
|
.spyOn(assetsModule.assetsApi, "bulkImport")
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
dry_run: true,
|
||||||
|
total_rows: 2,
|
||||||
|
valid_count: 1,
|
||||||
|
error_count: 1,
|
||||||
|
created_count: 0,
|
||||||
|
errors: [
|
||||||
|
{
|
||||||
|
row: 3,
|
||||||
|
asset_code: "PHRC-BAD-1",
|
||||||
|
error: "Unknown department 'NOPE'",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
preview_rows: [
|
||||||
|
{
|
||||||
|
row: 2,
|
||||||
|
asset_code: "PHRC-ICU-0901",
|
||||||
|
serial_no: "SN-901",
|
||||||
|
name: "Infusion Pump",
|
||||||
|
category_name: "Infusion Pump",
|
||||||
|
department_name: "ICU",
|
||||||
|
location_name: "ICU Bed 1",
|
||||||
|
status: "in_service",
|
||||||
|
valid: true,
|
||||||
|
error: null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
row: 3,
|
||||||
|
asset_code: "PHRC-BAD-1",
|
||||||
|
serial_no: "SN-902",
|
||||||
|
name: "Bad Device",
|
||||||
|
category_name: "Monitor",
|
||||||
|
department_name: "NOPE",
|
||||||
|
location_name: "Room 1",
|
||||||
|
status: "in_service",
|
||||||
|
valid: false,
|
||||||
|
error: "Unknown department 'NOPE'",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
dry_run: false,
|
||||||
|
total_rows: 2,
|
||||||
|
valid_count: 1,
|
||||||
|
error_count: 1,
|
||||||
|
created_count: 1,
|
||||||
|
errors: [],
|
||||||
|
preview_rows: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
const onClose = vi.fn();
|
||||||
|
renderModal(onClose);
|
||||||
|
|
||||||
|
const templateBtn = screen.getByRole("button", {
|
||||||
|
name: /Download Template \(\.xlsx\)/i,
|
||||||
|
});
|
||||||
|
fireEvent.click(templateBtn);
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(templateSpy).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
const fileInput = screen.getByLabelText("Upload asset spreadsheet");
|
||||||
|
const file = new File(["dummy"], "assets.xlsx", {
|
||||||
|
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
});
|
||||||
|
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(bulkImportSpy).toHaveBeenCalledWith(file, true, false);
|
||||||
|
expect(screen.getByText("Valid: 1")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("Errors: 1")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("PHRC-ICU-0901")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("Unknown department 'NOPE'")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
const importBtn = screen.getByRole("button", { name: /Import 1 Asset/i });
|
||||||
|
expect(importBtn).toBeDisabled();
|
||||||
|
|
||||||
|
const skipCheckbox = screen.getByLabelText(
|
||||||
|
/Skip invalid rows and import valid rows only/i
|
||||||
|
);
|
||||||
|
fireEvent.click(skipCheckbox);
|
||||||
|
expect(importBtn).toBeEnabled();
|
||||||
|
|
||||||
|
fireEvent.click(importBtn);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(bulkImportSpy).toHaveBeenNthCalledWith(2, file, false, true);
|
||||||
|
expect(onClose).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1 +1 @@
|
|||||||
{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/assets.ts","./src/api/attachments.ts","./src/api/audit.ts","./src/api/auth.ts","./src/api/calibration.ts","./src/api/client.ts","./src/api/complaints.ts","./src/api/dashboard.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/notifications.ts","./src/api/phase5.ts","./src/api/pm.ts","./src/api/reports.ts","./src/api/search.ts","./src/api/settings.ts","./src/components/assetformmodal.tsx","./src/components/assetpicker.tsx","./src/components/attachments.tsx","./src/components/calibrationmodals.tsx","./src/components/calibrationremindermodal.tsx","./src/components/confirmdialog.tsx","./src/components/insurancedrawer.tsx","./src/components/pmmodals.tsx","./src/components/raisecomplaintmodal.tsx","./src/components/statusbadge.tsx","./src/components/toastprovider.tsx","./src/components/datatable/datatable.test.tsx","./src/components/datatable/datatable.tsx","./src/components/datatable/index.ts","./src/components/layout/appshell.tsx","./src/components/layout/sidebar.tsx","./src/components/layout/topbar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/dialog.tsx","./src/hooks/useauth.ts","./src/lib/format.ts","./src/lib/permissions.ts","./src/lib/utils.ts","./src/pages/accessdeniedpage.tsx","./src/pages/assetdetailpage.tsx","./src/pages/assetspage.tsx","./src/pages/auditlogspage.tsx","./src/pages/calibrationpage.tsx","./src/pages/complaintdetailpage.tsx","./src/pages/complaintspage.tsx","./src/pages/contractspage.tsx","./src/pages/dashboardpage.tsx","./src/pages/datatabledemopage.tsx","./src/pages/demoequipmentpage.tsx","./src/pages/insurancepage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/notificationspage.tsx","./src/pages/pmpage.tsx","./src/pages/reportdetailpage.tsx","./src/pages/reportspage.tsx","./src/pages/settingspage.tsx","./src/pages/visitspage.tsx","./src/pages/stubs.tsx","./src/test/asset-picker.test.tsx","./src/test/attachments.test.tsx","./src/test/calibration-page.test.tsx","./src/test/complaint-detail.test.tsx","./src/test/login.test.tsx","./src/test/permissions.test.ts","./src/test/phase5-modules.test.tsx","./src/test/phase6-modules.test.tsx","./src/test/phase8-polish.test.tsx","./src/test/pm-page.test.tsx","./src/test/reports.test.tsx","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"}
|
{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/assets.ts","./src/api/attachments.ts","./src/api/audit.ts","./src/api/auth.ts","./src/api/calibration.ts","./src/api/client.ts","./src/api/complaints.ts","./src/api/dashboard.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/notifications.ts","./src/api/phase5.ts","./src/api/pm.ts","./src/api/reports.ts","./src/api/search.ts","./src/api/settings.ts","./src/components/assetformmodal.tsx","./src/components/assetpicker.tsx","./src/components/attachments.tsx","./src/components/bulkassetimportmodal.tsx","./src/components/calibrationmodals.tsx","./src/components/calibrationremindermodal.tsx","./src/components/confirmdialog.tsx","./src/components/insurancedrawer.tsx","./src/components/pmmodals.tsx","./src/components/raisecomplaintmodal.tsx","./src/components/statusbadge.tsx","./src/components/toastprovider.tsx","./src/components/datatable/datatable.test.tsx","./src/components/datatable/datatable.tsx","./src/components/datatable/index.ts","./src/components/layout/appshell.tsx","./src/components/layout/sidebar.tsx","./src/components/layout/topbar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/dialog.tsx","./src/hooks/useauth.ts","./src/lib/format.ts","./src/lib/permissions.ts","./src/lib/utils.ts","./src/pages/accessdeniedpage.tsx","./src/pages/assetdetailpage.tsx","./src/pages/assetspage.tsx","./src/pages/auditlogspage.tsx","./src/pages/calibrationpage.tsx","./src/pages/complaintdetailpage.tsx","./src/pages/complaintspage.tsx","./src/pages/contractspage.tsx","./src/pages/dashboardpage.tsx","./src/pages/datatabledemopage.tsx","./src/pages/demoequipmentpage.tsx","./src/pages/insurancepage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/notificationspage.tsx","./src/pages/pmpage.tsx","./src/pages/reportdetailpage.tsx","./src/pages/reportspage.tsx","./src/pages/settingspage.tsx","./src/pages/visitspage.tsx","./src/pages/stubs.tsx","./src/test/asset-picker.test.tsx","./src/test/attachments.test.tsx","./src/test/bulk-import.test.tsx","./src/test/calibration-page.test.tsx","./src/test/complaint-detail.test.tsx","./src/test/login.test.tsx","./src/test/permissions.test.ts","./src/test/phase5-modules.test.tsx","./src/test/phase6-modules.test.tsx","./src/test/phase8-polish.test.tsx","./src/test/pm-page.test.tsx","./src/test/reports.test.tsx","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"}
|
||||||
Reference in New Issue
Block a user