fix: resolve audit report gaps across bulk imports, auth, scoping, and exports
This commit is contained in:
@@ -4,6 +4,9 @@ backend/data/uploads/*
|
||||
!backend/data/uploads/.gitkeep
|
||||
backend/data/backups/*
|
||||
!backend/data/backups/.gitkeep
|
||||
backend/data/*.db
|
||||
backend/data/*.zip
|
||||
backend/data/*.tar.gz
|
||||
backend/data/*
|
||||
!backend/data/.gitkeep
|
||||
!backend/data/uploads/
|
||||
@@ -18,6 +21,8 @@ __pycache__/
|
||||
*.pyc
|
||||
frontend/node_modules/
|
||||
frontend/dist/
|
||||
*.tsbuildinfo
|
||||
**/*.tsbuildinfo
|
||||
.env
|
||||
*.env.local
|
||||
.DS_Store
|
||||
|
||||
@@ -6,13 +6,19 @@ from sqlalchemy.orm import Session, joinedload
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import get_current_user
|
||||
from ..core.exceptions import CodedHTTPException
|
||||
from ..core.security import create_access_token, verify_password
|
||||
from ..core.security import create_access_token, hash_password, verify_password
|
||||
from ..models.masters import User
|
||||
from ..schemas.auth import LoginRequest, TokenResponse, UserOut
|
||||
from ..services.settings_service import get_demo_as_of_date
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
|
||||
class ChangePasswordRequest(BaseModel):
|
||||
current_password: str
|
||||
new_password: str = Field(..., min_length=6)
|
||||
|
||||
MAX_LOGIN_ATTEMPTS = 15
|
||||
LOGIN_WINDOW_SECONDS = 60.0
|
||||
_login_attempts: dict[str, deque[float]] = defaultdict(deque)
|
||||
@@ -91,3 +97,25 @@ def get_me(
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
return _build_user_out(current_user, db)
|
||||
|
||||
|
||||
@router.post("/change-password")
|
||||
def change_password(
|
||||
payload: ChangePasswordRequest,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
if not verify_password(payload.current_password, current_user.password_hash):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Current password is incorrect.",
|
||||
)
|
||||
new_pass = payload.new_password.strip()
|
||||
if len(new_pass) < 6:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="New password must be at least 6 characters.",
|
||||
)
|
||||
current_user.password_hash = hash_password(new_pass)
|
||||
db.commit()
|
||||
return {"message": "Password changed successfully."}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Body, Depends, HTTPException, Query, status
|
||||
from fastapi import APIRouter, Body, Depends, File, HTTPException, Query, UploadFile, status
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
@@ -26,7 +26,7 @@ from ..schemas.calibration import (
|
||||
CalibrationStatusFilter,
|
||||
)
|
||||
from ..services.audit import log_audit
|
||||
from ..services.bulk_templates import build_calibration_template_xlsx
|
||||
from ..services.bulk_templates import build_calibration_template_xlsx, process_calibration_import
|
||||
from ..services.calculations import compute_schedule_status
|
||||
from ..services.permissions import Role
|
||||
from ..services.settings_service import get_setting_value
|
||||
@@ -211,6 +211,27 @@ def download_calibration_import_template(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/bulk-import")
|
||||
def bulk_import_calibration(
|
||||
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, Role.coordinator, Role.management)
|
||||
),
|
||||
):
|
||||
content = file.file.read()
|
||||
return process_calibration_import(
|
||||
db=db,
|
||||
filename=file.filename or "calibration.xlsx",
|
||||
content=content,
|
||||
user_id=current_user.id,
|
||||
dry_run=dry_run,
|
||||
skip_invalid=skip_invalid,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/plans", response_model=CalibrationPlanListOut)
|
||||
def list_calibration_plans(
|
||||
q: str = "",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Query, Response, UploadFile, status
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
@@ -22,7 +22,7 @@ from ..schemas.contracts import (
|
||||
)
|
||||
from ..services.attachment_service import get_attachment_counts
|
||||
from ..services.audit import log_audit
|
||||
from ..services.bulk_templates import build_contracts_template_xlsx
|
||||
from ..services.bulk_templates import build_contracts_template_xlsx, process_contracts_import
|
||||
from ..services.calculations import coverage_status
|
||||
from ..services.permissions import Role
|
||||
from ..services.settings_service import get_setting_value
|
||||
@@ -104,6 +104,8 @@ def list_contracts(
|
||||
provider_id: Optional[int] = None,
|
||||
contract_type: Optional[ContractType] = None,
|
||||
status_filter: Optional[ContractStatusFilter] = Query(None, alias="status"),
|
||||
expiry_from: Optional[date] = None,
|
||||
expiry_to: Optional[date] = None,
|
||||
include_superseded: bool = True,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(200, ge=1, le=500),
|
||||
@@ -135,6 +137,10 @@ def list_contracts(
|
||||
query = query.filter(Contract.contract_type == contract_type)
|
||||
if not include_superseded:
|
||||
query = query.filter(Contract.is_superseded.is_(False))
|
||||
if expiry_from is not None:
|
||||
query = query.filter(Contract.end_date >= expiry_from)
|
||||
if expiry_to is not None:
|
||||
query = query.filter(Contract.end_date <= expiry_to)
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
@@ -202,6 +208,25 @@ def download_contracts_import_template(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/bulk-import")
|
||||
def bulk_import_contracts(
|
||||
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, Role.coordinator)),
|
||||
):
|
||||
content = file.file.read()
|
||||
return process_contracts_import(
|
||||
db=db,
|
||||
filename=file.filename or "contracts.xlsx",
|
||||
content=content,
|
||||
user_id=current_user.id,
|
||||
dry_run=dry_run,
|
||||
skip_invalid=skip_invalid,
|
||||
)
|
||||
|
||||
|
||||
@router.post("", response_model=ContractOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_contract(
|
||||
payload: ContractCreate,
|
||||
|
||||
@@ -49,9 +49,14 @@ def get_dashboard_summary(
|
||||
scoped_dept_id: int | None = None
|
||||
dept_scope_name: str | None = None
|
||||
if current_user.role == Role.department_user.value:
|
||||
scoped_dept_id = current_user.department_id
|
||||
dept_obj = db.query(Department).filter(Department.id == scoped_dept_id).first()
|
||||
dept_scope_name = dept_obj.name if dept_obj else None
|
||||
if current_user.department_id is not None:
|
||||
scoped_dept_id = current_user.department_id
|
||||
dept_obj = db.query(Department).filter(Department.id == scoped_dept_id).first()
|
||||
dept_scope_name = dept_obj.name if dept_obj else None
|
||||
else:
|
||||
# Department user with unassigned department must see zero scope, never hospital-wide
|
||||
scoped_dept_id = -1
|
||||
dept_scope_name = "Unassigned Department"
|
||||
|
||||
# Settings for dynamic calculations
|
||||
cal_lead = int(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Query, Response, UploadFile, status
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
@@ -18,7 +18,7 @@ from ..schemas.insurance import (
|
||||
)
|
||||
from ..services.attachment_service import get_attachment_counts
|
||||
from ..services.audit import log_audit
|
||||
from ..services.bulk_templates import build_insurance_template_xlsx
|
||||
from ..services.bulk_templates import build_insurance_template_xlsx, process_insurance_import
|
||||
from ..services.calculations import coverage_status
|
||||
from ..services.permissions import Role
|
||||
from ..services.settings_service import get_setting_value
|
||||
@@ -88,6 +88,8 @@ def list_insurance_policies(
|
||||
asset_id: Optional[int] = None,
|
||||
insurer_id: Optional[int] = None,
|
||||
status_filter: Optional[InsuranceStatusFilter] = Query(None, alias="status"),
|
||||
expiry_from: Optional[date] = None,
|
||||
expiry_to: Optional[date] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(200, ge=1, le=500),
|
||||
db: Session = Depends(get_db),
|
||||
@@ -114,6 +116,10 @@ def list_insurance_policies(
|
||||
query = query.filter(InsurancePolicy.asset_id == asset_id)
|
||||
if insurer_id is not None:
|
||||
query = query.filter(InsurancePolicy.insurer_id == insurer_id)
|
||||
if expiry_from is not None:
|
||||
query = query.filter(InsurancePolicy.end_date >= expiry_from)
|
||||
if expiry_to is not None:
|
||||
query = query.filter(InsurancePolicy.end_date <= expiry_to)
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
@@ -151,6 +157,25 @@ def download_insurance_import_template(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/bulk-import")
|
||||
def bulk_import_insurance(
|
||||
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, Role.coordinator)),
|
||||
):
|
||||
content = file.file.read()
|
||||
return process_insurance_import(
|
||||
db=db,
|
||||
filename=file.filename or "insurance.xlsx",
|
||||
content=content,
|
||||
user_id=current_user.id,
|
||||
dry_run=dry_run,
|
||||
skip_invalid=skip_invalid,
|
||||
)
|
||||
|
||||
|
||||
@router.post("", response_model=InsuranceOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_insurance_policy(
|
||||
payload: InsuranceCreate,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
@@ -19,6 +20,10 @@ from ..services.permissions import Role
|
||||
router = APIRouter(prefix="/users", tags=["users"])
|
||||
|
||||
|
||||
class ResetPasswordRequest(BaseModel):
|
||||
new_password: str = Field(..., min_length=6)
|
||||
|
||||
|
||||
def _user_list_out(user: User) -> UserListOut:
|
||||
return UserListOut(
|
||||
id=user.id,
|
||||
@@ -77,6 +82,12 @@ def create_user(
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
if payload.role == "department_user" and payload.department_id is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Department is required for department_user role.",
|
||||
)
|
||||
|
||||
if payload.department_id is not None:
|
||||
dept = db.query(Department).filter(Department.id == payload.department_id).first()
|
||||
if dept is None:
|
||||
@@ -108,13 +119,52 @@ def update_user(
|
||||
user_id: int,
|
||||
payload: UserUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
current_user: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
user = db.query(User).options(joinedload(User.department)).filter(User.id == user_id).first()
|
||||
if user is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found.")
|
||||
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
|
||||
# Department user validation
|
||||
target_role = data.get("role", user.role)
|
||||
target_dept = data.get("department_id", user.department_id)
|
||||
if target_role == "department_user" and target_dept is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Department is required for department_user role.",
|
||||
)
|
||||
|
||||
# Prevent self-deactivation or changing own admin role
|
||||
if user.id == current_user.id:
|
||||
if "is_active" in data and not data["is_active"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot deactivate your own administrator account.",
|
||||
)
|
||||
if "role" in data and data["role"] != "system_admin":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot change the role of your own administrator account.",
|
||||
)
|
||||
|
||||
# Prevent deactivating or demoting the last active system admin
|
||||
if user.role == "system_admin" and (
|
||||
("is_active" in data and not data["is_active"])
|
||||
or ("role" in data and data["role"] != "system_admin")
|
||||
):
|
||||
active_admins = (
|
||||
db.query(User)
|
||||
.filter(User.role == "system_admin", User.is_active.is_(True), User.id != user.id)
|
||||
.count()
|
||||
)
|
||||
if active_admins == 0:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot deactivate or change role: system must have at least one active system administrator.",
|
||||
)
|
||||
|
||||
if "department_id" in data and data["department_id"] is not None:
|
||||
dept = db.query(Department).filter(Department.id == data["department_id"]).first()
|
||||
if dept is None:
|
||||
@@ -153,12 +203,52 @@ def update_user(
|
||||
def delete_user(
|
||||
user_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
current_user: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
if user_id == current_user.id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot delete your own administrator account.",
|
||||
)
|
||||
|
||||
user = db.query(User).options(joinedload(User.department)).filter(User.id == user_id).first()
|
||||
if user is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found.")
|
||||
|
||||
if user.role == "system_admin":
|
||||
active_admins = (
|
||||
db.query(User)
|
||||
.filter(User.role == "system_admin", User.is_active.is_(True), User.id != user.id)
|
||||
.count()
|
||||
)
|
||||
if active_admins == 0:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot delete the only active system administrator account.",
|
||||
)
|
||||
|
||||
user.is_active = False
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
return _user_list_out(user)
|
||||
|
||||
|
||||
@router.post("/{user_id}/reset-password")
|
||||
def reset_user_password(
|
||||
user_id: int,
|
||||
payload: ResetPasswordRequest,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if user is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found.")
|
||||
new_pass = payload.new_password.strip()
|
||||
if len(new_pass) < 6:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Password must be at least 6 characters.",
|
||||
)
|
||||
user.password_hash = hash_password(new_pass)
|
||||
db.commit()
|
||||
return {"message": f"Password for {user.name} has been reset successfully."}
|
||||
|
||||
@@ -84,6 +84,8 @@ def list_warranties(
|
||||
department_id: Optional[int] = None,
|
||||
asset_id: Optional[int] = None,
|
||||
status_filter: Optional[CoverageStatusFilter] = Query(None, alias="status"),
|
||||
expiry_from: Optional[date] = None,
|
||||
expiry_to: Optional[date] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(200, ge=1, le=500),
|
||||
db: Session = Depends(get_db),
|
||||
@@ -108,6 +110,10 @@ def list_warranties(
|
||||
|
||||
if asset_id is not None:
|
||||
query = query.filter(Warranty.asset_id == asset_id)
|
||||
if expiry_from is not None:
|
||||
query = query.filter(Warranty.end_date >= expiry_from)
|
||||
if expiry_to is not None:
|
||||
query = query.filter(Warranty.end_date <= expiry_to)
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
|
||||
@@ -3,13 +3,29 @@ Poona Hospital Asset Management System
|
||||
Bulk Import Template Builders for Contracts, Calibration Plans, and Insurance Policies.
|
||||
"""
|
||||
|
||||
from io import BytesIO
|
||||
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 Alignment, Border, Font, PatternFill, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import Asset, Department, Vendor
|
||||
from ..core.exceptions import CodedHTTPException
|
||||
from ..core.time_utils import add_months, effective_today
|
||||
from ..models import (
|
||||
Asset,
|
||||
CalibrationPlan,
|
||||
CalibrationRecord,
|
||||
Contract,
|
||||
Department,
|
||||
InsurancePolicy,
|
||||
Vendor,
|
||||
)
|
||||
from .audit import log_audit
|
||||
from .settings_service import get_setting_value
|
||||
|
||||
_HEADER_FILL = PatternFill(start_color="1E3A8A", end_color="1E3A8A", fill_type="solid")
|
||||
@@ -263,3 +279,627 @@ def build_insurance_template_xlsx(db: Session) -> BytesIO:
|
||||
buf.seek(0)
|
||||
return buf
|
||||
|
||||
|
||||
def _clean_str(val: Any) -> str:
|
||||
if val is None:
|
||||
return ""
|
||||
return str(val).strip()
|
||||
|
||||
|
||||
def _parse_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, f"Missing required field '{field_name}'"
|
||||
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", "%d/%m/%Y", "%m/%d/%Y", "%Y/%m/%d", "%d-%m-%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_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 _parse_positive_int(val: Any, field_name: str) -> tuple[int | None, str | None]:
|
||||
if val is None or (isinstance(val, str) and not val.strip()):
|
||||
return None, f"Missing required field '{field_name}'"
|
||||
try:
|
||||
parsed = int(float(val))
|
||||
except (TypeError, ValueError):
|
||||
return None, f"Invalid {field_name} '{val}' (must be an integer)"
|
||||
if parsed <= 0:
|
||||
return None, f"{field_name} must be greater than 0"
|
||||
return parsed, None
|
||||
|
||||
|
||||
def _extract_rows(filename: str, content: bytes, sheet_name: str | None = None) -> list[tuple[int, dict[str, Any]]]:
|
||||
ext = Path(filename or "").suffix.lower()
|
||||
if ext not in (".xlsx", ".csv", ".xls"):
|
||||
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 in (".xlsx", ".xls"):
|
||||
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[sheet_name] if sheet_name and sheet_name 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(" ", "_").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(" ", "_").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_contracts_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, sheet_name="Contracts")
|
||||
|
||||
assets = db.query(Asset).all()
|
||||
asset_lookup: dict[str, Asset] = {a.asset_code.strip().lower(): a for a in assets if a.asset_code}
|
||||
|
||||
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).all()
|
||||
vendor_lookup: dict[str, Vendor] = {}
|
||||
for v in vendors:
|
||||
vendor_lookup[v.name.strip().lower()] = v
|
||||
|
||||
errors: list[dict[str, Any]] = []
|
||||
preview_rows: list[dict[str, Any]] = []
|
||||
valid_records: list[dict[str, Any]] = []
|
||||
|
||||
for row_idx, row_dict in raw_rows:
|
||||
row_errors: list[str] = []
|
||||
|
||||
asset_code = _clean_str(row_dict.get("asset_code"))
|
||||
provider_name = _clean_str(
|
||||
row_dict.get("provider_name")
|
||||
or row_dict.get("vendor_name")
|
||||
or row_dict.get("provider")
|
||||
or row_dict.get("vendor")
|
||||
)
|
||||
contract_type_raw = _clean_str(row_dict.get("contract_type")).upper()
|
||||
start_date_val = row_dict.get("start_date")
|
||||
end_date_val = row_dict.get("end_date")
|
||||
cost_val = row_dict.get("cost")
|
||||
coverage_details = _clean_str(row_dict.get("coverage_details") or row_dict.get("coverage_period_text"))
|
||||
remarks = _clean_str(row_dict.get("remarks"))
|
||||
|
||||
target_asset = None
|
||||
if not asset_code:
|
||||
row_errors.append("Missing required field 'asset_code'")
|
||||
else:
|
||||
target_asset = asset_lookup.get(asset_code.lower())
|
||||
if not target_asset:
|
||||
row_errors.append(f"Asset with code '{asset_code}' not found")
|
||||
|
||||
target_vendor = None
|
||||
if not provider_name:
|
||||
row_errors.append("Missing required field 'provider_name'")
|
||||
else:
|
||||
target_vendor = vendor_lookup.get(provider_name.lower())
|
||||
if not target_vendor:
|
||||
row_errors.append(f"Provider vendor '{provider_name}' not found")
|
||||
|
||||
if not contract_type_raw:
|
||||
row_errors.append("Missing required field 'contract_type'")
|
||||
elif contract_type_raw not in ("AMC", "CMC", "OTHER"):
|
||||
row_errors.append(f"Invalid contract_type '{contract_type_raw}' (expected AMC, CMC, or OTHER)")
|
||||
|
||||
start_date, s_err = _parse_date(start_date_val, "start_date")
|
||||
if s_err:
|
||||
row_errors.append(s_err)
|
||||
|
||||
end_date, e_err = _parse_date(end_date_val, "end_date")
|
||||
if e_err:
|
||||
row_errors.append(e_err)
|
||||
|
||||
if start_date and end_date and end_date < start_date:
|
||||
row_errors.append("end_date cannot be earlier than start_date")
|
||||
|
||||
cost, c_err = _parse_optional_float(cost_val, "cost")
|
||||
if c_err:
|
||||
row_errors.append(c_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, "message": err_text})
|
||||
else:
|
||||
combined_remarks = remarks
|
||||
if cost is not None and cost > 0:
|
||||
cost_str = f"Cost: ₹{cost:,.2f}"
|
||||
combined_remarks = f"{remarks} ({cost_str})" if remarks else cost_str
|
||||
|
||||
valid_records.append({
|
||||
"asset_id": target_asset.id,
|
||||
"provider_id": target_vendor.id,
|
||||
"contract_type": contract_type_raw,
|
||||
"start_date": start_date,
|
||||
"end_date": end_date,
|
||||
"coverage_period_text": coverage_details or f"{start_date} to {end_date}",
|
||||
"remarks": combined_remarks or None,
|
||||
})
|
||||
|
||||
preview_rows.append({
|
||||
"row": row_idx,
|
||||
"data": {
|
||||
"asset_code": asset_code,
|
||||
"provider_name": provider_name,
|
||||
"contract_type": contract_type_raw,
|
||||
"start_date": str(start_date) if start_date else str(start_date_val or ""),
|
||||
"end_date": str(end_date) if end_date else str(end_date_val or ""),
|
||||
"cost": cost,
|
||||
"coverage_details": coverage_details,
|
||||
"remarks": remarks,
|
||||
},
|
||||
"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_records:
|
||||
for item in valid_records:
|
||||
contract = Contract(
|
||||
asset_id=item["asset_id"],
|
||||
provider_id=item["provider_id"],
|
||||
contract_type=item["contract_type"],
|
||||
start_date=item["start_date"],
|
||||
end_date=item["end_date"],
|
||||
coverage_period_text=item["coverage_period_text"],
|
||||
renewed_from_id=None,
|
||||
is_superseded=False,
|
||||
remarks=item["remarks"],
|
||||
created_by_id=user_id,
|
||||
updated_by_id=user_id,
|
||||
)
|
||||
db.add(contract)
|
||||
db.flush()
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="contract",
|
||||
entity_id=contract.id,
|
||||
action="create",
|
||||
changes={
|
||||
"asset_id": item["asset_id"],
|
||||
"contract_type": item["contract_type"],
|
||||
"provider_id": item["provider_id"],
|
||||
"start_date": str(item["start_date"]),
|
||||
"end_date": str(item["end_date"]),
|
||||
"source": "bulk_import",
|
||||
},
|
||||
user_id=user_id,
|
||||
)
|
||||
db.commit()
|
||||
created_count = len(valid_records)
|
||||
|
||||
return {
|
||||
"dry_run": dry_run,
|
||||
"total_rows": len(raw_rows),
|
||||
"valid_count": len(valid_records),
|
||||
"error_count": len(errors),
|
||||
"created_count": created_count,
|
||||
"errors": errors,
|
||||
"preview_rows": preview_rows,
|
||||
}
|
||||
|
||||
|
||||
def process_calibration_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, sheet_name="Calibration Plans")
|
||||
|
||||
assets = db.query(Asset).all()
|
||||
asset_lookup: dict[str, Asset] = {a.asset_code.strip().lower(): a for a in assets if a.asset_code}
|
||||
|
||||
existing_plan_asset_ids = {p.asset_id for p in db.query(CalibrationPlan.asset_id).all()}
|
||||
seen_asset_ids: set[int] = set()
|
||||
|
||||
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).all()
|
||||
vendor_lookup: dict[str, Vendor] = {}
|
||||
for v in vendors:
|
||||
vendor_lookup[v.name.strip().lower()] = v
|
||||
|
||||
today = effective_today(db)
|
||||
|
||||
errors: list[dict[str, Any]] = []
|
||||
preview_rows: list[dict[str, Any]] = []
|
||||
valid_records: list[dict[str, Any]] = []
|
||||
|
||||
for row_idx, row_dict in raw_rows:
|
||||
row_errors: list[str] = []
|
||||
|
||||
asset_code = _clean_str(row_dict.get("asset_code"))
|
||||
freq_val = row_dict.get("frequency_months")
|
||||
agency_name = _clean_str(
|
||||
row_dict.get("agency_name")
|
||||
or row_dict.get("vendor_name")
|
||||
or row_dict.get("agency")
|
||||
)
|
||||
next_due_val = row_dict.get("next_due_date")
|
||||
scope = _clean_str(row_dict.get("scope"))
|
||||
standards = _clean_str(row_dict.get("standards"))
|
||||
remarks = _clean_str(row_dict.get("remarks"))
|
||||
|
||||
target_asset = None
|
||||
if not asset_code:
|
||||
row_errors.append("Missing required field 'asset_code'")
|
||||
else:
|
||||
target_asset = asset_lookup.get(asset_code.lower())
|
||||
if not target_asset:
|
||||
row_errors.append(f"Asset with code '{asset_code}' not found")
|
||||
elif target_asset.id in existing_plan_asset_ids:
|
||||
row_errors.append(f"Calibration plan already exists for asset '{asset_code}'")
|
||||
elif target_asset.id in seen_asset_ids:
|
||||
row_errors.append(f"Duplicate calibration plan for asset '{asset_code}' in upload file")
|
||||
else:
|
||||
seen_asset_ids.add(target_asset.id)
|
||||
|
||||
freq_months, f_err = _parse_positive_int(freq_val, "frequency_months")
|
||||
if f_err:
|
||||
row_errors.append(f_err)
|
||||
|
||||
target_agency = None
|
||||
if agency_name:
|
||||
target_agency = vendor_lookup.get(agency_name.lower())
|
||||
if not target_agency:
|
||||
row_errors.append(f"Calibration agency vendor '{agency_name}' not found")
|
||||
|
||||
due_date = None
|
||||
if next_due_val:
|
||||
d_parsed, d_err = _parse_date(next_due_val, "next_due_date")
|
||||
if d_err:
|
||||
row_errors.append(d_err)
|
||||
else:
|
||||
due_date = d_parsed
|
||||
elif freq_months:
|
||||
due_date = add_months(today, freq_months)
|
||||
|
||||
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, "message": err_text})
|
||||
else:
|
||||
valid_records.append({
|
||||
"asset": target_asset,
|
||||
"frequency_months": freq_months,
|
||||
"agency_id": target_agency.id if target_agency else None,
|
||||
"next_due_date": due_date,
|
||||
"remarks": remarks,
|
||||
})
|
||||
|
||||
preview_rows.append({
|
||||
"row": row_idx,
|
||||
"data": {
|
||||
"asset_code": asset_code,
|
||||
"frequency_months": freq_months if freq_months else freq_val,
|
||||
"agency_name": agency_name,
|
||||
"next_due_date": str(due_date) if due_date else str(next_due_val or ""),
|
||||
"scope": scope,
|
||||
"standards": standards,
|
||||
"remarks": remarks,
|
||||
},
|
||||
"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_records:
|
||||
for item in valid_records:
|
||||
asset = item["asset"]
|
||||
freq = item["frequency_months"]
|
||||
agency_id = item["agency_id"]
|
||||
due_date = item["next_due_date"]
|
||||
per_year = max(1, round(12 / freq))
|
||||
|
||||
asset.requires_calibration = True
|
||||
asset.updated_by_id = user_id
|
||||
|
||||
plan = CalibrationPlan(
|
||||
asset_id=asset.id,
|
||||
frequency_months=freq,
|
||||
calibrations_per_year=per_year,
|
||||
agency_id=agency_id,
|
||||
approved_by_id=user_id,
|
||||
approved_on=today,
|
||||
next_due_date=due_date,
|
||||
is_active=True,
|
||||
created_by_id=user_id,
|
||||
updated_by_id=user_id,
|
||||
)
|
||||
db.add(plan)
|
||||
db.flush()
|
||||
|
||||
initial_rec = CalibrationRecord(
|
||||
asset_id=asset.id,
|
||||
plan_id=plan.id,
|
||||
due_date=due_date,
|
||||
agency_id=agency_id,
|
||||
status=None,
|
||||
created_by_id=user_id,
|
||||
updated_by_id=user_id,
|
||||
)
|
||||
db.add(initial_rec)
|
||||
db.flush()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="calibration_plan",
|
||||
entity_id=plan.id,
|
||||
action="create",
|
||||
changes={
|
||||
"asset_id": asset.id,
|
||||
"frequency_months": freq,
|
||||
"calibrations_per_year": per_year,
|
||||
"next_due_date": str(due_date),
|
||||
"approved": True,
|
||||
"initial_record_id": initial_rec.id,
|
||||
"source": "bulk_import",
|
||||
},
|
||||
user_id=user_id,
|
||||
)
|
||||
db.commit()
|
||||
created_count = len(valid_records)
|
||||
|
||||
return {
|
||||
"dry_run": dry_run,
|
||||
"total_rows": len(raw_rows),
|
||||
"valid_count": len(valid_records),
|
||||
"error_count": len(errors),
|
||||
"created_count": created_count,
|
||||
"errors": errors,
|
||||
"preview_rows": preview_rows,
|
||||
}
|
||||
|
||||
|
||||
def process_insurance_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, sheet_name="Insurance Policies")
|
||||
|
||||
assets = db.query(Asset).all()
|
||||
asset_lookup: dict[str, Asset] = {a.asset_code.strip().lower(): a for a in assets if a.asset_code}
|
||||
|
||||
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).all()
|
||||
vendor_lookup: dict[str, Vendor] = {}
|
||||
for v in vendors:
|
||||
vendor_lookup[v.name.strip().lower()] = v
|
||||
|
||||
errors: list[dict[str, Any]] = []
|
||||
preview_rows: list[dict[str, Any]] = []
|
||||
valid_records: list[dict[str, Any]] = []
|
||||
|
||||
for row_idx, row_dict in raw_rows:
|
||||
row_errors: list[str] = []
|
||||
|
||||
asset_code = _clean_str(row_dict.get("asset_code"))
|
||||
insurer_name = _clean_str(
|
||||
row_dict.get("insurer_name")
|
||||
or row_dict.get("vendor_name")
|
||||
or row_dict.get("insurer")
|
||||
or row_dict.get("vendor")
|
||||
)
|
||||
policy_no = _clean_str(
|
||||
row_dict.get("policy_number")
|
||||
or row_dict.get("policy_no")
|
||||
or row_dict.get("policy_num")
|
||||
)
|
||||
start_date_val = row_dict.get("start_date")
|
||||
end_date_val = row_dict.get("end_date")
|
||||
insured_val = row_dict.get("insured_value") or row_dict.get("coverage_amount")
|
||||
premium_val = row_dict.get("premium")
|
||||
remarks = _clean_str(row_dict.get("remarks"))
|
||||
|
||||
target_asset = None
|
||||
if not asset_code:
|
||||
row_errors.append("Missing required field 'asset_code'")
|
||||
else:
|
||||
target_asset = asset_lookup.get(asset_code.lower())
|
||||
if not target_asset:
|
||||
row_errors.append(f"Asset with code '{asset_code}' not found")
|
||||
|
||||
target_vendor = None
|
||||
if not insurer_name:
|
||||
row_errors.append("Missing required field 'insurer_name'")
|
||||
else:
|
||||
target_vendor = vendor_lookup.get(insurer_name.lower())
|
||||
if not target_vendor:
|
||||
row_errors.append(f"Insurer vendor '{insurer_name}' not found")
|
||||
|
||||
if not policy_no:
|
||||
row_errors.append("Missing required field 'policy_number'")
|
||||
|
||||
start_date, s_err = _parse_date(start_date_val, "start_date")
|
||||
if s_err:
|
||||
row_errors.append(s_err)
|
||||
|
||||
end_date, e_err = _parse_date(end_date_val, "end_date")
|
||||
if e_err:
|
||||
row_errors.append(e_err)
|
||||
|
||||
if start_date and end_date and end_date < start_date:
|
||||
row_errors.append("end_date cannot be earlier than start_date")
|
||||
|
||||
coverage_amount, ca_err = _parse_optional_float(insured_val, "insured_value")
|
||||
if ca_err:
|
||||
row_errors.append(ca_err)
|
||||
|
||||
premium, p_err = _parse_optional_float(premium_val, "premium")
|
||||
if p_err:
|
||||
row_errors.append(p_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, "message": err_text})
|
||||
else:
|
||||
combined_remarks = remarks
|
||||
if premium is not None and premium > 0:
|
||||
p_str = f"Premium: ₹{premium:,.2f}"
|
||||
combined_remarks = f"{remarks} ({p_str})" if remarks else p_str
|
||||
|
||||
valid_records.append({
|
||||
"asset": target_asset,
|
||||
"insurer_id": target_vendor.id,
|
||||
"policy_no": policy_no,
|
||||
"start_date": start_date,
|
||||
"end_date": end_date,
|
||||
"coverage_amount": coverage_amount,
|
||||
"remarks": combined_remarks or None,
|
||||
})
|
||||
|
||||
preview_rows.append({
|
||||
"row": row_idx,
|
||||
"data": {
|
||||
"asset_code": asset_code,
|
||||
"insurer_name": insurer_name,
|
||||
"policy_number": policy_no,
|
||||
"start_date": str(start_date) if start_date else str(start_date_val or ""),
|
||||
"end_date": str(end_date) if end_date else str(end_date_val or ""),
|
||||
"insured_value": coverage_amount,
|
||||
"premium": premium,
|
||||
"remarks": remarks,
|
||||
},
|
||||
"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_records:
|
||||
for item in valid_records:
|
||||
asset = item["asset"]
|
||||
asset.insurance_applicable = True
|
||||
asset.updated_by_id = user_id
|
||||
|
||||
policy = InsurancePolicy(
|
||||
asset_id=asset.id,
|
||||
insurer_id=item["insurer_id"],
|
||||
policy_no=item["policy_no"],
|
||||
start_date=item["start_date"],
|
||||
end_date=item["end_date"],
|
||||
coverage_amount=item["coverage_amount"],
|
||||
remarks=item["remarks"],
|
||||
created_by_id=user_id,
|
||||
updated_by_id=user_id,
|
||||
)
|
||||
db.add(policy)
|
||||
db.flush()
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="insurance_policy",
|
||||
entity_id=policy.id,
|
||||
action="create",
|
||||
changes={
|
||||
"asset_id": asset.id,
|
||||
"insurer_id": item["insurer_id"],
|
||||
"policy_no": item["policy_no"],
|
||||
"start_date": str(item["start_date"]),
|
||||
"end_date": str(item["end_date"]),
|
||||
"coverage_amount": item["coverage_amount"],
|
||||
"source": "bulk_import",
|
||||
},
|
||||
user_id=user_id,
|
||||
)
|
||||
db.commit()
|
||||
created_count = len(valid_records)
|
||||
|
||||
return {
|
||||
"dry_run": dry_run,
|
||||
"total_rows": len(raw_rows),
|
||||
"valid_count": len(valid_records),
|
||||
"error_count": len(errors),
|
||||
"created_count": created_count,
|
||||
"errors": errors,
|
||||
"preview_rows": preview_rows,
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import csv
|
||||
from io import BytesIO, StringIO
|
||||
import re
|
||||
from typing import Any
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||
@@ -8,6 +9,12 @@ from openpyxl.utils import get_column_letter
|
||||
from ..core.time_utils import format_datetime, utc_now
|
||||
|
||||
|
||||
def _sanitize_sheet_title(title: str) -> str:
|
||||
"""Sanitize Excel sheet title to comply with openpyxl / Excel naming rules."""
|
||||
cleaned = re.sub(r'[\\/*?:\[\]]', '_', title or "Report").strip()
|
||||
return cleaned[:31] or "Report"
|
||||
|
||||
|
||||
def _format_filters_echo(filters_applied: dict[str, Any]) -> str:
|
||||
if not filters_applied:
|
||||
return "None"
|
||||
@@ -86,7 +93,7 @@ def _detect_cell_format(col_key: str, col_label: str, val: Any) -> tuple[Alignme
|
||||
def build_xlsx(report_payload: dict[str, Any]) -> BytesIO:
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = report_payload["title"][:31]
|
||||
ws.title = _sanitize_sheet_title(report_payload.get("title", "Report"))
|
||||
|
||||
# Explicitly show grid lines in Excel view
|
||||
ws.views.sheetView[0].showGridLines = True
|
||||
|
||||
@@ -34,8 +34,25 @@ def get_default_paths() -> tuple[Path, Path, Path]:
|
||||
script_dir = Path(__file__).resolve().parent
|
||||
backend_dir = script_dir.parent
|
||||
data_dir = backend_dir / "data"
|
||||
db_path = data_dir / "ams.db"
|
||||
uploads_dir = data_dir / "uploads"
|
||||
|
||||
# Support DATABASE_URL environment variable if set (e.g. sqlite:///./data/ams.db or sqlite:///data/ams.db)
|
||||
db_url = os.environ.get("DATABASE_URL", "").strip()
|
||||
if db_url.startswith("sqlite:///"):
|
||||
sqlite_file = db_url.replace("sqlite:///", "").lstrip("./")
|
||||
db_path = Path(sqlite_file)
|
||||
if not db_path.is_absolute():
|
||||
db_path = backend_dir / sqlite_file
|
||||
else:
|
||||
db_path = data_dir / "ams.db"
|
||||
|
||||
upload_env = os.environ.get("UPLOAD_DIR", "").strip()
|
||||
if upload_env:
|
||||
uploads_dir = Path(upload_env)
|
||||
if not uploads_dir.is_absolute():
|
||||
uploads_dir = backend_dir / uploads_dir
|
||||
else:
|
||||
uploads_dir = data_dir / "uploads"
|
||||
|
||||
backups_dir = data_dir / "backups"
|
||||
return db_path, uploads_dir, backups_dir
|
||||
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
from io import BytesIO
|
||||
import openpyxl
|
||||
import pytest
|
||||
|
||||
from app.models import Asset, CalibrationPlan, CalibrationRecord, Contract, InsurancePolicy, Vendor
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_extra_import_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("extra_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(sheet_name: str, headers: list[str], rows: list[list[object]]) -> bytes:
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = sheet_name
|
||||
ws.append(headers)
|
||||
for r in rows:
|
||||
ws.append(r)
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def test_contracts_bulk_import_lifecycle(client, db):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
asset = db.query(Asset).filter(Asset.asset_code.isnot(None)).first()
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
assert asset is not None
|
||||
assert vendor is not None
|
||||
|
||||
headers = [
|
||||
"asset_code",
|
||||
"provider_name",
|
||||
"contract_type",
|
||||
"start_date",
|
||||
"end_date",
|
||||
"cost",
|
||||
"coverage_details",
|
||||
"remarks",
|
||||
]
|
||||
|
||||
# 1 valid, 1 invalid (invalid contract_type)
|
||||
rows = [
|
||||
[
|
||||
asset.asset_code,
|
||||
vendor.name,
|
||||
"CMC",
|
||||
"2026-01-01",
|
||||
"2026-12-31",
|
||||
85000,
|
||||
"All parts included",
|
||||
"Annual contract",
|
||||
],
|
||||
[
|
||||
asset.asset_code,
|
||||
vendor.name,
|
||||
"INVALID_TYPE",
|
||||
"2026-01-01",
|
||||
"2026-12-31",
|
||||
50000,
|
||||
"Test",
|
||||
"Test remarks",
|
||||
],
|
||||
]
|
||||
|
||||
xlsx_bytes = _make_xlsx_bytes("Contracts", headers, rows)
|
||||
|
||||
# Dry run
|
||||
res = client.post(
|
||||
"/api/contracts/bulk-import?dry_run=true",
|
||||
headers=admin_headers,
|
||||
files={"file": ("contracts_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
assert data["dry_run"] is True
|
||||
assert data["total_rows"] == 2
|
||||
assert data["valid_count"] == 1
|
||||
assert data["error_count"] == 1
|
||||
assert data["created_count"] == 0
|
||||
|
||||
# Fail commit without skip_invalid
|
||||
res_fail = client.post(
|
||||
"/api/contracts/bulk-import?dry_run=false&skip_invalid=false",
|
||||
headers=admin_headers,
|
||||
files={"file": ("contracts_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res_fail.status_code == 400
|
||||
|
||||
# Commit with skip_invalid
|
||||
res_commit = client.post(
|
||||
"/api/contracts/bulk-import?dry_run=false&skip_invalid=true",
|
||||
headers=admin_headers,
|
||||
files={"file": ("contracts_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res_commit.status_code == 200
|
||||
commit_data = res_commit.json()
|
||||
assert commit_data["created_count"] == 1
|
||||
|
||||
created_contract = (
|
||||
db.query(Contract)
|
||||
.filter(Contract.asset_id == asset.id, Contract.contract_type == "CMC")
|
||||
.order_by(Contract.id.desc())
|
||||
.first()
|
||||
)
|
||||
assert created_contract is not None
|
||||
assert created_contract.provider_id == vendor.id
|
||||
|
||||
|
||||
def test_calibration_bulk_import_lifecycle(client, db):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
# Find asset without calibration plan
|
||||
existing_plan_ids = [p.asset_id for p in db.query(CalibrationPlan.asset_id).all()]
|
||||
asset = db.query(Asset).filter(Asset.id.notin_(existing_plan_ids)).first()
|
||||
assert asset is not None
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
assert vendor is not None
|
||||
|
||||
headers = [
|
||||
"asset_code",
|
||||
"frequency_months",
|
||||
"agency_name",
|
||||
"scope",
|
||||
"standards",
|
||||
"remarks",
|
||||
]
|
||||
|
||||
rows = [
|
||||
[
|
||||
asset.asset_code,
|
||||
12,
|
||||
vendor.name,
|
||||
"Accuracy verification",
|
||||
"ISO 17025",
|
||||
"Imported plan",
|
||||
],
|
||||
]
|
||||
|
||||
xlsx_bytes = _make_xlsx_bytes("Calibration Plans", headers, rows)
|
||||
|
||||
# Dry run
|
||||
res = client.post(
|
||||
"/api/calibration/bulk-import?dry_run=true",
|
||||
headers=admin_headers,
|
||||
files={"file": ("cal_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
assert data["valid_count"] == 1
|
||||
assert data["error_count"] == 0
|
||||
|
||||
# Commit
|
||||
res_commit = client.post(
|
||||
"/api/calibration/bulk-import?dry_run=false",
|
||||
headers=admin_headers,
|
||||
files={"file": ("cal_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res_commit.status_code == 200
|
||||
assert res_commit.json()["created_count"] == 1
|
||||
|
||||
plan = db.query(CalibrationPlan).filter(CalibrationPlan.asset_id == asset.id).first()
|
||||
assert plan is not None
|
||||
assert plan.frequency_months == 12
|
||||
|
||||
record = db.query(CalibrationRecord).filter(CalibrationRecord.plan_id == plan.id).first()
|
||||
assert record is not None
|
||||
|
||||
|
||||
def test_insurance_bulk_import_lifecycle(client, db):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
asset = db.query(Asset).filter(Asset.asset_code.isnot(None)).first()
|
||||
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||
assert asset is not None
|
||||
assert vendor is not None
|
||||
|
||||
headers = [
|
||||
"asset_code",
|
||||
"insurer_name",
|
||||
"policy_number",
|
||||
"start_date",
|
||||
"end_date",
|
||||
"insured_value",
|
||||
"premium",
|
||||
"remarks",
|
||||
]
|
||||
|
||||
rows = [
|
||||
[
|
||||
asset.asset_code,
|
||||
vendor.name,
|
||||
"POL-TEST-9999",
|
||||
"2026-04-01",
|
||||
"2027-03-31",
|
||||
1200000,
|
||||
15000,
|
||||
"Annual equipment insurance",
|
||||
],
|
||||
]
|
||||
|
||||
xlsx_bytes = _make_xlsx_bytes("Insurance Policies", headers, rows)
|
||||
|
||||
# Dry run
|
||||
res = client.post(
|
||||
"/api/insurance/bulk-import?dry_run=true",
|
||||
headers=admin_headers,
|
||||
files={"file": ("ins_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
assert data["valid_count"] == 1
|
||||
assert data["error_count"] == 0
|
||||
|
||||
# Commit
|
||||
res_commit = client.post(
|
||||
"/api/insurance/bulk-import?dry_run=false",
|
||||
headers=admin_headers,
|
||||
files={"file": ("ins_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert res_commit.status_code == 200
|
||||
assert res_commit.json()["created_count"] == 1
|
||||
|
||||
pol = db.query(InsurancePolicy).filter(InsurancePolicy.policy_no == "POL-TEST-9999").first()
|
||||
assert pol is not None
|
||||
assert pol.coverage_amount == 1200000
|
||||
assert pol.asset_id == asset.id
|
||||
@@ -242,3 +242,34 @@ def test_report_exports_xlsx_and_csv(client):
|
||||
headers=mgmt_headers,
|
||||
)
|
||||
assert bad_fmt.status_code == 422
|
||||
|
||||
|
||||
def test_all_eight_reports_export_xlsx_and_csv(client):
|
||||
"""Verify that all 8 reports export cleanly as both XLSX and CSV without title/slash errors."""
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
for key in ALL_REPORT_KEYS:
|
||||
# Test XLSX export
|
||||
xlsx_res = client.get(
|
||||
f"/api/reports/{key}/export?format=xlsx",
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert xlsx_res.status_code == 200, f"XLSX export failed for {key}: {xlsx_res.text}"
|
||||
assert "spreadsheetml.sheet" in xlsx_res.headers["content-type"]
|
||||
assert f'filename="{key}.xlsx"' in xlsx_res.headers["content-disposition"]
|
||||
|
||||
wb = openpyxl.load_workbook(BytesIO(xlsx_res.content))
|
||||
ws = wb.active
|
||||
assert ws is not None
|
||||
assert "/" not in ws.title and "\\" not in ws.title
|
||||
assert len(ws.title) <= 31
|
||||
|
||||
# Test CSV export
|
||||
csv_res = client.get(
|
||||
f"/api/reports/{key}/export?format=csv",
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert csv_res.status_code == 200, f"CSV export failed for {key}: {csv_res.text}"
|
||||
assert "text/csv" in csv_res.headers["content-type"]
|
||||
assert f'filename="{key}.csv"' in csv_res.headers["content-disposition"]
|
||||
|
||||
|
||||
@@ -25,3 +25,10 @@ export function loginApi(email: string, password: string) {
|
||||
export function fetchMeApi() {
|
||||
return api.get<UserOut>("/auth/me");
|
||||
}
|
||||
|
||||
export function changePasswordApi(current_password: string, new_password: string) {
|
||||
return api.post<{ message: string }>("/auth/change-password", {
|
||||
current_password,
|
||||
new_password,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { api } from "./client";
|
||||
import type { BulkImportResult } from "./assets";
|
||||
|
||||
export interface CalibrationPlanItem {
|
||||
id: number;
|
||||
@@ -153,4 +154,12 @@ export const calibrationApi = {
|
||||
a.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
},
|
||||
bulkImport: (file: File, dryRun: boolean, skipInvalid: boolean) => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
return api.upload<BulkImportResult>(
|
||||
`/calibration/bulk-import?dry_run=${dryRun}&skip_invalid=${skipInvalid}`,
|
||||
formData
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { api } from "./client";
|
||||
import type { AlertSeverity, CoverageStatus } from "./assets";
|
||||
import type { AlertSeverity, BulkImportResult, CoverageStatus } from "./assets";
|
||||
|
||||
export type ContractStatus = CoverageStatus | "superseded";
|
||||
export type DemoStatus = "on_demo" | "overdue_return" | "returned";
|
||||
@@ -35,6 +35,8 @@ export interface ContractListParams {
|
||||
contract_type?: string;
|
||||
status?: string;
|
||||
include_superseded?: boolean;
|
||||
expiry_from?: string;
|
||||
expiry_to?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
@@ -83,6 +85,8 @@ export interface WarrantyListParams {
|
||||
department_id?: number;
|
||||
asset_id?: number;
|
||||
status?: string;
|
||||
expiry_from?: string;
|
||||
expiry_to?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
@@ -123,6 +127,8 @@ export interface InsuranceListParams {
|
||||
asset_id?: number;
|
||||
insurer_id?: number;
|
||||
status?: string;
|
||||
expiry_from?: string;
|
||||
expiry_to?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
@@ -266,6 +272,14 @@ export const contractsApi = {
|
||||
a.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
},
|
||||
bulkImport: (file: File, dryRun: boolean, skipInvalid: boolean) => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
return api.upload<BulkImportResult>(
|
||||
`/contracts/bulk-import?dry_run=${dryRun}&skip_invalid=${skipInvalid}`,
|
||||
formData
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
export const warrantiesApi = {
|
||||
@@ -299,6 +313,14 @@ export const insuranceApi = {
|
||||
a.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
},
|
||||
bulkImport: (file: File, dryRun: boolean, skipInvalid: boolean) => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
return api.upload<BulkImportResult>(
|
||||
`/insurance/bulk-import?dry_run=${dryRun}&skip_invalid=${skipInvalid}`,
|
||||
formData
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
export const demoEquipmentApi = {
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
Download,
|
||||
FileSpreadsheet,
|
||||
Upload,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import 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 "@/lib/toast";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface PreviewColumn {
|
||||
key: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
interface BulkGenericImportModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
title: string;
|
||||
description: string;
|
||||
entityName: string;
|
||||
templateFilename: string;
|
||||
onDownloadTemplate: () => Promise<void>;
|
||||
onImport: (file: File, dryRun: boolean, skipInvalid: boolean) => Promise<BulkImportResult>;
|
||||
queryKeysToInvalidate: string[][];
|
||||
previewColumns: PreviewColumn[];
|
||||
}
|
||||
|
||||
const ACCEPTED_EXTS = [".xlsx", ".xls", ".csv"];
|
||||
|
||||
export function BulkGenericImportModal({
|
||||
open,
|
||||
onClose,
|
||||
title,
|
||||
description,
|
||||
entityName,
|
||||
templateFilename,
|
||||
onDownloadTemplate,
|
||||
onImport,
|
||||
queryKeysToInvalidate,
|
||||
previewColumns,
|
||||
}: BulkGenericImportModalProps) {
|
||||
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 onDownloadTemplate();
|
||||
toast.success(`Downloaded ${templateFilename}`);
|
||||
} 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 onImport(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 onImport(selectedFile, false, skipInvalid);
|
||||
await Promise.all(
|
||||
queryKeysToInvalidate.map((key) => qc.invalidateQueries({ queryKey: key }))
|
||||
);
|
||||
toast.success(
|
||||
`Imported ${result.created_count} ${entityName.toLowerCase()}${
|
||||
result.created_count === 1 ? "" : "s"
|
||||
}`
|
||||
);
|
||||
resetState();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
const msg =
|
||||
err instanceof ApiError ? err.detail : `Bulk ${entityName.toLowerCase()} 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={title}
|
||||
description={description}
|
||||
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">
|
||||
Download the official pre-formatted template with lookup references before uploading.
|
||||
</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 ${entityName.toLowerCase()} 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>
|
||||
{previewColumns.map((col) => (
|
||||
<th key={col.key} className="px-3 py-2 text-left font-medium text-gray-600">
|
||||
{col.label}
|
||||
</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={previewColumns.length + 2}
|
||||
className="px-3 py-6 text-center text-gray-400"
|
||||
>
|
||||
No data rows found in spreadsheet.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
preview.preview_rows.map((r) => {
|
||||
const rowRecord = r as unknown as Record<string, unknown>;
|
||||
const rowData = (rowRecord.data as Record<string, unknown> | undefined) || rowRecord;
|
||||
return (
|
||||
<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>
|
||||
{previewColumns.map((col) => {
|
||||
const val = rowRecord[col.key] ?? rowData[col.key];
|
||||
return (
|
||||
<td key={col.key} className="px-3 py-2 text-gray-800">
|
||||
{val !== null && val !== undefined && val !== ""
|
||||
? String(val)
|
||||
: "—"}
|
||||
</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} {entityName}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import { useState } from "react";
|
||||
import { KeyRound, AlertCircle, Eye, EyeOff } from "lucide-react";
|
||||
import { changePasswordApi } from "@/api/auth";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { toast } from "@/lib/toast";
|
||||
|
||||
interface ChangePasswordModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function ChangePasswordModal({ open, onClose }: ChangePasswordModalProps) {
|
||||
const [currentPassword, setCurrentPassword] = useState("");
|
||||
const [newPassword, setNewPassword] = useState("");
|
||||
const [confirmPassword, setConfirmPassword] = useState("");
|
||||
const [showCurrent, setShowCurrent] = useState(false);
|
||||
const [showNew, setShowNew] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [errorMsg, setErrorMsg] = useState<string | null>(null);
|
||||
|
||||
function resetState() {
|
||||
setCurrentPassword("");
|
||||
setNewPassword("");
|
||||
setConfirmPassword("");
|
||||
setShowCurrent(false);
|
||||
setShowNew(false);
|
||||
setErrorMsg(null);
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
if (loading) return;
|
||||
resetState();
|
||||
onClose();
|
||||
}
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setErrorMsg(null);
|
||||
|
||||
if (!currentPassword) {
|
||||
setErrorMsg("Please enter your current password.");
|
||||
return;
|
||||
}
|
||||
if (!newPassword || newPassword.length < 6) {
|
||||
setErrorMsg("New password must be at least 6 characters.");
|
||||
return;
|
||||
}
|
||||
if (newPassword !== confirmPassword) {
|
||||
setErrorMsg("New passwords do not match.");
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await changePasswordApi(currentPassword, newPassword);
|
||||
toast.success(res.message || "Password changed successfully.");
|
||||
handleClose();
|
||||
} catch (err) {
|
||||
const msg =
|
||||
err instanceof ApiError ? err.detail : "Failed to change password.";
|
||||
setErrorMsg(msg);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) handleClose();
|
||||
}}
|
||||
title="Change Password"
|
||||
description="Update your account login password. Password must be at least 6 characters long."
|
||||
className="max-w-md"
|
||||
>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{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>
|
||||
)}
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="text-xs font-medium text-gray-700">
|
||||
Current Password <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type={showCurrent ? "text" : "password"}
|
||||
value={currentPassword}
|
||||
onChange={(e) => setCurrentPassword(e.target.value)}
|
||||
required
|
||||
autoComplete="current-password"
|
||||
placeholder="Enter current password"
|
||||
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md pr-10 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowCurrent((s) => !s)}
|
||||
className="absolute right-2.5 top-2.5 text-gray-400 hover:text-gray-600"
|
||||
aria-label={showCurrent ? "Hide current password" : "Show current password"}
|
||||
>
|
||||
{showCurrent ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="text-xs font-medium text-gray-700">
|
||||
New Password <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type={showNew ? "text" : "password"}
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)}
|
||||
required
|
||||
minLength={6}
|
||||
autoComplete="new-password"
|
||||
placeholder="At least 6 characters"
|
||||
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md pr-10 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowNew((s) => !s)}
|
||||
className="absolute right-2.5 top-2.5 text-gray-400 hover:text-gray-600"
|
||||
aria-label={showNew ? "Hide new password" : "Show new password"}
|
||||
>
|
||||
{showNew ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="text-xs font-medium text-gray-700">
|
||||
Confirm New Password <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
required
|
||||
autoComplete="new-password"
|
||||
placeholder="Re-enter new password"
|
||||
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-end gap-2 pt-3 border-t border-gray-100">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading}
|
||||
onClick={handleClose}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" size="sm" loading={loading}>
|
||||
<KeyRound className="h-4 w-4 mr-1.5" />
|
||||
Update Password
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent } from "@testing-library/react";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import { ColumnDef } from "@tanstack/react-table";
|
||||
import XLSX from "xlsx-js-style";
|
||||
import { DataTable } from "./DataTable";
|
||||
@@ -38,7 +38,7 @@ describe("DataTable", () => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("renders rows, filters globally, and exports visible rows to Excel (.xlsx)", () => {
|
||||
it("renders rows, filters globally, and exports visible rows to Excel (.xlsx)", async () => {
|
||||
render(
|
||||
<DataTable
|
||||
data={data}
|
||||
@@ -62,10 +62,12 @@ describe("DataTable", () => {
|
||||
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"
|
||||
);
|
||||
await waitFor(() => {
|
||||
expect(XLSX.writeFile).toHaveBeenCalledTimes(1);
|
||||
expect(XLSX.writeFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ SheetNames: ["Data"] }),
|
||||
"test-assets.xlsx"
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
type Table as TanStackTable,
|
||||
} from "@tanstack/react-table";
|
||||
import { useState } from "react";
|
||||
import XLSX from "xlsx-js-style";
|
||||
import {
|
||||
ChevronUp,
|
||||
ChevronDown,
|
||||
@@ -46,7 +45,7 @@ function formatExcelCell(val: unknown): string | number {
|
||||
return JSON.stringify(val);
|
||||
}
|
||||
|
||||
function exportToExcel<TData>(table: TanStackTable<TData>, filename: string) {
|
||||
async function exportToExcel<TData>(table: TanStackTable<TData>, filename: string) {
|
||||
const rows = table.getPrePaginationRowModel().rows;
|
||||
if (!rows.length) return;
|
||||
|
||||
@@ -55,6 +54,9 @@ function exportToExcel<TData>(table: TanStackTable<TData>, filename: string) {
|
||||
.filter((col) => col.id !== "actions");
|
||||
if (!visibleCols.length) return;
|
||||
|
||||
const XLSXModule = await import("xlsx-js-style");
|
||||
const XLSX = XLSXModule.default ?? XLSXModule;
|
||||
|
||||
const exportRows = rows.map((row) => {
|
||||
const record: Record<string, string | number> = {};
|
||||
for (const col of visibleCols) {
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
X,
|
||||
Package,
|
||||
AlertCircle,
|
||||
KeyRound,
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { formatDate, formatRelative } from "@/lib/format";
|
||||
@@ -28,6 +29,7 @@ import { notificationsApi, type NotificationItem } from "@/api/notifications";
|
||||
import { searchApi } from "@/api/search";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { AssetStatusBadge, CallStatusBadge } from "@/components/StatusBadge";
|
||||
import { ChangePasswordModal } from "@/components/ChangePasswordModal";
|
||||
import { toast } from "@/lib/toast";
|
||||
|
||||
interface TopBarProps {
|
||||
@@ -41,6 +43,7 @@ export function TopBar({ title, onMenuClick }: TopBarProps) {
|
||||
const { user, demoAsOfDate, setDemoAsOfDate, logout } = useAuthStore();
|
||||
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const [changePasswordOpen, setChangePasswordOpen] = useState(false);
|
||||
const [bellOpen, setBellOpen] = useState(false);
|
||||
const [dateInput, setDateInput] = useState(demoAsOfDate ?? "");
|
||||
const [savingDate, setSavingDate] = useState(false);
|
||||
@@ -233,6 +236,7 @@ export function TopBar({ title, onMenuClick }: TopBarProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<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/tablet nav toggle */}
|
||||
{onMenuClick && (
|
||||
@@ -598,6 +602,17 @@ export function TopBar({ title, onMenuClick }: TopBarProps) {
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setMenuOpen(false);
|
||||
setChangePasswordOpen(true);
|
||||
}}
|
||||
className="w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 text-left"
|
||||
>
|
||||
<KeyRound className="h-4 w-4 text-gray-500" />
|
||||
Change Password
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSignOut}
|
||||
@@ -611,6 +626,11 @@ export function TopBar({ title, onMenuClick }: TopBarProps) {
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<ChangePasswordModal
|
||||
open={changePasswordOpen}
|
||||
onClose={() => setChangePasswordOpen(false)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { Plus, CheckCircle2, Paperclip, ShieldCheck, Search, Download } from "lucide-react";
|
||||
import { Plus, CheckCircle2, Paperclip, ShieldCheck, Search, Download, Upload } from "lucide-react";
|
||||
import {
|
||||
calibrationApi,
|
||||
type CalibrationRecordItem,
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
ApproveCalibrationPlanModal,
|
||||
CompleteCalibrationModal,
|
||||
} from "@/components/CalibrationModals";
|
||||
import { BulkGenericImportModal } from "@/components/BulkGenericImportModal";
|
||||
import { toast } from "@/lib/toast";
|
||||
|
||||
type CalTab = "records" | "plans";
|
||||
@@ -50,6 +51,7 @@ export function CalibrationPage() {
|
||||
const [dueTo, setDueTo] = useState("");
|
||||
|
||||
const [bulkAddOpen, setBulkAddOpen] = useState(false);
|
||||
const [importModalOpen, setImportModalOpen] = useState(false);
|
||||
const [approvingPlan, setApprovingPlan] = useState<CalibrationPlanItem | null>(null);
|
||||
const [completingRec, setCompletingRec] = useState<CalibrationRecordItem | null>(null);
|
||||
const [certModalRec, setCertModalRec] = useState<CalibrationRecordItem | null>(null);
|
||||
@@ -314,6 +316,13 @@ export function CalibrationPage() {
|
||||
<Download className="h-4 w-4 mr-1.5" />
|
||||
Template (.xlsx)
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setImportModalOpen(true)}
|
||||
>
|
||||
<Upload className="h-4 w-4 mr-1.5" />
|
||||
Import (.xlsx)
|
||||
</Button>
|
||||
<Button onClick={() => setBulkAddOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-1.5" />
|
||||
Add Equipment to Calibration
|
||||
@@ -498,6 +507,24 @@ export function CalibrationPage() {
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
<BulkGenericImportModal
|
||||
open={importModalOpen}
|
||||
onClose={() => setImportModalOpen(false)}
|
||||
title="Bulk Import Calibration Plans"
|
||||
description="Upload an Excel (.xlsx/.xls) or CSV spreadsheet to register multiple equipment calibration frequencies and agency assignments at once."
|
||||
entityName="Calibration Plans"
|
||||
templateFilename="calibration_import_template.xlsx"
|
||||
onDownloadTemplate={() => calibrationApi.downloadImportTemplate()}
|
||||
onImport={(file, dryRun, skipInvalid) => calibrationApi.bulkImport(file, dryRun, skipInvalid)}
|
||||
queryKeysToInvalidate={[["calibration-plans"], ["calibration-records"], ["dashboard"]]}
|
||||
previewColumns={[
|
||||
{ key: "asset_code", label: "Asset Code" },
|
||||
{ key: "frequency_months", label: "Frequency (Mo)" },
|
||||
{ key: "agency_name", label: "Agency" },
|
||||
{ key: "next_due_date", label: "Next Due Date" },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
Search,
|
||||
AlertCircle,
|
||||
Download,
|
||||
Upload,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
contractsApi,
|
||||
@@ -33,6 +34,7 @@ import { ExpiryChip } from "@/components/StatusBadge";
|
||||
import { AssetPicker } from "@/components/AssetPicker";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import { ConfirmDialog } from "@/components/ConfirmDialog";
|
||||
import { BulkGenericImportModal } from "@/components/BulkGenericImportModal";
|
||||
import { toast } from "@/lib/toast";
|
||||
|
||||
type TabKey = "contracts" | "warranties";
|
||||
@@ -83,6 +85,9 @@ export function ContractsPage() {
|
||||
const [departmentId, setDepartmentId] = useState("");
|
||||
const [providerId, setProviderId] = useState("");
|
||||
const [contractTypeFilter, setContractTypeFilter] = useState("");
|
||||
const [expiryFrom, setExpiryFrom] = useState("");
|
||||
const [expiryTo, setExpiryTo] = useState("");
|
||||
const [importModalOpen, setImportModalOpen] = useState(false);
|
||||
|
||||
// Contract modals
|
||||
const [contractFormOpen, setContractFormOpen] = useState(false);
|
||||
@@ -131,6 +136,8 @@ export function ContractsPage() {
|
||||
contractTypeFilter,
|
||||
statusFilter,
|
||||
includeSuperseded,
|
||||
expiryFrom,
|
||||
expiryTo,
|
||||
],
|
||||
queryFn: () =>
|
||||
contractsApi.list({
|
||||
@@ -140,18 +147,22 @@ export function ContractsPage() {
|
||||
contract_type: contractTypeFilter || undefined,
|
||||
status: statusFilter || undefined,
|
||||
include_superseded: includeSuperseded,
|
||||
expiry_from: expiryFrom || undefined,
|
||||
expiry_to: expiryTo || undefined,
|
||||
page_size: 200,
|
||||
}),
|
||||
enabled: tab === "contracts",
|
||||
});
|
||||
|
||||
const warrantiesQuery = useQuery({
|
||||
queryKey: ["warranties", q, departmentId, statusFilter],
|
||||
queryKey: ["warranties", q, departmentId, statusFilter, expiryFrom, expiryTo],
|
||||
queryFn: () =>
|
||||
warrantiesApi.list({
|
||||
q: q.trim() || undefined,
|
||||
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
||||
status: statusFilter || undefined,
|
||||
expiry_from: expiryFrom || undefined,
|
||||
expiry_to: expiryTo || undefined,
|
||||
page_size: 200,
|
||||
}),
|
||||
enabled: tab === "warranties",
|
||||
@@ -472,20 +483,29 @@ export function ContractsPage() {
|
||||
{canManage && (
|
||||
<div className="flex items-center gap-2">
|
||||
{tab === "contracts" && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await contractsApi.downloadImportTemplate();
|
||||
toast.success("Downloaded Contract import template (.xlsx)");
|
||||
} catch {
|
||||
toast.error("Failed to download template");
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Download className="h-4 w-4 mr-1.5" />
|
||||
Template (.xlsx)
|
||||
</Button>
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await contractsApi.downloadImportTemplate();
|
||||
toast.success("Downloaded Contract import template (.xlsx)");
|
||||
} catch {
|
||||
toast.error("Failed to download template");
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Download className="h-4 w-4 mr-1.5" />
|
||||
Template (.xlsx)
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setImportModalOpen(true)}
|
||||
>
|
||||
<Upload className="h-4 w-4 mr-1.5" />
|
||||
Import (.xlsx)
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Button
|
||||
onClick={() => {
|
||||
@@ -625,6 +645,39 @@ export function ContractsPage() {
|
||||
</select>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="text-[11px] text-gray-500 whitespace-nowrap">Expiry:</span>
|
||||
<input
|
||||
type="date"
|
||||
value={expiryFrom}
|
||||
onChange={(e) => setExpiryFrom(e.target.value)}
|
||||
title="Expiry From"
|
||||
placeholder="From"
|
||||
className="w-full px-2 py-1 text-xs border border-gray-200 rounded-md bg-white"
|
||||
/>
|
||||
<span className="text-[11px] text-gray-400">to</span>
|
||||
<input
|
||||
type="date"
|
||||
value={expiryTo}
|
||||
onChange={(e) => setExpiryTo(e.target.value)}
|
||||
title="Expiry To"
|
||||
placeholder="To"
|
||||
className="w-full px-2 py-1 text-xs border border-gray-200 rounded-md bg-white"
|
||||
/>
|
||||
{(expiryFrom || expiryTo) && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setExpiryFrom("");
|
||||
setExpiryTo("");
|
||||
}}
|
||||
className="text-[11px] text-[#1e3a8a] hover:underline whitespace-nowrap"
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -718,6 +771,25 @@ export function ContractsPage() {
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
<BulkGenericImportModal
|
||||
open={importModalOpen}
|
||||
onClose={() => setImportModalOpen(false)}
|
||||
title="Bulk Import Contracts"
|
||||
description="Upload an Excel (.xlsx/.xls) or CSV spreadsheet to register or update multiple AMC/CMC equipment contracts at once."
|
||||
entityName="Contracts"
|
||||
templateFilename="contracts_import_template.xlsx"
|
||||
onDownloadTemplate={() => contractsApi.downloadImportTemplate()}
|
||||
onImport={(file, dryRun, skipInvalid) => contractsApi.bulkImport(file, dryRun, skipInvalid)}
|
||||
queryKeysToInvalidate={[["contracts"], ["dashboard"]]}
|
||||
previewColumns={[
|
||||
{ key: "asset_code", label: "Asset Code" },
|
||||
{ key: "provider_name", label: "Provider" },
|
||||
{ key: "contract_type", label: "Type" },
|
||||
{ key: "start_date", label: "Start Date" },
|
||||
{ key: "end_date", label: "End Date" },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
Search,
|
||||
AlertCircle,
|
||||
Download,
|
||||
Upload,
|
||||
} from "lucide-react";
|
||||
import { insuranceApi, type InsuranceItem } from "@/api/phase5";
|
||||
import { assetsApi, type AssetLookupItem } from "@/api/assets";
|
||||
@@ -27,6 +28,7 @@ import { AssetPicker } from "@/components/AssetPicker";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import { InsuranceDrawer } from "@/components/InsuranceDrawer";
|
||||
import { ConfirmDialog } from "@/components/ConfirmDialog";
|
||||
import { BulkGenericImportModal } from "@/components/BulkGenericImportModal";
|
||||
import { toast } from "@/lib/toast";
|
||||
|
||||
const inputCls =
|
||||
@@ -50,6 +52,9 @@ export function InsurancePage() {
|
||||
const [q, setQ] = useState("");
|
||||
const [departmentId, setDepartmentId] = useState("");
|
||||
const [insurerId, setInsurerId] = useState("");
|
||||
const [expiryFrom, setExpiryFrom] = useState("");
|
||||
const [expiryTo, setExpiryTo] = useState("");
|
||||
const [importModalOpen, setImportModalOpen] = useState(false);
|
||||
|
||||
const [formOpen, setFormOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<InsuranceItem | null>(null);
|
||||
@@ -72,13 +77,23 @@ export function InsurancePage() {
|
||||
});
|
||||
|
||||
const policiesQuery = useQuery({
|
||||
queryKey: ["insurance", q, departmentId, insurerId, statusFilter],
|
||||
queryKey: [
|
||||
"insurance",
|
||||
q,
|
||||
departmentId,
|
||||
insurerId,
|
||||
statusFilter,
|
||||
expiryFrom,
|
||||
expiryTo,
|
||||
],
|
||||
queryFn: () =>
|
||||
insuranceApi.list({
|
||||
q: q.trim() || undefined,
|
||||
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
||||
insurer_id: insurerId ? Number(insurerId) : undefined,
|
||||
status: statusFilter || undefined,
|
||||
expiry_from: expiryFrom || undefined,
|
||||
expiry_to: expiryTo || undefined,
|
||||
page_size: 200,
|
||||
}),
|
||||
});
|
||||
@@ -254,6 +269,13 @@ export function InsurancePage() {
|
||||
<Download className="h-4 w-4 mr-1.5" />
|
||||
Template (.xlsx)
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setImportModalOpen(true)}
|
||||
>
|
||||
<Upload className="h-4 w-4 mr-1.5" />
|
||||
Import (.xlsx)
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
setEditing(null);
|
||||
@@ -327,6 +349,39 @@ export function InsurancePage() {
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
<div className="flex items-center gap-1.5 sm:col-span-2 lg:col-span-3">
|
||||
<span className="text-[11px] text-gray-500 whitespace-nowrap">Expiry:</span>
|
||||
<input
|
||||
type="date"
|
||||
value={expiryFrom}
|
||||
onChange={(e) => setExpiryFrom(e.target.value)}
|
||||
title="Expiry From"
|
||||
placeholder="From"
|
||||
className="px-2 py-1 text-xs border border-gray-200 rounded-md bg-white"
|
||||
/>
|
||||
<span className="text-[11px] text-gray-400">to</span>
|
||||
<input
|
||||
type="date"
|
||||
value={expiryTo}
|
||||
onChange={(e) => setExpiryTo(e.target.value)}
|
||||
title="Expiry To"
|
||||
placeholder="To"
|
||||
className="px-2 py-1 text-xs border border-gray-200 rounded-md bg-white"
|
||||
/>
|
||||
{(expiryFrom || expiryTo) && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setExpiryFrom("");
|
||||
setExpiryTo("");
|
||||
}}
|
||||
className="text-[11px] text-[#1e3a8a] hover:underline whitespace-nowrap"
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -381,6 +436,25 @@ export function InsurancePage() {
|
||||
if (deleteTarget) deleteMutation.mutate(deleteTarget.id);
|
||||
}}
|
||||
/>
|
||||
|
||||
<BulkGenericImportModal
|
||||
open={importModalOpen}
|
||||
onClose={() => setImportModalOpen(false)}
|
||||
title="Bulk Import Insurance Policies"
|
||||
description="Upload an Excel (.xlsx/.xls) or CSV spreadsheet to register or update multiple equipment insurance policies at once."
|
||||
entityName="Insurance Policies"
|
||||
templateFilename="insurance_import_template.xlsx"
|
||||
onDownloadTemplate={() => insuranceApi.downloadImportTemplate()}
|
||||
onImport={(file, dryRun, skipInvalid) => insuranceApi.bulkImport(file, dryRun, skipInvalid)}
|
||||
queryKeysToInvalidate={[["insurance"], ["dashboard"]]}
|
||||
previewColumns={[
|
||||
{ key: "asset_code", label: "Asset Code" },
|
||||
{ key: "insurer_name", label: "Insurer" },
|
||||
{ key: "policy_number", label: "Policy No" },
|
||||
{ key: "start_date", label: "Start Date" },
|
||||
{ key: "end_date", label: "End Date" },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
{"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/toast.ts","./src/lib/utils.ts","./src/lib/validation.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/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