fix(worker): atomic approval via transaction, guard null targetGroup
Wrap message.update + approval.create in a $transaction using updateMany with a PENDING status guard to prevent duplicate approvals and audit gaps. Filter out null targetGroup routes to prevent runtime errors on DB inconsistency. Add TODO comment for multi-platform support and fallback accountId comment. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -11,6 +11,7 @@ export async function handleStarReaction(
|
||||
const message = await prisma.message.findUnique({
|
||||
where: {
|
||||
platform_platformMsgId: {
|
||||
// TODO: derive platform from NormalizedReaction when multi-platform support is added
|
||||
platform: 'whatsapp',
|
||||
platformMsgId: reaction.targetMsgId,
|
||||
},
|
||||
@@ -29,27 +30,32 @@ export async function handleStarReaction(
|
||||
if (message.status !== 'PENDING') return null;
|
||||
if (message.approval) return null;
|
||||
|
||||
await prisma.message.update({
|
||||
where: { id: message.id },
|
||||
data: { status: 'APPROVED' },
|
||||
await prisma.$transaction(async (tx: any) => {
|
||||
const updated = await tx.message.updateMany({
|
||||
where: { id: message.id, status: 'PENDING' },
|
||||
data: { status: 'APPROVED' },
|
||||
});
|
||||
if (updated.count === 0) return; // another admin approved first — idempotent
|
||||
await tx.approval.create({
|
||||
data: {
|
||||
messageId: message.id,
|
||||
adminId: reaction.reactorJid,
|
||||
decision: 'APPROVED',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
await prisma.approval.create({
|
||||
data: {
|
||||
const jobs: ForwardJobData[] = message.sourceGroup.syncRoutesFrom
|
||||
.filter((route: any) => route.targetGroup != null)
|
||||
.map((route: any) => ({
|
||||
messageId: message.id,
|
||||
adminId: reaction.reactorJid,
|
||||
decision: 'APPROVED',
|
||||
},
|
||||
});
|
||||
|
||||
const jobs: ForwardJobData[] = message.sourceGroup.syncRoutesFrom.map((route: any) => ({
|
||||
messageId: message.id,
|
||||
content: message.content,
|
||||
sourceGroupName: message.sourceGroup.name,
|
||||
senderName: message.senderName ?? undefined,
|
||||
toGroupJid: route.targetGroup.platformId,
|
||||
fromAccountId: route.targetGroup.accountId ?? reaction.accountId,
|
||||
}));
|
||||
content: message.content,
|
||||
sourceGroupName: message.sourceGroup.name,
|
||||
senderName: message.senderName ?? undefined,
|
||||
toGroupJid: route.targetGroup.platformId,
|
||||
// fallback: use the account that received the reaction when target group has no assigned account
|
||||
fromAccountId: route.targetGroup.accountId ?? reaction.accountId,
|
||||
}));
|
||||
|
||||
return jobs;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user