2026-05-12 21:32:19 +02:00
|
|
|
import pLimit from 'p-limit';
|
Initial commit: Port Nimara CRM (Layers 0-4)
Full CRM rebuild with Next.js 15, TypeScript, Tailwind, Drizzle ORM,
PostgreSQL, Redis, BullMQ, MinIO, and Socket.io. Includes 461 source
files covering clients, berths, interests/pipeline, documents/EOI,
expenses/invoices, email, notifications, dashboard, admin, and
client portal. CI/CD via Gitea Actions with Docker builds.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 11:52:51 +01:00
|
|
|
import { and, eq, count } from 'drizzle-orm';
|
|
|
|
|
|
|
|
|
|
import { db } from '@/lib/db';
|
|
|
|
|
import { customFieldDefinitions, customFieldValues } from '@/lib/db/schema/system';
|
2026-04-29 01:58:42 +02:00
|
|
|
import { createAuditLog, type AuditMeta } from '@/lib/audit';
|
fix(audit-tier-2): error-surface hygiene — toastError + CodedError sweep
Two mechanical sweeps closing the audit's HIGH §16 + MED §11 findings:
* 38 client components / 56 toast.error sites converted to
toastError(err) so the new admin error inspector becomes usable from
user-reported issues — every failed inline-edit, save, send, archive,
upload, etc. now carries the request-id + error-code (Copy ID action).
* 26 service files / 62 bare-Error throws converted to CodedError or
the existing AppError subclasses. Adds new error codes:
DOCUMENSO_UPSTREAM_ERROR (502), DOCUMENSO_AUTH_FAILURE (502),
DOCUMENSO_TIMEOUT (504), OCR_UPSTREAM_ERROR (502),
IMAP_UPSTREAM_ERROR (502), UMAMI_UPSTREAM_ERROR (502),
UMAMI_NOT_CONFIGURED (409), and INSERT_RETURNING_EMPTY (500) for
post-insert returning-empty guards.
* Five vitest assertions updated to match the new user-facing wording
(client-merge "already been merged", expense/interest "couldn't find
that …", documenso "signing service didn't respond").
Test status: 1168/1168 vitest, tsc clean.
Refs: docs/audit-comprehensive-2026-05-05.md HIGH §16 (auditor-H Issue 1)
+ MED §11 (auditor-G Issue 1).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 20:18:05 +02:00
|
|
|
import { CodedError, NotFoundError, ValidationError, ConflictError } from '@/lib/errors';
|
Initial commit: Port Nimara CRM (Layers 0-4)
Full CRM rebuild with Next.js 15, TypeScript, Tailwind, Drizzle ORM,
PostgreSQL, Redis, BullMQ, MinIO, and Socket.io. Includes 461 source
files covering clients, berths, interests/pipeline, documents/EOI,
expenses/invoices, email, notifications, dashboard, admin, and
client portal. CI/CD via Gitea Actions with Docker builds.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 11:52:51 +01:00
|
|
|
import type { CreateFieldInput, UpdateFieldInput } from '@/lib/validators/custom-fields';
|
|
|
|
|
import type { CustomFieldDefinition } from '@/lib/db/schema/system';
|
|
|
|
|
|
|
|
|
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
// ─── Value Validation ─────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
function validateCustomFieldValue(
|
|
|
|
|
definition: CustomFieldDefinition,
|
|
|
|
|
value: unknown,
|
|
|
|
|
): string | null {
|
|
|
|
|
if (value === null || value === undefined) {
|
|
|
|
|
return definition.isRequired ? 'This field is required' : null;
|
|
|
|
|
}
|
|
|
|
|
switch (definition.fieldType) {
|
|
|
|
|
case 'text':
|
|
|
|
|
return typeof value !== 'string'
|
|
|
|
|
? 'Must be text'
|
|
|
|
|
: value.length > 1000
|
|
|
|
|
? 'Max 1000 chars'
|
|
|
|
|
: null;
|
|
|
|
|
case 'number':
|
|
|
|
|
return typeof value !== 'number' || isNaN(value) ? 'Must be a number' : null;
|
|
|
|
|
case 'date':
|
2026-04-29 01:58:42 +02:00
|
|
|
return typeof value !== 'string' || isNaN(Date.parse(value)) ? 'Must be a valid date' : null;
|
Initial commit: Port Nimara CRM (Layers 0-4)
Full CRM rebuild with Next.js 15, TypeScript, Tailwind, Drizzle ORM,
PostgreSQL, Redis, BullMQ, MinIO, and Socket.io. Includes 461 source
files covering clients, berths, interests/pipeline, documents/EOI,
expenses/invoices, email, notifications, dashboard, admin, and
client portal. CI/CD via Gitea Actions with Docker builds.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 11:52:51 +01:00
|
|
|
case 'boolean':
|
|
|
|
|
return typeof value !== 'boolean' ? 'Must be true or false' : null;
|
|
|
|
|
case 'select': {
|
|
|
|
|
const options = (definition.selectOptions as string[] | null) ?? [];
|
2026-04-29 01:58:42 +02:00
|
|
|
return !options.includes(value as string) ? `Must be one of: ${options.join(', ')}` : null;
|
Initial commit: Port Nimara CRM (Layers 0-4)
Full CRM rebuild with Next.js 15, TypeScript, Tailwind, Drizzle ORM,
PostgreSQL, Redis, BullMQ, MinIO, and Socket.io. Includes 461 source
files covering clients, berths, interests/pipeline, documents/EOI,
expenses/invoices, email, notifications, dashboard, admin, and
client portal. CI/CD via Gitea Actions with Docker builds.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 11:52:51 +01:00
|
|
|
}
|
|
|
|
|
default:
|
|
|
|
|
return 'Unknown field type';
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ─── Definitions ──────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
export async function listDefinitions(portId: string, entityType?: string) {
|
|
|
|
|
const conditions = [eq(customFieldDefinitions.portId, portId)];
|
|
|
|
|
if (entityType) {
|
|
|
|
|
conditions.push(eq(customFieldDefinitions.entityType, entityType));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return db.query.customFieldDefinitions.findMany({
|
|
|
|
|
where: and(...conditions),
|
|
|
|
|
orderBy: (fields, { asc }) => [asc(fields.sortOrder), asc(fields.createdAt)],
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function createDefinition(
|
|
|
|
|
portId: string,
|
|
|
|
|
userId: string,
|
|
|
|
|
data: CreateFieldInput,
|
|
|
|
|
meta: AuditMeta,
|
|
|
|
|
) {
|
|
|
|
|
// Check for duplicate fieldName within portId + entityType
|
|
|
|
|
const existing = await db.query.customFieldDefinitions.findFirst({
|
|
|
|
|
where: and(
|
|
|
|
|
eq(customFieldDefinitions.portId, portId),
|
|
|
|
|
eq(customFieldDefinitions.entityType, data.entityType),
|
|
|
|
|
eq(customFieldDefinitions.fieldName, data.fieldName),
|
|
|
|
|
),
|
|
|
|
|
});
|
|
|
|
|
if (existing) {
|
|
|
|
|
throw new ConflictError(
|
|
|
|
|
`A custom field named "${data.fieldName}" already exists for ${data.entityType}`,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const rows = await db
|
|
|
|
|
.insert(customFieldDefinitions)
|
|
|
|
|
.values({
|
|
|
|
|
portId,
|
|
|
|
|
entityType: data.entityType,
|
|
|
|
|
fieldName: data.fieldName,
|
|
|
|
|
fieldLabel: data.fieldLabel,
|
|
|
|
|
fieldType: data.fieldType,
|
|
|
|
|
selectOptions: data.selectOptions ?? null,
|
|
|
|
|
isRequired: data.isRequired,
|
|
|
|
|
sortOrder: data.sortOrder,
|
|
|
|
|
})
|
|
|
|
|
.returning();
|
|
|
|
|
|
|
|
|
|
const created = rows[0];
|
fix(audit-tier-2): error-surface hygiene — toastError + CodedError sweep
Two mechanical sweeps closing the audit's HIGH §16 + MED §11 findings:
* 38 client components / 56 toast.error sites converted to
toastError(err) so the new admin error inspector becomes usable from
user-reported issues — every failed inline-edit, save, send, archive,
upload, etc. now carries the request-id + error-code (Copy ID action).
* 26 service files / 62 bare-Error throws converted to CodedError or
the existing AppError subclasses. Adds new error codes:
DOCUMENSO_UPSTREAM_ERROR (502), DOCUMENSO_AUTH_FAILURE (502),
DOCUMENSO_TIMEOUT (504), OCR_UPSTREAM_ERROR (502),
IMAP_UPSTREAM_ERROR (502), UMAMI_UPSTREAM_ERROR (502),
UMAMI_NOT_CONFIGURED (409), and INSERT_RETURNING_EMPTY (500) for
post-insert returning-empty guards.
* Five vitest assertions updated to match the new user-facing wording
(client-merge "already been merged", expense/interest "couldn't find
that …", documenso "signing service didn't respond").
Test status: 1168/1168 vitest, tsc clean.
Refs: docs/audit-comprehensive-2026-05-05.md HIGH §16 (auditor-H Issue 1)
+ MED §11 (auditor-G Issue 1).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 20:18:05 +02:00
|
|
|
if (!created)
|
|
|
|
|
throw new CodedError('INSERT_RETURNING_EMPTY', {
|
|
|
|
|
internalMessage: 'Custom field definition insert returned no row',
|
|
|
|
|
});
|
Initial commit: Port Nimara CRM (Layers 0-4)
Full CRM rebuild with Next.js 15, TypeScript, Tailwind, Drizzle ORM,
PostgreSQL, Redis, BullMQ, MinIO, and Socket.io. Includes 461 source
files covering clients, berths, interests/pipeline, documents/EOI,
expenses/invoices, email, notifications, dashboard, admin, and
client portal. CI/CD via Gitea Actions with Docker builds.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 11:52:51 +01:00
|
|
|
|
|
|
|
|
void createAuditLog({
|
|
|
|
|
userId,
|
|
|
|
|
portId,
|
|
|
|
|
action: 'create',
|
|
|
|
|
entityType: 'custom_field_definition',
|
|
|
|
|
entityId: created.id,
|
|
|
|
|
newValue: {
|
|
|
|
|
fieldName: created.fieldName,
|
|
|
|
|
fieldLabel: created.fieldLabel,
|
|
|
|
|
fieldType: created.fieldType,
|
|
|
|
|
entityType: created.entityType,
|
|
|
|
|
},
|
|
|
|
|
ipAddress: meta.ipAddress,
|
|
|
|
|
userAgent: meta.userAgent,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return created;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function updateDefinition(
|
|
|
|
|
portId: string,
|
|
|
|
|
fieldId: string,
|
|
|
|
|
userId: string,
|
|
|
|
|
data: UpdateFieldInput & { fieldType?: unknown },
|
|
|
|
|
meta: AuditMeta,
|
|
|
|
|
) {
|
2026-05-04 22:57:01 +02:00
|
|
|
// Immutability guard - fieldType must never change
|
Initial commit: Port Nimara CRM (Layers 0-4)
Full CRM rebuild with Next.js 15, TypeScript, Tailwind, Drizzle ORM,
PostgreSQL, Redis, BullMQ, MinIO, and Socket.io. Includes 461 source
files covering clients, berths, interests/pipeline, documents/EOI,
expenses/invoices, email, notifications, dashboard, admin, and
client portal. CI/CD via Gitea Actions with Docker builds.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 11:52:51 +01:00
|
|
|
if ('fieldType' in data && data.fieldType !== undefined) {
|
|
|
|
|
throw new ValidationError('Field type cannot be changed after creation');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const existing = await db.query.customFieldDefinitions.findFirst({
|
2026-04-29 01:58:42 +02:00
|
|
|
where: and(eq(customFieldDefinitions.id, fieldId), eq(customFieldDefinitions.portId, portId)),
|
Initial commit: Port Nimara CRM (Layers 0-4)
Full CRM rebuild with Next.js 15, TypeScript, Tailwind, Drizzle ORM,
PostgreSQL, Redis, BullMQ, MinIO, and Socket.io. Includes 461 source
files covering clients, berths, interests/pipeline, documents/EOI,
expenses/invoices, email, notifications, dashboard, admin, and
client portal. CI/CD via Gitea Actions with Docker builds.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 11:52:51 +01:00
|
|
|
});
|
|
|
|
|
if (!existing) {
|
|
|
|
|
throw new NotFoundError('Custom field definition');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const updateRows = await db
|
|
|
|
|
.update(customFieldDefinitions)
|
|
|
|
|
.set({
|
|
|
|
|
...(data.fieldLabel !== undefined && { fieldLabel: data.fieldLabel }),
|
|
|
|
|
...(data.selectOptions !== undefined && { selectOptions: data.selectOptions }),
|
|
|
|
|
...(data.isRequired !== undefined && { isRequired: data.isRequired }),
|
|
|
|
|
...(data.sortOrder !== undefined && { sortOrder: data.sortOrder }),
|
|
|
|
|
})
|
fix(audit): comprehensive 2026-05-15 audit fix wave + Documenso v2 polish
Bundles the prior session's 50-task fix sweep (Documenso v2 + EOI/signing-
progress redesign + env-to-admin migration + dev-mode banner) with the
2026-05-18 audit fix wave (3 CRITICAL, 14 HIGH, 28 MEDIUM, 6 LOW).
CRITICAL (3):
- C-01 interest-berths INNER JOIN -> LEFT JOIN so hard-deleted berths
no longer silently drop interest links
- C-02 /setup added to PUBLIC_PATHS; fresh-deploy bootstrap loop fixed
- C-03 generic PATCH /interests/[id] no longer accepts pipelineStage —
callers must go through /stage with the override-guard chain
HIGH (14/15):
- H-01 explicit ON DELETE on previously-implicit NO ACTION FKs across
interests/documents/reservations/reminders/invoices (migration 0070)
- H-02 login page reads ?redirect= param with same-origin guard
- H-03 CRM invite token moves to URL fragment so it never lands in
nginx access logs / Referer headers
- H-04 Retry-After header on sign-in-by-identifier 429 (RFC 6585 §4)
- H-05 toggleAccount writes an audit row
- H-06 upsertSetting masks any value whose key ends with _encrypted
- H-07 archiveClient cascade fires per-interest audit rows
- H-08 createSalesTransporter applies SMTP_TIMEOUTS
- H-09 AppShell stable children — viewport flip across breakpoint no
longer destroys in-progress form drafts
- H-10 portal documents page swaps Unicode glyph status icons for
Lucide CheckCircle2/XCircle/Circle + aria-labels
- H-12 list components swap alert(...) for toast.warning(...)
- H-13 5 icon-only buttons gain aria-label
- H-14 parseBody treats empty bodies as {}
- H-15 admin layout renders a 403 panel instead of silent bounce
- H-11 not applicable — mobile-search-overlay IS a mobile bottom-sheet
MEDIUM (28+):
- M-MT01-05 defense-in-depth port_id/parent-id filters on UPDATE/DELETE
WHEREs across custom-fields, notes (all 6 entity types x update +
delete), client-contacts, yacht ownerClient lookup, webhook reads
- M-D01 documents-hub realtime event-name typo (file:created -> uploaded)
- M-EM01 portal-auth emails thread through portId
- M-EM02 sendEmail accepts cc/bcc params
- M-EM04 notification_digest catalog key
- M-IN01 portal presigned download URLs use 4h TTL
- M-IN02 OpenAI client lazy-instantiated
- M-IN04 stale pdfme refs updated to pdf-lib AcroForm
- M-IN05 umami.testConnection returns tagged union
- M-L01 reservations tenure_type unified with berths
- M-L02 report-generators canonicalize stage values
- M-AU01 audit log placeholder copy fixed
- M-AU04 outcome_set / outcome_cleared distinct audit verbs
- M-NEW-2 activity feed entity name+type separator
- M-R01 portal allowlist narrowed + portal_session backstop in proxy
- M-SC02 companies archived partial index
- M-SC04 audit_logs.searchText documented as DB-managed
- M-S01 storage_s3_access_key_encrypted admin field
- M-U01 audit log empty state uses <EmptyState>
- M-U09 invoice delete dialog -> <AlertDialog>
- M-U10 toast.success on ClientForm + InterestForm create/edit
- M-U11 settings-form-card logo preview alt text
- M-U14 mobile topbar title on clients/yachts/interests/berths
- M-U15 Invoices in mobile More-sheet
LOW (6/8):
- L-AU01 severity defaults for security-relevant verbs
- L-AU02 +13 missing actions in admin audit filter
- L-AU03 +7 missing entity types in admin audit filter
- L-AU04 dead listAuditLogs stubbed
- L-D02 CLAUDE.md Owner-wins chain tightened
Bonus — Document detail polish (#67 partial, 3/6 deliverables):
- state-aware action button per signer
- watcher Add UI with display-name resolution
- cleanSignerName cleanup
Prior session work bundled in:
- Documenso v2 webhook + envelope-ID normalization + sequential signing
- SigningProgress UI redesign (avatars, per-signer state, timestamps)
- env->admin settings registry + RegistryDrivenForm + encrypted creds
- Embedded-signing card + Test connection + setup help
- Dev-mode EMAIL_REDIRECT_TO banner
- Pipeline rules admin page
- Sales email config card
- Audit log details Sheet
- EOI tab: Finalising badge, absolute timestamps, sequential indicator
- Notes pipeline_stage_at_creation (migration 0069)
- Documenso numeric ID dual-key webhook (migration 0068)
- Dimensions criterion copy (migration 0067)
Tests: 1374/1374 vitest pass. tsc clean. lint clean.
See docs/AUDIT-FIX-WAVE-2026-05-18.md for the full progress report and
the user-input items still pending.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 13:28:50 +02:00
|
|
|
// M-MT01: defense-in-depth port_id filter on the UPDATE WHERE.
|
|
|
|
|
// The findFirst above is the primary tenant check, but a concurrent
|
|
|
|
|
// port-swap (or a future cache-jitter path that lets the existing
|
|
|
|
|
// pointer outlive its read) would otherwise let the write land
|
|
|
|
|
// against a sibling port's row with the same id. The entry-point
|
|
|
|
|
// and the write share the same tuple identity now.
|
|
|
|
|
.where(and(eq(customFieldDefinitions.id, fieldId), eq(customFieldDefinitions.portId, portId)))
|
Initial commit: Port Nimara CRM (Layers 0-4)
Full CRM rebuild with Next.js 15, TypeScript, Tailwind, Drizzle ORM,
PostgreSQL, Redis, BullMQ, MinIO, and Socket.io. Includes 461 source
files covering clients, berths, interests/pipeline, documents/EOI,
expenses/invoices, email, notifications, dashboard, admin, and
client portal. CI/CD via Gitea Actions with Docker builds.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 11:52:51 +01:00
|
|
|
.returning();
|
|
|
|
|
|
|
|
|
|
const updated = updateRows[0];
|
fix(audit-tier-2): error-surface hygiene — toastError + CodedError sweep
Two mechanical sweeps closing the audit's HIGH §16 + MED §11 findings:
* 38 client components / 56 toast.error sites converted to
toastError(err) so the new admin error inspector becomes usable from
user-reported issues — every failed inline-edit, save, send, archive,
upload, etc. now carries the request-id + error-code (Copy ID action).
* 26 service files / 62 bare-Error throws converted to CodedError or
the existing AppError subclasses. Adds new error codes:
DOCUMENSO_UPSTREAM_ERROR (502), DOCUMENSO_AUTH_FAILURE (502),
DOCUMENSO_TIMEOUT (504), OCR_UPSTREAM_ERROR (502),
IMAP_UPSTREAM_ERROR (502), UMAMI_UPSTREAM_ERROR (502),
UMAMI_NOT_CONFIGURED (409), and INSERT_RETURNING_EMPTY (500) for
post-insert returning-empty guards.
* Five vitest assertions updated to match the new user-facing wording
(client-merge "already been merged", expense/interest "couldn't find
that …", documenso "signing service didn't respond").
Test status: 1168/1168 vitest, tsc clean.
Refs: docs/audit-comprehensive-2026-05-05.md HIGH §16 (auditor-H Issue 1)
+ MED §11 (auditor-G Issue 1).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 20:18:05 +02:00
|
|
|
if (!updated)
|
|
|
|
|
throw new CodedError('INSERT_RETURNING_EMPTY', {
|
|
|
|
|
internalMessage: 'Custom field definition update returned no row',
|
|
|
|
|
});
|
Initial commit: Port Nimara CRM (Layers 0-4)
Full CRM rebuild with Next.js 15, TypeScript, Tailwind, Drizzle ORM,
PostgreSQL, Redis, BullMQ, MinIO, and Socket.io. Includes 461 source
files covering clients, berths, interests/pipeline, documents/EOI,
expenses/invoices, email, notifications, dashboard, admin, and
client portal. CI/CD via Gitea Actions with Docker builds.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 11:52:51 +01:00
|
|
|
|
|
|
|
|
void createAuditLog({
|
|
|
|
|
userId,
|
|
|
|
|
portId,
|
|
|
|
|
action: 'update',
|
|
|
|
|
entityType: 'custom_field_definition',
|
|
|
|
|
entityId: fieldId,
|
|
|
|
|
oldValue: {
|
|
|
|
|
fieldLabel: existing.fieldLabel,
|
|
|
|
|
selectOptions: existing.selectOptions,
|
|
|
|
|
isRequired: existing.isRequired,
|
|
|
|
|
sortOrder: existing.sortOrder,
|
|
|
|
|
},
|
|
|
|
|
newValue: {
|
|
|
|
|
fieldLabel: updated.fieldLabel,
|
|
|
|
|
selectOptions: updated.selectOptions,
|
|
|
|
|
isRequired: updated.isRequired,
|
|
|
|
|
sortOrder: updated.sortOrder,
|
|
|
|
|
},
|
|
|
|
|
ipAddress: meta.ipAddress,
|
|
|
|
|
userAgent: meta.userAgent,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return updated;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function deleteDefinition(
|
|
|
|
|
portId: string,
|
|
|
|
|
fieldId: string,
|
|
|
|
|
userId: string,
|
|
|
|
|
meta: AuditMeta,
|
|
|
|
|
) {
|
|
|
|
|
const existing = await db.query.customFieldDefinitions.findFirst({
|
2026-04-29 01:58:42 +02:00
|
|
|
where: and(eq(customFieldDefinitions.id, fieldId), eq(customFieldDefinitions.portId, portId)),
|
Initial commit: Port Nimara CRM (Layers 0-4)
Full CRM rebuild with Next.js 15, TypeScript, Tailwind, Drizzle ORM,
PostgreSQL, Redis, BullMQ, MinIO, and Socket.io. Includes 461 source
files covering clients, berths, interests/pipeline, documents/EOI,
expenses/invoices, email, notifications, dashboard, admin, and
client portal. CI/CD via Gitea Actions with Docker builds.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 11:52:51 +01:00
|
|
|
});
|
|
|
|
|
if (!existing) {
|
|
|
|
|
throw new NotFoundError('Custom field definition');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Count associated values before deletion
|
|
|
|
|
const countResult = await db
|
|
|
|
|
.select({ count: count() })
|
|
|
|
|
.from(customFieldValues)
|
|
|
|
|
.where(eq(customFieldValues.fieldId, fieldId));
|
|
|
|
|
const valueCount = countResult[0]?.count ?? 0;
|
|
|
|
|
|
2026-05-04 22:57:01 +02:00
|
|
|
// Delete definition - CASCADE handles values
|
2026-04-29 01:58:42 +02:00
|
|
|
await db.delete(customFieldDefinitions).where(eq(customFieldDefinitions.id, fieldId));
|
Initial commit: Port Nimara CRM (Layers 0-4)
Full CRM rebuild with Next.js 15, TypeScript, Tailwind, Drizzle ORM,
PostgreSQL, Redis, BullMQ, MinIO, and Socket.io. Includes 461 source
files covering clients, berths, interests/pipeline, documents/EOI,
expenses/invoices, email, notifications, dashboard, admin, and
client portal. CI/CD via Gitea Actions with Docker builds.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 11:52:51 +01:00
|
|
|
|
|
|
|
|
void createAuditLog({
|
|
|
|
|
userId,
|
|
|
|
|
portId,
|
|
|
|
|
action: 'delete',
|
|
|
|
|
entityType: 'custom_field_definition',
|
|
|
|
|
entityId: fieldId,
|
|
|
|
|
oldValue: {
|
|
|
|
|
fieldName: existing.fieldName,
|
|
|
|
|
fieldLabel: existing.fieldLabel,
|
|
|
|
|
fieldType: existing.fieldType,
|
|
|
|
|
entityType: existing.entityType,
|
|
|
|
|
},
|
|
|
|
|
metadata: { deletedValueCount: Number(valueCount) },
|
|
|
|
|
ipAddress: meta.ipAddress,
|
|
|
|
|
userAgent: meta.userAgent,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { deletedValueCount: Number(valueCount) };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ─── Values ───────────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
export async function getValues(entityId: string, portId: string) {
|
|
|
|
|
const definitions = await db.query.customFieldDefinitions.findMany({
|
|
|
|
|
where: eq(customFieldDefinitions.portId, portId),
|
|
|
|
|
orderBy: (fields, { asc }) => [asc(fields.sortOrder), asc(fields.createdAt)],
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const values = await db.query.customFieldValues.findMany({
|
|
|
|
|
where: eq(customFieldValues.entityId, entityId),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const valueMap = new Map(values.map((v) => [v.fieldId, v]));
|
|
|
|
|
|
|
|
|
|
return definitions.map((definition) => ({
|
|
|
|
|
definition,
|
|
|
|
|
value: valueMap.get(definition.id) ?? null,
|
|
|
|
|
}));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function setValues(
|
|
|
|
|
entityId: string,
|
|
|
|
|
portId: string,
|
|
|
|
|
userId: string,
|
|
|
|
|
values: Array<{ fieldId: string; value: unknown }>,
|
|
|
|
|
meta: AuditMeta,
|
|
|
|
|
) {
|
|
|
|
|
if (values.length === 0) return [];
|
|
|
|
|
|
|
|
|
|
// Fetch relevant definitions to validate values
|
|
|
|
|
const fieldIds = values.map((v) => v.fieldId);
|
|
|
|
|
const definitions = await db.query.customFieldDefinitions.findMany({
|
|
|
|
|
where: eq(customFieldDefinitions.portId, portId),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const definitionMap = new Map(definitions.map((d) => [d.id, d]));
|
|
|
|
|
|
|
|
|
|
// Validate each value
|
|
|
|
|
const errors: Array<{ field: string; message: string }> = [];
|
|
|
|
|
for (const { fieldId, value } of values) {
|
|
|
|
|
const definition = definitionMap.get(fieldId);
|
|
|
|
|
if (!definition) {
|
|
|
|
|
errors.push({ field: fieldId, message: 'Custom field not found for this port' });
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
const error = validateCustomFieldValue(definition, value);
|
|
|
|
|
if (error) {
|
|
|
|
|
errors.push({ field: definition.fieldName, message: error });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (errors.length > 0) {
|
|
|
|
|
throw new ValidationError('Custom field validation failed', errors);
|
|
|
|
|
}
|
|
|
|
|
|
sec: lock down 5 cross-tenant FK gaps from fifth-pass review
1. HIGH — reminders.create/updateReminder accepted clientId/interestId/
berthId from the body and persisted them with no port check; getReminder
then hydrated the row via Drizzle relations (no port filter on the
join), so a port-A user with reminders:create could exfiltrate any
port-B client/interest/berth row by guessing its UUID. New
assertReminderFksInPort gates create + update.
2. HIGH — listRecommendations(interestId, _portId) discarded portId
entirely; the route GET /api/v1/interests/[id]/recommendations
forwarded the URL id straight through. A port-A user with
interests:view could read any other tenant's recommended berths
(mooring numbers, dimensions, status). Service now verifies the
interest belongs to portId and joins berths filtered by port.
3. HIGH — Berth waiting list. The PATCH route did not pre-check that
the berth belonged to ctx.portId — a port-A user with
manage_waiting_list could reorder a port-B berth's queue. Separately,
updateWaitingList accepted arbitrary entries[].clientId and inserted
them without verifying tenancy, polluting the table with foreign-port
FKs. Both gaps closed.
4. MEDIUM — setEntityTags (clients/companies/yachts/interests/berths)
accepted any tagId and inserted into the join table. The tags table
is per-port but the join only carries a single-column FK. The
downstream getById join `tags ON join.tag_id = tags.id` has no port
filter, so a foreign tag's name + color render in the requesting port.
Helper now batch-validates tagIds belong to portId before insert.
5. MEDIUM — /api/v1/custom-fields/[entityId] PUT had no withPermission
gate (any role, including viewer, could write) and didn't validate
that the URL entityId pointed at a port-scoped entity of the field
definition's entityType. Route now uses
withPermission('clients','view'/'edit',…); service validates the
entityId per resolved entityType (client/interest/berth/yacht/company)
against portId.
Test mocks updated to cover the new entity-port-scope check.
818 vitest tests pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 03:28:31 +02:00
|
|
|
// Tenant scope: verify entityId actually points at a port-scoped row of
|
|
|
|
|
// the entity type the field definitions target. Without this gate, any
|
|
|
|
|
// authenticated user could write custom-field rows pointing at arbitrary
|
2026-05-04 22:57:01 +02:00
|
|
|
// entityIds (or none at all) - polluting customFieldValues and creating
|
sec: lock down 5 cross-tenant FK gaps from fifth-pass review
1. HIGH — reminders.create/updateReminder accepted clientId/interestId/
berthId from the body and persisted them with no port check; getReminder
then hydrated the row via Drizzle relations (no port filter on the
join), so a port-A user with reminders:create could exfiltrate any
port-B client/interest/berth row by guessing its UUID. New
assertReminderFksInPort gates create + update.
2. HIGH — listRecommendations(interestId, _portId) discarded portId
entirely; the route GET /api/v1/interests/[id]/recommendations
forwarded the URL id straight through. A port-A user with
interests:view could read any other tenant's recommended berths
(mooring numbers, dimensions, status). Service now verifies the
interest belongs to portId and joins berths filtered by port.
3. HIGH — Berth waiting list. The PATCH route did not pre-check that
the berth belonged to ctx.portId — a port-A user with
manage_waiting_list could reorder a port-B berth's queue. Separately,
updateWaitingList accepted arbitrary entries[].clientId and inserted
them without verifying tenancy, polluting the table with foreign-port
FKs. Both gaps closed.
4. MEDIUM — setEntityTags (clients/companies/yachts/interests/berths)
accepted any tagId and inserted into the join table. The tags table
is per-port but the join only carries a single-column FK. The
downstream getById join `tags ON join.tag_id = tags.id` has no port
filter, so a foreign tag's name + color render in the requesting port.
Helper now batch-validates tagIds belong to portId before insert.
5. MEDIUM — /api/v1/custom-fields/[entityId] PUT had no withPermission
gate (any role, including viewer, could write) and didn't validate
that the URL entityId pointed at a port-scoped entity of the field
definition's entityType. Route now uses
withPermission('clients','view'/'edit',…); service validates the
entityId per resolved entityType (client/interest/berth/yacht/company)
against portId.
Test mocks updated to cover the new entity-port-scope check.
818 vitest tests pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 03:28:31 +02:00
|
|
|
// a join surface that could later leak data.
|
|
|
|
|
const entityTypes = new Set(
|
|
|
|
|
values
|
|
|
|
|
.map((v) => definitionMap.get(v.fieldId)?.entityType)
|
|
|
|
|
.filter((t): t is string => Boolean(t)),
|
|
|
|
|
);
|
|
|
|
|
for (const entityType of entityTypes) {
|
|
|
|
|
const { eq: drizzleEq, and: drizzleAnd } = await import('drizzle-orm');
|
|
|
|
|
let exists = false;
|
|
|
|
|
if (entityType === 'client') {
|
|
|
|
|
const { clients } = await import('@/lib/db/schema/clients');
|
|
|
|
|
const row = await db.query.clients.findFirst({
|
|
|
|
|
where: drizzleAnd(drizzleEq(clients.id, entityId), drizzleEq(clients.portId, portId)),
|
|
|
|
|
});
|
|
|
|
|
exists = Boolean(row);
|
|
|
|
|
} else if (entityType === 'interest') {
|
|
|
|
|
const { interests } = await import('@/lib/db/schema/interests');
|
|
|
|
|
const row = await db.query.interests.findFirst({
|
|
|
|
|
where: drizzleAnd(drizzleEq(interests.id, entityId), drizzleEq(interests.portId, portId)),
|
|
|
|
|
});
|
|
|
|
|
exists = Boolean(row);
|
|
|
|
|
} else if (entityType === 'berth') {
|
|
|
|
|
const { berths } = await import('@/lib/db/schema/berths');
|
|
|
|
|
const row = await db.query.berths.findFirst({
|
|
|
|
|
where: drizzleAnd(drizzleEq(berths.id, entityId), drizzleEq(berths.portId, portId)),
|
|
|
|
|
});
|
|
|
|
|
exists = Boolean(row);
|
|
|
|
|
} else if (entityType === 'yacht') {
|
|
|
|
|
const { yachts } = await import('@/lib/db/schema/yachts');
|
|
|
|
|
const row = await db.query.yachts.findFirst({
|
|
|
|
|
where: drizzleAnd(drizzleEq(yachts.id, entityId), drizzleEq(yachts.portId, portId)),
|
|
|
|
|
});
|
|
|
|
|
exists = Boolean(row);
|
|
|
|
|
} else if (entityType === 'company') {
|
|
|
|
|
const { companies } = await import('@/lib/db/schema/companies');
|
|
|
|
|
const row = await db.query.companies.findFirst({
|
|
|
|
|
where: drizzleAnd(drizzleEq(companies.id, entityId), drizzleEq(companies.portId, portId)),
|
|
|
|
|
});
|
|
|
|
|
exists = Boolean(row);
|
|
|
|
|
} else {
|
|
|
|
|
throw new ValidationError(`Unsupported custom-field entity type: ${entityType}`);
|
|
|
|
|
}
|
|
|
|
|
if (!exists) {
|
|
|
|
|
throw new ValidationError(`${entityType} not found in this port`);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-12 21:32:19 +02:00
|
|
|
// Upsert all values with bounded concurrency. Custom-field sets are
|
|
|
|
|
// typically 5-15 fields, but a port admin could stack 50+ definitions
|
|
|
|
|
// on a single client. Cap at 8 in flight so the pg pool isn't swamped
|
|
|
|
|
// on a bulk-update fan-out.
|
|
|
|
|
const upsertLimit = pLimit(8);
|
Initial commit: Port Nimara CRM (Layers 0-4)
Full CRM rebuild with Next.js 15, TypeScript, Tailwind, Drizzle ORM,
PostgreSQL, Redis, BullMQ, MinIO, and Socket.io. Includes 461 source
files covering clients, berths, interests/pipeline, documents/EOI,
expenses/invoices, email, notifications, dashboard, admin, and
client portal. CI/CD via Gitea Actions with Docker builds.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 11:52:51 +01:00
|
|
|
const results = await Promise.all(
|
2026-05-12 21:32:19 +02:00
|
|
|
values.map(({ fieldId, value }) =>
|
|
|
|
|
upsertLimit(async () => {
|
|
|
|
|
const [upserted] = await db
|
|
|
|
|
.insert(customFieldValues)
|
|
|
|
|
.values({
|
|
|
|
|
fieldId,
|
|
|
|
|
entityId,
|
Initial commit: Port Nimara CRM (Layers 0-4)
Full CRM rebuild with Next.js 15, TypeScript, Tailwind, Drizzle ORM,
PostgreSQL, Redis, BullMQ, MinIO, and Socket.io. Includes 461 source
files covering clients, berths, interests/pipeline, documents/EOI,
expenses/invoices, email, notifications, dashboard, admin, and
client portal. CI/CD via Gitea Actions with Docker builds.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 11:52:51 +01:00
|
|
|
value: value as Record<string, unknown>,
|
|
|
|
|
updatedAt: new Date(),
|
2026-05-12 21:32:19 +02:00
|
|
|
})
|
|
|
|
|
.onConflictDoUpdate({
|
|
|
|
|
target: [customFieldValues.fieldId, customFieldValues.entityId],
|
|
|
|
|
set: {
|
|
|
|
|
value: value as Record<string, unknown>,
|
|
|
|
|
updatedAt: new Date(),
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
.returning();
|
|
|
|
|
return upserted;
|
|
|
|
|
}),
|
|
|
|
|
),
|
Initial commit: Port Nimara CRM (Layers 0-4)
Full CRM rebuild with Next.js 15, TypeScript, Tailwind, Drizzle ORM,
PostgreSQL, Redis, BullMQ, MinIO, and Socket.io. Includes 461 source
files covering clients, berths, interests/pipeline, documents/EOI,
expenses/invoices, email, notifications, dashboard, admin, and
client portal. CI/CD via Gitea Actions with Docker builds.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 11:52:51 +01:00
|
|
|
);
|
|
|
|
|
|
|
|
|
|
void createAuditLog({
|
|
|
|
|
userId,
|
|
|
|
|
portId,
|
|
|
|
|
action: 'update',
|
|
|
|
|
entityType: 'custom_field_values',
|
|
|
|
|
entityId,
|
|
|
|
|
metadata: { fieldIds, updatedCount: results.length },
|
|
|
|
|
ipAddress: meta.ipAddress,
|
|
|
|
|
userAgent: meta.userAgent,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return results;
|
|
|
|
|
}
|