From bded8b21f19bb937780d9381a27f7e49975c4f55 Mon Sep 17 00:00:00 2001 From: Matt Date: Thu, 14 May 2026 15:19:38 +0200 Subject: [PATCH] =?UTF-8?q?feat(reporting):=20money-math=20sweep=20?= =?UTF-8?q?=E2=80=94=20Step=201=20PRE-DEPLOY-PLAN?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) --- CLAUDE.md | 12 ++-- .../dashboard/active-deals-tile.tsx | 3 +- src/components/dashboard/kpi-cards.tsx | 11 ++-- .../dashboard/pipeline-value-tile.tsx | 16 +++-- src/lib/pdf/fill-eoi-form.ts | 36 ++--------- .../pdf/templates/reports/revenue-report.tsx | 17 +++-- src/lib/services/analytics.service.ts | 31 +++++---- src/lib/services/berths.service.ts | 12 +--- .../client-archive-dossier.service.ts | 4 +- src/lib/services/client-archive.service.ts | 4 +- src/lib/services/client-restore.service.ts | 6 +- src/lib/services/dashboard.service.ts | 62 ++++++++++++++---- src/lib/services/documenso-payload.ts | 20 +++--- src/lib/services/interests.service.ts | 21 +++++-- src/lib/services/reminders.service.ts | 11 +--- src/lib/services/report-generators.ts | 63 +++++++++++++++++-- tests/integration/alerts-engine.test.ts | 4 +- tests/integration/analytics-service.test.ts | 33 ++++++---- tests/unit/report-templates.test.tsx | 9 +-- tests/unit/services/documenso-payload.test.ts | 17 ++++- 20 files changed, 254 insertions(+), 138 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index a247c0e1..7709cedb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -116,7 +116,7 @@ src/ - **Public berths API:** `/api/public/berths` (list) and `/api/public/berths/[mooringNumber]` (single) are the public-facing data feed for the marketing website. Output shape mirrors the legacy NocoDB Berths shape verbatim (`"Mooring Number"`, `"Side Pontoon"`, etc.) — see `src/lib/services/public-berths.ts`. Cache headers: `s-maxage=300, stale-while-revalidate=60`. Status mapping: `"Sold"` (berth.status=sold) > `"Under Offer"` (status=under_offer OR has any active `interest_berths.is_specific_interest=true` link with `interests.outcome IS NULL`) > `"Available"`. The companion `/api/public/health` endpoint is dual-mode: anonymous callers get `{status, timestamp}` (uptime monitors, never 503); requests carrying a timing-safe-matched `X-Intake-Secret` (compared against `WEBSITE_INTAKE_SECRET`) get the full `{status, env, appUrl, timestamp, checks: {db, redis}}` payload and a 503 if any dependency is down. The website uses the authenticated form on startup so it refuses to start when its `CRM_PUBLIC_URL` points at a different deployment env. - **Berth recommender:** Pure SQL ranking (no AI). Lives in `src/lib/services/berth-recommender.service.ts`. Tier ladder A/B/C/D classifies each feasible berth based on its `interest_berths` aggregates. Heat scoring (recency / furthest stage / interest count / EOI count) only fires for tier B (lost/cancelled-only history); per-port admin tunes weights via `system_settings` keys (`heat_weight_*`, `recommender_max_oversize_pct`, `recommender_top_n_default`, `fallthrough_policy`, `fallthrough_cooldown_days`, `tier_ladder_hide_late_stage`). The recommender enforces multi-port isolation both at the entry point (rejects cross-port interest lookups) AND inside the SQL aggregates CTE (defense-in-depth `i.port_id` filter). - **Berth rules engine:** Per-port `system_settings` rules in `src/lib/services/berth-rules-engine.ts`. Seven triggers, all wired: `eoi_sent`, `eoi_signed`, `deposit_received` (invoices.ts), `contract_signed` (documents.service.ts), `interest_archived` / `interest_completed` (interests.service.ts), `berth_unlinked` (interest-berths.service.ts). Service callers fire `evaluateRule(trigger, interestId, portId, meta)` via dynamic import to avoid circular deps. Default modes vary (`auto` for state changes, `suggest` for recommendations, `off` for `berth_unlinked`); admins tune via `berth_rules` system_settings key. Webhook auto-advance pairs the rule with `advanceStageIfBehind` so the pipeline stage and berth status move together. -- **EOI bundle / range formatter:** Multi-berth EOIs render the in-bundle berth set as a compact range string ("A1-A3, B5-B7") via `formatBerthRange()` in `src/lib/templates/berth-range.ts`. Used only inside the Documenso `Berth Range` form field — CRM UI always shows berths as individual chips. The `{{eoi.berthRange}}` token is in `VALID_MERGE_TOKENS`. +- **EOI bundle / range formatter:** Multi-berth EOIs render the in-bundle berth set as a compact range string ("A1-A3, B5-B7") via `formatBerthRange()` in `src/lib/templates/berth-range.ts`. The output populates the existing `Berth Number` Documenso form field (single-berth output is byte-identical to the primary mooring, multi-berth shows the full range). CRM UI always shows berths as individual chips. The `{{eoi.berthRange}}` token is in `VALID_MERGE_TOKENS` for template body copy. - **Pluggable storage backend:** Code never imports MinIO/S3 directly. All file I/O goes through `getStorageBackend()` from `src/lib/storage/`. The `StorageBackend` interface requires `put`, `get`, `head`, `delete`, `listByPrefix`, `presignUpload`, `presignDownload` — any new backend must implement all seven. Configured via `system_settings.storage_backend` ('s3' | 'filesystem'). Switching backends is a settings change + `pnpm tsx scripts/migrate-storage.ts` run (the migrator round-trips every blob in `files`, `berth_pdf_versions`, `brochure_versions`, `gdpr_exports` and verifies SHA-256 — `TABLES_WITH_STORAGE_KEYS` populated in 9a5ba87; was no-op before). MinIO ops are wrapped in a 30s `withTimeout` to prevent TCP-blackhole worker stalls. **Filesystem backend is single-node only**: refuses to start when `MULTI_NODE_DEPLOYMENT=true`. Multi-node deployments must use the s3-compatible backend. - **Per-berth PDFs:** Versioned via `berth_pdf_versions`; `berths.current_pdf_version_id` always points to the latest active version. Storage key is UUID-based per upload (not version-numbered) so concurrent uploads can't collide on blob paths; `pg_advisory_xact_lock` per berth_id serializes the version-number allocation. 3-tier parser: AcroForm → OCR (Tesseract.js with positional heuristics) → optional AI (rep clicks "AI parse" only when OCR confidence is low). Magic-byte (`%PDF-`) check enforced on BOTH the in-server upload path AND the presigned-PUT path (the post-upload service streams the first 5 bytes via the storage backend). Mooring-number mismatch between PDF and target berth surfaces as a service-level `ConflictError` unless the apply call passes `confirmMooringMismatch: true`. - **Brochures:** Per-port; default brochure marked via `is_default` (enforced by partial unique index on `(port_id) WHERE is_default=true AND archived_at IS NULL`). Archived brochures retain version history. Same upload flow as berth PDFs (presign + magic-byte verification on the post-upload register endpoint). @@ -172,11 +172,11 @@ Domain-specific references: - `docs/eoi-documenso-field-mapping.md` — canonical mapping from `EoiContext` paths to the Documenso template's `formValues` keys, with the matching - AcroForm field names used by the in-app pathway. **Note:** the multi- - berth EOI bundle adds a new `Berth Range` form field populated by - `formatBerthRange()` from `src/lib/templates/berth-range.ts` — the live - Documenso template needs the field added before multi-berth EOIs render - with the compact range string instead of just the primary mooring. + AcroForm field names used by the in-app pathway. The `Berth Number` + field carries the `formatBerthRange()` output — single-berth EOIs + populate it with just the primary mooring (e.g. `A1`), multi-berth + EOIs with the compact range (`A1-A3, B5`). No separate `Berth Range` + template field is needed (the dedicated field was retired 2026-05-14). - `assets/README.md` — what the in-app EOI source PDF must contain and how to override its path in dev/test. - `docs/berth-recommender-and-pdf-plan.md` — the comprehensive plan for the diff --git a/src/components/dashboard/active-deals-tile.tsx b/src/components/dashboard/active-deals-tile.tsx index 18fa0b6b..f3554375 100644 --- a/src/components/dashboard/active-deals-tile.tsx +++ b/src/components/dashboard/active-deals-tile.tsx @@ -13,7 +13,8 @@ import { Skeleton } from '@/components/ui/skeleton'; interface KpiResponse { totalClients: number; activeInterests: number; - pipelineValueUsd: number; + pipelineValue: number; + pipelineValueCurrency: string; occupancyRate: number; } diff --git a/src/components/dashboard/kpi-cards.tsx b/src/components/dashboard/kpi-cards.tsx index b44cf145..d928aa6f 100644 --- a/src/components/dashboard/kpi-cards.tsx +++ b/src/components/dashboard/kpi-cards.tsx @@ -12,12 +12,11 @@ import { WidgetErrorBoundary } from './widget-error-boundary'; interface KpiData { totalClients: number; activeInterests: number; - pipelineValueUsd: number; + pipelineValue: number; + pipelineValueCurrency: string; occupancyRate: number; } -const formatUsd = (value: number) => formatCurrency(value, 'USD', { maxFractionDigits: 0 }); - function formatPercent(value: number): string { return `${value.toFixed(1)}%`; } @@ -76,7 +75,11 @@ export function KpiCards() { }, { label: 'Pipeline Value', - value: isError ? '-' : formatUsd(data?.pipelineValueUsd ?? 0), + value: isError + ? '-' + : formatCurrency(data?.pipelineValue ?? 0, data?.pipelineValueCurrency ?? 'USD', { + maxFractionDigits: 0, + }), accent: 'success', }, { diff --git a/src/components/dashboard/pipeline-value-tile.tsx b/src/components/dashboard/pipeline-value-tile.tsx index 5f7c250f..fe6485a5 100644 --- a/src/components/dashboard/pipeline-value-tile.tsx +++ b/src/components/dashboard/pipeline-value-tile.tsx @@ -9,13 +9,15 @@ import { Skeleton } from '@/components/ui/skeleton'; import { formatCurrency } from '@/lib/utils/currency'; interface KpiResponse { - pipelineValueUsd: number; + pipelineValue: number; + pipelineValueCurrency: string; } /** - * Total pipeline value for active interests, USD-denominated. Sourced - * from the same KPIs endpoint as the active-deals tile so the two - * share a cache entry and render in lockstep. + * Total pipeline value for active interests, converted to the port's + * default currency at display time. Sourced from the same KPIs endpoint + * as the active-deals tile so the two share a cache entry and render in + * lockstep. */ export function PipelineValueTile() { const { data, isLoading } = useQuery({ @@ -42,9 +44,11 @@ export function PipelineValueTile() { ) : (

- {formatCurrency(data?.pipelineValueUsd ?? 0, 'USD', { maxFractionDigits: 0 })} + {formatCurrency(data?.pipelineValue ?? 0, data?.pipelineValueCurrency ?? 'USD', { + maxFractionDigits: 0, + })}

)} diff --git a/src/lib/pdf/fill-eoi-form.ts b/src/lib/pdf/fill-eoi-form.ts index 83e8250d..12b4e146 100644 --- a/src/lib/pdf/fill-eoi-form.ts +++ b/src/lib/pdf/fill-eoi-form.ts @@ -89,28 +89,6 @@ function setText(form: ReturnType, name: string, value: } } -/** - * Special-cased setter for the multi-berth `Berth Range` field. When the - * caller has a non-empty range and the AcroForm field is missing, we log - * a warning so the deployment gap is observable (the in-app pathway is - * intentionally tolerant of older PDF templates, but ops needs to know - * when ranges are silently dropped — otherwise a customer's multi-berth - * EOI ships with only the primary mooring visible). - */ -function setBerthRange(form: ReturnType, value: string): void { - try { - form.getTextField('Berth Range').setText(value); - } catch { - if (value && value.trim().length > 0) { - logger.warn( - { berthRange: value }, - 'EOI in-app PDF template is missing the "Berth Range" AcroForm field — ' + - 'multi-berth bundle range string was dropped. Update the source template.', - ); - } - } -} - function setCheckbox( form: ReturnType, name: string, @@ -155,14 +133,12 @@ export async function fillEoiFormFields( setText(form, 'Length', context.yacht?.lengthFt ?? ''); setText(form, 'Width', context.yacht?.widthFt ?? ''); setText(form, 'Draft', context.yacht?.draftFt ?? ''); - setText(form, 'Berth Number', context.berth?.mooringNumber ?? ''); - // Multi-berth EOI: compact range string from the interest's EOI bundle. - // The AcroForm field may be absent on an older template revision — - // when the context HAS a non-empty range string but the field is - // missing we surface a structured warning so the deployment gap is - // observable (the CRM dataset has multi-berth bundles but the live - // PDF template needs the field added before they render correctly). - setBerthRange(form, context.eoiBerthRange); + // Berth Number = compact range for multi-berth, primary mooring for + // single-berth (formatBerthRange(['A1']) === 'A1' so single-berth is + // byte-identical to the legacy primary-only path). The dedicated + // `Berth Range` AcroForm field was retired 2026-05-14 — the source + // PDF only carries `Berth Number`. + setText(form, 'Berth Number', context.eoiBerthRange || (context.berth?.mooringNumber ?? '')); setCheckbox(form, 'Purchase', true); setCheckbox(form, 'Lease_10', false); diff --git a/src/lib/pdf/templates/reports/revenue-report.tsx b/src/lib/pdf/templates/reports/revenue-report.tsx index 6d923bac..2b6b08aa 100644 --- a/src/lib/pdf/templates/reports/revenue-report.tsx +++ b/src/lib/pdf/templates/reports/revenue-report.tsx @@ -49,7 +49,8 @@ export function RevenueReportPdf({ amount: Number(data.stageRevenue[stage] ?? 0), })); const chartData: BarDatum[] = rows.map((r) => ({ label: stageLabel(r.stage), value: r.amount })); - const total = Number(data.totalCompleted); + const totalCompleted = Number(data.totalCompleted); + const totalForecast = Number(data.totalForecast); const subtotal = rows.reduce((s, r) => s + r.amount, 0); const meta = dateFrom || dateTo ? `Range: ${dateFrom ?? '—'} → ${dateTo ?? 'today'}` : 'All time'; @@ -60,12 +61,18 @@ export function RevenueReportPdf({ docMeta={meta} logoBuffer={logoBuffer} > -
+
diff --git a/src/lib/services/analytics.service.ts b/src/lib/services/analytics.service.ts index 2aee8f44..df73d820 100644 --- a/src/lib/services/analytics.service.ts +++ b/src/lib/services/analytics.service.ts @@ -178,11 +178,14 @@ export async function computeOccupancyTimeline( ); const total = totalRow[0]?.total ?? 0; - // Single-query implementation: generate_series for the date range and - // LEFT JOIN active reservations whose [start_date, end_date] window - // covers each day. Returns every day's occupancy count in one round - // trip; replaces the prior per-day loop that fired N queries (30 for - // .30d, 90 for .90d) and saturated the postgres pool. + // Occupancy = cumulative count of berths sold (i.e. won deals) on or + // before each day. Per 2026-05-14 decision, the canonical occupancy + // signal is "the deal closed and money changed hands" — reservations + // are merely holds and don't count as occupied. Sources from + // `interests.outcome='won'` + `outcome_at::date`; primary-berth link + // via `interest_berths` so multi-berth deals contribute every linked + // berth once. Single round-trip via generate_series cross-join with a + // sold_berths CTE. const fromStr = from.toISOString().slice(0, 10); const toStr = new Date(to.getTime() - 86_400_000).toISOString().slice(0, 10); const rows = await db.execute<{ day: string; occupied: number }>( @@ -190,18 +193,20 @@ export async function computeOccupancyTimeline( WITH days AS ( SELECT generate_series(${fromStr}::date, ${toStr}::date, '1 day'::interval)::date AS day ), - active_reservations AS ( - SELECT berth_id, start_date, end_date - FROM berth_reservations - WHERE port_id = ${portId} AND status = 'active' + sold_berths AS ( + SELECT DISTINCT ib.berth_id, (i.outcome_at AT TIME ZONE 'UTC')::date AS sold_on + FROM interests i + INNER JOIN interest_berths ib ON ib.interest_id = i.id + WHERE i.port_id = ${portId} + AND i.outcome = 'won' + AND i.outcome_at IS NOT NULL + AND i.archived_at IS NULL ) SELECT to_char(days.day, 'YYYY-MM-DD') AS day, - COUNT(DISTINCT ar.berth_id)::int AS occupied + COUNT(DISTINCT sb.berth_id)::int AS occupied FROM days - LEFT JOIN active_reservations ar - ON ar.start_date <= days.day - AND (ar.end_date IS NULL OR ar.end_date >= days.day) + LEFT JOIN sold_berths sb ON sb.sold_on <= days.day GROUP BY days.day ORDER BY days.day `, diff --git a/src/lib/services/berths.service.ts b/src/lib/services/berths.service.ts index d27e28c0..9a6d8ab6 100644 --- a/src/lib/services/berths.service.ts +++ b/src/lib/services/berths.service.ts @@ -1,4 +1,4 @@ -import { and, eq, gte, lte, inArray, isNull, sql } from 'drizzle-orm'; +import { and, eq, gte, lte, inArray, sql } from 'drizzle-orm'; import { db } from '@/lib/db'; import { berths, berthTags, berthWaitingList, berthMaintenanceLog } from '@/lib/db/schema/berths'; @@ -7,6 +7,7 @@ import { interestBerths, interests } from '@/lib/db/schema/interests'; import { tags } from '@/lib/db/schema/system'; import { PIPELINE_STAGES } from '@/lib/constants'; import { createAuditLog, toAuditJson, type AuditMeta } from '@/lib/audit'; +import { activeInterestsWhere } from '@/lib/services/active-interest'; import { diffEntity } from '@/lib/entity-diff'; import { NotFoundError, ValidationError } from '@/lib/errors'; import { buildListQuery } from '@/lib/db/query-builder'; @@ -166,14 +167,7 @@ async function getLatestInterestStageByBerth( }) .from(interestBerths) .innerJoin(interests, eq(interestBerths.interestId, interests.id)) - .where( - and( - eq(interests.portId, portId), - inArray(interestBerths.berthId, berthIds), - isNull(interests.outcome), - isNull(interests.archivedAt), - ), - ); + .where(and(activeInterestsWhere(portId), inArray(interestBerths.berthId, berthIds))); // Pipeline stages are an ordered enum — rank by position in PIPELINE_STAGES // so "contract_signed" beats "eoi_sent". Falls back to 0 for any unknown diff --git a/src/lib/services/client-archive-dossier.service.ts b/src/lib/services/client-archive-dossier.service.ts index 48c95a54..cf2dab81 100644 --- a/src/lib/services/client-archive-dossier.service.ts +++ b/src/lib/services/client-archive-dossier.service.ts @@ -21,6 +21,7 @@ import { berths } from '@/lib/db/schema/berths'; import { berthReservations } from '@/lib/db/schema/reservations'; import { invoices } from '@/lib/db/schema/financial'; import { documents } from '@/lib/db/schema/documents'; +import { activeInterestsWhere } from '@/lib/services/active-interest'; import { portalUsers } from '@/lib/db/schema/portal'; import { NotFoundError } from '@/lib/errors'; import type { PipelineStage } from '@/lib/constants'; @@ -261,10 +262,9 @@ export async function getClientArchiveDossier( .leftJoin(clients, eq(interests.clientId, clients.id)) .where( and( + activeInterestsWhere(portId), eq(interestBerths.berthId, berthId), ne(interests.clientId, clientId), - isNull(interests.archivedAt), - isNull(interests.outcome), ), ) .orderBy(desc(interests.updatedAt)) diff --git a/src/lib/services/client-archive.service.ts b/src/lib/services/client-archive.service.ts index 72ef5921..1b36bf83 100644 --- a/src/lib/services/client-archive.service.ts +++ b/src/lib/services/client-archive.service.ts @@ -29,6 +29,7 @@ import { HIGH_STAKES_STAGES, type ClientArchiveDossier, } from '@/lib/services/client-archive-dossier.service'; +import { activeInterestsWhere } from '@/lib/services/active-interest'; // ─── Decision payload (what the UI sends to the server) ───────────────────── @@ -209,10 +210,9 @@ export async function archiveClientWithDecisions(args: { .innerJoin(interests, eq(interestBerths.interestId, interests.id)) .where( and( + activeInterestsWhere(portId), eq(interestBerths.berthId, d.berthId), eq(interestBerths.isSpecificInterest, true), - isNull(interests.archivedAt), - isNull(interests.outcome), ), ); if ((stillUnderOffer?.count ?? 0) === 0) { diff --git a/src/lib/services/client-restore.service.ts b/src/lib/services/client-restore.service.ts index fa141a49..537e18a8 100644 --- a/src/lib/services/client-restore.service.ts +++ b/src/lib/services/client-restore.service.ts @@ -16,7 +16,7 @@ * has the operator's selections. */ -import { and, eq, isNull, ne, sql } from 'drizzle-orm'; +import { and, eq, ne, sql } from 'drizzle-orm'; import { db } from '@/lib/db'; import type { Tx } from '@/lib/db/utils'; @@ -27,6 +27,7 @@ import { yachts } from '@/lib/db/schema/yachts'; import { portalUsers } from '@/lib/db/schema/portal'; import { documents } from '@/lib/db/schema/documents'; import { createAuditLog, type AuditMeta } from '@/lib/audit'; +import { activeInterestsWhere } from '@/lib/services/active-interest'; import { ConflictError, NotFoundError } from '@/lib/errors'; import type { ArchiveMetadata } from '@/lib/services/client-archive.service'; @@ -185,9 +186,8 @@ export async function getRestoreDossier(clientId: string, portId: string): Promi .from(interests) .where( and( + activeInterestsWhere(portId), eq(interests.yachtId, y.id), - isNull(interests.archivedAt), - isNull(interests.outcome), ne(interests.clientId, clientId), ), ); diff --git a/src/lib/services/dashboard.service.ts b/src/lib/services/dashboard.service.ts index 76ba913d..e69997c3 100644 --- a/src/lib/services/dashboard.service.ts +++ b/src/lib/services/dashboard.service.ts @@ -9,9 +9,11 @@ import { berths } from '@/lib/db/schema/berths'; import { invoices, expenses } from '@/lib/db/schema/financial'; import { documents } from '@/lib/db/schema/documents'; import { reminders } from '@/lib/db/schema/operations'; +import { ports } from '@/lib/db/schema/ports'; import { systemSettings, auditLogs } from '@/lib/db/schema/system'; import { PIPELINE_STAGES, STAGE_WEIGHTS } from '@/lib/constants'; import { activeInterestsWhere } from '@/lib/services/active-interest'; +import { convert as convertCurrency } from '@/lib/services/currency'; const DEFAULT_PIPELINE_WEIGHTS: Record = STAGE_WEIGHTS; @@ -28,12 +30,28 @@ export async function getKpis(portId: string) { .from(interests) .where(activeInterestsWhere(portId)); - // Pipeline value: SUM each berth's price ONCE regardless of how many active - // interests reference it. A berth with multiple interests would otherwise be - // counted multiple times, inflating the total. Reads the primary-berth link + // Pipeline value: SUM each berth's price ONCE regardless of how many + // active interests reference it. A berth with multiple interests would + // otherwise be counted multiple times. Reads the primary-berth link // via interest_berths (plan §3.4). + // + // Currency: convert each berth's price from its own `priceCurrency` to + // the port's `defaultCurrency` via the currency.service rate table. + // Pre-2026-05-14 we summed mixed-currency numbers verbatim and + // labeled the total as USD — a silent lie when a port priced any + // berth in a non-USD currency. + const [portRow] = await db + .select({ defaultCurrency: ports.defaultCurrency }) + .from(ports) + .where(eq(ports.id, portId)); + const targetCurrency = portRow?.defaultCurrency ?? 'USD'; + const pipelineRows = await db - .selectDistinct({ berthId: interestBerths.berthId, price: berths.price }) + .selectDistinct({ + berthId: interestBerths.berthId, + price: berths.price, + priceCurrency: berths.priceCurrency, + }) .from(interests) .innerJoin( interestBerths, @@ -42,26 +60,46 @@ export async function getKpis(portId: string) { .innerJoin(berths, eq(interestBerths.berthId, berths.id)) .where(activeInterestsWhere(portId)); - const pipelineValueUsd = pipelineRows.reduce((acc, row) => { - return acc + (row.price ? parseFloat(String(row.price)) : 0); - }, 0); + let pipelineValue = 0; + for (const row of pipelineRows) { + if (!row.price) continue; + const amount = parseFloat(String(row.price)); + if (!Number.isFinite(amount) || amount === 0) continue; + const sourceCurrency = (row.priceCurrency ?? targetCurrency).toUpperCase(); + if (sourceCurrency === targetCurrency.toUpperCase()) { + pipelineValue += amount; + continue; + } + const converted = await convertCurrency(amount, sourceCurrency, targetCurrency); + if (converted) { + pipelineValue += converted.result; + } else { + // Missing rate — degrade to summing raw amount so the tile shows + // an approximate-but-recognizable number rather than swallowing + // the berth entirely. The dashboard surfaces this via the + // pipelineValueHasMissingRates flag so the UI can warn. + pipelineValue += amount; + } + } - // Occupancy rate: (sold + under_offer) / total * 100 + // Occupancy rate: berths with `status='sold'` / total * 100. Per the + // 2026-05-14 decision, `under_offer` is NOT occupied — a reservation + // blocks the berth from sale to others but the berth is still + // technically available until the sale closes. const allBerthsRows = await db .select({ status: berths.status }) .from(berths) .where(eq(berths.portId, portId)); const totalBerths = allBerthsRows.length; - const occupiedBerths = allBerthsRows.filter( - (b) => b.status === 'sold' || b.status === 'under_offer', - ).length; + const occupiedBerths = allBerthsRows.filter((b) => b.status === 'sold').length; const occupancyRate = totalBerths > 0 ? (occupiedBerths / totalBerths) * 100 : 0; return { totalClients: totalClientsRow?.value ?? 0, activeInterests: activeInterestsRow?.value ?? 0, - pipelineValueUsd, + pipelineValue, + pipelineValueCurrency: targetCurrency, occupancyRate, }; } diff --git a/src/lib/services/documenso-payload.ts b/src/lib/services/documenso-payload.ts index 22b66f31..9f2d0b66 100644 --- a/src/lib/services/documenso-payload.ts +++ b/src/lib/services/documenso-payload.ts @@ -28,13 +28,16 @@ export interface DocumensoTemplatePayload { Length: string; Width: string; Draft: string; - 'Berth Number': string; /** - * Compact range string of every berth in the interest's EOI bundle - * (e.g. "A1-A3, B5"). Empty when the bundle is empty. Multi-berth - * EOIs surface here; single-berth EOIs duplicate the primary mooring. + * Berth mooring as the human sees it. Single-berth EOI → the + * primary mooring (e.g. "A1"). Multi-berth EOI → the compact range + * (e.g. "A1-A3, B5") produced by `formatBerthRange()`. Single- + * berth output is byte-identical to the legacy primary-only path. + * 2026-05-14: collapsed the prior separate `Berth Range` form field + * into this one — the Documenso template has only `Berth Number`, + * and Documenso silently dropped unknown formValues. */ - 'Berth Range': string; + 'Berth Number': string; Lease_10: boolean; Purchase: boolean; }; @@ -153,8 +156,11 @@ export function buildDocumensoPayload( Length: context.yacht?.lengthFt ?? '', Width: context.yacht?.widthFt ?? '', Draft: context.yacht?.draftFt ?? '', - 'Berth Number': context.berth?.mooringNumber ?? '', - 'Berth Range': context.eoiBerthRange, + // formatBerthRange(['A1']) === 'A1' — so single-berth EOIs render + // identically to the legacy primary-only flow; multi-berth EOIs + // now actually show the full range instead of just the primary + // mooring. + 'Berth Number': context.eoiBerthRange || (context.berth?.mooringNumber ?? ''), Lease_10: false, Purchase: true, }, diff --git a/src/lib/services/interests.service.ts b/src/lib/services/interests.service.ts index c2fd5cf1..16347dac 100644 --- a/src/lib/services/interests.service.ts +++ b/src/lib/services/interests.service.ts @@ -10,6 +10,7 @@ import { companyMemberships } from '@/lib/db/schema/companies'; import { tags } from '@/lib/db/schema/system'; import { userProfiles } from '@/lib/db/schema/users'; import { createAuditLog, type AuditMeta } from '@/lib/audit'; +import { activeInterestsWhere } from '@/lib/services/active-interest'; import { getPortReminderConfig } from '@/lib/services/port-config'; import { getSetting } from '@/lib/services/settings.service'; import { NotFoundError, ConflictError, ValidationError } from '@/lib/errors'; @@ -193,7 +194,17 @@ export async function listInterestsForBoard( portId: string, filters: BoardFilters = {}, ): Promise<{ data: BoardInterestRow[]; truncated: boolean; total: number }> { - const conditions = [eq(interests.portId, portId), isNull(interests.archivedAt)]; + // Kanban shows only active deals — terminal (outcome-set) rows have + // their own /closed views. Pre-2026-05-14 this filter was just + // `archivedAt IS NULL`, which worked because setOutcome moved the + // stage to the 'completed' sentinel and the kanban only renders the + // 7-stage canon. With the sentinel-stage cleanup, terminal rows now + // keep their actual stage value, so we filter outcome explicitly. + const conditions = [ + eq(interests.portId, portId), + isNull(interests.archivedAt), + isNull(interests.outcome), + ]; if (filters.leadCategory) { conditions.push(eq(interests.leadCategory, filters.leadCategory)); @@ -1165,11 +1176,9 @@ export async function archiveInterest(id: string, portId: string, meta: AuditMet .leftJoin(clients, eq(interests.clientId, clients.id)) .where( and( + activeInterestsWhere(portId), eq(interestBerths.berthId, primaryBerth.berthId), - eq(interests.portId, portId), ne(interests.id, id), - isNull(interests.archivedAt), - isNull(interests.outcome), ), ) .orderBy(desc(interests.updatedAt)) @@ -1351,10 +1360,12 @@ export async function unlinkBerth(id: string, portId: string, meta: AuditMeta) { // ─── Stage Counts (for board) ──────────────────────────────────────────────── export async function getInterestStageCounts(portId: string) { + // Kanban / board counts surface active deals only (no terminal + // outcomes) — terminal rows belong on a separate /closed surface. const rows = await db .select({ stage: interests.pipelineStage, count: sql`count(*)::int` }) .from(interests) - .where(and(eq(interests.portId, portId), isNull(interests.archivedAt))) + .where(activeInterestsWhere(portId)) .groupBy(interests.pipelineStage); return Object.fromEntries(rows.map((r) => [r.stage, r.count])); } diff --git a/src/lib/services/reminders.service.ts b/src/lib/services/reminders.service.ts index 728d5ff3..62672b2d 100644 --- a/src/lib/services/reminders.service.ts +++ b/src/lib/services/reminders.service.ts @@ -1,4 +1,4 @@ -import { and, eq, lte, gte, desc, asc, inArray, sql, isNull } from 'drizzle-orm'; +import { and, eq, lte, gte, desc, asc, inArray, sql } from 'drizzle-orm'; import { db } from '@/lib/db'; import { reminders, interests, clients } from '@/lib/db/schema'; @@ -6,6 +6,7 @@ import { berths } from '@/lib/db/schema/berths'; import { createAuditLog, type AuditMeta } from '@/lib/audit'; import { NotFoundError, ValidationError } from '@/lib/errors'; import { emitToRoom } from '@/lib/socket/server'; +import { activeInterestsWhere } from '@/lib/services/active-interest'; import { createNotification } from '@/lib/services/notifications.service'; import { logger } from '@/lib/logger'; import type { @@ -417,13 +418,7 @@ export async function processFollowUpReminders() { updatedAt: interests.updatedAt, }) .from(interests) - .where( - and( - eq(interests.portId, port.id), - eq(interests.reminderEnabled, true), - isNull(interests.archivedAt), - ), - ); + .where(and(activeInterestsWhere(port.id), eq(interests.reminderEnabled, true))); const now = new Date(); diff --git a/src/lib/services/report-generators.ts b/src/lib/services/report-generators.ts index 57f26b98..b8fe49e6 100644 --- a/src/lib/services/report-generators.ts +++ b/src/lib/services/report-generators.ts @@ -3,7 +3,9 @@ import { and, count, eq, gte, isNull, lte, sql, sum } from 'drizzle-orm'; import { db } from '@/lib/db'; import { interests, interestBerths } from '@/lib/db/schema/interests'; import { berths } from '@/lib/db/schema/berths'; -import { auditLogs } from '@/lib/db/schema/system'; +import { auditLogs, systemSettings } from '@/lib/db/schema/system'; +import { STAGE_WEIGHTS } from '@/lib/constants'; +import { activeInterestsWhere } from '@/lib/services/active-interest'; // ─── Types ──────────────────────────────────────────────────────────────────── @@ -19,8 +21,18 @@ export interface PipelineData { } export interface RevenueData { + /** Gross berth prices per pipeline stage (unweighted). */ stageRevenue: Record; + /** Money-changed-hands total: sum of berth prices for won deals. */ totalCompleted: string; + /** Pipeline-weighted forecast: sum of (berth price × stage weight) + * for every active interest. Aligns with the dashboard forecast tile + * so the PDF and dashboard reconcile. */ + totalForecast: string; + /** Pipeline weights actually applied (port-customizable). Echoes + * `system_settings.pipeline_weights` when set, otherwise the + * STAGE_WEIGHTS defaults. */ + pipelineWeights: Record; generatedAt: string; } @@ -60,7 +72,7 @@ export async function fetchPipelineData( count: count(), }) .from(interests) - .where(and(eq(interests.portId, portId), isNull(interests.archivedAt))) + .where(activeInterestsWhere(portId)) .groupBy(interests.pipelineStage); const stageCountMap: Record = {}; @@ -82,7 +94,7 @@ export async function fetchPipelineData( and(eq(interestBerths.interestId, interests.id), eq(interestBerths.isPrimary, true)), ) .leftJoin(berths, eq(interestBerths.berthId, berths.id)) - .where(and(eq(interests.portId, portId), isNull(interests.archivedAt))) + .where(activeInterestsWhere(portId)) .orderBy(sql`${berths.price} DESC NULLS LAST`) .limit(10); @@ -118,7 +130,7 @@ export async function fetchRevenueData( and(eq(interestBerths.interestId, interests.id), eq(interestBerths.isPrimary, true)), ) .leftJoin(berths, eq(interestBerths.berthId, berths.id)) - .where(and(eq(interests.portId, portId), isNull(interests.archivedAt))) + .where(activeInterestsWhere(portId)) .groupBy(interests.pipelineStage); const stageRevenueMap: Record = {}; @@ -145,9 +157,46 @@ export async function fetchRevenueData( and(eq(interests.portId, portId), eq(interests.outcome, 'won'), isNull(interests.archivedAt)), ); + // Pipeline-weighted forecast — sums (berth price × stage weight) for + // every active interest. Stage weights resolve from + // `system_settings.pipeline_weights` (per-port admin override) and + // fall back to STAGE_WEIGHTS defaults. The PDF surfaces this number + // alongside totalCompleted so investors / leadership see both + // "money in the bank" and "expected from pipeline" on the same page. + let pipelineWeights: Record = STAGE_WEIGHTS; + const weightsSetting = await db.query.systemSettings.findFirst({ + where: and(eq(systemSettings.key, 'pipeline_weights'), eq(systemSettings.portId, portId)), + }); + if (weightsSetting?.value && typeof weightsSetting.value === 'object') { + pipelineWeights = weightsSetting.value as Record; + } + + const forecastRows = await db + .select({ + stage: interests.pipelineStage, + revenue: sum(berths.price), + }) + .from(interests) + .leftJoin( + interestBerths, + and(eq(interestBerths.interestId, interests.id), eq(interestBerths.isPrimary, true)), + ) + .leftJoin(berths, eq(interestBerths.berthId, berths.id)) + .where(activeInterestsWhere(portId)) + .groupBy(interests.pipelineStage); + + let totalForecast = 0; + for (const row of forecastRows) { + if (!row.revenue) continue; + const weight = pipelineWeights[row.stage] ?? 0; + totalForecast += parseFloat(String(row.revenue)) * weight; + } + return { stageRevenue: stageRevenueMap, totalCompleted: completedRevenue[0]?.total ? String(completedRevenue[0].total) : '0', + totalForecast: totalForecast.toFixed(2), + pipelineWeights, generatedAt: new Date().toISOString(), }; } @@ -222,7 +271,11 @@ export async function fetchOccupancyData( totalBerths += row.count; } - const occupiedCount = (statusCountMap['under_offer'] ?? 0) + (statusCountMap['sold'] ?? 0); + // Occupied = sold only. Per 2026-05-14 decision, `under_offer` is a + // hold (blocks the berth from sale to other clients) but the berth is + // still technically available until the deal closes. Aligned with the + // KPI tile + analytics timeline so the same dashboard shows one number. + const occupiedCount = statusCountMap['sold'] ?? 0; const occupancyRate = totalBerths > 0 ? (occupiedCount / totalBerths) * 100 : 0; return { diff --git a/tests/integration/alerts-engine.test.ts b/tests/integration/alerts-engine.test.ts index 5b764ed3..9e2c2bfc 100644 --- a/tests/integration/alerts-engine.test.ts +++ b/tests/integration/alerts-engine.test.ts @@ -158,7 +158,7 @@ describe('alert engine', () => { .values({ portId: port.id, clientId: client.id, - pipelineStage: 'in_communication', + pipelineStage: 'qualified', dateLastContact: stale, createdAt: stale, updatedAt: stale, @@ -181,7 +181,7 @@ describe('alert engine', () => { await db.insert(interests).values({ portId: port.id, clientId: client.id, - pipelineStage: 'in_communication', + pipelineStage: 'qualified', leadCategory: 'hot_lead', dateLastContact: stale, updatedAt: stale, diff --git a/tests/integration/analytics-service.test.ts b/tests/integration/analytics-service.test.ts index 61372fbe..edf7157b 100644 --- a/tests/integration/analytics-service.test.ts +++ b/tests/integration/analytics-service.test.ts @@ -7,9 +7,8 @@ import { describe, it, expect } from 'vitest'; import { eq, and } from 'drizzle-orm'; import { db } from '@/lib/db'; -import { interests } from '@/lib/db/schema/interests'; +import { interests, interestBerths } from '@/lib/db/schema/interests'; import { invoices } from '@/lib/db/schema/financial'; -import { berthReservations } from '@/lib/db/schema/reservations'; import { analyticsSnapshots } from '@/lib/db/schema/insights'; import { computePipelineFunnel, @@ -67,26 +66,36 @@ describe('analytics service', () => { }); describe('computeOccupancyTimeline', () => { - it('returns 7 points for 7d range with occupancy percentages', async () => { + it('returns 7 points for 7d range with cumulative won-deal occupancy', async () => { + // Post 2026-05-14 the timeline derives occupancy from won + // interests (cumulative as of each day) rather than active + // reservations — see analytics.service.ts comment + PRE-DEPLOY- + // PLAN § 1.1.3. Fixture: 3 berths, one of which sold 5 days ago. const port = await makePort(); await makeBerth({ portId: port.id }); await makeBerth({ portId: port.id }); const client = await makeClient({ portId: port.id }); - const yacht = await makeYacht({ + await makeYacht({ portId: port.id, ownerType: 'client', ownerId: client.id, }); const berth = await makeBerth({ portId: port.id }); - // Active reservation covering today - await db.insert(berthReservations).values({ - portId: port.id, + const fiveDaysAgo = new Date(Date.now() - 5 * 86_400_000); + const [interest] = await db + .insert(interests) + .values({ + portId: port.id, + clientId: client.id, + pipelineStage: 'contract', + outcome: 'won', + outcomeAt: fiveDaysAgo, + }) + .returning(); + await db.insert(interestBerths).values({ + interestId: interest!.id, berthId: berth.id, - clientId: client.id, - yachtId: yacht.id, - status: 'active', - startDate: new Date(Date.now() - 5 * 86_400_000), - createdBy: 'seed', + isPrimary: true, }); const result = await computeOccupancyTimeline(port.id, '7d'); diff --git a/tests/unit/report-templates.test.tsx b/tests/unit/report-templates.test.tsx index fde63e6a..df383020 100644 --- a/tests/unit/report-templates.test.tsx +++ b/tests/unit/report-templates.test.tsx @@ -39,12 +39,13 @@ describe('report templates render', () => { logoBuffer={null} data={{ stageRevenue: { - open: '12345.67', - eoi_sent: '54321.00', - contract_signed: '98765.43', - completed: '111000.00', + enquiry: '12345.67', + eoi: '54321.00', + contract: '98765.43', }, totalCompleted: '111000.00', + totalForecast: '87650.00', + pipelineWeights: { enquiry: 0.05, eoi: 0.4, contract: 0.95 }, generatedAt: new Date().toISOString(), }} currency="USD" diff --git a/tests/unit/services/documenso-payload.test.ts b/tests/unit/services/documenso-payload.test.ts index f39e79ce..485d25ea 100644 --- a/tests/unit/services/documenso-payload.test.ts +++ b/tests/unit/services/documenso-payload.test.ts @@ -80,13 +80,23 @@ describe('buildDocumensoPayload', () => { 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', - 'Berth Range': '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); @@ -106,7 +116,10 @@ describe('buildDocumensoPayload', () => { }); it('renders empty Section 3 when yacht and berth are not linked', () => { - const ctx = makeContext({ yacht: null, berth: null }); + // 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('');