From b14e209769d695c23e0e1234c9aa5a5ef5330bd4 Mon Sep 17 00:00:00 2001 From: Tofik Hasanov Date: Mon, 30 Mar 2026 11:16:42 -0400 Subject: [PATCH] fix(policies): preserve entityId when re-generating a policy Resolves ENG-90 Co-Authored-By: Claude Opus 4.6 (1M context) --- apps/api/src/trigger/policies/update-policy-helpers.ts | 5 +++++ .../src/trigger/tasks/onboarding/update-policies-helpers.ts | 6 +++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/apps/api/src/trigger/policies/update-policy-helpers.ts b/apps/api/src/trigger/policies/update-policy-helpers.ts index babdac073..e7ae6c903 100644 --- a/apps/api/src/trigger/policies/update-policy-helpers.ts +++ b/apps/api/src/trigger/policies/update-policy-helpers.ts @@ -251,7 +251,12 @@ export async function updatePolicyInDatabase( } await db.$transaction(async (tx) => { + // Clear version references first to avoid FK constraint issues during deletion if (policy.versions.length > 0) { + await tx.policy.update({ + where: { id: policyId }, + data: { currentVersionId: null, pendingVersionId: null }, + }); await tx.policyVersion.deleteMany({ where: { policyId } }); } diff --git a/apps/app/src/trigger/tasks/onboarding/update-policies-helpers.ts b/apps/app/src/trigger/tasks/onboarding/update-policies-helpers.ts index e3641ce69..2e76028f9 100644 --- a/apps/app/src/trigger/tasks/onboarding/update-policies-helpers.ts +++ b/apps/app/src/trigger/tasks/onboarding/update-policies-helpers.ts @@ -561,8 +561,12 @@ export async function updatePolicyInDatabase( // Use transaction to ensure atomicity - if any step fails, all are rolled back await db.$transaction(async (tx) => { - // Delete all existing versions + // Clear version references first to avoid FK constraint issues during deletion if (policy.versions.length > 0) { + await tx.policy.update({ + where: { id: policyId }, + data: { currentVersionId: null, pendingVersionId: null }, + }); await tx.policyVersion.deleteMany({ where: { policyId }, });