feat(documents): ensureSystemRoots + wire into createPort
Adds idempotent root-folder bootstrap (Clients/Companies/Yachts) called on every port-init. ON CONFLICT DO NOTHING on the sibling-name unique index prevents racing inserts; the re-SELECT returns the stable row set in SYSTEM_ROOT_NAMES order. Same helper is invoked by the backfill script in a later task. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -299,3 +299,41 @@ export function collectDescendantIds(tree: FolderNode[], rootId: string): string
|
||||
visit(tree, false);
|
||||
return out;
|
||||
}
|
||||
|
||||
const SYSTEM_ROOT_NAMES = ['Clients', 'Companies', 'Yachts'] as const;
|
||||
type SystemRootName = (typeof SYSTEM_ROOT_NAMES)[number];
|
||||
|
||||
/**
|
||||
* Idempotently create the three system root folders for a port
|
||||
* (`Clients/`, `Companies/`, `Yachts/`). Returns the rows in stable
|
||||
* order. Safe to call on every port-init and on every backfill run.
|
||||
*
|
||||
* Uses INSERT … ON CONFLICT … DO NOTHING via the sibling-name unique
|
||||
* index (`uniq_document_folders_sibling_name`) so a concurrent caller
|
||||
* can't race two inserts of the same root. Re-SELECTs on conflict so
|
||||
* the return shape is always populated.
|
||||
*/
|
||||
export async function ensureSystemRoots(portId: string, userId: string): Promise<DocumentFolder[]> {
|
||||
const values = SYSTEM_ROOT_NAMES.map((name) => ({
|
||||
portId,
|
||||
parentId: null,
|
||||
name,
|
||||
systemManaged: true,
|
||||
entityType: 'root' as const,
|
||||
entityId: null,
|
||||
createdBy: userId,
|
||||
}));
|
||||
|
||||
await db.insert(documentFolders).values(values).onConflictDoNothing();
|
||||
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(documentFolders)
|
||||
.where(and(eq(documentFolders.portId, portId), eq(documentFolders.entityType, 'root')));
|
||||
|
||||
return SYSTEM_ROOT_NAMES.map((name: SystemRootName) => {
|
||||
const row = rows.find((r) => r.name === name);
|
||||
if (!row) throw new Error(`ensureSystemRoots: missing root ${name} after upsert`);
|
||||
return row;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { createAuditLog, type AuditMeta } from '@/lib/audit';
|
||||
import { ConflictError, NotFoundError } from '@/lib/errors';
|
||||
import { emitToRoom } from '@/lib/socket/server';
|
||||
import type { CreatePortInput, UpdatePortInput } from '@/lib/validators/ports';
|
||||
import { ensureSystemRoots } from '@/lib/services/document-folders.service';
|
||||
|
||||
export async function listPorts() {
|
||||
return db.select().from(ports).orderBy(ports.name);
|
||||
@@ -40,6 +41,8 @@ export async function createPort(data: CreatePortInput, meta: AuditMeta) {
|
||||
})
|
||||
.returning();
|
||||
|
||||
await ensureSystemRoots(port!.id, meta.userId);
|
||||
|
||||
void createAuditLog({
|
||||
userId: meta.userId,
|
||||
portId: meta.portId,
|
||||
|
||||
Reference in New Issue
Block a user