Files
pn-new-crm/src/app/api/v1/interests/[id]/berths/handlers.ts
Matt Ciaccio a3e002852b fix(audit-2): integration regressions + data-integrity from second-pass review
Two reviewer agents did a second-pass deep audit of the 21-commit
refactor. Eight findings; four fixed here (one was deferred with a
schema comment, three were 🟡 nice-to-haves left for follow-up).

Integration regressions (🟠 high):
- Outbound webhook `interest.berth_linked` now fires from the new
  junction-add handler. Was emitting a socket-only event, leaving
  external integrations silent post-refactor.
- Two new webhook events `interest.berth_unlinked` and
  `interest.berth_link_updated` added to WEBHOOK_EVENTS +
  INTERNAL_TO_WEBHOOK_MAP. PATCH and DELETE handlers now dispatch them
  alongside the existing socket emits — lifecycle parity restored.
- BerthInterestPulse adds useRealtimeInvalidation for berth-link
  events. The query key was berth-scoped while the linked-berths
  dialog invalidates interest-scoped keys (no prefix match), so the
  pulse went stale. Bridges via the realtime hook now.

Recommender semantic fix (🟠 medium-high):
- aggregates CTE: active_interest_count now filters on
  `ib.is_specific_interest = true`, matching the public-map "Under
  Offer" derivation. EOI-bundle-only links no longer demote a berth
  to Tier C for other reps. Smoke test confirms previously-all-Tier-C
  results now correctly classify as Tier A.
- Same CTE: `total_interest_count` uses COUNT(ib.berth_id) instead of
  COUNT(*) so a berth with no junction rows reports 0 (not 1 from
  the LEFT JOIN's NULL-right-side row). Prevents heat over-counting.

Data integrity (🟠):
- AcroForm tier rejects negative numerics in coerceFieldValue (was
  letting through `length_ft="-50"` which would poison the
  recommender feasibility filter on apply).
- FilesystemBackend.resolveHmacSecret throws in production when
  storage_proxy_hmac_secret_encrypted is null. Dev still derives from
  BETTER_AUTH_SECRET for ergonomics; prod must explicitly configure.
- Documented the circular FK between berths.current_pdf_version_id
  and berth_pdf_versions.id. Drizzle's `.references()` can't express
  the cycle so the schema column is plain text + a comment; the FK
  is authoritatively maintained by migration 0030.

Tests still 1163/1163. tsc clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 04:20:38 +02:00

110 lines
4.2 KiB
TypeScript

import { NextResponse } from 'next/server';
import { and, eq } from 'drizzle-orm';
import { z } from 'zod';
import { type RouteHandler } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse, NotFoundError, ValidationError } from '@/lib/errors';
import { db } from '@/lib/db';
import { interests } from '@/lib/db/schema/interests';
import { berths } from '@/lib/db/schema/berths';
import { listBerthsForInterest, upsertInterestBerth } from '@/lib/services/interest-berths.service';
import { createAuditLog } from '@/lib/audit';
import { emitToRoom } from '@/lib/socket/server';
// ─── Schemas ────────────────────────────────────────────────────────────────
const addBerthSchema = z.object({
berthId: z.string().min(1),
/** Drives the public-map "Under Offer" sub-status. See plan §5.4. */
isSpecificInterest: z.boolean(),
});
// ─── GET /api/v1/interests/[id]/berths ──────────────────────────────────────
//
// Returns the linked-berths list (plan §5.5) along with the parent interest's
// `eoiStatus` so the UI can decide whether to show the EOI-bypass control.
// Tenant-scoped: 404 when the interest doesn't belong to the caller's port,
// matching the recommender route's enumeration-prevention behaviour.
export const listHandler: RouteHandler = async (_req, ctx, params) => {
try {
const interestId = params.id!;
const interest = await db.query.interests.findFirst({
where: eq(interests.id, interestId),
});
if (!interest || interest.portId !== ctx.portId) {
throw new NotFoundError('Interest');
}
const links = await listBerthsForInterest(interestId);
return NextResponse.json({
data: links,
meta: { eoiStatus: interest.eoiStatus },
});
} catch (error) {
return errorResponse(error);
}
};
// ─── POST /api/v1/interests/[id]/berths ─────────────────────────────────────
//
// Add a (non-primary) berth link to the interest. Defaults to
// `isInEoiBundle=false`, `isPrimary=false`; the rep can flip these later via
// the linked-berths list (PATCH route below).
export const addHandler: RouteHandler = async (req, ctx, params) => {
try {
const body = await parseBody(req, addBerthSchema);
const interestId = params.id!;
const interest = await db.query.interests.findFirst({
where: eq(interests.id, interestId),
});
if (!interest || interest.portId !== ctx.portId) {
throw new NotFoundError('Interest');
}
// Tenant scope: berth must belong to this port (never trust a client-
// supplied id to cross port boundaries — plan §14.10).
const berth = await db.query.berths.findFirst({
where: and(eq(berths.id, body.berthId), eq(berths.portId, ctx.portId)),
});
if (!berth) {
throw new ValidationError('berthId not found in this port');
}
const link = await upsertInterestBerth(interestId, body.berthId, {
isSpecificInterest: body.isSpecificInterest,
addedBy: ctx.userId,
});
void createAuditLog({
userId: ctx.userId,
portId: ctx.portId,
action: 'update',
entityType: 'interest',
entityId: interestId,
newValue: { berthId: body.berthId, isSpecificInterest: body.isSpecificInterest },
metadata: { type: 'berth_added_to_interest' },
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
emitToRoom(`port:${ctx.portId}`, 'interest:berthLinked', {
interestId,
berthId: body.berthId,
});
// Outbound webhook: the legacy /link-berth path dispatched
// `interest.berth_linked` and external integrations subscribe to it.
// The new junction-add path must keep that contract.
void import('@/lib/services/webhook-dispatch').then(({ dispatchWebhookEvent }) =>
dispatchWebhookEvent(ctx.portId, 'interest:berthLinked', {
interestId,
berthId: body.berthId,
}),
);
return NextResponse.json({ data: link }, { status: 201 });
} catch (error) {
return errorResponse(error);
}
};