fix(folders): logging, files-rescue, hard-delete wiring, audit logs
- A6: logger import + warn calls in document-folders.service.ts - G-C1: re-parent files (not just documents) in deleteFolderSoftRescue - A4: importer sets files.folder_id (was only setting documents.folder_id) - A7 + G-C3: demote system folder + nullify scratchpadNotes in client-hard-delete - Defense-in-depth portId on folder-move UPDATE - Audit logs for createFolder, syncEntityFolderName, archive/restore suffix - portId in companies/yachts archive log context - Row-count telemetry in backfill CLI Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -41,7 +41,7 @@ export const PATCH = withAuth(
|
||||
const [updated] = await db
|
||||
.update(documents)
|
||||
.set({ folderId: body.folderId, updatedAt: new Date() })
|
||||
.where(eq(documents.id, docId))
|
||||
.where(and(eq(documents.id, docId), eq(documents.portId, ctx.portId)))
|
||||
.returning();
|
||||
|
||||
void createAuditLog({
|
||||
|
||||
@@ -39,11 +39,13 @@ import { files, documents, formSubmissions } from '@/lib/db/schema/documents';
|
||||
import { documentSends } from '@/lib/db/schema/brochures';
|
||||
import { emailThreads } from '@/lib/db/schema/email';
|
||||
import { reminders } from '@/lib/db/schema/operations';
|
||||
import { scratchpadNotes } from '@/lib/db/schema/system';
|
||||
import { user as authUser } from '@/lib/db/schema/users';
|
||||
import { redis } from '@/lib/redis';
|
||||
import { sendEmail } from '@/lib/email';
|
||||
import { logger } from '@/lib/logger';
|
||||
import { createAuditLog, type AuditMeta } from '@/lib/audit';
|
||||
import { demoteSystemFolderOnEntityDelete } from '@/lib/services/document-folders.service';
|
||||
import { ConflictError, NotFoundError, ValidationError } from '@/lib/errors';
|
||||
|
||||
const CODE_TTL_SECONDS = 10 * 60;
|
||||
@@ -203,6 +205,14 @@ export async function hardDeleteClient(args: {
|
||||
.update(documentSends)
|
||||
.set({ clientId: null })
|
||||
.where(eq(documentSends.clientId, args.clientId));
|
||||
// G-C2: scratchpad_notes.linked_client_id is RESTRICT (default for no
|
||||
// onDelete clause). Any rep who linked a scratchpad note to this client
|
||||
// would otherwise throw an FK violation when we try to delete the
|
||||
// client row below. Nullify so the note survives the hard-delete.
|
||||
await tx
|
||||
.update(scratchpadNotes)
|
||||
.set({ linkedClientId: null })
|
||||
.where(eq(scratchpadNotes.linkedClientId, args.clientId));
|
||||
|
||||
// client_merge_log.surviving_client_id has no cascade and is
|
||||
// notNull → must be deleted explicitly. Merged records remain in
|
||||
@@ -218,6 +228,18 @@ export async function hardDeleteClient(args: {
|
||||
await tx.delete(clients).where(eq(clients.id, args.clientId));
|
||||
});
|
||||
|
||||
// G-C3 / A7: demote the system-managed folder so the partial unique
|
||||
// index `uniq_document_folders_entity` releases its slot. Done as a
|
||||
// post-commit fire-and-forget — folder hygiene is non-essential to the
|
||||
// delete being durable, and we don't want a folder-table glitch to
|
||||
// un-delete the client by aborting the outer transaction.
|
||||
void demoteSystemFolderOnEntityDelete(args.portId, 'client', args.clientId).catch((err) => {
|
||||
logger.error(
|
||||
{ err, clientId: args.clientId, portId: args.portId },
|
||||
'hardDeleteClient: failed to demote system folder',
|
||||
);
|
||||
});
|
||||
|
||||
void createAuditLog({
|
||||
portId: args.portId,
|
||||
userId: args.requesterUserId,
|
||||
|
||||
@@ -561,8 +561,11 @@ export async function archiveClient(id: string, portId: string, meta: AuditMeta)
|
||||
// being stamped before the HTTP response returns. Task 5 (rename
|
||||
// hook) uses await because the rename should be visible to the
|
||||
// next read; archive does not.
|
||||
void applyEntityArchivedSuffix(portId, 'client', id).catch((err) => {
|
||||
logger.warn({ err, clientId: id }, 'Failed to apply archived suffix to client folder');
|
||||
void applyEntityArchivedSuffix(portId, 'client', id, meta.userId).catch((err) => {
|
||||
logger.warn(
|
||||
{ err, clientId: id, portId },
|
||||
'Failed to apply archived suffix to client folder',
|
||||
);
|
||||
});
|
||||
|
||||
void createAuditLog({
|
||||
@@ -593,8 +596,11 @@ export async function restoreClient(id: string, portId: string, meta: AuditMeta)
|
||||
|
||||
await restore(clients, clients.id, id);
|
||||
|
||||
void applyEntityRestoredSuffix(portId, 'client', id).catch((err) => {
|
||||
logger.warn({ err, clientId: id }, 'Failed to clear archived suffix on client folder');
|
||||
void applyEntityRestoredSuffix(portId, 'client', id, meta.userId).catch((err) => {
|
||||
logger.warn(
|
||||
{ err, clientId: id, portId },
|
||||
'Failed to clear archived suffix on client folder',
|
||||
);
|
||||
});
|
||||
|
||||
void createAuditLog({
|
||||
|
||||
@@ -188,7 +188,7 @@ export async function updateCompany(
|
||||
|
||||
if (data.name !== undefined) {
|
||||
await syncEntityFolderName(portId, 'company', id, meta.userId).catch((err) => {
|
||||
logger.warn({ err, companyId: id }, 'Failed to sync company folder name');
|
||||
logger.warn({ err, companyId: id, portId }, 'Failed to sync company folder name');
|
||||
});
|
||||
}
|
||||
|
||||
@@ -215,8 +215,11 @@ export async function archiveCompany(id: string, portId: string, meta: AuditMeta
|
||||
.set({ archivedAt: new Date() })
|
||||
.where(and(eq(companies.id, id), eq(companies.portId, portId)));
|
||||
|
||||
void applyEntityArchivedSuffix(portId, 'company', id).catch((err) => {
|
||||
logger.warn({ err, companyId: id }, 'Failed to apply archived suffix to company folder');
|
||||
void applyEntityArchivedSuffix(portId, 'company', id, meta.userId).catch((err) => {
|
||||
logger.warn(
|
||||
{ err, companyId: id, portId },
|
||||
'Failed to apply archived suffix to company folder',
|
||||
);
|
||||
});
|
||||
|
||||
void createAuditLog({
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
import { and, asc, eq } from 'drizzle-orm';
|
||||
|
||||
import { db } from '@/lib/db';
|
||||
import { documentFolders, documents, type DocumentFolder } from '@/lib/db/schema/documents';
|
||||
import {
|
||||
documentFolders,
|
||||
documents,
|
||||
files,
|
||||
type DocumentFolder,
|
||||
} from '@/lib/db/schema/documents';
|
||||
import { clients } from '@/lib/db/schema/clients';
|
||||
import { companies } from '@/lib/db/schema/companies';
|
||||
import { yachts } from '@/lib/db/schema/yachts';
|
||||
import { createAuditLog } from '@/lib/audit';
|
||||
import { ConflictError, NotFoundError, ValidationError } from '@/lib/errors';
|
||||
import { logger } from '@/lib/logger';
|
||||
|
||||
/**
|
||||
* Returns true if the error is a Postgres unique-violation (SQLSTATE 23505)
|
||||
@@ -78,10 +84,17 @@ export async function listTree(portId: string): Promise<FolderNode[]> {
|
||||
roots.push(node);
|
||||
} else {
|
||||
const parent = byId.get(node.parentId);
|
||||
if (parent) parent.children.push(node);
|
||||
// Orphan rows (parentId pointing nowhere) are dropped from the
|
||||
// tree but stay in the DB. Surface via a separate maintenance
|
||||
// query if needed; never silently re-parent.
|
||||
if (parent) {
|
||||
parent.children.push(node);
|
||||
} else {
|
||||
// Orphan rows (parentId pointing nowhere) are dropped from the
|
||||
// tree but stay in the DB. Surface via a separate maintenance
|
||||
// query if needed; never silently re-parent.
|
||||
logger.warn(
|
||||
{ portId, folderId: node.id, parentId: node.parentId, name: node.name },
|
||||
'listTree: orphan folder row (parentId points to a missing folder); dropped from tree',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return roots;
|
||||
@@ -126,6 +139,17 @@ export async function createFolder(
|
||||
})
|
||||
.returning();
|
||||
if (!row) throw new NotFoundError('Folder');
|
||||
|
||||
void createAuditLog({
|
||||
userId,
|
||||
portId,
|
||||
action: 'create',
|
||||
entityType: 'document_folder',
|
||||
entityId: row.id,
|
||||
newValue: { name: row.name, parentId: row.parentId },
|
||||
metadata: { type: 'folder_created' },
|
||||
});
|
||||
|
||||
return row;
|
||||
} catch (err) {
|
||||
if (isSiblingNameConflict(err)) {
|
||||
@@ -276,6 +300,15 @@ export async function deleteFolderSoftRescue(
|
||||
.set({ folderId: newParent })
|
||||
.where(and(eq(documents.folderId, folderId), eq(documents.portId, portId)));
|
||||
|
||||
// G-C1: files.folder_id is ON DELETE SET NULL — without this UPDATE,
|
||||
// files in the deleted folder would scatter to root while documents
|
||||
// in the same folder land at the deleted folder's parent. Re-parent
|
||||
// files explicitly so the soft-rescue is symmetric across both.
|
||||
await tx
|
||||
.update(files)
|
||||
.set({ folderId: newParent })
|
||||
.where(and(eq(files.folderId, folderId), eq(files.portId, portId)));
|
||||
|
||||
await tx
|
||||
.delete(documentFolders)
|
||||
.where(and(eq(documentFolders.id, folderId), eq(documentFolders.portId, portId)));
|
||||
@@ -353,7 +386,13 @@ export async function ensureSystemRoots(portId: string, userId: string): Promise
|
||||
|
||||
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`);
|
||||
if (!row) {
|
||||
logger.error(
|
||||
{ portId, missingRoot: name, foundNames: rows.map((r) => r.name) },
|
||||
'ensureSystemRoots: invariant violated — system root missing after upsert',
|
||||
);
|
||||
throw new Error(`ensureSystemRoots: missing root ${name} after upsert`);
|
||||
}
|
||||
return row;
|
||||
});
|
||||
}
|
||||
@@ -513,6 +552,10 @@ export async function ensureEntityFolder(
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
logger.warn(
|
||||
{ portId, entityType, entityId, baseName, attempts: 50 },
|
||||
'ensureEntityFolder: exhausted 50 suffix attempts without finding a unique name',
|
||||
);
|
||||
throw new ConflictError(`Could not allocate a unique folder name for ${baseName}`);
|
||||
}
|
||||
|
||||
@@ -532,7 +575,7 @@ export async function syncEntityFolderName(
|
||||
portId: string,
|
||||
entityType: EntityType,
|
||||
entityId: string,
|
||||
_userId: string,
|
||||
userId: string,
|
||||
): Promise<void> {
|
||||
if (!ENTITY_TYPES.has(entityType)) return;
|
||||
|
||||
@@ -563,12 +606,28 @@ export async function syncEntityFolderName(
|
||||
.set({ name: candidate, updatedAt: new Date() })
|
||||
.where(and(eq(documentFolders.id, folder.id), eq(documentFolders.portId, portId)))
|
||||
.returning();
|
||||
if (updated) return;
|
||||
if (updated) {
|
||||
void createAuditLog({
|
||||
userId,
|
||||
portId,
|
||||
action: 'update',
|
||||
entityType: 'document_folder',
|
||||
entityId: folder.id,
|
||||
oldValue: { name: folder.name },
|
||||
newValue: { name: candidate },
|
||||
metadata: { type: 'folder_entity_rename_sync', entity: entityType, sourceEntityId: entityId },
|
||||
});
|
||||
return;
|
||||
}
|
||||
} catch (err) {
|
||||
if (isSiblingNameConflict(err)) continue;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
logger.warn(
|
||||
{ portId, entityType, entityId, baseName, attempts: 50 },
|
||||
'syncEntityFolderName: exhausted 50 suffix attempts without finding a unique name',
|
||||
);
|
||||
throw new ConflictError(`Could not allocate a unique folder name for ${baseName}`);
|
||||
}
|
||||
|
||||
@@ -587,6 +646,7 @@ export async function applyEntityArchivedSuffix(
|
||||
portId: string,
|
||||
entityType: EntityType,
|
||||
entityId: string,
|
||||
userId?: string,
|
||||
): Promise<void> {
|
||||
if (!ENTITY_TYPES.has(entityType)) return;
|
||||
const folder = await db.query.documentFolders.findFirst({
|
||||
@@ -605,6 +665,17 @@ export async function applyEntityArchivedSuffix(
|
||||
.update(documentFolders)
|
||||
.set({ name: newName, archivedAt: new Date(), updatedAt: new Date() })
|
||||
.where(and(eq(documentFolders.id, folder.id), eq(documentFolders.portId, portId)));
|
||||
|
||||
void createAuditLog({
|
||||
userId: userId ?? 'system',
|
||||
portId,
|
||||
action: 'archive',
|
||||
entityType: 'document_folder',
|
||||
entityId: folder.id,
|
||||
oldValue: { name: folder.name, archivedAt: folder.archivedAt },
|
||||
newValue: { name: newName, archivedAt: new Date() },
|
||||
metadata: { type: 'folder_entity_archived', entity: entityType, sourceEntityId: entityId },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -616,6 +687,7 @@ export async function applyEntityRestoredSuffix(
|
||||
portId: string,
|
||||
entityType: EntityType,
|
||||
entityId: string,
|
||||
userId?: string,
|
||||
): Promise<void> {
|
||||
if (!ENTITY_TYPES.has(entityType)) return;
|
||||
const folder = await db.query.documentFolders.findFirst({
|
||||
@@ -634,6 +706,17 @@ export async function applyEntityRestoredSuffix(
|
||||
.update(documentFolders)
|
||||
.set({ name: newName, archivedAt: null, updatedAt: new Date() })
|
||||
.where(and(eq(documentFolders.id, folder.id), eq(documentFolders.portId, portId)));
|
||||
|
||||
void createAuditLog({
|
||||
userId: userId ?? 'system',
|
||||
portId,
|
||||
action: 'restore',
|
||||
entityType: 'document_folder',
|
||||
entityId: folder.id,
|
||||
oldValue: { name: folder.name, archivedAt: folder.archivedAt },
|
||||
newValue: { name: newName, archivedAt: null },
|
||||
metadata: { type: 'folder_entity_restored', entity: entityType, sourceEntityId: entityId },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -168,7 +168,7 @@ export async function updateYacht(
|
||||
|
||||
if (data.name !== undefined) {
|
||||
await syncEntityFolderName(portId, 'yacht', id, meta.userId).catch((err) => {
|
||||
logger.warn({ err, yachtId: id }, 'Failed to sync yacht folder name');
|
||||
logger.warn({ err, yachtId: id, portId }, 'Failed to sync yacht folder name');
|
||||
});
|
||||
}
|
||||
|
||||
@@ -193,8 +193,8 @@ export async function archiveYacht(id: string, portId: string, meta: AuditMeta)
|
||||
.set({ archivedAt: new Date() })
|
||||
.where(and(eq(yachts.id, id), eq(yachts.portId, portId)));
|
||||
|
||||
void applyEntityArchivedSuffix(portId, 'yacht', id).catch((err) => {
|
||||
logger.warn({ err, yachtId: id }, 'Failed to apply archived suffix to yacht folder');
|
||||
void applyEntityArchivedSuffix(portId, 'yacht', id, meta.userId).catch((err) => {
|
||||
logger.warn({ err, yachtId: id, portId }, 'Failed to apply archived suffix to yacht folder');
|
||||
});
|
||||
|
||||
void createAuditLog({
|
||||
|
||||
Reference in New Issue
Block a user