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 { 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({
|
import { addHandler, listHandler } from './handlers';
|
||||||
berthId: z.string().min(1),
|
|
||||||
/** Drives the public-map "Under Offer" sub-status. See plan §5.4. */
|
|
||||||
isSpecificInterest: z.boolean(),
|
|
||||||
});
|
|
||||||
|
|
||||||
// POST /api/v1/interests/[id]/berths — link a berth (non-primary) to an interest.
|
export const GET = withAuth(withPermission('interests', 'view', listHandler));
|
||||||
export const POST = withAuth(
|
export const POST = withAuth(withPermission('interests', 'edit', addHandler));
|
||||||
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);
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { InlineEditableField } from '@/components/shared/inline-editable-field';
|
|||||||
import { InlineTagEditor } from '@/components/shared/inline-tag-editor';
|
import { InlineTagEditor } from '@/components/shared/inline-tag-editor';
|
||||||
import { RecommendationList } from '@/components/interests/recommendation-list';
|
import { RecommendationList } from '@/components/interests/recommendation-list';
|
||||||
import { BerthRecommenderPanel } from '@/components/interests/berth-recommender-panel';
|
import { BerthRecommenderPanel } from '@/components/interests/berth-recommender-panel';
|
||||||
|
import { LinkedBerthsList } from '@/components/interests/linked-berths-list';
|
||||||
import { InterestTimeline } from '@/components/interests/interest-timeline';
|
import { InterestTimeline } from '@/components/interests/interest-timeline';
|
||||||
import { InterestDocumentsTab } from '@/components/interests/interest-documents-tab';
|
import { InterestDocumentsTab } from '@/components/interests/interest-documents-tab';
|
||||||
import { InterestFilesTab } from '@/components/interests/interest-files-tab';
|
import { InterestFilesTab } from '@/components/interests/interest-files-tab';
|
||||||
@@ -510,6 +511,12 @@ function OverviewTab({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Linked berths (plan §5.5) - shown ABOVE the recommender so reps see
|
||||||
|
what's already linked before browsing more options. Each row exposes
|
||||||
|
per-berth role-flag toggles and the EOI bypass control (only visible
|
||||||
|
once the parent interest's primary EOI is signed). */}
|
||||||
|
<LinkedBerthsList interestId={interestId} />
|
||||||
|
|
||||||
{/* Berth recommender (plan §5.3) - always-mounted card driven by the
|
{/* Berth recommender (plan §5.3) - always-mounted card driven by the
|
||||||
interest's desired dimensions. Renders an inline guidance message
|
interest's desired dimensions. Renders an inline guidance message
|
||||||
when dimensions aren't set yet. */}
|
when dimensions aren't set yet. */}
|
||||||
|
|||||||
478
src/components/interests/linked-berths-list.tsx
Normal file
478
src/components/interests/linked-berths-list.tsx
Normal file
@@ -0,0 +1,478 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Linked-berths list — plan §5.5.
|
||||||
|
*
|
||||||
|
* Shows every berth currently linked to the interest with per-row controls:
|
||||||
|
* - "Specifically pitching" toggle (`is_specific_interest`) — drives the
|
||||||
|
* public-map "Under Offer" sub-status. Each state surfaces its consequence
|
||||||
|
* in plain text below the toggle.
|
||||||
|
* - "Mark in EOI bundle" toggle (`is_in_eoi_bundle`).
|
||||||
|
* - "Set as primary" button when this row isn't already primary. The
|
||||||
|
* service helper handles the demote-prior-primary case in a single tx.
|
||||||
|
* - "Bypass EOI for this berth" with a reason textarea. Only rendered when
|
||||||
|
* the parent interest's `eoiStatus === 'signed'`. Writes
|
||||||
|
* `eoi_bypass_reason`, `eoi_bypassed_by`, `eoi_bypassed_at`.
|
||||||
|
* - "Remove" — calls `removeInterestBerth`.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
import Link from 'next/link';
|
||||||
|
import { useParams } from 'next/navigation';
|
||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { Anchor, Loader2, Star, Trash2 } from 'lucide-react';
|
||||||
|
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { StatusPill, type StatusPillStatus } from '@/components/ui/status-pill';
|
||||||
|
import { Switch } from '@/components/ui/switch';
|
||||||
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
|
import { apiFetch } from '@/lib/api/client';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
|
// ─── Types (mirror the API GET shape — see interest-berths.service.ts) ─────
|
||||||
|
|
||||||
|
export interface LinkedBerthRow {
|
||||||
|
id: string;
|
||||||
|
interestId: string;
|
||||||
|
berthId: string;
|
||||||
|
isPrimary: boolean;
|
||||||
|
isSpecificInterest: boolean;
|
||||||
|
isInEoiBundle: boolean;
|
||||||
|
eoiBypassReason: string | null;
|
||||||
|
eoiBypassedBy: string | null;
|
||||||
|
eoiBypassedAt: string | null;
|
||||||
|
addedBy: string | null;
|
||||||
|
addedAt: string;
|
||||||
|
notes: string | null;
|
||||||
|
mooringNumber: string | null;
|
||||||
|
area: string | null;
|
||||||
|
status: string;
|
||||||
|
lengthFt: string | null;
|
||||||
|
widthFt: string | null;
|
||||||
|
draftFt: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface LinkedBerthsResponse {
|
||||||
|
data: LinkedBerthRow[];
|
||||||
|
meta: { eoiStatus: string | null };
|
||||||
|
}
|
||||||
|
|
||||||
|
interface LinkedBerthsListProps {
|
||||||
|
interestId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Helpers ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function statusToPill(status: string): StatusPillStatus {
|
||||||
|
switch (status) {
|
||||||
|
case 'available':
|
||||||
|
return 'active';
|
||||||
|
case 'under_offer':
|
||||||
|
return 'sent';
|
||||||
|
case 'sold':
|
||||||
|
return 'completed';
|
||||||
|
case 'reserved':
|
||||||
|
return 'partial';
|
||||||
|
default:
|
||||||
|
return 'pending';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatStatus(status: string): string {
|
||||||
|
return status.replace(/_/g, ' ').replace(/\b\w/g, (m) => m.toUpperCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDimensions(
|
||||||
|
length: string | null,
|
||||||
|
width: string | null,
|
||||||
|
draft: string | null,
|
||||||
|
): string | null {
|
||||||
|
const parts: string[] = [];
|
||||||
|
const toNum = (v: string | null) => {
|
||||||
|
if (v === null) return null;
|
||||||
|
const n = parseFloat(v);
|
||||||
|
return Number.isFinite(n) ? n : null;
|
||||||
|
};
|
||||||
|
const l = toNum(length);
|
||||||
|
const w = toNum(width);
|
||||||
|
const d = toNum(draft);
|
||||||
|
if (l !== null) parts.push(`${l.toFixed(1)}ft L`);
|
||||||
|
if (w !== null) parts.push(`${w.toFixed(1)}ft W`);
|
||||||
|
if (d !== null) parts.push(`${d.toFixed(1)}ft D`);
|
||||||
|
return parts.length > 0 ? parts.join(' · ') : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SPECIFIC_CONSEQUENCE_ON = 'This berth will appear as under interest on the public map.';
|
||||||
|
const SPECIFIC_CONSEQUENCE_OFF = 'This berth is hidden from the public map.';
|
||||||
|
|
||||||
|
// ─── Hooks ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function useLinkedBerths(interestId: string) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['interest-berths', interestId] as const,
|
||||||
|
queryFn: () => apiFetch<LinkedBerthsResponse>(`/api/v1/interests/${interestId}/berths`),
|
||||||
|
staleTime: 30_000,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PatchPayload {
|
||||||
|
isPrimary?: boolean;
|
||||||
|
isSpecificInterest?: boolean;
|
||||||
|
isInEoiBundle?: boolean;
|
||||||
|
eoiBypassReason?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function useUpdateLink(interestId: string) {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: async (args: { berthId: string; patch: PatchPayload }) =>
|
||||||
|
apiFetch(`/api/v1/interests/${interestId}/berths/${args.berthId}`, {
|
||||||
|
method: 'PATCH',
|
||||||
|
body: args.patch,
|
||||||
|
}),
|
||||||
|
onSuccess: () => {
|
||||||
|
qc.invalidateQueries({ queryKey: ['interest-berths', interestId] });
|
||||||
|
qc.invalidateQueries({ queryKey: ['interests', interestId] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function useRemoveLink(interestId: string) {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: async (berthId: string) =>
|
||||||
|
apiFetch(`/api/v1/interests/${interestId}/berths/${berthId}`, { method: 'DELETE' }),
|
||||||
|
onSuccess: () => {
|
||||||
|
qc.invalidateQueries({ queryKey: ['interest-berths', interestId] });
|
||||||
|
qc.invalidateQueries({ queryKey: ['interests', interestId] });
|
||||||
|
qc.invalidateQueries({ queryKey: ['berth-recommendations', interestId] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Bypass dialog ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
interface BypassDialogProps {
|
||||||
|
row: LinkedBerthRow;
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
onSubmit: (reason: string | null) => void;
|
||||||
|
isPending: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function BypassDialog({ row, open, onOpenChange, onSubmit, isPending }: BypassDialogProps) {
|
||||||
|
const [reason, setReason] = useState(row.eoiBypassReason ?? '');
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Bypass EOI for berth {row.mooringNumber}</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Record why this berth's individual EOI is being waived. The interest's primary
|
||||||
|
EOI signature will cover it instead.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor={`bypass-reason-${row.berthId}`} className="text-xs">
|
||||||
|
Reason
|
||||||
|
</Label>
|
||||||
|
<Textarea
|
||||||
|
id={`bypass-reason-${row.berthId}`}
|
||||||
|
value={reason}
|
||||||
|
onChange={(e) => setReason(e.target.value)}
|
||||||
|
placeholder="e.g. covered under bundle EOI signed 2025-04-12"
|
||||||
|
rows={4}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<DialogFooter className="gap-2 sm:gap-2">
|
||||||
|
{row.eoiBypassReason ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => onSubmit(null)}
|
||||||
|
disabled={isPending}
|
||||||
|
>
|
||||||
|
Clear bypass
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => onOpenChange(false)}
|
||||||
|
disabled={isPending}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onSubmit(reason.trim().length > 0 ? reason.trim() : null)}
|
||||||
|
disabled={isPending || reason.trim().length === 0}
|
||||||
|
>
|
||||||
|
{isPending ? <Loader2 className="mr-1.5 size-3.5 animate-spin" /> : null}
|
||||||
|
Save bypass
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Row ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
interface RowProps {
|
||||||
|
row: LinkedBerthRow;
|
||||||
|
portSlug: string;
|
||||||
|
eoiStatus: string | null;
|
||||||
|
onUpdate: (berthId: string, patch: PatchPayload) => void;
|
||||||
|
onRemove: (berthId: string) => void;
|
||||||
|
isPending: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function LinkedBerthRowItem({ row, portSlug, eoiStatus, onUpdate, onRemove, isPending }: RowProps) {
|
||||||
|
const [bypassOpen, setBypassOpen] = useState(false);
|
||||||
|
const [confirmRemove, setConfirmRemove] = useState(false);
|
||||||
|
const dims = formatDimensions(row.lengthFt, row.widthFt, row.draftFt);
|
||||||
|
const showBypassControl = eoiStatus === 'signed';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'rounded-lg border bg-card p-3 text-sm',
|
||||||
|
row.isPrimary ? 'border-brand-300 ring-1 ring-brand-200' : 'border-border',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="flex flex-wrap items-start justify-between gap-2">
|
||||||
|
<div className="min-w-0 space-y-1">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<Link
|
||||||
|
href={`/${portSlug}/berths/${row.berthId}`}
|
||||||
|
className="font-semibold text-primary hover:underline"
|
||||||
|
>
|
||||||
|
{row.mooringNumber ?? row.berthId}
|
||||||
|
</Link>
|
||||||
|
{row.area ? <span className="text-xs text-muted-foreground">{row.area}</span> : null}
|
||||||
|
<StatusPill status={statusToPill(row.status)}>{formatStatus(row.status)}</StatusPill>
|
||||||
|
{row.isPrimary ? (
|
||||||
|
<span className="inline-flex items-center gap-1 rounded-md border border-brand-200 bg-brand-50 px-2 py-0.5 text-xs font-medium text-brand-800">
|
||||||
|
<Star className="size-3" />
|
||||||
|
Primary
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
{row.eoiBypassReason ? (
|
||||||
|
<span className="inline-flex items-center rounded-md border border-amber-200 bg-amber-50 px-2 py-0.5 text-xs font-medium text-amber-800">
|
||||||
|
EOI bypassed
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
{dims ? <div className="text-xs text-muted-foreground">{dims}</div> : null}
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
{!row.isPrimary ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => onUpdate(row.berthId, { isPrimary: true })}
|
||||||
|
disabled={isPending}
|
||||||
|
>
|
||||||
|
<Star className="mr-1.5 size-3.5" />
|
||||||
|
Set as primary
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() => setConfirmRemove(true)}
|
||||||
|
disabled={isPending}
|
||||||
|
className="text-destructive hover:text-destructive"
|
||||||
|
aria-label={`Remove berth ${row.mooringNumber ?? row.berthId}`}
|
||||||
|
>
|
||||||
|
<Trash2 className="size-3.5" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-3 grid grid-cols-1 gap-3 border-t pt-3 sm:grid-cols-2">
|
||||||
|
<div className="space-y-1">
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
|
<Label htmlFor={`specific-${row.berthId}`} className="text-sm font-medium">
|
||||||
|
Specifically pitching
|
||||||
|
</Label>
|
||||||
|
<Switch
|
||||||
|
id={`specific-${row.berthId}`}
|
||||||
|
checked={row.isSpecificInterest}
|
||||||
|
disabled={isPending}
|
||||||
|
onCheckedChange={(checked) => onUpdate(row.berthId, { isSpecificInterest: checked })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{row.isSpecificInterest ? SPECIFIC_CONSEQUENCE_ON : SPECIFIC_CONSEQUENCE_OFF}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1">
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
|
<Label htmlFor={`bundle-${row.berthId}`} className="text-sm font-medium">
|
||||||
|
Mark in EOI bundle
|
||||||
|
</Label>
|
||||||
|
<Switch
|
||||||
|
id={`bundle-${row.berthId}`}
|
||||||
|
checked={row.isInEoiBundle}
|
||||||
|
disabled={isPending}
|
||||||
|
onCheckedChange={(checked) => onUpdate(row.berthId, { isInEoiBundle: checked })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{row.isInEoiBundle
|
||||||
|
? 'Covered by the interest’s EOI signature.'
|
||||||
|
: 'Not covered by the EOI bundle.'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{showBypassControl ? (
|
||||||
|
<div className="mt-3 flex flex-wrap items-start justify-between gap-2 border-t pt-3">
|
||||||
|
<div className="min-w-0 space-y-0.5">
|
||||||
|
<p className="text-sm font-medium">Bypass EOI for this berth</p>
|
||||||
|
{row.eoiBypassReason ? (
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
<span className="font-medium text-foreground/80">Bypassed:</span>{' '}
|
||||||
|
{row.eoiBypassReason}
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Record a reason if this berth doesn't need its own EOI.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setBypassOpen(true)}
|
||||||
|
disabled={isPending}
|
||||||
|
>
|
||||||
|
{row.eoiBypassReason ? 'Edit bypass' : 'Add bypass'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{bypassOpen ? (
|
||||||
|
<BypassDialog
|
||||||
|
row={row}
|
||||||
|
open={bypassOpen}
|
||||||
|
onOpenChange={setBypassOpen}
|
||||||
|
isPending={isPending}
|
||||||
|
onSubmit={(reason) => {
|
||||||
|
onUpdate(row.berthId, { eoiBypassReason: reason });
|
||||||
|
setBypassOpen(false);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<Dialog open={confirmRemove} onOpenChange={setConfirmRemove}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Remove berth {row.mooringNumber} from interest?</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
The berth itself isn't deleted — only its link to this interest.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogFooter className="gap-2 sm:gap-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setConfirmRemove(false)}
|
||||||
|
disabled={isPending}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="destructive"
|
||||||
|
onClick={() => {
|
||||||
|
onRemove(row.berthId);
|
||||||
|
setConfirmRemove(false);
|
||||||
|
}}
|
||||||
|
disabled={isPending}
|
||||||
|
>
|
||||||
|
Remove
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Component ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function LinkedBerthsList({ interestId }: LinkedBerthsListProps) {
|
||||||
|
const params = useParams<{ portSlug: string }>();
|
||||||
|
const portSlug = params?.portSlug ?? '';
|
||||||
|
const { data, isLoading } = useLinkedBerths(interestId);
|
||||||
|
const updateMutation = useUpdateLink(interestId);
|
||||||
|
const removeMutation = useRemoveLink(interestId);
|
||||||
|
|
||||||
|
const rows = data?.data ?? [];
|
||||||
|
const eoiStatus = data?.meta.eoiStatus ?? null;
|
||||||
|
const isPending = updateMutation.isPending || removeMutation.isPending;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="flex items-center gap-2 text-base">
|
||||||
|
<Anchor className="size-4 text-brand-600" />
|
||||||
|
Linked berths{rows.length > 0 ? ` (${rows.length})` : ''}
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-3">
|
||||||
|
{isLoading ? (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{[0, 1].map((i) => (
|
||||||
|
<div key={i} className="h-24 animate-pulse rounded-lg bg-muted" />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : rows.length === 0 ? (
|
||||||
|
<p className="py-6 text-center text-sm text-muted-foreground">
|
||||||
|
No berths linked yet. Use the recommender below to add one.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{rows.map((row) => (
|
||||||
|
<LinkedBerthRowItem
|
||||||
|
key={row.id}
|
||||||
|
row={row}
|
||||||
|
portSlug={portSlug}
|
||||||
|
eoiStatus={eoiStatus}
|
||||||
|
onUpdate={(berthId, patch) => updateMutation.mutate({ berthId, patch })}
|
||||||
|
onRemove={(berthId) => removeMutation.mutate(berthId)}
|
||||||
|
isPending={isPending}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{updateMutation.isError ? (
|
||||||
|
<p className="text-sm text-destructive">
|
||||||
|
{(updateMutation.error as Error)?.message ?? 'Failed to update berth.'}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
{removeMutation.isError ? (
|
||||||
|
<p className="text-sm text-destructive">
|
||||||
|
{(removeMutation.error as Error)?.message ?? 'Failed to remove berth.'}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -99,10 +99,20 @@ export async function getPrimaryBerthsForInterests(
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Berth metadata surfaced alongside each junction row by {@link listBerthsForInterest}. */
|
||||||
|
export interface InterestBerthWithDetails extends InterestBerth {
|
||||||
|
mooringNumber: string | null;
|
||||||
|
area: string | null;
|
||||||
|
status: string;
|
||||||
|
lengthFt: string | null;
|
||||||
|
widthFt: string | null;
|
||||||
|
draftFt: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
/** All berth links for a single interest, ordered with primary first. */
|
/** All berth links for a single interest, ordered with primary first. */
|
||||||
export async function listBerthsForInterest(
|
export async function listBerthsForInterest(
|
||||||
interestId: string,
|
interestId: string,
|
||||||
): Promise<Array<InterestBerth & { mooringNumber: string | null }>> {
|
): Promise<Array<InterestBerthWithDetails>> {
|
||||||
return db
|
return db
|
||||||
.select({
|
.select({
|
||||||
id: interestBerths.id,
|
id: interestBerths.id,
|
||||||
@@ -118,6 +128,11 @@ export async function listBerthsForInterest(
|
|||||||
addedAt: interestBerths.addedAt,
|
addedAt: interestBerths.addedAt,
|
||||||
notes: interestBerths.notes,
|
notes: interestBerths.notes,
|
||||||
mooringNumber: berths.mooringNumber,
|
mooringNumber: berths.mooringNumber,
|
||||||
|
area: berths.area,
|
||||||
|
status: berths.status,
|
||||||
|
lengthFt: berths.lengthFt,
|
||||||
|
widthFt: berths.widthFt,
|
||||||
|
draftFt: berths.draftFt,
|
||||||
})
|
})
|
||||||
.from(interestBerths)
|
.from(interestBerths)
|
||||||
.innerJoin(berths, eq(berths.id, interestBerths.berthId))
|
.innerJoin(berths, eq(berths.id, interestBerths.berthId))
|
||||||
@@ -142,6 +157,15 @@ interface AddOrUpdateOpts {
|
|||||||
isInEoiBundle?: boolean;
|
isInEoiBundle?: boolean;
|
||||||
addedBy?: string;
|
addedBy?: string;
|
||||||
notes?: string;
|
notes?: string;
|
||||||
|
/**
|
||||||
|
* EOI bypass fields. Set `eoiBypassReason` to a non-empty string to record
|
||||||
|
* that the berth's own EOI is waived (the parent interest's primary EOI
|
||||||
|
* covers it), or to `null` to clear the bypass and re-require it.
|
||||||
|
* `eoiBypassedBy` should be the acting user id; the timestamp is stamped
|
||||||
|
* server-side.
|
||||||
|
*/
|
||||||
|
eoiBypassReason?: string | null;
|
||||||
|
eoiBypassedBy?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -186,6 +210,19 @@ export async function upsertInterestBerthTx(
|
|||||||
if (opts.isInEoiBundle !== undefined) setForUpdate.isInEoiBundle = opts.isInEoiBundle;
|
if (opts.isInEoiBundle !== undefined) setForUpdate.isInEoiBundle = opts.isInEoiBundle;
|
||||||
if (opts.addedBy !== undefined) setForUpdate.addedBy = opts.addedBy;
|
if (opts.addedBy !== undefined) setForUpdate.addedBy = opts.addedBy;
|
||||||
if (opts.notes !== undefined) setForUpdate.notes = opts.notes;
|
if (opts.notes !== undefined) setForUpdate.notes = opts.notes;
|
||||||
|
// Bypass fields move as a unit — either we set all three to record a bypass
|
||||||
|
// or clear all three. Touching the reason field decides which.
|
||||||
|
if (opts.eoiBypassReason !== undefined) {
|
||||||
|
if (opts.eoiBypassReason && opts.eoiBypassReason.trim().length > 0) {
|
||||||
|
setForUpdate.eoiBypassReason = opts.eoiBypassReason;
|
||||||
|
setForUpdate.eoiBypassedBy = opts.eoiBypassedBy ?? null;
|
||||||
|
setForUpdate.eoiBypassedAt = new Date();
|
||||||
|
} else {
|
||||||
|
setForUpdate.eoiBypassReason = null;
|
||||||
|
setForUpdate.eoiBypassedBy = null;
|
||||||
|
setForUpdate.eoiBypassedAt = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const [row] = await tx
|
const [row] = await tx
|
||||||
.insert(interestBerths)
|
.insert(interestBerths)
|
||||||
@@ -197,6 +234,9 @@ export async function upsertInterestBerthTx(
|
|||||||
isInEoiBundle: opts.isInEoiBundle ?? false,
|
isInEoiBundle: opts.isInEoiBundle ?? false,
|
||||||
addedBy: opts.addedBy,
|
addedBy: opts.addedBy,
|
||||||
notes: opts.notes,
|
notes: opts.notes,
|
||||||
|
eoiBypassReason: setForUpdate.eoiBypassReason ?? null,
|
||||||
|
eoiBypassedBy: setForUpdate.eoiBypassedBy ?? null,
|
||||||
|
eoiBypassedAt: setForUpdate.eoiBypassedAt ?? null,
|
||||||
})
|
})
|
||||||
.onConflictDoUpdate({
|
.onConflictDoUpdate({
|
||||||
target: [interestBerths.interestId, interestBerths.berthId],
|
target: [interestBerths.interestId, interestBerths.berthId],
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ export interface ServerToClientEvents {
|
|||||||
}) => void;
|
}) => void;
|
||||||
'interest:berthLinked': (payload: { interestId: string; berthId: string }) => void;
|
'interest:berthLinked': (payload: { interestId: string; berthId: string }) => void;
|
||||||
'interest:berthUnlinked': (payload: { interestId: string; berthId: string }) => void;
|
'interest:berthUnlinked': (payload: { interestId: string; berthId: string }) => void;
|
||||||
|
'interest:berthLinkUpdated': (payload: { interestId: string; berthId: string }) => void;
|
||||||
'interest:archived': (payload: { interestId: string }) => void;
|
'interest:archived': (payload: { interestId: string }) => void;
|
||||||
'interest:outcomeSet': (payload: {
|
'interest:outcomeSet': (payload: {
|
||||||
interestId: string;
|
interestId: string;
|
||||||
|
|||||||
427
tests/integration/api/interest-berths.test.ts
Normal file
427
tests/integration/api/interest-berths.test.ts
Normal file
@@ -0,0 +1,427 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { eq, and } from 'drizzle-orm';
|
||||||
|
|
||||||
|
import { listHandler, addHandler } from '@/app/api/v1/interests/[id]/berths/handlers';
|
||||||
|
import { patchHandler, deleteHandler } from '@/app/api/v1/interests/[id]/berths/[berthId]/handlers';
|
||||||
|
import { withPermission } from '@/lib/api/helpers';
|
||||||
|
import { db } from '@/lib/db';
|
||||||
|
import { interestBerths, interests } from '@/lib/db/schema/interests';
|
||||||
|
import { makeMockCtx, makeMockRequest } from '../../helpers/route-tester';
|
||||||
|
import {
|
||||||
|
makePort,
|
||||||
|
makeClient,
|
||||||
|
makeBerth,
|
||||||
|
makeFullPermissions,
|
||||||
|
makeViewerPermissions,
|
||||||
|
} from '../../helpers/factories';
|
||||||
|
|
||||||
|
async function makeInterest(args: {
|
||||||
|
portId: string;
|
||||||
|
clientId: string;
|
||||||
|
eoiStatus?: 'waiting_for_signatures' | 'signed' | 'expired' | null;
|
||||||
|
}) {
|
||||||
|
const [row] = await db
|
||||||
|
.insert(interests)
|
||||||
|
.values({
|
||||||
|
portId: args.portId,
|
||||||
|
clientId: args.clientId,
|
||||||
|
pipelineStage: 'open',
|
||||||
|
eoiStatus: args.eoiStatus ?? null,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
return row!;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── GET /api/v1/interests/[id]/berths ──────────────────────────────────────
|
||||||
|
|
||||||
|
describe('GET /api/v1/interests/[id]/berths (listHandler)', () => {
|
||||||
|
it('returns linked berths and surfaces eoiStatus in meta', async () => {
|
||||||
|
const port = await makePort();
|
||||||
|
const client = await makeClient({ portId: port.id });
|
||||||
|
const interest = await makeInterest({
|
||||||
|
portId: port.id,
|
||||||
|
clientId: client.id,
|
||||||
|
eoiStatus: 'signed',
|
||||||
|
});
|
||||||
|
const berth = await makeBerth({ portId: port.id });
|
||||||
|
await db.insert(interestBerths).values({
|
||||||
|
interestId: interest.id,
|
||||||
|
berthId: berth.id,
|
||||||
|
isPrimary: true,
|
||||||
|
isSpecificInterest: true,
|
||||||
|
isInEoiBundle: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
|
||||||
|
const req = makeMockRequest('GET', `http://localhost/api/v1/interests/${interest.id}/berths`);
|
||||||
|
const res = await listHandler(req, ctx, { id: interest.id });
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const body = await res.json();
|
||||||
|
expect(body.data).toHaveLength(1);
|
||||||
|
expect(body.data[0].berthId).toBe(berth.id);
|
||||||
|
expect(body.data[0].mooringNumber).toBe(berth.mooringNumber);
|
||||||
|
expect(body.meta.eoiStatus).toBe('signed');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns 404 for a cross-port interest (tenant isolation)', async () => {
|
||||||
|
const portA = await makePort();
|
||||||
|
const portB = await makePort();
|
||||||
|
const client = await makeClient({ portId: portA.id });
|
||||||
|
const interest = await makeInterest({ portId: portA.id, clientId: client.id });
|
||||||
|
|
||||||
|
const ctx = makeMockCtx({ portId: portB.id, permissions: makeFullPermissions() });
|
||||||
|
const req = makeMockRequest('GET', `http://localhost/api/v1/interests/${interest.id}/berths`);
|
||||||
|
const res = await listHandler(req, ctx, { id: interest.id });
|
||||||
|
expect(res.status).toBe(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('viewer with interests.view can list', async () => {
|
||||||
|
const port = await makePort();
|
||||||
|
const client = await makeClient({ portId: port.id });
|
||||||
|
const interest = await makeInterest({ portId: port.id, clientId: client.id });
|
||||||
|
const ctx = makeMockCtx({ portId: port.id, permissions: makeViewerPermissions() });
|
||||||
|
const gated = withPermission('interests', 'view', listHandler);
|
||||||
|
const req = makeMockRequest('GET', `http://localhost/api/v1/interests/${interest.id}/berths`);
|
||||||
|
const res = await gated(req, ctx, { id: interest.id });
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── POST /api/v1/interests/[id]/berths ─────────────────────────────────────
|
||||||
|
|
||||||
|
describe('POST /api/v1/interests/[id]/berths (addHandler)', () => {
|
||||||
|
it('links a berth to an interest with isSpecificInterest', async () => {
|
||||||
|
const port = await makePort();
|
||||||
|
const client = await makeClient({ portId: port.id });
|
||||||
|
const interest = await makeInterest({ portId: port.id, clientId: client.id });
|
||||||
|
const berth = await makeBerth({ portId: port.id });
|
||||||
|
|
||||||
|
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
|
||||||
|
const req = makeMockRequest('POST', `http://localhost/api/v1/interests/${interest.id}/berths`, {
|
||||||
|
body: { berthId: berth.id, isSpecificInterest: true },
|
||||||
|
});
|
||||||
|
const res = await addHandler(req, ctx, { id: interest.id });
|
||||||
|
expect(res.status).toBe(201);
|
||||||
|
const body = await res.json();
|
||||||
|
expect(body.data.berthId).toBe(berth.id);
|
||||||
|
expect(body.data.isSpecificInterest).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a berth from a different port (404 on the interest scope)', async () => {
|
||||||
|
const portA = await makePort();
|
||||||
|
const portB = await makePort();
|
||||||
|
const clientA = await makeClient({ portId: portA.id });
|
||||||
|
const interestA = await makeInterest({ portId: portA.id, clientId: clientA.id });
|
||||||
|
const berthB = await makeBerth({ portId: portB.id });
|
||||||
|
|
||||||
|
const ctx = makeMockCtx({ portId: portA.id, permissions: makeFullPermissions() });
|
||||||
|
const req = makeMockRequest(
|
||||||
|
'POST',
|
||||||
|
`http://localhost/api/v1/interests/${interestA.id}/berths`,
|
||||||
|
{ body: { berthId: berthB.id, isSpecificInterest: true } },
|
||||||
|
);
|
||||||
|
const res = await addHandler(req, ctx, { id: interestA.id });
|
||||||
|
// berth doesn't belong to caller's port → 400 ValidationError
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('viewer (no interests.edit) receives 403 through the permission gate', async () => {
|
||||||
|
const port = await makePort();
|
||||||
|
const client = await makeClient({ portId: port.id });
|
||||||
|
const interest = await makeInterest({ portId: port.id, clientId: client.id });
|
||||||
|
const berth = await makeBerth({ portId: port.id });
|
||||||
|
|
||||||
|
const gated = withPermission('interests', 'edit', addHandler);
|
||||||
|
const ctx = makeMockCtx({ portId: port.id, permissions: makeViewerPermissions() });
|
||||||
|
const req = makeMockRequest('POST', `http://localhost/api/v1/interests/${interest.id}/berths`, {
|
||||||
|
body: { berthId: berth.id, isSpecificInterest: true },
|
||||||
|
});
|
||||||
|
const res = await gated(req, ctx, { id: interest.id });
|
||||||
|
expect(res.status).toBe(403);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── PATCH /api/v1/interests/[id]/berths/[berthId] ──────────────────────────
|
||||||
|
|
||||||
|
describe('PATCH /api/v1/interests/[id]/berths/[berthId] (patchHandler)', () => {
|
||||||
|
it('updates flags and returns the latest junction row', async () => {
|
||||||
|
const port = await makePort();
|
||||||
|
const client = await makeClient({ portId: port.id });
|
||||||
|
const interest = await makeInterest({ portId: port.id, clientId: client.id });
|
||||||
|
const berth = await makeBerth({ portId: port.id });
|
||||||
|
await db.insert(interestBerths).values({
|
||||||
|
interestId: interest.id,
|
||||||
|
berthId: berth.id,
|
||||||
|
isPrimary: false,
|
||||||
|
isSpecificInterest: true,
|
||||||
|
isInEoiBundle: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
|
||||||
|
const req = makeMockRequest(
|
||||||
|
'PATCH',
|
||||||
|
`http://localhost/api/v1/interests/${interest.id}/berths/${berth.id}`,
|
||||||
|
{ body: { isInEoiBundle: true, isSpecificInterest: false } },
|
||||||
|
);
|
||||||
|
const res = await patchHandler(req, ctx, { id: interest.id, berthId: berth.id });
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const body = await res.json();
|
||||||
|
expect(body.data.isInEoiBundle).toBe(true);
|
||||||
|
expect(body.data.isSpecificInterest).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('promoting one row to primary demotes the prior primary in the same interest', async () => {
|
||||||
|
const port = await makePort();
|
||||||
|
const client = await makeClient({ portId: port.id });
|
||||||
|
const interest = await makeInterest({ portId: port.id, clientId: client.id });
|
||||||
|
const berthA = await makeBerth({ portId: port.id });
|
||||||
|
const berthB = await makeBerth({ portId: port.id });
|
||||||
|
await db.insert(interestBerths).values([
|
||||||
|
{ interestId: interest.id, berthId: berthA.id, isPrimary: true },
|
||||||
|
{ interestId: interest.id, berthId: berthB.id, isPrimary: false },
|
||||||
|
]);
|
||||||
|
|
||||||
|
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
|
||||||
|
const req = makeMockRequest(
|
||||||
|
'PATCH',
|
||||||
|
`http://localhost/api/v1/interests/${interest.id}/berths/${berthB.id}`,
|
||||||
|
{ body: { isPrimary: true } },
|
||||||
|
);
|
||||||
|
const res = await patchHandler(req, ctx, { id: interest.id, berthId: berthB.id });
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
|
||||||
|
const rows = await db
|
||||||
|
.select()
|
||||||
|
.from(interestBerths)
|
||||||
|
.where(eq(interestBerths.interestId, interest.id));
|
||||||
|
const rowA = rows.find((r) => r.berthId === berthA.id);
|
||||||
|
const rowB = rows.find((r) => r.berthId === berthB.id);
|
||||||
|
expect(rowA?.isPrimary).toBe(false);
|
||||||
|
expect(rowB?.isPrimary).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('records bypass fields when interest has signed primary EOI', async () => {
|
||||||
|
const port = await makePort();
|
||||||
|
const client = await makeClient({ portId: port.id });
|
||||||
|
const interest = await makeInterest({
|
||||||
|
portId: port.id,
|
||||||
|
clientId: client.id,
|
||||||
|
eoiStatus: 'signed',
|
||||||
|
});
|
||||||
|
const berth = await makeBerth({ portId: port.id });
|
||||||
|
await db.insert(interestBerths).values({
|
||||||
|
interestId: interest.id,
|
||||||
|
berthId: berth.id,
|
||||||
|
isPrimary: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const ctx = makeMockCtx({
|
||||||
|
portId: port.id,
|
||||||
|
permissions: makeFullPermissions(),
|
||||||
|
userId: 'rep-1',
|
||||||
|
});
|
||||||
|
const req = makeMockRequest(
|
||||||
|
'PATCH',
|
||||||
|
`http://localhost/api/v1/interests/${interest.id}/berths/${berth.id}`,
|
||||||
|
{ body: { eoiBypassReason: 'covered under bundle EOI' } },
|
||||||
|
);
|
||||||
|
const res = await patchHandler(req, ctx, { id: interest.id, berthId: berth.id });
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
|
||||||
|
const [row] = await db
|
||||||
|
.select()
|
||||||
|
.from(interestBerths)
|
||||||
|
.where(and(eq(interestBerths.interestId, interest.id), eq(interestBerths.berthId, berth.id)));
|
||||||
|
expect(row?.eoiBypassReason).toBe('covered under bundle EOI');
|
||||||
|
expect(row?.eoiBypassedBy).toBe('rep-1');
|
||||||
|
expect(row?.eoiBypassedAt).toBeInstanceOf(Date);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects bypass when the interest does not have a signed EOI', async () => {
|
||||||
|
const port = await makePort();
|
||||||
|
const client = await makeClient({ portId: port.id });
|
||||||
|
const interest = await makeInterest({
|
||||||
|
portId: port.id,
|
||||||
|
clientId: client.id,
|
||||||
|
eoiStatus: 'waiting_for_signatures',
|
||||||
|
});
|
||||||
|
const berth = await makeBerth({ portId: port.id });
|
||||||
|
await db.insert(interestBerths).values({
|
||||||
|
interestId: interest.id,
|
||||||
|
berthId: berth.id,
|
||||||
|
});
|
||||||
|
|
||||||
|
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
|
||||||
|
const req = makeMockRequest(
|
||||||
|
'PATCH',
|
||||||
|
`http://localhost/api/v1/interests/${interest.id}/berths/${berth.id}`,
|
||||||
|
{ body: { eoiBypassReason: 'too early' } },
|
||||||
|
);
|
||||||
|
const res = await patchHandler(req, ctx, { id: interest.id, berthId: berth.id });
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears bypass when reason is null', async () => {
|
||||||
|
const port = await makePort();
|
||||||
|
const client = await makeClient({ portId: port.id });
|
||||||
|
const interest = await makeInterest({
|
||||||
|
portId: port.id,
|
||||||
|
clientId: client.id,
|
||||||
|
eoiStatus: 'signed',
|
||||||
|
});
|
||||||
|
const berth = await makeBerth({ portId: port.id });
|
||||||
|
await db.insert(interestBerths).values({
|
||||||
|
interestId: interest.id,
|
||||||
|
berthId: berth.id,
|
||||||
|
eoiBypassReason: 'previously bypassed',
|
||||||
|
eoiBypassedBy: 'someone',
|
||||||
|
eoiBypassedAt: new Date(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
|
||||||
|
const req = makeMockRequest(
|
||||||
|
'PATCH',
|
||||||
|
`http://localhost/api/v1/interests/${interest.id}/berths/${berth.id}`,
|
||||||
|
{ body: { eoiBypassReason: null } },
|
||||||
|
);
|
||||||
|
const res = await patchHandler(req, ctx, { id: interest.id, berthId: berth.id });
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
|
||||||
|
const [row] = await db
|
||||||
|
.select()
|
||||||
|
.from(interestBerths)
|
||||||
|
.where(and(eq(interestBerths.interestId, interest.id), eq(interestBerths.berthId, berth.id)));
|
||||||
|
expect(row?.eoiBypassReason).toBeNull();
|
||||||
|
expect(row?.eoiBypassedBy).toBeNull();
|
||||||
|
expect(row?.eoiBypassedAt).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns 404 for a cross-port interest', async () => {
|
||||||
|
const portA = await makePort();
|
||||||
|
const portB = await makePort();
|
||||||
|
const client = await makeClient({ portId: portA.id });
|
||||||
|
const interest = await makeInterest({ portId: portA.id, clientId: client.id });
|
||||||
|
const berth = await makeBerth({ portId: portA.id });
|
||||||
|
await db.insert(interestBerths).values({ interestId: interest.id, berthId: berth.id });
|
||||||
|
|
||||||
|
const ctx = makeMockCtx({ portId: portB.id, permissions: makeFullPermissions() });
|
||||||
|
const req = makeMockRequest(
|
||||||
|
'PATCH',
|
||||||
|
`http://localhost/api/v1/interests/${interest.id}/berths/${berth.id}`,
|
||||||
|
{ body: { isPrimary: true } },
|
||||||
|
);
|
||||||
|
const res = await patchHandler(req, ctx, { id: interest.id, berthId: berth.id });
|
||||||
|
expect(res.status).toBe(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns 404 when the junction row does not exist', async () => {
|
||||||
|
const port = await makePort();
|
||||||
|
const client = await makeClient({ portId: port.id });
|
||||||
|
const interest = await makeInterest({ portId: port.id, clientId: client.id });
|
||||||
|
const berth = await makeBerth({ portId: port.id });
|
||||||
|
|
||||||
|
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
|
||||||
|
const req = makeMockRequest(
|
||||||
|
'PATCH',
|
||||||
|
`http://localhost/api/v1/interests/${interest.id}/berths/${berth.id}`,
|
||||||
|
{ body: { isPrimary: true } },
|
||||||
|
);
|
||||||
|
const res = await patchHandler(req, ctx, { id: interest.id, berthId: berth.id });
|
||||||
|
expect(res.status).toBe(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns 400 when the body is empty', async () => {
|
||||||
|
const port = await makePort();
|
||||||
|
const client = await makeClient({ portId: port.id });
|
||||||
|
const interest = await makeInterest({ portId: port.id, clientId: client.id });
|
||||||
|
const berth = await makeBerth({ portId: port.id });
|
||||||
|
await db.insert(interestBerths).values({ interestId: interest.id, berthId: berth.id });
|
||||||
|
|
||||||
|
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
|
||||||
|
const req = makeMockRequest(
|
||||||
|
'PATCH',
|
||||||
|
`http://localhost/api/v1/interests/${interest.id}/berths/${berth.id}`,
|
||||||
|
{ body: {} },
|
||||||
|
);
|
||||||
|
const res = await patchHandler(req, ctx, { id: interest.id, berthId: berth.id });
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('viewer (no interests.edit) receives 403 through the permission gate', async () => {
|
||||||
|
const port = await makePort();
|
||||||
|
const client = await makeClient({ portId: port.id });
|
||||||
|
const interest = await makeInterest({ portId: port.id, clientId: client.id });
|
||||||
|
const berth = await makeBerth({ portId: port.id });
|
||||||
|
await db.insert(interestBerths).values({ interestId: interest.id, berthId: berth.id });
|
||||||
|
|
||||||
|
const gated = withPermission('interests', 'edit', patchHandler);
|
||||||
|
const ctx = makeMockCtx({ portId: port.id, permissions: makeViewerPermissions() });
|
||||||
|
const req = makeMockRequest(
|
||||||
|
'PATCH',
|
||||||
|
`http://localhost/api/v1/interests/${interest.id}/berths/${berth.id}`,
|
||||||
|
{ body: { isPrimary: true } },
|
||||||
|
);
|
||||||
|
const res = await gated(req, ctx, { id: interest.id, berthId: berth.id });
|
||||||
|
expect(res.status).toBe(403);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── DELETE /api/v1/interests/[id]/berths/[berthId] ─────────────────────────
|
||||||
|
|
||||||
|
describe('DELETE /api/v1/interests/[id]/berths/[berthId] (deleteHandler)', () => {
|
||||||
|
it('removes the junction row and returns 204', async () => {
|
||||||
|
const port = await makePort();
|
||||||
|
const client = await makeClient({ portId: port.id });
|
||||||
|
const interest = await makeInterest({ portId: port.id, clientId: client.id });
|
||||||
|
const berth = await makeBerth({ portId: port.id });
|
||||||
|
await db.insert(interestBerths).values({ interestId: interest.id, berthId: berth.id });
|
||||||
|
|
||||||
|
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
|
||||||
|
const req = makeMockRequest(
|
||||||
|
'DELETE',
|
||||||
|
`http://localhost/api/v1/interests/${interest.id}/berths/${berth.id}`,
|
||||||
|
);
|
||||||
|
const res = await deleteHandler(req, ctx, { id: interest.id, berthId: berth.id });
|
||||||
|
expect(res.status).toBe(204);
|
||||||
|
|
||||||
|
const rows = await db
|
||||||
|
.select()
|
||||||
|
.from(interestBerths)
|
||||||
|
.where(and(eq(interestBerths.interestId, interest.id), eq(interestBerths.berthId, berth.id)));
|
||||||
|
expect(rows).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns 404 for a cross-port interest', async () => {
|
||||||
|
const portA = await makePort();
|
||||||
|
const portB = await makePort();
|
||||||
|
const client = await makeClient({ portId: portA.id });
|
||||||
|
const interest = await makeInterest({ portId: portA.id, clientId: client.id });
|
||||||
|
const berth = await makeBerth({ portId: portA.id });
|
||||||
|
await db.insert(interestBerths).values({ interestId: interest.id, berthId: berth.id });
|
||||||
|
|
||||||
|
const ctx = makeMockCtx({ portId: portB.id, permissions: makeFullPermissions() });
|
||||||
|
const req = makeMockRequest(
|
||||||
|
'DELETE',
|
||||||
|
`http://localhost/api/v1/interests/${interest.id}/berths/${berth.id}`,
|
||||||
|
);
|
||||||
|
const res = await deleteHandler(req, ctx, { id: interest.id, berthId: berth.id });
|
||||||
|
expect(res.status).toBe(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('viewer (no interests.edit) receives 403 through the permission gate', async () => {
|
||||||
|
const port = await makePort();
|
||||||
|
const client = await makeClient({ portId: port.id });
|
||||||
|
const interest = await makeInterest({ portId: port.id, clientId: client.id });
|
||||||
|
const berth = await makeBerth({ portId: port.id });
|
||||||
|
await db.insert(interestBerths).values({ interestId: interest.id, berthId: berth.id });
|
||||||
|
|
||||||
|
const gated = withPermission('interests', 'edit', deleteHandler);
|
||||||
|
const ctx = makeMockCtx({ portId: port.id, permissions: makeViewerPermissions() });
|
||||||
|
const req = makeMockRequest(
|
||||||
|
'DELETE',
|
||||||
|
`http://localhost/api/v1/interests/${interest.id}/berths/${berth.id}`,
|
||||||
|
);
|
||||||
|
const res = await gated(req, ctx, { id: interest.id, berthId: berth.id });
|
||||||
|
expect(res.status).toBe(403);
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user