fix(task2): import templates must not import sample data
This commit is contained in:
@@ -69,7 +69,7 @@ def build_import_template_xlsx(db: Session) -> BytesIO:
|
||||
cell.border = _HEADER_BORDER
|
||||
ws.row_dimensions[1].height = 26
|
||||
ws.views.sheetView[0].showGridLines = True
|
||||
ws.auto_filter.ref = f"A1:{get_column_letter(len(IMPORT_COLUMNS))}2"
|
||||
ws.auto_filter.ref = f"A1:{get_column_letter(len(IMPORT_COLUMNS))}1"
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
departments = (
|
||||
@@ -125,11 +125,17 @@ def build_import_template_xlsx(db: Session) -> BytesIO:
|
||||
"false",
|
||||
"Sample row - replace or remove before import",
|
||||
]
|
||||
for col_idx, val in enumerate(sample_row, start=1):
|
||||
ws.cell(row=2, column=col_idx, value=val)
|
||||
_auto_fit_columns(ws)
|
||||
|
||||
# Sheet 2: Master Reference
|
||||
# Sheet 2: Example
|
||||
ws_ex = wb.create_sheet(title="Example")
|
||||
ws_ex.views.sheetView[0].showGridLines = True
|
||||
ws_ex.cell(row=1, column=1, value="Example only - this sheet is ignored on import")
|
||||
for col_idx, val in enumerate(sample_row, start=1):
|
||||
ws_ex.cell(row=2, column=col_idx, value=val)
|
||||
_auto_fit_columns(ws_ex)
|
||||
|
||||
# Sheet 3: Master Reference
|
||||
ref = wb.create_sheet(title="Master Reference")
|
||||
ref.row_dimensions[1].height = 26
|
||||
ref.views.sheetView[0].showGridLines = True
|
||||
@@ -272,7 +278,7 @@ def _extract_rows(filename: str, content: bytes) -> list[tuple[int, dict[str, An
|
||||
detail="Invalid Excel file. Please download and use the import template.",
|
||||
code="INVALID_FILE_TYPE",
|
||||
) from exc
|
||||
ws = wb["Assets"] if "Assets" in wb.sheetnames else wb.active
|
||||
ws = wb.worksheets[0]
|
||||
header_cells = next(ws.iter_rows(min_row=1, max_row=1, values_only=True), None)
|
||||
if not header_cells:
|
||||
return []
|
||||
|
||||
@@ -73,7 +73,7 @@ def build_contracts_template_xlsx(db: Session) -> BytesIO:
|
||||
c.border = _HEADER_BORDER
|
||||
ws.row_dimensions[1].height = 26
|
||||
ws.views.sheetView[0].showGridLines = True
|
||||
ws.auto_filter.ref = f"A1:{get_column_letter(len(cols))}2"
|
||||
ws.auto_filter.ref = f"A1:{get_column_letter(len(cols))}1"
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
assets = db.query(Asset).join(Department).filter(Asset.status != "condemned").order_by(Asset.asset_code).all()
|
||||
@@ -91,11 +91,17 @@ def build_contracts_template_xlsx(db: Session) -> BytesIO:
|
||||
"Comprehensive maintenance with all spare parts included",
|
||||
"Annual contract renewal",
|
||||
]
|
||||
for col_idx, val in enumerate(sample_row, start=1):
|
||||
ws.cell(row=2, column=col_idx, value=val)
|
||||
_auto_fit_columns(ws)
|
||||
|
||||
# Reference sheet
|
||||
# Sheet 2: Example
|
||||
ws_ex = wb.create_sheet(title="Example")
|
||||
ws_ex.views.sheetView[0].showGridLines = True
|
||||
ws_ex.cell(row=1, column=1, value="Example only - this sheet is ignored on import")
|
||||
for col_idx, val in enumerate(sample_row, start=1):
|
||||
ws_ex.cell(row=2, column=col_idx, value=val)
|
||||
_auto_fit_columns(ws_ex)
|
||||
|
||||
# Sheet 3: Master Reference
|
||||
ws_ref = wb.create_sheet(title="Master Reference")
|
||||
ws_ref.row_dimensions[1].height = 26
|
||||
ws_ref.views.sheetView[0].showGridLines = True
|
||||
@@ -151,7 +157,7 @@ def build_calibration_template_xlsx(db: Session) -> BytesIO:
|
||||
c.border = _HEADER_BORDER
|
||||
ws.row_dimensions[1].height = 26
|
||||
ws.views.sheetView[0].showGridLines = True
|
||||
ws.auto_filter.ref = f"A1:{get_column_letter(len(cols))}2"
|
||||
ws.auto_filter.ref = f"A1:{get_column_letter(len(cols))}1"
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
assets = (
|
||||
@@ -176,11 +182,17 @@ def build_calibration_template_xlsx(db: Session) -> BytesIO:
|
||||
"ISO/IEC 17025 accredited",
|
||||
"Annual calibration plan",
|
||||
]
|
||||
for col_idx, val in enumerate(sample_row, start=1):
|
||||
ws.cell(row=2, column=col_idx, value=val)
|
||||
_auto_fit_columns(ws)
|
||||
|
||||
# Reference sheet
|
||||
# Sheet 2: Example
|
||||
ws_ex = wb.create_sheet(title="Example")
|
||||
ws_ex.views.sheetView[0].showGridLines = True
|
||||
ws_ex.cell(row=1, column=1, value="Example only - this sheet is ignored on import")
|
||||
for col_idx, val in enumerate(sample_row, start=1):
|
||||
ws_ex.cell(row=2, column=col_idx, value=val)
|
||||
_auto_fit_columns(ws_ex)
|
||||
|
||||
# Sheet 3: Master Reference
|
||||
ws_ref = wb.create_sheet(title="Master Reference")
|
||||
ws_ref.row_dimensions[1].height = 26
|
||||
ws_ref.views.sheetView[0].showGridLines = True
|
||||
@@ -238,7 +250,7 @@ def build_insurance_template_xlsx(db: Session) -> BytesIO:
|
||||
c.border = _HEADER_BORDER
|
||||
ws.row_dimensions[1].height = 26
|
||||
ws.views.sheetView[0].showGridLines = True
|
||||
ws.auto_filter.ref = f"A1:{get_column_letter(len(cols))}2"
|
||||
ws.auto_filter.ref = f"A1:{get_column_letter(len(cols))}1"
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
assets = db.query(Asset).join(Department).filter(Asset.status != "condemned").order_by(Asset.asset_code).all()
|
||||
@@ -254,11 +266,17 @@ def build_insurance_template_xlsx(db: Session) -> BytesIO:
|
||||
18500,
|
||||
"Annual hospital equipment comprehensive policy",
|
||||
]
|
||||
for col_idx, val in enumerate(sample_row, start=1):
|
||||
ws.cell(row=2, column=col_idx, value=val)
|
||||
_auto_fit_columns(ws)
|
||||
|
||||
# Reference sheet
|
||||
# Sheet 2: Example
|
||||
ws_ex = wb.create_sheet(title="Example")
|
||||
ws_ex.views.sheetView[0].showGridLines = True
|
||||
ws_ex.cell(row=1, column=1, value="Example only - this sheet is ignored on import")
|
||||
for col_idx, val in enumerate(sample_row, start=1):
|
||||
ws_ex.cell(row=2, column=col_idx, value=val)
|
||||
_auto_fit_columns(ws_ex)
|
||||
|
||||
# Sheet 3: Master Reference
|
||||
ws_ref = wb.create_sheet(title="Master Reference")
|
||||
ws_ref.row_dimensions[1].height = 26
|
||||
ws_ref.views.sheetView[0].showGridLines = True
|
||||
@@ -376,7 +394,7 @@ def _extract_rows(filename: str, content: bytes, sheet_name: str | None = None)
|
||||
code="INVALID_FILE_TYPE",
|
||||
) from exc
|
||||
|
||||
ws = wb[sheet_name] if sheet_name and sheet_name in wb.sheetnames else wb.active
|
||||
ws = wb.worksheets[0]
|
||||
header_cells = next(ws.iter_rows(min_row=1, max_row=1, values_only=True), None)
|
||||
if not header_cells:
|
||||
return []
|
||||
|
||||
@@ -54,8 +54,8 @@ def test_import_template_download_and_rbac(client):
|
||||
assert 'filename="asset_import_template.xlsx"' in res.headers["content-disposition"]
|
||||
|
||||
wb = openpyxl.load_workbook(BytesIO(res.content))
|
||||
assert "Assets" in wb.sheetnames
|
||||
assert "Master Reference" in wb.sheetnames
|
||||
assert wb.sheetnames == ["Assets", "Example", "Master Reference"]
|
||||
assert wb["Example"].cell(row=1, column=1).value == "Example only - this sheet is ignored on import"
|
||||
ws = wb["Assets"]
|
||||
headers = [ws.cell(row=1, column=i).value for i in range(1, 16)]
|
||||
assert headers[:6] == ["asset_code", "serial_no", "name", "category", "department", "location"]
|
||||
@@ -71,8 +71,8 @@ def test_bulk_import_dry_run_validation_and_commit(client, db):
|
||||
# Read a valid sample from template so we match real seeded department/location/category
|
||||
tmpl_res = client.get("/api/assets/import-template", headers=bio_headers)
|
||||
wb_tmpl = openpyxl.load_workbook(BytesIO(tmpl_res.content))
|
||||
ws_tmpl = wb_tmpl["Assets"]
|
||||
headers = [ws_tmpl.cell(row=1, column=i).value for i in range(1, 16)]
|
||||
ws_tmpl = wb_tmpl["Example"]
|
||||
headers = [wb_tmpl["Assets"].cell(row=1, column=i).value for i in range(1, 16)]
|
||||
cat_name = ws_tmpl.cell(row=2, column=4).value
|
||||
dept_code = ws_tmpl.cell(row=2, column=5).value
|
||||
loc_name = ws_tmpl.cell(row=2, column=6).value
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
from io import BytesIO
|
||||
import openpyxl
|
||||
import pytest
|
||||
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_task2_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("task2_test_uploads")
|
||||
seed_database(db, upload_dir=upload_dir)
|
||||
return upload_dir
|
||||
|
||||
|
||||
def _auth_headers(client, email: str = "admin@poona.demo") -> 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']}"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"template_url,import_url,file_field,filename,expected_sheet1",
|
||||
[
|
||||
(
|
||||
"/api/assets/import-template",
|
||||
"/api/assets/bulk-import?dry_run=true",
|
||||
"file",
|
||||
"asset_template.xlsx",
|
||||
"Assets",
|
||||
),
|
||||
(
|
||||
"/api/contracts/import-template",
|
||||
"/api/contracts/bulk-import?dry_run=true",
|
||||
"file",
|
||||
"contracts_template.xlsx",
|
||||
"Contracts",
|
||||
),
|
||||
(
|
||||
"/api/calibration/import-template",
|
||||
"/api/calibration/bulk-import?dry_run=true",
|
||||
"file",
|
||||
"calibration_template.xlsx",
|
||||
"Calibration Plans",
|
||||
),
|
||||
(
|
||||
"/api/insurance/import-template",
|
||||
"/api/insurance/bulk-import?dry_run=true",
|
||||
"file",
|
||||
"insurance_template.xlsx",
|
||||
"Insurance Policies",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_download_template_and_upload_unchanged_dry_run_zero_rows(
|
||||
client, template_url, import_url, file_field, filename, expected_sheet1
|
||||
):
|
||||
headers = _auth_headers(client)
|
||||
|
||||
# 1. Download template
|
||||
dl_res = client.get(template_url, headers=headers)
|
||||
assert dl_res.status_code == 200
|
||||
content = dl_res.content
|
||||
|
||||
# 2. Verify sheet structure
|
||||
wb = openpyxl.load_workbook(BytesIO(content))
|
||||
assert wb.sheetnames == [expected_sheet1, "Example", "Master Reference"]
|
||||
|
||||
ws1 = wb[expected_sheet1]
|
||||
# First sheet has only header row (max_row == 1)
|
||||
assert ws1.max_row == 1
|
||||
|
||||
ws2 = wb["Example"]
|
||||
# Second sheet has disclaimer on row 1
|
||||
assert ws2.cell(row=1, column=1).value == "Example only - this sheet is ignored on import"
|
||||
# Second sheet has sample row on row 2
|
||||
assert ws2.cell(row=2, column=1).value is not None
|
||||
|
||||
# 3. Upload unchanged template with dry_run=true: must return total_rows == 0
|
||||
up_res = client.post(
|
||||
import_url,
|
||||
headers=headers,
|
||||
files={file_field: (filename, content, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||
)
|
||||
assert up_res.status_code == 200, up_res.text
|
||||
data = up_res.json()
|
||||
assert data["total_rows"] == 0
|
||||
assert data["valid_count"] == 0
|
||||
assert data["error_count"] == 0
|
||||
assert data["created_count"] == 0
|
||||
@@ -40,3 +40,4 @@ Items marked "to be confirmed" or left flexible in the proposal are recorded her
|
||||
- **Contracts**: A duplicate contract is defined by `(asset_id, contract_type, start_date, end_date)` matching any existing contract in the database (including superseded ones). `POST /api/contracts` rejects exact duplicates with HTTP 409 (`A contract with the same asset, type and dates already exists.`). Contract renewals via `POST /api/contracts/{id}/renew` remain unaffected. In bulk import, in-file duplicate rows receive `Duplicate of row N in this file.` and rows duplicating database records receive `Already exists in the system.`.
|
||||
- **Insurance Policies**: A duplicate insurance policy is defined by trimmed, case-insensitive `policy_no` matching any existing policy in the database. `POST /api/insurance` rejects duplicates with HTTP 409 (`Policy number already exists.`). In bulk import, in-file duplicate rows receive `Duplicate of row N in this file.` and rows duplicating database records receive `Already exists in the system.`.
|
||||
- **Calibration Plans**: Each asset can have at most one calibration plan. In bulk import, rows for assets that already have a calibration plan in the database receive `Asset already has a calibration plan.`, while rows repeating an earlier row for the same asset in the same upload file receive `Duplicate of row N in this file.`. Dry run previews surface these validation errors identically.
|
||||
25. **Import Template Multi-Sheet Structure (Task 2)**: All four bulk-import templates (Assets, Contracts, Calibration Plans, Insurance Policies) feature an empty data template on Sheet 1 (containing only styled headers), an 'Example' reference on Sheet 2 (with warning banner 'Example only - this sheet is ignored on import' in Row 1 and sample values in Row 2), and 'Master Reference' lookup tables on Sheet 3. All four importers read strictly the first worksheet (`wb.worksheets[0]`), ensuring sample rows and reference sheets are never accidentally imported.
|
||||
|
||||
Reference in New Issue
Block a user