fix(audit): interests/pipeline — M1 (outcome terminal guard), M3 (single-UPDATE + milestone gating), L1 (dead 'completed'), L2 (nurturing edge), L24 (deposit re-lock on refund)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -11,7 +11,7 @@
|
||||
import { and, asc, desc, eq, sql } from 'drizzle-orm';
|
||||
|
||||
import { db } from '@/lib/db';
|
||||
import { interests, payments } from '@/lib/db/schema';
|
||||
import { berths, interests, payments } from '@/lib/db/schema';
|
||||
import { createAuditLog, type AuditMeta } from '@/lib/audit';
|
||||
import { NotFoundError, ValidationError } from '@/lib/errors';
|
||||
import { emitToRoom } from '@/lib/socket/server';
|
||||
@@ -102,6 +102,10 @@ export async function createPayment(portId: string, data: CreatePaymentInput, me
|
||||
depositExpectedAmount: true,
|
||||
depositExpectedCurrency: true,
|
||||
pipelineStage: true,
|
||||
// L24: needed to tell whether the deposit gate had previously fired
|
||||
// (so a later refund can recompute it and re-lock if net drops below
|
||||
// expected).
|
||||
dateDepositReceived: true,
|
||||
},
|
||||
});
|
||||
if (!interest) throw new NotFoundError('Interest');
|
||||
@@ -164,7 +168,9 @@ export async function createPayment(portId: string, data: CreatePaymentInput, me
|
||||
const expectedCurrency = interest.depositExpectedCurrency ?? 'EUR';
|
||||
const { total } = await getDepositTotalForInterest(data.interestId, portId, expectedCurrency);
|
||||
const expected = interest.depositExpectedAmount ? Number(interest.depositExpectedAmount) : null;
|
||||
if (expected !== null && Number.isFinite(expected) && Number(total) >= expected) {
|
||||
const gateMet = expected !== null && Number.isFinite(expected) && Number(total) >= expected;
|
||||
|
||||
if (gateMet) {
|
||||
const { advanceStageIfBehindGated } = await import('@/lib/services/interests.service');
|
||||
void advanceStageIfBehindGated(
|
||||
data.interestId,
|
||||
@@ -185,6 +191,82 @@ export async function createPayment(portId: string, data: CreatePaymentInput, me
|
||||
// Berth rule fires via the same hook the legacy invoices.ts path uses.
|
||||
const { evaluateRule } = await import('@/lib/services/berth-rules-engine');
|
||||
void evaluateRule('deposit_received', data.interestId, portId, meta);
|
||||
} else if (
|
||||
data.paymentType === 'refund' &&
|
||||
expected !== null &&
|
||||
Number.isFinite(expected) &&
|
||||
interest.dateDepositReceived !== null
|
||||
) {
|
||||
// L24 — lower-bound re-lock. A prior deposit tripped the gate (stamping
|
||||
// dateDepositReceived and, via the deposit_received rule, flipping the
|
||||
// primary berth to 'sold'). This refund just dropped the net deposit
|
||||
// (in the expected currency) BACK below the expected amount, so the
|
||||
// "deposit met" state is no longer true. Reverse the deposit-driven
|
||||
// side effects conservatively:
|
||||
//
|
||||
// 1. Un-stamp dateDepositReceived — the timeline/reports must stop
|
||||
// claiming the deposit was met.
|
||||
// 2. Revert the primary berth 'sold' → 'under_offer', but ONLY when
|
||||
// it is currently 'sold' AND that status was set automatically by
|
||||
// the rules engine (statusOverrideMode='automated'). We never undo
|
||||
// a 'sold' an admin set by hand, and we never touch a berth a
|
||||
// different deal/contract subsequently moved on.
|
||||
//
|
||||
// We deliberately do NOT auto-regress the pipeline stage here: stage is
|
||||
// monotonic-forward by design (advanceStageIfBehind never moves a deal
|
||||
// backwards) and a contract may already have been signed off this deal.
|
||||
// Reversing the stage is left to a rep via the manual /stage path. The
|
||||
// un-stamp + berth re-lock are the conservative, non-destructive subset
|
||||
// that stops the underpaid deposit from reading as fully met.
|
||||
await db
|
||||
.update(interests)
|
||||
.set({ dateDepositReceived: null, updatedAt: new Date() })
|
||||
.where(eq(interests.id, data.interestId));
|
||||
|
||||
const { getPrimaryBerth } = await import('@/lib/services/interest-berths.service');
|
||||
const primaryBerth = await getPrimaryBerth(data.interestId);
|
||||
if (primaryBerth?.berthId) {
|
||||
const [reverted] = await db
|
||||
.update(berths)
|
||||
.set({
|
||||
status: 'under_offer',
|
||||
statusLastChangedBy: meta.userId,
|
||||
statusLastChangedReason: `Deposit refunded — net (${total} ${expectedCurrency}) fell below expected; auto-reverted from sold`,
|
||||
statusLastModified: new Date(),
|
||||
statusOverrideMode: 'automated',
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(berths.id, primaryBerth.berthId),
|
||||
eq(berths.portId, portId),
|
||||
eq(berths.status, 'sold'),
|
||||
eq(berths.statusOverrideMode, 'automated'),
|
||||
),
|
||||
)
|
||||
.returning({ id: berths.id });
|
||||
|
||||
if (reverted) {
|
||||
void createAuditLog({
|
||||
userId: meta.userId,
|
||||
portId,
|
||||
action: 'update',
|
||||
entityType: 'berth',
|
||||
entityId: reverted.id,
|
||||
oldValue: { status: 'sold' },
|
||||
newValue: { status: 'under_offer' },
|
||||
metadata: { type: 'deposit_refund_relock', interestId: data.interestId },
|
||||
ipAddress: meta.ipAddress,
|
||||
userAgent: meta.userAgent,
|
||||
});
|
||||
emitToRoom(`port:${portId}`, 'berth:statusChanged', {
|
||||
berthId: reverted.id,
|
||||
newStatus: 'under_offer',
|
||||
triggeredBy: meta.userId,
|
||||
trigger: 'deposit_refund_relock',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user