feat(audit-session): legacy-stage canonicalization + multi-berth label sweep + PDF/UI polish

Critical data-correctness fixes
- external-eoi.service: stage-advance list rewritten against canonical
  7-stage vocab (enquiry/qualified/nurturing → eoi). Was hardcoded to
  legacy 9-stage names (open/details_sent/in_communication/eoi_sent), so
  EOI uploads from 'qualified' silently skipped the stage flip. Now also
  writes eoiDocStatus='signed' alongside eoiStatus='signed'.
- public-interest.service + api/public/interests/route: pipelineStage
  'open' → 'enquiry' for new public interests.
- interests.service: legacy 'open' gate → 'enquiry'; inline-stage-picker
  comments updated.
- Display fallbacks canonicalized: dashboard.service, dashboard-report-data,
  pdf/templates/{interest,client}-summary, interest-picker, timeline route
  all route through canonicalizeStage / stageLabelFor.

Multi-berth interest label sweep
- New helper src/lib/templates/interest-berth-label.ts with 9 unit tests
  (deriveInterestBerthLabel reuses formatBerthRange + caps at 5 segments,
  falls back to 'first + N more').
- New batched aggregator getAllBerthMooringsForInterests on the
  interest-berths service.
- BoardInterestRow + listInterests + getInterest extended with
  berthMoorings: string[].
- Swept render sites: interest-detail-header, pipeline-card +
  pipeline-column (kanban), interest-columns (list), interest-card,
  interest-detail (breadcrumb), client-pipeline-summary +
  client-interests-tab, yacht-tabs, shared interest-picker.
- PDF report "New interests (in period)" Source column → Berth column.

Dashboard PDF report fixes
- Hardcoded EUR → reads ports.default_currency once at the top of
  resolveDashboardReportData. Falls back to USD.
- 'maintenance' berth-status bucket removed everywhere (wasn't in
  canonical BERTH_STATUSES); cleaned from dashboard.service,
  dashboard-report-data, occupancy-report, berth-status-chart, fixture.
- Berth demand ranking: dropped placeholder Tier column (resolver
  hardcoded 'A' — heat-tier never plumbed through).
- Deal pulse distribution: tier values capitalized (hot → Hot etc.).
- Validator widgetIds.max 20 → 40 (catalog has 25 entries; was throwing
  "Validation failed" when all sections checked).
- Export dialog: badges tightened (text-[8px] py-px whitespace-nowrap, no
  more 2-line wraps on "needs date range"); accepts initialRange?:
  DateRange so the dashboard's active range pre-fills dateFrom/dateTo via
  rangeToBounds.

Interest banner overcounts fix
- interest-berth-status-banner: filters out self-caused under-offer
  berths (where the only active deal touching the berth IS this same
  interest). Waits for all competing-queries before committing the
  count. Was showing "3 berths unavailable" when only 1 actually had a
  competitor.

Sessions list ordering
- sessions-list: client-side sort by lastAt desc + displays lastAt
  instead of firstAt so visible timestamp matches the sort key.

Audit log polish
- Details button: side Sheet → Popover anchored to the button (in-place
  inline dropdown). Works with the virtualized table.
- From/To date pickers: width w-44 → w-52, wrapper gap-3 → gap-x-4 gap-y-3.

EntityFolderView (Documents Hub entity view)
- Per-row Download button (hover-reveal icon).
- File-type icon prefix + tighter row layout.
- Per-row interest-berth badge: files.ts attaches interestBerthLabel via
  one batched getAllBerthMooringsForInterests call across all groups.
  AggregatedFile type + EntityFolderView render the badge linking back
  to the parent interest.

External EOI upload dialog
- Title input pre-fills from the derived default via controlled
  displayTitle = title || defaultTitle (no setState-in-effect).

EOI Generate dialog
- Success toast on mutation success.
- Primary berth's "Include in EOI" checkbox is now forced-on + disabled
  with tooltip: the primary IS the canonical "berth for this deal",
  excluding it is semantically nonsense.

Primary berth must always be in EOI bundle (service + backfill)
- interest-berths.service: insert path forces is_in_eoi_bundle=true
  whenever is_primary=true; update path coerces back to true when the
  caller tries to set false on a primary. Backfilled 7 existing rows.

Documenso redirect URL fallback
- port-config getPortDocumensoConfig: resolution chain extended to
  documenso_redirect_url → public_site_url → null. Operators with
  public_site_url configured (most ports) now get sensible signer
  landing without setting two settings.

World-map click → navigate
- website-analytics-shell: country click navigates to the nationality-
  filtered Clients page via router.push instead of copying a URL to
  clipboard.

Documents Hub: subfolder grid in main panel
- Subfolder cards rendered above the documents list when the current
  folder has children. Lets reps drill into subfolders from the main
  content area, not only via the sidebar tree.

Interest list initial sort
- usePaginatedQuery gains initialSort option (used when URL has no sort
  param). Interest list passes updatedAt desc so the table header
  surfaces the active sort visibly + most-recently-added/edited bubble
  to the top.

Interest auto-assign on create
- interests.service createInterest: three-tier owner resolution chain
  — explicit input → port's default_new_interest_owner setting →
  creator (when not super-admin). Super-admins skipped since they often
  create on behalf of other reps.

Backfills
- 12 interests with eoi_status='signed' + missing eoi_doc_status='signed'
  aligned.
- 7 interest_berths rows with is_primary=true but is_in_eoi_bundle=false
  flipped to true.

Verified
- pnpm tsc --noEmit: clean
- pnpm exec vitest run: 1463 / 1463 passed

Captured 25+ additional UAT findings to docs/superpowers/audits/alpha-uat-master.md
across all 4 buckets, including two OPEN QUESTIONS (Reservations module
re-imagine, Reports dedicated page promotion).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-24 20:41:27 +02:00
parent 70d1e7e9b2
commit 41737fa950
47 changed files with 905 additions and 269 deletions

View File

@@ -25,7 +25,6 @@ export interface DashboardReportData {
berthStatus?: {
available: number;
underOffer: number;
maintenance: number;
sold: number;
total: number;
};
@@ -119,7 +118,7 @@ export interface DashboardReportData {
newInterestsInPeriod?: Array<{
clientName: string;
stage: string;
source: string | null;
berthLabel: string | null;
createdAt: string;
}>;
/** Berths transitioned to Sold status during the report window. */
@@ -269,11 +268,6 @@ export function DashboardReport({
String(data.berthStatus.sold),
pct(data.berthStatus.sold, data.berthStatus.total),
],
[
'Maintenance',
String(data.berthStatus.maintenance),
pct(data.berthStatus.maintenance, data.berthStatus.total),
],
]}
/>
</View>
@@ -330,7 +324,6 @@ export function DashboardReport({
{ label: 'Available', value: data.berthStatus.available, color: '#0d9488' },
{ label: 'Under offer', value: data.berthStatus.underOffer, color: '#f59e0b' },
{ label: 'Sold', value: data.berthStatus.sold, color: '#0284c7' },
{ label: 'Maintenance', value: data.berthStatus.maintenance, color: '#94a3b8' },
]}
/>
</View>
@@ -535,17 +528,14 @@ export function DashboardReport({
data.berthDemandRanking.length > 0 ? (
<View wrap={false}>
<Text style={styles.sectionTitle}>Berth demand ranking</Text>
<Text style={styles.sectionSubtitle}>
Top berths by active-interest count + heat tier (A = strongest signal).
</Text>
<Text style={styles.sectionSubtitle}>Top berths by active-interest count.</Text>
<SimpleTable
styles={styles}
headers={['Mooring', 'Active interests', 'Tier']}
widths={[40, 40, 20]}
headers={['Mooring', 'Active interests']}
widths={[50, 50]}
rows={data.berthDemandRanking.map((row) => [
row.mooringNumber,
String(row.interestCount),
row.tier,
])}
/>
</View>
@@ -557,13 +547,16 @@ export function DashboardReport({
<View wrap={false}>
<Text style={styles.sectionTitle}>Deal pulse distribution</Text>
<Text style={styles.sectionSubtitle}>
Counts of active interests in each pulse tier (hot / warm / cool / cold).
Counts of active interests in each pulse tier (Hot / Warm / Cool / Cold).
</Text>
<SimpleTable
styles={styles}
headers={['Tier', 'Count']}
widths={[70, 30]}
rows={data.dealPulseDistribution.map((row) => [row.tier, String(row.count)])}
rows={data.dealPulseDistribution.map((row) => [
row.tier ? row.tier.charAt(0).toUpperCase() + row.tier.slice(1) : row.tier,
String(row.count),
])}
/>
</View>
) : null}
@@ -632,17 +625,17 @@ export function DashboardReport({
<View wrap={false}>
<Text style={styles.sectionTitle}>New interests (in period)</Text>
<Text style={styles.sectionSubtitle}>
Interests opened during the report window, with the stage they currently sit at and
their lead source.
Interests opened during the report window, with the stage they currently sit at and the
berth(s) attached.
</Text>
<SimpleTable
styles={styles}
headers={['Client', 'Stage', 'Source', 'Opened']}
widths={[40, 22, 18, 20]}
headers={['Client', 'Stage', 'Berth', 'Opened']}
widths={[35, 22, 23, 20]}
rows={data.newInterestsInPeriod.map((r) => [
r.clientName,
stageLabel(r.stage),
r.source ?? '-',
r.berthLabel ?? '-',
new Date(r.createdAt).toLocaleDateString('en-GB'),
])}
/>

View File

@@ -1,4 +1,5 @@
import { Badge, DataTable, DocumentShell, KeyValueGrid, Section } from '@/lib/pdf/brand-kit';
import { stageLabelFor } from '@/lib/constants';
export interface ClientContact {
channel: string;
@@ -131,7 +132,7 @@ export function ClientSummaryPdf({
<Section title="Pipeline interests">
<DataTable<InterestRow>
columns={[
{ header: 'Stage', flex: 2, render: (i) => i.pipelineStage ?? 'open' },
{ header: 'Stage', flex: 2, render: (i) => stageLabelFor(i.pipelineStage) },
{ header: 'Berth', flex: 1, render: (i) => i.berthMooringNumber ?? '-' },
{ header: 'Category', flex: 2, render: (i) => i.leadCategory ?? '-' },
{ header: 'Created', flex: 1.5, render: (i) => fmtDate(i.createdAt) },

View File

@@ -6,6 +6,7 @@ import {
Section,
type BadgeTone,
} from '@/lib/pdf/brand-kit';
import { stageLabelFor } from '@/lib/constants';
export interface InterestSummaryPdfProps {
portName: string;
@@ -74,8 +75,8 @@ export function InterestSummaryPdf({
berth,
timeline,
}: InterestSummaryPdfProps) {
const stage = (interest.pipelineStage ?? 'open').toLowerCase();
const docMeta = `${client.fullName ?? 'Unknown client'} · stage: ${stage.replace('_', ' ')}`;
const stage = stageLabelFor(interest.pipelineStage);
const docMeta = `${client.fullName ?? 'Unknown client'} · stage: ${stage}`;
return (
<DocumentShell

View File

@@ -15,20 +15,20 @@ export interface OccupancyReportPdfProps {
data: OccupancyData;
}
// Mirrors BERTH_STATUSES in src/lib/constants.ts (canonical 3-status
// enum). 'reserved' and 'maintenance' were dropped from the schema; if
// pre-migration data still carries them, the label falls back to the
// raw status string via the `?? status` guard at the call site below.
const STATUS_LABELS: Record<string, string> = {
available: 'Available',
under_offer: 'Under offer',
sold: 'Sold',
reserved: 'Reserved',
maintenance: 'Maintenance',
};
const STATUS_COLORS: Record<string, string> = {
available: PDF_TOKENS.colors.success,
under_offer: PDF_TOKENS.colors.warning,
sold: PDF_TOKENS.colors.accentBlue,
reserved: PDF_TOKENS.colors.accentSlate,
maintenance: PDF_TOKENS.colors.danger,
};
export function OccupancyReportPdf({ portName, logoBuffer, data }: OccupancyReportPdfProps) {

View File

@@ -21,10 +21,14 @@ import { berths } from '@/lib/db/schema/berths';
import { documents } from '@/lib/db/schema/documents';
import { reminders } from '@/lib/db/schema/operations';
import { payments } from '@/lib/db/schema/pipeline';
import { ports } from '@/lib/db/schema/ports';
import { auditLogs } from '@/lib/db/schema/system';
import { userProfiles } from '@/lib/db/schema/users';
import { canonicalizeStage } from '@/lib/constants';
import { websiteSubmissions } from '@/lib/db/schema/website-submissions';
import { computeDealHealth } from './deal-health';
import { getAllBerthMooringsForInterests } from './interest-berths.service';
import { deriveInterestBerthLabel } from '@/lib/templates/interest-berth-label';
import {
getKpis,
getPipelineCounts,
@@ -92,6 +96,16 @@ export async function resolveDashboardReportData(
const { from: windowFrom, to: windowTo } = parseWindow(window);
const hasWindow = windowFrom !== null && windowTo !== null;
// Resolve the port's configured currency once - every money-bearing
// section reads it for the Intl.NumberFormat output. Falls back to USD
// for any port row without a default set (schema default is also USD).
const portRow = await db
.select({ defaultCurrency: ports.defaultCurrency })
.from(ports)
.where(eq(ports.id, portId))
.limit(1);
const portCurrency = portRow[0]?.defaultCurrency ?? 'USD';
// ─── KPI / summary ───────────────────────────────────────────────
if (want.has('kpi_overview')) {
data.kpis = await getKpis(portId);
@@ -232,7 +246,6 @@ export async function resolveDashboardReportData(
id: interests.id,
clientName: clients.fullName,
stage: interests.pipelineStage,
source: interests.source,
createdAt: interests.createdAt,
})
.from(interests)
@@ -247,10 +260,14 @@ export async function resolveDashboardReportData(
)
.orderBy(desc(interests.createdAt))
.limit(50);
// Resolve berth moorings per interest in one batched round-trip so
// the "Berth" column renders the same multi-berth label idiom as
// every other interest-row surface (`A1-A3, B5`).
const allMooringsMap = await getAllBerthMooringsForInterests(rows.map((r) => r.id));
data.newInterestsInPeriod = rows.map((r) => ({
clientName: r.clientName,
stage: r.stage,
source: r.source ?? null,
berthLabel: deriveInterestBerthLabel(allMooringsMap.get(r.id)),
createdAt: r.createdAt.toISOString(),
}));
}
@@ -396,7 +413,7 @@ export async function resolveDashboardReportData(
const buckets: Record<string, number> = { hot: 0, warm: 0, cold: 0 };
for (const r of rows) {
const health = computeDealHealth({
pipelineStage: r.pipelineStage ?? 'open',
pipelineStage: canonicalizeStage(r.pipelineStage),
outcome: r.outcome,
archivedAt: r.archivedAt ? r.archivedAt.toISOString() : null,
dateFirstContact: r.dateFirstContact ? r.dateFirstContact.toISOString() : null,
@@ -572,7 +589,7 @@ export async function resolveDashboardReportData(
data.revenueForecast = {
grossValue: forecast.totalGrossValue,
weightedValue: forecast.totalWeightedValue,
currency: 'EUR',
currency: portCurrency,
};
}
@@ -629,10 +646,12 @@ export async function resolveDashboardReportData(
gross: s.grossValue,
weighted: s.weightedValue,
deals: s.count,
// The forecast service doesn't return a port-currency hint;
// default to EUR which matches the seeded berths schema. A
// multi-currency-aware breakdown would need extra plumbing.
currency: 'EUR',
// The forecast service doesn't return a per-stage currency hint;
// every stage rolls up under the port's configured defaultCurrency
// (ports.default_currency). Multi-currency-per-stage rollups would
// need extra plumbing - until then a single port currency drives
// the whole breakdown to match the dashboard tile.
currency: portCurrency,
}));
}

View File

@@ -15,7 +15,7 @@ import { residentialClients, residentialInterests } from '@/lib/db/schema/reside
import { ports } from '@/lib/db/schema/ports';
import { systemSettings, auditLogs } from '@/lib/db/schema/system';
import { userProfiles } from '@/lib/db/schema/users';
import { PIPELINE_STAGES, STAGE_WEIGHTS } from '@/lib/constants';
import { PIPELINE_STAGES, STAGE_WEIGHTS, canonicalizeStage } from '@/lib/constants';
import { activeInterestsWhere } from '@/lib/services/active-interest';
import { convert as convertCurrency } from '@/lib/services/currency';
@@ -205,7 +205,7 @@ export async function getRevenueForecast(portId: string, range?: { from: Date; t
> = {};
for (const row of interestRows) {
const stage = row.pipelineStage ?? 'open';
const stage = canonicalizeStage(row.pipelineStage);
const price = row.berthPrice ? parseFloat(String(row.berthPrice)) : 0;
const weight = weights[stage] ?? 0;
const weighted = price * weight;
@@ -261,7 +261,6 @@ export async function getBerthStatusDistribution(portId: string) {
available: counts['available'] ?? 0,
underOffer: counts['under_offer'] ?? 0,
sold: counts['sold'] ?? 0,
maintenance: counts['maintenance'] ?? 0,
};
}

View File

@@ -18,6 +18,7 @@ import { env } from '@/lib/env';
import { buildStoragePath } from '@/lib/minio';
import { getStorageBackend } from '@/lib/storage';
import { createAuditLog, type AuditMeta } from '@/lib/audit';
import { canonicalizeStage, type PipelineStage } from '@/lib/constants';
import { CodedError, ConflictError, NotFoundError, ValidationError } from '@/lib/errors';
import { emitToRoom } from '@/lib/socket/server';
@@ -172,29 +173,34 @@ export async function uploadExternallySignedEoi(input: ExternalEoiInput) {
});
// Two concerns to keep separate:
// 1. Document metadata - always write `dateEoiSigned` + `eoiStatus`
// from the upload. Even if the rep already advanced the stage
// manually, the paper signing event needs a recorded date so
// downstream surfaces (SkipAheadBanner, milestone strip, EOI
// merge fields) reflect reality. Honour an existing
// dateEoiSigned (don't overwrite if already set - covers the
// case where the rep is uploading evidence for an event whose
// date was already backfilled).
// 2. Stage advance - only when the deal hasn't reached eoi_signed
// yet. Bypasses canTransitionStage because the operator just
// brought concrete proof.
// 1. Document metadata - always write dateEoiSigned, eoiStatus, and
// eoiDocStatus from the upload. Even if the rep already advanced
// the stage manually, the paper signing event needs a recorded
// date + doc-status badge so downstream surfaces (SkipAheadBanner,
// milestone strip, EOI merge fields, signing-progress chip) reflect
// reality. Honour an existing dateEoiSigned - covers the case where
// the rep is uploading evidence for an event whose date was already
// backfilled.
// 2. Stage advance - in the 7-stage pipeline (PIPELINE_STAGES), every
// pre-EOI stage (enquiry / qualified / nurturing) should flip to
// 'eoi' on signing. The doc-status 'signed' carries the within-stage
// sub-state. Bypasses canTransitionStage because the operator just
// brought concrete proof. Idempotent at the 'eoi' / 'reservation' /
// 'deposit_paid' / 'contract' stages (stays put).
const stageBeforeAdvance = interest.pipelineStage as PipelineStage | null | undefined;
const canonicalStage = canonicalizeStage(stageBeforeAdvance);
const shouldAdvanceStage =
interest.pipelineStage === 'open' ||
interest.pipelineStage === 'details_sent' ||
interest.pipelineStage === 'in_communication' ||
interest.pipelineStage === 'eoi_sent';
canonicalStage === 'enquiry' ||
canonicalStage === 'qualified' ||
canonicalStage === 'nurturing';
await tx
.update(interests)
.set({
dateEoiSigned: interest.dateEoiSigned ?? input.signedAt ?? new Date(),
eoiStatus: 'signed',
...(shouldAdvanceStage ? { pipelineStage: 'eoi_signed' as const } : {}),
eoiDocStatus: 'signed',
...(shouldAdvanceStage ? { pipelineStage: 'eoi' as const } : {}),
updatedAt: new Date(),
})
.where(eq(interests.id, interestId));
@@ -203,7 +209,7 @@ export async function uploadExternallySignedEoi(input: ExternalEoiInput) {
documentId: doc.id,
fileId: fileRecord.id,
stageChanged: shouldAdvanceStage,
newStage: shouldAdvanceStage ? ('eoi_signed' as const) : interest.pipelineStage,
newStage: shouldAdvanceStage ? ('eoi' as const) : canonicalStage,
};
});

View File

@@ -16,7 +16,9 @@ import {
PREVIEWABLE_MIMES,
bufferMatchesMime,
} from '@/lib/constants/file-validation';
import { getAllBerthMooringsForInterests } from '@/lib/services/interest-berths.service';
import { generateStorageKey, sanitizeFilename } from '@/lib/services/storage';
import { deriveInterestBerthLabel } from '@/lib/templates/interest-berth-label';
import type { UploadFileInput, UpdateFileInput, ListFilesInput } from '@/lib/validators/files';
import { documentFolders } from '@/lib/db/schema/documents';
import { clients } from '@/lib/db/schema/clients';
@@ -334,6 +336,13 @@ export async function getFileById(id: string, portId: string) {
*/
export type AggregatedFileRow = Omit<typeof files.$inferSelect, 'storagePath' | 'storageBucket'> & {
signedFromDocumentId: string | null;
/** When the file is tagged to an interest, the multi-berth label of
* that interest (e.g. "A1-A3, B5") - or null. Resolved in
* listFilesAggregated* via one batched mooring lookup per request.
* Lets EntityFolderView render a per-row "which deal" badge so reps
* can tell apart files that all look identical on a multi-deal
* client. */
interestBerthLabel: string | null;
};
export interface AggregatedFileGroup {
@@ -443,7 +452,13 @@ export async function listFilesAggregatedByEntity(
columns: { id: true, clientId: true },
});
if (!interest) return { groups: [] };
return listFilesAggregatedForInterest(portId, interest.id, interest.clientId ?? null);
const result = await listFilesAggregatedForInterest(
portId,
interest.id,
interest.clientId ?? null,
);
await attachInterestBerthLabels(result.groups);
return result;
}
const related = await collectRelatedEntities(portId, entityType, entityId);
@@ -499,6 +514,8 @@ export async function listFilesAggregatedByEntity(
});
}
await attachInterestBerthLabels(groups);
return { groups };
}
@@ -688,6 +705,9 @@ async function fetchGroupRows(
// Reverse-link: if any document row has this file as its signed_file_id,
// surface that document's id.
signedFromDocumentId: documents.id,
// interestBerthLabel is filled post-fetch via a single batched
// getAllBerthMooringsForInterests call at the entry-point level so
// we don't N+1 the moorings join inside each group.
})
.from(files)
.leftJoin(documents, eq(documents.signedFileId, files.id))
@@ -708,7 +728,37 @@ async function fetchGroupRows(
.from(files)
.where(and(eq(files.portId, portId), predicate));
return { rows, total: Number(countRow?.count ?? 0) };
// interestBerthLabel filled by the entry-point post-pass (see
// attachInterestBerthLabels below); default to null inside this row.
const rowsWithDefault: AggregatedFileRow[] = rows.map((r) => ({
...r,
interestBerthLabel: null,
}));
return { rows: rowsWithDefault, total: Number(countRow?.count ?? 0) };
}
/**
* Mutate the rows of every group in-place to fill `interestBerthLabel`
* from a single batched mooring lookup. Called by both interest- and
* entity-aggregation entry-points so EntityFolderView gets the "which
* deal" badge without an N+1 join.
*/
async function attachInterestBerthLabels(groups: AggregatedFileGroup[]): Promise<void> {
const interestIds = new Set<string>();
for (const g of groups) {
for (const f of g.files) {
if (f.interestId) interestIds.add(f.interestId);
}
}
if (interestIds.size === 0) return;
const mooringsMap = await getAllBerthMooringsForInterests(Array.from(interestIds));
for (const g of groups) {
for (const f of g.files) {
if (!f.interestId) continue;
f.interestBerthLabel = deriveInterestBerthLabel(mooringsMap.get(f.interestId));
}
}
}
function dedupeBy<T, K>(items: T[], key: (t: T) => K): T[] {

View File

@@ -101,6 +101,41 @@ export async function getPrimaryBerthsForInterests(
return out;
}
/**
* Map { interestId → mooring numbers[] } for a batch of interest ids.
* Used by list/kanban/header surfaces that need to render the full
* berth-range label (`A1-A3, B5`) rather than just the primary mooring.
* One round-trip; siblings the primary-only aggregator above.
*
* Mooring numbers come back sorted lexically; the consumer formatter
* (`deriveInterestBerthLabel` / `formatBerthRange`) re-sorts by
* prefix+number for range collapsing. Null mooring numbers (orphaned
* junction rows where the berth was hard-deleted) are filtered out.
*/
export async function getAllBerthMooringsForInterests(
interestIds: string[],
): Promise<Map<string, string[]>> {
if (interestIds.length === 0) return new Map();
const rows = await db
.select({
interestId: interestBerths.interestId,
mooringNumber: berths.mooringNumber,
})
.from(interestBerths)
.leftJoin(berths, eq(berths.id, interestBerths.berthId))
.where(inArray(interestBerths.interestId, interestIds))
.orderBy(berths.mooringNumber);
const out = new Map<string, string[]>();
for (const r of rows) {
if (!r.mooringNumber) continue;
const existing = out.get(r.interestId);
if (existing) existing.push(r.mooringNumber);
else out.set(r.interestId, [r.mooringNumber]);
}
return out;
}
/** Berth metadata surfaced alongside each junction row by {@link listBerthsForInterest}.
* All berth-derived fields are nullable so an orphaned junction row (berth
* hard-deleted out from under the link) still renders rather than vanishing. */
@@ -256,6 +291,15 @@ export async function upsertInterestBerthTx(
if (opts.isSpecificInterest !== undefined)
setForUpdate.isSpecificInterest = opts.isSpecificInterest;
if (opts.isInEoiBundle !== undefined) setForUpdate.isInEoiBundle = opts.isInEoiBundle;
// Invariant: primary berth is ALWAYS in the EOI bundle. The primary IS
// the canonical "berth for this deal" - excluding it from the signed
// envelope is semantically nonsense. If the caller is setting the row
// to primary OR opting to take out of the EOI bundle, force the bundle
// flag back on whenever the row is also (about to be) primary.
const willBePrimary = opts.isPrimary === true;
if (willBePrimary && opts.isInEoiBundle === false) {
setForUpdate.isInEoiBundle = true;
}
if (opts.addedBy !== undefined) setForUpdate.addedBy = opts.addedBy;
if (opts.notes !== undefined) setForUpdate.notes = opts.notes;
// Bypass fields move as a unit - either we set all three to record a bypass
@@ -283,6 +327,11 @@ export async function upsertInterestBerthTx(
// non-primary rows default to FALSE so the public map doesn't
// light up extra berths.
const isPrimary = opts.isPrimary ?? false;
// Force is_in_eoi_bundle=true when this row is the primary: the EOI
// bundle MUST cover the deal's canonical berth, regardless of what
// the caller passed. Non-primary rows still default to true (rep can
// opt out per-berth) but primary is non-negotiable.
const isInEoiBundle = isPrimary ? true : (opts.isInEoiBundle ?? true);
const [row] = await tx
.insert(interestBerths)
.values({
@@ -290,7 +339,7 @@ export async function upsertInterestBerthTx(
berthId,
isPrimary,
isSpecificInterest: opts.isSpecificInterest ?? isPrimary,
isInEoiBundle: opts.isInEoiBundle ?? true,
isInEoiBundle,
addedBy: opts.addedBy,
notes: opts.notes,
eoiBypassReason: setForUpdate.eoiBypassReason ?? null,

View File

@@ -22,6 +22,7 @@ import { evaluateRule } from '@/lib/services/berth-rules-engine';
import { notifyNextInLine } from '@/lib/services/next-in-line-notify.service';
import { logger } from '@/lib/logger';
import {
getAllBerthMooringsForInterests,
getPrimaryBerth,
getPrimaryBerthsForInterests,
listBerthsForInterest,
@@ -163,6 +164,11 @@ export interface BoardInterestRow {
id: string;
clientName: string | null;
berthMooringNumber: string | null;
/** Every linked berth's mooring on this interest (sorted). Consumers
* pass this through `deriveInterestBerthLabel` for the header / card
* display so multi-berth interests render as `A1-A3, B5` rather than
* just the primary mooring. */
berthMoorings: string[];
leadCategory: string | null;
pipelineStage: string;
updatedAt: Date;
@@ -262,13 +268,20 @@ export async function listInterestsForBoard(
// Primary-berth resolution stays in the junction-aware service so the
// board sees the same "the berth for this deal" as every other surface.
const primaryBerthMap = await getPrimaryBerthsForInterests(data.map((r) => r.id));
// All-berth aggregator runs in parallel; both come from the same
// interest_berths table so the round-trips are independent.
const interestIds = data.map((r) => r.id);
const [primaryBerthMap, allBerthMooringsMap] = await Promise.all([
getPrimaryBerthsForInterests(interestIds),
getAllBerthMooringsForInterests(interestIds),
]);
return {
data: data.map((r) => ({
id: r.id,
clientName: r.clientName ?? null,
berthMooringNumber: primaryBerthMap.get(r.id)?.mooringNumber ?? null,
berthMoorings: allBerthMooringsMap.get(r.id) ?? [],
leadCategory: r.leadCategory ?? null,
pipelineStage: r.pipelineStage,
updatedAt: r.updatedAt,
@@ -405,7 +418,12 @@ export async function listInterests(portId: string, query: ListInterestsInput) {
// Primary-berth lookup via the interest_berths junction. Single round-trip
// by interestId list - see plan §3.4: every "the berth for this interest"
// surface resolves through getPrimaryBerth(...) rather than a column read.
const primaryBerthMap = await getPrimaryBerthsForInterests(interestIds);
// Sibling all-mooring aggregator runs in parallel so the list endpoint
// can surface multi-berth labels (A1-A3, B5) without a second waterfall.
const [primaryBerthMap, allBerthMooringsMap] = await Promise.all([
getPrimaryBerthsForInterests(interestIds),
getAllBerthMooringsForInterests(interestIds),
]);
if (yachtIds.length > 0) {
const yachtRows = await db
@@ -453,6 +471,7 @@ export async function listInterests(portId: string, query: ListInterestsInput) {
clientName: clientsMap[i.clientId as string] ?? null,
berthId: primary?.berthId ?? null,
berthMooringNumber: primary?.mooringNumber ?? null,
berthMoorings: allBerthMooringsMap.get(i.id as string) ?? [],
yachtName: i.yachtId ? (yachtsMap[i.yachtId as string] ?? null) : null,
tags: tagsByInterestId[i.id as string] ?? [],
notesCount: notesCountByInterestId[i.id as string] ?? 0,
@@ -515,9 +534,15 @@ export async function getInterestById(id: string, portId: string) {
.limit(1);
// Primary berth comes from the interest_berths junction (plan §3.4).
const primaryBerth = await getPrimaryBerth(interest.id);
// All linked moorings come from the same junction in one go - powers
// the multi-berth label rendered on every "interest header" surface.
const [primaryBerth, allMooringsMap] = await Promise.all([
getPrimaryBerth(interest.id),
getAllBerthMooringsForInterests([interest.id]),
]);
const berthId = primaryBerth?.berthId ?? null;
const berthMooringNumber = primaryBerth?.mooringNumber ?? null;
const berthMoorings = allMooringsMap.get(interest.id) ?? [];
// Total linked-berth count powers the "Berth Interest" milestone on
// the OverviewTab - first thing the rep needs to capture, especially
@@ -666,6 +691,7 @@ export async function getInterestById(id: string, portId: string) {
clientHasAddress: !!addressRow,
berthId,
berthMooringNumber,
berthMoorings,
linkedBerthCount,
tags: tagRows,
notesCount,
@@ -712,14 +738,33 @@ export async function createInterest(portId: string, data: CreateInterestInput,
const resolvedReminderDays =
interestData.reminderDays ?? (resolvedReminderEnabled ? reminderConfig.defaultDays : null);
// Auto-assign to the port's default owner when the caller omits assignedTo.
// Setting is stored as `{ userId: "..." }` so other surfaces can extend it
// with round-robin / quota rules later without breaking this code path.
// Resolve the deal owner. Three-tier chain:
// 1. Explicit `data.assignedTo` from the caller (rep picked an
// assignee in the create form).
// 2. Port's `default_new_interest_owner` setting (used for round-
// robin / "front desk owns all new leads" rules).
// 3. Auto-assign to the creating user when they're a regular role
// (sales rep, sales manager, etc.). Skipped for super-admins who
// often create on behalf of other reps - they'd otherwise hijack
// every new lead. Falls back to null (Unassigned) when none of
// the above resolve.
let resolvedAssignedTo = interestData.assignedTo ?? null;
if (resolvedAssignedTo === null && !('assignedTo' in interestData)) {
const defaultOwner = await getSetting('default_new_interest_owner', portId);
const v = defaultOwner?.value as { userId?: string } | null | undefined;
if (v?.userId) resolvedAssignedTo = v.userId;
if (v?.userId) {
resolvedAssignedTo = v.userId;
} else {
// Tier 3: auto-assign to creator unless they're a super-admin.
const [profile] = await db
.select({ isSuperAdmin: userProfiles.isSuperAdmin })
.from(userProfiles)
.where(eq(userProfiles.userId, meta.userId))
.limit(1);
if (profile && !profile.isSuperAdmin) {
resolvedAssignedTo = meta.userId;
}
}
}
const result = await withTransaction(async (tx) => {
@@ -1133,10 +1178,11 @@ export async function advanceStageIfBehind(
return false;
}
// yachtId gate: changeInterestStage requires a yacht before leaving `open`.
// EOI events imply a yacht is in the picture, but if the data is missing we
// bail rather than throw - the EOI itself shouldn't fail because of this.
if (existing.pipelineStage === 'open' && !existing.yachtId) {
// yachtId gate: changeInterestStage requires a yacht before leaving the
// initial enquiry stage. EOI events imply a yacht is in the picture, but
// if the data is missing we bail rather than throw - the EOI itself
// shouldn't fail because of this.
if (existing.pipelineStage === 'enquiry' && !existing.yachtId) {
return false;
}

View File

@@ -89,10 +89,14 @@ export const SETTING_KEYS = {
// Ignored entirely on v1 instances.
documensoSigningOrder: 'documenso_signing_order',
// v2-only override of the post-signing redirect URL set on documentMeta.
// Falls back to the embedded signing host (or APP_URL) when unset. Use
// this to land signed clients on /portal/eoi-complete (or wherever
// makes sense for the workflow).
// Resolver chain: explicit override -> port's public_site_url -> null
// (let Documenso use its own default). Lets signers land on the port's
// marketing site by default without each admin having to configure two
// settings.
documensoRedirectUrl: 'documenso_redirect_url',
// Per-port public marketing-site URL. Used by signing-redirect
// fallback, email CTAs, and some templates.
publicSiteUrl: 'public_site_url',
// Branding
brandingLogoUrl: 'branding_logo_url',
@@ -396,6 +400,7 @@ export async function getPortDocumensoConfig(portId: string): Promise<PortDocume
approverUserId,
signingOrder,
redirectUrlOverride,
publicSiteUrl,
] = await Promise.all([
readSetting<string>(SETTING_KEYS.documensoApiUrlOverride, portId),
readSetting<string>(SETTING_KEYS.documensoApiKeyOverride, portId),
@@ -419,6 +424,7 @@ export async function getPortDocumensoConfig(portId: string): Promise<PortDocume
readSetting<string>(SETTING_KEYS.documensoApproverUserId, portId),
readSetting<'PARALLEL' | 'SEQUENTIAL'>(SETTING_KEYS.documensoSigningOrder, portId),
readSetting<string>(SETTING_KEYS.documensoRedirectUrl, portId),
readSetting<string>(SETTING_KEYS.publicSiteUrl, portId),
]);
// Determine the resolution source for the two credentials. Used by
@@ -457,7 +463,12 @@ export async function getPortDocumensoConfig(portId: string): Promise<PortDocume
developerUserId: developerUserId ?? null,
approverUserId: approverUserId ?? null,
signingOrder: signingOrder ?? null,
redirectUrl: redirectUrlOverride ?? null,
// Resolution chain: explicit Documenso override → port's marketing
// site URL → null (Documenso falls back to its own default, which is
// typically the configured APP_URL = the CRM login - not what we want
// for signers). The marketing-site fallback means operators who set
// public_site_url (most do) automatically get sensible signer landing.
redirectUrl: redirectUrlOverride ?? publicSiteUrl ?? null,
};
}

View File

@@ -230,7 +230,7 @@ export async function createPublicInterest(
clientId,
yachtId,
source: 'website',
pipelineStage: 'open',
pipelineStage: 'enquiry',
})
.returning();

View File

@@ -0,0 +1,40 @@
/**
* Shared helper that turns an interest's full berth list into the display
* label surfaced everywhere the record is named (header, kanban card, list
* rows, search results, picker chips). Mirrors the EOI / Documents-Hub
* idiom: consecutive runs collapse to a hyphenated range, separate runs
* comma-join, and an over-cap fallback degrades to "<first> + N more".
*
* deriveInterestBerthLabel([]) -> null
* deriveInterestBerthLabel(['A1']) -> 'A1'
* deriveInterestBerthLabel(['A1','A2','A3']) -> 'A1-A3'
* deriveInterestBerthLabel(['A1','A3']) -> 'A1, A3'
* deriveInterestBerthLabel(['A1','A3','B5','B6']) -> 'A1, A3, B5-B6'
* deriveInterestBerthLabel(['A1','A3','A5','A7','A9','A11'])
* -> 'A1 + 5 more'
*
* Truncation triggers when, post-range-collapse, the segment count exceeds
* MAX_SEGMENTS - keeps the button / header from overflowing.
*/
import { formatBerthRange } from '@/lib/templates/berth-range';
const MAX_SEGMENTS = 5;
export function deriveInterestBerthLabel(
mooringNumbers: readonly (string | null | undefined)[] | null | undefined,
): string | null {
if (!mooringNumbers) return null;
const clean = mooringNumbers.filter((m): m is string => !!m && m.trim().length > 0);
if (clean.length === 0) return null;
const compact = formatBerthRange(clean);
if (!compact) return null;
const segments = compact.split(', ');
if (segments.length <= MAX_SEGMENTS) return compact;
// Over-cap: degrade to "first + N more" against the total berth count.
const first = segments[0]!;
const remaining = clean.length - 1;
return `${first} + ${remaining} more`;
}