feat(berths): public berths API + health env-match endpoint

Adds the read-only public-website data feed promised by plan §4.5 and
§7.3. The marketing site's `getBerths()` swap is now a one-line URL
change against the existing 5-min TTL behaviour.

- src/app/api/public/berths/route.ts: GET / unauth, returns the full
  port-nimara berth list as { list, pageInfo } in the verbatim NocoDB
  shape ("Mooring Number", "Side Pontoon", quoted-key fields). Cache:
  s-maxage=300 + stale-while-revalidate=60. portSlug query param lets
  future ports opt in.
- src/app/api/public/berths/[mooringNumber]/route.ts: GET single. Up-
  front regex validation (^[A-Z]+\\d+$) rejects malformed lookups with
  400 + cache-control:no-store before hitting the DB. 404 + no-store
  when not found.
- src/app/api/public/health/route.ts: returns { status, env, appUrl,
  timestamp } so the marketing site can refuse to start when its
  CRM_PUBLIC_URL points at a different deployment env (§14.8 critical
  env-mismatch protection).
- src/lib/services/public-berths.ts: pure mapper with derivePublicStatus
  ("sold" wins; otherwise specific-interest junction OR
  status='under_offer' -> "Under Offer"; else "Available").
- 11 unit tests covering numeric coercion, status derivation,
  archived-berth handling, missing-map-data omission, and the
  status-precedence rule that "sold" trumps the specific-interest
  signal.

Smoke-tested: /api/public/berths -> 117 rows, A1 correctly shows
"Under Offer" (has interest_berths.is_specific_interest=true link),
INVALID -> 400, Z99 -> 404. Total tests: 996 -> 1007.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Matt Ciaccio
2026-05-05 02:52:44 +02:00
parent 5b70e9b04b
commit fb1116f1d4
5 changed files with 537 additions and 0 deletions

View File

@@ -0,0 +1,93 @@
import { NextResponse } from 'next/server';
import { and, eq, isNull } from 'drizzle-orm';
import { db } from '@/lib/db';
import { ports } from '@/lib/db/schema/ports';
import { berths, berthMapData } from '@/lib/db/schema/berths';
import { interestBerths, interests } from '@/lib/db/schema/interests';
import { logger } from '@/lib/logger';
import { toPublicBerth } from '@/lib/services/public-berths';
/**
* GET /api/public/berths/[mooringNumber]
*
* Single-berth lookup for the public website's `/berths/[number]`
* page. Mooring numbers are matched against the canonical bare form
* ("A1", "B12") - Phase 0 normalized the entire CRM dataset.
*/
const DEFAULT_PUBLIC_PORT_SLUG = 'port-nimara';
const RESPONSE_HEADERS = {
'cache-control': 'public, s-maxage=300, stale-while-revalidate=60',
'content-type': 'application/json; charset=utf-8',
};
const MOORING_PATTERN = /^[A-Z]+\d+$/;
export async function GET(
request: Request,
ctx: { params: Promise<{ mooringNumber: string }> },
): Promise<Response> {
const { mooringNumber } = await ctx.params;
const url = new URL(request.url);
const portSlug = url.searchParams.get('portSlug') ?? DEFAULT_PUBLIC_PORT_SLUG;
// Reject obviously malformed mooring numbers up front so cache poisoning
// / random-URL probing returns 400 rather than 404 (saves a DB hit).
if (!MOORING_PATTERN.test(mooringNumber)) {
return NextResponse.json(
{ error: 'invalid mooring number', mooringNumber },
{ status: 400, headers: { 'cache-control': 'no-store' } },
);
}
const [port] = await db
.select({ id: ports.id })
.from(ports)
.where(eq(ports.slug, portSlug))
.limit(1);
if (!port) {
return NextResponse.json(
{ error: 'port not found', portSlug },
{ status: 404, headers: { 'cache-control': 'no-store' } },
);
}
const [berth] = await db
.select()
.from(berths)
.where(and(eq(berths.portId, port.id), eq(berths.mooringNumber, mooringNumber)))
.limit(1);
if (!berth) {
return NextResponse.json(
{ error: 'berth not found', mooringNumber },
{ status: 404, headers: { 'cache-control': 'no-store' } },
);
}
const [mapData, specificInterestRows] = await Promise.all([
db.select().from(berthMapData).where(eq(berthMapData.berthId, berth.id)).limit(1),
db
.select({ berthId: interestBerths.berthId })
.from(interestBerths)
.innerJoin(interests, eq(interests.id, interestBerths.interestId))
.where(
and(
eq(interestBerths.berthId, berth.id),
eq(interestBerths.isSpecificInterest, true),
isNull(interests.archivedAt),
),
)
.limit(1),
]);
const out = toPublicBerth(berth, mapData[0] ?? null, specificInterestRows.length > 0);
if (out.Status !== 'Available' && out.Status !== 'Under Offer' && out.Status !== 'Sold') {
logger.error({ berthId: berth.id, status: out.Status }, 'Public berth status out of range');
return NextResponse.json({ error: 'internal' }, { status: 500 });
}
return new Response(JSON.stringify(out), { headers: RESPONSE_HEADERS, status: 200 });
}

View File

@@ -0,0 +1,140 @@
import { NextResponse } from 'next/server';
import { and, eq, inArray, isNull, sql } from 'drizzle-orm';
import { db } from '@/lib/db';
import { ports } from '@/lib/db/schema/ports';
import { berths, berthMapData } from '@/lib/db/schema/berths';
import { interestBerths, interests } from '@/lib/db/schema/interests';
import { logger } from '@/lib/logger';
import { toPublicBerth, type PublicBerth } from '@/lib/services/public-berths';
/**
* GET /api/public/berths
*
* Public-website data feed. Returns the full berth list for the public-
* facing port (default: port-nimara) in the same JSON shape NocoDB
* returned, so the website's existing `getBerths()` swap is a one-line
* URL change (plan §4.5 + §7.3).
*
* Auth: none. The endpoint is read-only and exposes only the explicit
* field allowlist defined in `toPublicBerth`.
*
* Caching: `s-maxage=300, stale-while-revalidate=60` matches the
* website's existing 5-minute TTL behaviour against NocoDB. Edge/CDN
* caches honour these headers; the Next.js fetch cache also picks
* them up.
*/
const DEFAULT_PUBLIC_PORT_SLUG = 'port-nimara';
const RESPONSE_HEADERS = {
'cache-control': 'public, s-maxage=300, stale-while-revalidate=60',
'content-type': 'application/json; charset=utf-8',
};
interface ListResponse {
list: PublicBerth[];
pageInfo: {
totalRows: number;
page: 1;
pageSize: number;
isFirstPage: true;
isLastPage: true;
};
}
export async function GET(request: Request): Promise<Response> {
const url = new URL(request.url);
const portSlug = url.searchParams.get('portSlug') ?? DEFAULT_PUBLIC_PORT_SLUG;
const [port] = await db
.select({ id: ports.id })
.from(ports)
.where(eq(ports.slug, portSlug))
.limit(1);
if (!port) {
return NextResponse.json(
{ error: 'port not found', portSlug },
{ status: 404, headers: { 'cache-control': 'no-store' } },
);
}
// 1. Active berths for the port (archived would be an explicit field
// once we add one - today we don't have an archived_at on berths,
// so we surface every row except those marked status='sold' on
// request? No: §4.5 says "filters out berths archived in CRM".
// The current schema has no archived flag for berths, so this is
// a no-op today; future archive flag plugs in here.
const berthRows = await db.select().from(berths).where(eq(berths.portId, port.id));
if (berthRows.length === 0) {
return jsonResponse({ list: [], pageInfo: emptyPageInfo() });
}
const berthIds = berthRows.map((b) => b.id);
// 2. Bulk-fetch map_data + the "has specific-interest link" flag.
const [mapRows, specificInterestRows] = await Promise.all([
db.select().from(berthMapData).where(inArray(berthMapData.berthId, berthIds)),
db
.selectDistinct({ berthId: interestBerths.berthId })
.from(interestBerths)
.innerJoin(interests, eq(interests.id, interestBerths.interestId))
.where(
and(
inArray(interestBerths.berthId, berthIds),
eq(interestBerths.isSpecificInterest, true),
isNull(interests.archivedAt),
),
),
]);
const mapByBerth = new Map(mapRows.map((m) => [m.berthId, m]));
const specificInterestSet = new Set(specificInterestRows.map((r) => r.berthId));
const list = berthRows.map((b) =>
toPublicBerth(b, mapByBerth.get(b.id) ?? null, specificInterestSet.has(b.id)),
);
// Validate the response enum before returning - any unknown status
// value would hit a 500 (per §14.8) rather than silently shipping
// invalid data downstream.
for (const row of list) {
if (row.Status !== 'Available' && row.Status !== 'Under Offer' && row.Status !== 'Sold') {
logger.error({ row }, 'Public berth status out of range');
return NextResponse.json(
{ error: 'internal', detail: 'berth status enum drift' },
{ status: 500 },
);
}
}
return jsonResponse({
list,
pageInfo: {
totalRows: list.length,
page: 1,
pageSize: list.length,
isFirstPage: true,
isLastPage: true,
},
});
}
function jsonResponse(body: ListResponse): Response {
return new Response(JSON.stringify(body), { headers: RESPONSE_HEADERS, status: 200 });
}
function emptyPageInfo() {
return {
totalRows: 0,
page: 1 as const,
pageSize: 0,
isFirstPage: true as const,
isLastPage: true as const,
};
}
// Suppress the `sql` import unused-warning when no inline raw SQL appears
// further down (helper kept for future where-clause extensions).
void sql;

View File

@@ -0,0 +1,25 @@
import { NextResponse } from 'next/server';
import { env } from '@/lib/env';
/**
* GET /api/public/health
*
* Public-facing health probe. Used by the marketing-website server on
* startup to verify it's pointed at a CRM matching its own deployment
* env (plan §14.8 critical: prevent staging-website-talking-to-prod-CRM).
*
* Returns the CRM's `NODE_ENV` and `APP_URL` so the website can do a
* strict equality check before serving any request.
*/
export function GET(): Response {
return NextResponse.json(
{
status: 'ok',
env: env.NODE_ENV,
appUrl: env.APP_URL,
timestamp: new Date().toISOString(),
},
{ headers: { 'cache-control': 'no-store' } },
);
}