Files
pn-new-crm/src/lib/services/eoi-context.ts

315 lines
11 KiB
TypeScript
Raw Normal View History

import { and, desc, eq } from 'drizzle-orm';
import { db } from '@/lib/db';
import { berths } from '@/lib/db/schema/berths';
import { clients, clientAddresses, clientContacts } from '@/lib/db/schema/clients';
import { companies, companyAddresses } from '@/lib/db/schema/companies';
feat(eoi): multi-berth EOI generation + berth-range formatter Plan §4.6 + §1: a render function that compresses every berth marked is_in_eoi_bundle=true on an interest into a compact range string ("A1-A3, B5-B7"), wired into both EOI generation paths (the Documenso template-generate call and the in-app pdf-lib AcroForm fill). - src/lib/templates/berth-range.ts: pure formatBerthRange() with the full edge-case set from §4.6 - empty, single, run, gap, multiple prefixes, sort/dedup, multi-letter prefixes, non-canonical passthrough, long ranges. Sorts by (prefix, number); dedupes; passes non-canonical inputs through with a logger warning. - src/lib/templates/merge-fields.ts: new {{eoi.berthRange}} token added to VALID_MERGE_TOKENS allow-list under a fresh `eoi` scope so unknown-token validation at template creation time still rejects typos. - src/lib/services/eoi-context.ts: EoiContext gains eoiBerthRange. Resolved by joining interest_berths (is_in_eoi_bundle=true) → berths and feeding the mooring numbers through formatBerthRange. - src/lib/services/documenso-payload.ts: formValues now includes "Berth Range" alongside the legacy "Berth Number". Multi-berth EOIs surface here; single-berth EOIs duplicate the primary. - src/lib/pdf/fill-eoi-form.ts: in-app AcroForm fill mirrors the Documenso payload by populating "Berth Range". Falls back silently when older PDFs don't have the field (setText is no-op-on-missing). 15 unit tests on the formatter; existing EoiContext + Documenso payload tests updated to assert the new field. 1022 -> 1037 passing. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 03:03:29 +02:00
import { interests, interestBerths } from '@/lib/db/schema/interests';
import { ports } from '@/lib/db/schema/ports';
import { yachts } from '@/lib/db/schema/yachts';
import { getCountryName } from '@/lib/i18n/countries';
import { NotFoundError, ValidationError } from '@/lib/errors';
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 } from '@/lib/services/interest-berths.service';
feat(eoi): multi-berth EOI generation + berth-range formatter Plan §4.6 + §1: a render function that compresses every berth marked is_in_eoi_bundle=true on an interest into a compact range string ("A1-A3, B5-B7"), wired into both EOI generation paths (the Documenso template-generate call and the in-app pdf-lib AcroForm fill). - src/lib/templates/berth-range.ts: pure formatBerthRange() with the full edge-case set from §4.6 - empty, single, run, gap, multiple prefixes, sort/dedup, multi-letter prefixes, non-canonical passthrough, long ranges. Sorts by (prefix, number); dedupes; passes non-canonical inputs through with a logger warning. - src/lib/templates/merge-fields.ts: new {{eoi.berthRange}} token added to VALID_MERGE_TOKENS allow-list under a fresh `eoi` scope so unknown-token validation at template creation time still rejects typos. - src/lib/services/eoi-context.ts: EoiContext gains eoiBerthRange. Resolved by joining interest_berths (is_in_eoi_bundle=true) → berths and feeding the mooring numbers through formatBerthRange. - src/lib/services/documenso-payload.ts: formValues now includes "Berth Range" alongside the legacy "Berth Number". Multi-berth EOIs surface here; single-berth EOIs duplicate the primary. - src/lib/pdf/fill-eoi-form.ts: in-app AcroForm fill mirrors the Documenso payload by populating "Berth Range". Falls back silently when older PDFs don't have the field (setText is no-op-on-missing). 15 unit tests on the formatter; existing EoiContext + Documenso payload tests updated to assert the new field. 1022 -> 1037 passing. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 03:03:29 +02:00
import { formatBerthRange } from '@/lib/templates/berth-range';
// ─── Types ────────────────────────────────────────────────────────────────────
export type EoiContext = {
client: {
fullName: string;
nationality: string | null;
primaryEmail: string | null;
primaryPhone: string | null;
address: { street: string; city: string; country: string } | null;
};
feat(eoi): align prerequisites with EOI document structure Match the gate to the actual EOI's structure (Section 2 vs Section 3) so the rep can generate the document the moment they have what they need — and not before. Required (Section 2 — top paragraph): - Client name - Client primary email - Client primary address Optional (Section 3 — left blank when absent): - Linked yacht (name, dimensions) - Linked berth (mooring number) Previously the dialog blocked generation unless yacht AND berth were both linked, which was overzealous — early-stage EOIs are routinely sent before a specific berth is pinned down. - eoi-context.ts: yacht and berth are now nullable in the returned context. The hard ValidationError is now driven by the EOI's Section 2 fields (name/email/address) rather than yacht/berth presence. The owner block falls back to the interest's client when no yacht is linked, so signing parties remain resolvable. - documenso-payload.ts + fill-eoi-form.ts: Section 3 form values render as empty strings when yacht or berth are absent, so the rendered PDF leaves those template inputs blank. - document-templates.ts: yacht.* and berth.* tokens fall back to empty strings; the legacy-fallback catch handler also recognises the new "missing required client details" error. - interests.service.ts: getInterestById now also returns `clientPrimaryEmail` and `clientHasAddress` so the Documents tab can compute the EOI prerequisites checklist client-side without an extra fetch. - eoi-generate-dialog.tsx: prereqs split into two groups visually — Required (with red ✗ when missing) and Optional (with grey – when absent). The Generate button only requires the Required block to pass. A small amber banner surfaces when Required is incomplete so the rep knows where to add the missing data. Tests: 835/835 pass. Replaces the obsolete "throws on missing yacht/ berth" tests with parity coverage for the new behaviour ("builds a valid context when yacht/berth missing", "throws when client email/ address missing"). Adds a payload test for the empty-Section-3 case. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 03:11:14 +02:00
/** Optional. The EOI's Section 3 yacht block is left blank when null. */
yacht: {
name: string;
lengthFt: string | null;
widthFt: string | null;
draftFt: string | null;
lengthM: string | null;
widthM: string | null;
draftM: string | null;
hullNumber: string | null;
flag: string | null;
yearBuilt: number | null;
feat(eoi): align prerequisites with EOI document structure Match the gate to the actual EOI's structure (Section 2 vs Section 3) so the rep can generate the document the moment they have what they need — and not before. Required (Section 2 — top paragraph): - Client name - Client primary email - Client primary address Optional (Section 3 — left blank when absent): - Linked yacht (name, dimensions) - Linked berth (mooring number) Previously the dialog blocked generation unless yacht AND berth were both linked, which was overzealous — early-stage EOIs are routinely sent before a specific berth is pinned down. - eoi-context.ts: yacht and berth are now nullable in the returned context. The hard ValidationError is now driven by the EOI's Section 2 fields (name/email/address) rather than yacht/berth presence. The owner block falls back to the interest's client when no yacht is linked, so signing parties remain resolvable. - documenso-payload.ts + fill-eoi-form.ts: Section 3 form values render as empty strings when yacht or berth are absent, so the rendered PDF leaves those template inputs blank. - document-templates.ts: yacht.* and berth.* tokens fall back to empty strings; the legacy-fallback catch handler also recognises the new "missing required client details" error. - interests.service.ts: getInterestById now also returns `clientPrimaryEmail` and `clientHasAddress` so the Documents tab can compute the EOI prerequisites checklist client-side without an extra fetch. - eoi-generate-dialog.tsx: prereqs split into two groups visually — Required (with red ✗ when missing) and Optional (with grey – when absent). The Generate button only requires the Required block to pass. A small amber banner surfaces when Required is incomplete so the rep knows where to add the missing data. Tests: 835/835 pass. Replaces the obsolete "throws on missing yacht/ berth" tests with parity coverage for the new behaviour ("builds a valid context when yacht/berth missing", "throws when client email/ address missing"). Adds a payload test for the empty-Section-3 case. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 03:11:14 +02:00
} | null;
company: {
name: string;
legalName: string | null;
taxId: string | null;
billingAddress: string | null;
} | null;
feat(eoi): align prerequisites with EOI document structure Match the gate to the actual EOI's structure (Section 2 vs Section 3) so the rep can generate the document the moment they have what they need — and not before. Required (Section 2 — top paragraph): - Client name - Client primary email - Client primary address Optional (Section 3 — left blank when absent): - Linked yacht (name, dimensions) - Linked berth (mooring number) Previously the dialog blocked generation unless yacht AND berth were both linked, which was overzealous — early-stage EOIs are routinely sent before a specific berth is pinned down. - eoi-context.ts: yacht and berth are now nullable in the returned context. The hard ValidationError is now driven by the EOI's Section 2 fields (name/email/address) rather than yacht/berth presence. The owner block falls back to the interest's client when no yacht is linked, so signing parties remain resolvable. - documenso-payload.ts + fill-eoi-form.ts: Section 3 form values render as empty strings when yacht or berth are absent, so the rendered PDF leaves those template inputs blank. - document-templates.ts: yacht.* and berth.* tokens fall back to empty strings; the legacy-fallback catch handler also recognises the new "missing required client details" error. - interests.service.ts: getInterestById now also returns `clientPrimaryEmail` and `clientHasAddress` so the Documents tab can compute the EOI prerequisites checklist client-side without an extra fetch. - eoi-generate-dialog.tsx: prereqs split into two groups visually — Required (with red ✗ when missing) and Optional (with grey – when absent). The Generate button only requires the Required block to pass. A small amber banner surfaces when Required is incomplete so the rep knows where to add the missing data. Tests: 835/835 pass. Replaces the obsolete "throws on missing yacht/ berth" tests with parity coverage for the new behaviour ("builds a valid context when yacht/berth missing", "throws when client email/ address missing"). Adds a payload test for the empty-Section-3 case. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 03:11:14 +02:00
/** Inferred from the yacht's polymorphic owner. Falls back to the interest's
* client when no yacht is linked (so the EOI's signing party is still
* resolvable). */
owner: {
type: 'client' | 'company';
name: string;
legalName?: string;
};
feat(eoi): align prerequisites with EOI document structure Match the gate to the actual EOI's structure (Section 2 vs Section 3) so the rep can generate the document the moment they have what they need — and not before. Required (Section 2 — top paragraph): - Client name - Client primary email - Client primary address Optional (Section 3 — left blank when absent): - Linked yacht (name, dimensions) - Linked berth (mooring number) Previously the dialog blocked generation unless yacht AND berth were both linked, which was overzealous — early-stage EOIs are routinely sent before a specific berth is pinned down. - eoi-context.ts: yacht and berth are now nullable in the returned context. The hard ValidationError is now driven by the EOI's Section 2 fields (name/email/address) rather than yacht/berth presence. The owner block falls back to the interest's client when no yacht is linked, so signing parties remain resolvable. - documenso-payload.ts + fill-eoi-form.ts: Section 3 form values render as empty strings when yacht or berth are absent, so the rendered PDF leaves those template inputs blank. - document-templates.ts: yacht.* and berth.* tokens fall back to empty strings; the legacy-fallback catch handler also recognises the new "missing required client details" error. - interests.service.ts: getInterestById now also returns `clientPrimaryEmail` and `clientHasAddress` so the Documents tab can compute the EOI prerequisites checklist client-side without an extra fetch. - eoi-generate-dialog.tsx: prereqs split into two groups visually — Required (with red ✗ when missing) and Optional (with grey – when absent). The Generate button only requires the Required block to pass. A small amber banner surfaces when Required is incomplete so the rep knows where to add the missing data. Tests: 835/835 pass. Replaces the obsolete "throws on missing yacht/ berth" tests with parity coverage for the new behaviour ("builds a valid context when yacht/berth missing", "throws when client email/ address missing"). Adds a payload test for the empty-Section-3 case. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 03:11:14 +02:00
/** Optional. The EOI's Section 3 berth-number is left blank when null. */
berth: {
mooringNumber: string;
area: string | null;
lengthFt: string | null;
price: string | null;
priceCurrency: string;
tenureType: string;
feat(eoi): align prerequisites with EOI document structure Match the gate to the actual EOI's structure (Section 2 vs Section 3) so the rep can generate the document the moment they have what they need — and not before. Required (Section 2 — top paragraph): - Client name - Client primary email - Client primary address Optional (Section 3 — left blank when absent): - Linked yacht (name, dimensions) - Linked berth (mooring number) Previously the dialog blocked generation unless yacht AND berth were both linked, which was overzealous — early-stage EOIs are routinely sent before a specific berth is pinned down. - eoi-context.ts: yacht and berth are now nullable in the returned context. The hard ValidationError is now driven by the EOI's Section 2 fields (name/email/address) rather than yacht/berth presence. The owner block falls back to the interest's client when no yacht is linked, so signing parties remain resolvable. - documenso-payload.ts + fill-eoi-form.ts: Section 3 form values render as empty strings when yacht or berth are absent, so the rendered PDF leaves those template inputs blank. - document-templates.ts: yacht.* and berth.* tokens fall back to empty strings; the legacy-fallback catch handler also recognises the new "missing required client details" error. - interests.service.ts: getInterestById now also returns `clientPrimaryEmail` and `clientHasAddress` so the Documents tab can compute the EOI prerequisites checklist client-side without an extra fetch. - eoi-generate-dialog.tsx: prereqs split into two groups visually — Required (with red ✗ when missing) and Optional (with grey – when absent). The Generate button only requires the Required block to pass. A small amber banner surfaces when Required is incomplete so the rep knows where to add the missing data. Tests: 835/835 pass. Replaces the obsolete "throws on missing yacht/ berth" tests with parity coverage for the new behaviour ("builds a valid context when yacht/berth missing", "throws when client email/ address missing"). Adds a payload test for the empty-Section-3 case. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 03:11:14 +02:00
} | null;
feat(eoi): multi-berth EOI generation + berth-range formatter Plan §4.6 + §1: a render function that compresses every berth marked is_in_eoi_bundle=true on an interest into a compact range string ("A1-A3, B5-B7"), wired into both EOI generation paths (the Documenso template-generate call and the in-app pdf-lib AcroForm fill). - src/lib/templates/berth-range.ts: pure formatBerthRange() with the full edge-case set from §4.6 - empty, single, run, gap, multiple prefixes, sort/dedup, multi-letter prefixes, non-canonical passthrough, long ranges. Sorts by (prefix, number); dedupes; passes non-canonical inputs through with a logger warning. - src/lib/templates/merge-fields.ts: new {{eoi.berthRange}} token added to VALID_MERGE_TOKENS allow-list under a fresh `eoi` scope so unknown-token validation at template creation time still rejects typos. - src/lib/services/eoi-context.ts: EoiContext gains eoiBerthRange. Resolved by joining interest_berths (is_in_eoi_bundle=true) → berths and feeding the mooring numbers through formatBerthRange. - src/lib/services/documenso-payload.ts: formValues now includes "Berth Range" alongside the legacy "Berth Number". Multi-berth EOIs surface here; single-berth EOIs duplicate the primary. - src/lib/pdf/fill-eoi-form.ts: in-app AcroForm fill mirrors the Documenso payload by populating "Berth Range". Falls back silently when older PDFs don't have the field (setText is no-op-on-missing). 15 unit tests on the formatter; existing EoiContext + Documenso payload tests updated to assert the new field. 1022 -> 1037 passing. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 03:03:29 +02:00
/**
* Compact range string for every berth in the interest's EOI bundle
* (rows where `interest_berths.is_in_eoi_bundle=true`). Populates the
* Documenso `Berth Range` form field for multi-berth EOIs (plan §1
* + §4.6). Empty string when the bundle is empty.
*/
eoiBerthRange: string;
interest: {
stage: string;
leadCategory: string | null;
dateFirstContact: Date | null;
notes: string | null;
};
port: {
name: string;
defaultCurrency: string;
};
date: {
today: string;
year: string;
};
};
// ─── buildEoiContext ──────────────────────────────────────────────────────────
/**
* Assembles the shared context object used by EOI generation, templates, and
* any other flow that needs a denormalised snapshot of an interest + its
* surrounding entities (client, yacht, berth, owner, port, etc.).
*
* Pure read-only: no audit logs, no socket emits, no mutations.
*
* Tenant-scoped: every fetch is gated by `portId`, and missing rows surface
feat(eoi): align prerequisites with EOI document structure Match the gate to the actual EOI's structure (Section 2 vs Section 3) so the rep can generate the document the moment they have what they need — and not before. Required (Section 2 — top paragraph): - Client name - Client primary email - Client primary address Optional (Section 3 — left blank when absent): - Linked yacht (name, dimensions) - Linked berth (mooring number) Previously the dialog blocked generation unless yacht AND berth were both linked, which was overzealous — early-stage EOIs are routinely sent before a specific berth is pinned down. - eoi-context.ts: yacht and berth are now nullable in the returned context. The hard ValidationError is now driven by the EOI's Section 2 fields (name/email/address) rather than yacht/berth presence. The owner block falls back to the interest's client when no yacht is linked, so signing parties remain resolvable. - documenso-payload.ts + fill-eoi-form.ts: Section 3 form values render as empty strings when yacht or berth are absent, so the rendered PDF leaves those template inputs blank. - document-templates.ts: yacht.* and berth.* tokens fall back to empty strings; the legacy-fallback catch handler also recognises the new "missing required client details" error. - interests.service.ts: getInterestById now also returns `clientPrimaryEmail` and `clientHasAddress` so the Documents tab can compute the EOI prerequisites checklist client-side without an extra fetch. - eoi-generate-dialog.tsx: prereqs split into two groups visually — Required (with red ✗ when missing) and Optional (with grey – when absent). The Generate button only requires the Required block to pass. A small amber banner surfaces when Required is incomplete so the rep knows where to add the missing data. Tests: 835/835 pass. Replaces the obsolete "throws on missing yacht/ berth" tests with parity coverage for the new behaviour ("builds a valid context when yacht/berth missing", "throws when client email/ address missing"). Adds a payload test for the empty-Section-3 case. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 03:11:14 +02:00
* as NotFoundError. The hard gate matches the EOI document's top paragraph
* (Section 2 - name, address, email): without those the EOI is unsignable
* and we throw. Yacht and berth (Section 3) are optional - the rendered PDF
feat(eoi): align prerequisites with EOI document structure Match the gate to the actual EOI's structure (Section 2 vs Section 3) so the rep can generate the document the moment they have what they need — and not before. Required (Section 2 — top paragraph): - Client name - Client primary email - Client primary address Optional (Section 3 — left blank when absent): - Linked yacht (name, dimensions) - Linked berth (mooring number) Previously the dialog blocked generation unless yacht AND berth were both linked, which was overzealous — early-stage EOIs are routinely sent before a specific berth is pinned down. - eoi-context.ts: yacht and berth are now nullable in the returned context. The hard ValidationError is now driven by the EOI's Section 2 fields (name/email/address) rather than yacht/berth presence. The owner block falls back to the interest's client when no yacht is linked, so signing parties remain resolvable. - documenso-payload.ts + fill-eoi-form.ts: Section 3 form values render as empty strings when yacht or berth are absent, so the rendered PDF leaves those template inputs blank. - document-templates.ts: yacht.* and berth.* tokens fall back to empty strings; the legacy-fallback catch handler also recognises the new "missing required client details" error. - interests.service.ts: getInterestById now also returns `clientPrimaryEmail` and `clientHasAddress` so the Documents tab can compute the EOI prerequisites checklist client-side without an extra fetch. - eoi-generate-dialog.tsx: prereqs split into two groups visually — Required (with red ✗ when missing) and Optional (with grey – when absent). The Generate button only requires the Required block to pass. A small amber banner surfaces when Required is incomplete so the rep knows where to add the missing data. Tests: 835/835 pass. Replaces the obsolete "throws on missing yacht/ berth" tests with parity coverage for the new behaviour ("builds a valid context when yacht/berth missing", "throws when client email/ address missing"). Adds a payload test for the empty-Section-3 case. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 03:11:14 +02:00
* leaves those fields blank when not set.
*/
export async function buildEoiContext(interestId: string, portId: string): Promise<EoiContext> {
// 1. Interest (tenant-scoped)
const interest = await db.query.interests.findFirst({
where: and(eq(interests.id, interestId), eq(interests.portId, portId)),
});
if (!interest) {
throw new NotFoundError('Interest');
}
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 the interest's primary berth via the junction (plan §3.4).
// EOI Section 3 stays blank when no primary is set.
const primaryBerth = await getPrimaryBerth(interest.id);
const primaryBerthId = primaryBerth?.berthId ?? null;
feat(eoi): multi-berth EOI generation + berth-range formatter Plan §4.6 + §1: a render function that compresses every berth marked is_in_eoi_bundle=true on an interest into a compact range string ("A1-A3, B5-B7"), wired into both EOI generation paths (the Documenso template-generate call and the in-app pdf-lib AcroForm fill). - src/lib/templates/berth-range.ts: pure formatBerthRange() with the full edge-case set from §4.6 - empty, single, run, gap, multiple prefixes, sort/dedup, multi-letter prefixes, non-canonical passthrough, long ranges. Sorts by (prefix, number); dedupes; passes non-canonical inputs through with a logger warning. - src/lib/templates/merge-fields.ts: new {{eoi.berthRange}} token added to VALID_MERGE_TOKENS allow-list under a fresh `eoi` scope so unknown-token validation at template creation time still rejects typos. - src/lib/services/eoi-context.ts: EoiContext gains eoiBerthRange. Resolved by joining interest_berths (is_in_eoi_bundle=true) → berths and feeding the mooring numbers through formatBerthRange. - src/lib/services/documenso-payload.ts: formValues now includes "Berth Range" alongside the legacy "Berth Number". Multi-berth EOIs surface here; single-berth EOIs duplicate the primary. - src/lib/pdf/fill-eoi-form.ts: in-app AcroForm fill mirrors the Documenso payload by populating "Berth Range". Falls back silently when older PDFs don't have the field (setText is no-op-on-missing). 15 unit tests on the formatter; existing EoiContext + Documenso payload tests updated to assert the new field. 1022 -> 1037 passing. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 03:03:29 +02:00
// Resolve every berth in the EOI bundle (is_in_eoi_bundle=true) for the
// multi-berth EOI compact-range merge field. Empty bundle → "" so the
// Documenso template renders blank rather than "undefined".
const bundleRows = await db
.select({ mooringNumber: berths.mooringNumber })
.from(interestBerths)
.innerJoin(berths, eq(berths.id, interestBerths.berthId))
.where(and(eq(interestBerths.interestId, interest.id), eq(interestBerths.isInEoiBundle, true)));
const eoiBerthRange = formatBerthRange(bundleRows.map((r) => r.mooringNumber));
// Parallelise independent reads. Yacht and berth are both nullable -
feat(eoi): align prerequisites with EOI document structure Match the gate to the actual EOI's structure (Section 2 vs Section 3) so the rep can generate the document the moment they have what they need — and not before. Required (Section 2 — top paragraph): - Client name - Client primary email - Client primary address Optional (Section 3 — left blank when absent): - Linked yacht (name, dimensions) - Linked berth (mooring number) Previously the dialog blocked generation unless yacht AND berth were both linked, which was overzealous — early-stage EOIs are routinely sent before a specific berth is pinned down. - eoi-context.ts: yacht and berth are now nullable in the returned context. The hard ValidationError is now driven by the EOI's Section 2 fields (name/email/address) rather than yacht/berth presence. The owner block falls back to the interest's client when no yacht is linked, so signing parties remain resolvable. - documenso-payload.ts + fill-eoi-form.ts: Section 3 form values render as empty strings when yacht or berth are absent, so the rendered PDF leaves those template inputs blank. - document-templates.ts: yacht.* and berth.* tokens fall back to empty strings; the legacy-fallback catch handler also recognises the new "missing required client details" error. - interests.service.ts: getInterestById now also returns `clientPrimaryEmail` and `clientHasAddress` so the Documents tab can compute the EOI prerequisites checklist client-side without an extra fetch. - eoi-generate-dialog.tsx: prereqs split into two groups visually — Required (with red ✗ when missing) and Optional (with grey – when absent). The Generate button only requires the Required block to pass. A small amber banner surfaces when Required is incomplete so the rep knows where to add the missing data. Tests: 835/835 pass. Replaces the obsolete "throws on missing yacht/ berth" tests with parity coverage for the new behaviour ("builds a valid context when yacht/berth missing", "throws when client email/ address missing"). Adds a payload test for the empty-Section-3 case. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 03:11:14 +02:00
// the EOI's Section 3 stays blank when they're absent.
const [yacht, berth, client, port] = await Promise.all([
feat(eoi): align prerequisites with EOI document structure Match the gate to the actual EOI's structure (Section 2 vs Section 3) so the rep can generate the document the moment they have what they need — and not before. Required (Section 2 — top paragraph): - Client name - Client primary email - Client primary address Optional (Section 3 — left blank when absent): - Linked yacht (name, dimensions) - Linked berth (mooring number) Previously the dialog blocked generation unless yacht AND berth were both linked, which was overzealous — early-stage EOIs are routinely sent before a specific berth is pinned down. - eoi-context.ts: yacht and berth are now nullable in the returned context. The hard ValidationError is now driven by the EOI's Section 2 fields (name/email/address) rather than yacht/berth presence. The owner block falls back to the interest's client when no yacht is linked, so signing parties remain resolvable. - documenso-payload.ts + fill-eoi-form.ts: Section 3 form values render as empty strings when yacht or berth are absent, so the rendered PDF leaves those template inputs blank. - document-templates.ts: yacht.* and berth.* tokens fall back to empty strings; the legacy-fallback catch handler also recognises the new "missing required client details" error. - interests.service.ts: getInterestById now also returns `clientPrimaryEmail` and `clientHasAddress` so the Documents tab can compute the EOI prerequisites checklist client-side without an extra fetch. - eoi-generate-dialog.tsx: prereqs split into two groups visually — Required (with red ✗ when missing) and Optional (with grey – when absent). The Generate button only requires the Required block to pass. A small amber banner surfaces when Required is incomplete so the rep knows where to add the missing data. Tests: 835/835 pass. Replaces the obsolete "throws on missing yacht/ berth" tests with parity coverage for the new behaviour ("builds a valid context when yacht/berth missing", "throws when client email/ address missing"). Adds a payload test for the empty-Section-3 case. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 03:11:14 +02:00
interest.yachtId
? db.query.yachts.findFirst({
where: and(eq(yachts.id, interest.yachtId), eq(yachts.portId, portId)),
})
: Promise.resolve(undefined),
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
primaryBerthId
feat(eoi): align prerequisites with EOI document structure Match the gate to the actual EOI's structure (Section 2 vs Section 3) so the rep can generate the document the moment they have what they need — and not before. Required (Section 2 — top paragraph): - Client name - Client primary email - Client primary address Optional (Section 3 — left blank when absent): - Linked yacht (name, dimensions) - Linked berth (mooring number) Previously the dialog blocked generation unless yacht AND berth were both linked, which was overzealous — early-stage EOIs are routinely sent before a specific berth is pinned down. - eoi-context.ts: yacht and berth are now nullable in the returned context. The hard ValidationError is now driven by the EOI's Section 2 fields (name/email/address) rather than yacht/berth presence. The owner block falls back to the interest's client when no yacht is linked, so signing parties remain resolvable. - documenso-payload.ts + fill-eoi-form.ts: Section 3 form values render as empty strings when yacht or berth are absent, so the rendered PDF leaves those template inputs blank. - document-templates.ts: yacht.* and berth.* tokens fall back to empty strings; the legacy-fallback catch handler also recognises the new "missing required client details" error. - interests.service.ts: getInterestById now also returns `clientPrimaryEmail` and `clientHasAddress` so the Documents tab can compute the EOI prerequisites checklist client-side without an extra fetch. - eoi-generate-dialog.tsx: prereqs split into two groups visually — Required (with red ✗ when missing) and Optional (with grey – when absent). The Generate button only requires the Required block to pass. A small amber banner surfaces when Required is incomplete so the rep knows where to add the missing data. Tests: 835/835 pass. Replaces the obsolete "throws on missing yacht/ berth" tests with parity coverage for the new behaviour ("builds a valid context when yacht/berth missing", "throws when client email/ address missing"). Adds a payload test for the empty-Section-3 case. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 03:11:14 +02:00
? db.query.berths.findFirst({
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(berths.id, primaryBerthId), eq(berths.portId, portId)),
feat(eoi): align prerequisites with EOI document structure Match the gate to the actual EOI's structure (Section 2 vs Section 3) so the rep can generate the document the moment they have what they need — and not before. Required (Section 2 — top paragraph): - Client name - Client primary email - Client primary address Optional (Section 3 — left blank when absent): - Linked yacht (name, dimensions) - Linked berth (mooring number) Previously the dialog blocked generation unless yacht AND berth were both linked, which was overzealous — early-stage EOIs are routinely sent before a specific berth is pinned down. - eoi-context.ts: yacht and berth are now nullable in the returned context. The hard ValidationError is now driven by the EOI's Section 2 fields (name/email/address) rather than yacht/berth presence. The owner block falls back to the interest's client when no yacht is linked, so signing parties remain resolvable. - documenso-payload.ts + fill-eoi-form.ts: Section 3 form values render as empty strings when yacht or berth are absent, so the rendered PDF leaves those template inputs blank. - document-templates.ts: yacht.* and berth.* tokens fall back to empty strings; the legacy-fallback catch handler also recognises the new "missing required client details" error. - interests.service.ts: getInterestById now also returns `clientPrimaryEmail` and `clientHasAddress` so the Documents tab can compute the EOI prerequisites checklist client-side without an extra fetch. - eoi-generate-dialog.tsx: prereqs split into two groups visually — Required (with red ✗ when missing) and Optional (with grey – when absent). The Generate button only requires the Required block to pass. A small amber banner surfaces when Required is incomplete so the rep knows where to add the missing data. Tests: 835/835 pass. Replaces the obsolete "throws on missing yacht/ berth" tests with parity coverage for the new behaviour ("builds a valid context when yacht/berth missing", "throws when client email/ address missing"). Adds a payload test for the empty-Section-3 case. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 03:11:14 +02:00
})
: Promise.resolve(undefined),
db.query.clients.findFirst({
where: and(eq(clients.id, interest.clientId), eq(clients.portId, portId)),
}),
db.query.ports.findFirst({
where: eq(ports.id, portId),
}),
]);
if (!client) throw new NotFoundError('Client');
if (!port) throw new NotFoundError('Port');
// 5. Primary contacts - email + phone for the interest's client.
const contactRows = await db
.select({
channel: clientContacts.channel,
value: clientContacts.value,
isPrimary: clientContacts.isPrimary,
updatedAt: clientContacts.updatedAt,
})
.from(clientContacts)
.where(eq(clientContacts.clientId, client.id))
.orderBy(desc(clientContacts.isPrimary), desc(clientContacts.updatedAt));
const firstEmail = contactRows.find((c) => c.channel === 'email');
const firstPhone =
contactRows.find((c) => c.channel === 'phone') ??
contactRows.find((c) => c.channel === 'whatsapp');
// 6. Primary address. Country is rendered as the localized name (English by
// default for documents) from the ISO code.
const [primaryAddress] = await db
.select({
streetAddress: clientAddresses.streetAddress,
city: clientAddresses.city,
countryIso: clientAddresses.countryIso,
})
.from(clientAddresses)
.where(and(eq(clientAddresses.clientId, client.id), eq(clientAddresses.isPrimary, true)))
.limit(1);
const clientAddress = primaryAddress
? {
street: primaryAddress.streetAddress ?? '',
city: primaryAddress.city ?? '',
country: primaryAddress.countryIso ? getCountryName(primaryAddress.countryIso, 'en') : '',
}
: null;
feat(eoi): align prerequisites with EOI document structure Match the gate to the actual EOI's structure (Section 2 vs Section 3) so the rep can generate the document the moment they have what they need — and not before. Required (Section 2 — top paragraph): - Client name - Client primary email - Client primary address Optional (Section 3 — left blank when absent): - Linked yacht (name, dimensions) - Linked berth (mooring number) Previously the dialog blocked generation unless yacht AND berth were both linked, which was overzealous — early-stage EOIs are routinely sent before a specific berth is pinned down. - eoi-context.ts: yacht and berth are now nullable in the returned context. The hard ValidationError is now driven by the EOI's Section 2 fields (name/email/address) rather than yacht/berth presence. The owner block falls back to the interest's client when no yacht is linked, so signing parties remain resolvable. - documenso-payload.ts + fill-eoi-form.ts: Section 3 form values render as empty strings when yacht or berth are absent, so the rendered PDF leaves those template inputs blank. - document-templates.ts: yacht.* and berth.* tokens fall back to empty strings; the legacy-fallback catch handler also recognises the new "missing required client details" error. - interests.service.ts: getInterestById now also returns `clientPrimaryEmail` and `clientHasAddress` so the Documents tab can compute the EOI prerequisites checklist client-side without an extra fetch. - eoi-generate-dialog.tsx: prereqs split into two groups visually — Required (with red ✗ when missing) and Optional (with grey – when absent). The Generate button only requires the Required block to pass. A small amber banner surfaces when Required is incomplete so the rep knows where to add the missing data. Tests: 835/835 pass. Replaces the obsolete "throws on missing yacht/ berth" tests with parity coverage for the new behaviour ("builds a valid context when yacht/berth missing", "throws when client email/ address missing"). Adds a payload test for the empty-Section-3 case. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 03:11:14 +02:00
// EOI hard gate: the document's top paragraph (Section 2) requires Name,
// Address, and Email. Without these the rendered EOI is unsignable. Yacht
// and berth (Section 3) are intentionally optional and may be left blank.
const missing: string[] = [];
if (!client.fullName?.trim()) missing.push('client name');
if (!firstEmail?.value?.trim()) missing.push('client email');
if (!clientAddress || !clientAddress.street.trim()) missing.push('client address');
if (missing.length > 0) {
throw new ValidationError(
`Cannot generate EOI - missing required client details: ${missing.join(', ')}.`,
feat(eoi): align prerequisites with EOI document structure Match the gate to the actual EOI's structure (Section 2 vs Section 3) so the rep can generate the document the moment they have what they need — and not before. Required (Section 2 — top paragraph): - Client name - Client primary email - Client primary address Optional (Section 3 — left blank when absent): - Linked yacht (name, dimensions) - Linked berth (mooring number) Previously the dialog blocked generation unless yacht AND berth were both linked, which was overzealous — early-stage EOIs are routinely sent before a specific berth is pinned down. - eoi-context.ts: yacht and berth are now nullable in the returned context. The hard ValidationError is now driven by the EOI's Section 2 fields (name/email/address) rather than yacht/berth presence. The owner block falls back to the interest's client when no yacht is linked, so signing parties remain resolvable. - documenso-payload.ts + fill-eoi-form.ts: Section 3 form values render as empty strings when yacht or berth are absent, so the rendered PDF leaves those template inputs blank. - document-templates.ts: yacht.* and berth.* tokens fall back to empty strings; the legacy-fallback catch handler also recognises the new "missing required client details" error. - interests.service.ts: getInterestById now also returns `clientPrimaryEmail` and `clientHasAddress` so the Documents tab can compute the EOI prerequisites checklist client-side without an extra fetch. - eoi-generate-dialog.tsx: prereqs split into two groups visually — Required (with red ✗ when missing) and Optional (with grey – when absent). The Generate button only requires the Required block to pass. A small amber banner surfaces when Required is incomplete so the rep knows where to add the missing data. Tests: 835/835 pass. Replaces the obsolete "throws on missing yacht/ berth" tests with parity coverage for the new behaviour ("builds a valid context when yacht/berth missing", "throws when client email/ address missing"). Adds a payload test for the empty-Section-3 case. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 03:11:14 +02:00
);
}
// Owner block. When a yacht is linked, derive from the yacht's polymorphic
// owner. When no yacht is linked, fall back to the interest's client so the
// EOI's signing party is still resolvable.
let ownerBlock: EoiContext['owner'];
let companyBlock: EoiContext['company'] = null;
feat(eoi): align prerequisites with EOI document structure Match the gate to the actual EOI's structure (Section 2 vs Section 3) so the rep can generate the document the moment they have what they need — and not before. Required (Section 2 — top paragraph): - Client name - Client primary email - Client primary address Optional (Section 3 — left blank when absent): - Linked yacht (name, dimensions) - Linked berth (mooring number) Previously the dialog blocked generation unless yacht AND berth were both linked, which was overzealous — early-stage EOIs are routinely sent before a specific berth is pinned down. - eoi-context.ts: yacht and berth are now nullable in the returned context. The hard ValidationError is now driven by the EOI's Section 2 fields (name/email/address) rather than yacht/berth presence. The owner block falls back to the interest's client when no yacht is linked, so signing parties remain resolvable. - documenso-payload.ts + fill-eoi-form.ts: Section 3 form values render as empty strings when yacht or berth are absent, so the rendered PDF leaves those template inputs blank. - document-templates.ts: yacht.* and berth.* tokens fall back to empty strings; the legacy-fallback catch handler also recognises the new "missing required client details" error. - interests.service.ts: getInterestById now also returns `clientPrimaryEmail` and `clientHasAddress` so the Documents tab can compute the EOI prerequisites checklist client-side without an extra fetch. - eoi-generate-dialog.tsx: prereqs split into two groups visually — Required (with red ✗ when missing) and Optional (with grey – when absent). The Generate button only requires the Required block to pass. A small amber banner surfaces when Required is incomplete so the rep knows where to add the missing data. Tests: 835/835 pass. Replaces the obsolete "throws on missing yacht/ berth" tests with parity coverage for the new behaviour ("builds a valid context when yacht/berth missing", "throws when client email/ address missing"). Adds a payload test for the empty-Section-3 case. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 03:11:14 +02:00
if (!yacht) {
ownerBlock = { type: 'client', name: client.fullName };
} else if (yacht.currentOwnerType === 'client') {
// The yacht-owning client may or may not be the same as the interest's client.
const ownerClient =
yacht.currentOwnerId === client.id
? client
: await db.query.clients.findFirst({
where: and(eq(clients.id, yacht.currentOwnerId), eq(clients.portId, portId)),
});
if (!ownerClient) throw new NotFoundError('Client');
ownerBlock = { type: 'client', name: ownerClient.fullName };
} else if (yacht.currentOwnerType === 'company') {
const company = await db.query.companies.findFirst({
where: and(eq(companies.id, yacht.currentOwnerId), eq(companies.portId, portId)),
});
if (!company) throw new NotFoundError('Company');
ownerBlock = {
type: 'company',
name: company.name,
...(company.legalName ? { legalName: company.legalName } : {}),
};
const [companyPrimaryAddress] = await db
.select({
streetAddress: companyAddresses.streetAddress,
city: companyAddresses.city,
countryIso: companyAddresses.countryIso,
})
.from(companyAddresses)
.where(and(eq(companyAddresses.companyId, company.id), eq(companyAddresses.isPrimary, true)))
.limit(1);
const billingAddress = companyPrimaryAddress
? [
companyPrimaryAddress.streetAddress,
companyPrimaryAddress.city,
companyPrimaryAddress.countryIso
? getCountryName(companyPrimaryAddress.countryIso, 'en')
: null,
]
.filter((s): s is string => Boolean(s))
.join(', ') || null
: null;
companyBlock = {
name: company.name,
legalName: company.legalName,
taxId: company.taxId,
billingAddress,
};
} else {
throw new ValidationError(`unknown yacht owner type: ${String(yacht.currentOwnerType)}`);
}
// 10. Date.
const now = new Date();
const today = now.toISOString().slice(0, 10);
const year = String(now.getFullYear());
return {
client: {
fullName: client.fullName,
nationality: client.nationalityIso ? getCountryName(client.nationalityIso, 'en') : null,
primaryEmail: firstEmail?.value ?? null,
primaryPhone: firstPhone?.value ?? null,
address: clientAddress,
},
feat(eoi): align prerequisites with EOI document structure Match the gate to the actual EOI's structure (Section 2 vs Section 3) so the rep can generate the document the moment they have what they need — and not before. Required (Section 2 — top paragraph): - Client name - Client primary email - Client primary address Optional (Section 3 — left blank when absent): - Linked yacht (name, dimensions) - Linked berth (mooring number) Previously the dialog blocked generation unless yacht AND berth were both linked, which was overzealous — early-stage EOIs are routinely sent before a specific berth is pinned down. - eoi-context.ts: yacht and berth are now nullable in the returned context. The hard ValidationError is now driven by the EOI's Section 2 fields (name/email/address) rather than yacht/berth presence. The owner block falls back to the interest's client when no yacht is linked, so signing parties remain resolvable. - documenso-payload.ts + fill-eoi-form.ts: Section 3 form values render as empty strings when yacht or berth are absent, so the rendered PDF leaves those template inputs blank. - document-templates.ts: yacht.* and berth.* tokens fall back to empty strings; the legacy-fallback catch handler also recognises the new "missing required client details" error. - interests.service.ts: getInterestById now also returns `clientPrimaryEmail` and `clientHasAddress` so the Documents tab can compute the EOI prerequisites checklist client-side without an extra fetch. - eoi-generate-dialog.tsx: prereqs split into two groups visually — Required (with red ✗ when missing) and Optional (with grey – when absent). The Generate button only requires the Required block to pass. A small amber banner surfaces when Required is incomplete so the rep knows where to add the missing data. Tests: 835/835 pass. Replaces the obsolete "throws on missing yacht/ berth" tests with parity coverage for the new behaviour ("builds a valid context when yacht/berth missing", "throws when client email/ address missing"). Adds a payload test for the empty-Section-3 case. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 03:11:14 +02:00
yacht: yacht
? {
name: yacht.name,
lengthFt: yacht.lengthFt,
widthFt: yacht.widthFt,
draftFt: yacht.draftFt,
lengthM: yacht.lengthM,
widthM: yacht.widthM,
draftM: yacht.draftM,
hullNumber: yacht.hullNumber,
flag: yacht.flag,
yearBuilt: yacht.yearBuilt,
}
: null,
company: companyBlock,
owner: ownerBlock,
feat(eoi): align prerequisites with EOI document structure Match the gate to the actual EOI's structure (Section 2 vs Section 3) so the rep can generate the document the moment they have what they need — and not before. Required (Section 2 — top paragraph): - Client name - Client primary email - Client primary address Optional (Section 3 — left blank when absent): - Linked yacht (name, dimensions) - Linked berth (mooring number) Previously the dialog blocked generation unless yacht AND berth were both linked, which was overzealous — early-stage EOIs are routinely sent before a specific berth is pinned down. - eoi-context.ts: yacht and berth are now nullable in the returned context. The hard ValidationError is now driven by the EOI's Section 2 fields (name/email/address) rather than yacht/berth presence. The owner block falls back to the interest's client when no yacht is linked, so signing parties remain resolvable. - documenso-payload.ts + fill-eoi-form.ts: Section 3 form values render as empty strings when yacht or berth are absent, so the rendered PDF leaves those template inputs blank. - document-templates.ts: yacht.* and berth.* tokens fall back to empty strings; the legacy-fallback catch handler also recognises the new "missing required client details" error. - interests.service.ts: getInterestById now also returns `clientPrimaryEmail` and `clientHasAddress` so the Documents tab can compute the EOI prerequisites checklist client-side without an extra fetch. - eoi-generate-dialog.tsx: prereqs split into two groups visually — Required (with red ✗ when missing) and Optional (with grey – when absent). The Generate button only requires the Required block to pass. A small amber banner surfaces when Required is incomplete so the rep knows where to add the missing data. Tests: 835/835 pass. Replaces the obsolete "throws on missing yacht/ berth" tests with parity coverage for the new behaviour ("builds a valid context when yacht/berth missing", "throws when client email/ address missing"). Adds a payload test for the empty-Section-3 case. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 03:11:14 +02:00
berth: berth
? {
mooringNumber: berth.mooringNumber,
area: berth.area,
lengthFt: berth.lengthFt,
price: berth.price,
priceCurrency: berth.priceCurrency,
tenureType: berth.tenureType,
}
: null,
feat(eoi): multi-berth EOI generation + berth-range formatter Plan §4.6 + §1: a render function that compresses every berth marked is_in_eoi_bundle=true on an interest into a compact range string ("A1-A3, B5-B7"), wired into both EOI generation paths (the Documenso template-generate call and the in-app pdf-lib AcroForm fill). - src/lib/templates/berth-range.ts: pure formatBerthRange() with the full edge-case set from §4.6 - empty, single, run, gap, multiple prefixes, sort/dedup, multi-letter prefixes, non-canonical passthrough, long ranges. Sorts by (prefix, number); dedupes; passes non-canonical inputs through with a logger warning. - src/lib/templates/merge-fields.ts: new {{eoi.berthRange}} token added to VALID_MERGE_TOKENS allow-list under a fresh `eoi` scope so unknown-token validation at template creation time still rejects typos. - src/lib/services/eoi-context.ts: EoiContext gains eoiBerthRange. Resolved by joining interest_berths (is_in_eoi_bundle=true) → berths and feeding the mooring numbers through formatBerthRange. - src/lib/services/documenso-payload.ts: formValues now includes "Berth Range" alongside the legacy "Berth Number". Multi-berth EOIs surface here; single-berth EOIs duplicate the primary. - src/lib/pdf/fill-eoi-form.ts: in-app AcroForm fill mirrors the Documenso payload by populating "Berth Range". Falls back silently when older PDFs don't have the field (setText is no-op-on-missing). 15 unit tests on the formatter; existing EoiContext + Documenso payload tests updated to assert the new field. 1022 -> 1037 passing. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 03:03:29 +02:00
eoiBerthRange,
interest: {
stage: interest.pipelineStage,
leadCategory: interest.leadCategory,
dateFirstContact: interest.dateFirstContact,
notes: interest.notes,
},
port: {
name: port.name,
defaultCurrency: port.defaultCurrency,
},
date: {
today,
year,
},
};
}