feat(interests): linked berths list with role-flag toggles + EOI bypass
Implements plan §5.5: a per-interest "Linked berths" panel mounted above the
recommender on the interest detail Overview tab. Each junction row exposes
the role-flag controls reps need to manage the M:M `interest_berths` link
without the legacy single-berth flow.
UI (`src/components/interests/linked-berths-list.tsx`)
* Rows ordered with primary first; mooring number links to /berths/[id], with
area + a status pill (available/under_offer/sold) and a "Primary" chip.
* "Specifically pitching" Switch (writes `is_specific_interest`) with the
consequence text from §1: "This berth will appear as under interest on the
public map" / "This berth is hidden from the public map".
* "Mark in EOI bundle" Switch (writes `is_in_eoi_bundle`).
* "Set as primary" button when the row isn't primary - the existing
`upsertInterestBerth` helper demotes the prior primary in the same tx.
* "Bypass EOI for this berth" with reason textarea, ONLY rendered when the
parent interest's `eoiStatus === 'signed'`. Writes the bypass triple
(`eoi_bypass_reason`, `eoi_bypassed_by` = caller, `eoi_bypassed_at` = now);
also supports clearing.
* Remove-from-interest action gated by a confirmation dialog.
API (`src/app/api/v1/interests/[id]/berths/...`)
* `GET /` - list endpoint returning `listBerthsForInterest` plus the parent
interest's `eoiStatus` in `meta.eoiStatus` so the UI can decide whether to
show the bypass control.
* `PATCH /[berthId]` - partial update of the junction row's flags + bypass
fields. Server-side guard: rejects bypass writes when `eoiStatus !==
'signed'` (defence in depth - never trust the UI to gate this).
* `DELETE /[berthId]` - calls `removeInterestBerth`.
* The existing POST stays unchanged. All routes wrapped with
`withAuth(withPermission('interests', view|edit, ...))`. portId from ctx;
cross-port reads/writes return 404 for enumeration prevention (§14.10).
Service changes (`src/lib/services/interest-berths.service.ts`)
* `upsertInterestBerth` now accepts `eoiBypassReason` (tri-state: omit = no
change, non-empty = record, null = clear) and `eoiBypassedBy`. The bypass
triple moves as a unit, with `eoi_bypassed_at` stamped server-side.
* `listBerthsForInterest` now returns berth detail (area, status, dimensions)
alongside the junction row, typed as `InterestBerthWithDetails`.
Socket: added `interest:berthLinkUpdated` event for live UI refreshes.
Tests: 18 new integration tests in `tests/integration/api/interest-berths.test.ts`
covering happy paths, primary-demotion in same tx, bypass write/clear, the
"requires signed EOI" guard, cross-port 404s, missing-link 404s, empty-body
400, and viewer 403 through the permission gate.
This commit is contained in:
144
src/app/api/v1/interests/[id]/berths/[berthId]/handlers.ts
Normal file
144
src/app/api/v1/interests/[id]/berths/[berthId]/handlers.ts
Normal file
@@ -0,0 +1,144 @@
|
||||
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, interestBerths } from '@/lib/db/schema/interests';
|
||||
import { berths } from '@/lib/db/schema/berths';
|
||||
import { removeInterestBerth, upsertInterestBerth } from '@/lib/services/interest-berths.service';
|
||||
import { createAuditLog } from '@/lib/audit';
|
||||
import { emitToRoom } from '@/lib/socket/server';
|
||||
|
||||
// ─── Schemas ────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Partial update of a junction row's role flags + EOI bypass fields. Every
|
||||
* field is optional; passing only the ones the rep wants to change.
|
||||
*
|
||||
* `eoiBypassReason` is a tri-state:
|
||||
* - omitted → no change
|
||||
* - non-empty → record bypass (server stamps `eoiBypassedAt = now()` and
|
||||
* `eoiBypassedBy = caller`)
|
||||
* - null → clear bypass (also clears `eoiBypassedBy` / `eoiBypassedAt`)
|
||||
*/
|
||||
const patchBerthSchema = z
|
||||
.object({
|
||||
isPrimary: z.boolean().optional(),
|
||||
isSpecificInterest: z.boolean().optional(),
|
||||
isInEoiBundle: z.boolean().optional(),
|
||||
eoiBypassReason: z.string().max(2000).nullable().optional(),
|
||||
})
|
||||
.refine((v) => Object.values(v).some((x) => x !== undefined), {
|
||||
message: 'At least one field must be provided.',
|
||||
});
|
||||
|
||||
// ─── Helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
async function loadScopedRow(interestId: string, berthId: string, portId: string) {
|
||||
// Verify interest port-scope first so unrelated 404s look identical to a
|
||||
// truly-missing row (enumeration prevention — plan §14.10).
|
||||
const interest = await db.query.interests.findFirst({
|
||||
where: eq(interests.id, interestId),
|
||||
});
|
||||
if (!interest || interest.portId !== portId) {
|
||||
throw new NotFoundError('Interest');
|
||||
}
|
||||
const link = await db.query.interestBerths.findFirst({
|
||||
where: and(eq(interestBerths.interestId, interestId), eq(interestBerths.berthId, berthId)),
|
||||
});
|
||||
if (!link) {
|
||||
throw new NotFoundError('Berth link');
|
||||
}
|
||||
// Also confirm the berth itself is in-port; defensive against a junction row
|
||||
// pointing at a foreign berth (shouldn't happen, but cheap to check).
|
||||
const berth = await db.query.berths.findFirst({
|
||||
where: and(eq(berths.id, berthId), eq(berths.portId, portId)),
|
||||
});
|
||||
if (!berth) {
|
||||
throw new NotFoundError('Berth');
|
||||
}
|
||||
return { interest, link, berth };
|
||||
}
|
||||
|
||||
// ─── PATCH /api/v1/interests/[id]/berths/[berthId] ──────────────────────────
|
||||
export const patchHandler: RouteHandler = async (req, ctx, params) => {
|
||||
try {
|
||||
const interestId = params.id!;
|
||||
const berthId = params.berthId!;
|
||||
const body = await parseBody(req, patchBerthSchema);
|
||||
|
||||
const { interest } = await loadScopedRow(interestId, berthId, ctx.portId);
|
||||
|
||||
// Plan §5.5: the bypass control is only available once the interest's
|
||||
// primary EOI is signed. Defend the API too — never trust the UI to
|
||||
// gate this.
|
||||
if (body.eoiBypassReason !== undefined && interest.eoiStatus !== 'signed') {
|
||||
throw new ValidationError('EOI bypass requires a signed primary EOI on the interest');
|
||||
}
|
||||
|
||||
const updated = await upsertInterestBerth(interestId, berthId, {
|
||||
isPrimary: body.isPrimary,
|
||||
isSpecificInterest: body.isSpecificInterest,
|
||||
isInEoiBundle: body.isInEoiBundle,
|
||||
eoiBypassReason: body.eoiBypassReason,
|
||||
eoiBypassedBy: body.eoiBypassReason ? ctx.userId : null,
|
||||
});
|
||||
|
||||
void createAuditLog({
|
||||
userId: ctx.userId,
|
||||
portId: ctx.portId,
|
||||
action: 'update',
|
||||
entityType: 'interest',
|
||||
entityId: interestId,
|
||||
newValue: { berthId, ...body },
|
||||
metadata: { type: 'berth_link_updated' },
|
||||
ipAddress: ctx.ipAddress,
|
||||
userAgent: ctx.userAgent,
|
||||
});
|
||||
|
||||
emitToRoom(`port:${ctx.portId}`, 'interest:berthLinkUpdated', {
|
||||
interestId,
|
||||
berthId,
|
||||
});
|
||||
|
||||
return NextResponse.json({ data: updated });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
// ─── DELETE /api/v1/interests/[id]/berths/[berthId] ─────────────────────────
|
||||
export const deleteHandler: RouteHandler = async (_req, ctx, params) => {
|
||||
try {
|
||||
const interestId = params.id!;
|
||||
const berthId = params.berthId!;
|
||||
|
||||
await loadScopedRow(interestId, berthId, ctx.portId);
|
||||
|
||||
await removeInterestBerth(interestId, berthId);
|
||||
|
||||
void createAuditLog({
|
||||
userId: ctx.userId,
|
||||
portId: ctx.portId,
|
||||
action: 'update',
|
||||
entityType: 'interest',
|
||||
entityId: interestId,
|
||||
oldValue: { berthId },
|
||||
metadata: { type: 'berth_removed_from_interest' },
|
||||
ipAddress: ctx.ipAddress,
|
||||
userAgent: ctx.userAgent,
|
||||
});
|
||||
|
||||
emitToRoom(`port:${ctx.portId}`, 'interest:berthUnlinked', {
|
||||
interestId,
|
||||
berthId,
|
||||
});
|
||||
|
||||
return new NextResponse(null, { status: 204 });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
};
|
||||
6
src/app/api/v1/interests/[id]/berths/[berthId]/route.ts
Normal file
6
src/app/api/v1/interests/[id]/berths/[berthId]/route.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { withAuth, withPermission } from '@/lib/api/helpers';
|
||||
|
||||
import { deleteHandler, patchHandler } from './handlers';
|
||||
|
||||
export const PATCH = withAuth(withPermission('interests', 'edit', patchHandler));
|
||||
export const DELETE = withAuth(withPermission('interests', 'edit', deleteHandler));
|
||||
100
src/app/api/v1/interests/[id]/berths/handlers.ts
Normal file
100
src/app/api/v1/interests/[id]/berths/handlers.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
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,
|
||||
});
|
||||
|
||||
return NextResponse.json({ data: link }, { status: 201 });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
};
|
||||
@@ -1,72 +1,6 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { and, eq } from 'drizzle-orm';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { withAuth, withPermission } 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 { upsertInterestBerth } from '@/lib/services/interest-berths.service';
|
||||
import { createAuditLog } from '@/lib/audit';
|
||||
import { emitToRoom } from '@/lib/socket/server';
|
||||
|
||||
const addBerthSchema = z.object({
|
||||
berthId: z.string().min(1),
|
||||
/** Drives the public-map "Under Offer" sub-status. See plan §5.4. */
|
||||
isSpecificInterest: z.boolean(),
|
||||
});
|
||||
import { addHandler, listHandler } from './handlers';
|
||||
|
||||
// POST /api/v1/interests/[id]/berths — link a berth (non-primary) to an interest.
|
||||
export const POST = withAuth(
|
||||
withPermission('interests', 'edit', async (req, ctx, params) => {
|
||||
try {
|
||||
const body = await parseBody(req, addBerthSchema);
|
||||
const interestId = params.id!;
|
||||
|
||||
// Tenant scope: interest must belong to this port.
|
||||
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,
|
||||
});
|
||||
|
||||
return NextResponse.json({ data: link }, { status: 201 });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}),
|
||||
);
|
||||
export const GET = withAuth(withPermission('interests', 'view', listHandler));
|
||||
export const POST = withAuth(withPermission('interests', 'edit', addHandler));
|
||||
|
||||
Reference in New Issue
Block a user