Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 44 additions & 33 deletions tests/unsubmitted_forms/cleanup_unsubmitted_forms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,49 +29,60 @@ import { update_job_status } from "./generic_scheduler";
export const cleanup_unsubmitted_forms = async (job: JobScheduleQueue) => {
try {
//Find forms that were created 7 days ago and have not been submitted
const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60);
const sevenDaysAgoPlusOneDay = new Date(
sevenDaysAgo.getTime() + 24 * 60 * 60 * 1000
);
const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);

const expiredTokens = await prisma.publicFormsTokens.findMany({
where: {
createdAt: {
gte: sevenDaysAgo, // greater than or equal to 7 days ago
lt: sevenDaysAgoPlusOneDay, // but less than 7 days ago + 1 day
},
createdAt: { lt: sevenDaysAgo },
},
select: {
token: true,
entityId: true,
productId: true,
},
});

for (const token of expiredTokens) {
const relationship = await prisma.relationship.findFirst({
where: {
product_id: token.productId,
status: "new",
},
});

if (relationship) {
await prisma.$transaction([
// Delete relationship
prisma.relationship.delete({
where: { id: relationship.id },
}),
// // Delete the token
prisma.publicFormsTokens.delete({
where: { token: token.token },
}),
// Delete all corpus items associated with the entity
prisma.new_corpus.deleteMany({
try {
await prisma.$transaction(async (tx) => {

const relationships = await tx.relationship.findMany({
where: {
entity_id: token.entityId || "",
product_id: token.productId,
status: "new",
},
}),
// Delete the entity (company)
prisma.entity.delete({
where: { id: token.entityId || "" },
}),
]);
});

if (relationships.length > 0) {

await tx.relationship.deleteMany({
where: { id: { in: relationships.map((r) => r.id) } },
});
}

Comment on lines +50 to +63
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

⚠️ Potential issue

Over-broad relationship deletion (by product only) risks data loss

Filtering only by product_id and status: "new" can delete unrelated “new” relationships for other tokens/entities in the same product. Restrict by the specific entity (or token) you are cleaning.

-          const relationships = await tx.relationship.findMany({
-            where: {
-              product_id: token.productId,
-              status: "new",
-            },
-          });
-
-          if (relationships.length > 0) {
-            await tx.relationship.deleteMany({
-              where: { id: { in: relationships.map((r) => r.id) } },
-            });
-          }
+          if (token.entityId) {
+            await tx.relationship.deleteMany({
+              where: {
+                product_id: token.productId,
+                status: "new",
+                entity_id: token.entityId,
+              },
+            });
+          }

Optional: log the delete count from deleteMany for observability.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const relationships = await tx.relationship.findMany({
where: {
entity_id: token.entityId || "",
product_id: token.productId,
status: "new",
},
}),
// Delete the entity (company)
prisma.entity.delete({
where: { id: token.entityId || "" },
}),
]);
});
if (relationships.length > 0) {
await tx.relationship.deleteMany({
where: { id: { in: relationships.map((r) => r.id) } },
});
}
if (token.entityId) {
await tx.relationship.deleteMany({
where: {
product_id: token.productId,
status: "new",
entity_id: token.entityId,
},
});
}
🤖 Prompt for AI Agents
In tests/unsubmitted_forms/cleanup_unsubmitted_forms.ts around lines 50 to 63,
the current query finds and deletes relationships filtered only by product_id
and status "new", which may remove "new" relationships belonging to other
tokens/entities in the same product; restrict both the findMany and the
deleteMany to the specific token/entity you are cleaning (e.g., add token_id or
entity_id = token.id or token.entityId to the where clauses) so you only delete
relationships for that token, and optionally capture and log the deleteMany
result.count to observe how many records were removed.


await tx.publicFormsTokens.delete({
where: { token: token.token },
});

if (token.entityId) {

await tx.new_corpus.deleteMany({
where: { entity_id: token.entityId },
});

await tx.entity.delete({
where: { id: token.entityId },
});
}
Comment on lines +69 to +78
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add safety checks before deleting the entity

Delete the entity only if it’s no longer referenced by other tokens or non-“new” relationships. Current code can remove an entity still in use.

-          if (token.entityId) {
-            
-            await tx.new_corpus.deleteMany({
-              where: { entity_id: token.entityId },
-            });
-
-            await tx.entity.delete({
-              where: { id: token.entityId },
-            });
-          }
+          if (token.entityId) {
+            const [otherTokens, nonNewRels] = await Promise.all([
+              tx.publicFormsTokens.count({
+                where: { entityId: token.entityId, token: { not: token.token } },
+              }),
+              tx.relationship.count({
+                where: { entity_id: token.entityId, status: { not: "new" } },
+              }),
+            ]);
+            if (otherTokens === 0 && nonNewRels === 0) {
+              await tx.new_corpus.deleteMany({ where: { entity_id: token.entityId } });
+              await tx.entity.delete({ where: { id: token.entityId } });
+            } else {
+              // Entity still referenced; skip entity removal.
+            }
+          }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (token.entityId) {
await tx.new_corpus.deleteMany({
where: { entity_id: token.entityId },
});
await tx.entity.delete({
where: { id: token.entityId },
});
}
if (token.entityId) {
const [otherTokens, nonNewRels] = await Promise.all([
tx.publicFormsTokens.count({
where: { entityId: token.entityId, token: { not: token.token } },
}),
tx.relationship.count({
where: { entity_id: token.entityId, status: { not: "new" } },
}),
]);
if (otherTokens === 0 && nonNewRels === 0) {
await tx.new_corpus.deleteMany({
where: { entity_id: token.entityId },
});
await tx.entity.delete({
where: { id: token.entityId },
});
} else {
// Entity still referenced; skip entity removal.
}
}
🤖 Prompt for AI Agents
In tests/unsubmitted_forms/cleanup_unsubmitted_forms.ts around lines 69 to 78,
the code unconditionally deletes an entity when token.entityId is present which
can remove an entity still referenced elsewhere; before calling
tx.entity.delete, query and verify there are zero other tokens referencing that
entity (exclude the current token id) and zero relationships referencing that
entity that are not of type "new" (or that do not match the safe-to-delete
criteria), and only perform tx.entity.delete when both counts are zero; if
either count is non-zero, skip deletion (or log/mark it) to avoid removing
in-use entities.

});
} catch (innerError) {
console.error(
`Failed cleanup for token ${token.token} (entity ${token.entityId}):`,
innerError
);

}
}

Expand Down