refactor(interests): migrate callers to interest_berths junction + drop berth_id

Phase 2b of the berth-recommender refactor (plan §3.4). Every caller of
the legacy `interests.berth_id` column now reads / writes through the
`interest_berths` junction via the helper service introduced in Phase 2a;
the column itself is dropped in a final migration.

Service-layer changes
- interests.service: filter `?berthId=X` becomes EXISTS-against-junction;
  list enrichment uses `getPrimaryBerthsForInterests`; create/update/
  linkBerth/unlinkBerth all dispatch through the junction helpers, with
  createInterest's row insert + junction write sharing a single transaction.
- clients / dashboard / report-generators / search: leftJoin chains pivot
  through `interest_berths` filtered by `is_primary=true`.
- eoi-context / document-templates / berth-rules-engine / portal /
  record-export / queue worker: read primary via `getPrimaryBerth(...)`.
- interest-scoring: berthLinked is now derived from any junction row count.
- dedup/migration-apply + public interest route: write a primary junction
  row alongside the interest insert when a berth is provided.

API contract preserved: list/detail responses still emit `berthId` and
`berthMooringNumber`, derived from the primary junction row, so frontend
consumers (interest-form, interest-detail-header) need no changes.

Schema + migration
- Drop `interestsRelations.berth` and `idx_interests_berth`.
- Replace `berthsRelations.interests` with `interestBerths`.
- Migration 0029_puzzling_romulus drops `interests.berth_id` + the index.
- Tests that previously inserted `interests.berthId` now seed a primary
  junction row alongside the interest.

Verified: vitest 995 passing (1 unrelated pre-existing flake in
maintenance-cleanup.test.ts), tsc clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Matt Ciaccio
2026-05-05 02:41:52 +02:00
parent ff92a08620
commit 6e3d910c76
26 changed files with 11351 additions and 220 deletions

View File

@@ -1,9 +1,13 @@
import { and, desc, eq, inArray, isNull, or } from 'drizzle-orm';
import { and, desc, eq, exists, inArray, isNull, or, sql } from 'drizzle-orm';
import { db } from '@/lib/db';
import { clients, clientContacts } from '@/lib/db/schema/clients';
import { interests } from '@/lib/db/schema/interests';
import { interests, interestBerths } from '@/lib/db/schema/interests';
import { berths, berthWaitingList, berthMaintenanceLog } from '@/lib/db/schema/berths';
import {
getPrimaryBerth,
getPrimaryBerthsForInterests,
} from '@/lib/services/interest-berths.service';
import { yachts } from '@/lib/db/schema/yachts';
import { companyMemberships } from '@/lib/db/schema/companies';
import { auditLogs } from '@/lib/db/schema/system';
@@ -61,22 +65,18 @@ export async function exportClientPdf(clientId: string, portId: string): Promise
.orderBy(desc(auditLogs.createdAt))
.limit(20);
// Enrich interests with berth mooring numbers
const berthIds = interestList.map((i) => i.berthId).filter(Boolean) as string[];
// Enrich interests with primary-berth mooring numbers (plan §3.4 - the
// legacy interest.berth_id column has been replaced by the junction).
const primaryBerthMap = await getPrimaryBerthsForInterests(interestList.map((i) => i.id));
let berthsMap: Record<string, string> = {};
if (berthIds.length > 0) {
const berthRows = await db
.select({ id: berths.id, mooringNumber: berths.mooringNumber })
.from(berths)
.where(inArray(berths.id, berthIds));
berthsMap = Object.fromEntries(berthRows.map((b) => [b.id, b.mooringNumber]));
}
const enrichedInterests = interestList.map((i) => ({
...i,
berthMooringNumber: i.berthId ? (berthsMap[i.berthId] ?? null) : null,
}));
const enrichedInterests = interestList.map((i) => {
const primary = primaryBerthMap.get(i.id);
return {
...i,
berthId: primary?.berthId ?? null,
berthMooringNumber: primary?.mooringNumber ?? null,
};
});
// Yachts owned by the client directly OR by a company they're an active
// member of. Active membership = no end date.
@@ -169,11 +169,24 @@ export async function exportBerthPdf(berthId: string, portId: string): Promise<U
.orderBy(desc(berthMaintenanceLog.performedDate))
.limit(20);
// Linked interests
// Linked interests - "this berth is linked to this interest in any role"
// (plan §3.4 - EXISTS against the junction).
const linkedInterests = await db
.select()
.from(interests)
.where(and(eq(interests.berthId, berthId), eq(interests.portId, portId)))
.where(
and(
eq(interests.portId, portId),
exists(
db
.select({ one: sql`1` })
.from(interestBerths)
.where(
and(eq(interestBerths.interestId, interests.id), eq(interestBerths.berthId, berthId)),
),
),
),
)
.orderBy(desc(interests.updatedAt))
.limit(20);
@@ -204,9 +217,11 @@ export async function exportInterestPdf(interestId: string, portId: string): Pro
db.query.ports.findFirst({ where: eq(ports.id, portId) }),
]);
// Resolve primary berth via the junction (plan §3.4).
const primaryBerth = await getPrimaryBerth(interest.id);
let berth = null;
if (interest.berthId) {
berth = await db.query.berths.findFirst({ where: eq(berths.id, interest.berthId) });
if (primaryBerth?.berthId) {
berth = await db.query.berths.findFirst({ where: eq(berths.id, primaryBerth.berthId) });
}
let yacht = null;