2026-04-08 15:47:11 -04:00
|
|
|
import { and, eq } from 'drizzle-orm';
|
|
|
|
|
|
|
|
|
|
import { db } from '@/lib/db';
|
|
|
|
|
import { user, userProfiles, userPortRoles, roles } from '@/lib/db/schema';
|
|
|
|
|
import { auth } from '@/lib/auth';
|
2026-04-29 01:58:42 +02:00
|
|
|
import { createAuditLog, type AuditMeta } from '@/lib/audit';
|
2026-04-08 15:47:11 -04:00
|
|
|
import { ConflictError, NotFoundError, ValidationError } from '@/lib/errors';
|
|
|
|
|
import { emitToRoom } from '@/lib/socket/server';
|
|
|
|
|
import type { CreateUserInput, UpdateUserInput } from '@/lib/validators/users';
|
|
|
|
|
|
|
|
|
|
export async function listUsers(portId: string) {
|
feat(interests): EOI/contract/reservation tabs + contact log + berth interest milestone + interest list overhaul
Major interest workflow expansion driven by the rapid-fire UX session.
EOI / Contract / Reservation tabs replace the generic Documents tab when
the deal is at the relevant stage — workspace pattern with active-doc
hero, signing progress, paper-signed upload, and history strip. Stage-
conditional visibility wired through interest-tabs.tsx so the tab set
shrinks/expands as the deal moves through the pipeline.
Contact log: per-interaction structured log (channel/direction/summary/
optional follow-up reminder). New `interest_contact_log` table + service
+ tab UI (timeline with channel-coded icons + compose dialog).
auto-creates a reminder when followUpAt is set.
Berth Interest milestone: first milestone in the OverviewTab's pipeline
strip, completes the moment any berth is linked via the junction. Drives
the "have we captured what they want?" sanity check for general_interest
leads before they move to EOI.
Stage-conditional milestones: past phases collapse into a one-liner
strip, current phase expands, future phases hide behind a "Show
upcoming" toggle. Inline stage picker now defers reason capture to an
override-confirm view (only required for illegal transitions, not the
default flow).
Notes blob → threaded: dropped `interests.notes` column entirely; the
threaded `interest_notes` table is the single source of truth. Latest-
note teaser on Overview links into the dedicated Notes tab. Polymorphic
notes service gains aggregated client view (unions client + interest +
yacht notes with source chips and group-by-source toggle).
Berth interest list overhaul:
- Configurable columns via ColumnPicker (18 toggleable, 5 default-on)
- Natural-sort SQL ORDER BY on mooring number (A1, A2, A10 not A10, A2)
- Per-letter row tinting via colored left-border accent + dot in cell
- Documents tab merged Files (single attachments section)
Topbar improvements:
- Always-visible back arrow on detail pages (path depth > 2)
- Breadcrumb-hint store + useBreadcrumbHint hook so detail pages can
push their entity hierarchy (Clients › Mary Smith › Interest › B17)
- Tighter spacing, softer separators, 160px crumb truncation
DataTable upgrades:
- Page-size selector with All option (validator cap raised to 1000)
- getRowClassName slot for per-row styling (used by berth tinting)
- Fixed Radix SelectItem crash on empty-string values via __any__
sentinel (was crashing every list page that opened a select filter)
Interest list:
- Configurable columns picker
- Stage cell clickable into detail
- TagPicker + SavedViewsDropdown sized h-8 to match adjacent buttons
- Save view moved into ColumnPicker menu; Views button hidden when
no views are saved
- Pipeline kanban board endpoint at /api/v1/interests/board with
minimal projection, 5000-row cap + truncated banner, filter
pass-through
Mobile chrome + sidebar collapse removed (always-expanded design choice).
User management lists super-admins (was inner-joined on user_port_roles
which excluded global super-admins).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 20:59:28 +02:00
|
|
|
// Two passes:
|
|
|
|
|
// 1. Users with an explicit user_port_roles row for this port
|
|
|
|
|
// 2. All super-admins (they have global access via the
|
|
|
|
|
// userProfiles.isSuperAdmin flag, no per-port row required —
|
|
|
|
|
// previous query missed them and the admin list looked empty
|
|
|
|
|
// to the only super-admin viewing it)
|
|
|
|
|
const portRoleRows = await db
|
2026-04-08 15:47:11 -04:00
|
|
|
.select({
|
|
|
|
|
userId: userPortRoles.userId,
|
|
|
|
|
displayName: userProfiles.displayName,
|
|
|
|
|
email: user.email,
|
|
|
|
|
phone: userProfiles.phone,
|
|
|
|
|
isActive: userProfiles.isActive,
|
|
|
|
|
isSuperAdmin: userProfiles.isSuperAdmin,
|
|
|
|
|
lastLoginAt: userProfiles.lastLoginAt,
|
|
|
|
|
roleId: roles.id,
|
|
|
|
|
roleName: roles.name,
|
|
|
|
|
assignedAt: userPortRoles.createdAt,
|
|
|
|
|
})
|
|
|
|
|
.from(userPortRoles)
|
|
|
|
|
.innerJoin(userProfiles, eq(userPortRoles.userId, userProfiles.userId))
|
|
|
|
|
.innerJoin(user, eq(userPortRoles.userId, user.id))
|
|
|
|
|
.innerJoin(roles, eq(userPortRoles.roleId, roles.id))
|
feat(interests): EOI/contract/reservation tabs + contact log + berth interest milestone + interest list overhaul
Major interest workflow expansion driven by the rapid-fire UX session.
EOI / Contract / Reservation tabs replace the generic Documents tab when
the deal is at the relevant stage — workspace pattern with active-doc
hero, signing progress, paper-signed upload, and history strip. Stage-
conditional visibility wired through interest-tabs.tsx so the tab set
shrinks/expands as the deal moves through the pipeline.
Contact log: per-interaction structured log (channel/direction/summary/
optional follow-up reminder). New `interest_contact_log` table + service
+ tab UI (timeline with channel-coded icons + compose dialog).
auto-creates a reminder when followUpAt is set.
Berth Interest milestone: first milestone in the OverviewTab's pipeline
strip, completes the moment any berth is linked via the junction. Drives
the "have we captured what they want?" sanity check for general_interest
leads before they move to EOI.
Stage-conditional milestones: past phases collapse into a one-liner
strip, current phase expands, future phases hide behind a "Show
upcoming" toggle. Inline stage picker now defers reason capture to an
override-confirm view (only required for illegal transitions, not the
default flow).
Notes blob → threaded: dropped `interests.notes` column entirely; the
threaded `interest_notes` table is the single source of truth. Latest-
note teaser on Overview links into the dedicated Notes tab. Polymorphic
notes service gains aggregated client view (unions client + interest +
yacht notes with source chips and group-by-source toggle).
Berth interest list overhaul:
- Configurable columns via ColumnPicker (18 toggleable, 5 default-on)
- Natural-sort SQL ORDER BY on mooring number (A1, A2, A10 not A10, A2)
- Per-letter row tinting via colored left-border accent + dot in cell
- Documents tab merged Files (single attachments section)
Topbar improvements:
- Always-visible back arrow on detail pages (path depth > 2)
- Breadcrumb-hint store + useBreadcrumbHint hook so detail pages can
push their entity hierarchy (Clients › Mary Smith › Interest › B17)
- Tighter spacing, softer separators, 160px crumb truncation
DataTable upgrades:
- Page-size selector with All option (validator cap raised to 1000)
- getRowClassName slot for per-row styling (used by berth tinting)
- Fixed Radix SelectItem crash on empty-string values via __any__
sentinel (was crashing every list page that opened a select filter)
Interest list:
- Configurable columns picker
- Stage cell clickable into detail
- TagPicker + SavedViewsDropdown sized h-8 to match adjacent buttons
- Save view moved into ColumnPicker menu; Views button hidden when
no views are saved
- Pipeline kanban board endpoint at /api/v1/interests/board with
minimal projection, 5000-row cap + truncated banner, filter
pass-through
Mobile chrome + sidebar collapse removed (always-expanded design choice).
User management lists super-admins (was inner-joined on user_port_roles
which excluded global super-admins).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 20:59:28 +02:00
|
|
|
.where(eq(userPortRoles.portId, portId));
|
2026-04-08 15:47:11 -04:00
|
|
|
|
feat(interests): EOI/contract/reservation tabs + contact log + berth interest milestone + interest list overhaul
Major interest workflow expansion driven by the rapid-fire UX session.
EOI / Contract / Reservation tabs replace the generic Documents tab when
the deal is at the relevant stage — workspace pattern with active-doc
hero, signing progress, paper-signed upload, and history strip. Stage-
conditional visibility wired through interest-tabs.tsx so the tab set
shrinks/expands as the deal moves through the pipeline.
Contact log: per-interaction structured log (channel/direction/summary/
optional follow-up reminder). New `interest_contact_log` table + service
+ tab UI (timeline with channel-coded icons + compose dialog).
auto-creates a reminder when followUpAt is set.
Berth Interest milestone: first milestone in the OverviewTab's pipeline
strip, completes the moment any berth is linked via the junction. Drives
the "have we captured what they want?" sanity check for general_interest
leads before they move to EOI.
Stage-conditional milestones: past phases collapse into a one-liner
strip, current phase expands, future phases hide behind a "Show
upcoming" toggle. Inline stage picker now defers reason capture to an
override-confirm view (only required for illegal transitions, not the
default flow).
Notes blob → threaded: dropped `interests.notes` column entirely; the
threaded `interest_notes` table is the single source of truth. Latest-
note teaser on Overview links into the dedicated Notes tab. Polymorphic
notes service gains aggregated client view (unions client + interest +
yacht notes with source chips and group-by-source toggle).
Berth interest list overhaul:
- Configurable columns via ColumnPicker (18 toggleable, 5 default-on)
- Natural-sort SQL ORDER BY on mooring number (A1, A2, A10 not A10, A2)
- Per-letter row tinting via colored left-border accent + dot in cell
- Documents tab merged Files (single attachments section)
Topbar improvements:
- Always-visible back arrow on detail pages (path depth > 2)
- Breadcrumb-hint store + useBreadcrumbHint hook so detail pages can
push their entity hierarchy (Clients › Mary Smith › Interest › B17)
- Tighter spacing, softer separators, 160px crumb truncation
DataTable upgrades:
- Page-size selector with All option (validator cap raised to 1000)
- getRowClassName slot for per-row styling (used by berth tinting)
- Fixed Radix SelectItem crash on empty-string values via __any__
sentinel (was crashing every list page that opened a select filter)
Interest list:
- Configurable columns picker
- Stage cell clickable into detail
- TagPicker + SavedViewsDropdown sized h-8 to match adjacent buttons
- Save view moved into ColumnPicker menu; Views button hidden when
no views are saved
- Pipeline kanban board endpoint at /api/v1/interests/board with
minimal projection, 5000-row cap + truncated banner, filter
pass-through
Mobile chrome + sidebar collapse removed (always-expanded design choice).
User management lists super-admins (was inner-joined on user_port_roles
which excluded global super-admins).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 20:59:28 +02:00
|
|
|
const superAdminRows = await db
|
|
|
|
|
.select({
|
|
|
|
|
userId: userProfiles.userId,
|
|
|
|
|
displayName: userProfiles.displayName,
|
|
|
|
|
email: user.email,
|
|
|
|
|
phone: userProfiles.phone,
|
|
|
|
|
isActive: userProfiles.isActive,
|
|
|
|
|
isSuperAdmin: userProfiles.isSuperAdmin,
|
|
|
|
|
lastLoginAt: userProfiles.lastLoginAt,
|
|
|
|
|
assignedAt: userProfiles.createdAt,
|
|
|
|
|
})
|
|
|
|
|
.from(userProfiles)
|
|
|
|
|
.innerJoin(user, eq(userProfiles.userId, user.id))
|
|
|
|
|
.where(eq(userProfiles.isSuperAdmin, true));
|
|
|
|
|
|
|
|
|
|
// Dedup: a super-admin who ALSO has an explicit per-port role
|
|
|
|
|
// appears once with their port-role displayed (more specific).
|
|
|
|
|
const seen = new Set(portRoleRows.map((r) => r.userId));
|
|
|
|
|
const merged = [
|
|
|
|
|
...portRoleRows.map((row) => ({
|
|
|
|
|
userId: row.userId,
|
|
|
|
|
displayName: row.displayName,
|
|
|
|
|
email: row.email,
|
|
|
|
|
phone: row.phone,
|
|
|
|
|
isActive: row.isActive,
|
|
|
|
|
isSuperAdmin: row.isSuperAdmin,
|
|
|
|
|
lastLoginAt: row.lastLoginAt,
|
|
|
|
|
role: { id: row.roleId, name: row.roleName },
|
|
|
|
|
assignedAt: row.assignedAt,
|
|
|
|
|
})),
|
|
|
|
|
...superAdminRows
|
|
|
|
|
.filter((row) => !seen.has(row.userId))
|
|
|
|
|
.map((row) => ({
|
|
|
|
|
userId: row.userId,
|
|
|
|
|
displayName: row.displayName,
|
|
|
|
|
email: row.email,
|
|
|
|
|
phone: row.phone,
|
|
|
|
|
isActive: row.isActive,
|
|
|
|
|
isSuperAdmin: row.isSuperAdmin,
|
|
|
|
|
lastLoginAt: row.lastLoginAt,
|
|
|
|
|
// Synthetic role label — super admins don't have a per-port
|
|
|
|
|
// role row, but the UI expects a `role` object. The list
|
|
|
|
|
// already shows the "Super Admin" badge separately.
|
|
|
|
|
role: { id: 'super_admin', name: 'super_admin' },
|
|
|
|
|
assignedAt: row.assignedAt,
|
|
|
|
|
})),
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
merged.sort((a, b) => (a.displayName ?? '').localeCompare(b.displayName ?? ''));
|
|
|
|
|
return merged;
|
2026-04-08 15:47:11 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function getUser(userId: string, portId: string) {
|
|
|
|
|
const profile = await db.query.userProfiles.findFirst({
|
|
|
|
|
where: eq(userProfiles.userId, userId),
|
|
|
|
|
});
|
|
|
|
|
if (!profile) throw new NotFoundError('User');
|
|
|
|
|
|
|
|
|
|
const authUser = await db.query.user.findFirst({
|
|
|
|
|
where: eq(user.id, userId),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const portRole = await db.query.userPortRoles.findFirst({
|
|
|
|
|
where: and(eq(userPortRoles.userId, userId), eq(userPortRoles.portId, portId)),
|
|
|
|
|
with: { role: true },
|
|
|
|
|
});
|
|
|
|
|
if (!portRole) throw new NotFoundError('User not assigned to this port');
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
userId: profile.userId,
|
|
|
|
|
displayName: profile.displayName,
|
|
|
|
|
email: authUser?.email ?? '',
|
|
|
|
|
phone: profile.phone,
|
|
|
|
|
isActive: profile.isActive,
|
|
|
|
|
isSuperAdmin: profile.isSuperAdmin,
|
|
|
|
|
lastLoginAt: profile.lastLoginAt,
|
|
|
|
|
avatarUrl: profile.avatarUrl,
|
|
|
|
|
preferences: profile.preferences,
|
|
|
|
|
role: { id: portRole.role.id, name: portRole.role.name },
|
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
|
|
|
residentialAccess: portRole.residentialAccess,
|
2026-04-08 15:47:11 -04:00
|
|
|
createdAt: profile.createdAt,
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function createUser(portId: string, data: CreateUserInput, meta: AuditMeta) {
|
|
|
|
|
// Check email uniqueness
|
|
|
|
|
const existingUser = await db.query.user.findFirst({
|
|
|
|
|
where: eq(user.email, data.email.toLowerCase()),
|
|
|
|
|
});
|
|
|
|
|
if (existingUser) {
|
|
|
|
|
throw new ConflictError('A user with this email already exists');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Validate role exists
|
|
|
|
|
const role = await db.query.roles.findFirst({
|
|
|
|
|
where: eq(roles.id, data.roleId),
|
|
|
|
|
});
|
|
|
|
|
if (!role) throw new ValidationError('Invalid role ID');
|
|
|
|
|
|
|
|
|
|
// Create Better Auth user
|
|
|
|
|
const authResult = await auth.api.signUpEmail({
|
|
|
|
|
body: {
|
|
|
|
|
email: data.email.toLowerCase(),
|
|
|
|
|
password: data.password,
|
|
|
|
|
name: data.name,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const newUserId = authResult.user.id;
|
|
|
|
|
|
|
|
|
|
// Create CRM profile
|
|
|
|
|
await db.insert(userProfiles).values({
|
|
|
|
|
userId: newUserId,
|
|
|
|
|
displayName: data.displayName,
|
|
|
|
|
phone: data.phone ?? null,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Assign to port with role
|
|
|
|
|
await db.insert(userPortRoles).values({
|
|
|
|
|
userId: newUserId,
|
|
|
|
|
portId,
|
|
|
|
|
roleId: data.roleId,
|
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
|
|
|
residentialAccess: data.residentialAccess ?? false,
|
2026-04-08 15:47:11 -04:00
|
|
|
assignedBy: meta.userId,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
void createAuditLog({
|
|
|
|
|
userId: meta.userId,
|
|
|
|
|
portId,
|
|
|
|
|
action: 'create',
|
|
|
|
|
entityType: 'user',
|
|
|
|
|
entityId: newUserId,
|
|
|
|
|
newValue: { email: data.email, displayName: data.displayName, role: role.name },
|
|
|
|
|
ipAddress: meta.ipAddress,
|
|
|
|
|
userAgent: meta.userAgent,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
emitToRoom(`port:${portId}`, 'system:alert', {
|
|
|
|
|
alertType: 'user:created',
|
|
|
|
|
message: `User "${data.displayName}" added`,
|
|
|
|
|
severity: 'info',
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return getUser(newUserId, portId);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function updateUser(
|
|
|
|
|
userId: string,
|
|
|
|
|
portId: string,
|
|
|
|
|
data: UpdateUserInput,
|
|
|
|
|
meta: AuditMeta,
|
|
|
|
|
) {
|
|
|
|
|
const profile = await db.query.userProfiles.findFirst({
|
|
|
|
|
where: eq(userProfiles.userId, userId),
|
|
|
|
|
});
|
|
|
|
|
if (!profile) throw new NotFoundError('User');
|
|
|
|
|
|
|
|
|
|
const portRole = await db.query.userPortRoles.findFirst({
|
|
|
|
|
where: and(eq(userPortRoles.userId, userId), eq(userPortRoles.portId, portId)),
|
|
|
|
|
});
|
|
|
|
|
if (!portRole) throw new NotFoundError('User not assigned to this port');
|
|
|
|
|
|
|
|
|
|
// Update profile fields
|
|
|
|
|
const profileUpdates: Record<string, unknown> = { updatedAt: new Date() };
|
|
|
|
|
if (data.displayName !== undefined) profileUpdates.displayName = data.displayName;
|
|
|
|
|
if (data.phone !== undefined) profileUpdates.phone = data.phone;
|
|
|
|
|
if (data.isActive !== undefined) profileUpdates.isActive = data.isActive;
|
|
|
|
|
|
|
|
|
|
if (Object.keys(profileUpdates).length > 1) {
|
|
|
|
|
await db.update(userProfiles).set(profileUpdates).where(eq(userProfiles.userId, userId));
|
|
|
|
|
}
|
|
|
|
|
|
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
|
|
|
// Update role assignment + per-user toggles
|
|
|
|
|
const portRoleUpdates: Record<string, unknown> = {};
|
2026-04-08 15:47:11 -04:00
|
|
|
if (data.roleId && data.roleId !== portRole.roleId) {
|
|
|
|
|
const newRole = await db.query.roles.findFirst({
|
|
|
|
|
where: eq(roles.id, data.roleId),
|
|
|
|
|
});
|
|
|
|
|
if (!newRole) throw new ValidationError('Invalid role ID');
|
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
|
|
|
portRoleUpdates.roleId = data.roleId;
|
|
|
|
|
portRoleUpdates.assignedBy = meta.userId;
|
|
|
|
|
}
|
|
|
|
|
if (
|
|
|
|
|
data.residentialAccess !== undefined &&
|
|
|
|
|
data.residentialAccess !== portRole.residentialAccess
|
|
|
|
|
) {
|
|
|
|
|
portRoleUpdates.residentialAccess = data.residentialAccess;
|
|
|
|
|
}
|
|
|
|
|
if (Object.keys(portRoleUpdates).length > 0) {
|
2026-04-08 15:47:11 -04:00
|
|
|
await db
|
|
|
|
|
.update(userPortRoles)
|
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
|
|
|
.set(portRoleUpdates)
|
2026-04-08 15:47:11 -04:00
|
|
|
.where(and(eq(userPortRoles.userId, userId), eq(userPortRoles.portId, portId)));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void createAuditLog({
|
|
|
|
|
userId: meta.userId,
|
|
|
|
|
portId,
|
|
|
|
|
action: 'update',
|
|
|
|
|
entityType: 'user',
|
|
|
|
|
entityId: userId,
|
|
|
|
|
oldValue: {
|
|
|
|
|
displayName: profile.displayName,
|
|
|
|
|
isActive: profile.isActive,
|
|
|
|
|
roleId: portRole.roleId,
|
|
|
|
|
},
|
|
|
|
|
newValue: data,
|
|
|
|
|
ipAddress: meta.ipAddress,
|
|
|
|
|
userAgent: meta.userAgent,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
emitToRoom(`port:${portId}`, 'system:alert', {
|
|
|
|
|
alertType: 'user:updated',
|
|
|
|
|
message: `User "${data.displayName ?? profile.displayName}" updated`,
|
|
|
|
|
severity: 'info',
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return getUser(userId, portId);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function removeUserFromPort(userId: string, portId: string, meta: AuditMeta) {
|
|
|
|
|
const portRole = await db.query.userPortRoles.findFirst({
|
|
|
|
|
where: and(eq(userPortRoles.userId, userId), eq(userPortRoles.portId, portId)),
|
|
|
|
|
});
|
|
|
|
|
if (!portRole) throw new NotFoundError('User not assigned to this port');
|
|
|
|
|
|
|
|
|
|
// Prevent removing yourself
|
|
|
|
|
if (userId === meta.userId) {
|
|
|
|
|
throw new ValidationError('Cannot remove yourself from the port');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await db
|
|
|
|
|
.delete(userPortRoles)
|
|
|
|
|
.where(and(eq(userPortRoles.userId, userId), eq(userPortRoles.portId, portId)));
|
|
|
|
|
|
|
|
|
|
const profile = await db.query.userProfiles.findFirst({
|
|
|
|
|
where: eq(userProfiles.userId, userId),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
void createAuditLog({
|
|
|
|
|
userId: meta.userId,
|
|
|
|
|
portId,
|
|
|
|
|
action: 'delete',
|
|
|
|
|
entityType: 'user',
|
|
|
|
|
entityId: userId,
|
|
|
|
|
oldValue: { displayName: profile?.displayName, roleId: portRole.roleId },
|
|
|
|
|
ipAddress: meta.ipAddress,
|
|
|
|
|
userAgent: meta.userAgent,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
emitToRoom(`port:${portId}`, 'system:alert', {
|
|
|
|
|
alertType: 'user:removed',
|
|
|
|
|
message: `User "${profile?.displayName}" removed from port`,
|
|
|
|
|
severity: 'info',
|
|
|
|
|
});
|
|
|
|
|
}
|