479 lines
17 KiB
Python
479 lines
17 KiB
Python
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
|
|
from .settings_service import get_setting_value
|
|
|
|
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_prefix = str(get_setting_value(db, "asset_code_prefix", "PHRC")).strip() or "PHRC"
|
|
sample_dept_code = sample_dept.code if sample_dept else "ICU"
|
|
sample_row = [
|
|
f"{sample_prefix}-{sample_dept_code}-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,
|
|
}
|