2026-05-11 12:02:33 +02:00
|
|
|
import { and, arrayContains, desc, eq, inArray, isNull, or, sql } from 'drizzle-orm';
|
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 { db } from '@/lib/db';
|
|
|
|
|
import { files, documents } from '@/lib/db/schema/documents';
|
|
|
|
|
import { expenses } from '@/lib/db/schema/financial';
|
|
|
|
|
import { berthMaintenanceLog } from '@/lib/db/schema/berths';
|
2026-04-29 01:58:42 +02:00
|
|
|
import { createAuditLog, type AuditMeta } from '@/lib/audit';
|
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 { ConflictError, NotFoundError, ValidationError } from '@/lib/errors';
|
|
|
|
|
import { emitToRoom } from '@/lib/socket/server';
|
fix(storage): route every file op through getStorageBackend()
Removes 12 direct minioClient.{put,get,remove}Object call sites that
bypassed the pluggable storage abstraction. Filesystem-mode deploys
(MULTI_NODE_DEPLOYMENT=false, storage_backend=filesystem) silently
broke at every site: GDPR export, invoice PDF, EOI generation, portal
download, file upload, folder create/rename/delete, signed PDF land,
maintenance cleanup, etc. Each site now resolves the active backend
and uses its put/get/delete + the new presignDownloadUrl() helper.
Folder marker objects in /files/folders/* keep the same on-the-wire
shape but route through the backend. A future refactor should move
folder bookkeeping to a DB-backed virtual-folder table (see audit
HIGH §3 follow-up note in the route file).
Sites left untouched: src/lib/services/system-monitoring.service.ts
and src/app/api/ready/route.ts use minioClient.bucketExists as an S3-
specific health probe — those are correctly mode-aware and stay.
Refs: docs/audit-comprehensive-2026-05-05.md HIGH §3 (auditor-D Issue 1)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 18:41:02 +02:00
|
|
|
import { getStorageBackend, presignDownloadUrl } from '@/lib/storage';
|
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 { buildListQuery } from '@/lib/db/query-builder';
|
|
|
|
|
import { env } from '@/lib/env';
|
|
|
|
|
import {
|
|
|
|
|
ALLOWED_MIME_TYPES,
|
|
|
|
|
MAX_FILE_SIZE,
|
|
|
|
|
PREVIEWABLE_MIMES,
|
fix(audit-tier-6): validation, perms, ops/infra, per-port webhook secret
Final audit polish — closes the remaining LOW + MED items the previous
tiers didn't reach:
* Validation hardening: me.preferences uses .strict() + 8KB cap
instead of unbounded .passthrough(); files.uploadFile gains
magic-byte verification (jpeg/png/gif/webp/pdf/doc/xlsx); OCR scan
endpoint enforces 10MB cap + magic-byte check on receipt images;
port logoUrl + me.avatarUrl reject javascript:/data: schemes via
a shared httpUrl refinement.
* Permission gates: document-sends/{brochure,berth-pdf} now require
email.send (was withAuth-only); document-sends/{preview,list} on
email.view; ai/email-draft on email.send; documents/[id]/send
uses send_for_signing (was create); expenses/export/parent-company
flips from hard isSuperAdmin to expenses.export for parity;
admin/users/options gated on reminders.assign_others (was withAuth).
* Envelope hygiene: auth/set-password switches the third {message}
variant to errorResponse + {data: {email}}; ai/email-draft wraps
jobId in {data: {jobId}}.
* UI polish: reports-list.handleDownload surfaces failures via
toastError (was console-only).
* Ops/infra: pin pnpm@10.33.2 across all three Dockerfiles +
packageManager field in package.json; Dockerfile.worker re-orders
user creation BEFORE pnpm install so node_modules / .cache dirs
are worker-owned (fixes tesseract.js + sharp EACCES at first PDF
parse); add Redis-ping HEALTHCHECK to the worker container.
* Public health endpoint: returns full env+appUrl payload only when
the caller presents X-Intake-Secret, otherwise a minimal {status}
so generic uptime monitors still work but anonymous internet
doesn't get deployment fingerprints.
* Per-port Documenso webhook secret: new system_settings key
+ listDocumensoWebhookSecrets() helper. The webhook receiver
iterates every configured per-port secret with timing-safe
comparison + falls back to env, then forwards the resolved portId
into handleDocumentExpired so two ports sharing a documensoId
cannot cross-mutate.
Deferred (handled in dedicated follow-up PRs):
* Tier 5.1 — direct service tests for portal-auth / users /
email-accounts / document-sends / sales-email-config. MED, large
test-writing scope.
* The {ok: true} → {data: null} envelope migration across
alerts/expenses/admin-ocr-settings/storage routes. Mechanical but
needs coordinated client + test updates.
* CSP-nonce migration (drop unsafe-inline) — needs middleware-level
nonce generation that the Next 15 router has to thread through.
* Idempotency-Key header on Documenso createDocument. Requires
schema column on documents to persist the key; deferred so it
doesn't bundle a migration into this commit.
* The 16 better-auth user_id FKs — separate dedicated migration
with care (some columns are NOT NULL today and cascade decisions
matter).
* PermissionGate / Skeleton / EmptyState wraps across 5 admin lists
(auditor-H §§36–37) and the residential-clients filter bar.
Test status: 1175/1175 vitest, tsc clean.
Refs: docs/audit-comprehensive-2026-05-05.md MED §§28,29,30 + LOW §§32–43
+ HIGH §9 (Documenso secrets follow-up).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 21:03:31 +02:00
|
|
|
bufferMatchesMime,
|
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
|
|
|
} from '@/lib/constants/file-validation';
|
|
|
|
|
import { generateStorageKey, sanitizeFilename } from '@/lib/services/storage';
|
|
|
|
|
import type { UploadFileInput, UpdateFileInput, ListFilesInput } from '@/lib/validators/files';
|
2026-05-11 11:54:23 +02:00
|
|
|
import { documentFolders } from '@/lib/db/schema/documents';
|
|
|
|
|
import { clients } from '@/lib/db/schema/clients';
|
|
|
|
|
import { companies, companyMemberships } from '@/lib/db/schema/companies';
|
|
|
|
|
import { yachts } from '@/lib/db/schema/yachts';
|
|
|
|
|
import type { EntityType } from '@/lib/services/document-folders.service';
|
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
|
|
|
|
|
|
|
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
interface UploadFileParams {
|
|
|
|
|
buffer: Buffer;
|
|
|
|
|
originalName: string;
|
|
|
|
|
mimeType: string;
|
|
|
|
|
size: number;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ─── Upload ───────────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
export async function uploadFile(
|
|
|
|
|
portId: string,
|
|
|
|
|
portSlug: string,
|
|
|
|
|
file: UploadFileParams,
|
|
|
|
|
data: UploadFileInput,
|
|
|
|
|
meta: AuditMeta,
|
|
|
|
|
) {
|
|
|
|
|
if (!ALLOWED_MIME_TYPES.has(file.mimeType)) {
|
|
|
|
|
throw new ValidationError(`File type '${file.mimeType}' is not allowed`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (file.size > MAX_FILE_SIZE) {
|
|
|
|
|
throw new ValidationError('File exceeds maximum size of 50MB');
|
|
|
|
|
}
|
|
|
|
|
|
fix(audit-tier-6): validation, perms, ops/infra, per-port webhook secret
Final audit polish — closes the remaining LOW + MED items the previous
tiers didn't reach:
* Validation hardening: me.preferences uses .strict() + 8KB cap
instead of unbounded .passthrough(); files.uploadFile gains
magic-byte verification (jpeg/png/gif/webp/pdf/doc/xlsx); OCR scan
endpoint enforces 10MB cap + magic-byte check on receipt images;
port logoUrl + me.avatarUrl reject javascript:/data: schemes via
a shared httpUrl refinement.
* Permission gates: document-sends/{brochure,berth-pdf} now require
email.send (was withAuth-only); document-sends/{preview,list} on
email.view; ai/email-draft on email.send; documents/[id]/send
uses send_for_signing (was create); expenses/export/parent-company
flips from hard isSuperAdmin to expenses.export for parity;
admin/users/options gated on reminders.assign_others (was withAuth).
* Envelope hygiene: auth/set-password switches the third {message}
variant to errorResponse + {data: {email}}; ai/email-draft wraps
jobId in {data: {jobId}}.
* UI polish: reports-list.handleDownload surfaces failures via
toastError (was console-only).
* Ops/infra: pin pnpm@10.33.2 across all three Dockerfiles +
packageManager field in package.json; Dockerfile.worker re-orders
user creation BEFORE pnpm install so node_modules / .cache dirs
are worker-owned (fixes tesseract.js + sharp EACCES at first PDF
parse); add Redis-ping HEALTHCHECK to the worker container.
* Public health endpoint: returns full env+appUrl payload only when
the caller presents X-Intake-Secret, otherwise a minimal {status}
so generic uptime monitors still work but anonymous internet
doesn't get deployment fingerprints.
* Per-port Documenso webhook secret: new system_settings key
+ listDocumensoWebhookSecrets() helper. The webhook receiver
iterates every configured per-port secret with timing-safe
comparison + falls back to env, then forwards the resolved portId
into handleDocumentExpired so two ports sharing a documensoId
cannot cross-mutate.
Deferred (handled in dedicated follow-up PRs):
* Tier 5.1 — direct service tests for portal-auth / users /
email-accounts / document-sends / sales-email-config. MED, large
test-writing scope.
* The {ok: true} → {data: null} envelope migration across
alerts/expenses/admin-ocr-settings/storage routes. Mechanical but
needs coordinated client + test updates.
* CSP-nonce migration (drop unsafe-inline) — needs middleware-level
nonce generation that the Next 15 router has to thread through.
* Idempotency-Key header on Documenso createDocument. Requires
schema column on documents to persist the key; deferred so it
doesn't bundle a migration into this commit.
* The 16 better-auth user_id FKs — separate dedicated migration
with care (some columns are NOT NULL today and cascade decisions
matter).
* PermissionGate / Skeleton / EmptyState wraps across 5 admin lists
(auditor-H §§36–37) and the residential-clients filter bar.
Test status: 1175/1175 vitest, tsc clean.
Refs: docs/audit-comprehensive-2026-05-05.md MED §§28,29,30 + LOW §§32–43
+ HIGH §9 (Documenso secrets follow-up).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 21:03:31 +02:00
|
|
|
// Magic-byte verification — without this, the browser-declared MIME is
|
|
|
|
|
// attacker-controlled and a malicious uploader could ship arbitrary
|
|
|
|
|
// bytes through the ALLOWED_MIME_TYPES allow-list (auditor-E3 §27).
|
|
|
|
|
// Berth-PDF and brochure paths already do this; the generic uploader
|
|
|
|
|
// matches their guarantee here.
|
|
|
|
|
if (!bufferMatchesMime(file.buffer, file.mimeType)) {
|
|
|
|
|
throw new ValidationError(`File contents do not match the declared type '${file.mimeType}'`);
|
|
|
|
|
}
|
|
|
|
|
|
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 entity = data.entityType ?? 'general';
|
|
|
|
|
const entityId = data.entityId ?? portId;
|
|
|
|
|
const storagePath = generateStorageKey(portSlug, entity, entityId, file.mimeType);
|
|
|
|
|
const sanitizedOriginal = sanitizeFilename(file.originalName);
|
|
|
|
|
const sanitizedFilename = sanitizeFilename(data.filename);
|
|
|
|
|
|
fix(storage): route every file op through getStorageBackend()
Removes 12 direct minioClient.{put,get,remove}Object call sites that
bypassed the pluggable storage abstraction. Filesystem-mode deploys
(MULTI_NODE_DEPLOYMENT=false, storage_backend=filesystem) silently
broke at every site: GDPR export, invoice PDF, EOI generation, portal
download, file upload, folder create/rename/delete, signed PDF land,
maintenance cleanup, etc. Each site now resolves the active backend
and uses its put/get/delete + the new presignDownloadUrl() helper.
Folder marker objects in /files/folders/* keep the same on-the-wire
shape but route through the backend. A future refactor should move
folder bookkeeping to a DB-backed virtual-folder table (see audit
HIGH §3 follow-up note in the route file).
Sites left untouched: src/lib/services/system-monitoring.service.ts
and src/app/api/ready/route.ts use minioClient.bucketExists as an S3-
specific health probe — those are correctly mode-aware and stay.
Refs: docs/audit-comprehensive-2026-05-05.md HIGH §3 (auditor-D Issue 1)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 18:41:02 +02:00
|
|
|
const backend = await getStorageBackend();
|
|
|
|
|
await backend.put(storagePath, file.buffer, {
|
|
|
|
|
contentType: file.mimeType,
|
|
|
|
|
sizeBytes: file.size,
|
2026-04-29 01:58:42 +02:00
|
|
|
});
|
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
|
|
|
|
2026-05-11 11:54:23 +02:00
|
|
|
// E8: auto-set entity FK from system-managed folder when the rep uploads
|
|
|
|
|
// directly into a client/company/yacht folder. No-op for non-system folders.
|
|
|
|
|
const enrichedValues = await applyEntityFkFromFolder(portId, {
|
|
|
|
|
portId,
|
|
|
|
|
clientId: data.clientId ?? null,
|
|
|
|
|
yachtId: data.yachtId ?? null,
|
|
|
|
|
companyId: data.companyId ?? null,
|
|
|
|
|
folderId: data.folderId ?? null,
|
|
|
|
|
filename: sanitizedFilename,
|
|
|
|
|
originalName: sanitizedOriginal,
|
|
|
|
|
mimeType: file.mimeType,
|
|
|
|
|
sizeBytes: String(file.size),
|
|
|
|
|
storagePath,
|
|
|
|
|
storageBucket: env.MINIO_BUCKET,
|
|
|
|
|
category: data.category ?? null,
|
|
|
|
|
uploadedBy: meta.userId,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const [record] = await db.insert(files).values(enrichedValues).returning();
|
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: meta.userId,
|
|
|
|
|
portId,
|
|
|
|
|
action: 'create',
|
|
|
|
|
entityType: 'file',
|
|
|
|
|
entityId: record!.id,
|
|
|
|
|
newValue: { filename: record!.filename, mimeType: file.mimeType, size: file.size },
|
|
|
|
|
ipAddress: meta.ipAddress,
|
|
|
|
|
userAgent: meta.userAgent,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
emitToRoom(`port:${portId}`, 'file:uploaded', {
|
|
|
|
|
fileId: record!.id,
|
|
|
|
|
filename: record!.filename,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return record!;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ─── Download / Preview URLs ──────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
export async function getDownloadUrl(id: string, portId: string) {
|
|
|
|
|
const file = await getFileById(id, portId);
|
fix(storage): route every file op through getStorageBackend()
Removes 12 direct minioClient.{put,get,remove}Object call sites that
bypassed the pluggable storage abstraction. Filesystem-mode deploys
(MULTI_NODE_DEPLOYMENT=false, storage_backend=filesystem) silently
broke at every site: GDPR export, invoice PDF, EOI generation, portal
download, file upload, folder create/rename/delete, signed PDF land,
maintenance cleanup, etc. Each site now resolves the active backend
and uses its put/get/delete + the new presignDownloadUrl() helper.
Folder marker objects in /files/folders/* keep the same on-the-wire
shape but route through the backend. A future refactor should move
folder bookkeeping to a DB-backed virtual-folder table (see audit
HIGH §3 follow-up note in the route file).
Sites left untouched: src/lib/services/system-monitoring.service.ts
and src/app/api/ready/route.ts use minioClient.bucketExists as an S3-
specific health probe — those are correctly mode-aware and stay.
Refs: docs/audit-comprehensive-2026-05-05.md HIGH §3 (auditor-D Issue 1)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 18:41:02 +02:00
|
|
|
const url = await presignDownloadUrl(file.storagePath);
|
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
|
|
|
return { url, filename: file.filename };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function getPreviewUrl(id: string, portId: string) {
|
|
|
|
|
const file = await getFileById(id, portId);
|
|
|
|
|
|
|
|
|
|
if (!file.mimeType || !PREVIEWABLE_MIMES.has(file.mimeType)) {
|
|
|
|
|
throw new ValidationError('This file type cannot be previewed');
|
|
|
|
|
}
|
|
|
|
|
|
fix(storage): route every file op through getStorageBackend()
Removes 12 direct minioClient.{put,get,remove}Object call sites that
bypassed the pluggable storage abstraction. Filesystem-mode deploys
(MULTI_NODE_DEPLOYMENT=false, storage_backend=filesystem) silently
broke at every site: GDPR export, invoice PDF, EOI generation, portal
download, file upload, folder create/rename/delete, signed PDF land,
maintenance cleanup, etc. Each site now resolves the active backend
and uses its put/get/delete + the new presignDownloadUrl() helper.
Folder marker objects in /files/folders/* keep the same on-the-wire
shape but route through the backend. A future refactor should move
folder bookkeeping to a DB-backed virtual-folder table (see audit
HIGH §3 follow-up note in the route file).
Sites left untouched: src/lib/services/system-monitoring.service.ts
and src/app/api/ready/route.ts use minioClient.bucketExists as an S3-
specific health probe — those are correctly mode-aware and stay.
Refs: docs/audit-comprehensive-2026-05-05.md HIGH §3 (auditor-D Issue 1)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 18:41:02 +02:00
|
|
|
const url = await presignDownloadUrl(file.storagePath);
|
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
|
|
|
return { url, mimeType: file.mimeType };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ─── Update ───────────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
export async function updateFile(
|
|
|
|
|
id: string,
|
|
|
|
|
portId: string,
|
|
|
|
|
data: UpdateFileInput,
|
|
|
|
|
meta: AuditMeta,
|
|
|
|
|
) {
|
|
|
|
|
const existing = await getFileById(id, portId);
|
|
|
|
|
|
|
|
|
|
const updates: { filename?: string; category?: string } = {};
|
|
|
|
|
if (data.filename !== undefined) updates.filename = sanitizeFilename(data.filename);
|
|
|
|
|
if (data.category !== undefined) updates.category = data.category;
|
|
|
|
|
|
|
|
|
|
const [updated] = await db
|
|
|
|
|
.update(files)
|
|
|
|
|
.set(updates)
|
|
|
|
|
.where(and(eq(files.id, id), eq(files.portId, portId)))
|
|
|
|
|
.returning();
|
|
|
|
|
|
|
|
|
|
void createAuditLog({
|
|
|
|
|
userId: meta.userId,
|
|
|
|
|
portId,
|
|
|
|
|
action: 'update',
|
|
|
|
|
entityType: 'file',
|
|
|
|
|
entityId: id,
|
|
|
|
|
oldValue: { filename: existing.filename, category: existing.category },
|
|
|
|
|
newValue: updates,
|
|
|
|
|
ipAddress: meta.ipAddress,
|
|
|
|
|
userAgent: meta.userAgent,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
emitToRoom(`port:${portId}`, 'file:updated', { fileId: id });
|
|
|
|
|
|
|
|
|
|
return updated!;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ─── Delete (BR-091) ──────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
export async function deleteFile(id: string, portId: string, meta: AuditMeta) {
|
|
|
|
|
const existing = await getFileById(id, portId);
|
|
|
|
|
|
|
|
|
|
// BR-091: check references before deleting
|
|
|
|
|
const [docRefs, expenseRefs, maintenanceRefs] = await Promise.all([
|
|
|
|
|
db
|
|
|
|
|
.select({ id: documents.id })
|
|
|
|
|
.from(documents)
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(documents.portId, portId),
|
|
|
|
|
or(eq(documents.fileId, id), eq(documents.signedFileId, id)),
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
.limit(1),
|
|
|
|
|
db
|
|
|
|
|
.select({ id: expenses.id })
|
|
|
|
|
.from(expenses)
|
2026-04-29 01:58:42 +02:00
|
|
|
.where(and(eq(expenses.portId, portId), arrayContains(expenses.receiptFileIds, [id])))
|
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
|
|
|
.limit(1),
|
|
|
|
|
db
|
|
|
|
|
.select({ id: berthMaintenanceLog.id })
|
|
|
|
|
.from(berthMaintenanceLog)
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(berthMaintenanceLog.portId, portId),
|
|
|
|
|
arrayContains(berthMaintenanceLog.photoFileIds, [id]),
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
.limit(1),
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
if (docRefs.length > 0 || expenseRefs.length > 0 || maintenanceRefs.length > 0) {
|
2026-04-29 01:58:42 +02:00
|
|
|
throw new ConflictError('File cannot be deleted because it is referenced by other records');
|
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
|
|
|
}
|
|
|
|
|
|
fix(storage): route every file op through getStorageBackend()
Removes 12 direct minioClient.{put,get,remove}Object call sites that
bypassed the pluggable storage abstraction. Filesystem-mode deploys
(MULTI_NODE_DEPLOYMENT=false, storage_backend=filesystem) silently
broke at every site: GDPR export, invoice PDF, EOI generation, portal
download, file upload, folder create/rename/delete, signed PDF land,
maintenance cleanup, etc. Each site now resolves the active backend
and uses its put/get/delete + the new presignDownloadUrl() helper.
Folder marker objects in /files/folders/* keep the same on-the-wire
shape but route through the backend. A future refactor should move
folder bookkeeping to a DB-backed virtual-folder table (see audit
HIGH §3 follow-up note in the route file).
Sites left untouched: src/lib/services/system-monitoring.service.ts
and src/app/api/ready/route.ts use minioClient.bucketExists as an S3-
specific health probe — those are correctly mode-aware and stay.
Refs: docs/audit-comprehensive-2026-05-05.md HIGH §3 (auditor-D Issue 1)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 18:41:02 +02:00
|
|
|
// Delete the blob first, then DB. The storage backend's delete is
|
|
|
|
|
// idempotent, so a partial replay (worker crashed mid-delete) does not
|
|
|
|
|
// throw on the missing-object retry.
|
|
|
|
|
await (await getStorageBackend()).delete(existing.storagePath);
|
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
|
|
|
|
|
|
|
|
await db.delete(files).where(and(eq(files.id, id), eq(files.portId, portId)));
|
|
|
|
|
|
|
|
|
|
void createAuditLog({
|
|
|
|
|
userId: meta.userId,
|
|
|
|
|
portId,
|
|
|
|
|
action: 'delete',
|
|
|
|
|
entityType: 'file',
|
|
|
|
|
entityId: id,
|
|
|
|
|
oldValue: { filename: existing.filename },
|
|
|
|
|
ipAddress: meta.ipAddress,
|
|
|
|
|
userAgent: meta.userAgent,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
emitToRoom(`port:${portId}`, 'file:deleted', { fileId: id });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ─── List ─────────────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
export async function listFiles(portId: string, query: ListFilesInput) {
|
fix(audit): non-Documenso backlog sweep — port-binding, NULLS NOT DISTINCT, custom merge tokens, company docs
Wave through the remaining audit-final-deferred items that aren't blocked
on the back-burnered Documenso work.
Multi-tenant isolation:
- Storage proxy ProxyTokenPayload gains optional `p` (port slug) claim;
verifier asserts `key.startsWith(${p}/)`. Defense-in-depth against a
buggy issuer in some future code path that mixes port scopes — every
storage key generated by generateStorageKey() already prefixes the
slug. document-sends opts in for 24h emailed download links; other
callers continue working unchanged via the optional field.
DB schema reconciliation:
- Migration 0047 rebuilds system_settings unique index with NULLS NOT
DISTINCT (Postgres 15+) so global settings (port_id IS NULL) are
uniquely keyed by `key` alone. Surfaced + dedupe'd 65 duplicate
(storage_backend, NULL) rows that had accumulated from race-prone
delete-then-insert patterns in ocr-config / settings / residential-
stages / ai-budget services. All four services converted to true
onConflictDoUpdate upserts so the race window is closed.
API uniformity:
- Response shape standardization: 16 routes converted from
`{ success: true }` to 204 No Content. CLAUDE.md documents the
convention (`{ data: <T> }` for content, 204 for empty mutations,
portal-auth retains `{ success: true }` for the frontend's auth chain).
- req.json() → parseBody() migration across 9 admin/CRM routes
(custom-fields, expenses/export ×3, currency convert,
search/recently-viewed, admin/duplicates, berths/pdf-{upload-url,
versions, parse-results}). Uniform 400 error shapes for
ZodError-flagged bodies.
Custom-fields merge tokens (shipped end-to-end):
- merge-fields.ts gains CUSTOM_MERGE_TOKEN_RE + helpers for the
`{{custom.<fieldName>}}` shape.
- document-templates validator accepts the dynamic shape alongside
the static catalog tokens.
- document-sends.service mergeCustomFieldValues resolver fetches
per-port custom_field_definitions for client/interest/berth contexts
and substitutes stored values keyed by `{{custom.fieldName}}`.
- custom-fields-manager amber banner updated to reflect that merge
tokens now expand (search index + entity-diff remain documented
design limitations).
/api/v1/files cross-entity filtering:
- Validator + listFiles + uploadFile accept companyId AND yachtId
alongside clientId. file-upload-zone propagates both.
- New CompanyFilesTab component mirrors ClientFilesTab; restored as a
visible Documents tab in company-tabs.tsx (was a hidden stub).
Inline TODOs:
- Reviewed remaining two TODOs (per-user reminder schedule, import
worker handlers). Both are placeholders for future feature surfaces,
not bugs — per-port digest works for every customer; nothing
currently enqueues import jobs (verified). Annotated in BACKLOG.
BACKLOG.md updated to reflect what landed and what's still pending
(Documenso-related items still bundled with the back-burnered phases).
Tests: 1185/1185 vitest, tsc clean.
2026-05-08 02:20:27 +02:00
|
|
|
const { page, limit, sort, order, search, clientId, yachtId, companyId, category } = query;
|
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 filters = [];
|
|
|
|
|
|
|
|
|
|
if (clientId) {
|
|
|
|
|
filters.push(eq(files.clientId, clientId));
|
|
|
|
|
}
|
fix(audit): non-Documenso backlog sweep — port-binding, NULLS NOT DISTINCT, custom merge tokens, company docs
Wave through the remaining audit-final-deferred items that aren't blocked
on the back-burnered Documenso work.
Multi-tenant isolation:
- Storage proxy ProxyTokenPayload gains optional `p` (port slug) claim;
verifier asserts `key.startsWith(${p}/)`. Defense-in-depth against a
buggy issuer in some future code path that mixes port scopes — every
storage key generated by generateStorageKey() already prefixes the
slug. document-sends opts in for 24h emailed download links; other
callers continue working unchanged via the optional field.
DB schema reconciliation:
- Migration 0047 rebuilds system_settings unique index with NULLS NOT
DISTINCT (Postgres 15+) so global settings (port_id IS NULL) are
uniquely keyed by `key` alone. Surfaced + dedupe'd 65 duplicate
(storage_backend, NULL) rows that had accumulated from race-prone
delete-then-insert patterns in ocr-config / settings / residential-
stages / ai-budget services. All four services converted to true
onConflictDoUpdate upserts so the race window is closed.
API uniformity:
- Response shape standardization: 16 routes converted from
`{ success: true }` to 204 No Content. CLAUDE.md documents the
convention (`{ data: <T> }` for content, 204 for empty mutations,
portal-auth retains `{ success: true }` for the frontend's auth chain).
- req.json() → parseBody() migration across 9 admin/CRM routes
(custom-fields, expenses/export ×3, currency convert,
search/recently-viewed, admin/duplicates, berths/pdf-{upload-url,
versions, parse-results}). Uniform 400 error shapes for
ZodError-flagged bodies.
Custom-fields merge tokens (shipped end-to-end):
- merge-fields.ts gains CUSTOM_MERGE_TOKEN_RE + helpers for the
`{{custom.<fieldName>}}` shape.
- document-templates validator accepts the dynamic shape alongside
the static catalog tokens.
- document-sends.service mergeCustomFieldValues resolver fetches
per-port custom_field_definitions for client/interest/berth contexts
and substitutes stored values keyed by `{{custom.fieldName}}`.
- custom-fields-manager amber banner updated to reflect that merge
tokens now expand (search index + entity-diff remain documented
design limitations).
/api/v1/files cross-entity filtering:
- Validator + listFiles + uploadFile accept companyId AND yachtId
alongside clientId. file-upload-zone propagates both.
- New CompanyFilesTab component mirrors ClientFilesTab; restored as a
visible Documents tab in company-tabs.tsx (was a hidden stub).
Inline TODOs:
- Reviewed remaining two TODOs (per-user reminder schedule, import
worker handlers). Both are placeholders for future feature surfaces,
not bugs — per-port digest works for every customer; nothing
currently enqueues import jobs (verified). Annotated in BACKLOG.
BACKLOG.md updated to reflect what landed and what's still pending
(Documenso-related items still bundled with the back-burnered phases).
Tests: 1185/1185 vitest, tsc clean.
2026-05-08 02:20:27 +02:00
|
|
|
if (yachtId) {
|
|
|
|
|
filters.push(eq(files.yachtId, yachtId));
|
|
|
|
|
}
|
|
|
|
|
if (companyId) {
|
|
|
|
|
filters.push(eq(files.companyId, companyId));
|
|
|
|
|
}
|
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 (category) {
|
|
|
|
|
filters.push(eq(files.category, category));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const sortColumn =
|
2026-04-29 01:58:42 +02:00
|
|
|
sort === 'filename' ? files.filename : sort === 'sizeBytes' ? files.sizeBytes : files.createdAt;
|
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
|
|
|
|
|
|
|
|
return buildListQuery({
|
|
|
|
|
table: files,
|
|
|
|
|
portIdColumn: files.portId,
|
|
|
|
|
portId,
|
|
|
|
|
idColumn: files.id,
|
|
|
|
|
updatedAtColumn: files.createdAt, // no updatedAt on files
|
|
|
|
|
searchColumns: [files.filename, files.originalName],
|
|
|
|
|
searchTerm: search,
|
|
|
|
|
filters,
|
|
|
|
|
sort: sort ? { column: sortColumn, direction: order } : undefined,
|
|
|
|
|
page,
|
|
|
|
|
pageSize: limit,
|
2026-05-04 22:57:01 +02:00
|
|
|
// no archivedAtColumn - files are immutable records
|
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
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ─── Get by ID ────────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
export async function getFileById(id: string, portId: string) {
|
|
|
|
|
const file = await db.query.files.findFirst({
|
|
|
|
|
where: eq(files.id, id),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!file || file.portId !== portId) {
|
|
|
|
|
throw new NotFoundError('File');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return file;
|
|
|
|
|
}
|
2026-05-11 11:54:23 +02:00
|
|
|
|
|
|
|
|
// ─── Aggregated Projection ────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
export interface AggregatedFileGroup {
|
|
|
|
|
label: string;
|
|
|
|
|
source: 'direct' | 'client' | 'company' | 'yacht';
|
2026-05-11 12:44:48 +02:00
|
|
|
files: Array<typeof files.$inferSelect & { signedFromDocumentId: string | null }>;
|
2026-05-11 11:54:23 +02:00
|
|
|
total: number;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
interface AggregatedFilesResult {
|
|
|
|
|
groups: AggregatedFileGroup[];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const GROUP_LIMIT = 20;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Walk the relationship graph from the requested entity and return
|
|
|
|
|
* files grouped by source. Symmetric reach.
|
|
|
|
|
*
|
|
|
|
|
* Source of truth: each file's snapshotted entity FKs.
|
|
|
|
|
* Defense-in-depth: port_id at every entity / membership / yacht / file join.
|
|
|
|
|
*/
|
|
|
|
|
export async function listFilesAggregatedByEntity(
|
|
|
|
|
portId: string,
|
|
|
|
|
entityType: EntityType,
|
|
|
|
|
entityId: string,
|
|
|
|
|
): Promise<AggregatedFilesResult> {
|
|
|
|
|
const entityExists = await assertEntityInPort(portId, entityType, entityId);
|
|
|
|
|
if (!entityExists) return { groups: [] };
|
|
|
|
|
|
|
|
|
|
const related = await collectRelatedEntities(portId, entityType, entityId);
|
|
|
|
|
const groups: AggregatedFileGroup[] = [];
|
|
|
|
|
|
|
|
|
|
const directColumn =
|
|
|
|
|
entityType === 'client'
|
|
|
|
|
? files.clientId
|
|
|
|
|
: entityType === 'company'
|
|
|
|
|
? files.companyId
|
|
|
|
|
: files.yachtId;
|
|
|
|
|
|
|
|
|
|
const direct = await fetchGroupRows(portId, eq(directColumn, entityId), GROUP_LIMIT);
|
|
|
|
|
if (direct.rows.length > 0) {
|
|
|
|
|
groups.push({
|
|
|
|
|
label: 'DIRECTLY ATTACHED',
|
|
|
|
|
source: 'direct',
|
|
|
|
|
files: direct.rows,
|
|
|
|
|
total: direct.total,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for (const { id, name } of related.companies) {
|
|
|
|
|
const g = await fetchGroupRows(portId, eq(files.companyId, id), GROUP_LIMIT);
|
|
|
|
|
if (g.rows.length === 0) continue;
|
|
|
|
|
groups.push({
|
|
|
|
|
label: `FROM COMPANY — ${name.toUpperCase()}`,
|
|
|
|
|
source: 'company',
|
|
|
|
|
files: g.rows,
|
|
|
|
|
total: g.total,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for (const { id, name } of related.yachts) {
|
|
|
|
|
const g = await fetchGroupRows(portId, eq(files.yachtId, id), GROUP_LIMIT);
|
|
|
|
|
if (g.rows.length === 0) continue;
|
|
|
|
|
groups.push({
|
|
|
|
|
label: `FROM YACHT — ${name.toUpperCase()}`,
|
|
|
|
|
source: 'yacht',
|
|
|
|
|
files: g.rows,
|
|
|
|
|
total: g.total,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for (const { id, name } of related.clients) {
|
|
|
|
|
const g = await fetchGroupRows(portId, eq(files.clientId, id), GROUP_LIMIT);
|
|
|
|
|
if (g.rows.length === 0) continue;
|
|
|
|
|
groups.push({
|
|
|
|
|
label: `FROM CLIENT — ${name.toUpperCase()}`,
|
|
|
|
|
source: 'client',
|
|
|
|
|
files: g.rows,
|
|
|
|
|
total: g.total,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return { groups };
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-11 12:02:33 +02:00
|
|
|
export async function assertEntityInPort(
|
2026-05-11 11:54:23 +02:00
|
|
|
portId: string,
|
|
|
|
|
entityType: EntityType,
|
|
|
|
|
entityId: string,
|
|
|
|
|
): Promise<boolean> {
|
|
|
|
|
if (entityType === 'client') {
|
|
|
|
|
const c = await db.query.clients.findFirst({
|
|
|
|
|
where: and(eq(clients.id, entityId), eq(clients.portId, portId)),
|
|
|
|
|
columns: { id: true },
|
|
|
|
|
});
|
|
|
|
|
return Boolean(c);
|
|
|
|
|
}
|
|
|
|
|
if (entityType === 'company') {
|
|
|
|
|
const c = await db.query.companies.findFirst({
|
|
|
|
|
where: and(eq(companies.id, entityId), eq(companies.portId, portId)),
|
|
|
|
|
columns: { id: true },
|
|
|
|
|
});
|
|
|
|
|
return Boolean(c);
|
|
|
|
|
}
|
|
|
|
|
const y = await db.query.yachts.findFirst({
|
|
|
|
|
where: and(eq(yachts.id, entityId), eq(yachts.portId, portId)),
|
|
|
|
|
columns: { id: true },
|
|
|
|
|
});
|
|
|
|
|
return Boolean(y);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export interface RelatedEntities {
|
|
|
|
|
clients: Array<{ id: string; name: string }>;
|
|
|
|
|
companies: Array<{ id: string; name: string }>;
|
|
|
|
|
yachts: Array<{ id: string; name: string }>;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Walk the relationship graph and collect related entity ids per
|
|
|
|
|
* source bucket. Symmetric reach. Every join carries port_id.
|
|
|
|
|
*
|
|
|
|
|
* Note: clients schema has fullName only (no firstName/lastName).
|
|
|
|
|
*/
|
|
|
|
|
export async function collectRelatedEntities(
|
|
|
|
|
portId: string,
|
|
|
|
|
entityType: EntityType,
|
|
|
|
|
entityId: string,
|
|
|
|
|
): Promise<RelatedEntities> {
|
|
|
|
|
if (entityType === 'client') {
|
|
|
|
|
const memberCompanies = await db
|
|
|
|
|
.select({ id: companies.id, name: companies.name })
|
|
|
|
|
.from(companyMemberships)
|
|
|
|
|
.innerJoin(
|
|
|
|
|
companies,
|
|
|
|
|
and(eq(companies.id, companyMemberships.companyId), eq(companies.portId, portId)),
|
|
|
|
|
)
|
2026-05-11 12:44:48 +02:00
|
|
|
.where(and(eq(companyMemberships.clientId, entityId), isNull(companyMemberships.endDate)));
|
2026-05-11 11:54:23 +02:00
|
|
|
|
|
|
|
|
const directYachts = await db
|
|
|
|
|
.select({ id: yachts.id, name: yachts.name })
|
|
|
|
|
.from(yachts)
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(yachts.portId, portId),
|
|
|
|
|
eq(yachts.currentOwnerType, 'client'),
|
|
|
|
|
eq(yachts.currentOwnerId, entityId),
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
let companyYachts: Array<{ id: string; name: string }> = [];
|
|
|
|
|
if (memberCompanies.length > 0) {
|
|
|
|
|
companyYachts = await db
|
|
|
|
|
.select({ id: yachts.id, name: yachts.name })
|
|
|
|
|
.from(yachts)
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(yachts.portId, portId),
|
|
|
|
|
eq(yachts.currentOwnerType, 'company'),
|
|
|
|
|
inArray(
|
|
|
|
|
yachts.currentOwnerId,
|
|
|
|
|
memberCompanies.map((c) => c.id),
|
|
|
|
|
),
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
clients: [],
|
|
|
|
|
companies: memberCompanies,
|
|
|
|
|
yachts: dedupeBy([...directYachts, ...companyYachts], (y) => y.id),
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (entityType === 'company') {
|
|
|
|
|
// Adapted: use fullName not firstName/lastName.
|
|
|
|
|
const memberClients = await db
|
|
|
|
|
.select({ id: clients.id, fullName: clients.fullName })
|
|
|
|
|
.from(companyMemberships)
|
|
|
|
|
.innerJoin(
|
|
|
|
|
clients,
|
|
|
|
|
and(eq(clients.id, companyMemberships.clientId), eq(clients.portId, portId)),
|
|
|
|
|
)
|
2026-05-11 12:44:48 +02:00
|
|
|
.where(and(eq(companyMemberships.companyId, entityId), isNull(companyMemberships.endDate)));
|
2026-05-11 11:54:23 +02:00
|
|
|
|
|
|
|
|
const ownedYachts = await db
|
|
|
|
|
.select({ id: yachts.id, name: yachts.name })
|
|
|
|
|
.from(yachts)
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(yachts.portId, portId),
|
|
|
|
|
eq(yachts.currentOwnerType, 'company'),
|
|
|
|
|
eq(yachts.currentOwnerId, entityId),
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
clients: memberClients.map((c) => ({ id: c.id, name: c.fullName })),
|
|
|
|
|
companies: [],
|
|
|
|
|
yachts: ownedYachts,
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// yacht view
|
|
|
|
|
const yacht = await db.query.yachts.findFirst({
|
|
|
|
|
where: and(eq(yachts.id, entityId), eq(yachts.portId, portId)),
|
|
|
|
|
});
|
|
|
|
|
if (!yacht) return { clients: [], companies: [], yachts: [] };
|
|
|
|
|
|
|
|
|
|
if (yacht.currentOwnerType === 'client') {
|
|
|
|
|
const owner = await db.query.clients.findFirst({
|
|
|
|
|
where: and(eq(clients.id, yacht.currentOwnerId), eq(clients.portId, portId)),
|
|
|
|
|
columns: { id: true, fullName: true },
|
|
|
|
|
});
|
|
|
|
|
return {
|
|
|
|
|
clients: owner ? [{ id: owner.id, name: owner.fullName }] : [],
|
|
|
|
|
companies: [],
|
|
|
|
|
yachts: [],
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const owner = await db.query.companies.findFirst({
|
|
|
|
|
where: and(eq(companies.id, yacht.currentOwnerId), eq(companies.portId, portId)),
|
|
|
|
|
columns: { id: true, name: true },
|
|
|
|
|
});
|
|
|
|
|
return {
|
|
|
|
|
clients: [],
|
|
|
|
|
companies: owner ? [{ id: owner.id, name: owner.name }] : [],
|
|
|
|
|
yachts: [],
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function fetchGroupRows(
|
|
|
|
|
portId: string,
|
|
|
|
|
predicate: ReturnType<typeof eq>,
|
|
|
|
|
limit: number,
|
2026-05-11 12:44:48 +02:00
|
|
|
): Promise<{
|
|
|
|
|
rows: Array<typeof files.$inferSelect & { signedFromDocumentId: string | null }>;
|
|
|
|
|
total: number;
|
|
|
|
|
}> {
|
2026-05-11 11:54:23 +02:00
|
|
|
const rows = await db
|
2026-05-11 12:44:48 +02:00
|
|
|
.select({
|
|
|
|
|
id: files.id,
|
|
|
|
|
portId: files.portId,
|
|
|
|
|
clientId: files.clientId,
|
|
|
|
|
yachtId: files.yachtId,
|
|
|
|
|
companyId: files.companyId,
|
|
|
|
|
folderId: files.folderId,
|
|
|
|
|
filename: files.filename,
|
|
|
|
|
originalName: files.originalName,
|
|
|
|
|
mimeType: files.mimeType,
|
|
|
|
|
sizeBytes: files.sizeBytes,
|
|
|
|
|
storagePath: files.storagePath,
|
|
|
|
|
storageBucket: files.storageBucket,
|
|
|
|
|
category: files.category,
|
|
|
|
|
uploadedBy: files.uploadedBy,
|
|
|
|
|
createdAt: files.createdAt,
|
|
|
|
|
// Reverse-link: if any document row has this file as its signed_file_id,
|
|
|
|
|
// surface that document's id. LEFT JOIN preserves files with no workflow link.
|
|
|
|
|
// Defense-in-depth: portId filter on both the join condition and the outer where.
|
|
|
|
|
signedFromDocumentId: documents.id,
|
|
|
|
|
})
|
2026-05-11 11:54:23 +02:00
|
|
|
.from(files)
|
2026-05-11 13:01:47 +02:00
|
|
|
.leftJoin(documents, and(eq(documents.signedFileId, files.id), eq(documents.portId, portId)))
|
2026-05-11 11:54:23 +02:00
|
|
|
.where(and(eq(files.portId, portId), predicate))
|
|
|
|
|
.orderBy(desc(files.createdAt))
|
|
|
|
|
.limit(limit);
|
|
|
|
|
|
|
|
|
|
const [countRow] = await db
|
|
|
|
|
.select({ count: sql<number>`count(*)::int` })
|
|
|
|
|
.from(files)
|
|
|
|
|
.where(and(eq(files.portId, portId), predicate));
|
|
|
|
|
|
|
|
|
|
return { rows, total: Number(countRow?.count ?? 0) };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function dedupeBy<T, K>(items: T[], key: (t: T) => K): T[] {
|
|
|
|
|
const seen = new Set<K>();
|
|
|
|
|
const out: T[] = [];
|
|
|
|
|
for (const item of items) {
|
|
|
|
|
const k = key(item);
|
|
|
|
|
if (seen.has(k)) continue;
|
|
|
|
|
seen.add(k);
|
|
|
|
|
out.push(item);
|
|
|
|
|
}
|
|
|
|
|
return out;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ─── E8: applyEntityFkFromFolder ─────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* E8: when a rep manually uploads a file into a system-managed entity
|
|
|
|
|
* subfolder, auto-set the matching entity FK on the file row from the
|
|
|
|
|
* folder's entityType + entityId. Custom (non-system) folders →
|
|
|
|
|
* returns the input unchanged.
|
|
|
|
|
*/
|
|
|
|
|
export async function applyEntityFkFromFolder<
|
|
|
|
|
T extends {
|
|
|
|
|
clientId?: string | null;
|
|
|
|
|
companyId?: string | null;
|
|
|
|
|
yachtId?: string | null;
|
|
|
|
|
folderId?: string | null;
|
|
|
|
|
},
|
|
|
|
|
>(portId: string, payload: T): Promise<T> {
|
|
|
|
|
if (!payload.folderId) return payload;
|
|
|
|
|
|
|
|
|
|
const folder = await db.query.documentFolders.findFirst({
|
2026-05-11 12:02:33 +02:00
|
|
|
where: and(eq(documentFolders.id, payload.folderId), eq(documentFolders.portId, portId)),
|
2026-05-11 11:54:23 +02:00
|
|
|
columns: { systemManaged: true, entityType: true, entityId: true },
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!folder || !folder.systemManaged || !folder.entityType || !folder.entityId) {
|
|
|
|
|
return payload;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (folder.entityType === 'client' && !payload.clientId) {
|
|
|
|
|
return { ...payload, clientId: folder.entityId };
|
|
|
|
|
}
|
|
|
|
|
if (folder.entityType === 'company' && !payload.companyId) {
|
|
|
|
|
return { ...payload, companyId: folder.entityId };
|
|
|
|
|
}
|
|
|
|
|
if (folder.entityType === 'yacht' && !payload.yachtId) {
|
|
|
|
|
return { ...payload, yachtId: folder.entityId };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return payload;
|
|
|
|
|
}
|