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

@@ -9,7 +9,7 @@ import { systemSettings } from '@/lib/db/schema/system';
import { clients, clientAddresses } from '@/lib/db/schema/clients';
import { companies, companyAddresses } from '@/lib/db/schema/companies';
import { buildListQuery } from '@/lib/db/query-builder';
import { createAuditLog } from '@/lib/audit';
import { createAuditLog, type AuditMeta } from '@/lib/audit';
import { diffEntity } from '@/lib/entity-diff';
import { withTransaction } from '@/lib/db/utils';
import { NotFoundError, ConflictError, ValidationError } from '@/lib/errors';
@@ -29,14 +29,6 @@ import type {
ListInvoicesInput,
} from '@/lib/validators/invoices';
// AuditMeta type expected by service functions
export interface ServiceAuditMeta {
userId: string;
portId: string;
ipAddress: string;
userAgent: string;
}
// ─── Auto-numbering (BR-041) ───────────────────────────────────────────────
async function generateInvoiceNumber(portId: string, tx: typeof db): Promise<string> {
@@ -218,11 +210,7 @@ export async function getInvoiceById(id: string, portId: string) {
// ─── Create (BR-041, BR-042, BR-045) ─────────────────────────────────────
export async function createInvoice(
portId: string,
data: CreateInvoiceInput,
meta: ServiceAuditMeta,
) {
export async function createInvoice(portId: string, data: CreateInvoiceInput, meta: AuditMeta) {
const invoice = await withTransaction(async (tx) => {
// Resolve the polymorphic billing entity (client | company). Throws
// ValidationError if the entity is missing or belongs to another tenant.
@@ -361,7 +349,7 @@ export async function updateInvoice(
id: string,
portId: string,
data: UpdateInvoiceInput,
meta: ServiceAuditMeta,
meta: AuditMeta,
) {
const existing = await getInvoiceById(id, portId);
if (existing.status !== 'draft') {
@@ -496,7 +484,7 @@ export async function updateInvoice(
// ─── Delete (draft only) ──────────────────────────────────────────────────
export async function deleteInvoice(id: string, portId: string, meta: ServiceAuditMeta) {
export async function deleteInvoice(id: string, portId: string, meta: AuditMeta) {
const existing = await getInvoiceById(id, portId);
if (existing.status !== 'draft') {
throw new ConflictError('Only draft invoices can be deleted');
@@ -527,7 +515,7 @@ export async function deleteInvoice(id: string, portId: string, meta: ServiceAud
// ─── Generate PDF ─────────────────────────────────────────────────────────
export async function generateInvoicePdf(id: string, portId: string, meta: ServiceAuditMeta) {
export async function generateInvoicePdf(id: string, portId: string, meta: AuditMeta) {
const invoice = await getInvoiceById(id, portId);
const [port] = await db
@@ -589,7 +577,7 @@ export async function generateInvoicePdf(id: string, portId: string, meta: Servi
// ─── Send invoice ─────────────────────────────────────────────────────────
export async function sendInvoice(id: string, portId: string, meta: ServiceAuditMeta) {
export async function sendInvoice(id: string, portId: string, meta: AuditMeta) {
const invoice = await getInvoiceById(id, portId);
// Generate PDF if not exists
@@ -637,7 +625,7 @@ export async function recordPayment(
id: string,
portId: string,
data: RecordPaymentInput,
meta: ServiceAuditMeta,
meta: AuditMeta,
) {
const existing = await getInvoiceById(id, portId);