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
+16
View File
@@ -243,6 +243,22 @@ def create_contract(
if not db.query(Vendor.id).filter(Vendor.id == payload.provider_id).first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Provider vendor not found.")
existing_contract = (
db.query(Contract.id)
.filter(
Contract.asset_id == payload.asset_id,
Contract.contract_type == payload.contract_type,
Contract.start_date == payload.start_date,
Contract.end_date == payload.end_date,
)
.first()
)
if existing_contract:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="A contract with the same asset, type and dates already exists.",
)
contract = Contract(
asset_id=payload.asset_id,
contract_type=payload.contract_type,
+12 -1
View File
@@ -2,7 +2,7 @@ from datetime import date
from typing import Optional
from fastapi import APIRouter, Depends, File, HTTPException, Query, Response, UploadFile, status
from fastapi.responses import StreamingResponse
from sqlalchemy import or_
from sqlalchemy import func, or_
from sqlalchemy.orm import Session, joinedload
from ..core.db import get_db
@@ -200,6 +200,17 @@ def create_insurance_policy(
detail="policy_no cannot be blank.",
)
existing_policy = (
db.query(InsurancePolicy.id)
.filter(func.lower(func.trim(InsurancePolicy.policy_no)) == clean_policy_no.lower())
.first()
)
if existing_policy:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Policy number already exists.",
)
asset.insurance_applicable = True
pol = InsurancePolicy(
asset_id=payload.asset_id,
+38 -5
View File
@@ -430,6 +430,12 @@ def process_contracts_import(
for v in vendors:
vendor_lookup[v.name.strip().lower()] = v
existing_contracts = {
(c.asset_id, (c.contract_type or "").upper(), c.start_date, c.end_date)
for c in db.query(Contract.asset_id, Contract.contract_type, Contract.start_date, Contract.end_date).all()
}
seen_contracts_in_file: dict[tuple[int, str, date, date], int] = {}
errors: list[dict[str, Any]] = []
preview_rows: list[dict[str, Any]] = []
valid_records: list[dict[str, Any]] = []
@@ -483,6 +489,16 @@ def process_contracts_import(
if start_date and end_date and end_date < start_date:
row_errors.append("end_date cannot be earlier than start_date")
if target_asset and contract_type_raw in ("AMC", "CMC", "OTHER") and start_date and end_date and end_date >= start_date:
key = (target_asset.id, contract_type_raw, start_date, end_date)
if key in seen_contracts_in_file:
row_errors.append(f"Duplicate of row {seen_contracts_in_file[key]} in this file.")
elif key in existing_contracts:
row_errors.append("Already exists in the system.")
seen_contracts_in_file[key] = row_idx
else:
seen_contracts_in_file[key] = row_idx
cost, c_err = _parse_optional_float(cost_val, "cost")
if c_err:
row_errors.append(c_err)
@@ -592,7 +608,7 @@ def process_calibration_import(
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()
seen_asset_ids: dict[int, int] = {}
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).all()
vendor_lookup: dict[str, Vendor] = {}
@@ -627,12 +643,13 @@ def process_calibration_import(
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")
row_errors.append(f"Duplicate of row {seen_asset_ids[target_asset.id]} in this file.")
elif target_asset.id in existing_plan_asset_ids:
row_errors.append("Asset already has a calibration plan.")
seen_asset_ids[target_asset.id] = row_idx
else:
seen_asset_ids.add(target_asset.id)
seen_asset_ids[target_asset.id] = row_idx
freq_months, f_err = _parse_positive_int(freq_val, "frequency_months")
if f_err:
@@ -777,6 +794,13 @@ def process_insurance_import(
for v in vendors:
vendor_lookup[v.name.strip().lower()] = v
existing_policies = {
p[0].strip().lower()
for p in db.query(InsurancePolicy.policy_no).all()
if p[0] and p[0].strip()
}
seen_policies_in_file: dict[str, int] = {}
errors: list[dict[str, Any]] = []
preview_rows: list[dict[str, Any]] = []
valid_records: list[dict[str, Any]] = []
@@ -820,6 +844,15 @@ def process_insurance_import(
if not policy_no:
row_errors.append("Missing required field 'policy_number'")
else:
pol_key = policy_no.strip().lower()
if pol_key in seen_policies_in_file:
row_errors.append(f"Duplicate of row {seen_policies_in_file[pol_key]} in this file.")
elif pol_key in existing_policies:
row_errors.append("Already exists in the system.")
seen_policies_in_file[pol_key] = row_idx
else:
seen_policies_in_file[pol_key] = row_idx
start_date, s_err = _parse_date(start_date_val, "start_date")
if s_err:
+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)