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>
This commit is contained in:
@@ -13,7 +13,8 @@ import { Skeleton } from '@/components/ui/skeleton';
|
||||
interface KpiResponse {
|
||||
totalClients: number;
|
||||
activeInterests: number;
|
||||
pipelineValueUsd: number;
|
||||
pipelineValue: number;
|
||||
pipelineValueCurrency: string;
|
||||
occupancyRate: number;
|
||||
}
|
||||
|
||||
|
||||
@@ -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',
|
||||
},
|
||||
{
|
||||
|
||||
@@ -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<KpiResponse>({
|
||||
@@ -42,9 +44,11 @@ export function PipelineValueTile() {
|
||||
) : (
|
||||
<p
|
||||
className="truncate text-2xl font-bold leading-tight text-foreground"
|
||||
title={formatCurrency(data?.pipelineValueUsd ?? 0, 'USD')}
|
||||
title={formatCurrency(data?.pipelineValue ?? 0, data?.pipelineValueCurrency ?? 'USD')}
|
||||
>
|
||||
{formatCurrency(data?.pipelineValueUsd ?? 0, 'USD', { maxFractionDigits: 0 })}
|
||||
{formatCurrency(data?.pipelineValue ?? 0, data?.pipelineValueCurrency ?? 'USD', {
|
||||
maxFractionDigits: 0,
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -89,28 +89,6 @@ function setText(form: ReturnType<PDFDocument['getForm']>, 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<PDFDocument['getForm']>, 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<PDFDocument['getForm']>,
|
||||
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);
|
||||
|
||||
@@ -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}
|
||||
>
|
||||
<Section title="Summary">
|
||||
<Section
|
||||
title="Revenue summary"
|
||||
subtitle="Completed = money changed hands. Forecast = active pipeline weighted by stage probability."
|
||||
>
|
||||
<KeyValueGrid
|
||||
rows={[
|
||||
{ label: 'Total completed', value: fmtAmount(total, currency) },
|
||||
{ label: 'Pipeline value (open)', value: fmtAmount(subtotal - total, currency) },
|
||||
{ label: 'Total stages', value: rows.length },
|
||||
{ label: 'Completed revenue (won)', value: fmtAmount(totalCompleted, currency) },
|
||||
{
|
||||
label: 'Forecast revenue (pipeline-weighted)',
|
||||
value: fmtAmount(totalForecast, currency),
|
||||
},
|
||||
{ label: 'Pipeline value (open, gross)', value: fmtAmount(subtotal, currency) },
|
||||
{ label: 'Currency', value: currency },
|
||||
]}
|
||||
/>
|
||||
|
||||
@@ -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
|
||||
`,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -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<string, number> = 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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
|
||||
@@ -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<number>`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]));
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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<string, string>;
|
||||
/** 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<string, number>;
|
||||
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<string, number> = {};
|
||||
@@ -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<string, string> = {};
|
||||
@@ -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<string, number> = 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<string, number>;
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
Reference in New Issue
Block a user