Files
pn-new-crm/src/lib/services/settings.service.ts
Matt Ciaccio 5d29bfc153 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>
2026-04-29 01:58:42 +02:00

101 lines
2.9 KiB
TypeScript

import { and, eq, isNull } from 'drizzle-orm';
import { db } from '@/lib/db';
import { systemSettings } from '@/lib/db/schema';
import { createAuditLog, type AuditMeta } from '@/lib/audit';
import { NotFoundError } from '@/lib/errors';
import { emitToRoom } from '@/lib/socket/server';
export async function listSettings(portId: string) {
// Get port-specific settings
const portSettings = await db
.select()
.from(systemSettings)
.where(eq(systemSettings.portId, portId))
.orderBy(systemSettings.key);
// Get global settings (portId is null)
const globalSettings = await db
.select()
.from(systemSettings)
.where(isNull(systemSettings.portId))
.orderBy(systemSettings.key);
return { portSettings, globalSettings };
}
export async function getSetting(key: string, portId: string) {
// Try port-specific first, fall back to global
const setting = await db.query.systemSettings.findFirst({
where: and(eq(systemSettings.key, key), eq(systemSettings.portId, portId)),
});
if (setting) return setting;
const global = await db.query.systemSettings.findFirst({
where: and(eq(systemSettings.key, key), isNull(systemSettings.portId)),
});
return global ?? null;
}
export async function upsertSetting(key: string, value: unknown, portId: string, meta: AuditMeta) {
const existing = await db.query.systemSettings.findFirst({
where: and(eq(systemSettings.key, key), eq(systemSettings.portId, portId)),
});
if (existing) {
await db
.update(systemSettings)
.set({ value, updatedBy: meta.userId, updatedAt: new Date() })
.where(and(eq(systemSettings.key, key), eq(systemSettings.portId, portId)));
} else {
await db.insert(systemSettings).values({
key,
value,
portId,
updatedBy: meta.userId,
});
}
void createAuditLog({
userId: meta.userId,
portId,
action: existing ? 'update' : 'create',
entityType: 'setting',
entityId: key,
oldValue: existing ? { value: existing.value } : undefined,
newValue: { value },
ipAddress: meta.ipAddress,
userAgent: meta.userAgent,
});
emitToRoom(`port:${portId}`, 'system:alert', {
alertType: 'setting:updated',
message: `Setting "${key}" updated`,
severity: 'info',
});
return { key, value, portId };
}
export async function deleteSetting(key: string, portId: string, meta: AuditMeta) {
const existing = await db.query.systemSettings.findFirst({
where: and(eq(systemSettings.key, key), eq(systemSettings.portId, portId)),
});
if (!existing) throw new NotFoundError('Setting');
await db
.delete(systemSettings)
.where(and(eq(systemSettings.key, key), eq(systemSettings.portId, portId)));
void createAuditLog({
userId: meta.userId,
portId,
action: 'delete',
entityType: 'setting',
entityId: key,
oldValue: { value: existing.value },
ipAddress: meta.ipAddress,
userAgent: meta.userAgent,
});
}