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>
104 lines
3.2 KiB
TypeScript
104 lines
3.2 KiB
TypeScript
import { eq } from 'drizzle-orm';
|
|
|
|
import { db } from '@/lib/db';
|
|
import { ports } from '@/lib/db/schema';
|
|
import type { PortSettings } from '@/lib/db/schema/ports';
|
|
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';
|
|
|
|
export async function listPorts() {
|
|
return db.select().from(ports).orderBy(ports.name);
|
|
}
|
|
|
|
export async function getPort(id: string) {
|
|
const port = await db.query.ports.findFirst({
|
|
where: eq(ports.id, id),
|
|
});
|
|
if (!port) throw new NotFoundError('Port');
|
|
return port;
|
|
}
|
|
|
|
export async function createPort(data: CreatePortInput, meta: AuditMeta) {
|
|
const existing = await db.query.ports.findFirst({
|
|
where: eq(ports.slug, data.slug),
|
|
});
|
|
if (existing) {
|
|
throw new ConflictError(`A port with slug "${data.slug}" already exists`);
|
|
}
|
|
|
|
const [port] = await db
|
|
.insert(ports)
|
|
.values({
|
|
name: data.name,
|
|
slug: data.slug,
|
|
logoUrl: data.logoUrl ?? null,
|
|
primaryColor: data.primaryColor ?? null,
|
|
defaultCurrency: data.defaultCurrency,
|
|
timezone: data.timezone,
|
|
})
|
|
.returning();
|
|
|
|
void createAuditLog({
|
|
userId: meta.userId,
|
|
portId: meta.portId,
|
|
action: 'create',
|
|
entityType: 'port',
|
|
entityId: port!.id,
|
|
newValue: { name: port!.name, slug: port!.slug },
|
|
ipAddress: meta.ipAddress,
|
|
userAgent: meta.userAgent,
|
|
});
|
|
|
|
return port!;
|
|
}
|
|
|
|
export async function updatePort(id: string, data: UpdatePortInput, meta: AuditMeta) {
|
|
const port = await db.query.ports.findFirst({
|
|
where: eq(ports.id, id),
|
|
});
|
|
if (!port) throw new NotFoundError('Port');
|
|
|
|
if (data.slug && data.slug !== port.slug) {
|
|
const conflict = await db.query.ports.findFirst({
|
|
where: eq(ports.slug, data.slug),
|
|
});
|
|
if (conflict) {
|
|
throw new ConflictError(`A port with slug "${data.slug}" already exists`);
|
|
}
|
|
}
|
|
|
|
const updates: Record<string, unknown> = { updatedAt: new Date() };
|
|
if (data.name !== undefined) updates.name = data.name;
|
|
if (data.slug !== undefined) updates.slug = data.slug;
|
|
if (data.logoUrl !== undefined) updates.logoUrl = data.logoUrl;
|
|
if (data.primaryColor !== undefined) updates.primaryColor = data.primaryColor;
|
|
if (data.defaultCurrency !== undefined) updates.defaultCurrency = data.defaultCurrency;
|
|
if (data.timezone !== undefined) updates.timezone = data.timezone;
|
|
if (data.isActive !== undefined) updates.isActive = data.isActive;
|
|
if (data.settings !== undefined) updates.settings = data.settings as PortSettings;
|
|
|
|
const [updated] = await db.update(ports).set(updates).where(eq(ports.id, id)).returning();
|
|
|
|
void createAuditLog({
|
|
userId: meta.userId,
|
|
portId: meta.portId,
|
|
action: 'update',
|
|
entityType: 'port',
|
|
entityId: id,
|
|
oldValue: { name: port.name, slug: port.slug, isActive: port.isActive },
|
|
newValue: { name: updated!.name, slug: updated!.slug, isActive: updated!.isActive },
|
|
ipAddress: meta.ipAddress,
|
|
userAgent: meta.userAgent,
|
|
});
|
|
|
|
emitToRoom(`port:${id}`, 'system:alert', {
|
|
alertType: 'port:updated',
|
|
message: `Port "${updated!.name}" updated`,
|
|
severity: 'info',
|
|
});
|
|
|
|
return updated!;
|
|
}
|