fix(wizard): use raw SQL DELETE for draft cleanup to trigger DB-level CASCADE
Some checks are pending
NordaBiz Tests / Unit & Integration Tests (push) Waiting to run
NordaBiz Tests / E2E Tests (Playwright) (push) Blocked by required conditions
NordaBiz Tests / Smoke Tests (Production) (push) Blocked by required conditions
NordaBiz Tests / Send Failure Notification (push) Blocked by required conditions

ORM db.delete() doesn't honor ondelete='CASCADE' on FK constraints,
causing NotNullViolation on company_financial_reports and other tables.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Maciej Pienczyn 2026-04-03 12:22:48 +02:00
parent 73daa28bb0
commit 3a4213a077

View File

@ -28,6 +28,13 @@ from utils.decorators import role_required
logger = logging.getLogger(__name__)
def _delete_draft_company(db, company_id):
"""Delete a wizard_draft company using raw SQL to trigger DB-level CASCADE."""
from sqlalchemy import text
db.execute(text("DELETE FROM companies WHERE id = :cid AND status = 'wizard_draft'"),
{'cid': company_id})
def _validate_nip(nip: str) -> bool:
"""Validate Polish NIP number (10 digits, checksum)."""
if not nip or not re.match(r'^\d{10}$', nip):
@ -133,13 +140,7 @@ def wizard_step1():
Company.status == 'wizard_draft'
).first()
if old_draft:
# Clean up related records first
db.query(CompanyPKD).filter_by(company_id=old_draft.id).delete()
db.query(CompanyPerson).filter_by(company_id=old_draft.id).delete()
db.query(CompanyWebsiteAnalysis).filter_by(company_id=old_draft.id).delete()
db.query(CompanySocialMedia).filter_by(company_id=old_draft.id).delete()
db.query(GBPAudit).filter_by(company_id=old_draft.id).delete()
db.delete(old_draft)
_delete_draft_company(db, old_draft.id)
db.commit()
# Try KRS first (via Biala Lista → KRS Open API)
@ -856,14 +857,7 @@ def wizard_cancel():
from logo_fetch_service import LogoFetchService
LogoFetchService.cleanup_candidates(company.slug)
# Delete related records
db.query(CompanyPKD).filter_by(company_id=company.id).delete()
db.query(CompanyPerson).filter_by(company_id=company.id).delete()
db.query(CompanyWebsiteAnalysis).filter_by(company_id=company.id).delete()
db.query(CompanySocialMedia).filter_by(company_id=company.id).delete()
db.query(GBPAudit).filter_by(company_id=company.id).delete()
db.delete(company)
_delete_draft_company(db, company.id)
db.commit()
return jsonify({'success': True})