Files
pn-new-crm/tests/unit/services/documenso-payload.test.ts
Matt bded8b21f1 feat(reporting): money-math sweep — Step 1 PRE-DEPLOY-PLAN
Single coherent commit completing § 1.1 (hot-path correctness) plus
§ 1.1.4.5 (multi-berth EOI mooring fix). Numbers users see are now
self-consistent across dashboard / kanban / hot deals / PDF reports.

## Active-interest sweep (canonical predicate everywhere)

Routed every "active interest" filter through `activeInterestsWhere`
(commit b966d81 helper). The helper enforces port-scoping + archivedAt
IS NULL + outcome IS NULL — strict definition, won is closed.

Touched sites:
- src/lib/services/reminders.service.ts:digestPort — no longer fires
  reminders for won/lost/cancelled deals
- src/lib/services/berths.service.ts:getLatestInterestStageByBerth
- src/lib/services/client-archive-dossier.service.ts (next-in-line
  others lookup)
- src/lib/services/client-archive.service.ts (remaining-under-offer
  recount before flipping berth back to available)
- src/lib/services/client-restore.service.ts (yacht-usage check)
- src/lib/services/interests.service.ts:listInterestsForBoard +
  getInterestStageCounts + the "others on same berth" lookup —
  kanban / board now exclude terminal deals
- src/lib/services/report-generators.ts: fetchPipelineData,
  fetchRevenueData stage breakdowns, top-N interests

## Pipeline-value currency conversion

`getKpis()` now fetches the port's defaultCurrency from `ports` and
converts each berth's `priceCurrency`→port-default via
`currency.service`. Returns `pipelineValue` + `pipelineValueCurrency`
instead of the lying `pipelineValueUsd`. Missing rates fall through to
raw amount summing (so the tile still shows an approximate number) —
behind a follow-up to surface a "rates incomplete" indicator.

3 consumers updated: KpiCards, PipelineValueTile, ActiveDealsTile.

## Occupancy = sold only

Both the dashboard KPI tile and the revenue-report PDF occupancy data
now count only `berth.status='sold'`. `under_offer` is a hold, not
occupation. The analytics timeline switches from
`berth_reservations`-derived to a cumulative-won-deals derivation via
`interests.outcome='won' AND outcome_at::date <= day` — same source of
truth, historical shape preserved.

## Revenue PDF two-card layout

Added `totalForecast` + `pipelineWeights` to `RevenueData`. Summary
section now renders both:
- "Completed revenue (won)"  — money in the bank
- "Forecast revenue (pipeline-weighted)" — expected pipeline value

Pipeline weights resolve from `system_settings.pipeline_weights`
(per-port admin override) and fall back to STAGE_WEIGHTS defaults. PDF
and dashboard forecast tiles reconcile.

## Multi-berth EOI mooring (4.5)

Documenso `Berth Number` form field now carries the formatBerthRange
output for BOTH single- and multi-berth EOIs. Single-berth output is
byte-identical to the legacy primary-only path
(`formatBerthRange(['A1']) === 'A1'`). Multi-berth EOIs now render
the full range ("A1-A3, B5") in the existing field instead of being
silently dropped against a nonexistent `Berth Range` field.

Dropped:
- `'Berth Range'` from the Documenso formValues payload + TS type
- `setBerthRange()` helper from fill-eoi-form.ts (now redundant)
- The "missing Berth Range AcroForm field" warning log

Updated CLAUDE.md to reflect — no Documenso admin template change
needed.

## Tests

- Updated `documenso-payload.test.ts` — new fixture asserts
  formatBerthRange output flows into Berth Number; multi-berth case
  added.
- Updated `analytics-service.test.ts:computeOccupancyTimeline` —
  fixture creates a won interest instead of a reservation.
- Updated `alerts-engine.test.ts:interest.stale` — fixture stage
  switched from dead `'in_communication'` to canonical `'qualified'`.
- Updated `report-templates.test.tsx:revenue` — fixture carries
  `totalForecast` + `pipelineWeights` to match new RevenueData.

1373/1373 vitest pass. tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:19:38 +02:00

239 lines
8.1 KiB
TypeScript

import { describe, it, expect } from 'vitest';
import { buildDocumensoPayload } from '@/lib/services/documenso-payload';
import type { EoiContext } from '@/lib/services/eoi-context';
function makeContext(overrides?: Partial<EoiContext>): EoiContext {
return {
client: {
id: 'client-fixture-1',
fullName: 'Alice Smith',
nationality: 'US',
primaryEmail: 'alice@example.com',
primaryPhone: '+1-555-0100',
address: { street: '123 Main St', city: 'Austin', country: 'USA' },
},
yacht: {
id: 'yacht-fixture-1',
name: 'Sea Breeze',
lengthFt: '45',
widthFt: '14',
draftFt: '6',
lengthM: null,
widthM: null,
draftM: null,
hullNumber: 'ABC-123',
flag: 'US',
yearBuilt: 2020,
},
company: null,
owner: { type: 'client', name: 'Alice Smith' },
berth: {
mooringNumber: 'A12',
area: 'North Dock',
lengthFt: '50',
price: '1200',
priceCurrency: 'USD',
tenureType: 'permanent',
},
eoiBerthRange: 'A12',
interest: {
stage: 'open',
leadCategory: null,
dateFirstContact: null,
notes: null,
},
port: {
name: 'Port Nimara',
defaultCurrency: 'USD',
},
date: { today: '2026-04-23', year: '2026' },
...overrides,
};
}
const OPTIONS = {
interestId: 'int-123',
clientRecipientId: 192,
developerRecipientId: 193,
approvalRecipientId: 194,
};
describe('buildDocumensoPayload', () => {
it('builds title as "{fullName}-EOI-NDA"', () => {
const payload = buildDocumensoPayload(makeContext(), OPTIONS);
expect(payload.title).toBe('Alice Smith-EOI-NDA');
});
it('builds externalId as "loi-{interestId}"', () => {
const payload = buildDocumensoPayload(makeContext(), OPTIONS);
expect(payload.externalId).toBe('loi-int-123');
});
it('formats formValues with all EoiContext fields', () => {
const payload = buildDocumensoPayload(makeContext(), OPTIONS);
expect(payload.formValues).toEqual({
Name: 'Alice Smith',
Email: 'alice@example.com',
Address: '123 Main St, Austin, USA',
'Yacht Name': 'Sea Breeze',
Length: '45',
Width: '14',
Draft: '6',
// Berth Number carries the formatBerthRange output — single-
// berth EOI duplicates the primary mooring; multi-berth shows
// the compact range. The separate 'Berth Range' formValue key
// was retired 2026-05-14 (the Documenso template never had
// that field, so the value was silently dropped).
'Berth Number': 'A12',
Lease_10: false,
Purchase: true,
});
});
it('renders Berth Number as the multi-berth range string when bundle has > 1', () => {
const ctx = makeContext({ eoiBerthRange: 'A1-A3, B5' });
const payload = buildDocumensoPayload(ctx, OPTIONS);
expect(payload.formValues['Berth Number']).toBe('A1-A3, B5');
});
it('defaults missing primaryEmail to empty string', () => {
const ctx = makeContext({ client: { ...makeContext().client, primaryEmail: null } });
const payload = buildDocumensoPayload(ctx, OPTIONS);
expect(payload.formValues.Email).toBe('');
expect(payload.recipients[0]!.email).toBe('');
});
it('defaults missing yacht dimensions to empty strings', () => {
const baseYacht = makeContext().yacht!;
const ctx = makeContext({
yacht: { ...baseYacht, lengthFt: null, widthFt: null, draftFt: null },
});
const payload = buildDocumensoPayload(ctx, OPTIONS);
expect(payload.formValues.Length).toBe('');
expect(payload.formValues.Width).toBe('');
expect(payload.formValues.Draft).toBe('');
});
it('renders empty Section 3 when yacht and berth are not linked', () => {
// Also explicitly clear the berth-range fallback that defaults to
// the primary mooring — when there's no berth AND no bundle, the
// form field renders as empty.
const ctx = makeContext({ yacht: null, berth: null, eoiBerthRange: '' });
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', () => {
const ctx = makeContext({ client: { ...makeContext().client, address: null } });
const payload = buildDocumensoPayload(ctx, OPTIONS);
expect(payload.formValues.Address).toBe('');
});
it('skips null parts in address', () => {
const ctx = makeContext({
client: {
...makeContext().client,
address: { street: '', city: 'Austin', country: 'USA' },
},
});
const payload = buildDocumensoPayload(ctx, OPTIONS);
expect(payload.formValues.Address).toBe('Austin, USA');
});
it('sets Lease_10=false and Purchase=true (hardcoded)', () => {
const payload = buildDocumensoPayload(makeContext(), OPTIONS);
expect(payload.formValues.Lease_10).toBe(false);
expect(payload.formValues.Purchase).toBe(true);
});
it('includes client, developer, and approver recipients in signing order', () => {
const payload = buildDocumensoPayload(makeContext(), OPTIONS);
expect(payload.recipients).toHaveLength(3);
expect(payload.recipients[0]).toEqual({
id: 192,
name: 'Alice Smith',
email: 'alice@example.com',
role: 'SIGNER',
signingOrder: 1,
});
expect(payload.recipients[1]).toEqual({
id: 193,
name: 'David Mizrahi',
email: 'dm@portnimara.com',
role: 'SIGNER',
signingOrder: 2,
});
expect(payload.recipients[2]).toEqual({
id: 194,
name: 'Abbie May',
email: 'sales@portnimara.com',
role: 'APPROVER',
signingOrder: 3,
});
});
it('allows overriding developer/approver recipient names', () => {
const payload = buildDocumensoPayload(makeContext(), {
...OPTIONS,
developerName: 'Custom Dev',
developerEmail: 'dev@custom.com',
approverName: 'Custom Approver',
approverEmail: 'approve@custom.com',
});
expect(payload.recipients[1]!.name).toBe('Custom Dev');
expect(payload.recipients[1]!.email).toBe('dev@custom.com');
expect(payload.recipients[2]!.name).toBe('Custom Approver');
expect(payload.recipients[2]!.email).toBe('approve@custom.com');
});
it('builds message with port name and greeting', () => {
const payload = buildDocumensoPayload(makeContext(), OPTIONS);
expect(payload.meta.message).toContain('Dear Alice Smith');
expect(payload.meta.message).toContain('Port Nimara');
expect(payload.meta.message).toContain('Best Regards');
// No company on-behalf block for client-owned yachts
expect(payload.meta.message).not.toContain('On behalf of');
});
it('adds company on-behalf block for company-owned yachts', () => {
const ctx = makeContext({
company: {
name: 'Aegean Holdings',
legalName: 'Aegean Holdings SA',
taxId: null,
billingAddress: null,
},
owner: { type: 'company', name: 'Aegean Holdings', legalName: 'Aegean Holdings SA' },
});
const payload = buildDocumensoPayload(ctx, OPTIONS);
expect(payload.meta.message).toContain('On behalf of Aegean Holdings SA');
});
it('uses company name when legalName is missing in on-behalf block', () => {
const ctx = makeContext({
company: { name: 'Blue Seas', legalName: null, taxId: null, billingAddress: null },
owner: { type: 'company', name: 'Blue Seas' },
});
const payload = buildDocumensoPayload(ctx, OPTIONS);
expect(payload.meta.message).toContain('On behalf of Blue Seas');
});
it('uses default redirect URL when not provided', () => {
const payload = buildDocumensoPayload(makeContext(), OPTIONS);
expect(payload.meta.redirectUrl).toBe('https://portnimara.com');
});
it('uses custom redirect URL when provided', () => {
const payload = buildDocumensoPayload(makeContext(), {
...OPTIONS,
redirectUrl: 'https://custom.example.com',
});
expect(payload.meta.redirectUrl).toBe('https://custom.example.com');
});
});