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

@@ -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;
}