2026-05-21 18:06:41 +02:00
|
|
|
import { and, desc, eq, ilike, inArray, isNull, or, sql } from 'drizzle-orm';
|
2026-04-23 23:40:56 +02:00
|
|
|
import { db } from '@/lib/db';
|
feat(platform): residential module + admin UI + reliability fixes
Residential platform
- New schema: residentialClients, residentialInterests (separate from
marina/yacht clients) with migration 0010
- Service layer with CRUD + audit + sockets + per-port portal toggle
- v1 + public API routes (/api/v1/residential/*, /api/public/residential-inquiries)
- List + detail pages with inline editing for clients and interests
- Per-user residentialAccess toggle on userPortRoles (migration 0011)
- Permission keys: residential_clients, residential_interests
- Sidebar nav + role form integration
- Smoke spec covering page loads, UI create flow, public endpoint
Admin & shared UI
- Admin → Forms (form templates CRUD) with validators + service
- Notification preferences page (in-app + email per type)
- Email composition + accounts list + threads view
- Branded auth shell shared across CRM + portal auth surfaces
- Inline editing extended to yacht/company/interest detail pages
- InlineTagEditor + per-entity tags endpoints (yachts, companies)
- Notes service polymorphic across clients/interests/yachts/companies
- Client list columns: yachtCount + companyCount badges
- Reservation file-download via presigned URL (replaces stale <a href>)
Route handler refactor
- Extracted yachts/companies/berths reservation handlers to sibling
handlers.ts files (Next.js 15 route.ts only allows specific exports)
Reliability fixes
- apiFetch double-stringify bug fixed across 13 components
(apiFetch already JSON.stringifies its body; passing a stringified
body produced double-encoded JSON which failed zod validation)
- SocketProvider gated behind useSyncExternalStore-based mount check
to avoid useSession() SSR crashes under React 19 + Next 15
- apiFetch falls back to URL-pathname → port-id resolution when the
Zustand store hasn't hydrated yet (fresh contexts, e2e tests)
- CRM invite flow (schema, service, route, email, dev script)
- Dashboard route → [portSlug]/dashboard/page.tsx + redirect
- Document the dev-server restart-after-migration gotcha in CLAUDE.md
Tests
- 5-case residential smoke spec
- Integration test updates for new service signatures
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 21:54:32 +02:00
|
|
|
import { yachts, yachtOwnershipHistory, yachtTags, clients } from '@/lib/db/schema';
|
feat(yachts): list + owner-scoped list + autocomplete
Adds `listYachts`, `listYachtsForOwner`, and `autocomplete` to the
yacht service so UIs can page/filter yachts per port, look up all
yachts tied to a given client/company, and power search-as-you-type.
`listYachts` delegates to the shared port-scoped `buildListQuery`,
supporting search over name/hullNumber/registration plus ownerType,
ownerId and status filters; `autocomplete` caps at 10 results and is
tenant-scoped; `listYachtsForOwner` returns all yachts whose current
owner matches, newest first. Extends `makeYacht` factory to accept
flat `name`, `status`, `hullNumber`, `registration` overrides.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 00:03:36 +02:00
|
|
|
import type { Yacht } from '@/lib/db/schema/yachts';
|
2026-04-23 23:40:56 +02:00
|
|
|
import { companies } from '@/lib/db/schema/companies';
|
fix(audit-wave-10): types-auditor fixes — Tx type, BerthDetailData, parseBody, toAuditJson
Address the CRITICAL + high-leverage HIGH items from the types-auditor:
**C1 — `tx: any` in client-restore.service**
Export a canonical `Tx` type from `lib/db/utils.ts` (derived from
Drizzle's `db.transaction` callback shape) and use it in
`applyReversal` so the 12+ downstream tx writes get full inference.
**C2 — berth-detail page stacked `useQuery<any>` escape hatches**
Export `BerthDetailData` from berth-detail-header and consume it
through useQuery + apiFetch. Removed three `any` escapes in the
highest-traffic detail page. Also collapsed the duplicate `BerthData`
in berth-tabs.tsx to import from berth-detail-header so the two
types can't drift.
**C3 — parseBody migration for portal/public routes**
Replace raw `await req.json() + schema.parse(body)` with the
project-standard `parseBody(req, schema)` helper across 7 routes:
- portal/auth/{change-password, activate, reset-password}
- auth/set-password
- public/{interests, residential-inquiries}
Skipped the three anti-enumeration routes (forgot-password, sign-in,
sign-in-by-identifier) where the manual validation gives opaque
errors on purpose. website-inquiries already wraps the parse in a
custom 400 — left as-is.
**HIGH #5 — `toAuditJson<T>` helper (21 → 0 inline casts)**
Introduce `toAuditJson<T extends object>(row: T): Record<string,
unknown>` in lib/audit.ts (mirrors gdpr-bundle-builder's `toJsonRow`
that already exists for the same reason). Codemod 21 `<row> as unknown
as Record<string, unknown>` sites across:
- invoices.ts × 6
- expenses.ts × 6
- berths.service × 2
- documents.service × 2
- ocr-config.service × 2
- ai-budget.service × 2
- yachts.service, companies.service, company-memberships.service × 1 each
document-templates' `payload as unknown as Record<...>` is a different
shape (Documenso form-values widening, not an audit log) — kept the
manual cast there. Tests stay 1315/1315.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 12:27:08 +02:00
|
|
|
import { createAuditLog, toAuditJson, type AuditMeta } from '@/lib/audit';
|
2026-04-23 23:40:56 +02:00
|
|
|
import { NotFoundError, ValidationError } from '@/lib/errors';
|
2026-05-11 11:25:16 +02:00
|
|
|
import { logger } from '@/lib/logger';
|
2026-05-11 11:34:02 +02:00
|
|
|
import {
|
|
|
|
|
syncEntityFolderName,
|
|
|
|
|
applyEntityArchivedSuffix,
|
|
|
|
|
} from '@/lib/services/document-folders.service';
|
2026-04-23 23:40:56 +02:00
|
|
|
import { emitToRoom } from '@/lib/socket/server';
|
2026-04-29 01:58:42 +02:00
|
|
|
import { setEntityTags } from '@/lib/services/entity-tags.helper';
|
2026-04-23 23:52:24 +02:00
|
|
|
import { diffEntity } from '@/lib/entity-diff';
|
feat(yachts): list + owner-scoped list + autocomplete
Adds `listYachts`, `listYachtsForOwner`, and `autocomplete` to the
yacht service so UIs can page/filter yachts per port, look up all
yachts tied to a given client/company, and power search-as-you-type.
`listYachts` delegates to the shared port-scoped `buildListQuery`,
supporting search over name/hullNumber/registration plus ownerType,
ownerId and status filters; `autocomplete` caps at 10 results and is
tenant-scoped; `listYachtsForOwner` returns all yachts whose current
owner matches, newest first. Extends `makeYacht` factory to accept
flat `name`, `status`, `hullNumber`, `registration` overrides.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 00:03:36 +02:00
|
|
|
import { buildListQuery } from '@/lib/db/query-builder';
|
2026-04-23 23:47:12 +02:00
|
|
|
import { withTransaction } from '@/lib/db/utils';
|
2026-04-23 23:40:56 +02:00
|
|
|
import type { z } from 'zod';
|
2026-04-23 23:58:20 +02:00
|
|
|
import type {
|
|
|
|
|
createYachtSchema,
|
|
|
|
|
UpdateYachtInput,
|
|
|
|
|
TransferOwnershipInput,
|
feat(yachts): list + owner-scoped list + autocomplete
Adds `listYachts`, `listYachtsForOwner`, and `autocomplete` to the
yacht service so UIs can page/filter yachts per port, look up all
yachts tied to a given client/company, and power search-as-you-type.
`listYachts` delegates to the shared port-scoped `buildListQuery`,
supporting search over name/hullNumber/registration plus ownerType,
ownerId and status filters; `autocomplete` caps at 10 results and is
tenant-scoped; `listYachtsForOwner` returns all yachts whose current
owner matches, newest first. Extends `makeYacht` factory to accept
flat `name`, `status`, `hullNumber`, `registration` overrides.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 00:03:36 +02:00
|
|
|
ListYachtsInput,
|
2026-04-23 23:58:20 +02:00
|
|
|
} from '@/lib/validators/yachts';
|
2026-04-23 23:40:56 +02:00
|
|
|
|
|
|
|
|
type CreateYachtInput = z.input<typeof createYachtSchema>;
|
|
|
|
|
|
|
|
|
|
async function assertOwnerExists(
|
|
|
|
|
portId: string,
|
|
|
|
|
owner: { type: 'client' | 'company'; id: string },
|
2026-04-23 23:46:03 +02:00
|
|
|
tx: typeof db,
|
2026-04-23 23:40:56 +02:00
|
|
|
): Promise<void> {
|
|
|
|
|
if (owner.type === 'client') {
|
2026-04-23 23:46:03 +02:00
|
|
|
const client = await tx.query.clients.findFirst({
|
2026-04-23 23:40:56 +02:00
|
|
|
where: and(eq(clients.id, owner.id), eq(clients.portId, portId)),
|
|
|
|
|
});
|
|
|
|
|
if (!client) throw new ValidationError('owner not found');
|
|
|
|
|
} else {
|
2026-04-23 23:46:03 +02:00
|
|
|
const company = await tx.query.companies.findFirst({
|
2026-04-23 23:40:56 +02:00
|
|
|
where: and(eq(companies.id, owner.id), eq(companies.portId, portId)),
|
|
|
|
|
});
|
|
|
|
|
if (!company) throw new ValidationError('owner not found');
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function createYacht(portId: string, data: CreateYachtInput, meta: AuditMeta) {
|
2026-04-23 23:47:12 +02:00
|
|
|
return await withTransaction(async (tx) => {
|
|
|
|
|
await assertOwnerExists(portId, data.owner, tx);
|
2026-04-23 23:40:56 +02:00
|
|
|
|
|
|
|
|
const [yacht] = await tx
|
|
|
|
|
.insert(yachts)
|
|
|
|
|
.values({
|
|
|
|
|
portId,
|
|
|
|
|
name: data.name,
|
|
|
|
|
hullNumber: data.hullNumber ?? null,
|
|
|
|
|
registration: data.registration ?? null,
|
|
|
|
|
flag: data.flag ?? null,
|
|
|
|
|
yearBuilt: data.yearBuilt ?? null,
|
|
|
|
|
builder: data.builder ?? null,
|
|
|
|
|
model: data.model ?? null,
|
|
|
|
|
hullMaterial: data.hullMaterial ?? null,
|
|
|
|
|
lengthFt: data.lengthFt ?? null,
|
|
|
|
|
widthFt: data.widthFt ?? null,
|
|
|
|
|
draftFt: data.draftFt ?? null,
|
|
|
|
|
lengthM: data.lengthM ?? null,
|
|
|
|
|
widthM: data.widthM ?? null,
|
|
|
|
|
draftM: data.draftM ?? null,
|
|
|
|
|
currentOwnerType: data.owner.type,
|
|
|
|
|
currentOwnerId: data.owner.id,
|
|
|
|
|
status: data.status ?? 'active',
|
|
|
|
|
notes: data.notes ?? null,
|
chore(autonomous-session): consolidate uncommitted work from prior session
Bundles the prior autonomous-session output that was sitting unstaged:
- Em-dash sweep across src/ + tests/ (en-dash/em-dash to hyphen, ~2280 instances)
- country-flag-icons rollout (CountryFlag component, replaces emoji glyphs that
never rendered on Windows; lazy-loads the 3x2 SVG index as a single chunk
after the per-subpath dynamic-import approach silently failed in webpack)
- Admin IA Phase 1+2: 7-domain regroup, 41 to 38 pages, /admin/berths index,
redirects (ocr to ai, reports to dashboard, invitations to users),
docs/admin-ia-proposal.md
- Per-template email tester (registry + endpoint + UI on Email admin page)
- Cancel-document mode picker (delete-from-Documenso vs keep-for-audit)
- Dashboard PDF report: 25 widgets, SVG charts, date-range picker, 11 resolvers
- Customize-widgets per-region sortables at xl+ (charts/rails/feed); single
flat sortable below xl when the layout stacks; per-viewport saved orders
- Audit doc updates capturing each shipped item
- Lint fixes: react-compiler immutability in DonutChart (reduce instead of
let-reassign), set-state-in-effect disables in CountryFlag and
UploadForSigning preview-bytes effect, unused 'confirm' destructures in
interest contract + reservation tabs, unescaped apostrophe in test-template
card copy
2026-05-23 00:52:59 +02:00
|
|
|
// Phase 3c - origin tracking. Defaults to 'manual' at the DB
|
2026-05-18 16:18:03 +02:00
|
|
|
// level; pass-through allows the EOI spawn flow to mark the row
|
|
|
|
|
// as 'eoi-generated' with the generating document_id.
|
|
|
|
|
source: data.source ?? 'manual',
|
|
|
|
|
sourceDocumentId: data.sourceDocumentId ?? null,
|
2026-04-23 23:40:56 +02:00
|
|
|
})
|
|
|
|
|
.returning();
|
|
|
|
|
|
|
|
|
|
await tx.insert(yachtOwnershipHistory).values({
|
|
|
|
|
yachtId: yacht!.id,
|
|
|
|
|
ownerType: data.owner.type,
|
|
|
|
|
ownerId: data.owner.id,
|
|
|
|
|
startDate: new Date(),
|
|
|
|
|
endDate: null,
|
|
|
|
|
createdBy: meta.userId,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
void createAuditLog({
|
|
|
|
|
userId: meta.userId,
|
|
|
|
|
portId,
|
|
|
|
|
action: 'create',
|
|
|
|
|
entityType: 'yacht',
|
|
|
|
|
entityId: yacht!.id,
|
|
|
|
|
newValue: { name: yacht!.name, owner: data.owner },
|
|
|
|
|
ipAddress: meta.ipAddress,
|
|
|
|
|
userAgent: meta.userAgent,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
emitToRoom(`port:${portId}`, 'yacht:created', { yachtId: yacht!.id });
|
|
|
|
|
|
|
|
|
|
return yacht!;
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function getYachtById(id: string, portId: string) {
|
|
|
|
|
const yacht = await db.query.yachts.findFirst({
|
|
|
|
|
where: and(eq(yachts.id, id), eq(yachts.portId, portId)),
|
feat(platform): residential module + admin UI + reliability fixes
Residential platform
- New schema: residentialClients, residentialInterests (separate from
marina/yacht clients) with migration 0010
- Service layer with CRUD + audit + sockets + per-port portal toggle
- v1 + public API routes (/api/v1/residential/*, /api/public/residential-inquiries)
- List + detail pages with inline editing for clients and interests
- Per-user residentialAccess toggle on userPortRoles (migration 0011)
- Permission keys: residential_clients, residential_interests
- Sidebar nav + role form integration
- Smoke spec covering page loads, UI create flow, public endpoint
Admin & shared UI
- Admin → Forms (form templates CRUD) with validators + service
- Notification preferences page (in-app + email per type)
- Email composition + accounts list + threads view
- Branded auth shell shared across CRM + portal auth surfaces
- Inline editing extended to yacht/company/interest detail pages
- InlineTagEditor + per-entity tags endpoints (yachts, companies)
- Notes service polymorphic across clients/interests/yachts/companies
- Client list columns: yachtCount + companyCount badges
- Reservation file-download via presigned URL (replaces stale <a href>)
Route handler refactor
- Extracted yachts/companies/berths reservation handlers to sibling
handlers.ts files (Next.js 15 route.ts only allows specific exports)
Reliability fixes
- apiFetch double-stringify bug fixed across 13 components
(apiFetch already JSON.stringifies its body; passing a stringified
body produced double-encoded JSON which failed zod validation)
- SocketProvider gated behind useSyncExternalStore-based mount check
to avoid useSession() SSR crashes under React 19 + Next 15
- apiFetch falls back to URL-pathname → port-id resolution when the
Zustand store hasn't hydrated yet (fresh contexts, e2e tests)
- CRM invite flow (schema, service, route, email, dev script)
- Dashboard route → [portSlug]/dashboard/page.tsx + redirect
- Document the dev-server restart-after-migration gotcha in CLAUDE.md
Tests
- 5-case residential smoke spec
- Integration test updates for new service signatures
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 21:54:32 +02:00
|
|
|
with: {
|
|
|
|
|
tags: { with: { tag: true } },
|
|
|
|
|
},
|
2026-04-23 23:40:56 +02:00
|
|
|
});
|
|
|
|
|
if (!yacht) throw new NotFoundError('Yacht');
|
feat(platform): residential module + admin UI + reliability fixes
Residential platform
- New schema: residentialClients, residentialInterests (separate from
marina/yacht clients) with migration 0010
- Service layer with CRUD + audit + sockets + per-port portal toggle
- v1 + public API routes (/api/v1/residential/*, /api/public/residential-inquiries)
- List + detail pages with inline editing for clients and interests
- Per-user residentialAccess toggle on userPortRoles (migration 0011)
- Permission keys: residential_clients, residential_interests
- Sidebar nav + role form integration
- Smoke spec covering page loads, UI create flow, public endpoint
Admin & shared UI
- Admin → Forms (form templates CRUD) with validators + service
- Notification preferences page (in-app + email per type)
- Email composition + accounts list + threads view
- Branded auth shell shared across CRM + portal auth surfaces
- Inline editing extended to yacht/company/interest detail pages
- InlineTagEditor + per-entity tags endpoints (yachts, companies)
- Notes service polymorphic across clients/interests/yachts/companies
- Client list columns: yachtCount + companyCount badges
- Reservation file-download via presigned URL (replaces stale <a href>)
Route handler refactor
- Extracted yachts/companies/berths reservation handlers to sibling
handlers.ts files (Next.js 15 route.ts only allows specific exports)
Reliability fixes
- apiFetch double-stringify bug fixed across 13 components
(apiFetch already JSON.stringifies its body; passing a stringified
body produced double-encoded JSON which failed zod validation)
- SocketProvider gated behind useSyncExternalStore-based mount check
to avoid useSession() SSR crashes under React 19 + Next 15
- apiFetch falls back to URL-pathname → port-id resolution when the
Zustand store hasn't hydrated yet (fresh contexts, e2e tests)
- CRM invite flow (schema, service, route, email, dev script)
- Dashboard route → [portSlug]/dashboard/page.tsx + redirect
- Document the dev-server restart-after-migration gotcha in CLAUDE.md
Tests
- 5-case residential smoke spec
- Integration test updates for new service signatures
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 21:54:32 +02:00
|
|
|
const { tags: tagJoins, ...rest } = yacht as typeof yacht & {
|
|
|
|
|
tags: Array<{ tag: { id: string; name: string; color: string } }>;
|
|
|
|
|
};
|
feat(launch-readiness-batch): UAT drains, navigation refactor, launch infra, trackers
Bundles the rest of the in-flight work from this UAT round into one
checkpoint. Each sub-area is independent; see the headings below.
UAT polish (drained 11 findings from active-uat.md):
- Dialog primitive default bumped sm:max-w-xl/lg:max-w-3xl →
sm:max-w-2xl/lg:max-w-4xl so multi-field forms + PDF previews
aren't cramped at 1440-1920px.
- Notes tab badge aggregation: new countFor{Client,Yacht,Company}
Aggregated helpers in notes.service mirror the listFor*Aggregated
symmetric-reach joins. yacht-tabs + company-tabs render the
badge; client-tabs already had badge support.
- Supplemental-info form polish bundle: BrandedAuthShell gains a
`width: 'sm' | 'md'` prop (md uses min-h-dvh scroll instead of
fixed inset-0 pin so long forms scroll naturally). Form picks up
port branding (logoUrl + backgroundUrl + appName) via
loadByToken. Address fields completed (street + city + region +
postal + country). Port name eyebrow + success-state copy added.
- new-document-menu Upload-file landing toast: per-file completion
emits toast.success with action link to the destination entity
or folder.
- interest-tabs OverviewTab "from client" pill on Email + Phone
rows via new EditableRow `inheritedFrom` prop.
- create-document-wizard subject picker → segmented button strip
(5 types visible at once).
Launch infra:
- UTM column wiring (Init 1b step 4): migration
0089_website_submissions_utm.sql adds utm_source/medium/campaign/
term/content + composite index (port_id, utm_source, received_at)
for per-campaign rollups. website-inquiries intake accepts the
five fields. Residential intake intentionally untouched per audit
scope.
- Invoicing module gate (Init 1c spike): new
invoices-module.service + invoices layout guard + registry entry
invoices_module_enabled (default false). Audit conclusion in
launch-readiness.md: payments table is canonical money path;
/invoices flow is parallel infrastructure now hidden by default.
Smart-back navigation refactor:
- Replaced breadcrumb component with history-aware Back button.
New route-labels.ts + use-smart-back hook +
navigation-history-tracker so back falls through to the parent
route when there's no prior page in history.
- Sidebar / topbar / mobile-topbar adopt the new pattern; old
breadcrumb-store kept for back-compat consumers but the
breadcrumbs component is gone.
- 6 detail pages (admin/errors per-id + codes, invoices/
upload-receipts, reports kind, tenancies detail, analytics
metric, client detail) migrated.
Trackers + docs:
- docs/launch-readiness.md — master pre-launch tracker. Includes
the reports gap audit (cross-cutting filter set, Marketing +
Financial blockers, custom builder remaining entities, scheduled
CSV/XLSX, template scope picker).
- docs/superpowers/audits/active-uat.md — 15 findings flipped
OPEN → SHIPPED locally with fix-applied notes; 4 OPEN remaining
(each blocked on user input or cross-repo).
- CLAUDE.md — minor session notes carried forward.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27 22:42:37 +02:00
|
|
|
|
|
|
|
|
// Aggregated note count for the Notes tab badge. Mirrors the
|
|
|
|
|
// symmetric-reach used by the NotesList that renders below it.
|
|
|
|
|
const { countForYachtAggregated } = await import('@/lib/services/notes.service');
|
|
|
|
|
const noteCount = await countForYachtAggregated(portId, id).catch(() => 0);
|
|
|
|
|
|
feat(platform): residential module + admin UI + reliability fixes
Residential platform
- New schema: residentialClients, residentialInterests (separate from
marina/yacht clients) with migration 0010
- Service layer with CRUD + audit + sockets + per-port portal toggle
- v1 + public API routes (/api/v1/residential/*, /api/public/residential-inquiries)
- List + detail pages with inline editing for clients and interests
- Per-user residentialAccess toggle on userPortRoles (migration 0011)
- Permission keys: residential_clients, residential_interests
- Sidebar nav + role form integration
- Smoke spec covering page loads, UI create flow, public endpoint
Admin & shared UI
- Admin → Forms (form templates CRUD) with validators + service
- Notification preferences page (in-app + email per type)
- Email composition + accounts list + threads view
- Branded auth shell shared across CRM + portal auth surfaces
- Inline editing extended to yacht/company/interest detail pages
- InlineTagEditor + per-entity tags endpoints (yachts, companies)
- Notes service polymorphic across clients/interests/yachts/companies
- Client list columns: yachtCount + companyCount badges
- Reservation file-download via presigned URL (replaces stale <a href>)
Route handler refactor
- Extracted yachts/companies/berths reservation handlers to sibling
handlers.ts files (Next.js 15 route.ts only allows specific exports)
Reliability fixes
- apiFetch double-stringify bug fixed across 13 components
(apiFetch already JSON.stringifies its body; passing a stringified
body produced double-encoded JSON which failed zod validation)
- SocketProvider gated behind useSyncExternalStore-based mount check
to avoid useSession() SSR crashes under React 19 + Next 15
- apiFetch falls back to URL-pathname → port-id resolution when the
Zustand store hasn't hydrated yet (fresh contexts, e2e tests)
- CRM invite flow (schema, service, route, email, dev script)
- Dashboard route → [portSlug]/dashboard/page.tsx + redirect
- Document the dev-server restart-after-migration gotcha in CLAUDE.md
Tests
- 5-case residential smoke spec
- Integration test updates for new service signatures
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 21:54:32 +02:00
|
|
|
return {
|
|
|
|
|
...rest,
|
|
|
|
|
tags: tagJoins.map((t) => t.tag),
|
feat(launch-readiness-batch): UAT drains, navigation refactor, launch infra, trackers
Bundles the rest of the in-flight work from this UAT round into one
checkpoint. Each sub-area is independent; see the headings below.
UAT polish (drained 11 findings from active-uat.md):
- Dialog primitive default bumped sm:max-w-xl/lg:max-w-3xl →
sm:max-w-2xl/lg:max-w-4xl so multi-field forms + PDF previews
aren't cramped at 1440-1920px.
- Notes tab badge aggregation: new countFor{Client,Yacht,Company}
Aggregated helpers in notes.service mirror the listFor*Aggregated
symmetric-reach joins. yacht-tabs + company-tabs render the
badge; client-tabs already had badge support.
- Supplemental-info form polish bundle: BrandedAuthShell gains a
`width: 'sm' | 'md'` prop (md uses min-h-dvh scroll instead of
fixed inset-0 pin so long forms scroll naturally). Form picks up
port branding (logoUrl + backgroundUrl + appName) via
loadByToken. Address fields completed (street + city + region +
postal + country). Port name eyebrow + success-state copy added.
- new-document-menu Upload-file landing toast: per-file completion
emits toast.success with action link to the destination entity
or folder.
- interest-tabs OverviewTab "from client" pill on Email + Phone
rows via new EditableRow `inheritedFrom` prop.
- create-document-wizard subject picker → segmented button strip
(5 types visible at once).
Launch infra:
- UTM column wiring (Init 1b step 4): migration
0089_website_submissions_utm.sql adds utm_source/medium/campaign/
term/content + composite index (port_id, utm_source, received_at)
for per-campaign rollups. website-inquiries intake accepts the
five fields. Residential intake intentionally untouched per audit
scope.
- Invoicing module gate (Init 1c spike): new
invoices-module.service + invoices layout guard + registry entry
invoices_module_enabled (default false). Audit conclusion in
launch-readiness.md: payments table is canonical money path;
/invoices flow is parallel infrastructure now hidden by default.
Smart-back navigation refactor:
- Replaced breadcrumb component with history-aware Back button.
New route-labels.ts + use-smart-back hook +
navigation-history-tracker so back falls through to the parent
route when there's no prior page in history.
- Sidebar / topbar / mobile-topbar adopt the new pattern; old
breadcrumb-store kept for back-compat consumers but the
breadcrumbs component is gone.
- 6 detail pages (admin/errors per-id + codes, invoices/
upload-receipts, reports kind, tenancies detail, analytics
metric, client detail) migrated.
Trackers + docs:
- docs/launch-readiness.md — master pre-launch tracker. Includes
the reports gap audit (cross-cutting filter set, Marketing +
Financial blockers, custom builder remaining entities, scheduled
CSV/XLSX, template scope picker).
- docs/superpowers/audits/active-uat.md — 15 findings flipped
OPEN → SHIPPED locally with fix-applied notes; 4 OPEN remaining
(each blocked on user input or cross-repo).
- CLAUDE.md — minor session notes carried forward.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27 22:42:37 +02:00
|
|
|
noteCount,
|
feat(platform): residential module + admin UI + reliability fixes
Residential platform
- New schema: residentialClients, residentialInterests (separate from
marina/yacht clients) with migration 0010
- Service layer with CRUD + audit + sockets + per-port portal toggle
- v1 + public API routes (/api/v1/residential/*, /api/public/residential-inquiries)
- List + detail pages with inline editing for clients and interests
- Per-user residentialAccess toggle on userPortRoles (migration 0011)
- Permission keys: residential_clients, residential_interests
- Sidebar nav + role form integration
- Smoke spec covering page loads, UI create flow, public endpoint
Admin & shared UI
- Admin → Forms (form templates CRUD) with validators + service
- Notification preferences page (in-app + email per type)
- Email composition + accounts list + threads view
- Branded auth shell shared across CRM + portal auth surfaces
- Inline editing extended to yacht/company/interest detail pages
- InlineTagEditor + per-entity tags endpoints (yachts, companies)
- Notes service polymorphic across clients/interests/yachts/companies
- Client list columns: yachtCount + companyCount badges
- Reservation file-download via presigned URL (replaces stale <a href>)
Route handler refactor
- Extracted yachts/companies/berths reservation handlers to sibling
handlers.ts files (Next.js 15 route.ts only allows specific exports)
Reliability fixes
- apiFetch double-stringify bug fixed across 13 components
(apiFetch already JSON.stringifies its body; passing a stringified
body produced double-encoded JSON which failed zod validation)
- SocketProvider gated behind useSyncExternalStore-based mount check
to avoid useSession() SSR crashes under React 19 + Next 15
- apiFetch falls back to URL-pathname → port-id resolution when the
Zustand store hasn't hydrated yet (fresh contexts, e2e tests)
- CRM invite flow (schema, service, route, email, dev script)
- Dashboard route → [portSlug]/dashboard/page.tsx + redirect
- Document the dev-server restart-after-migration gotcha in CLAUDE.md
Tests
- 5-case residential smoke spec
- Integration test updates for new service signatures
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 21:54:32 +02:00
|
|
|
};
|
2026-04-23 23:40:56 +02:00
|
|
|
}
|
2026-04-23 23:52:24 +02:00
|
|
|
|
|
|
|
|
export async function updateYacht(
|
|
|
|
|
id: string,
|
|
|
|
|
portId: string,
|
|
|
|
|
data: UpdateYachtInput,
|
|
|
|
|
meta: AuditMeta,
|
|
|
|
|
) {
|
|
|
|
|
// Defense-in-depth: owner changes must go through /transfer, not PATCH.
|
|
|
|
|
const dataRecord = data as Record<string, unknown>;
|
|
|
|
|
if (
|
|
|
|
|
Object.prototype.hasOwnProperty.call(dataRecord, 'currentOwnerType') ||
|
|
|
|
|
Object.prototype.hasOwnProperty.call(dataRecord, 'currentOwnerId')
|
|
|
|
|
) {
|
|
|
|
|
throw new ValidationError('use /transfer to change ownership');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const existing = await db.query.yachts.findFirst({
|
|
|
|
|
where: eq(yachts.id, id),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!existing || existing.portId !== portId) {
|
|
|
|
|
throw new NotFoundError('Yacht');
|
|
|
|
|
}
|
|
|
|
|
|
fix(audit-wave-10): types-auditor fixes — Tx type, BerthDetailData, parseBody, toAuditJson
Address the CRITICAL + high-leverage HIGH items from the types-auditor:
**C1 — `tx: any` in client-restore.service**
Export a canonical `Tx` type from `lib/db/utils.ts` (derived from
Drizzle's `db.transaction` callback shape) and use it in
`applyReversal` so the 12+ downstream tx writes get full inference.
**C2 — berth-detail page stacked `useQuery<any>` escape hatches**
Export `BerthDetailData` from berth-detail-header and consume it
through useQuery + apiFetch. Removed three `any` escapes in the
highest-traffic detail page. Also collapsed the duplicate `BerthData`
in berth-tabs.tsx to import from berth-detail-header so the two
types can't drift.
**C3 — parseBody migration for portal/public routes**
Replace raw `await req.json() + schema.parse(body)` with the
project-standard `parseBody(req, schema)` helper across 7 routes:
- portal/auth/{change-password, activate, reset-password}
- auth/set-password
- public/{interests, residential-inquiries}
Skipped the three anti-enumeration routes (forgot-password, sign-in,
sign-in-by-identifier) where the manual validation gives opaque
errors on purpose. website-inquiries already wraps the parse in a
custom 400 — left as-is.
**HIGH #5 — `toAuditJson<T>` helper (21 → 0 inline casts)**
Introduce `toAuditJson<T extends object>(row: T): Record<string,
unknown>` in lib/audit.ts (mirrors gdpr-bundle-builder's `toJsonRow`
that already exists for the same reason). Codemod 21 `<row> as unknown
as Record<string, unknown>` sites across:
- invoices.ts × 6
- expenses.ts × 6
- berths.service × 2
- documents.service × 2
- ocr-config.service × 2
- ai-budget.service × 2
- yachts.service, companies.service, company-memberships.service × 1 each
document-templates' `payload as unknown as Record<...>` is a different
shape (Documenso form-values widening, not an audit log) — kept the
manual cast there. Tests stay 1315/1315.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 12:27:08 +02:00
|
|
|
const { diff } = diffEntity(toAuditJson(existing), data as Record<string, unknown>);
|
2026-04-23 23:52:24 +02:00
|
|
|
|
|
|
|
|
const [updated] = await db
|
|
|
|
|
.update(yachts)
|
|
|
|
|
.set({ ...data, updatedAt: new Date() })
|
|
|
|
|
.where(and(eq(yachts.id, id), eq(yachts.portId, portId)))
|
|
|
|
|
.returning();
|
|
|
|
|
|
|
|
|
|
void createAuditLog({
|
|
|
|
|
userId: meta.userId,
|
|
|
|
|
portId,
|
|
|
|
|
action: 'update',
|
|
|
|
|
entityType: 'yacht',
|
|
|
|
|
entityId: id,
|
|
|
|
|
oldValue: diff as Record<string, unknown>,
|
|
|
|
|
newValue: data as Record<string, unknown>,
|
|
|
|
|
ipAddress: meta.ipAddress,
|
|
|
|
|
userAgent: meta.userAgent,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
emitToRoom(`port:${portId}`, 'yacht:updated', {
|
|
|
|
|
yachtId: id,
|
|
|
|
|
changedFields: Object.keys(diff),
|
|
|
|
|
});
|
|
|
|
|
|
2026-05-11 11:25:16 +02:00
|
|
|
if (data.name !== undefined) {
|
|
|
|
|
await syncEntityFolderName(portId, 'yacht', id, meta.userId).catch((err) => {
|
2026-05-11 13:57:42 +02:00
|
|
|
logger.warn({ err, yachtId: id, portId }, 'Failed to sync yacht folder name');
|
2026-05-11 11:25:16 +02:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-23 23:52:24 +02:00
|
|
|
return updated!;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function archiveYacht(id: string, portId: string, meta: AuditMeta) {
|
|
|
|
|
const existing = await db.query.yachts.findFirst({
|
|
|
|
|
where: eq(yachts.id, id),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!existing || existing.portId !== portId) {
|
|
|
|
|
throw new NotFoundError('Yacht');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// NOTE: bypassing the shared `softDelete(...)` util: it sets the raw
|
|
|
|
|
// column key `archived_at`, which Drizzle does not recognise (the JS
|
|
|
|
|
// key is `archivedAt`) and therefore emits an empty SET clause. Until
|
|
|
|
|
// the utility is fixed, do the update inline.
|
|
|
|
|
await db
|
|
|
|
|
.update(yachts)
|
|
|
|
|
.set({ archivedAt: new Date() })
|
|
|
|
|
.where(and(eq(yachts.id, id), eq(yachts.portId, portId)));
|
|
|
|
|
|
2026-05-11 13:57:42 +02:00
|
|
|
void applyEntityArchivedSuffix(portId, 'yacht', id, meta.userId).catch((err) => {
|
|
|
|
|
logger.warn({ err, yachtId: id, portId }, 'Failed to apply archived suffix to yacht folder');
|
2026-05-11 11:34:02 +02:00
|
|
|
});
|
|
|
|
|
|
2026-04-23 23:52:24 +02:00
|
|
|
void createAuditLog({
|
|
|
|
|
userId: meta.userId,
|
|
|
|
|
portId,
|
|
|
|
|
action: 'archive',
|
|
|
|
|
entityType: 'yacht',
|
|
|
|
|
entityId: id,
|
|
|
|
|
ipAddress: meta.ipAddress,
|
|
|
|
|
userAgent: meta.userAgent,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
emitToRoom(`port:${portId}`, 'yacht:archived', { yachtId: id });
|
|
|
|
|
}
|
2026-04-23 23:58:20 +02:00
|
|
|
|
2026-06-02 12:24:46 +02:00
|
|
|
/**
|
|
|
|
|
* Transaction-aware ownership transfer. Performs the FULL ledger move —
|
|
|
|
|
* closes the open `yacht_ownership_history` row, opens a new one for the
|
|
|
|
|
* new owner, and updates the yacht's denormalized current-owner columns —
|
|
|
|
|
* so the history ledger and the denormalized columns never drift apart.
|
|
|
|
|
*
|
|
|
|
|
* Use this from any flow that moves a yacht to a new owner inside a
|
|
|
|
|
* transaction (smart-archive / restore included). The public
|
|
|
|
|
* `transferOwnership` wraps this in its own tx + audit/socket emissions.
|
|
|
|
|
*
|
|
|
|
|
* NOTE: callers are responsible for any same-owner / owner-exists
|
|
|
|
|
* validation they need; this helper intentionally does only the ledger
|
|
|
|
|
* write so it stays composable. `effectiveDate` defaults to now() when
|
|
|
|
|
* omitted (archive/restore have no operator-chosen date).
|
|
|
|
|
*/
|
|
|
|
|
export async function transferOwnershipTx(
|
|
|
|
|
tx: typeof db,
|
|
|
|
|
args: {
|
|
|
|
|
yachtId: string;
|
|
|
|
|
newOwner: { type: 'client' | 'company'; id: string };
|
|
|
|
|
effectiveDate?: Date;
|
|
|
|
|
transferReason?: string | null;
|
|
|
|
|
transferNotes?: string | null;
|
|
|
|
|
createdBy: string;
|
|
|
|
|
},
|
|
|
|
|
): Promise<Yacht> {
|
|
|
|
|
const effectiveDate = args.effectiveDate ?? new Date();
|
|
|
|
|
|
|
|
|
|
// Close the currently-active history row (endDate IS NULL → guarded by
|
|
|
|
|
// the idx_yoh_active partial unique index, so there's at most one).
|
|
|
|
|
await tx
|
|
|
|
|
.update(yachtOwnershipHistory)
|
|
|
|
|
.set({ endDate: effectiveDate })
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(yachtOwnershipHistory.yachtId, args.yachtId),
|
|
|
|
|
sql`${yachtOwnershipHistory.endDate} IS NULL`,
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
// Open the new active row for the incoming owner.
|
|
|
|
|
await tx.insert(yachtOwnershipHistory).values({
|
|
|
|
|
yachtId: args.yachtId,
|
|
|
|
|
ownerType: args.newOwner.type,
|
|
|
|
|
ownerId: args.newOwner.id,
|
|
|
|
|
startDate: effectiveDate,
|
|
|
|
|
endDate: null,
|
|
|
|
|
transferReason: args.transferReason ?? null,
|
|
|
|
|
transferNotes: args.transferNotes ?? null,
|
|
|
|
|
createdBy: args.createdBy,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Update denormalized current-owner columns to match the ledger head.
|
|
|
|
|
const [updated] = await tx
|
|
|
|
|
.update(yachts)
|
|
|
|
|
.set({
|
|
|
|
|
currentOwnerType: args.newOwner.type,
|
|
|
|
|
currentOwnerId: args.newOwner.id,
|
|
|
|
|
updatedAt: new Date(),
|
|
|
|
|
})
|
|
|
|
|
.where(eq(yachts.id, args.yachtId))
|
|
|
|
|
.returning();
|
|
|
|
|
|
|
|
|
|
return updated!;
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-23 23:58:20 +02:00
|
|
|
export async function transferOwnership(
|
|
|
|
|
yachtId: string,
|
|
|
|
|
portId: string,
|
|
|
|
|
data: TransferOwnershipInput,
|
|
|
|
|
meta: AuditMeta,
|
|
|
|
|
) {
|
|
|
|
|
return await withTransaction(async (tx) => {
|
|
|
|
|
const yacht = await tx.query.yachts.findFirst({
|
|
|
|
|
where: and(eq(yachts.id, yachtId), eq(yachts.portId, portId)),
|
|
|
|
|
});
|
|
|
|
|
if (!yacht) throw new NotFoundError('Yacht');
|
|
|
|
|
|
|
|
|
|
if (
|
|
|
|
|
yacht.currentOwnerType === data.newOwner.type &&
|
|
|
|
|
yacht.currentOwnerId === data.newOwner.id
|
|
|
|
|
) {
|
2026-05-04 22:57:01 +02:00
|
|
|
throw new ValidationError('same owner - nothing to transfer');
|
2026-04-23 23:58:20 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await assertOwnerExists(portId, data.newOwner, tx);
|
|
|
|
|
|
feat(uat-polish): live-UAT round — dialog widths, recommender polish, inline create, tenancy + notes plumbing
Compendium of polish + small-fix work captured during the 2026-05-26
live UAT session. Every change has a corresponding entry in
docs/superpowers/audits/active-uat.md with file:line evidence + root
cause + alternatives considered.
Dialog primitive width
- DialogContent default bumped from sm:max-w-lg (512px) to
sm:max-w-xl + lg:max-w-3xl so every consumer gets a sane desktop
default. Confirm dialogs override DOWN, content-heavy dialogs
override UP.
- FilePreviewDialog full-viewport via w-[min(95vw,1400px)] +
h-[85vh] so PDFs render at usable width on real desktops.
Recommender card
- Heat badge now a Popover with the score (X/100), the formula in
plain English, the four component breakdowns (recency / furthest
stage / interest count / EOI count), and a pointer to the admin
weight tuning page.
- Area letter span dropped from the card header - mooring number
already prefixes it.
- BerthRecommenderPanel + the dedicated "Berth Recommendations" tab
both hidden when interest.desiredLengthFt is null. The empty
guidance card was reading as noise. interest-tabs.tsx computes
hasDesiredDims once and gates the inline mount + tab strip
spread off it.
BerthPicker
- Drop area suffix from row labels. Mooring number already carries
the area letter prefix; group heading conveys the same context.
Same fix flows to every BerthPicker consumer (tenancy
create/renew/transfer, interest form, linked-berths picker).
CreateDocumentWizard
- DOCUMENT_TYPE_LABELS constant added to constants.ts. Wizard reads
from the map instead of naive replace(/_/g, ' '): "EOI",
"Contract", "NDA", "Reservation Agreement", "Other".
- "Other" option surfaces a hint pointing the rep at the Title
field so they describe what the doc actually is.
InterestForm inline client + yacht create
- ClientForm gains an onCreated(clientId) callback. Mutation
returns { id } in create mode so onSuccess can forward.
- InterestForm renders an "Add new" Button next to the Client label
(create mode only - hidden on edit), opens ClientForm, auto-
selects the new client into the draft. Mirrors the existing
inline yacht-create pattern.
- Reset path includes source: 'manual' alongside the other create-
mode defaults; the manual flow was dropping back to a blank
source dropdown on reopen.
Tenancy list
- ClientTenanciesTab activeTenancies query now includes status
IN ('pending', 'active'). Was filtering to active-only; pending
rows from manual create + webhook auto-create were invisible on
the client detail's Tenancies tab.
- TenancyList rows are now keyboard- and click-navigable to the
tenancy detail page (Enter/Space included). Inner links + buttons
stop propagation so per-cell navigation works.
NotesList source badge
- Aggregated-mode source badge ("Yacht / Test Yacht") is now a Link
to the source entity's detail page. New sourceLinkFor helper
centralises the URL mapping across clients/companies/yachts/
interests + residential variants.
Yacht transfer audit log
- transferOwnership emits a distinct 'transfer' AuditAction (added
to AuditAction union in src/lib/audit.ts) with old/new owner
names resolved at write time. EntityActivityFeed renders
"Matt transferred owner to Jane Smith" instead of "Matt updated
this record." formatValueForField unwraps the { name } shape so
the audit_logs Record<string, unknown> typing stays clean.
- yacht-transfer-dialog copy: dropped "atomic" jargon. Reads "The
change is logged in the audit history" instead.
Companies autocomplete
- /api/v1/companies/autocomplete now returns the 10 most-recently-
updated companies when the query string is empty. Was returning
[]. CompanyPicker popover opens with results to scan instead of a
blank dropdown.
DocumentsHub FlatFolderListing
- Uploaded files (the files table) now merge into the documents
table view via a parallel /api/v1/files?folderId=X query +
client-side merge into a unified row list. listFiles service
honours the folderId filter that was already accepted by the
validator. New renderFileRow renders file rows with an "Uploaded
file" type pill + "Stored" status pill, links the filename to
the download URL. Existing FolderDropZone invalidation covers
the new query, so drag-drop and New-document-menu uploads
refresh the list without a page reload.
- FlatFolderListing wrapped in a vertically-spaced container so
subfolders / search row / list have consistent gap.
- Per-row chevron only renders when totalSigners > 0; empty
placeholder column kept so grid alignment doesn't jump.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 20:07:45 +02:00
|
|
|
// Resolve old + new owner names so the audit log row reads as a
|
|
|
|
|
// sentence ("Matt transferred owner from Smith to Jones") rather
|
|
|
|
|
// than a generic "updated this record." Resolution mirrors the
|
|
|
|
|
// assertOwnerExists pattern — same client/company tables, scoped
|
|
|
|
|
// to the same port.
|
|
|
|
|
const resolveOwnerName = async (
|
|
|
|
|
ownerType: string | null,
|
|
|
|
|
ownerId: string | null,
|
|
|
|
|
): Promise<string | null> => {
|
|
|
|
|
if (!ownerType || !ownerId) return null;
|
|
|
|
|
if (ownerType === 'client') {
|
|
|
|
|
const row = await tx.query.clients.findFirst({
|
|
|
|
|
where: and(eq(clients.id, ownerId), eq(clients.portId, portId)),
|
|
|
|
|
columns: { fullName: true },
|
|
|
|
|
});
|
|
|
|
|
return row?.fullName ?? null;
|
|
|
|
|
}
|
|
|
|
|
if (ownerType === 'company') {
|
|
|
|
|
const row = await tx.query.companies.findFirst({
|
|
|
|
|
where: and(eq(companies.id, ownerId), eq(companies.portId, portId)),
|
|
|
|
|
columns: { name: true },
|
|
|
|
|
});
|
|
|
|
|
return row?.name ?? null;
|
|
|
|
|
}
|
|
|
|
|
return null;
|
|
|
|
|
};
|
|
|
|
|
const [oldOwnerName, newOwnerName] = await Promise.all([
|
|
|
|
|
resolveOwnerName(yacht.currentOwnerType, yacht.currentOwnerId),
|
|
|
|
|
resolveOwnerName(data.newOwner.type, data.newOwner.id),
|
|
|
|
|
]);
|
|
|
|
|
|
2026-06-02 12:24:46 +02:00
|
|
|
// Close the open history row, open the new one, and sync the
|
|
|
|
|
// denormalized columns — all via the shared tx-aware helper so the
|
|
|
|
|
// ledger invariant holds for every transfer pathway.
|
|
|
|
|
const updated = await transferOwnershipTx(tx, {
|
2026-04-23 23:58:20 +02:00
|
|
|
yachtId,
|
2026-06-02 12:24:46 +02:00
|
|
|
newOwner: data.newOwner,
|
|
|
|
|
effectiveDate: data.effectiveDate,
|
2026-04-23 23:58:20 +02:00
|
|
|
transferReason: data.transferReason ?? null,
|
|
|
|
|
transferNotes: data.transferNotes ?? null,
|
|
|
|
|
createdBy: meta.userId,
|
|
|
|
|
});
|
|
|
|
|
|
feat(uat-polish): live-UAT round — dialog widths, recommender polish, inline create, tenancy + notes plumbing
Compendium of polish + small-fix work captured during the 2026-05-26
live UAT session. Every change has a corresponding entry in
docs/superpowers/audits/active-uat.md with file:line evidence + root
cause + alternatives considered.
Dialog primitive width
- DialogContent default bumped from sm:max-w-lg (512px) to
sm:max-w-xl + lg:max-w-3xl so every consumer gets a sane desktop
default. Confirm dialogs override DOWN, content-heavy dialogs
override UP.
- FilePreviewDialog full-viewport via w-[min(95vw,1400px)] +
h-[85vh] so PDFs render at usable width on real desktops.
Recommender card
- Heat badge now a Popover with the score (X/100), the formula in
plain English, the four component breakdowns (recency / furthest
stage / interest count / EOI count), and a pointer to the admin
weight tuning page.
- Area letter span dropped from the card header - mooring number
already prefixes it.
- BerthRecommenderPanel + the dedicated "Berth Recommendations" tab
both hidden when interest.desiredLengthFt is null. The empty
guidance card was reading as noise. interest-tabs.tsx computes
hasDesiredDims once and gates the inline mount + tab strip
spread off it.
BerthPicker
- Drop area suffix from row labels. Mooring number already carries
the area letter prefix; group heading conveys the same context.
Same fix flows to every BerthPicker consumer (tenancy
create/renew/transfer, interest form, linked-berths picker).
CreateDocumentWizard
- DOCUMENT_TYPE_LABELS constant added to constants.ts. Wizard reads
from the map instead of naive replace(/_/g, ' '): "EOI",
"Contract", "NDA", "Reservation Agreement", "Other".
- "Other" option surfaces a hint pointing the rep at the Title
field so they describe what the doc actually is.
InterestForm inline client + yacht create
- ClientForm gains an onCreated(clientId) callback. Mutation
returns { id } in create mode so onSuccess can forward.
- InterestForm renders an "Add new" Button next to the Client label
(create mode only - hidden on edit), opens ClientForm, auto-
selects the new client into the draft. Mirrors the existing
inline yacht-create pattern.
- Reset path includes source: 'manual' alongside the other create-
mode defaults; the manual flow was dropping back to a blank
source dropdown on reopen.
Tenancy list
- ClientTenanciesTab activeTenancies query now includes status
IN ('pending', 'active'). Was filtering to active-only; pending
rows from manual create + webhook auto-create were invisible on
the client detail's Tenancies tab.
- TenancyList rows are now keyboard- and click-navigable to the
tenancy detail page (Enter/Space included). Inner links + buttons
stop propagation so per-cell navigation works.
NotesList source badge
- Aggregated-mode source badge ("Yacht / Test Yacht") is now a Link
to the source entity's detail page. New sourceLinkFor helper
centralises the URL mapping across clients/companies/yachts/
interests + residential variants.
Yacht transfer audit log
- transferOwnership emits a distinct 'transfer' AuditAction (added
to AuditAction union in src/lib/audit.ts) with old/new owner
names resolved at write time. EntityActivityFeed renders
"Matt transferred owner to Jane Smith" instead of "Matt updated
this record." formatValueForField unwraps the { name } shape so
the audit_logs Record<string, unknown> typing stays clean.
- yacht-transfer-dialog copy: dropped "atomic" jargon. Reads "The
change is logged in the audit history" instead.
Companies autocomplete
- /api/v1/companies/autocomplete now returns the 10 most-recently-
updated companies when the query string is empty. Was returning
[]. CompanyPicker popover opens with results to scan instead of a
blank dropdown.
DocumentsHub FlatFolderListing
- Uploaded files (the files table) now merge into the documents
table view via a parallel /api/v1/files?folderId=X query +
client-side merge into a unified row list. listFiles service
honours the folderId filter that was already accepted by the
validator. New renderFileRow renders file rows with an "Uploaded
file" type pill + "Stored" status pill, links the filename to
the download URL. Existing FolderDropZone invalidation covers
the new query, so drag-drop and New-document-menu uploads
refresh the list without a page reload.
- FlatFolderListing wrapped in a vertically-spaced container so
subfolders / search row / list have consistent gap.
- Per-row chevron only renders when totalSigners > 0; empty
placeholder column kept so grid alignment doesn't jump.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 20:07:45 +02:00
|
|
|
// Audit log shape designed for the EntityActivityFeed sentence
|
|
|
|
|
// formatter: a discrete `transfer` action + human-readable owner
|
|
|
|
|
// names render as "Matt transferred owner from X to Y" instead of
|
|
|
|
|
// the generic "updated this record." Reason + new-owner-type
|
|
|
|
|
// ride along in metadata for downstream consumers that need the
|
|
|
|
|
// structured form.
|
2026-04-23 23:58:20 +02:00
|
|
|
void createAuditLog({
|
|
|
|
|
userId: meta.userId,
|
|
|
|
|
portId,
|
feat(uat-polish): live-UAT round — dialog widths, recommender polish, inline create, tenancy + notes plumbing
Compendium of polish + small-fix work captured during the 2026-05-26
live UAT session. Every change has a corresponding entry in
docs/superpowers/audits/active-uat.md with file:line evidence + root
cause + alternatives considered.
Dialog primitive width
- DialogContent default bumped from sm:max-w-lg (512px) to
sm:max-w-xl + lg:max-w-3xl so every consumer gets a sane desktop
default. Confirm dialogs override DOWN, content-heavy dialogs
override UP.
- FilePreviewDialog full-viewport via w-[min(95vw,1400px)] +
h-[85vh] so PDFs render at usable width on real desktops.
Recommender card
- Heat badge now a Popover with the score (X/100), the formula in
plain English, the four component breakdowns (recency / furthest
stage / interest count / EOI count), and a pointer to the admin
weight tuning page.
- Area letter span dropped from the card header - mooring number
already prefixes it.
- BerthRecommenderPanel + the dedicated "Berth Recommendations" tab
both hidden when interest.desiredLengthFt is null. The empty
guidance card was reading as noise. interest-tabs.tsx computes
hasDesiredDims once and gates the inline mount + tab strip
spread off it.
BerthPicker
- Drop area suffix from row labels. Mooring number already carries
the area letter prefix; group heading conveys the same context.
Same fix flows to every BerthPicker consumer (tenancy
create/renew/transfer, interest form, linked-berths picker).
CreateDocumentWizard
- DOCUMENT_TYPE_LABELS constant added to constants.ts. Wizard reads
from the map instead of naive replace(/_/g, ' '): "EOI",
"Contract", "NDA", "Reservation Agreement", "Other".
- "Other" option surfaces a hint pointing the rep at the Title
field so they describe what the doc actually is.
InterestForm inline client + yacht create
- ClientForm gains an onCreated(clientId) callback. Mutation
returns { id } in create mode so onSuccess can forward.
- InterestForm renders an "Add new" Button next to the Client label
(create mode only - hidden on edit), opens ClientForm, auto-
selects the new client into the draft. Mirrors the existing
inline yacht-create pattern.
- Reset path includes source: 'manual' alongside the other create-
mode defaults; the manual flow was dropping back to a blank
source dropdown on reopen.
Tenancy list
- ClientTenanciesTab activeTenancies query now includes status
IN ('pending', 'active'). Was filtering to active-only; pending
rows from manual create + webhook auto-create were invisible on
the client detail's Tenancies tab.
- TenancyList rows are now keyboard- and click-navigable to the
tenancy detail page (Enter/Space included). Inner links + buttons
stop propagation so per-cell navigation works.
NotesList source badge
- Aggregated-mode source badge ("Yacht / Test Yacht") is now a Link
to the source entity's detail page. New sourceLinkFor helper
centralises the URL mapping across clients/companies/yachts/
interests + residential variants.
Yacht transfer audit log
- transferOwnership emits a distinct 'transfer' AuditAction (added
to AuditAction union in src/lib/audit.ts) with old/new owner
names resolved at write time. EntityActivityFeed renders
"Matt transferred owner to Jane Smith" instead of "Matt updated
this record." formatValueForField unwraps the { name } shape so
the audit_logs Record<string, unknown> typing stays clean.
- yacht-transfer-dialog copy: dropped "atomic" jargon. Reads "The
change is logged in the audit history" instead.
Companies autocomplete
- /api/v1/companies/autocomplete now returns the 10 most-recently-
updated companies when the query string is empty. Was returning
[]. CompanyPicker popover opens with results to scan instead of a
blank dropdown.
DocumentsHub FlatFolderListing
- Uploaded files (the files table) now merge into the documents
table view via a parallel /api/v1/files?folderId=X query +
client-side merge into a unified row list. listFiles service
honours the folderId filter that was already accepted by the
validator. New renderFileRow renders file rows with an "Uploaded
file" type pill + "Stored" status pill, links the filename to
the download URL. Existing FolderDropZone invalidation covers
the new query, so drag-drop and New-document-menu uploads
refresh the list without a page reload.
- FlatFolderListing wrapped in a vertically-spaced container so
subfolders / search row / list have consistent gap.
- Per-row chevron only renders when totalSigners > 0; empty
placeholder column kept so grid alignment doesn't jump.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 20:07:45 +02:00
|
|
|
action: 'transfer',
|
2026-04-23 23:58:20 +02:00
|
|
|
entityType: 'yacht',
|
|
|
|
|
entityId: yachtId,
|
feat(uat-polish): live-UAT round — dialog widths, recommender polish, inline create, tenancy + notes plumbing
Compendium of polish + small-fix work captured during the 2026-05-26
live UAT session. Every change has a corresponding entry in
docs/superpowers/audits/active-uat.md with file:line evidence + root
cause + alternatives considered.
Dialog primitive width
- DialogContent default bumped from sm:max-w-lg (512px) to
sm:max-w-xl + lg:max-w-3xl so every consumer gets a sane desktop
default. Confirm dialogs override DOWN, content-heavy dialogs
override UP.
- FilePreviewDialog full-viewport via w-[min(95vw,1400px)] +
h-[85vh] so PDFs render at usable width on real desktops.
Recommender card
- Heat badge now a Popover with the score (X/100), the formula in
plain English, the four component breakdowns (recency / furthest
stage / interest count / EOI count), and a pointer to the admin
weight tuning page.
- Area letter span dropped from the card header - mooring number
already prefixes it.
- BerthRecommenderPanel + the dedicated "Berth Recommendations" tab
both hidden when interest.desiredLengthFt is null. The empty
guidance card was reading as noise. interest-tabs.tsx computes
hasDesiredDims once and gates the inline mount + tab strip
spread off it.
BerthPicker
- Drop area suffix from row labels. Mooring number already carries
the area letter prefix; group heading conveys the same context.
Same fix flows to every BerthPicker consumer (tenancy
create/renew/transfer, interest form, linked-berths picker).
CreateDocumentWizard
- DOCUMENT_TYPE_LABELS constant added to constants.ts. Wizard reads
from the map instead of naive replace(/_/g, ' '): "EOI",
"Contract", "NDA", "Reservation Agreement", "Other".
- "Other" option surfaces a hint pointing the rep at the Title
field so they describe what the doc actually is.
InterestForm inline client + yacht create
- ClientForm gains an onCreated(clientId) callback. Mutation
returns { id } in create mode so onSuccess can forward.
- InterestForm renders an "Add new" Button next to the Client label
(create mode only - hidden on edit), opens ClientForm, auto-
selects the new client into the draft. Mirrors the existing
inline yacht-create pattern.
- Reset path includes source: 'manual' alongside the other create-
mode defaults; the manual flow was dropping back to a blank
source dropdown on reopen.
Tenancy list
- ClientTenanciesTab activeTenancies query now includes status
IN ('pending', 'active'). Was filtering to active-only; pending
rows from manual create + webhook auto-create were invisible on
the client detail's Tenancies tab.
- TenancyList rows are now keyboard- and click-navigable to the
tenancy detail page (Enter/Space included). Inner links + buttons
stop propagation so per-cell navigation works.
NotesList source badge
- Aggregated-mode source badge ("Yacht / Test Yacht") is now a Link
to the source entity's detail page. New sourceLinkFor helper
centralises the URL mapping across clients/companies/yachts/
interests + residential variants.
Yacht transfer audit log
- transferOwnership emits a distinct 'transfer' AuditAction (added
to AuditAction union in src/lib/audit.ts) with old/new owner
names resolved at write time. EntityActivityFeed renders
"Matt transferred owner to Jane Smith" instead of "Matt updated
this record." formatValueForField unwraps the { name } shape so
the audit_logs Record<string, unknown> typing stays clean.
- yacht-transfer-dialog copy: dropped "atomic" jargon. Reads "The
change is logged in the audit history" instead.
Companies autocomplete
- /api/v1/companies/autocomplete now returns the 10 most-recently-
updated companies when the query string is empty. Was returning
[]. CompanyPicker popover opens with results to scan instead of a
blank dropdown.
DocumentsHub FlatFolderListing
- Uploaded files (the files table) now merge into the documents
table view via a parallel /api/v1/files?folderId=X query +
client-side merge into a unified row list. listFiles service
honours the folderId filter that was already accepted by the
validator. New renderFileRow renders file rows with an "Uploaded
file" type pill + "Stored" status pill, links the filename to
the download URL. Existing FolderDropZone invalidation covers
the new query, so drag-drop and New-document-menu uploads
refresh the list without a page reload.
- FlatFolderListing wrapped in a vertically-spaced container so
subfolders / search row / list have consistent gap.
- Per-row chevron only renders when totalSigners > 0; empty
placeholder column kept so grid alignment doesn't jump.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 20:07:45 +02:00
|
|
|
fieldChanged: 'owner',
|
|
|
|
|
// oldValue/newValue are Record<string, unknown> in the audit schema;
|
|
|
|
|
// wrap the owner-name strings in a `name` field so the type matches
|
|
|
|
|
// and the feed's `formatValueForField` can pluck the readable label.
|
|
|
|
|
oldValue: oldOwnerName ? { name: oldOwnerName } : undefined,
|
|
|
|
|
newValue: newOwnerName ? { name: newOwnerName } : undefined,
|
|
|
|
|
metadata: {
|
|
|
|
|
newOwnerType: data.newOwner.type,
|
|
|
|
|
newOwnerId: data.newOwner.id,
|
|
|
|
|
reason: data.transferReason ?? null,
|
|
|
|
|
notes: data.transferNotes ?? null,
|
|
|
|
|
},
|
2026-04-23 23:58:20 +02:00
|
|
|
ipAddress: meta.ipAddress,
|
|
|
|
|
userAgent: meta.userAgent,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
emitToRoom(`port:${portId}`, 'yacht:ownership_transferred', {
|
|
|
|
|
yachtId,
|
|
|
|
|
newOwner: data.newOwner,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return updated!;
|
|
|
|
|
});
|
|
|
|
|
}
|
feat(yachts): list + owner-scoped list + autocomplete
Adds `listYachts`, `listYachtsForOwner`, and `autocomplete` to the
yacht service so UIs can page/filter yachts per port, look up all
yachts tied to a given client/company, and power search-as-you-type.
`listYachts` delegates to the shared port-scoped `buildListQuery`,
supporting search over name/hullNumber/registration plus ownerType,
ownerId and status filters; `autocomplete` caps at 10 results and is
tenant-scoped; `listYachtsForOwner` returns all yachts whose current
owner matches, newest first. Extends `makeYacht` factory to accept
flat `name`, `status`, `hullNumber`, `registration` overrides.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 00:03:36 +02:00
|
|
|
|
|
|
|
|
// ─── List ─────────────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
export async function listYachts(portId: string, query: ListYachtsInput) {
|
|
|
|
|
const { page, limit, sort, order, search, includeArchived, ownerType, ownerId, status } = query;
|
|
|
|
|
|
|
|
|
|
const filters = [];
|
|
|
|
|
if (ownerType) filters.push(eq(yachts.currentOwnerType, ownerType));
|
|
|
|
|
if (ownerId) filters.push(eq(yachts.currentOwnerId, ownerId));
|
|
|
|
|
if (status) filters.push(eq(yachts.status, status));
|
|
|
|
|
|
|
|
|
|
let sortColumn: typeof yachts.name | typeof yachts.createdAt | typeof yachts.updatedAt =
|
|
|
|
|
yachts.updatedAt;
|
|
|
|
|
if (sort === 'name') sortColumn = yachts.name;
|
|
|
|
|
else if (sort === 'createdAt') sortColumn = yachts.createdAt;
|
|
|
|
|
|
|
|
|
|
const result = await buildListQuery<Yacht>({
|
|
|
|
|
table: yachts,
|
|
|
|
|
portIdColumn: yachts.portId,
|
|
|
|
|
portId,
|
|
|
|
|
idColumn: yachts.id,
|
|
|
|
|
updatedAtColumn: yachts.updatedAt,
|
|
|
|
|
searchColumns: [yachts.name, yachts.hullNumber, yachts.registration],
|
|
|
|
|
searchTerm: search,
|
|
|
|
|
filters,
|
|
|
|
|
sort: sort ? { column: sortColumn, direction: order } : undefined,
|
|
|
|
|
page,
|
|
|
|
|
pageSize: limit,
|
|
|
|
|
includeArchived,
|
|
|
|
|
archivedAtColumn: yachts.archivedAt,
|
|
|
|
|
});
|
|
|
|
|
|
2026-04-27 23:54:04 +02:00
|
|
|
if (result.data.length === 0) return result;
|
|
|
|
|
|
|
|
|
|
// Resolve current owner names in two parallel batched queries instead of
|
|
|
|
|
// an N+1 fetch from the client (was 1 round-trip per row from yacht-columns).
|
|
|
|
|
const clientIds = result.data
|
|
|
|
|
.filter((y) => y.currentOwnerType === 'client')
|
|
|
|
|
.map((y) => y.currentOwnerId);
|
|
|
|
|
const companyIds = result.data
|
|
|
|
|
.filter((y) => y.currentOwnerType === 'company')
|
|
|
|
|
.map((y) => y.currentOwnerId);
|
|
|
|
|
|
|
|
|
|
const [clientRows, companyRows] = await Promise.all([
|
|
|
|
|
clientIds.length > 0
|
|
|
|
|
? db
|
|
|
|
|
.select({ id: clients.id, fullName: clients.fullName })
|
|
|
|
|
.from(clients)
|
|
|
|
|
.where(inArray(clients.id, clientIds))
|
|
|
|
|
: Promise.resolve([] as { id: string; fullName: string }[]),
|
|
|
|
|
companyIds.length > 0
|
|
|
|
|
? db
|
|
|
|
|
.select({ id: companies.id, name: companies.name })
|
|
|
|
|
.from(companies)
|
|
|
|
|
.where(inArray(companies.id, companyIds))
|
|
|
|
|
: Promise.resolve([] as { id: string; name: string }[]),
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
const clientNames = new Map(clientRows.map((r) => [r.id, r.fullName]));
|
|
|
|
|
const companyNames = new Map(companyRows.map((r) => [r.id, r.name]));
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
...result,
|
|
|
|
|
data: result.data.map((y) => ({
|
|
|
|
|
...y,
|
|
|
|
|
currentOwnerName:
|
|
|
|
|
y.currentOwnerType === 'client'
|
|
|
|
|
? (clientNames.get(y.currentOwnerId) ?? null)
|
|
|
|
|
: (companyNames.get(y.currentOwnerId) ?? null),
|
|
|
|
|
})),
|
|
|
|
|
};
|
feat(yachts): list + owner-scoped list + autocomplete
Adds `listYachts`, `listYachtsForOwner`, and `autocomplete` to the
yacht service so UIs can page/filter yachts per port, look up all
yachts tied to a given client/company, and power search-as-you-type.
`listYachts` delegates to the shared port-scoped `buildListQuery`,
supporting search over name/hullNumber/registration plus ownerType,
ownerId and status filters; `autocomplete` caps at 10 results and is
tenant-scoped; `listYachtsForOwner` returns all yachts whose current
owner matches, newest first. Extends `makeYacht` factory to accept
flat `name`, `status`, `hullNumber`, `registration` overrides.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 00:03:36 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ─── List for owner ───────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
export async function listYachtsForOwner(
|
|
|
|
|
portId: string,
|
|
|
|
|
ownerType: 'client' | 'company',
|
|
|
|
|
ownerId: string,
|
|
|
|
|
) {
|
chore(cleanup): Phase 1 — gap closure across audit, alerts, soft-delete, perms
Multi-area cleanup pass closing partial-implementation gaps surfaced by the
post-i18n audit. No behavior changes for happy-path users; closes real
correctness/security holes.
PR1a Public yacht-interest endpoint i18n. /api/public/interests now accepts
phoneE164/phoneCountry, nationalityIso, address.{countryIso, subdivisionIso},
and company.{incorporationCountryIso, incorporationSubdivisionIso}.
Server-side parsePhone() fallback for legacy raw phone strings.
PR1b Alert rule registry trim. Two rule slots ('document.expiring_soon',
'audit.suspicious_login') were registered but evaluators returned [].
Both required schema/instrumentation that hadn't landed. Removed from
the registry; comments record the dependencies needed to revive them.
Effective rule count: 8 active.
PR1c vi.mock hoist + flake fix. Hoisted vi.mock calls to top-level in 5
integration test files; webhook-delivery uses vi.hoisted for the
queue-add ref. Vitest no longer warns about non-top-level mocks.
Deflaked the 'short value' assertion in security-encryption.test.ts
by switching plaintext from 'ab' to 'XY' (non-hex chars). 5/5 runs green.
PR1d Soft-delete reference audit. listClientOptions and listYachtsForOwner
now filter by isNull(archivedAt). Berths use status (no archivedAt).
PR1e Permission-matrix audit script + report. scripts/audit-permissions.ts
walks every src/app/api/v1/**/route.ts and reports handlers without a
withPermission() wrapper. Initial run found 33 violations.
- Allow-listed 17 with explicit reasons (self-data, admin, alerts,
search, currency, ai, custom-fields — some marked TODO).
- Wrapped 7 routes with concrete permissions: clients/options
(clients:view), berths/options (berths:view), dashboard/*
(reports:view_dashboard), analytics (reports:view_analytics).
Audit report at docs/runbooks/permission-audit.md. Script exits
non-zero on any unallow-listed violation so it can become a CI gate.
Vitest: 741 -> 741 (no new tests; existing suite covers the changes).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-28 18:48:22 +02:00
|
|
|
// Owner-detail tabs only surface active yachts. Archived ones live in the
|
|
|
|
|
// ownership history view and are reachable by id, not via this lister.
|
feat(yachts): list + owner-scoped list + autocomplete
Adds `listYachts`, `listYachtsForOwner`, and `autocomplete` to the
yacht service so UIs can page/filter yachts per port, look up all
yachts tied to a given client/company, and power search-as-you-type.
`listYachts` delegates to the shared port-scoped `buildListQuery`,
supporting search over name/hullNumber/registration plus ownerType,
ownerId and status filters; `autocomplete` caps at 10 results and is
tenant-scoped; `listYachtsForOwner` returns all yachts whose current
owner matches, newest first. Extends `makeYacht` factory to accept
flat `name`, `status`, `hullNumber`, `registration` overrides.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 00:03:36 +02:00
|
|
|
return await db.query.yachts.findMany({
|
|
|
|
|
where: and(
|
|
|
|
|
eq(yachts.portId, portId),
|
|
|
|
|
eq(yachts.currentOwnerType, ownerType),
|
|
|
|
|
eq(yachts.currentOwnerId, ownerId),
|
chore(cleanup): Phase 1 — gap closure across audit, alerts, soft-delete, perms
Multi-area cleanup pass closing partial-implementation gaps surfaced by the
post-i18n audit. No behavior changes for happy-path users; closes real
correctness/security holes.
PR1a Public yacht-interest endpoint i18n. /api/public/interests now accepts
phoneE164/phoneCountry, nationalityIso, address.{countryIso, subdivisionIso},
and company.{incorporationCountryIso, incorporationSubdivisionIso}.
Server-side parsePhone() fallback for legacy raw phone strings.
PR1b Alert rule registry trim. Two rule slots ('document.expiring_soon',
'audit.suspicious_login') were registered but evaluators returned [].
Both required schema/instrumentation that hadn't landed. Removed from
the registry; comments record the dependencies needed to revive them.
Effective rule count: 8 active.
PR1c vi.mock hoist + flake fix. Hoisted vi.mock calls to top-level in 5
integration test files; webhook-delivery uses vi.hoisted for the
queue-add ref. Vitest no longer warns about non-top-level mocks.
Deflaked the 'short value' assertion in security-encryption.test.ts
by switching plaintext from 'ab' to 'XY' (non-hex chars). 5/5 runs green.
PR1d Soft-delete reference audit. listClientOptions and listYachtsForOwner
now filter by isNull(archivedAt). Berths use status (no archivedAt).
PR1e Permission-matrix audit script + report. scripts/audit-permissions.ts
walks every src/app/api/v1/**/route.ts and reports handlers without a
withPermission() wrapper. Initial run found 33 violations.
- Allow-listed 17 with explicit reasons (self-data, admin, alerts,
search, currency, ai, custom-fields — some marked TODO).
- Wrapped 7 routes with concrete permissions: clients/options
(clients:view), berths/options (berths:view), dashboard/*
(reports:view_dashboard), analytics (reports:view_analytics).
Audit report at docs/runbooks/permission-audit.md. Script exits
non-zero on any unallow-listed violation so it can become a CI gate.
Vitest: 741 -> 741 (no new tests; existing suite covers the changes).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-28 18:48:22 +02:00
|
|
|
isNull(yachts.archivedAt),
|
feat(yachts): list + owner-scoped list + autocomplete
Adds `listYachts`, `listYachtsForOwner`, and `autocomplete` to the
yacht service so UIs can page/filter yachts per port, look up all
yachts tied to a given client/company, and power search-as-you-type.
`listYachts` delegates to the shared port-scoped `buildListQuery`,
supporting search over name/hullNumber/registration plus ownerType,
ownerId and status filters; `autocomplete` caps at 10 results and is
tenant-scoped; `listYachtsForOwner` returns all yachts whose current
owner matches, newest first. Extends `makeYacht` factory to accept
flat `name`, `status`, `hullNumber`, `registration` overrides.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 00:03:36 +02:00
|
|
|
),
|
|
|
|
|
orderBy: (t, { desc }) => [desc(t.updatedAt)],
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-24 12:40:51 +02:00
|
|
|
// ─── Ownership history ────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
export async function listOwnershipHistory(yachtId: string, portId: string) {
|
|
|
|
|
// First scope-check the yacht (throws NotFoundError if cross-tenant)
|
|
|
|
|
await getYachtById(yachtId, portId);
|
|
|
|
|
return await db.query.yachtOwnershipHistory.findMany({
|
|
|
|
|
where: eq(yachtOwnershipHistory.yachtId, yachtId),
|
|
|
|
|
orderBy: (t, { desc }) => [desc(t.startDate)],
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
feat(yachts): list + owner-scoped list + autocomplete
Adds `listYachts`, `listYachtsForOwner`, and `autocomplete` to the
yacht service so UIs can page/filter yachts per port, look up all
yachts tied to a given client/company, and power search-as-you-type.
`listYachts` delegates to the shared port-scoped `buildListQuery`,
supporting search over name/hullNumber/registration plus ownerType,
ownerId and status filters; `autocomplete` caps at 10 results and is
tenant-scoped; `listYachtsForOwner` returns all yachts whose current
owner matches, newest first. Extends `makeYacht` factory to accept
flat `name`, `status`, `hullNumber`, `registration` overrides.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 00:03:36 +02:00
|
|
|
// ─── Autocomplete ─────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
export async function autocomplete(portId: string, q: string) {
|
2026-05-21 18:06:41 +02:00
|
|
|
// Empty query returns the top 20 most-recently-updated yachts so the
|
|
|
|
|
// picker has something useful to show the moment it opens, instead of
|
|
|
|
|
// a dead-end empty state until the rep types something.
|
|
|
|
|
if (!q) {
|
|
|
|
|
return await db
|
|
|
|
|
.select()
|
|
|
|
|
.from(yachts)
|
|
|
|
|
.where(eq(yachts.portId, portId))
|
|
|
|
|
.orderBy(desc(yachts.updatedAt))
|
|
|
|
|
.limit(20);
|
|
|
|
|
}
|
feat(yachts): list + owner-scoped list + autocomplete
Adds `listYachts`, `listYachtsForOwner`, and `autocomplete` to the
yacht service so UIs can page/filter yachts per port, look up all
yachts tied to a given client/company, and power search-as-you-type.
`listYachts` delegates to the shared port-scoped `buildListQuery`,
supporting search over name/hullNumber/registration plus ownerType,
ownerId and status filters; `autocomplete` caps at 10 results and is
tenant-scoped; `listYachtsForOwner` returns all yachts whose current
owner matches, newest first. Extends `makeYacht` factory to accept
flat `name`, `status`, `hullNumber`, `registration` overrides.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 00:03:36 +02:00
|
|
|
const pattern = `%${q}%`;
|
|
|
|
|
return await db
|
|
|
|
|
.select()
|
|
|
|
|
.from(yachts)
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(yachts.portId, portId),
|
|
|
|
|
or(
|
|
|
|
|
ilike(yachts.name, pattern),
|
|
|
|
|
ilike(yachts.hullNumber, pattern),
|
|
|
|
|
ilike(yachts.registration, pattern),
|
|
|
|
|
),
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
.limit(10);
|
|
|
|
|
}
|
feat(platform): residential module + admin UI + reliability fixes
Residential platform
- New schema: residentialClients, residentialInterests (separate from
marina/yacht clients) with migration 0010
- Service layer with CRUD + audit + sockets + per-port portal toggle
- v1 + public API routes (/api/v1/residential/*, /api/public/residential-inquiries)
- List + detail pages with inline editing for clients and interests
- Per-user residentialAccess toggle on userPortRoles (migration 0011)
- Permission keys: residential_clients, residential_interests
- Sidebar nav + role form integration
- Smoke spec covering page loads, UI create flow, public endpoint
Admin & shared UI
- Admin → Forms (form templates CRUD) with validators + service
- Notification preferences page (in-app + email per type)
- Email composition + accounts list + threads view
- Branded auth shell shared across CRM + portal auth surfaces
- Inline editing extended to yacht/company/interest detail pages
- InlineTagEditor + per-entity tags endpoints (yachts, companies)
- Notes service polymorphic across clients/interests/yachts/companies
- Client list columns: yachtCount + companyCount badges
- Reservation file-download via presigned URL (replaces stale <a href>)
Route handler refactor
- Extracted yachts/companies/berths reservation handlers to sibling
handlers.ts files (Next.js 15 route.ts only allows specific exports)
Reliability fixes
- apiFetch double-stringify bug fixed across 13 components
(apiFetch already JSON.stringifies its body; passing a stringified
body produced double-encoded JSON which failed zod validation)
- SocketProvider gated behind useSyncExternalStore-based mount check
to avoid useSession() SSR crashes under React 19 + Next 15
- apiFetch falls back to URL-pathname → port-id resolution when the
Zustand store hasn't hydrated yet (fresh contexts, e2e tests)
- CRM invite flow (schema, service, route, email, dev script)
- Dashboard route → [portSlug]/dashboard/page.tsx + redirect
- Document the dev-server restart-after-migration gotcha in CLAUDE.md
Tests
- 5-case residential smoke spec
- Integration test updates for new service signatures
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 21:54:32 +02:00
|
|
|
|
|
|
|
|
export async function setYachtTags(
|
|
|
|
|
yachtId: string,
|
|
|
|
|
portId: string,
|
|
|
|
|
tagIds: string[],
|
|
|
|
|
meta: AuditMeta,
|
|
|
|
|
) {
|
|
|
|
|
const yacht = await db.query.yachts.findFirst({ where: eq(yachts.id, yachtId) });
|
|
|
|
|
if (!yacht || yacht.portId !== portId) throw new NotFoundError('Yacht');
|
|
|
|
|
|
2026-04-29 01:58:42 +02:00
|
|
|
await setEntityTags({
|
|
|
|
|
joinTable: yachtTags,
|
|
|
|
|
entityColumn: yachtTags.yachtId,
|
|
|
|
|
tagColumn: yachtTags.tagId,
|
|
|
|
|
entityId: yachtId,
|
feat(platform): residential module + admin UI + reliability fixes
Residential platform
- New schema: residentialClients, residentialInterests (separate from
marina/yacht clients) with migration 0010
- Service layer with CRUD + audit + sockets + per-port portal toggle
- v1 + public API routes (/api/v1/residential/*, /api/public/residential-inquiries)
- List + detail pages with inline editing for clients and interests
- Per-user residentialAccess toggle on userPortRoles (migration 0011)
- Permission keys: residential_clients, residential_interests
- Sidebar nav + role form integration
- Smoke spec covering page loads, UI create flow, public endpoint
Admin & shared UI
- Admin → Forms (form templates CRUD) with validators + service
- Notification preferences page (in-app + email per type)
- Email composition + accounts list + threads view
- Branded auth shell shared across CRM + portal auth surfaces
- Inline editing extended to yacht/company/interest detail pages
- InlineTagEditor + per-entity tags endpoints (yachts, companies)
- Notes service polymorphic across clients/interests/yachts/companies
- Client list columns: yachtCount + companyCount badges
- Reservation file-download via presigned URL (replaces stale <a href>)
Route handler refactor
- Extracted yachts/companies/berths reservation handlers to sibling
handlers.ts files (Next.js 15 route.ts only allows specific exports)
Reliability fixes
- apiFetch double-stringify bug fixed across 13 components
(apiFetch already JSON.stringifies its body; passing a stringified
body produced double-encoded JSON which failed zod validation)
- SocketProvider gated behind useSyncExternalStore-based mount check
to avoid useSession() SSR crashes under React 19 + Next 15
- apiFetch falls back to URL-pathname → port-id resolution when the
Zustand store hasn't hydrated yet (fresh contexts, e2e tests)
- CRM invite flow (schema, service, route, email, dev script)
- Dashboard route → [portSlug]/dashboard/page.tsx + redirect
- Document the dev-server restart-after-migration gotcha in CLAUDE.md
Tests
- 5-case residential smoke spec
- Integration test updates for new service signatures
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 21:54:32 +02:00
|
|
|
portId,
|
2026-04-29 01:58:42 +02:00
|
|
|
tagIds,
|
|
|
|
|
meta,
|
feat(platform): residential module + admin UI + reliability fixes
Residential platform
- New schema: residentialClients, residentialInterests (separate from
marina/yacht clients) with migration 0010
- Service layer with CRUD + audit + sockets + per-port portal toggle
- v1 + public API routes (/api/v1/residential/*, /api/public/residential-inquiries)
- List + detail pages with inline editing for clients and interests
- Per-user residentialAccess toggle on userPortRoles (migration 0011)
- Permission keys: residential_clients, residential_interests
- Sidebar nav + role form integration
- Smoke spec covering page loads, UI create flow, public endpoint
Admin & shared UI
- Admin → Forms (form templates CRUD) with validators + service
- Notification preferences page (in-app + email per type)
- Email composition + accounts list + threads view
- Branded auth shell shared across CRM + portal auth surfaces
- Inline editing extended to yacht/company/interest detail pages
- InlineTagEditor + per-entity tags endpoints (yachts, companies)
- Notes service polymorphic across clients/interests/yachts/companies
- Client list columns: yachtCount + companyCount badges
- Reservation file-download via presigned URL (replaces stale <a href>)
Route handler refactor
- Extracted yachts/companies/berths reservation handlers to sibling
handlers.ts files (Next.js 15 route.ts only allows specific exports)
Reliability fixes
- apiFetch double-stringify bug fixed across 13 components
(apiFetch already JSON.stringifies its body; passing a stringified
body produced double-encoded JSON which failed zod validation)
- SocketProvider gated behind useSyncExternalStore-based mount check
to avoid useSession() SSR crashes under React 19 + Next 15
- apiFetch falls back to URL-pathname → port-id resolution when the
Zustand store hasn't hydrated yet (fresh contexts, e2e tests)
- CRM invite flow (schema, service, route, email, dev script)
- Dashboard route → [portSlug]/dashboard/page.tsx + redirect
- Document the dev-server restart-after-migration gotcha in CLAUDE.md
Tests
- 5-case residential smoke spec
- Integration test updates for new service signatures
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 21:54:32 +02:00
|
|
|
entityType: 'yacht',
|
|
|
|
|
});
|
|
|
|
|
}
|