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>
This commit is contained in:
@@ -4,6 +4,7 @@ import { db } from '@/lib/db';
|
||||
import { clients } from '@/lib/db/schema/clients';
|
||||
import { ports } from '@/lib/db/schema/ports';
|
||||
import { portalAuthTokens, portalUsers } from '@/lib/db/schema/portal';
|
||||
import { systemSettings } from '@/lib/db/schema/system';
|
||||
import { env } from '@/lib/env';
|
||||
import { sendEmail } from '@/lib/email';
|
||||
import { activationEmail, resetEmail } from '@/lib/email/templates/portal-auth';
|
||||
@@ -15,6 +16,19 @@ import { hashPassword, hashToken, mintToken, verifyPassword } from '@/lib/portal
|
||||
const ACTIVATION_TOKEN_TTL_HOURS = 72;
|
||||
const RESET_TOKEN_TTL_MINUTES = 30;
|
||||
const MIN_PASSWORD_LENGTH = 9;
|
||||
const PORTAL_ENABLED_KEY = 'client_portal_enabled';
|
||||
|
||||
/**
|
||||
* Per-port toggle for the client portal feature. Default-on so existing
|
||||
* deployments behave the way they did before this setting existed.
|
||||
*/
|
||||
export async function isPortalEnabledForPort(portId: string): Promise<boolean> {
|
||||
const row = await db.query.systemSettings.findFirst({
|
||||
where: and(eq(systemSettings.key, PORTAL_ENABLED_KEY), eq(systemSettings.portId, portId)),
|
||||
});
|
||||
if (!row) return true;
|
||||
return row.value === true || row.value === 'true';
|
||||
}
|
||||
|
||||
// ─── Admin-side: invite a client to the portal ───────────────────────────────
|
||||
|
||||
@@ -32,6 +46,10 @@ export async function createPortalUser(args: {
|
||||
});
|
||||
if (!client) throw new NotFoundError('Client');
|
||||
|
||||
if (!(await isPortalEnabledForPort(args.portId))) {
|
||||
throw new ConflictError('Client portal is disabled for this port');
|
||||
}
|
||||
|
||||
// Email uniqueness check is enforced at the DB level too, but we do a
|
||||
// friendlier preflight so the admin sees a clear conflict error.
|
||||
const existing = await db.query.portalUsers.findFirst({
|
||||
@@ -96,6 +114,9 @@ async function issueActivationToken(
|
||||
}
|
||||
|
||||
export async function resendActivation(portalUserId: string, portId: string): Promise<void> {
|
||||
if (!(await isPortalEnabledForPort(portId))) {
|
||||
throw new ConflictError('Client portal is disabled for this port');
|
||||
}
|
||||
const user = await db.query.portalUsers.findFirst({
|
||||
where: and(eq(portalUsers.id, portalUserId), eq(portalUsers.portId, portId)),
|
||||
});
|
||||
@@ -113,6 +134,13 @@ export async function activateAccount(rawToken: string, password: string): Promi
|
||||
throw new ValidationError(`Password must be at least ${MIN_PASSWORD_LENGTH} characters`);
|
||||
}
|
||||
const tokenRow = await consumeToken(rawToken, 'activation');
|
||||
const portalUser = await db.query.portalUsers.findFirst({
|
||||
where: eq(portalUsers.id, tokenRow.portalUserId),
|
||||
});
|
||||
if (!portalUser) throw new ValidationError('Invalid or expired token');
|
||||
if (!(await isPortalEnabledForPort(portalUser.portId))) {
|
||||
throw new ValidationError('Client portal is disabled for this port');
|
||||
}
|
||||
const passwordHash = await hashPassword(password);
|
||||
await db
|
||||
.update(portalUsers)
|
||||
@@ -147,6 +175,13 @@ export async function signIn(args: {
|
||||
throw new UnauthorizedError('Invalid email or password');
|
||||
}
|
||||
|
||||
// Disabled-port check happens AFTER the credential check so that a wrong
|
||||
// password on a disabled-port account still surfaces "invalid email or
|
||||
// password" — we never leak which ports have the portal turned off.
|
||||
if (!(await isPortalEnabledForPort(user.portId))) {
|
||||
throw new UnauthorizedError('Invalid email or password');
|
||||
}
|
||||
|
||||
const token = await createPortalToken({
|
||||
clientId: user.clientId,
|
||||
portId: user.portId,
|
||||
@@ -174,6 +209,13 @@ export async function requestPasswordReset(email: string): Promise<void> {
|
||||
return;
|
||||
}
|
||||
|
||||
// Same silent no-op when the port has the portal disabled — keeps the
|
||||
// disabled-state from leaking through the public reset endpoint.
|
||||
if (!(await isPortalEnabledForPort(user.portId))) {
|
||||
logger.debug({ portId: user.portId }, 'Password reset on disabled-portal port');
|
||||
return;
|
||||
}
|
||||
|
||||
const { raw, hash } = mintToken();
|
||||
const expiresAt = new Date(Date.now() + RESET_TOKEN_TTL_MINUTES * 60 * 1000);
|
||||
|
||||
@@ -206,6 +248,13 @@ export async function resetPassword(rawToken: string, password: string): Promise
|
||||
throw new ValidationError(`Password must be at least ${MIN_PASSWORD_LENGTH} characters`);
|
||||
}
|
||||
const tokenRow = await consumeToken(rawToken, 'reset');
|
||||
const portalUser = await db.query.portalUsers.findFirst({
|
||||
where: eq(portalUsers.id, tokenRow.portalUserId),
|
||||
});
|
||||
if (!portalUser) throw new ValidationError('Invalid or expired token');
|
||||
if (!(await isPortalEnabledForPort(portalUser.portId))) {
|
||||
throw new ValidationError('Client portal is disabled for this port');
|
||||
}
|
||||
const passwordHash = await hashPassword(password);
|
||||
await db
|
||||
.update(portalUsers)
|
||||
|
||||
Reference in New Issue
Block a user