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
|
|
|
import { and, count, desc, eq, ilike, inArray, isNull, or, sql } from 'drizzle-orm';
|
2026-04-24 12:02:08 +02:00
|
|
|
import { db } from '@/lib/db';
|
2026-04-28 19:38:43 +02:00
|
|
|
import {
|
|
|
|
|
companies,
|
|
|
|
|
companyMemberships,
|
|
|
|
|
companyTags,
|
|
|
|
|
companyAddresses,
|
|
|
|
|
} from '@/lib/db/schema/companies';
|
2026-04-24 12:02:08 +02:00
|
|
|
import type { Company } from '@/lib/db/schema/companies';
|
2026-04-27 21:57:13 +02:00
|
|
|
import { yachts } from '@/lib/db/schema/yachts';
|
2026-04-24 12:02:08 +02:00
|
|
|
import { withTransaction } from '@/lib/db/utils';
|
|
|
|
|
import { buildListQuery } from '@/lib/db/query-builder';
|
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-24 12:02:08 +02:00
|
|
|
import { NotFoundError, ConflictError } 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-24 12:02:08 +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-24 12:02:08 +02:00
|
|
|
import { diffEntity } from '@/lib/entity-diff';
|
|
|
|
|
import type { z } from 'zod';
|
|
|
|
|
import type {
|
|
|
|
|
createCompanySchema,
|
|
|
|
|
UpdateCompanyInput,
|
|
|
|
|
ListCompaniesInput,
|
|
|
|
|
} from '@/lib/validators/companies';
|
|
|
|
|
|
2026-05-12 14:50:58 +02:00
|
|
|
type CreateCompanyInput = z.output<typeof createCompanySchema>;
|
2026-04-24 12:02:08 +02:00
|
|
|
|
|
|
|
|
export type { Company };
|
|
|
|
|
|
|
|
|
|
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Returns true if the error is a Postgres unique-violation (SQLSTATE 23505).
|
|
|
|
|
* We check a few shapes because the exact object depends on the driver.
|
|
|
|
|
*/
|
|
|
|
|
function isUniqueViolation(err: unknown): boolean {
|
|
|
|
|
if (!err || typeof err !== 'object') return false;
|
|
|
|
|
const e = err as { code?: unknown; cause?: { code?: unknown } };
|
|
|
|
|
if (e.code === '23505') return true;
|
|
|
|
|
if (e.cause && typeof e.cause === 'object' && e.cause.code === '23505') return true;
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ─── Create ──────────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
export async function createCompany(portId: string, data: CreateCompanyInput, meta: AuditMeta) {
|
|
|
|
|
// Pre-check (case-insensitive) for friendlier ConflictError; the partial unique
|
|
|
|
|
// index `idx_companies_name_unique ON companies(portId, lower(name))` is the
|
|
|
|
|
// authoritative guard and caught below as defense-in-depth.
|
|
|
|
|
const existing = await db.query.companies.findFirst({
|
|
|
|
|
where: and(eq(companies.portId, portId), sql`lower(${companies.name}) = lower(${data.name})`),
|
|
|
|
|
});
|
|
|
|
|
if (existing) {
|
|
|
|
|
throw new ConflictError('company name already exists');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
return await withTransaction(async (tx) => {
|
|
|
|
|
const [company] = await tx
|
|
|
|
|
.insert(companies)
|
|
|
|
|
.values({
|
|
|
|
|
portId,
|
|
|
|
|
name: data.name,
|
|
|
|
|
legalName: data.legalName ?? null,
|
|
|
|
|
taxId: data.taxId ?? null,
|
|
|
|
|
registrationNumber: data.registrationNumber ?? null,
|
chore(i18n): drop legacy free-text country/nationality columns
Test-data only — no production migration needed (per earlier decision).
Schema is now ISO-only; readers convert ISO codes to localized names where
human-readable output is required (EOI documents, invoices, portal).
Migration 0016 drops:
- clients.nationality
- companies.incorporation_country
- client_addresses.{state_province, country}
- company_addresses.{state_province, country}
Code paths that previously read free-text values now read the ISO column
and pass through `getCountryName()` / `getSubdivisionName()` for rendering.
Document templates ({{client.nationality}}), portal client view, EOI/
reservation-agreement contexts, and invoice billing addresses all updated.
Public yacht-interest endpoint (/api/public/interests) drops the legacy
fields from its insert path and writes ISO codes only. The Zod validators
no longer accept the legacy fields — older website builds posting raw
'incorporationCountry' / 'country' / 'stateProvince' will get 400s.
Server-side phone normalization is unchanged.
Seed data updated to use ISO codes (GB/FR/ES/GR/SE/IT/GH/MC/PA), spread
across continents to keep test fixtures realistic.
Test assertions updated to match the new render shape (e.g.
'United States' not 'US', 'California' not 'CA').
Vitest: 741 -> 741 (unchanged count; assertions updated, no new tests).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-28 19:00:57 +02:00
|
|
|
incorporationCountryIso: data.incorporationCountryIso ?? null,
|
|
|
|
|
incorporationSubdivisionIso: data.incorporationSubdivisionIso ?? null,
|
2026-04-24 12:02:08 +02:00
|
|
|
incorporationDate: data.incorporationDate ?? null,
|
|
|
|
|
status: data.status ?? 'active',
|
|
|
|
|
billingEmail: data.billingEmail ?? null,
|
|
|
|
|
notes: data.notes ?? null,
|
|
|
|
|
})
|
|
|
|
|
.returning();
|
|
|
|
|
|
|
|
|
|
const tagIds = data.tagIds ?? [];
|
|
|
|
|
if (tagIds.length > 0) {
|
|
|
|
|
await tx
|
|
|
|
|
.insert(companyTags)
|
|
|
|
|
.values(tagIds.map((tagId) => ({ companyId: company!.id, tagId })));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void createAuditLog({
|
|
|
|
|
userId: meta.userId,
|
|
|
|
|
portId,
|
|
|
|
|
action: 'create',
|
|
|
|
|
entityType: 'company',
|
|
|
|
|
entityId: company!.id,
|
|
|
|
|
newValue: { name: company!.name, status: company!.status },
|
|
|
|
|
ipAddress: meta.ipAddress,
|
|
|
|
|
userAgent: meta.userAgent,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
emitToRoom(`port:${portId}`, 'company:created', { companyId: company!.id });
|
|
|
|
|
|
|
|
|
|
return company!;
|
|
|
|
|
});
|
|
|
|
|
} catch (err) {
|
|
|
|
|
if (isUniqueViolation(err)) {
|
|
|
|
|
throw new ConflictError('company name already exists');
|
|
|
|
|
}
|
|
|
|
|
throw err;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ─── Get ─────────────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
export async function getCompanyById(id: string, portId: string) {
|
|
|
|
|
const company = await db.query.companies.findFirst({
|
|
|
|
|
where: and(eq(companies.id, id), eq(companies.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-24 12:02:08 +02:00
|
|
|
});
|
|
|
|
|
if (!company) throw new NotFoundError('Company');
|
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 } = company as typeof company & {
|
|
|
|
|
tags: Array<{ tag: { id: string; name: string; color: string } }>;
|
|
|
|
|
};
|
2026-04-28 19:38:43 +02:00
|
|
|
|
|
|
|
|
const addresses = await db.query.companyAddresses.findMany({
|
|
|
|
|
where: eq(companyAddresses.companyId, id),
|
|
|
|
|
orderBy: (t, { desc }) => [desc(t.isPrimary), desc(t.createdAt)],
|
|
|
|
|
});
|
|
|
|
|
|
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. Symmetric-reach via
|
|
|
|
|
// owned yachts + their linked interests (member-client personal
|
|
|
|
|
// notes intentionally excluded — they belong on the client dossier).
|
|
|
|
|
const { countForCompanyAggregated } = await import('@/lib/services/notes.service');
|
|
|
|
|
const noteCount = await countForCompanyAggregated(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),
|
2026-04-28 19:38:43 +02:00
|
|
|
addresses,
|
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-24 12:02:08 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ─── Update ──────────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
export async function updateCompany(
|
|
|
|
|
id: string,
|
|
|
|
|
portId: string,
|
|
|
|
|
data: UpdateCompanyInput,
|
|
|
|
|
meta: AuditMeta,
|
|
|
|
|
) {
|
|
|
|
|
const existing = await db.query.companies.findFirst({
|
|
|
|
|
where: eq(companies.id, id),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!existing || existing.portId !== portId) {
|
|
|
|
|
throw new NotFoundError('Company');
|
|
|
|
|
}
|
|
|
|
|
|
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-24 12:02:08 +02:00
|
|
|
|
|
|
|
|
let updated: Company | undefined;
|
|
|
|
|
try {
|
|
|
|
|
const rows = await db
|
|
|
|
|
.update(companies)
|
|
|
|
|
.set({ ...data, updatedAt: new Date() })
|
|
|
|
|
.where(and(eq(companies.id, id), eq(companies.portId, portId)))
|
|
|
|
|
.returning();
|
|
|
|
|
updated = rows[0];
|
|
|
|
|
} catch (err) {
|
|
|
|
|
if (isUniqueViolation(err)) {
|
|
|
|
|
throw new ConflictError('company name already exists');
|
|
|
|
|
}
|
|
|
|
|
throw err;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void createAuditLog({
|
|
|
|
|
userId: meta.userId,
|
|
|
|
|
portId,
|
|
|
|
|
action: 'update',
|
|
|
|
|
entityType: 'company',
|
|
|
|
|
entityId: id,
|
|
|
|
|
oldValue: diff as Record<string, unknown>,
|
|
|
|
|
newValue: data as Record<string, unknown>,
|
|
|
|
|
ipAddress: meta.ipAddress,
|
|
|
|
|
userAgent: meta.userAgent,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
emitToRoom(`port:${portId}`, 'company:updated', {
|
|
|
|
|
companyId: id,
|
|
|
|
|
changedFields: Object.keys(diff),
|
|
|
|
|
});
|
|
|
|
|
|
2026-05-11 11:25:16 +02:00
|
|
|
if (data.name !== undefined) {
|
|
|
|
|
await syncEntityFolderName(portId, 'company', id, meta.userId).catch((err) => {
|
2026-05-11 13:57:42 +02:00
|
|
|
logger.warn({ err, companyId: id, portId }, 'Failed to sync company folder name');
|
2026-05-11 11:25:16 +02:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-24 12:02:08 +02:00
|
|
|
return updated!;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ─── Archive ─────────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
export async function archiveCompany(id: string, portId: string, meta: AuditMeta) {
|
|
|
|
|
const existing = await db.query.companies.findFirst({
|
|
|
|
|
where: eq(companies.id, id),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!existing || existing.portId !== portId) {
|
|
|
|
|
throw new NotFoundError('Company');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 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. (See Task 2.3 for context.)
|
|
|
|
|
await db
|
|
|
|
|
.update(companies)
|
|
|
|
|
.set({ archivedAt: new Date() })
|
|
|
|
|
.where(and(eq(companies.id, id), eq(companies.portId, portId)));
|
|
|
|
|
|
2026-05-11 13:57:42 +02:00
|
|
|
void applyEntityArchivedSuffix(portId, 'company', id, meta.userId).catch((err) => {
|
|
|
|
|
logger.warn(
|
|
|
|
|
{ err, companyId: id, portId },
|
|
|
|
|
'Failed to apply archived suffix to company folder',
|
|
|
|
|
);
|
2026-05-11 11:34:02 +02:00
|
|
|
});
|
|
|
|
|
|
2026-04-24 12:02:08 +02:00
|
|
|
void createAuditLog({
|
|
|
|
|
userId: meta.userId,
|
|
|
|
|
portId,
|
|
|
|
|
action: 'archive',
|
|
|
|
|
entityType: 'company',
|
|
|
|
|
entityId: id,
|
|
|
|
|
ipAddress: meta.ipAddress,
|
|
|
|
|
userAgent: meta.userAgent,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
emitToRoom(`port:${portId}`, 'company:archived', { companyId: id });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ─── List ────────────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
export async function listCompanies(portId: string, query: ListCompaniesInput) {
|
|
|
|
|
const { page, limit, sort, order, search, includeArchived, status } = query;
|
|
|
|
|
|
|
|
|
|
const filters = [];
|
|
|
|
|
if (status) filters.push(eq(companies.status, status));
|
|
|
|
|
|
|
|
|
|
let sortColumn: typeof companies.name | typeof companies.createdAt | typeof companies.updatedAt =
|
|
|
|
|
companies.updatedAt;
|
|
|
|
|
if (sort === 'name') sortColumn = companies.name;
|
|
|
|
|
else if (sort === 'createdAt') sortColumn = companies.createdAt;
|
|
|
|
|
|
|
|
|
|
const result = await buildListQuery<Company>({
|
|
|
|
|
table: companies,
|
|
|
|
|
portIdColumn: companies.portId,
|
|
|
|
|
portId,
|
|
|
|
|
idColumn: companies.id,
|
|
|
|
|
updatedAtColumn: companies.updatedAt,
|
|
|
|
|
searchColumns: [companies.name, companies.legalName, companies.taxId],
|
|
|
|
|
searchTerm: search,
|
|
|
|
|
filters,
|
|
|
|
|
sort: sort ? { column: sortColumn, direction: order } : undefined,
|
|
|
|
|
page,
|
|
|
|
|
pageSize: limit,
|
|
|
|
|
includeArchived,
|
|
|
|
|
archivedAtColumn: companies.archivedAt,
|
|
|
|
|
});
|
|
|
|
|
|
2026-04-27 21:57:13 +02:00
|
|
|
if (result.data.length === 0) return result;
|
|
|
|
|
|
|
|
|
|
const ids = result.data.map((r) => r.id);
|
|
|
|
|
|
|
|
|
|
const [memberCounts, yachtCounts] = await Promise.all([
|
|
|
|
|
db
|
|
|
|
|
.select({ companyId: companyMemberships.companyId, count: count() })
|
|
|
|
|
.from(companyMemberships)
|
|
|
|
|
.where(and(inArray(companyMemberships.companyId, ids), isNull(companyMemberships.endDate)))
|
|
|
|
|
.groupBy(companyMemberships.companyId),
|
|
|
|
|
db
|
|
|
|
|
.select({ ownerId: yachts.currentOwnerId, count: count() })
|
|
|
|
|
.from(yachts)
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(yachts.portId, portId),
|
|
|
|
|
eq(yachts.currentOwnerType, 'company'),
|
|
|
|
|
inArray(yachts.currentOwnerId, ids),
|
|
|
|
|
isNull(yachts.archivedAt),
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
.groupBy(yachts.currentOwnerId),
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
const memberCountMap = new Map(memberCounts.map((r) => [r.companyId, r.count]));
|
|
|
|
|
const yachtCountMap = new Map(yachtCounts.map((r) => [r.ownerId, r.count]));
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
...result,
|
|
|
|
|
data: result.data.map((row) => ({
|
|
|
|
|
...row,
|
|
|
|
|
memberCount: memberCountMap.get(row.id) ?? 0,
|
|
|
|
|
yachtCount: yachtCountMap.get(row.id) ?? 0,
|
|
|
|
|
})),
|
|
|
|
|
};
|
2026-04-24 12:02:08 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ─── Autocomplete ────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
export async function autocomplete(portId: string, q: string) {
|
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
|
|
|
// Empty query → return the 10 most-recently-updated companies for the
|
|
|
|
|
// port so the picker has something to scan on first open. Non-empty
|
|
|
|
|
// query → ilike-match against name + legalName as before.
|
|
|
|
|
const trimmed = q.trim();
|
|
|
|
|
const baseQuery = db.select().from(companies);
|
|
|
|
|
if (!trimmed) {
|
|
|
|
|
return await baseQuery
|
|
|
|
|
.where(eq(companies.portId, portId))
|
|
|
|
|
.orderBy(desc(companies.updatedAt))
|
|
|
|
|
.limit(10);
|
|
|
|
|
}
|
|
|
|
|
const pattern = `%${trimmed}%`;
|
|
|
|
|
return await baseQuery
|
2026-04-24 12:02:08 +02:00
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(companies.portId, portId),
|
|
|
|
|
or(ilike(companies.name, pattern), ilike(companies.legalName, pattern)),
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
.limit(10);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ─── Upsert by name (find-or-create) ─────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Find-or-create a company by (portId, lower(name)). NOT a Postgres UPSERT.
|
|
|
|
|
*
|
|
|
|
|
* Runs a case-insensitive SELECT scoped by portId; if found, returns it.
|
|
|
|
|
* Otherwise inserts a new row with the provided `name` verbatim. A concurrent
|
|
|
|
|
* insert that hits the partial unique index (23505) is re-raised as
|
|
|
|
|
* ConflictError for the caller to retry if desired.
|
|
|
|
|
*/
|
|
|
|
|
export async function upsertByName(portId: string, name: string, meta: AuditMeta) {
|
|
|
|
|
return await withTransaction(async (tx) => {
|
|
|
|
|
const existing = await tx.query.companies.findFirst({
|
|
|
|
|
where: and(eq(companies.portId, portId), sql`lower(${companies.name}) = lower(${name})`),
|
|
|
|
|
});
|
|
|
|
|
if (existing) return existing;
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const [company] = await tx
|
|
|
|
|
.insert(companies)
|
|
|
|
|
.values({
|
|
|
|
|
portId,
|
|
|
|
|
name,
|
|
|
|
|
status: 'active',
|
|
|
|
|
})
|
|
|
|
|
.returning();
|
|
|
|
|
|
|
|
|
|
void createAuditLog({
|
|
|
|
|
userId: meta.userId,
|
|
|
|
|
portId,
|
|
|
|
|
action: 'create',
|
|
|
|
|
entityType: 'company',
|
|
|
|
|
entityId: company!.id,
|
|
|
|
|
newValue: { name: company!.name, status: company!.status },
|
|
|
|
|
ipAddress: meta.ipAddress,
|
|
|
|
|
userAgent: meta.userAgent,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
emitToRoom(`port:${portId}`, 'company:created', { companyId: company!.id });
|
|
|
|
|
|
|
|
|
|
return company!;
|
|
|
|
|
} catch (err) {
|
|
|
|
|
if (isUniqueViolation(err)) {
|
|
|
|
|
throw new ConflictError('company name already exists');
|
|
|
|
|
}
|
|
|
|
|
throw err;
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
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 setCompanyTags(
|
|
|
|
|
companyId: string,
|
|
|
|
|
portId: string,
|
|
|
|
|
tagIds: string[],
|
|
|
|
|
meta: AuditMeta,
|
|
|
|
|
) {
|
|
|
|
|
const company = await db.query.companies.findFirst({ where: eq(companies.id, companyId) });
|
|
|
|
|
if (!company || company.portId !== portId) throw new NotFoundError('Company');
|
|
|
|
|
|
2026-04-29 01:58:42 +02:00
|
|
|
await setEntityTags({
|
|
|
|
|
joinTable: companyTags,
|
|
|
|
|
entityColumn: companyTags.companyId,
|
|
|
|
|
tagColumn: companyTags.tagId,
|
|
|
|
|
entityId: companyId,
|
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: 'company',
|
|
|
|
|
});
|
|
|
|
|
}
|
2026-04-28 19:38:43 +02:00
|
|
|
|
|
|
|
|
// ─── Addresses ────────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
interface CompanyAddressInput {
|
|
|
|
|
label?: string;
|
|
|
|
|
streetAddress?: string | null;
|
|
|
|
|
city?: string | null;
|
|
|
|
|
subdivisionIso?: string | null;
|
|
|
|
|
postalCode?: string | null;
|
|
|
|
|
countryIso?: string | null;
|
|
|
|
|
isPrimary?: boolean;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function listCompanyAddresses(companyId: string, portId: string) {
|
|
|
|
|
const company = await db.query.companies.findFirst({ where: eq(companies.id, companyId) });
|
|
|
|
|
if (!company || company.portId !== portId) throw new NotFoundError('Company');
|
|
|
|
|
|
|
|
|
|
return db.query.companyAddresses.findMany({
|
|
|
|
|
where: eq(companyAddresses.companyId, companyId),
|
|
|
|
|
orderBy: (t, { desc }) => [desc(t.isPrimary), desc(t.createdAt)],
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function addCompanyAddress(
|
|
|
|
|
companyId: string,
|
|
|
|
|
portId: string,
|
|
|
|
|
data: CompanyAddressInput,
|
|
|
|
|
meta: AuditMeta,
|
|
|
|
|
) {
|
|
|
|
|
const company = await db.query.companies.findFirst({ where: eq(companies.id, companyId) });
|
|
|
|
|
if (!company || company.portId !== portId) throw new NotFoundError('Company');
|
|
|
|
|
|
|
|
|
|
const address = await withTransaction(async (tx) => {
|
2026-04-29 01:52:41 +02:00
|
|
|
// Lock the company row to serialize concurrent primary-toggle requests.
|
|
|
|
|
await tx
|
|
|
|
|
.select({ id: companies.id })
|
|
|
|
|
.from(companies)
|
|
|
|
|
.where(eq(companies.id, companyId))
|
|
|
|
|
.for('update');
|
|
|
|
|
|
2026-04-28 19:38:43 +02:00
|
|
|
const wantsPrimary = data.isPrimary ?? false;
|
|
|
|
|
if (wantsPrimary) {
|
|
|
|
|
await tx
|
|
|
|
|
.update(companyAddresses)
|
|
|
|
|
.set({ isPrimary: false })
|
|
|
|
|
.where(
|
|
|
|
|
and(eq(companyAddresses.companyId, companyId), eq(companyAddresses.isPrimary, true)),
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
const [row] = await tx
|
|
|
|
|
.insert(companyAddresses)
|
|
|
|
|
.values({
|
|
|
|
|
companyId,
|
|
|
|
|
portId,
|
|
|
|
|
label: data.label ?? 'Primary',
|
|
|
|
|
streetAddress: data.streetAddress ?? null,
|
|
|
|
|
city: data.city ?? null,
|
|
|
|
|
subdivisionIso: data.subdivisionIso ?? null,
|
|
|
|
|
postalCode: data.postalCode ?? null,
|
|
|
|
|
countryIso: data.countryIso ?? null,
|
|
|
|
|
isPrimary: wantsPrimary,
|
|
|
|
|
})
|
|
|
|
|
.returning();
|
|
|
|
|
return row!;
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
void createAuditLog({
|
|
|
|
|
userId: meta.userId,
|
|
|
|
|
portId,
|
|
|
|
|
action: 'create',
|
|
|
|
|
entityType: 'companyAddress',
|
|
|
|
|
entityId: address.id,
|
|
|
|
|
newValue: { companyId, label: address.label, countryIso: address.countryIso },
|
|
|
|
|
ipAddress: meta.ipAddress,
|
|
|
|
|
userAgent: meta.userAgent,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
emitToRoom(`port:${portId}`, 'company:updated', { companyId, changedFields: ['addresses'] });
|
|
|
|
|
|
|
|
|
|
return address;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function updateCompanyAddress(
|
|
|
|
|
addressId: string,
|
|
|
|
|
companyId: string,
|
|
|
|
|
portId: string,
|
|
|
|
|
data: CompanyAddressInput,
|
|
|
|
|
_meta: AuditMeta,
|
|
|
|
|
) {
|
|
|
|
|
const company = await db.query.companies.findFirst({ where: eq(companies.id, companyId) });
|
|
|
|
|
if (!company || company.portId !== portId) throw new NotFoundError('Company');
|
|
|
|
|
|
|
|
|
|
const existing = await db.query.companyAddresses.findFirst({
|
|
|
|
|
where: and(eq(companyAddresses.id, addressId), eq(companyAddresses.companyId, companyId)),
|
|
|
|
|
});
|
|
|
|
|
if (!existing) throw new NotFoundError('Address');
|
|
|
|
|
|
|
|
|
|
const updated = await withTransaction(async (tx) => {
|
2026-04-29 01:52:41 +02:00
|
|
|
// Lock the company row to serialize primary-toggle changes.
|
|
|
|
|
await tx
|
|
|
|
|
.select({ id: companies.id })
|
|
|
|
|
.from(companies)
|
|
|
|
|
.where(eq(companies.id, companyId))
|
|
|
|
|
.for('update');
|
|
|
|
|
|
2026-04-28 19:38:43 +02:00
|
|
|
if (data.isPrimary === true && !existing.isPrimary) {
|
|
|
|
|
await tx
|
|
|
|
|
.update(companyAddresses)
|
|
|
|
|
.set({ isPrimary: false })
|
|
|
|
|
.where(
|
|
|
|
|
and(eq(companyAddresses.companyId, companyId), eq(companyAddresses.isPrimary, true)),
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
const [row] = await tx
|
|
|
|
|
.update(companyAddresses)
|
|
|
|
|
.set({ ...data, updatedAt: new Date() })
|
|
|
|
|
.where(eq(companyAddresses.id, addressId))
|
|
|
|
|
.returning();
|
|
|
|
|
return row!;
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
emitToRoom(`port:${portId}`, 'company:updated', { companyId, changedFields: ['addresses'] });
|
|
|
|
|
|
|
|
|
|
return updated;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function removeCompanyAddress(
|
|
|
|
|
addressId: string,
|
|
|
|
|
companyId: string,
|
|
|
|
|
portId: string,
|
|
|
|
|
_meta: AuditMeta,
|
|
|
|
|
) {
|
|
|
|
|
const company = await db.query.companies.findFirst({ where: eq(companies.id, companyId) });
|
|
|
|
|
if (!company || company.portId !== portId) throw new NotFoundError('Company');
|
|
|
|
|
|
|
|
|
|
const address = await db.query.companyAddresses.findFirst({
|
|
|
|
|
where: and(eq(companyAddresses.id, addressId), eq(companyAddresses.companyId, companyId)),
|
|
|
|
|
});
|
|
|
|
|
if (!address) throw new NotFoundError('Address');
|
|
|
|
|
|
|
|
|
|
await db.delete(companyAddresses).where(eq(companyAddresses.id, addressId));
|
|
|
|
|
|
|
|
|
|
emitToRoom(`port:${portId}`, 'company:updated', { companyId, changedFields: ['addresses'] });
|
|
|
|
|
}
|