Files
pn-new-crm/src/lib/services/record-export.tsx

369 lines
12 KiB
TypeScript
Raw Normal View History

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>
2026-05-05 02:41:52 +02:00
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';
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>
2026-05-05 02:41:52 +02:00
import { interests, interestBerths } from '@/lib/db/schema/interests';
import { berths, berthWaitingList, berthMaintenanceLog } from '@/lib/db/schema/berths';
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>
2026-05-05 02:41:52 +02:00
import {
getPrimaryBerth,
getPrimaryBerthsForInterests,
} from '@/lib/services/interest-berths.service';
refactor(clients): drop deprecated yacht/company/proxy columns PR 13: now that all reads are migrated to the dedicated yacht / company / membership entities, drop the columns that mirrored them on `clients`: companyName, isProxy, proxyType, actualOwnerName, relationshipNotes, yachtName, yachtLength{Ft,M}, yachtWidth{Ft,M}, yachtDraft{Ft,M}, berthSizeDesired. Migration `0008_loud_ikaris.sql` issues the destructive ALTER TABLE DROP COLUMN statements. Run `pnpm db:push` (or the migration runner) to apply. Caller cleanup (zero behavioral change to remaining flows): - Drops the legacy `generateEoi` flow entirely (route, service function, pdfme template, validator schema). The dual-path generate-and-sign service from PR 11 has fully replaced it; the route was no longer wired to the UI. - `clients.service`: company-name search column / WHERE / audit value removed; search now ranks by full name only. - `interests.service`: `resolveLeadCategory` reads dimensions from `yachts` via `interest.yachtId` instead of the dropped `client.yachtLength{Ft,M}`. - `record-export`: client-summary now lists yachts via owner-side lookup (direct + active company memberships); interest-summary fetches yacht via `interest.yachtId`. Both PDF templates updated to read yacht details from the new entity. - `client-detail-header`, `client-picker`, `command-search`, `search-result-item`, `use-search` hook, `types/domain.ts`, `search.service` — drop the companyName badge / sub-label / typed field everywhere it was rendered or fetched. - `ai.ts` worker: drop the company / yacht context lines from the prompt (will be re-added later sourced from the new entities). - `validators/interests.ts`: remove the deprecated public-form flat yacht/company fields. The route already ignores them. - `factories.ts`: drop the `isProxy: false` default. Tests: 652/652 green; type-check clean. The `security-sensitive-data` tests use `companyName` / `isProxy` as arbitrary record keys for a generic util — left unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 13:57:54 +02:00
import { yachts } from '@/lib/db/schema/yachts';
import { companyMemberships } from '@/lib/db/schema/companies';
import { auditLogs } from '@/lib/db/schema/system';
import { ports } from '@/lib/db/schema/ports';
import { NotFoundError } from '@/lib/errors';
feat(record-export): migrate client/berth/interest summaries to react-pdf Phase 1 / commits 7-9 of 14 — bundled because all three record exports share the same conversion pattern and call sites. Templates: client-summary.tsx header + KV grid for client, contacts table with primary badge, yacht table, interests table with stage/category, recent activity table berth-spec.tsx header + status badge, overview KV grid, dimensions KV grid (with min markers), pricing & tenure KV grid, infrastructure KV grid, waiting list table with priority badges, maintenance log table interest-summary.tsx header + stage badge, status KV grid, client KV, optional yacht/berth sections, milestones KV grid, recent timeline table record-export.tsx (renamed .ts -> .tsx for JSX): - swap generatePdf(...) calls for renderPdf(<…Pdf … />) calls - inject port logo via resolvePortLogo() - shape data into typed template props (Drizzle returns are passed through deliberately so the template controls its own type surface) Drops two latent bugs the old templates carried: - client.nationality was read as a property but the schema field is nationalityIso — old PDFs always showed "—" for nationality - interest.notes was read but the interests table doesn't have a notes column (interest_berths does) — old PDFs always showed "No notes" Both fields are now sourced correctly (or omitted) in the new templates. Old pdfme files deleted (3 templates). API routes that import exportClientPdf/exportBerthPdf/exportInterestPdf unchanged. Tests: tests/unit/record-export-templates.test.tsx (4 tests): each template renders to valid PDF bytes with representative data, plus a minimal- input path for the berth spec. 1317/1317 vitest green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 20:59:05 +02:00
import { renderPdf } from '@/lib/pdf/render';
import { resolvePortLogo } from '@/lib/pdf/brand-kit/logo';
import { BerthSpecPdf } from '@/lib/pdf/templates/berth-spec';
import { ClientSummaryPdf } from '@/lib/pdf/templates/client-summary';
import { InterestSummaryPdf } from '@/lib/pdf/templates/interest-summary';
// ─── Export Client PDF ────────────────────────────────────────────────────────
export async function exportClientPdf(clientId: string, portId: string): Promise<Uint8Array> {
const client = await db.query.clients.findFirst({
where: eq(clients.id, clientId),
});
if (!client || client.portId !== portId) {
throw new NotFoundError('Client');
}
const [contactList, port] = await Promise.all([
db.query.clientContacts.findMany({
where: eq(clientContacts.clientId, clientId),
orderBy: (t, { desc }) => [desc(t.isPrimary), desc(t.createdAt)],
}),
db.query.ports.findFirst({ where: eq(ports.id, portId) }),
]);
// Fetch last 20 interests for this client in this port
const interestList = await db
.select()
.from(interests)
.where(and(eq(interests.clientId, clientId), eq(interests.portId, portId)))
.orderBy(desc(interests.updatedAt))
.limit(20);
// Fetch last 20 audit logs for this client
const activity = await db
.select()
.from(auditLogs)
.where(
and(
eq(auditLogs.portId, portId),
eq(auditLogs.entityType, 'client'),
eq(auditLogs.entityId, clientId),
),
)
.orderBy(desc(auditLogs.createdAt))
.limit(20);
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>
2026-05-05 02:41:52 +02:00
// 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));
const enrichedInterests = interestList.map((i) => {
const primary = primaryBerthMap.get(i.id);
return {
...i,
berthId: primary?.berthId ?? null,
berthMooringNumber: primary?.mooringNumber ?? null,
};
});
refactor(clients): drop deprecated yacht/company/proxy columns PR 13: now that all reads are migrated to the dedicated yacht / company / membership entities, drop the columns that mirrored them on `clients`: companyName, isProxy, proxyType, actualOwnerName, relationshipNotes, yachtName, yachtLength{Ft,M}, yachtWidth{Ft,M}, yachtDraft{Ft,M}, berthSizeDesired. Migration `0008_loud_ikaris.sql` issues the destructive ALTER TABLE DROP COLUMN statements. Run `pnpm db:push` (or the migration runner) to apply. Caller cleanup (zero behavioral change to remaining flows): - Drops the legacy `generateEoi` flow entirely (route, service function, pdfme template, validator schema). The dual-path generate-and-sign service from PR 11 has fully replaced it; the route was no longer wired to the UI. - `clients.service`: company-name search column / WHERE / audit value removed; search now ranks by full name only. - `interests.service`: `resolveLeadCategory` reads dimensions from `yachts` via `interest.yachtId` instead of the dropped `client.yachtLength{Ft,M}`. - `record-export`: client-summary now lists yachts via owner-side lookup (direct + active company memberships); interest-summary fetches yacht via `interest.yachtId`. Both PDF templates updated to read yacht details from the new entity. - `client-detail-header`, `client-picker`, `command-search`, `search-result-item`, `use-search` hook, `types/domain.ts`, `search.service` — drop the companyName badge / sub-label / typed field everywhere it was rendered or fetched. - `ai.ts` worker: drop the company / yacht context lines from the prompt (will be re-added later sourced from the new entities). - `validators/interests.ts`: remove the deprecated public-form flat yacht/company fields. The route already ignores them. - `factories.ts`: drop the `isProxy: false` default. Tests: 652/652 green; type-check clean. The `security-sensitive-data` tests use `companyName` / `isProxy` as arbitrary record keys for a generic util — left unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 13:57:54 +02:00
// Yachts owned by the client directly OR by a company they're an active
// member of. Active membership = no end date.
const memberCompanies = await db
.select({ companyId: companyMemberships.companyId })
.from(companyMemberships)
.where(and(eq(companyMemberships.clientId, clientId), isNull(companyMemberships.endDate)));
const companyIds = memberCompanies.map((m) => m.companyId);
const ownerConditions = [
and(eq(yachts.currentOwnerType, 'client'), eq(yachts.currentOwnerId, clientId))!,
];
if (companyIds.length > 0) {
ownerConditions.push(
and(eq(yachts.currentOwnerType, 'company'), inArray(yachts.currentOwnerId, companyIds))!,
);
}
const ownedYachts = await db
.select({
name: yachts.name,
lengthFt: yachts.lengthFt,
widthFt: yachts.widthFt,
draftFt: yachts.draftFt,
lengthM: yachts.lengthM,
widthM: yachts.widthM,
draftM: yachts.draftM,
})
.from(yachts)
.where(and(eq(yachts.portId, portId), isNull(yachts.archivedAt), or(...ownerConditions)));
feat(record-export): migrate client/berth/interest summaries to react-pdf Phase 1 / commits 7-9 of 14 — bundled because all three record exports share the same conversion pattern and call sites. Templates: client-summary.tsx header + KV grid for client, contacts table with primary badge, yacht table, interests table with stage/category, recent activity table berth-spec.tsx header + status badge, overview KV grid, dimensions KV grid (with min markers), pricing & tenure KV grid, infrastructure KV grid, waiting list table with priority badges, maintenance log table interest-summary.tsx header + stage badge, status KV grid, client KV, optional yacht/berth sections, milestones KV grid, recent timeline table record-export.tsx (renamed .ts -> .tsx for JSX): - swap generatePdf(...) calls for renderPdf(<…Pdf … />) calls - inject port logo via resolvePortLogo() - shape data into typed template props (Drizzle returns are passed through deliberately so the template controls its own type surface) Drops two latent bugs the old templates carried: - client.nationality was read as a property but the schema field is nationalityIso — old PDFs always showed "—" for nationality - interest.notes was read but the interests table doesn't have a notes column (interest_berths does) — old PDFs always showed "No notes" Both fields are now sourced correctly (or omitted) in the new templates. Old pdfme files deleted (3 templates). API routes that import exportClientPdf/exportBerthPdf/exportInterestPdf unchanged. Tests: tests/unit/record-export-templates.test.tsx (4 tests): each template renders to valid PDF bytes with representative data, plus a minimal- input path for the berth spec. 1317/1317 vitest green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 20:59:05 +02:00
const logo = await resolvePortLogo(portId);
return renderPdf(
<ClientSummaryPdf
fix(audit-wave-9): PDF correctness + brand asset hardening (pdf-auditor) Address the pdf-auditor findings that survived the 2026-05-12 PDF stack overhaul (pdfme → react-pdf). Items C-2/C-3 (tiptap-to-pdfme bugs) were resolved when that 571-LOC bridge was deleted; remaining items: - **M-7 wrong-port brand fallback** — replace `'Port Nimara'` defaults in PDF-rendering services. `reports.service` and `expense-export` throw when the port row is missing (the job is FK-keyed on a real port, so absence = broken state, must not stamp a competitor brand). `record-export` uses `'(port)'` as the visible placeholder. - **M-2 silent field drift in fill-eoi-form** — promote the always-silent catch in `setText` / `setCheckbox` to log a structured warning per missing field (mirroring the existing `setBerthRange` pattern). A re-cut template with drifted AcroForm field names now surfaces in ops logs instead of shipping with empty values. - **M-3 form not flattened** — `fillEoiFormFields` now flattens the AcroForm before save. Documenso pathway flattens server-side; this brings the in-app pathway to parity, so the signer can't edit pre-filled yacht dimensions / address / berth number after the fact. - **M-1 PDF metadata** — set Title / Author / Subject / Lang / Producer / Creator on the generated EOI PDF for downstream readers and a11y tooling. - **M-4 noisy berth-range warnings** — downgrade per-mooring warn to debug; emit a single summary warn per call when any passthrough occurred. Multi-berth EOIs with archived/legacy moorings no longer spam the log on every render. - **M-6 source PDF sha pinning** — pin `assets/eoi-template.pdf` sha256 via `EXPECTED_EOI_SHA256` (exported for tests); `loadEoiTemplatePdf` warns once per process when the bytes drift without an explicit hash bump. Documented the intentional-update workflow in `assets/README.md`. Tests updated in `tests/unit/pdf/fill-eoi-form.test.ts` to reflect flatten + metadata (form fields are gone after flatten; pdf-lib has no getLanguage so we assert the other setters round-trip). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 12:07:57 +02:00
portName={port?.name ?? '(port)'}
feat(record-export): migrate client/berth/interest summaries to react-pdf Phase 1 / commits 7-9 of 14 — bundled because all three record exports share the same conversion pattern and call sites. Templates: client-summary.tsx header + KV grid for client, contacts table with primary badge, yacht table, interests table with stage/category, recent activity table berth-spec.tsx header + status badge, overview KV grid, dimensions KV grid (with min markers), pricing & tenure KV grid, infrastructure KV grid, waiting list table with priority badges, maintenance log table interest-summary.tsx header + stage badge, status KV grid, client KV, optional yacht/berth sections, milestones KV grid, recent timeline table record-export.tsx (renamed .ts -> .tsx for JSX): - swap generatePdf(...) calls for renderPdf(<…Pdf … />) calls - inject port logo via resolvePortLogo() - shape data into typed template props (Drizzle returns are passed through deliberately so the template controls its own type surface) Drops two latent bugs the old templates carried: - client.nationality was read as a property but the schema field is nationalityIso — old PDFs always showed "—" for nationality - interest.notes was read but the interests table doesn't have a notes column (interest_berths does) — old PDFs always showed "No notes" Both fields are now sourced correctly (or omitted) in the new templates. Old pdfme files deleted (3 templates). API routes that import exportClientPdf/exportBerthPdf/exportInterestPdf unchanged. Tests: tests/unit/record-export-templates.test.tsx (4 tests): each template renders to valid PDF bytes with representative data, plus a minimal- input path for the berth spec. 1317/1317 vitest green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 20:59:05 +02:00
logoBuffer={logo.buffer}
client={{
fullName: client.fullName,
nationality: client.nationalityIso,
source: client.source,
createdAt: client.createdAt,
}}
contacts={contactList.map((c) => ({
channel: c.channel,
value: c.value,
label: c.label,
isPrimary: c.isPrimary,
}))}
yachts={ownedYachts}
interests={enrichedInterests.map((i) => ({
id: i.id,
pipelineStage: i.pipelineStage,
leadCategory: i.leadCategory,
berthMooringNumber: i.berthMooringNumber,
createdAt: i.createdAt,
}))}
activity={activity.map((a) => ({
action: a.action,
entityType: a.entityType,
fieldChanged: a.fieldChanged,
createdAt: a.createdAt,
}))}
/>,
refactor(clients): drop deprecated yacht/company/proxy columns PR 13: now that all reads are migrated to the dedicated yacht / company / membership entities, drop the columns that mirrored them on `clients`: companyName, isProxy, proxyType, actualOwnerName, relationshipNotes, yachtName, yachtLength{Ft,M}, yachtWidth{Ft,M}, yachtDraft{Ft,M}, berthSizeDesired. Migration `0008_loud_ikaris.sql` issues the destructive ALTER TABLE DROP COLUMN statements. Run `pnpm db:push` (or the migration runner) to apply. Caller cleanup (zero behavioral change to remaining flows): - Drops the legacy `generateEoi` flow entirely (route, service function, pdfme template, validator schema). The dual-path generate-and-sign service from PR 11 has fully replaced it; the route was no longer wired to the UI. - `clients.service`: company-name search column / WHERE / audit value removed; search now ranks by full name only. - `interests.service`: `resolveLeadCategory` reads dimensions from `yachts` via `interest.yachtId` instead of the dropped `client.yachtLength{Ft,M}`. - `record-export`: client-summary now lists yachts via owner-side lookup (direct + active company memberships); interest-summary fetches yacht via `interest.yachtId`. Both PDF templates updated to read yacht details from the new entity. - `client-detail-header`, `client-picker`, `command-search`, `search-result-item`, `use-search` hook, `types/domain.ts`, `search.service` — drop the companyName badge / sub-label / typed field everywhere it was rendered or fetched. - `ai.ts` worker: drop the company / yacht context lines from the prompt (will be re-added later sourced from the new entities). - `validators/interests.ts`: remove the deprecated public-form flat yacht/company fields. The route already ignores them. - `factories.ts`: drop the `isProxy: false` default. Tests: 652/652 green; type-check clean. The `security-sensitive-data` tests use `companyName` / `isProxy` as arbitrary record keys for a generic util — left unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 13:57:54 +02:00
);
}
// ─── Export Berth PDF ─────────────────────────────────────────────────────────
export async function exportBerthPdf(berthId: string, portId: string): Promise<Uint8Array> {
const berth = await db.query.berths.findFirst({
where: eq(berths.id, berthId),
});
if (!berth || berth.portId !== portId) {
throw new NotFoundError('Berth');
}
const port = await db.query.ports.findFirst({ where: eq(ports.id, portId) });
// Waiting list with client names
const waitingListRows = await db
.select({
id: berthWaitingList.id,
position: berthWaitingList.position,
priority: berthWaitingList.priority,
notes: berthWaitingList.notes,
clientId: berthWaitingList.clientId,
})
.from(berthWaitingList)
.where(eq(berthWaitingList.berthId, berthId))
.orderBy(berthWaitingList.position);
const clientIds = waitingListRows.map((w) => w.clientId);
let clientsMap: Record<string, string> = {};
if (clientIds.length > 0) {
const clientRows = await db
.select({ id: clients.id, fullName: clients.fullName })
.from(clients)
.where(inArray(clients.id, clientIds));
clientsMap = Object.fromEntries(clientRows.map((c) => [c.id, c.fullName]));
}
const enrichedWaitingList = waitingListRows.map((w) => ({
...w,
clientName: clientsMap[w.clientId] ?? 'Unknown',
}));
// Maintenance log (last 20)
const maintenance = await db
.select()
.from(berthMaintenanceLog)
.where(eq(berthMaintenanceLog.berthId, berthId))
.orderBy(desc(berthMaintenanceLog.performedDate))
.limit(20);
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>
2026-05-05 02:41:52 +02:00
// 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)
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>
2026-05-05 02:41:52 +02:00
.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);
feat(record-export): migrate client/berth/interest summaries to react-pdf Phase 1 / commits 7-9 of 14 — bundled because all three record exports share the same conversion pattern and call sites. Templates: client-summary.tsx header + KV grid for client, contacts table with primary badge, yacht table, interests table with stage/category, recent activity table berth-spec.tsx header + status badge, overview KV grid, dimensions KV grid (with min markers), pricing & tenure KV grid, infrastructure KV grid, waiting list table with priority badges, maintenance log table interest-summary.tsx header + stage badge, status KV grid, client KV, optional yacht/berth sections, milestones KV grid, recent timeline table record-export.tsx (renamed .ts -> .tsx for JSX): - swap generatePdf(...) calls for renderPdf(<…Pdf … />) calls - inject port logo via resolvePortLogo() - shape data into typed template props (Drizzle returns are passed through deliberately so the template controls its own type surface) Drops two latent bugs the old templates carried: - client.nationality was read as a property but the schema field is nationalityIso — old PDFs always showed "—" for nationality - interest.notes was read but the interests table doesn't have a notes column (interest_berths does) — old PDFs always showed "No notes" Both fields are now sourced correctly (or omitted) in the new templates. Old pdfme files deleted (3 templates). API routes that import exportClientPdf/exportBerthPdf/exportInterestPdf unchanged. Tests: tests/unit/record-export-templates.test.tsx (4 tests): each template renders to valid PDF bytes with representative data, plus a minimal- input path for the berth spec. 1317/1317 vitest green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 20:59:05 +02:00
// linkedInterests not currently surfaced in the PDF (the old template
// also omitted them); kept the query to preserve the existing data
// contract until a future revision wants to surface them.
void linkedInterests;
const logo = await resolvePortLogo(portId);
return renderPdf(
<BerthSpecPdf
fix(audit-wave-9): PDF correctness + brand asset hardening (pdf-auditor) Address the pdf-auditor findings that survived the 2026-05-12 PDF stack overhaul (pdfme → react-pdf). Items C-2/C-3 (tiptap-to-pdfme bugs) were resolved when that 571-LOC bridge was deleted; remaining items: - **M-7 wrong-port brand fallback** — replace `'Port Nimara'` defaults in PDF-rendering services. `reports.service` and `expense-export` throw when the port row is missing (the job is FK-keyed on a real port, so absence = broken state, must not stamp a competitor brand). `record-export` uses `'(port)'` as the visible placeholder. - **M-2 silent field drift in fill-eoi-form** — promote the always-silent catch in `setText` / `setCheckbox` to log a structured warning per missing field (mirroring the existing `setBerthRange` pattern). A re-cut template with drifted AcroForm field names now surfaces in ops logs instead of shipping with empty values. - **M-3 form not flattened** — `fillEoiFormFields` now flattens the AcroForm before save. Documenso pathway flattens server-side; this brings the in-app pathway to parity, so the signer can't edit pre-filled yacht dimensions / address / berth number after the fact. - **M-1 PDF metadata** — set Title / Author / Subject / Lang / Producer / Creator on the generated EOI PDF for downstream readers and a11y tooling. - **M-4 noisy berth-range warnings** — downgrade per-mooring warn to debug; emit a single summary warn per call when any passthrough occurred. Multi-berth EOIs with archived/legacy moorings no longer spam the log on every render. - **M-6 source PDF sha pinning** — pin `assets/eoi-template.pdf` sha256 via `EXPECTED_EOI_SHA256` (exported for tests); `loadEoiTemplatePdf` warns once per process when the bytes drift without an explicit hash bump. Documented the intentional-update workflow in `assets/README.md`. Tests updated in `tests/unit/pdf/fill-eoi-form.test.ts` to reflect flatten + metadata (form fields are gone after flatten; pdf-lib has no getLanguage so we assert the other setters round-trip). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 12:07:57 +02:00
portName={port?.name ?? '(port)'}
feat(record-export): migrate client/berth/interest summaries to react-pdf Phase 1 / commits 7-9 of 14 — bundled because all three record exports share the same conversion pattern and call sites. Templates: client-summary.tsx header + KV grid for client, contacts table with primary badge, yacht table, interests table with stage/category, recent activity table berth-spec.tsx header + status badge, overview KV grid, dimensions KV grid (with min markers), pricing & tenure KV grid, infrastructure KV grid, waiting list table with priority badges, maintenance log table interest-summary.tsx header + stage badge, status KV grid, client KV, optional yacht/berth sections, milestones KV grid, recent timeline table record-export.tsx (renamed .ts -> .tsx for JSX): - swap generatePdf(...) calls for renderPdf(<…Pdf … />) calls - inject port logo via resolvePortLogo() - shape data into typed template props (Drizzle returns are passed through deliberately so the template controls its own type surface) Drops two latent bugs the old templates carried: - client.nationality was read as a property but the schema field is nationalityIso — old PDFs always showed "—" for nationality - interest.notes was read but the interests table doesn't have a notes column (interest_berths does) — old PDFs always showed "No notes" Both fields are now sourced correctly (or omitted) in the new templates. Old pdfme files deleted (3 templates). API routes that import exportClientPdf/exportBerthPdf/exportInterestPdf unchanged. Tests: tests/unit/record-export-templates.test.tsx (4 tests): each template renders to valid PDF bytes with representative data, plus a minimal- input path for the berth spec. 1317/1317 vitest green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 20:59:05 +02:00
logoBuffer={logo.buffer}
berth={{
mooringNumber: berth.mooringNumber,
area: berth.area,
status: berth.status,
nominalBoatSize: berth.nominalBoatSize,
bowFacing: berth.bowFacing,
lengthFt: berth.lengthFt,
lengthM: berth.lengthM,
widthFt: berth.widthFt,
widthM: berth.widthM,
widthIsMinimum: berth.widthIsMinimum,
draftFt: berth.draftFt,
draftM: berth.draftM,
waterDepth: berth.waterDepth,
waterDepthM: berth.waterDepthM,
waterDepthIsMinimum: berth.waterDepthIsMinimum,
price: berth.price,
priceCurrency: berth.priceCurrency,
tenureType: berth.tenureType,
tenureYears: berth.tenureYears,
tenureStartDate: berth.tenureStartDate,
tenureEndDate: berth.tenureEndDate,
mooringType: berth.mooringType,
powerCapacity: berth.powerCapacity,
voltage: berth.voltage,
cleatType: berth.cleatType,
cleatCapacity: berth.cleatCapacity,
bollardType: berth.bollardType,
bollardCapacity: berth.bollardCapacity,
sidePontoon: berth.sidePontoon,
access: berth.access,
}}
waitingList={enrichedWaitingList.map((w) => ({
position: w.position,
priority: w.priority,
clientName: w.clientName,
notes: w.notes,
}))}
maintenance={maintenance.map((m) => ({
performedDate: m.performedDate,
category: m.category,
description: m.description,
cost: m.cost,
costCurrency: m.costCurrency,
}))}
/>,
refactor(clients): drop deprecated yacht/company/proxy columns PR 13: now that all reads are migrated to the dedicated yacht / company / membership entities, drop the columns that mirrored them on `clients`: companyName, isProxy, proxyType, actualOwnerName, relationshipNotes, yachtName, yachtLength{Ft,M}, yachtWidth{Ft,M}, yachtDraft{Ft,M}, berthSizeDesired. Migration `0008_loud_ikaris.sql` issues the destructive ALTER TABLE DROP COLUMN statements. Run `pnpm db:push` (or the migration runner) to apply. Caller cleanup (zero behavioral change to remaining flows): - Drops the legacy `generateEoi` flow entirely (route, service function, pdfme template, validator schema). The dual-path generate-and-sign service from PR 11 has fully replaced it; the route was no longer wired to the UI. - `clients.service`: company-name search column / WHERE / audit value removed; search now ranks by full name only. - `interests.service`: `resolveLeadCategory` reads dimensions from `yachts` via `interest.yachtId` instead of the dropped `client.yachtLength{Ft,M}`. - `record-export`: client-summary now lists yachts via owner-side lookup (direct + active company memberships); interest-summary fetches yacht via `interest.yachtId`. Both PDF templates updated to read yacht details from the new entity. - `client-detail-header`, `client-picker`, `command-search`, `search-result-item`, `use-search` hook, `types/domain.ts`, `search.service` — drop the companyName badge / sub-label / typed field everywhere it was rendered or fetched. - `ai.ts` worker: drop the company / yacht context lines from the prompt (will be re-added later sourced from the new entities). - `validators/interests.ts`: remove the deprecated public-form flat yacht/company fields. The route already ignores them. - `factories.ts`: drop the `isProxy: false` default. Tests: 652/652 green; type-check clean. The `security-sensitive-data` tests use `companyName` / `isProxy` as arbitrary record keys for a generic util — left unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 13:57:54 +02:00
);
}
// ─── Export Interest PDF ──────────────────────────────────────────────────────
export async function exportInterestPdf(interestId: string, portId: string): Promise<Uint8Array> {
const interest = await db.query.interests.findFirst({
where: eq(interests.id, interestId),
});
if (!interest || interest.portId !== portId) {
throw new NotFoundError('Interest');
}
const [client, port] = await Promise.all([
db.query.clients.findFirst({ where: eq(clients.id, interest.clientId) }),
db.query.ports.findFirst({ where: eq(ports.id, portId) }),
]);
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>
2026-05-05 02:41:52 +02:00
// Resolve primary berth via the junction (plan §3.4).
const primaryBerth = await getPrimaryBerth(interest.id);
let berth = null;
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>
2026-05-05 02:41:52 +02:00
if (primaryBerth?.berthId) {
berth = await db.query.berths.findFirst({ where: eq(berths.id, primaryBerth.berthId) });
}
refactor(clients): drop deprecated yacht/company/proxy columns PR 13: now that all reads are migrated to the dedicated yacht / company / membership entities, drop the columns that mirrored them on `clients`: companyName, isProxy, proxyType, actualOwnerName, relationshipNotes, yachtName, yachtLength{Ft,M}, yachtWidth{Ft,M}, yachtDraft{Ft,M}, berthSizeDesired. Migration `0008_loud_ikaris.sql` issues the destructive ALTER TABLE DROP COLUMN statements. Run `pnpm db:push` (or the migration runner) to apply. Caller cleanup (zero behavioral change to remaining flows): - Drops the legacy `generateEoi` flow entirely (route, service function, pdfme template, validator schema). The dual-path generate-and-sign service from PR 11 has fully replaced it; the route was no longer wired to the UI. - `clients.service`: company-name search column / WHERE / audit value removed; search now ranks by full name only. - `interests.service`: `resolveLeadCategory` reads dimensions from `yachts` via `interest.yachtId` instead of the dropped `client.yachtLength{Ft,M}`. - `record-export`: client-summary now lists yachts via owner-side lookup (direct + active company memberships); interest-summary fetches yacht via `interest.yachtId`. Both PDF templates updated to read yacht details from the new entity. - `client-detail-header`, `client-picker`, `command-search`, `search-result-item`, `use-search` hook, `types/domain.ts`, `search.service` — drop the companyName badge / sub-label / typed field everywhere it was rendered or fetched. - `ai.ts` worker: drop the company / yacht context lines from the prompt (will be re-added later sourced from the new entities). - `validators/interests.ts`: remove the deprecated public-form flat yacht/company fields. The route already ignores them. - `factories.ts`: drop the `isProxy: false` default. Tests: 652/652 green; type-check clean. The `security-sensitive-data` tests use `companyName` / `isProxy` as arbitrary record keys for a generic util — left unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 13:57:54 +02:00
let yacht = null;
if (interest.yachtId) {
yacht = await db.query.yachts.findFirst({ where: eq(yachts.id, interest.yachtId) });
}
// Audit timeline (last 20 events for this interest)
const timeline = await db
.select()
.from(auditLogs)
.where(
and(
eq(auditLogs.portId, portId),
eq(auditLogs.entityType, 'interest'),
eq(auditLogs.entityId, interestId),
),
)
.orderBy(desc(auditLogs.createdAt))
.limit(20);
feat(record-export): migrate client/berth/interest summaries to react-pdf Phase 1 / commits 7-9 of 14 — bundled because all three record exports share the same conversion pattern and call sites. Templates: client-summary.tsx header + KV grid for client, contacts table with primary badge, yacht table, interests table with stage/category, recent activity table berth-spec.tsx header + status badge, overview KV grid, dimensions KV grid (with min markers), pricing & tenure KV grid, infrastructure KV grid, waiting list table with priority badges, maintenance log table interest-summary.tsx header + stage badge, status KV grid, client KV, optional yacht/berth sections, milestones KV grid, recent timeline table record-export.tsx (renamed .ts -> .tsx for JSX): - swap generatePdf(...) calls for renderPdf(<…Pdf … />) calls - inject port logo via resolvePortLogo() - shape data into typed template props (Drizzle returns are passed through deliberately so the template controls its own type surface) Drops two latent bugs the old templates carried: - client.nationality was read as a property but the schema field is nationalityIso — old PDFs always showed "—" for nationality - interest.notes was read but the interests table doesn't have a notes column (interest_berths does) — old PDFs always showed "No notes" Both fields are now sourced correctly (or omitted) in the new templates. Old pdfme files deleted (3 templates). API routes that import exportClientPdf/exportBerthPdf/exportInterestPdf unchanged. Tests: tests/unit/record-export-templates.test.tsx (4 tests): each template renders to valid PDF bytes with representative data, plus a minimal- input path for the berth spec. 1317/1317 vitest green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 20:59:05 +02:00
const logo = await resolvePortLogo(portId);
return renderPdf(
<InterestSummaryPdf
fix(audit-wave-9): PDF correctness + brand asset hardening (pdf-auditor) Address the pdf-auditor findings that survived the 2026-05-12 PDF stack overhaul (pdfme → react-pdf). Items C-2/C-3 (tiptap-to-pdfme bugs) were resolved when that 571-LOC bridge was deleted; remaining items: - **M-7 wrong-port brand fallback** — replace `'Port Nimara'` defaults in PDF-rendering services. `reports.service` and `expense-export` throw when the port row is missing (the job is FK-keyed on a real port, so absence = broken state, must not stamp a competitor brand). `record-export` uses `'(port)'` as the visible placeholder. - **M-2 silent field drift in fill-eoi-form** — promote the always-silent catch in `setText` / `setCheckbox` to log a structured warning per missing field (mirroring the existing `setBerthRange` pattern). A re-cut template with drifted AcroForm field names now surfaces in ops logs instead of shipping with empty values. - **M-3 form not flattened** — `fillEoiFormFields` now flattens the AcroForm before save. Documenso pathway flattens server-side; this brings the in-app pathway to parity, so the signer can't edit pre-filled yacht dimensions / address / berth number after the fact. - **M-1 PDF metadata** — set Title / Author / Subject / Lang / Producer / Creator on the generated EOI PDF for downstream readers and a11y tooling. - **M-4 noisy berth-range warnings** — downgrade per-mooring warn to debug; emit a single summary warn per call when any passthrough occurred. Multi-berth EOIs with archived/legacy moorings no longer spam the log on every render. - **M-6 source PDF sha pinning** — pin `assets/eoi-template.pdf` sha256 via `EXPECTED_EOI_SHA256` (exported for tests); `loadEoiTemplatePdf` warns once per process when the bytes drift without an explicit hash bump. Documented the intentional-update workflow in `assets/README.md`. Tests updated in `tests/unit/pdf/fill-eoi-form.test.ts` to reflect flatten + metadata (form fields are gone after flatten; pdf-lib has no getLanguage so we assert the other setters round-trip). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 12:07:57 +02:00
portName={port?.name ?? '(port)'}
feat(record-export): migrate client/berth/interest summaries to react-pdf Phase 1 / commits 7-9 of 14 — bundled because all three record exports share the same conversion pattern and call sites. Templates: client-summary.tsx header + KV grid for client, contacts table with primary badge, yacht table, interests table with stage/category, recent activity table berth-spec.tsx header + status badge, overview KV grid, dimensions KV grid (with min markers), pricing & tenure KV grid, infrastructure KV grid, waiting list table with priority badges, maintenance log table interest-summary.tsx header + stage badge, status KV grid, client KV, optional yacht/berth sections, milestones KV grid, recent timeline table record-export.tsx (renamed .ts -> .tsx for JSX): - swap generatePdf(...) calls for renderPdf(<…Pdf … />) calls - inject port logo via resolvePortLogo() - shape data into typed template props (Drizzle returns are passed through deliberately so the template controls its own type surface) Drops two latent bugs the old templates carried: - client.nationality was read as a property but the schema field is nationalityIso — old PDFs always showed "—" for nationality - interest.notes was read but the interests table doesn't have a notes column (interest_berths does) — old PDFs always showed "No notes" Both fields are now sourced correctly (or omitted) in the new templates. Old pdfme files deleted (3 templates). API routes that import exportClientPdf/exportBerthPdf/exportInterestPdf unchanged. Tests: tests/unit/record-export-templates.test.tsx (4 tests): each template renders to valid PDF bytes with representative data, plus a minimal- input path for the berth spec. 1317/1317 vitest green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 20:59:05 +02:00
logoBuffer={logo.buffer}
interest={{
id: interest.id,
pipelineStage: interest.pipelineStage,
leadCategory: interest.leadCategory,
source: interest.source,
eoiStatus: interest.eoiStatus,
contractStatus: interest.contractStatus,
depositStatus: interest.depositStatus,
dateFirstContact: interest.dateFirstContact,
dateLastContact: interest.dateLastContact,
dateEoiSent: interest.dateEoiSent,
dateEoiSigned: interest.dateEoiSigned,
dateContractSent: interest.dateContractSent,
dateContractSigned: interest.dateContractSigned,
dateDepositReceived: interest.dateDepositReceived,
}}
client={client ? { fullName: client.fullName } : { fullName: null }}
yacht={
yacht
? {
name: yacht.name,
lengthFt: yacht.lengthFt,
lengthM: yacht.lengthM,
widthFt: yacht.widthFt,
draftFt: yacht.draftFt,
}
: null
}
berth={
berth
? {
mooringNumber: berth.mooringNumber,
area: berth.area,
lengthFt: berth.lengthFt,
price: berth.price,
priceCurrency: berth.priceCurrency,
status: berth.status,
}
: null
}
timeline={timeline.map((t) => ({
createdAt: t.createdAt,
action: t.action,
entityType: t.entityType,
fieldChanged: t.fieldChanged,
}))}
/>,
refactor(clients): drop deprecated yacht/company/proxy columns PR 13: now that all reads are migrated to the dedicated yacht / company / membership entities, drop the columns that mirrored them on `clients`: companyName, isProxy, proxyType, actualOwnerName, relationshipNotes, yachtName, yachtLength{Ft,M}, yachtWidth{Ft,M}, yachtDraft{Ft,M}, berthSizeDesired. Migration `0008_loud_ikaris.sql` issues the destructive ALTER TABLE DROP COLUMN statements. Run `pnpm db:push` (or the migration runner) to apply. Caller cleanup (zero behavioral change to remaining flows): - Drops the legacy `generateEoi` flow entirely (route, service function, pdfme template, validator schema). The dual-path generate-and-sign service from PR 11 has fully replaced it; the route was no longer wired to the UI. - `clients.service`: company-name search column / WHERE / audit value removed; search now ranks by full name only. - `interests.service`: `resolveLeadCategory` reads dimensions from `yachts` via `interest.yachtId` instead of the dropped `client.yachtLength{Ft,M}`. - `record-export`: client-summary now lists yachts via owner-side lookup (direct + active company memberships); interest-summary fetches yacht via `interest.yachtId`. Both PDF templates updated to read yacht details from the new entity. - `client-detail-header`, `client-picker`, `command-search`, `search-result-item`, `use-search` hook, `types/domain.ts`, `search.service` — drop the companyName badge / sub-label / typed field everywhere it was rendered or fetched. - `ai.ts` worker: drop the company / yacht context lines from the prompt (will be re-added later sourced from the new entities). - `validators/interests.ts`: remove the deprecated public-form flat yacht/company fields. The route already ignores them. - `factories.ts`: drop the `isProxy: false` default. Tests: 652/652 green; type-check clean. The `security-sensitive-data` tests use `companyName` / `isProxy` as arbitrary record keys for a generic util — left unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 13:57:54 +02:00
);
}