Commit Graph

622 Commits

Author SHA1 Message Date
397dbd1490 docs(spec): env-to-admin migration design
Design spec for moving tenant-configurable env vars into the per-port
admin UI via a settings registry. Covers scope decisions, registry
shape, resolver, encryption, admin UI generation, env catalog by
disposition, migration plan, and testing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 14:22:39 +02:00
d15f5509ad docs(audit): progress report for the 2026-05-15 fix wave
All checks were successful
Build & Push Docker Images / lint (push) Successful in 2m6s
Build & Push Docker Images / build-and-push (push) Successful in 1m13s
11 of 13 known issues (A1-A20) fixed and verified; legacy-stage rank
tables in clients.service.ts + berth-recommender.service.ts purged of
9-stage enum keys. 1373/1373 vitest pass.

Remaining catalog (300+ checks) listed by section so it's clear what's
covered vs. still on the to-do list.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 01:22:14 +02:00
98211066a5 fix(legacy-stage): purge 9-stage enum keys from rank tables and stale copy
Some checks failed
Build & Push Docker Images / lint (push) Successful in 2m4s
Build & Push Docker Images / build-and-push (push) Has been cancelled
L-001 hunt landed these:

  - src/lib/services/clients.service.ts — stageRank used pre-refactor
    9-stage names exclusively (`contract_signed`, `deposit_10pct`, …).
    Every modern 7-stage interest fell to rank 0, making client-list
    "most-progressed deal" sort effectively random. Modern values now
    own the canonical ranks; legacy aliases map to their 7-stage
    equivalents so historical audit data still sorts.

  - src/lib/services/berth-recommender.service.ts — STAGE_ORDER had
    the same 9-stage shape. LATE_STAGE_THRESHOLD pointed at the (now
    nonexistent) `deposit_10pct` slot. Reworked to the 7-stage scale;
    threshold now at `deposit_paid` (5).

  - Stale comments referencing `deposit_10pct` in schema (clients,
    financial) and client-archive services updated to current copy.

  - Smart-archive dialog rendered `i.pipelineStage` as raw enum; now
    routes through `stageLabelFor` (the new helper added with A2).

Test fixture updates: berth-recommender.test.ts numeric inputs
re-mapped to the new 7-stage scale (eoi_signed=5 → eoi=3, etc.).
1373/1373 vitest pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 01:18:13 +02:00
0d9208a052 fix(audit): A1/A2/A4/A6/A8/A9/A16/A17/A19/A20 from 2026-05-15 sweep
Knocks out 10 of the 13 known issues from yesterday's Playwright audit.

A4 — Client form silently rejected submit when a contact row had an
empty value. The F19 filter ran in mutationFn after zod's
handleSubmit had already short-circuited on min(1). Now wraps the
onSubmit to prune empty rows BEFORE handleSubmit/zod sees them.

A16 — File upload to documents hub root 400'd because FormData.get
returns null for absent fields and zod's .optional() rejects null.
Route handler now coerces null/empty → undefined before parse.

A17 — Added /api/v1/me/ports endpoint that any authenticated user
can hit; client.ts now uses it as the bootstrap port-slug→port-id
resolver. Eliminates the wasteful 400s sales-reps and viewers were
firing on every page load against the super-admin-gated /admin/ports.

A1 — Filter permission_denied actions from the dashboard activity
feed. Still in the audit log; just not noise on the dashboard.

A2 — New LEGACY_STAGE_REMAP table + canonicalizeStage / stageLabelFor
helpers in lib/constants. Activity-feed maps legacy 9-stage enum
values (deposit_10pct, contract_sent, etc.) to their 7-stage labels
on the way out, so historical audit rows read as "Deposit Paid" not
"Deposit 10Pct".

A19 — Same-stage write now returns 204 No Content. Service returns
a STAGE_NOOP sentinel; the route handler translates it.

A9 — Catch-up wizard now derives stage from berth status (under_offer
→ EOI, sold → contract) with a stageOverride state for explicit
user picks. Avoids the set-state-in-effect rule violation.

A20 — OwnerPicker shows a "Client / Company" hint chip on the
trigger when no value is set, so users know the trigger opens a
two-tab picker instead of just a client list.

A8 — Migration 0066 normalizes legacy `statusOverrideMode = 'auto'`
to NULL so the column lives at strictly 3 states.

A6 — file-preview-dialog gets a screen-reader DialogDescription so
the Radix "Missing aria-describedby" warning stops firing on every
preview.

A18 closed as not-a-bug: /api/v1/users genuinely doesn't exist
(Next returns 404); /api/v1/admin/audit exists and 403s.

A5 (Socket.IO dev noise) + A3 (react-grab CSP) left for a separate
pass — both are dev-only cosmetic.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 01:12:20 +02:00
3b3ac287e0 docs(audit): comprehensive 320+ check catalog organized by area
All checks were successful
Build & Push Docker Images / lint (push) Successful in 2m6s
Build & Push Docker Images / build-and-push (push) Successful in 22s
Companion to the 2026-05-15 sweep findings. Catalogues every audit-worthy
surface across 19 areas:

  0. Already-known issues (A1-A20 cross-reference)
  1. Legacy stage enum bleed (the deposit_10pct class) — 20 checks
  2. Routes / page reachability — 30 checks
  3. UX consistency (forms, lists, tables, badges, modals, mobile) — 100 checks
  4. Sales workflows happy + edge cases — 52 checks
  5. Admin workflows — 60 checks
  6. Multi-tenancy port isolation — 11 checks
  7. Security — 30 checks
  8. Realtime / sockets — 9 checks
  9. Performance — 14 checks
  10. Documents / files — 22 checks
  11. Audit log surface — 14 checks
  12. Email / SMTP / IMAP — 19 checks
  13. Integrations (Documenso, NocoDB, S3, AI, BullMQ) — 29 checks
  14. Schema / migration — 15 checks
  15. i18n / l10n — 8 checks
  16. Browser / device — 7 checks
  17. Specific behavioral correctness (legacy stage drift, A1 hard-delete fallout, etc) — 22 checks
  18. Data clean-up jobs — 5 checks
  19. CI / dev experience — 13 checks

Each check tagged with effort (XS/S/M/L), severity (🔴/🟠/🟡/🟢), and
current coverage (/⚠️//). Recommended priority tiering at the bottom.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 00:54:08 +02:00
ff5e71092e docs(audit): 2026-05-15 comprehensive Playwright sweep findings
All checks were successful
Build & Push Docker Images / lint (push) Successful in 2m7s
Build & Push Docker Images / build-and-push (push) Successful in 22s
Covers super-admin, sales-rep, viewer, portal, catch-up wizard, and the
single-tree responsive shell. 13 findings catalogued with reproduction +
effort estimates, plus a positive-findings section confirming what
shipped is working end-to-end:
  - F22/F23/F25/F44 verified live
  - #67 catch-up wizard runs full transaction (client+interest+clear-override)
  - #26 single-tree shell verified at 390px and 1440px viewports
  - permission gating holds for sales-agent and viewer

Critical issues found:
  - A4 New Client form silently rejects submit when an empty contact row is present (F19 filter runs in mutationFn, too late)
  - A16 file upload at documents-hub root fails: client sends nulls, validator wants strings or absent
  - A17 /api/v1/admin/ports is super-admin-only but apiFetch uses it to bootstrap port-slug→port-id resolution for every user

See docs/audit-2026-05-15.md for the full list.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 00:44:51 +02:00
58940552be test: update yacht-prereq error message assertion to match F21 copy
All checks were successful
Build & Push Docker Images / lint (push) Successful in 2m12s
Build & Push Docker Images / build-and-push (push) Successful in 4m35s
The integration test was pinned to the legacy "yachtId is required before
leaving stage=enquiry" developer-language string. F21 reworded it to
"A yacht must be linked before leaving the Enquiry stage." for the toast
surface — bring the test regex along.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 00:00:32 +02:00
202e0b1bc5 refactor(layout): single-tree responsive shell (#26)
Pre-fix the dashboard layout mounted BOTH the desktop and mobile shells
to the DOM on every page, hidden via CSS data-shell rules. Two Tabs
providers had data-state="active" concurrently, every fetch fired twice,
every component piece of state lived in two trees, a11y landmarks
duplicated, and half the click attempts hit the wrong layer.

New <AppShell> client wrapper mounts exactly ONE tree based on the
server-classified User-Agent (no hydration mismatch, no first-paint
flash on real mobile devices) plus a runtime matchMedia subscription
that swaps shells when the viewport crosses 1024px (e.g. desktop
browser resized).

Knock-on changes:
  - Dashboard layout fetches once and hands the data to AppShell;
    AppShell picks Desktop (Sidebar + Topbar + main) or MobileLayout
  - Stripped the now-orphan data-shell CSS rules from globals.css —
    nothing emits the attribute any more
  - MobileLayout drops its data-shell="mobile" attribute (was the lever
    the dead CSS rules pulled)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 23:59:30 +02:00
7d33e73eef feat(berths): manual status catch-up wizard + reconciliation queue (#67)
Wires the long-dormant berths.status_override_mode column into a closed
loop so reps can reconcile berths flipped to under_offer/sold without a
backing interest.

Phase 1 — Status source tracking:
  - updateBerthStatus() stamps 'manual' on every user-facing write
  - berth-rules-engine.ts stamps 'automated' on auto-rule writes
  - new clearBerthOverride() helper nulls the field and stamps the
    reason "Reconciled via interest <id>" — only the wizard calls it

Phase 2 — Visual indicator:
  - Amber "Manual" chip on berth-list rows where statusOverrideMode='manual'
    AND no active linked interest (the candidates for catch-up)

Phase 3 — Reconciliation queue:
  - new service listManualReconcileBerths() with cross-port-safe
    NOT-EXISTS against activeInterestsWhere
  - GET /api/v1/berths/reconcile-queue
  - new page /[portSlug]/admin/berths/reconcile listing the queue,
    each row linking to the catch-up wizard

Phase 4 — Catch-up wizard:
  - POST /api/v1/berths/[id]/reconcile orchestrates create-client
    (optional quick-create), create-interest with primary berth link,
    and clearBerthOverride — composed via existing service helpers
  - <CatchUpWizard> dialog: existing-client or quick-create, optional
    yacht link, stage picker scoped to the current berth status, with
    contract auto-setting outcome=won

Phase 5 — Entry points:
  - sidebar Admin > "Reconcile berths" link
  - berth-list row action menu shows "Catch up…" on flagged rows

Doc upload + payment recording (spec phases 4.4 / 4.5) are deferred —
once the interest exists, the rep uses the standard interest detail
page surfaces for those follow-ups. The wizard's MVP responsibility is
to take a manual berth to "interest exists, override cleared" in one
round-trip.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 23:55:22 +02:00
d2804de0d1 fix(ux): inline yacht-prereq picker + deprioritize country in client form
F23: when the rep tries to leave the Enquiry stage on an interest with no yacht linked, the stage popover now switches into an inline yacht-picker view (filtered to the client's own yachts when known). On submit it PATCHes interest.yachtId then chains the stage move, so the prereq fix and the advance happen in one flow instead of the rep bouncing to the validation error toast.
F24: Country moved out of the Basic Information section (next to Full Name *) into Source & Preferences alongside Timezone — country is timezone-hint material, not first-line identity data. Quick-path for a new client is now just name + contact.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 23:46:36 +02:00
84468386d9 fix(ux): T4 polish wave — empty-contact filter, redirect-on-create, friendly stage errors
F19: client form drops empty-value contacts on submit; auto-promotes first remaining row to primary if none flagged.
F20: new-interest dialog redirects to the detail page on create instead of bouncing back to the list.
F21: stage-transition validation errors render with STAGE_LABELS — "Yacht is required before leaving the Enquiry stage." (was "yachtId is required before leaving stage=enquiry").
F22: blocked-stage marker swapped from the ⚑ unicode glyph to a Lucide AlertTriangle with aria-label.
F25: documents-hub folder selection moves to ?folder=<id> querystring so deep-link / browser-back / refresh round-trip the current folder.
F26: reopen-outcome action now toasts "Outcome cleared — interest is open again."
F27: stage PATCH where target === current short-circuits to a no-op return; downstream callers don't see a phantom stage_change audit row.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 23:42:27 +02:00
3e78c2d4ab fix(F17 ext): apply DetailNotFound to clients/yachts/companies/berths
All checks were successful
Build & Push Docker Images / lint (push) Successful in 2m12s
Build & Push Docker Images / build-and-push (push) Successful in 4m44s
Refactored the interest-detail 404 pattern into a reusable
`<DetailNotFound>` component and applied it to the four other entity
detail pages. Pre-fix, navigating to a wrong-port or stale entity URL
silently rendered the layout shell with empty tabs on:

  - /[portSlug]/clients/[id]
  - /[portSlug]/yachts/[id]
  - /[portSlug]/companies/[id]
  - /[portSlug]/berths/[id]

All four now route a 404/403 response into an explicit "<Entity> not
found" / "No access" EmptyState with a back-to-list CTA, and the
TanStack Query retry policy short-circuits 404/403s so the empty state
appears immediately.

1373/1373 vitest pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 23:06:36 +02:00
608641c23b fix(T3): inline tag create + explicit 404 on interest detail
F16 — InlineTagEditor: inline "Create new tag" affordance
  The popover now has a search input at the top. Typing a name that
  doesn't match any existing tag surfaces a "Create new tag: <name>"
  action that POSTs /api/v1/tags then attaches the new id to the entity.
  Reps no longer need to context-switch to Admin → Tags to create the
  first chip. Enter on the input also triggers create-and-attach.

F17 — Interest detail page: explicit not-found state
  Pre-fix, navigating to /port-X/interests/<port-Y-id> 404'd at the API
  but the UI silently rendered the list shell with empty tabs. Cross-
  port URL pastes now show an EmptyState with title "Interest not found"
  + a "Back to interests" CTA. 403 (no access in this port) gets its
  own copy. TanStack Query is told not to retry 404/403s so the empty
  state appears immediately.

1373/1373 vitest pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 23:03:30 +02:00
e7e498dedd fix(T3): copy + entry points + recommender alias
Batch of small fixes from the post-audit plan:

F11 — "Mark as won" dialog copy
  Was: "This will move the interest to Completed and stamp the outcome."
  Completed was retired in the 7-stage refactor; copy now reads
  "marks Won; stage stays where it is" with a parallel Lost variant.

F13 — Bulk-add berths wizard had no UI entry point
  Page existed at /[portSlug]/admin/berths/bulk-add but nothing linked
  to it. Added a "Bulk add" button on the Berths list toolbar, gated
  on `berths.import`. Also fixed the API route's permission key
  (was `berths.create`, a phantom — switched to `berths.import` to
  match seed-permissions).

F14 — Audit Log nav entry
  Sidebar Admin section now lists "Audit Log" → /admin/audit, gated
  by the adminRequired group rule.

F18 — Recommender `limit` param ignored
  POST /interests/[id]/recommend-berths now accepts `limit` as an
  alias for `topN`. Audit sent `{limit:3}` and silently got 8 rows
  back; both names now resolve.

Tests still green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 22:59:38 +02:00
98fe295675 fix: cascade-archive client's open interests — F10
Pre-audit, archiving a client set `clients.archived_at` but left their
in-flight `interests.archived_at = NULL`. Active-interest queries kept
surfacing those interests with a shadowed client — breadcrumbs broke,
detail-page drill-ins silent-404'd, and the dashboard double-counted.

Now `archiveClient()` runs in a transaction:
  1. Set archived_at on the client.
  2. Cascade-archive every interest where the client is the owner AND
     the interest is currently active (archived_at IS NULL AND
     outcome IS NULL).

Won/lost/cancelled interests are explicitly NOT touched — those are
historical records of closed business and should stay queryable.

The audit-log entry's newValue carries the list of cascaded interest
IDs so /admin/audit shows exactly which deals got swept up. Socket
`interest:archived` events fire per-id so any open list views invalidate.

Verified live: archived Olivia Sinclair, her active interest archived
too in the same call. 1373/1373 vitest pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 22:53:42 +02:00
f85948488d test: update GDPR export test for dashed jobId — companion to F3
The test asserted the old `gdpr-export:${id}` shape that BullMQ rejects.
Mirrors the production fix in 7da3c5b.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 22:50:51 +02:00
025648c40b fix(P1): soft-archive berths instead of hard-delete — F5
Pre-audit, DELETE /api/v1/berths/[id] called `db.delete()` which
permanently dropped the row, cascade-vanished `interest_berths` links,
broke historical audit references, and could 404 the public feed mid-
customer-inquiry. The `berths.archived_at` column existed in the schema
but was never written.

Changes:
  - `archiveBerth(id, portId, { reason }, meta)` is the new canonical
    soft-archive. Requires a reason (min 5 chars). Blocks when an
    active interest still depends on the berth (forces the rep to
    resolve the deal first). Audit-logs the old status + reason.
  - `restoreBerth(...)` reverses it.
  - DELETE route now accepts `{ reason }` and routes to archiveBerth.
  - New POST /api/v1/berths/[id]/restore.
  - `getBerthOptions` + dashboard occupancy / status-distribution
    queries gain `isNull(berths.archivedAt)` so archived moorings
    don't show up in pickers or skew metrics.
  - Legacy `deleteBerth(...)` kept as a thin wrapper around archiveBerth
    so import sites we haven't migrated still work — labeled @deprecated.

Verified live:
  - DELETE w/o reason       → 400 (validation)
  - DELETE w/ "x"           → 400 "Reason must be ≥ 5 characters"
  - DELETE w/ proper reason → 204, row archived, reason persisted
  - DELETE twice            → 409 "Berth is already archived"
  - POST /restore           → 204, archived_at cleared

Follow-up (deferred): apply isNull(archivedAt) to recommendations.ts,
alert-rules.ts, portal.service.ts, report-generators.ts, berth-rules-
engine.ts. The current set covers the visible surfaces; the rest are
secondary aggregators.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 22:49:43 +02:00
2d0a49e0d1 fix(P1): input validation hardening for client API — F6
Pre-audit /api/v1/clients accepted:
  - contacts[].value='not-an-email' with channel='email' → silent bounce
  - fullName='   ' (whitespace-only) → blank-chip renders everywhere
  - fullName='Hidden<ZWSP>Char<ZWSP>Name' (zero-width chars) → search blind spot

This commit:
  1. New `humanTextSchema()` helper in src/lib/validators/text.ts that
     strips invisible/bidi/control chars, trims, then length-checks.
  2. `fullName` switched to `humanTextSchema({ min: 1, max: 200 })`.
  3. `contactSchema` gains a `superRefine` requiring valid email format
     when `channel === 'email'`.

Verified live:
  - invalid email      → 400 "Must be a valid email address." (field-scoped)
  - whitespace name    → 400 "Too small: expected string to have >=1 characters"
  - zero-width chars   → stored as cleaned "HiddenCharName"
  - valid baseline     → 201

Followup tasks (deferred): apply `humanTextSchema` to yachts/companies/
interests/notes/reminders names; audit render paths for XSS-via-stored-
HTML (default React escaping is safe; pdfme/email-merge surfaces need a
spot-check).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 22:44:15 +02:00
27f8db4c67 fix(P1): rate-limit auth endpoints — F7
Pre-audit: 20 rapid wrong-password attempts all returned 401 with no
lockout. Brute-force open.

Post-fix: better-auth's built-in rate limiter caps /sign-in/email at
5 attempts per 60s. Verified live — attempts 1-5 return 401, attempt 6+
returns 429 "Too many requests".

Same tight cap applied to /sign-up/email, /forget-password,
/reset-password. Default 120/min for everything else so legitimate
multi-widget dashboards aren't hampered.

Memory storage in this commit (resets on restart). Production multi-replica
swap to `storage: 'database'` planned for a follow-up once the
rateLimit migration is run.

Also: in production, trust X-Forwarded-For / X-Real-IP so the IP that
rate-limit + audit logging see is the real client, not the proxy.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 22:41:47 +02:00
2c57082d8d fix(P1): postgres-js pool reliability — F8
During the audit the dev server twice entered a stuck state where every
query 500'd with `write CONNECT_TIMEOUT` while the DB was healthy (1/100
connections used, queryable from psql immediately). The Docker bridge can
silently drop TCP sockets and postgres-js holds the stale handles until
max_lifetime expires.

- connect_timeout: 10 → 5  (fail fast)
- max_lifetime: 30min → 10min  (recycle before staleness accumulates)
- onnotice: surface NOTICE/WARNING for visibility

Reduces the window of stuck state. Full recovery still requires a
restart if the pool hard-fails. pgbouncer in production is the proper
long-term answer; this is the safe one-file change.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 22:40:24 +02:00
e469b2b6a6 fix(P1): GDPR export + Redis eviction policy
F3: BullMQ 5.x rejects custom job IDs containing `:` (collides with internal
Redis-key namespacing). GDPR export crashed with "Custom Id cannot contain :".
Switched to dash separator. GDPR Article 15 right-to-access now functional.

F4: Redis was configured with `allkeys-lru` eviction in both docker-compose.yml
and docker-compose.prod.yml. BullMQ explicitly requires `noeviction` —
otherwise queue keys can be evicted under memory pressure and jobs vanish
silently. Switched to noeviction with comment pointing at the audit finding.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 22:39:16 +02:00
85bd0d82e1 docs: capture post-audit fix plan from two-round Playwright sweep
24 fixes + 1 new feature, tiered by priority. T0 already shipped in the
previous commit; T1-T4 batches sequenced with effort estimates and file
pointers. Includes the manual-berth-status catch-up workflow design.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 22:38:02 +02:00
446342aa69 fix: P0 — bootstrap proxy + interest detail Date crash
Two pre-deploy blockers found during click-testing:

1. /api/v1/bootstrap/status returned 401 to anonymous visitors because
   /api/v1/bootstrap/ was not in proxy.ts's PUBLIC_PATHS allow-list. Fresh
   VPS deploys couldn't bootstrap their first super-admin via /setup — the
   page reads bootstrap status to decide whether to render the form and got
   no signal back. The route handlers self-protect via hasAnySuperAdmin().

2. getInterestById() crashed every interest detail request with
   `CONNECT_TIMEOUT` / "string argument must be of type string or Buffer"
   because the contact-log count query passed a raw Date through a sql
   template fragment. postgres-js's Bind step can't serialize a Date
   that way. Switched to drizzle's gte() operator which routes the value
   through the column-aware serializer.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 22:37:47 +02:00
b2ba0b4e0a fix(ci): repair pnpm lint for Next 16 + cross-tree ignores
All checks were successful
Build & Push Docker Images / lint (push) Successful in 2m14s
Build & Push Docker Images / build-and-push (push) Successful in 6m30s
Two issues caught when CI ran against the freshly-pushed main:

1. `next lint` is removed in Next 16 — package.json#scripts.lint
   was still `next lint` and aborts with "Invalid project directory
   provided, no such directory: …/lint". Switched to `eslint .`
   (the canonical flat-config invocation; pre-commit already runs
   eslint --fix on staged files via lint-staged).

2. Flat-config rule overrides for `@typescript-eslint/*` rules
   applied to non-TS files when walking the repo root (root-level
   .mjs / config files), failing with "plugin not found" because
   typescript-eslint only registers itself for TS/TSX files. Added
   an explicit `files: ['**/*.ts', '**/*.tsx']` filter to the rule
   block so the override scope matches the plugin's registration
   scope.

Plus tightened the ignores: `.claude/**` (agent worktree artifacts),
`.next/**`, `dist/**`, `website/**` (sub-project with its own
toolchain).

Test files relaxed to `warn` on no-unused-vars since e2e setup /
teardown destructuring patterns frequently leave helper-named locals
unused — fine for tests, not worth churning every spec file.

Result: 0 errors, 36 pre-existing warnings (none added by this
commit). CI lint job should now pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 16:03:37 +02:00
a8607ecc9e docs(plan): close Step 9 — recommender simulator deferred
Some checks failed
Build & Push Docker Images / lint (push) Failing after 36s
Build & Push Docker Images / build-and-push (push) Has been skipped
NocoDB inspection (via MCP) confirms the legacy Interests table carries
only the current Sales Process Level value plus point-in-time event
timestamps as text fields — no dedicated stage-change history table.
That isn't enough resolution to replay stages-over-time through the
recommender's tier-ladder + heat-score weights. Simulator deferred
until ~10+ real wins accumulate under the new pipeline, then we can
simulate against actual CRM history.

The existing /admin/berth-recommender heat-weight tuning UI is
sufficient for v1 launch.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:55:17 +02:00
3c2826635d feat(portal-auth): URL fragment for activation/reset tokens
Step 8 per PRE-DEPLOY-PLAN § 1.2.5.

Activation + password-reset links now carry the token in the URL
fragment (`#token=…`) instead of the query string (`?token=…`). URL
fragments are client-side only — the token never hits the server,
never lands in proxy logs, never sits in the Referer header, and is
invisible to upstream CDN/cache layers. The form still POSTs the
token in the request body to authenticate.

Changes:
- portal-auth.service.ts URL builders for activation + reset switch
  to `#token=`. Inline comments cite the security rationale.
- password-set-form.tsx reads the token via useSyncExternalStore so
  the SSR snapshot returns `null` and the client snapshot reads
  window.location.hash post-hydration (no set-state-in-effect
  Compiler violation). Helper prefers the fragment but falls back to
  the legacy `?token=` search param for the back-compat TTL window —
  so links sent before the switchover still work for their remaining
  lifetime. Component renders a "Loading…" placeholder during the
  pre-hydration null state.

No DB changes; tokens themselves unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:54:15 +02:00
2a2673e328 refactor(terminology): "deal" → "interest" sweep + route rename
Step 7 per PRE-DEPLOY-PLAN § 1.7. The canonical noun for an in-flight
sales record is "interest" everywhere in the codebase — entity name,
schema, kanban label, URL, etc. Customer-visible "deal" remnants are
either a holdover from pre-refactor copy or hand-written admin
descriptions that drifted.

Sweeps applied:

- /admin/qualification-criteria description: "before a deal moves out
  of the Enquiry stage" → "before an interest moves out…"
- /admin/documenso descriptions (×3): "per-deal upload-and-place…" →
  "per-interest upload-and-place…"; "upload per deal" → "upload per
  interest"; "drafted per deal" → "drafted per interest".
- bulk-archive-wizard.tsx placeholder: "late-stage deal" → "late-stage
  interest".
- smart-archive-dialog.tsx title: "Late-stage deal" → "Late-stage
  interest".
- /api/v1/berths/[id]/deal-documents → /api/v1/berths/[id]/interest-documents
  (route directory renamed; the single in-tree caller in
  berth-deal-documents-tab.tsx updated to match; React Query key also
  switched to "berth-interest-documents" for cache hygiene).

The `BerthDealDocumentsTab` component name + `berth-deal-documents-tab.tsx`
file path are intentionally left as-is — pure aliases, internal to the
codebase, churn cost > readability win. Rename when next touched.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:50:56 +02:00
66869c9a90 feat(dashboard): berth-heat widget + investor-default surfacing
Step 6 minimal-but-functional per PRE-DEPLOY-PLAN § 1.6.

Berth Heat — new widget showing top 15 berths by active interest
count via the interest_berths junction (non-primary links included so
multi-berth deals warm every berth in their bundle). Investor-friendly
demand-pressure view; the ranked-table shape exports cleanly to PDF/
CSV. Future heatmap viz reads the same shape via /api/v1/dashboard/
berth-heat.

Defaults flipped for investor-friendliness:
- kpi_pipeline_value → defaultVisible (currency-aware headline number).
- source_conversion → defaultVisible (conversion funnel by source;
  reads the inquiry → client linkage from Step 3).
- berth_heat → defaultVisible.

Pipeline-velocity-over-time + true heatmap viz deferred. pipeline_funnel
covers snapshot stage breakdowns; over-time velocity warrants its own
design pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:47:49 +02:00
709ef350ff feat(bulk-berths): 2-step wizard for new-port setup
Step 5 per PRE-DEPLOY-PLAN § 1.4.13.

Service: bulkAddBerths(portId, inputs, meta) — input-level dedup
catches in-batch duplicates, then a single SELECT against existing
port rows rejects with ConflictError on first collision. All inserts
in one round-trip; audit log + realtime alert.

Validator: bulkAddBerthsSchema with min(1) max(500) per call.

Route: POST /api/v1/berths/bulk-add gated on berths.create.

Wizard UI (/[portSlug]/admin/berths/bulk-add):
  Step 1 — dock letter A-E, range start+end mooring numbers, tenure
    default. Generates N empty rows.
  Step 2 — editable table with per-row dimensions / pontoon / pricing.
    "Apply to all" inputs in the header row copy a value down every
    row at once (covers the "every row is 40ft × 15ft at €125k" case
    in two clicks). Per-row remove button.

Drag-fill deferred. Server-side mooring uniqueness check is canonical;
client-side dedup is a pre-flight courtesy.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:45:06 +02:00
4182652d49 feat(externally-signed): mark contract/reservation as signed without file
Step 4 second slice. Adds the "Mark as signed without file" action to
contract + reservation tabs per PRE-DEPLOY-PLAN § 1.5.14.

Service: `markExternallySigned(interestId, portId, docType, reason)`
flips the relevant doc-status column ('contract_doc_status' /
'reservation_doc_status' / 'eoi_doc_status') to 'signed', writes an
audit log entry with `metadata.type='externally_signed'` capturing
the optional reason, and fires the appropriate berth-rule trigger
(eoi_signed / contract_signed) so downstream automation (berth
status flips, notifications) treats it identically to a Documenso-
signed completion.

Route: POST /api/v1/interests/[id]/mark-externally-signed gated on
interests.edit. Validates docType against the canonical 3-value enum.

UI: <MarkExternallySignedDialog> AlertDialog with optional reason
textarea + per-docType copy. Wired into EmptyContractState and
EmptyReservationState empty-state buttons. The action sits alongside
"Upload draft for signing" and "Upload paper-signed copy" as a third
option for reps whose canonical paper lives elsewhere.

EOI not yet wired into a UI surface — the eoi flow already has a
full upload pipeline. Service supports it for completeness.

Followup: quick brochure/PDF download buttons + per-user reminder
digest schedule still pending in Step 4 backlog.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:42:21 +02:00
a77b3c670a feat(ux): P-4.5 inquiry linkage + docs N+1 parallelization
Step 4 (in progress) — first slice of UX features.

P-4.5: inquiry → client linkage now survives the triage conversion.

- inquiry-inbox.tsx adds `?create=1` to the redirect so the new-client
  sheet auto-opens (the existing prefill_* params were already being
  written but the form never opened).
- client-list.tsx reads prefill_name / prefill_email / prefill_phone /
  prefill_source / prefill_inquiry_id from useSearchParams and passes
  them to ClientForm via a typed `prefill` prop.
- ClientForm hydrates the create-flow initial values from the prefill
  AND threads `sourceInquiryId` through to the createClient mutation.
- createClientSchema accepts `sourceInquiryId`; the existing service
  spread already passes it to drizzle's insert.

Net effect: a website inquiry that gets converted now lands as a
client row with `clients.source_inquiry_id` populated. The conversion
funnel-by-source chart (Step 6) can attribute the win back to the
originating inquiry.

Documents tab N+1: `listInflightWorkflowsAggregatedByEntity` previously
walked direct + every company + every yacht + every related client
sequentially. On a busy client (~25 related entities) this was ~50
sequential round-trips with cumulative latency. Replaced with a single
`Promise.all` over the four lookup groups + nested Promise.all over
the per-entity queries within each group. Same query count, but wall-
clock collapses from "sum of every query" to "max single round-trip"
(typically <100ms now vs >1s before).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:37:23 +02:00
e933e32dbd feat(schema): berths.archived_at + clients.source_inquiry_id + email_bounces
Step 3 schema additions per PRE-DEPLOY-PLAN § 1.4.

berths.archived_at (+ archived_by, archive_reason) — soft-delete column
so retired moorings can be hidden from the public feed and admin lists
without losing historical interest joins. Partial index `idx_berths_active`
on (port_id) WHERE archived_at IS NULL keeps the active-only list path
fast. Already wired:
- /api/public/berths and /api/public/berths/[mooringNumber] now filter
  out archived rows.
- berths.service.listBerths defaults to active-only with an
  ?includeArchived=true escape hatch for the archive bin.

clients.source_inquiry_id — text column with ON DELETE SET NULL FK to
website_submissions(id). Preserves the linkage from a website inquiry
to the client that came out of the "Convert to client" triage flow
(P-4.5). Drives the conversion-funnel-by-source chart (Step 6). The
Drizzle column ships without `.references()` to avoid the cross-file
circular import; the FK lives in the migration SQL.

email_bounces table — bounce-monitoring storage. The DSN poller worker
(forthcoming, depends on this table existing) writes one row per parsed
bounce; consumers join via (original_send_type, original_send_id).
Three secondary indexes cover the expected access patterns (port +
recent bounces; lookup by bounced address; lookup by original send).

Schema additions plus the migration SQL are ready for `pnpm db:push`
(or the migration runner once its journal is backfilled — separate
concern, journal currently stops at 0042 despite migrations through
0065 existing on disk).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:33:20 +02:00
fd2c7d6b12 feat(send-dialog): surface per-port attachment threshold in preview UI
Per PRE-DEPLOY-PLAN § 1.3.9. Adds an informational banner to the
SendDocumentDialog explaining the size cutoff at which the attachment
switches from inline to a 24h signed-link download. Threshold sourced
from the existing `email_attach_threshold_mb` setting, plumbed through
the previewBody return shape so rep-facing dialogs don't need to call
the admin-only sales-config endpoint.

Bounce monitoring deferred to land alongside the email_bounces table
in Step 3 (schema additions).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:27:37 +02:00
d556bb88f7 feat(email-routing): per-category send-from routing infra + admin matrix
Per PRE-DEPLOY-PLAN § 1.3.7. Lays the foundation for admin-configurable
routing of every outbound email category to either the noreply or
sales sender account.

Pieces shipped:
- `src/lib/services/email-routing.ts` — EmailCategory enum (17
  categories covering every shipped surface), DEFAULT_CATEGORY_ROUTING
  map (auth/notifications/EOI-invite → noreply; brochure/PDF/sales
  send-outs → sales), `resolveSenderForCategory()` + a graceful
  fallback to noreply when the resolved sender is sales but creds
  aren't configured.
- `GET / PATCH /api/v1/admin/email/routing` endpoints — gated on
  `admin.manage_settings`. Returns the routing + sales-availability
  flag + canonical category list.
- `EmailRoutingCard` — matrix UI dropped into /admin/email below the
  sales-email-config card. Per-category dropdown auto-disables the
  `sales` option when the port has no sales SMTP creds; explains the
  state in an amber callout. Save-on-change with toast + "Reset to
  defaults" button.

Setting persisted as `system_settings.email_routing` (JSONB blob).
Followup: opportunistic migration of existing dispatchers (sendEmail,
createSalesTransporter callers) to use `resolveSenderForCategory()` —
the defaults preserve current behavior so this is non-blocking.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:24:38 +02:00
bded8b21f1 feat(reporting): money-math sweep — Step 1 PRE-DEPLOY-PLAN
Single coherent commit completing § 1.1 (hot-path correctness) plus
§ 1.1.4.5 (multi-berth EOI mooring fix). Numbers users see are now
self-consistent across dashboard / kanban / hot deals / PDF reports.

## Active-interest sweep (canonical predicate everywhere)

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

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

## Pipeline-value currency conversion

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

3 consumers updated: KpiCards, PipelineValueTile, ActiveDealsTile.

## Occupancy = sold only

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

## Revenue PDF two-card layout

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

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

## Multi-berth EOI mooring (4.5)

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

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

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

## Tests

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

1373/1373 vitest pass. tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:19:38 +02:00
81d4e64f69 refactor(interests): drop pipelineStage='completed' sentinel convention
`outcome` is the canonical terminal-state signal. Pre-2026-05-14
`setInterestOutcome` also forced `pipelineStage='completed'` (a value
outside the 7-stage canon) which:

- broke `safeStage()` (silently coerced to 'enquiry' downstream)
- prevented analytics from answering "what stage was the deal at when
  it closed?" because every closed deal looked identical
- forced belt-and-suspenders filters everywhere ('outcome=won' AND
  'pipeline_stage=completed') that became redundant after migration 0062

Changes:

- `setInterestOutcome` no longer touches pipelineStage. Deal stays at
  whatever stage it was on when the outcome was recorded; outcome is
  the terminal signal. Audit log + websocket emit now carry
  `stageAtOutcome` instead of the stale `oldStage`.

- `clearInterestOutcome` smarter reopen-stage logic: if current stage
  is the legacy 'completed' sentinel (pre-existing rows from before
  this commit), default to 'qualified'. Otherwise preserve the stage
  the deal was at, so reopening drops the rep back where they were.
  Explicit data.reopenStage still wins.

- `/api/v1/admin/dashboard-stats` route reworked: per-stage breakdown
  now filters `outcome IS NULL` (only active rows count per stage);
  `closedTotal` derives from a new `outcome IS NOT NULL` count query;
  `completed30d` switches from `pipelineStage='completed' AND updatedAt`
  to `outcome IS NOT NULL AND outcomeAt` (avoids long-closed deals
  leaking into the window on unrelated edits).

- `berth-interests-tab.tsx` "active" filter switches from
  `pipelineStage !== 'completed'` to `!outcome && !archivedAt` — the
  legacy check stopped matching post-refactor.

- Socket event type `interest:outcomeSet` renames `oldStage` →
  `stageAtOutcome` with a doc-comment explaining the semantics shift.

PIPELINE_STAGES canon is now the only valid pipeline_stage value range
for newly-set outcomes. Legacy rows still carry 'completed' until they
naturally churn through reopen + re-close, at which point they enter
the new convention.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:04:13 +02:00
465650957b fix(pipeline-refactor): purge stale 9-stage name references
Audit of every '*_sent' / '*_signed' / 'in_communication' / 'details_sent'
/ 'deposit_10pct' / 'completed' literal under src/ caught four genuinely
broken sites that migration 0062 collapsed away but the runtime code
never followed through on:

1. alert-rules.ts: `interest.stale` matched 'details_sent' /
   'in_communication' / 'eoi_sent' — none of which exist post-migration.
   The alert never fired. Updated to the new mid-funnel canon (enquiry /
   qualified / nurturing).

2. berth-recommender.service.ts: TWO copies of the same stage-rank CASE
   (one for active history, one for fallthrough scoring) referenced the
   full legacy 8-stage ladder. Every WHEN missed → MAX(...) returned 0 →
   tier-ladder + heat-score logic collapsed silently. Rebuilt both
   against the 7-stage canon mirroring getHotDeals.

3. interests.service.ts: clearInterestOutcome reopen default was the
   dead 'in_communication'. Switched to 'qualified' (closest analog;
   rep can still override via data.reopenStage). Pre-fix, any reopened
   deal fell through safeStage() to 'enquiry'.

4. report-generators.ts: revenue-PDF "total completed" filter
   intersected pipeline_stage='completed' AND outcome='won'. The stage
   filter is redundant today (setInterestOutcome always writes
   'completed' for terminal outcomes) and is brittle to the upcoming
   sentinel-stage cleanup. Dropped the stage filter — outcome='won' is
   the canonical money-changed-hands signal.

Follow-up flagged: setInterestOutcome still writes pipeline_stage =
'completed' as a sentinel, which is non-canonical under the new 7-stage
type (PIPELINE_STAGES doesn't include 'completed'). Migration 0062's
intent is `outcome` carries terminal state forward; pipeline_stage stays
in-canon. Cleaning up requires sweeping every consumer of
pipeline_stage='completed' as a terminal marker — separate commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 14:56:58 +02:00
b966d8106d feat(active-interest): canonical predicate + fix stale getHotDeals rank
Extract activeInterestsWhere(portId) as the single source of truth for
"active interest" SQL filtering: scoped + archived_at IS NULL + outcome
IS NULL. Won deals are now CLOSED, not active — pre-2026-05-14 the
dashboard used a permissive `outcome IS NULL OR outcome = 'won'` that
double-counted won revenue against the in-flight pipeline.

Locked in PRE-DEPLOY-PLAN § 1.1.2.

Bonus catch: getHotDeals rank-CASE referenced the OLD 9-stage pipeline
names ('completed', 'contract_signed', 'contract_sent', 'deposit_10pct',
'eoi_signed', 'eoi_sent', 'in_communication', 'details_sent'). Every
row hit the ELSE 0 branch under the new 7-stage model, collapsing
ordering to updatedAt only — the widget silently stopped surfacing
"closest to closing". Rebuilt the rank ladder against the current
canonical stages (enquiry → ... → contract).

Tests: 2 unit tests assert the predicate's compiled SQL contains
"archived_at" IS NULL + "outcome" IS NULL, and never the legacy 'won'
literal.

Remaining sweep targets queued for the next commit:
- client-archive-dossier.service.ts
- client-restore.service.ts
- client-archive.service.ts
- reminders.service.ts
- berths.service.ts (recommender feasibility)
- interests.service.ts
- report-generators.ts

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 14:53:58 +02:00
f86f511e7b docs(plan): lock pre-deploy plan from 2026-05-14 planning session
Single source of truth for everything between today and initial VPS
deploy. Captures every decision reached across the 2026-05-14 rounds:

- Hot-path correctness: canonical active-interest definition, currency-
  aware pipeline value, occupancy=sold, two-card revenue PDF, multi-
  berth EOI mooring rendering via existing Berth Number form field.
- Security gate: portal activation/reset URLs switch to URL fragment.
- Email refactor: drop signature field, per-category send-from routing,
  per-port IMAP bounce monitoring, compose-UI attachment-threshold
  banner.
- Schema: berths.archived_at, clients.metadata.source_inquiry_id,
  email_bounces table.
- UX: externally-signed mark, contract paper-upload endpoint, inquiry
  P-4.5 linkage, quick brochure/PDF download, per-user digest schedule,
  documents-tab N+1 batch fix.
- Bulk berth wizard for new-port setup.
- Four investor charts as toggleable dashboard widgets.
- Mechanical "deal" -> "interest" sweep incl. route rename.

Implementation order + deferred items + operator deploy checklist all
captured. Future agents resuming this work start here.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 14:49:13 +02:00
c44d818144 docs(backlog): mark set-state-in-effect migration as DONE
Wave 3 of the 2026-05-12 audit cleared all ~45 useEffect→fetch→
setState sites; eslint.config.mjs promoted the rule to error in the
same sweep. BACKLOG's "next pass" entry was stale from before that.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 03:51:30 +02:00
080e1fa454 perf(audit-log): wire DataTable virtual prop on audit-log-list
Audit log entries accumulate via cursor pagination — the user can
load many pages into the same client-side array. With virtual=true
the table only renders the visible viewport rows (plus overscan), so
a 10k-row session stays at 60fps instead of choking on a full DOM
write per "Load more" click.

The other two BACKLOG candidates (super-admin port switcher, client
export modal preview) aren't present in the current codebase — the
super-admin route group hasn't been built and the export modal is
download-only. Skip until those surfaces exist.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 03:50:34 +02:00
233129f91a feat(qualification-criteria): dnd reordering with whole-list PATCH
The chevron up/down buttons rewrote a single row's display_order,
which didn't actually swap positions since the neighbouring rows kept
their original orders. Replaced with a proper drag-handle (dnd-kit
sortable, matching the waiting-list-manager pattern) backed by a new
POST /admin/qualification-criteria/reorder endpoint that rewrites
display_order = index for every row in a transaction. The service
rejects partial / extraneous id lists so a stale UI can't silently
drop a criterion. Optimistic local-cache update keeps the row in
position during the round-trip; rollback on error.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 03:49:17 +02:00
905852b8a5 feat(permissions): carve out dedicated payments resource
Payments (deposit / balance / refund records on an interest) used to
share `invoices.record_payment`, which forces a port that doesn't
issue invoices at all to still navigate the invoicing permission
group to grant its sales reps payment-recording rights. Splitting
the resource lets admins gate the two surfaces independently.

The new resource has three actions:
  - view   — gates the UI affordance (API reads still go through
             `interests.view`)
  - record — POST / PATCH a payment
  - delete — DELETE a payment record

Seed maps updated for all six system roles; existing role rows +
per-user permission overrides are backfilled by migration 0064 so
upgrades don't silently lose access. Two call sites (POST /interests/
[id]/payments, PATCH /payments/[id]) → payments.record; one
(DELETE /payments/[id]) → payments.delete. The PermissionGates on the
payments-section UI swap to the new keys.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 03:46:01 +02:00
6b28459c45 feat(pipeline): 9→7 stage refactor + v1.1 hardening wave
Replaces the legacy 9-stage pipeline with 7 canonical stages
(enquiry → qualified → eoi → reservation → deposit_paid → contract →
nurturing) plus three doc sub-status columns (eoi_doc_status,
reservation_doc_status, contract_doc_status) that track sent/signed
within a single stage instead of branching it.

Schema (migration 0062):
- interests gains assigned_to, deposit_expected_amount/currency,
  three doc-status columns, two documenso-id columns, and
  date_reservation_signed.
- New tables: qualification_criteria (per-port admin-configurable),
  interest_qualifications (per-interest state), payments (deposit /
  balance / refund records keyed to interest + client).
- Default qualification criteria seeded for every existing port.
- Dummy-data UPDATEs collapse Sent/Signed pairs and 'completed' into
  the new stage + doc-status + outcome shape.

Migration 0063 adds interest_contact_log.voice_transcript and
template_used columns for v1.1-A/B (quick-template buttons + voice
transcription via Web Speech API).

v1.1 phase work bundled here:
- A/B: Quick-template buttons (Call / Visit / Email) + mic toggle on
       the contact-log compose dialog (useVoiceTranscription hook).
- C:   berth-rules-engine wraps state writes in pg_advisory_xact_lock
       with an idempotent re-read; emits rule_evaluated audit traces.
- D:   Documenso webhook: reservation/contract sub-status stamping
       moved out of the PDF-download try-block so a download failure
       no longer swallows the stamp. New integration test coverage.
- E:   /admin/qualification-criteria CRUD page + admin component.
- F:   default_new_interest_owner exposed in System Settings.
- G:   recentActivityCount + active_engagement deal-pulse signal
       surfaced as a chip on interests + hot-deals card.
- H:   interest_assigned notification on assignedTo change (skips
       self-assign, uses a dedupe key).

Plus the supporting components: AssignedToChip, DealPulseChip,
PaymentsSection, QualificationChecklist, MultiEoiChip,
SkipAheadBanner, WonStatusPanel, InterestBerthStatusBanner,
SupplementalInfoRequestButton, UserPicker.

Tests: 1370/1370 vitest pass (added deal-health unit suite +
expanded constants/validators/pipeline-transitions coverage). tsc
clean, eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 03:39:21 +02:00
b10bf9bf8e fix(bootstrap): include missing bootstrap.service helper
The route handlers in 1a65e02 import hasAnySuperAdmin and
createInitialSuperAdmin from this file; was accidentally left
untracked.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 03:38:16 +02:00
1a65e02885 feat(bootstrap): first-run super-admin setup flow
Fresh-DB detection on the login screen — if no super-admin row
exists, /api/v1/bootstrap/status reports needsBootstrap and login
redirects to /setup, which mints the first super-admin via
/api/v1/bootstrap/super-admin. Endpoint refuses once any user
already exists.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 03:37:19 +02:00
0fe3e984d1 feat(supplemental-info): pre-EOI public form flow
Lets a sales rep send a client a one-shot link to fill out the
information we need before drafting the EOI (intent, dimensions,
signatory, timeline). Token-keyed: single-use, soft-expiring, scoped
to one interest + client. Public POST endpoint accepts the form
submission; CRM endpoint mints tokens for rep-initiated requests;
portal page renders the form for the recipient.

Schema: supplemental_form_tokens table (migration 0061) with port_id
+ interest_id + client_id refs, unique token, consumed_at marker.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 03:36:56 +02:00
e11529ffcc refactor(activity-feed): collapse/expand grouping + verb-tense rewrite
Action labels switch to past-tense verbs (created/updated/deleted/…)
and the feed now groups bursts of rapid edits under one expandable
header so a 12-field form save stops drowning out other events.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 03:35:35 +02:00
05b57abf05 refactor(settings): consolidate user profile into single settings page
Drop the standalone /settings/profile route + user-profile component;
folding the same fields into user-settings means one place to update
and one menu item. UserMenu loses the Profile dropdown entry.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 03:35:07 +02:00
12e22d9be3 fix(ui+auth): origin-forwarding for sign-in + disable dark mode + center dialog
Three related cleanups while QA-testing on iPad:

1. Origin-forwarding bug on /api/auth/sign-in-by-identifier
   - The custom identifier-sign-in route forwarded to better-auth's
     /sign-in/email handler but did NOT preserve the inbound Origin +
     Referer headers. Better-auth's CSRF check then 403'd every login
     with MISSING_OR_NULL_ORIGIN — and the UI showed a generic
     "Invalid credentials" toast even when the password was right.
   - Fix: pass through req.headers.get('origin') and
     req.headers.get('referer') when constructing forwardReq.
   - Affects: every login attempt from any device (this isn't dev-
     only); discovered testing from 192.168.1.17 → app on the same
     LAN IP. Production users hit the same path.

2. Dark mode disabled
   - Drop the Sun/Moon toggle from user-menu, the documentElement
     class flip, darkMode from ui-store, darkMode from the user-
     preferences validator. Hardcode sonner theme="light" (was
     reading next-themes which isn't actually wired anywhere else).
   - The 10 stray `dark:` Tailwind utilities are left alone — they're
     inactive without the `dark` class on <html> so they don't ship
     anything that renders, just dead CSS.

3. Center dialog animation
   - Dialog content was sliding in from the top-right corner (slide-
     in-from-left-1/2 + slide-in-from-top-[48%]) which felt jarring.
     Drop the slide directions, keep just zoom-in-95 + the base
     fade-in/out so dialogs appear in place with a subtle scale-up.

4. Login placeholder
   - Removed the "you@example.com  or  yourname" placeholder so the
     field reads as a clean empty input below the "Email or username"
     label.

No tests added (the 1340 vitest suite passes); changes are surface-
level UI tweaks + the origin-header fix where a unit-test of the
custom route would mostly be testing better-auth's behaviour.

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