refactor(services): centralize AuditMeta + transactional setEntityTags helper

The same `interface AuditMeta { userId; portId; ipAddress; userAgent }`
was duplicated in 26 service files. Move the canonical definition into
`@/lib/audit` next to the related types and update every service to
import it. `ServiceAuditMeta` (the alias used in invoices.ts and
expenses.ts) collapses into the same name.

Tag CRUD across clients/companies/yachts/interests/berths followed an
identical wipe-then-rewrite recipe with two latent issues: the delete
and insert weren't wrapped in a transaction (a partial failure left
the entity with zero tags) and the audit-log payload shape diverged
(`newValue: { tagIds }` for clients/yachts/companies but
`metadata: { type: 'tags_updated', tagIds }` for interests/berths).

Extract `setEntityTags` in `entity-tags.helper.ts` that performs the
delete+insert inside a single transaction, normalizes the audit payload
to `newValue: { tagIds }`, and dispatches the per-entity socket event
through a switch so `ServerToClientEvents` typing stays intact.

The five `setXTags(...)` service functions now do parent-row tenant
verification and delegate the join-table work + side effects.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Matt Ciaccio
2026-04-29 01:58:42 +02:00
parent 43f68ca093
commit 5d29bfc153
29 changed files with 234 additions and 409 deletions

View File

@@ -2,20 +2,13 @@ import { and, eq, count } from 'drizzle-orm';
import { db } from '@/lib/db';
import { customFieldDefinitions, customFieldValues } from '@/lib/db/schema/system';
import { createAuditLog } from '@/lib/audit';
import { createAuditLog, type AuditMeta } from '@/lib/audit';
import { NotFoundError, ValidationError, ConflictError } from '@/lib/errors';
import type { CreateFieldInput, UpdateFieldInput } from '@/lib/validators/custom-fields';
import type { CustomFieldDefinition } from '@/lib/db/schema/system';
// ─── Types ────────────────────────────────────────────────────────────────────
interface AuditMeta {
userId: string;
portId: string;
ipAddress: string;
userAgent: string;
}
// ─── Value Validation ─────────────────────────────────────────────────────────
function validateCustomFieldValue(
@@ -35,16 +28,12 @@ function validateCustomFieldValue(
case 'number':
return typeof value !== 'number' || isNaN(value) ? 'Must be a number' : null;
case 'date':
return typeof value !== 'string' || isNaN(Date.parse(value))
? 'Must be a valid date'
: null;
return typeof value !== 'string' || isNaN(Date.parse(value)) ? 'Must be a valid date' : null;
case 'boolean':
return typeof value !== 'boolean' ? 'Must be true or false' : null;
case 'select': {
const options = (definition.selectOptions as string[] | null) ?? [];
return !options.includes(value as string)
? `Must be one of: ${options.join(', ')}`
: null;
return !options.includes(value as string) ? `Must be one of: ${options.join(', ')}` : null;
}
default:
return 'Unknown field type';
@@ -134,10 +123,7 @@ export async function updateDefinition(
}
const existing = await db.query.customFieldDefinitions.findFirst({
where: and(
eq(customFieldDefinitions.id, fieldId),
eq(customFieldDefinitions.portId, portId),
),
where: and(eq(customFieldDefinitions.id, fieldId), eq(customFieldDefinitions.portId, portId)),
});
if (!existing) {
throw new NotFoundError('Custom field definition');
@@ -189,10 +175,7 @@ export async function deleteDefinition(
meta: AuditMeta,
) {
const existing = await db.query.customFieldDefinitions.findFirst({
where: and(
eq(customFieldDefinitions.id, fieldId),
eq(customFieldDefinitions.portId, portId),
),
where: and(eq(customFieldDefinitions.id, fieldId), eq(customFieldDefinitions.portId, portId)),
});
if (!existing) {
throw new NotFoundError('Custom field definition');
@@ -206,9 +189,7 @@ export async function deleteDefinition(
const valueCount = countResult[0]?.count ?? 0;
// Delete definition — CASCADE handles values
await db
.delete(customFieldDefinitions)
.where(eq(customFieldDefinitions.id, fieldId));
await db.delete(customFieldDefinitions).where(eq(customFieldDefinitions.id, fieldId));
void createAuditLog({
userId,