fix(task1): block duplicate imports and duplicate records

This commit is contained in:
Atharv1705
2026-11-17 17:38:37 +05:30
parent b6465708f0
commit 041a4075dd
5 changed files with 330 additions and 6 deletions
+260
View File
@@ -0,0 +1,260 @@
from io import BytesIO
from datetime import date
import openpyxl
import pytest
from app.models import Asset, CalibrationPlan, Contract, Department, InsurancePolicy, Vendor
from app.seed.seed import seed_database
@pytest.fixture(scope="module", autouse=True)
def seeded_task1_db(db, tmp_path_factory):
upload_dir = tmp_path_factory.mktemp("task1_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']}"}
def _make_xlsx_bytes(sheet_name: str, headers: list[str], rows: list[list]) -> 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_api_duplicate_409(client, db):
headers = _auth_headers(client)
asset = db.query(Asset).first()
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
assert asset and vendor
payload = {
"asset_id": asset.id,
"contract_type": "AMC",
"provider_id": vendor.id,
"start_date": "2026-01-01",
"end_date": "2026-12-31",
"coverage_period_text": "2026 Annual AMC",
}
# First creation should succeed
res1 = client.post("/api/contracts", json=payload, headers=headers)
assert res1.status_code == 201
contract_id = res1.json()["id"]
# Second creation with identical asset, type, start_date, end_date must return 409
res2 = client.post("/api/contracts", json=payload, headers=headers)
assert res2.status_code == 409
assert res2.json()["detail"] == "A contract with the same asset, type and dates already exists."
# Renewal must still work
renew_payload = {
"start_date": "2027-01-01",
"end_date": "2027-12-31",
"contract_type": "AMC",
"coverage_period_text": "2027 Annual Renewal",
}
res_renew = client.post(f"/api/contracts/{contract_id}/renew", json=renew_payload, headers=headers)
assert res_renew.status_code == 200
assert res_renew.json()["new_contract"]["start_date"] == "2027-01-01"
def test_insurance_api_duplicate_409(client, db):
headers = _auth_headers(client)
asset = db.query(Asset).first()
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
assert asset and vendor
policy_no = "POL-DUP-TEST-999"
payload = {
"asset_id": asset.id,
"insurer_id": vendor.id,
"policy_no": f" {policy_no} ",
"start_date": "2026-04-01",
"end_date": "2027-03-31",
"coverage_amount": 500000.0,
}
# First creation succeeds
res1 = client.post("/api/insurance", json=payload, headers=headers)
assert res1.status_code == 201
# Exact duplicate (case-insensitive and trimmed) must return 409
dup_payload = {
"asset_id": asset.id,
"insurer_id": vendor.id,
"policy_no": f"pol-dup-test-999 ",
"start_date": "2026-04-01",
"end_date": "2027-03-31",
}
res2 = client.post("/api/insurance", json=dup_payload, headers=headers)
assert res2.status_code == 409
assert res2.json()["detail"] == "Policy number already exists."
def test_contracts_bulk_import_in_file_and_db_duplicates(client, db):
headers = _auth_headers(client)
asset = db.query(Asset).first()
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
assert asset and vendor
xlsx_headers = ["asset_code", "provider_name", "contract_type", "start_date", "end_date", "cost", "coverage_details", "remarks"]
rows = [
[asset.asset_code, vendor.name, "AMC", "2028-01-01", "2028-12-31", 10000, "Coverage", "Remark 1"],
[asset.asset_code, vendor.name, "AMC", "2028-01-01", "2028-12-31", 10000, "Coverage", "Remark 2"],
]
file_bytes = _make_xlsx_bytes("Contracts", xlsx_headers, rows)
# Dry run should flag row 3 as duplicate of row 2
res_dry = client.post(
"/api/contracts/bulk-import?dry_run=true",
files={"file": ("contracts_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
headers=headers,
)
assert res_dry.status_code == 200
dry_data = res_dry.json()
assert dry_data["valid_count"] == 1
assert dry_data["error_count"] == 1
assert any("Duplicate of row 2 in this file." in err["message"] for err in dry_data["errors"])
# Import with skip_invalid=true creates exactly 1 record
res_imp1 = client.post(
"/api/contracts/bulk-import?dry_run=false&skip_invalid=true",
files={"file": ("contracts_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
headers=headers,
)
assert res_imp1.status_code == 200
assert res_imp1.json()["created_count"] == 1
# Second import of the same file creates 0 records and reports DB duplicates
res_imp2 = client.post(
"/api/contracts/bulk-import?dry_run=false&skip_invalid=true",
files={"file": ("contracts_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
headers=headers,
)
assert res_imp2.status_code == 200
data2 = res_imp2.json()
assert data2["created_count"] == 0
assert data2["error_count"] == 2
messages = [e["message"] for e in data2["errors"]]
assert any("Already exists in the system." in m for m in messages)
assert any("Duplicate of row 2 in this file." in m for m in messages)
def test_insurance_bulk_import_in_file_and_db_duplicates(client, db):
headers = _auth_headers(client)
asset = db.query(Asset).first()
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
assert asset and vendor
xlsx_headers = ["asset_code", "insurer_name", "policy_number", "start_date", "end_date", "insured_value", "premium", "remarks"]
rows = [
[asset.asset_code, vendor.name, "POL-BULK-101", "2028-01-01", "2028-12-31", 200000, 5000, "Policy row 2"],
[asset.asset_code, vendor.name, " pol-bulk-101 ", "2028-01-01", "2028-12-31", 200000, 5000, "Policy row 3"],
]
file_bytes = _make_xlsx_bytes("Insurance Policies", xlsx_headers, rows)
# Dry run should flag row 3 as duplicate of row 2
res_dry = client.post(
"/api/insurance/bulk-import?dry_run=true",
files={"file": ("insurance_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
headers=headers,
)
assert res_dry.status_code == 200
dry_data = res_dry.json()
assert dry_data["valid_count"] == 1
assert dry_data["error_count"] == 1
assert any("Duplicate of row 2 in this file." in err["message"] for err in dry_data["errors"])
# Import with skip_invalid=true creates 1 record
res_imp1 = client.post(
"/api/insurance/bulk-import?dry_run=false&skip_invalid=true",
files={"file": ("insurance_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
headers=headers,
)
assert res_imp1.status_code == 200
assert res_imp1.json()["created_count"] == 1
# Second import creates 0 records
res_imp2 = client.post(
"/api/insurance/bulk-import?dry_run=false&skip_invalid=true",
files={"file": ("insurance_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
headers=headers,
)
assert res_imp2.status_code == 200
data2 = res_imp2.json()
assert data2["created_count"] == 0
assert data2["error_count"] == 2
messages = [e["message"] for e in data2["errors"]]
assert any("Already exists in the system." in m for m in messages)
assert any("Duplicate of row 2 in this file." in m for m in messages)
def test_calibration_bulk_import_in_file_and_existing_plan(client, db):
headers = _auth_headers(client)
from app.models import CalibrationPlan
planned_ids = {p.asset_id for p in db.query(CalibrationPlan.asset_id).all()}
asset = db.query(Asset).filter(~Asset.id.in_(planned_ids)).first()
if not asset:
dept = db.query(Department).first()
asset = Asset(
asset_code="PHRC-TEST-CAL-99",
name="Test Cal Asset",
department_id=dept.id,
status="in_service",
requires_calibration=True,
)
db.add(asset)
db.commit()
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
xlsx_headers = ["asset_code", "frequency_months", "agency_name", "next_due_date", "scope", "standards", "remarks"]
rows = [
[asset.asset_code, 12, vendor.name if vendor else "", "2028-06-01", "Accredited scope", "ISO 17025", "Cal row 2"],
[asset.asset_code, 6, vendor.name if vendor else "", "2028-06-01", "Accredited scope", "ISO 17025", "Cal row 3"],
]
file_bytes = _make_xlsx_bytes("Calibration Plans", xlsx_headers, rows)
# Dry run flags row 3 as duplicate of row 2
res_dry = client.post(
"/api/calibration/bulk-import?dry_run=true",
files={"file": ("calibration_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
headers=headers,
)
assert res_dry.status_code == 200
dry_data = res_dry.json()
assert dry_data["valid_count"] == 1
assert dry_data["error_count"] == 1
assert any("Duplicate of row 2 in this file." in err["message"] for err in dry_data["errors"])
# Import with skip_invalid=true creates 1 record
res_imp1 = client.post(
"/api/calibration/bulk-import?dry_run=false&skip_invalid=true",
files={"file": ("calibration_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
headers=headers,
)
assert res_imp1.status_code == 200
assert res_imp1.json()["created_count"] == 1
# Second import creates 0 records and reports "Asset already has a calibration plan."
res_imp2 = client.post(
"/api/calibration/bulk-import?dry_run=false&skip_invalid=true",
files={"file": ("calibration_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
headers=headers,
)
assert res_imp2.status_code == 200
data2 = res_imp2.json()
assert data2["created_count"] == 0
assert data2["error_count"] == 2
messages = [e["message"] for e in data2["errors"]]
assert any("Asset already has a calibration plan." in m for m in messages)
assert any("Duplicate of row 2 in this file." in m for m in messages)