feat: excel exports, bulk asset import, and responsive layout improvements

This commit is contained in:
Atharv1705
2026-11-12 15:23:07 +05:30
parent 0a2db8454d
commit 22fad38280
23 changed files with 1560 additions and 95 deletions
+37 -1
View File
@@ -1,6 +1,7 @@
from datetime import date
from typing import Any, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, status
from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile, status
from fastapi.responses import StreamingResponse
from sqlalchemy import or_
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session, joinedload
@@ -44,6 +45,7 @@ from ..schemas.assets import (
PMScheduleSummaryOut,
WarrantySummaryOut,
)
from ..services.asset_import import build_import_template_xlsx, process_asset_import
from ..services.audit import log_audit
from ..services.calculations import compute_schedule_status, coverage_status
from ..services.permissions import Role
@@ -506,6 +508,40 @@ def create_asset(
return _to_asset_out(loaded, rels, effective_today(db), _lead_settings(db))
@router.get("/import-template")
def download_asset_import_template(
db: Session = Depends(get_db),
_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
):
buf = build_import_template_xlsx(db)
return StreamingResponse(
buf,
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
headers={
"Content-Disposition": 'attachment; filename="asset_import_template.xlsx"',
},
)
@router.post("/bulk-import")
def bulk_import_assets(
file: UploadFile = File(...),
dry_run: bool = Query(False),
skip_invalid: bool = Query(False),
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
):
content = file.file.read()
return process_asset_import(
db=db,
filename=file.filename or "upload.xlsx",
content=content,
user_id=current_user.id,
dry_run=dry_run,
skip_invalid=skip_invalid,
)
@router.get("/{asset_id}", response_model=AssetOut)
def get_asset(
asset_id: int,
+1
View File
@@ -89,6 +89,7 @@ def seed_database(db: Session, upload_dir: Path | None = None) -> dict[str, int]
except Exception:
pass
db.flush()
db.expunge_all()
# 2. Settings (14 keys)
ensure_default_settings(db)
+475
View File
@@ -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,
}
+227
View File
@@ -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"