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>
This commit is contained in:
@@ -22,8 +22,14 @@ import {
|
|||||||
import { Label } from '@/components/ui/label';
|
import { Label } from '@/components/ui/label';
|
||||||
import { apiFetch } from '@/lib/api/client';
|
import { apiFetch } from '@/lib/api/client';
|
||||||
|
|
||||||
|
/** Required for the EOI's top paragraph (Section 2) — without these the
|
||||||
|
* document is unsignable, so generation is blocked. Yacht and berth fields
|
||||||
|
* belong to Section 3 and may be left blank. */
|
||||||
interface EoiPrerequisites {
|
interface EoiPrerequisites {
|
||||||
hasName: boolean;
|
hasName: boolean;
|
||||||
|
hasEmail: boolean;
|
||||||
|
hasAddress: boolean;
|
||||||
|
/** Optional — info-only checks. Generation proceeds without them. */
|
||||||
hasYacht: boolean;
|
hasYacht: boolean;
|
||||||
hasBerth: boolean;
|
hasBerth: boolean;
|
||||||
}
|
}
|
||||||
@@ -35,10 +41,15 @@ interface EoiGenerateDialogProps {
|
|||||||
prerequisites: EoiPrerequisites;
|
prerequisites: EoiPrerequisites;
|
||||||
}
|
}
|
||||||
|
|
||||||
const PREREQUISITE_LABELS: { key: keyof EoiPrerequisites; label: string }[] = [
|
const REQUIRED_LABELS: { key: keyof EoiPrerequisites; label: string }[] = [
|
||||||
{ key: 'hasName', label: 'Client has full name' },
|
{ key: 'hasName', label: 'Client name' },
|
||||||
{ key: 'hasYacht', label: 'Yacht linked to interest' },
|
{ key: 'hasAddress', label: 'Client address' },
|
||||||
{ key: 'hasBerth', label: 'Berth linked to interest' },
|
{ key: 'hasEmail', label: 'Client email' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const OPTIONAL_LABELS: { key: keyof EoiPrerequisites; label: string }[] = [
|
||||||
|
{ key: 'hasYacht', label: 'Yacht linked (name + dimensions)' },
|
||||||
|
{ key: 'hasBerth', label: 'Berth linked (mooring number)' },
|
||||||
];
|
];
|
||||||
|
|
||||||
const DOCUMENSO_TEMPLATE_VALUE = 'documenso-template';
|
const DOCUMENSO_TEMPLATE_VALUE = 'documenso-template';
|
||||||
@@ -65,7 +76,7 @@ export function EoiGenerateDialog({
|
|||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [selectedTemplate, setSelectedTemplate] = useState<string>(DOCUMENSO_TEMPLATE_VALUE);
|
const [selectedTemplate, setSelectedTemplate] = useState<string>(DOCUMENSO_TEMPLATE_VALUE);
|
||||||
|
|
||||||
const allMet = Object.values(prerequisites).every(Boolean);
|
const requiredMet = REQUIRED_LABELS.every(({ key }) => prerequisites[key]);
|
||||||
|
|
||||||
// Load in-app EOI templates so the operator can pick one as an alternative
|
// Load in-app EOI templates so the operator can pick one as an alternative
|
||||||
// to the Documenso external-signing flow.
|
// to the Documenso external-signing flow.
|
||||||
@@ -79,7 +90,7 @@ export function EoiGenerateDialog({
|
|||||||
const inAppTemplates = useMemo(() => templatesRes?.data ?? [], [templatesRes]);
|
const inAppTemplates = useMemo(() => templatesRes?.data ?? [], [templatesRes]);
|
||||||
|
|
||||||
const handleGenerate = async () => {
|
const handleGenerate = async () => {
|
||||||
if (!allMet) return;
|
if (!requiredMet) return;
|
||||||
|
|
||||||
setIsGenerating(true);
|
setIsGenerating(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
@@ -138,22 +149,59 @@ export function EoiGenerateDialog({
|
|||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-3">
|
||||||
<p className="text-xs font-medium text-muted-foreground">Prerequisites</p>
|
<div className="space-y-1.5">
|
||||||
{PREREQUISITE_LABELS.map(({ key, label }) => (
|
<p className="text-xs font-medium text-muted-foreground">
|
||||||
<div key={key} className="flex items-center gap-3">
|
Required (Section 2 of the EOI)
|
||||||
<span
|
</p>
|
||||||
className={`flex h-5 w-5 items-center justify-center rounded-full text-xs font-bold ${
|
{REQUIRED_LABELS.map(({ key, label }) => (
|
||||||
prerequisites[key] ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
|
<div key={key} className="flex items-center gap-3 text-sm">
|
||||||
}`}
|
<span
|
||||||
>
|
className={`flex h-5 w-5 items-center justify-center rounded-full text-xs font-bold ${
|
||||||
{prerequisites[key] ? '✓' : '✗'}
|
prerequisites[key] ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
|
||||||
</span>
|
}`}
|
||||||
<span className={prerequisites[key] ? 'text-foreground' : 'text-muted-foreground'}>
|
>
|
||||||
{label}
|
{prerequisites[key] ? '✓' : '✗'}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
<span
|
||||||
))}
|
className={prerequisites[key] ? 'text-foreground' : 'text-muted-foreground'}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<p className="text-xs font-medium text-muted-foreground">
|
||||||
|
Optional (Section 3 — left blank if absent)
|
||||||
|
</p>
|
||||||
|
{OPTIONAL_LABELS.map(({ key, label }) => (
|
||||||
|
<div key={key} className="flex items-center gap-3 text-sm">
|
||||||
|
<span
|
||||||
|
className={`flex h-5 w-5 items-center justify-center rounded-full text-xs font-bold ${
|
||||||
|
prerequisites[key]
|
||||||
|
? 'bg-green-100 text-green-700'
|
||||||
|
: 'bg-muted text-muted-foreground'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{prerequisites[key] ? '✓' : '–'}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className={prerequisites[key] ? 'text-foreground' : 'text-muted-foreground'}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!requiredMet ? (
|
||||||
|
<p className="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900">
|
||||||
|
Add the missing required details on the client's record before generating the
|
||||||
|
EOI.
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -163,7 +211,7 @@ export function EoiGenerateDialog({
|
|||||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||||
Cancel
|
Cancel
|
||||||
</Button>
|
</Button>
|
||||||
<Button onClick={handleGenerate} disabled={!allMet || isGenerating}>
|
<Button onClick={handleGenerate} disabled={!requiredMet || isGenerating}>
|
||||||
{isGenerating ? 'Generating…' : 'Generate EOI'}
|
{isGenerating ? 'Generating…' : 'Generate EOI'}
|
||||||
</Button>
|
</Button>
|
||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
|
|||||||
@@ -18,6 +18,9 @@ interface InterestData {
|
|||||||
yachtId?: string | null;
|
yachtId?: string | null;
|
||||||
berthId?: string | null;
|
berthId?: string | null;
|
||||||
clientName?: string | null;
|
clientName?: string | null;
|
||||||
|
/** Surfaced by getInterestById for the EOI prerequisites checklist. */
|
||||||
|
clientPrimaryEmail?: string | null;
|
||||||
|
clientHasAddress?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function InterestDocumentsTab({ interestId }: InterestDocumentsTabProps) {
|
export function InterestDocumentsTab({ interestId }: InterestDocumentsTabProps) {
|
||||||
@@ -33,7 +36,11 @@ export function InterestDocumentsTab({ interestId }: InterestDocumentsTabProps)
|
|||||||
});
|
});
|
||||||
|
|
||||||
const prerequisites = {
|
const prerequisites = {
|
||||||
|
// Required (EOI Section 2 — top paragraph): name, address, email.
|
||||||
hasName: Boolean(interest?.clientName),
|
hasName: Boolean(interest?.clientName),
|
||||||
|
hasEmail: Boolean(interest?.clientPrimaryEmail),
|
||||||
|
hasAddress: Boolean(interest?.clientHasAddress),
|
||||||
|
// Optional (EOI Section 3): yacht + berth. Render blank when absent.
|
||||||
hasYacht: Boolean(interest?.yachtId),
|
hasYacht: Boolean(interest?.yachtId),
|
||||||
hasBerth: Boolean(interest?.berthId),
|
hasBerth: Boolean(interest?.berthId),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -80,11 +80,13 @@ export async function fillEoiFormFields(
|
|||||||
setText(form, 'Name', context.client.fullName);
|
setText(form, 'Name', context.client.fullName);
|
||||||
setText(form, 'Email', context.client.primaryEmail ?? '');
|
setText(form, 'Email', context.client.primaryEmail ?? '');
|
||||||
setText(form, 'Address', formatAddress(context.client.address));
|
setText(form, 'Address', formatAddress(context.client.address));
|
||||||
setText(form, 'Yacht Name', context.yacht.name);
|
// Yacht + berth (EOI Section 3) are optional — leave the AcroForm fields
|
||||||
setText(form, 'Length', context.yacht.lengthFt ?? '');
|
// blank when the interest hasn't been linked to either.
|
||||||
setText(form, 'Width', context.yacht.widthFt ?? '');
|
setText(form, 'Yacht Name', context.yacht?.name ?? '');
|
||||||
setText(form, 'Draft', context.yacht.draftFt ?? '');
|
setText(form, 'Length', context.yacht?.lengthFt ?? '');
|
||||||
setText(form, 'Berth Number', context.berth.mooringNumber);
|
setText(form, 'Width', context.yacht?.widthFt ?? '');
|
||||||
|
setText(form, 'Draft', context.yacht?.draftFt ?? '');
|
||||||
|
setText(form, 'Berth Number', context.berth?.mooringNumber ?? '');
|
||||||
|
|
||||||
setCheckbox(form, 'Purchase', true);
|
setCheckbox(form, 'Purchase', true);
|
||||||
setCheckbox(form, 'Lease_10', false);
|
setCheckbox(form, 'Lease_10', false);
|
||||||
|
|||||||
@@ -128,11 +128,13 @@ export function buildDocumensoPayload(
|
|||||||
Name: context.client.fullName,
|
Name: context.client.fullName,
|
||||||
Email: context.client.primaryEmail ?? '',
|
Email: context.client.primaryEmail ?? '',
|
||||||
Address: formatAddress(context.client.address),
|
Address: formatAddress(context.client.address),
|
||||||
'Yacht Name': context.yacht.name,
|
// Yacht + berth are optional EOI fields; when not linked, render as
|
||||||
Length: context.yacht.lengthFt ?? '',
|
// empty strings so the corresponding template inputs stay blank.
|
||||||
Width: context.yacht.widthFt ?? '',
|
'Yacht Name': context.yacht?.name ?? '',
|
||||||
Draft: context.yacht.draftFt ?? '',
|
Length: context.yacht?.lengthFt ?? '',
|
||||||
'Berth Number': context.berth.mooringNumber,
|
Width: context.yacht?.widthFt ?? '',
|
||||||
|
Draft: context.yacht?.draftFt ?? '',
|
||||||
|
'Berth Number': context.berth?.mooringNumber ?? '',
|
||||||
Lease_10: false,
|
Lease_10: false,
|
||||||
Purchase: true,
|
Purchase: true,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -237,18 +237,20 @@ export async function resolveTemplate(
|
|||||||
tokenMap['{{client.phone}}'] = eoi.client.primaryPhone ?? '';
|
tokenMap['{{client.phone}}'] = eoi.client.primaryPhone ?? '';
|
||||||
tokenMap['{{client.nationality}}'] = eoi.client.nationality ?? '';
|
tokenMap['{{client.nationality}}'] = eoi.client.nationality ?? '';
|
||||||
|
|
||||||
// Yacht tokens
|
// Yacht tokens — `eoi.yacht` is null when no yacht is linked
|
||||||
tokenMap['{{yacht.name}}'] = eoi.yacht.name;
|
// (Section 3 of the EOI is optional). Tokens render as empty strings
|
||||||
tokenMap['{{yacht.hullNumber}}'] = eoi.yacht.hullNumber ?? '';
|
// in that case so the template still produces output.
|
||||||
tokenMap['{{yacht.flag}}'] = eoi.yacht.flag ?? '';
|
tokenMap['{{yacht.name}}'] = eoi.yacht?.name ?? '';
|
||||||
|
tokenMap['{{yacht.hullNumber}}'] = eoi.yacht?.hullNumber ?? '';
|
||||||
|
tokenMap['{{yacht.flag}}'] = eoi.yacht?.flag ?? '';
|
||||||
tokenMap['{{yacht.yearBuilt}}'] =
|
tokenMap['{{yacht.yearBuilt}}'] =
|
||||||
eoi.yacht.yearBuilt != null ? String(eoi.yacht.yearBuilt) : '';
|
eoi.yacht?.yearBuilt != null ? String(eoi.yacht.yearBuilt) : '';
|
||||||
tokenMap['{{yacht.lengthFt}}'] = eoi.yacht.lengthFt ?? '';
|
tokenMap['{{yacht.lengthFt}}'] = eoi.yacht?.lengthFt ?? '';
|
||||||
tokenMap['{{yacht.widthFt}}'] = eoi.yacht.widthFt ?? '';
|
tokenMap['{{yacht.widthFt}}'] = eoi.yacht?.widthFt ?? '';
|
||||||
tokenMap['{{yacht.draftFt}}'] = eoi.yacht.draftFt ?? '';
|
tokenMap['{{yacht.draftFt}}'] = eoi.yacht?.draftFt ?? '';
|
||||||
tokenMap['{{yacht.lengthM}}'] = eoi.yacht.lengthM ?? '';
|
tokenMap['{{yacht.lengthM}}'] = eoi.yacht?.lengthM ?? '';
|
||||||
tokenMap['{{yacht.widthM}}'] = eoi.yacht.widthM ?? '';
|
tokenMap['{{yacht.widthM}}'] = eoi.yacht?.widthM ?? '';
|
||||||
tokenMap['{{yacht.draftM}}'] = eoi.yacht.draftM ?? '';
|
tokenMap['{{yacht.draftM}}'] = eoi.yacht?.draftM ?? '';
|
||||||
|
|
||||||
// EoiContext doesn't expose the yacht.registration column — look it up
|
// EoiContext doesn't expose the yacht.registration column — look it up
|
||||||
// separately (cheap, indexed fetch) so the token resolves when present.
|
// separately (cheap, indexed fetch) so the token resolves when present.
|
||||||
@@ -281,29 +283,31 @@ export async function resolveTemplate(
|
|||||||
tokenMap['{{owner.name}}'] = eoi.owner.name;
|
tokenMap['{{owner.name}}'] = eoi.owner.name;
|
||||||
tokenMap['{{owner.legalName}}'] = eoi.owner.legalName ?? '';
|
tokenMap['{{owner.legalName}}'] = eoi.owner.legalName ?? '';
|
||||||
|
|
||||||
// Berth tokens (from EoiContext)
|
// Berth tokens — also optional. Render empty when no berth is linked.
|
||||||
tokenMap['{{berth.mooringNumber}}'] = eoi.berth.mooringNumber;
|
tokenMap['{{berth.mooringNumber}}'] = eoi.berth?.mooringNumber ?? '';
|
||||||
tokenMap['{{berth.area}}'] = eoi.berth.area ?? '';
|
tokenMap['{{berth.area}}'] = eoi.berth?.area ?? '';
|
||||||
tokenMap['{{berth.lengthFt}}'] = eoi.berth.lengthFt ?? '';
|
tokenMap['{{berth.lengthFt}}'] = eoi.berth?.lengthFt ?? '';
|
||||||
tokenMap['{{berth.price}}'] = eoi.berth.price ?? '';
|
tokenMap['{{berth.price}}'] = eoi.berth?.price ?? '';
|
||||||
tokenMap['{{berth.priceCurrency}}'] = eoi.berth.priceCurrency;
|
tokenMap['{{berth.priceCurrency}}'] = eoi.berth?.priceCurrency ?? '';
|
||||||
tokenMap['{{berth.tenureType}}'] = eoi.berth.tenureType;
|
tokenMap['{{berth.tenureType}}'] = eoi.berth?.tenureType ?? '';
|
||||||
|
|
||||||
// Interest tokens
|
// Interest tokens
|
||||||
tokenMap['{{interest.stage}}'] = eoi.interest.stage;
|
tokenMap['{{interest.stage}}'] = eoi.interest.stage;
|
||||||
tokenMap['{{interest.leadCategory}}'] = eoi.interest.leadCategory ?? '';
|
tokenMap['{{interest.leadCategory}}'] = eoi.interest.leadCategory ?? '';
|
||||||
tokenMap['{{interest.berthNumber}}'] = eoi.berth.mooringNumber;
|
tokenMap['{{interest.berthNumber}}'] = eoi.berth?.mooringNumber ?? '';
|
||||||
tokenMap['{{interest.dateFirstContact}}'] = eoi.interest.dateFirstContact
|
tokenMap['{{interest.dateFirstContact}}'] = eoi.interest.dateFirstContact
|
||||||
? eoi.interest.dateFirstContact.toLocaleDateString('en-GB')
|
? eoi.interest.dateFirstContact.toLocaleDateString('en-GB')
|
||||||
: '';
|
: '';
|
||||||
tokenMap['{{interest.notes}}'] = eoi.interest.notes ?? '';
|
tokenMap['{{interest.notes}}'] = eoi.interest.notes ?? '';
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// buildEoiContext throws ValidationError when the interest has no yacht
|
// buildEoiContext throws ValidationError when the EOI's required client
|
||||||
// or berth; non-EOI templates don't need those. Fall through to the
|
// fields (name/email/address — Section 2) are missing. For non-EOI
|
||||||
// legacy resolution path below. Re-throw anything else.
|
// templates (correspondence, welcome letters, etc.) those gates don't
|
||||||
|
// apply — fall through to the legacy resolution path below. Re-throw
|
||||||
|
// anything else.
|
||||||
if (
|
if (
|
||||||
!(err instanceof ValidationError) ||
|
!(err instanceof ValidationError) ||
|
||||||
!/interest has no (yacht|berth)/i.test(err.message)
|
!/missing required client details|interest has no (yacht|berth)/i.test(err.message)
|
||||||
) {
|
) {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ export type EoiContext = {
|
|||||||
primaryPhone: string | null;
|
primaryPhone: string | null;
|
||||||
address: { street: string; city: string; country: string } | null;
|
address: { street: string; city: string; country: string } | null;
|
||||||
};
|
};
|
||||||
|
/** Optional. The EOI's Section 3 yacht block is left blank when null. */
|
||||||
yacht: {
|
yacht: {
|
||||||
name: string;
|
name: string;
|
||||||
lengthFt: string | null;
|
lengthFt: string | null;
|
||||||
@@ -31,18 +32,22 @@ export type EoiContext = {
|
|||||||
hullNumber: string | null;
|
hullNumber: string | null;
|
||||||
flag: string | null;
|
flag: string | null;
|
||||||
yearBuilt: number | null;
|
yearBuilt: number | null;
|
||||||
};
|
} | null;
|
||||||
company: {
|
company: {
|
||||||
name: string;
|
name: string;
|
||||||
legalName: string | null;
|
legalName: string | null;
|
||||||
taxId: string | null;
|
taxId: string | null;
|
||||||
billingAddress: string | null;
|
billingAddress: string | null;
|
||||||
} | null;
|
} | null;
|
||||||
|
/** 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: {
|
owner: {
|
||||||
type: 'client' | 'company';
|
type: 'client' | 'company';
|
||||||
name: string;
|
name: string;
|
||||||
legalName?: string;
|
legalName?: string;
|
||||||
};
|
};
|
||||||
|
/** Optional. The EOI's Section 3 berth-number is left blank when null. */
|
||||||
berth: {
|
berth: {
|
||||||
mooringNumber: string;
|
mooringNumber: string;
|
||||||
area: string | null;
|
area: string | null;
|
||||||
@@ -50,7 +55,7 @@ export type EoiContext = {
|
|||||||
price: string | null;
|
price: string | null;
|
||||||
priceCurrency: string;
|
priceCurrency: string;
|
||||||
tenureType: string;
|
tenureType: string;
|
||||||
};
|
} | null;
|
||||||
interest: {
|
interest: {
|
||||||
stage: string;
|
stage: string;
|
||||||
leadCategory: string | null;
|
leadCategory: string | null;
|
||||||
@@ -77,8 +82,10 @@ export type EoiContext = {
|
|||||||
* Pure read-only: no audit logs, no socket emits, no mutations.
|
* Pure read-only: no audit logs, no socket emits, no mutations.
|
||||||
*
|
*
|
||||||
* Tenant-scoped: every fetch is gated by `portId`, and missing rows surface
|
* Tenant-scoped: every fetch is gated by `portId`, and missing rows surface
|
||||||
* as NotFoundError. Missing yacht/berth references on the interest surface as
|
* as NotFoundError. The hard gate matches the EOI document's top paragraph
|
||||||
* ValidationError, because EOI flows cannot proceed without them.
|
* (Section 2 — name, address, email): without those the EOI is unsignable
|
||||||
|
* and we throw. Yacht and berth (Section 3) are optional — the rendered PDF
|
||||||
|
* leaves those fields blank when not set.
|
||||||
*/
|
*/
|
||||||
export async function buildEoiContext(interestId: string, portId: string): Promise<EoiContext> {
|
export async function buildEoiContext(interestId: string, portId: string): Promise<EoiContext> {
|
||||||
// 1. Interest (tenant-scoped)
|
// 1. Interest (tenant-scoped)
|
||||||
@@ -89,24 +96,19 @@ export async function buildEoiContext(interestId: string, portId: string): Promi
|
|||||||
throw new NotFoundError('Interest');
|
throw new NotFoundError('Interest');
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Yacht reference must exist on the interest
|
// Parallelise independent reads. Yacht and berth are both nullable —
|
||||||
if (!interest.yachtId) {
|
// the EOI's Section 3 stays blank when they're absent.
|
||||||
throw new ValidationError('interest has no yacht');
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Berth reference must exist on the interest
|
|
||||||
if (!interest.berthId) {
|
|
||||||
throw new ValidationError('interest has no berth');
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2 + 3 + 4 + 9: parallelise independent reads.
|
|
||||||
const [yacht, berth, client, port] = await Promise.all([
|
const [yacht, berth, client, port] = await Promise.all([
|
||||||
db.query.yachts.findFirst({
|
interest.yachtId
|
||||||
where: and(eq(yachts.id, interest.yachtId), eq(yachts.portId, portId)),
|
? db.query.yachts.findFirst({
|
||||||
}),
|
where: and(eq(yachts.id, interest.yachtId), eq(yachts.portId, portId)),
|
||||||
db.query.berths.findFirst({
|
})
|
||||||
where: and(eq(berths.id, interest.berthId), eq(berths.portId, portId)),
|
: Promise.resolve(undefined),
|
||||||
}),
|
interest.berthId
|
||||||
|
? db.query.berths.findFirst({
|
||||||
|
where: and(eq(berths.id, interest.berthId), eq(berths.portId, portId)),
|
||||||
|
})
|
||||||
|
: Promise.resolve(undefined),
|
||||||
db.query.clients.findFirst({
|
db.query.clients.findFirst({
|
||||||
where: and(eq(clients.id, interest.clientId), eq(clients.portId, portId)),
|
where: and(eq(clients.id, interest.clientId), eq(clients.portId, portId)),
|
||||||
}),
|
}),
|
||||||
@@ -115,8 +117,6 @@ export async function buildEoiContext(interestId: string, portId: string): Promi
|
|||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
if (!yacht) throw new NotFoundError('Yacht');
|
|
||||||
if (!berth) throw new NotFoundError('Berth');
|
|
||||||
if (!client) throw new NotFoundError('Client');
|
if (!client) throw new NotFoundError('Client');
|
||||||
if (!port) throw new NotFoundError('Port');
|
if (!port) throw new NotFoundError('Port');
|
||||||
|
|
||||||
@@ -157,11 +157,28 @@ export async function buildEoiContext(interestId: string, portId: string): Promi
|
|||||||
}
|
}
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
// 7 + 8. Yacht owner (polymorphic) + optional company billing address.
|
// 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(', ')}.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 ownerBlock: EoiContext['owner'];
|
||||||
let companyBlock: EoiContext['company'] = null;
|
let companyBlock: EoiContext['company'] = null;
|
||||||
|
|
||||||
if (yacht.currentOwnerType === 'client') {
|
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.
|
// The yacht-owning client may or may not be the same as the interest's client.
|
||||||
const ownerClient =
|
const ownerClient =
|
||||||
yacht.currentOwnerId === client.id
|
yacht.currentOwnerId === client.id
|
||||||
@@ -228,28 +245,32 @@ export async function buildEoiContext(interestId: string, portId: string): Promi
|
|||||||
primaryPhone: firstPhone?.value ?? null,
|
primaryPhone: firstPhone?.value ?? null,
|
||||||
address: clientAddress,
|
address: clientAddress,
|
||||||
},
|
},
|
||||||
yacht: {
|
yacht: yacht
|
||||||
name: yacht.name,
|
? {
|
||||||
lengthFt: yacht.lengthFt,
|
name: yacht.name,
|
||||||
widthFt: yacht.widthFt,
|
lengthFt: yacht.lengthFt,
|
||||||
draftFt: yacht.draftFt,
|
widthFt: yacht.widthFt,
|
||||||
lengthM: yacht.lengthM,
|
draftFt: yacht.draftFt,
|
||||||
widthM: yacht.widthM,
|
lengthM: yacht.lengthM,
|
||||||
draftM: yacht.draftM,
|
widthM: yacht.widthM,
|
||||||
hullNumber: yacht.hullNumber,
|
draftM: yacht.draftM,
|
||||||
flag: yacht.flag,
|
hullNumber: yacht.hullNumber,
|
||||||
yearBuilt: yacht.yearBuilt,
|
flag: yacht.flag,
|
||||||
},
|
yearBuilt: yacht.yearBuilt,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
company: companyBlock,
|
company: companyBlock,
|
||||||
owner: ownerBlock,
|
owner: ownerBlock,
|
||||||
berth: {
|
berth: berth
|
||||||
mooringNumber: berth.mooringNumber,
|
? {
|
||||||
area: berth.area,
|
mooringNumber: berth.mooringNumber,
|
||||||
lengthFt: berth.lengthFt,
|
area: berth.area,
|
||||||
price: berth.price,
|
lengthFt: berth.lengthFt,
|
||||||
priceCurrency: berth.priceCurrency,
|
price: berth.price,
|
||||||
tenureType: berth.tenureType,
|
priceCurrency: berth.priceCurrency,
|
||||||
},
|
tenureType: berth.tenureType,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
interest: {
|
interest: {
|
||||||
stage: interest.pipelineStage,
|
stage: interest.pipelineStage,
|
||||||
leadCategory: interest.leadCategory,
|
leadCategory: interest.leadCategory,
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { and, eq, inArray, isNull, sql } from 'drizzle-orm';
|
import { and, desc, eq, inArray, isNull, sql } from 'drizzle-orm';
|
||||||
|
|
||||||
import { db } from '@/lib/db';
|
import { db } from '@/lib/db';
|
||||||
import { interests, interestTags } from '@/lib/db/schema/interests';
|
import { interests, interestTags } from '@/lib/db/schema/interests';
|
||||||
import { clients } from '@/lib/db/schema/clients';
|
import { clients, clientAddresses, clientContacts } from '@/lib/db/schema/clients';
|
||||||
import { berths } from '@/lib/db/schema/berths';
|
import { berths } from '@/lib/db/schema/berths';
|
||||||
import { yachts } from '@/lib/db/schema/yachts';
|
import { yachts } from '@/lib/db/schema/yachts';
|
||||||
import { companyMemberships } from '@/lib/db/schema/companies';
|
import { companyMemberships } from '@/lib/db/schema/companies';
|
||||||
@@ -282,6 +282,24 @@ export async function getInterestById(id: string, portId: string) {
|
|||||||
.from(clients)
|
.from(clients)
|
||||||
.where(eq(clients.id, interest.clientId));
|
.where(eq(clients.id, interest.clientId));
|
||||||
|
|
||||||
|
// EOI prerequisites: surface enough of the linked client's primary contact
|
||||||
|
// and address so the Documents tab can show the readiness checklist
|
||||||
|
// (Required: name, email, address — Section 2 of the EOI document).
|
||||||
|
const [emailContact] = await db
|
||||||
|
.select({ value: clientContacts.value })
|
||||||
|
.from(clientContacts)
|
||||||
|
.where(and(eq(clientContacts.clientId, interest.clientId), eq(clientContacts.channel, 'email')))
|
||||||
|
.orderBy(desc(clientContacts.isPrimary), desc(clientContacts.updatedAt))
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
const [addressRow] = await db
|
||||||
|
.select({ id: clientAddresses.id })
|
||||||
|
.from(clientAddresses)
|
||||||
|
.where(
|
||||||
|
and(eq(clientAddresses.clientId, interest.clientId), eq(clientAddresses.isPrimary, true)),
|
||||||
|
)
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
let berthMooringNumber: string | null = null;
|
let berthMooringNumber: string | null = null;
|
||||||
if (interest.berthId) {
|
if (interest.berthId) {
|
||||||
const [berthRow] = await db
|
const [berthRow] = await db
|
||||||
@@ -300,6 +318,8 @@ export async function getInterestById(id: string, portId: string) {
|
|||||||
return {
|
return {
|
||||||
...interest,
|
...interest,
|
||||||
clientName: clientRow?.fullName ?? null,
|
clientName: clientRow?.fullName ?? null,
|
||||||
|
clientPrimaryEmail: emailContact?.value ?? null,
|
||||||
|
clientHasAddress: !!addressRow,
|
||||||
berthMooringNumber,
|
berthMooringNumber,
|
||||||
tags: tagRows,
|
tags: tagRows,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -268,6 +268,21 @@ describe('resolveTemplate — company-owned yacht', () => {
|
|||||||
portId: port.id,
|
portId: port.id,
|
||||||
overrides: { fullName: 'Bob Contact' },
|
overrides: { fullName: 'Bob Contact' },
|
||||||
});
|
});
|
||||||
|
// EOI gate now requires client primary email + address.
|
||||||
|
await db.insert(clientContacts).values({
|
||||||
|
clientId: client.id,
|
||||||
|
channel: 'email',
|
||||||
|
value: 'bob@example.com',
|
||||||
|
isPrimary: true,
|
||||||
|
});
|
||||||
|
await db.insert(clientAddresses).values({
|
||||||
|
clientId: client.id,
|
||||||
|
portId: port.id,
|
||||||
|
streetAddress: '1 Marina Way',
|
||||||
|
city: 'Anguilla',
|
||||||
|
countryIso: 'AI',
|
||||||
|
isPrimary: true,
|
||||||
|
});
|
||||||
const yacht = await makeYacht({
|
const yacht = await makeYacht({
|
||||||
portId: port.id,
|
portId: port.id,
|
||||||
ownerType: 'company',
|
ownerType: 'company',
|
||||||
|
|||||||
@@ -91,8 +91,9 @@ describe('buildDocumensoPayload', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('defaults missing yacht dimensions to empty strings', () => {
|
it('defaults missing yacht dimensions to empty strings', () => {
|
||||||
|
const baseYacht = makeContext().yacht!;
|
||||||
const ctx = makeContext({
|
const ctx = makeContext({
|
||||||
yacht: { ...makeContext().yacht, lengthFt: null, widthFt: null, draftFt: null },
|
yacht: { ...baseYacht, lengthFt: null, widthFt: null, draftFt: null },
|
||||||
});
|
});
|
||||||
const payload = buildDocumensoPayload(ctx, OPTIONS);
|
const payload = buildDocumensoPayload(ctx, OPTIONS);
|
||||||
expect(payload.formValues.Length).toBe('');
|
expect(payload.formValues.Length).toBe('');
|
||||||
@@ -100,6 +101,16 @@ describe('buildDocumensoPayload', () => {
|
|||||||
expect(payload.formValues.Draft).toBe('');
|
expect(payload.formValues.Draft).toBe('');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('renders empty Section 3 when yacht and berth are not linked', () => {
|
||||||
|
const ctx = makeContext({ yacht: null, berth: null });
|
||||||
|
const payload = buildDocumensoPayload(ctx, OPTIONS);
|
||||||
|
expect(payload.formValues['Yacht Name']).toBe('');
|
||||||
|
expect(payload.formValues.Length).toBe('');
|
||||||
|
expect(payload.formValues.Width).toBe('');
|
||||||
|
expect(payload.formValues.Draft).toBe('');
|
||||||
|
expect(payload.formValues['Berth Number']).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
it('formats empty address when client has no address', () => {
|
it('formats empty address when client has no address', () => {
|
||||||
const ctx = makeContext({ client: { ...makeContext().client, address: null } });
|
const ctx = makeContext({ client: { ...makeContext().client, address: null } });
|
||||||
const payload = buildDocumensoPayload(ctx, OPTIONS);
|
const payload = buildDocumensoPayload(ctx, OPTIONS);
|
||||||
|
|||||||
@@ -28,6 +28,33 @@ async function insertInterest(args: {
|
|||||||
return row!;
|
return row!;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds the EOI-required client details (primary email + primary address) so
|
||||||
|
* `buildEoiContext` clears its hard gate. Tests that exercise non-EOI-gating
|
||||||
|
* behavior should call this once per client they create.
|
||||||
|
*/
|
||||||
|
async function seedClientEoiPrereqs(args: {
|
||||||
|
clientId: string;
|
||||||
|
portId: string;
|
||||||
|
email?: string;
|
||||||
|
street?: string;
|
||||||
|
}) {
|
||||||
|
await db.insert(clientContacts).values({
|
||||||
|
clientId: args.clientId,
|
||||||
|
channel: 'email',
|
||||||
|
value: args.email ?? `client-${args.clientId.slice(0, 8)}@example.com`,
|
||||||
|
isPrimary: true,
|
||||||
|
});
|
||||||
|
await db.insert(clientAddresses).values({
|
||||||
|
clientId: args.clientId,
|
||||||
|
portId: args.portId,
|
||||||
|
streetAddress: args.street ?? '1 Harbour Way',
|
||||||
|
city: 'Anguilla',
|
||||||
|
countryIso: 'AI',
|
||||||
|
isPrimary: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// ─── Tests ────────────────────────────────────────────────────────────────────
|
// ─── Tests ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
describe('buildEoiContext', () => {
|
describe('buildEoiContext', () => {
|
||||||
@@ -107,13 +134,13 @@ describe('buildEoiContext', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Yacht assertions.
|
// Yacht assertions.
|
||||||
expect(ctx.yacht.name).toBe('Sea Breeze');
|
expect(ctx.yacht?.name).toBe('Sea Breeze');
|
||||||
expect(ctx.yacht.hullNumber).toBe('HN-1');
|
expect(ctx.yacht?.hullNumber).toBe('HN-1');
|
||||||
expect(ctx.yacht.yearBuilt).toBe(2020);
|
expect(ctx.yacht?.yearBuilt).toBe(2020);
|
||||||
|
|
||||||
// Berth assertions.
|
// Berth assertions.
|
||||||
expect(ctx.berth.mooringNumber).toBe('M-42');
|
expect(ctx.berth?.mooringNumber).toBe('M-42');
|
||||||
expect(ctx.berth.area).toBe('North');
|
expect(ctx.berth?.area).toBe('North');
|
||||||
|
|
||||||
// Interest assertions.
|
// Interest assertions.
|
||||||
expect(ctx.interest.stage).toBe('in_communication');
|
expect(ctx.interest.stage).toBe('in_communication');
|
||||||
@@ -144,6 +171,7 @@ describe('buildEoiContext', () => {
|
|||||||
portId: port.id,
|
portId: port.id,
|
||||||
overrides: { fullName: 'Bob Contact' },
|
overrides: { fullName: 'Bob Contact' },
|
||||||
});
|
});
|
||||||
|
await seedClientEoiPrereqs({ clientId: client.id, portId: port.id });
|
||||||
|
|
||||||
const yacht = await makeYacht({
|
const yacht = await makeYacht({
|
||||||
portId: port.id,
|
portId: port.id,
|
||||||
@@ -187,6 +215,7 @@ describe('buildEoiContext', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const client = await makeClient({ portId: port.id });
|
const client = await makeClient({ portId: port.id });
|
||||||
|
await seedClientEoiPrereqs({ clientId: client.id, portId: port.id });
|
||||||
const yacht = await makeYacht({
|
const yacht = await makeYacht({
|
||||||
portId: port.id,
|
portId: port.id,
|
||||||
ownerType: 'company',
|
ownerType: 'company',
|
||||||
@@ -211,9 +240,10 @@ describe('buildEoiContext', () => {
|
|||||||
expect(ctx.company!.billingAddress).toContain('Anguilla');
|
expect(ctx.company!.billingAddress).toContain('Anguilla');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('throws ValidationError when interest has no yacht', async () => {
|
it('builds a valid context when yacht is missing (Section 3 left blank)', async () => {
|
||||||
const port = await makePort();
|
const port = await makePort();
|
||||||
const client = await makeClient({ portId: port.id });
|
const client = await makeClient({ portId: port.id });
|
||||||
|
await seedClientEoiPrereqs({ clientId: client.id, portId: port.id });
|
||||||
const berth = await makeBerth({ portId: port.id });
|
const berth = await makeBerth({ portId: port.id });
|
||||||
|
|
||||||
const interest = await insertInterest({
|
const interest = await insertInterest({
|
||||||
@@ -223,13 +253,18 @@ describe('buildEoiContext', () => {
|
|||||||
berthId: berth.id,
|
berthId: berth.id,
|
||||||
});
|
});
|
||||||
|
|
||||||
await expect(buildEoiContext(interest.id, port.id)).rejects.toThrow(ValidationError);
|
const ctx = await buildEoiContext(interest.id, port.id);
|
||||||
await expect(buildEoiContext(interest.id, port.id)).rejects.toThrow(/interest has no yacht/i);
|
expect(ctx.yacht).toBeNull();
|
||||||
|
expect(ctx.berth?.mooringNumber).toBe(berth.mooringNumber);
|
||||||
|
// Owner falls back to the interest's client when no yacht is linked.
|
||||||
|
expect(ctx.owner.type).toBe('client');
|
||||||
|
expect(ctx.owner.name).toBe(client.fullName);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('throws ValidationError when interest has no berth', async () => {
|
it('builds a valid context when berth is missing (Section 3 left blank)', async () => {
|
||||||
const port = await makePort();
|
const port = await makePort();
|
||||||
const client = await makeClient({ portId: port.id });
|
const client = await makeClient({ portId: port.id });
|
||||||
|
await seedClientEoiPrereqs({ clientId: client.id, portId: port.id });
|
||||||
const yacht = await makeYacht({
|
const yacht = await makeYacht({
|
||||||
portId: port.id,
|
portId: port.id,
|
||||||
ownerType: 'client',
|
ownerType: 'client',
|
||||||
@@ -243,8 +278,45 @@ describe('buildEoiContext', () => {
|
|||||||
berthId: null,
|
berthId: null,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const ctx = await buildEoiContext(interest.id, port.id);
|
||||||
|
expect(ctx.berth).toBeNull();
|
||||||
|
expect(ctx.yacht?.name).toBe(yacht.name);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws ValidationError when client has no email', async () => {
|
||||||
|
const port = await makePort();
|
||||||
|
const client = await makeClient({ portId: port.id });
|
||||||
|
// Address only, no email — gate should fail.
|
||||||
|
await db.insert(clientAddresses).values({
|
||||||
|
clientId: client.id,
|
||||||
|
portId: port.id,
|
||||||
|
streetAddress: '1 Harbour Way',
|
||||||
|
city: 'Anguilla',
|
||||||
|
countryIso: 'AI',
|
||||||
|
isPrimary: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const interest = await insertInterest({ portId: port.id, clientId: client.id });
|
||||||
|
|
||||||
await expect(buildEoiContext(interest.id, port.id)).rejects.toThrow(ValidationError);
|
await expect(buildEoiContext(interest.id, port.id)).rejects.toThrow(ValidationError);
|
||||||
await expect(buildEoiContext(interest.id, port.id)).rejects.toThrow(/interest has no berth/i);
|
await expect(buildEoiContext(interest.id, port.id)).rejects.toThrow(/client email/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws ValidationError when client has no primary address', async () => {
|
||||||
|
const port = await makePort();
|
||||||
|
const client = await makeClient({ portId: port.id });
|
||||||
|
// Email only, no address — gate should fail.
|
||||||
|
await db.insert(clientContacts).values({
|
||||||
|
clientId: client.id,
|
||||||
|
channel: 'email',
|
||||||
|
value: 'test@example.com',
|
||||||
|
isPrimary: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const interest = await insertInterest({ portId: port.id, clientId: client.id });
|
||||||
|
|
||||||
|
await expect(buildEoiContext(interest.id, port.id)).rejects.toThrow(ValidationError);
|
||||||
|
await expect(buildEoiContext(interest.id, port.id)).rejects.toThrow(/client address/i);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('throws NotFoundError for non-existent interest', async () => {
|
it('throws NotFoundError for non-existent interest', async () => {
|
||||||
|
|||||||
Reference in New Issue
Block a user