Files
pn-new-crm/src/lib/services/email-accounts.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

165 lines
5.5 KiB
TypeScript

import { and, eq } from 'drizzle-orm';
import { db } from '@/lib/db';
import { emailAccounts } from '@/lib/db/schema/email';
import { encrypt, decrypt } from '@/lib/utils/encryption';
import { createAuditLog, type AuditMeta } from '@/lib/audit';
import { NotFoundError, ForbiddenError } from '@/lib/errors';
import type { ConnectAccountInput, ToggleAccountInput } from '@/lib/validators/email';
// ─── Types ────────────────────────────────────────────────────────────────────
type AccountWithoutCredentials = Omit<typeof emailAccounts.$inferSelect, 'credentialsEnc'>;
// ─── Helpers ──────────────────────────────────────────────────────────────────
function stripCredentials(account: typeof emailAccounts.$inferSelect): AccountWithoutCredentials {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { credentialsEnc: _, ...safe } = account;
return safe;
}
// ─── List ─────────────────────────────────────────────────────────────────────
export async function listAccounts(
userId: string,
portId: string,
): Promise<AccountWithoutCredentials[]> {
const accounts = await db
.select()
.from(emailAccounts)
.where(and(eq(emailAccounts.userId, userId), eq(emailAccounts.portId, portId)));
return accounts.map(stripCredentials);
}
// ─── Connect ──────────────────────────────────────────────────────────────────
export async function connectAccount(
userId: string,
portId: string,
data: ConnectAccountInput,
audit: AuditMeta,
): Promise<AccountWithoutCredentials> {
const credentialsEnc = encrypt(
JSON.stringify({ username: data.username, password: data.password }),
);
const inserted = await db
.insert(emailAccounts)
.values({
userId,
portId,
provider: data.provider,
emailAddress: data.emailAddress,
smtpHost: data.smtpHost,
smtpPort: data.smtpPort,
imapHost: data.imapHost,
imapPort: data.imapPort,
credentialsEnc,
isActive: true,
})
.returning();
const account = inserted[0];
if (!account) throw new Error('Failed to insert email account');
void createAuditLog({
userId: audit.userId,
portId: audit.portId,
action: 'create',
entityType: 'email_account',
entityId: account.id,
metadata: { emailAddress: data.emailAddress, provider: data.provider },
ipAddress: audit.ipAddress,
userAgent: audit.userAgent,
});
return stripCredentials(account);
}
// ─── Toggle ───────────────────────────────────────────────────────────────────
export async function toggleAccount(
accountId: string,
userId: string,
data: ToggleAccountInput,
): Promise<AccountWithoutCredentials> {
const existing = await db.query.emailAccounts.findFirst({
where: eq(emailAccounts.id, accountId),
});
if (!existing) {
throw new NotFoundError('Email account');
}
if (existing.userId !== userId) {
throw new ForbiddenError('You do not own this email account');
}
const updatedRows = await db
.update(emailAccounts)
.set({ isActive: data.isActive, updatedAt: new Date() })
.where(eq(emailAccounts.id, accountId))
.returning();
const updated = updatedRows[0];
if (!updated) throw new Error('Failed to update email account');
return stripCredentials(updated);
}
// ─── Disconnect ───────────────────────────────────────────────────────────────
export async function disconnectAccount(
accountId: string,
userId: string,
audit: AuditMeta,
): Promise<void> {
const existing = await db.query.emailAccounts.findFirst({
where: eq(emailAccounts.id, accountId),
});
if (!existing) {
throw new NotFoundError('Email account');
}
if (existing.userId !== userId) {
throw new ForbiddenError('You do not own this email account');
}
await db.delete(emailAccounts).where(eq(emailAccounts.id, accountId));
void createAuditLog({
userId: audit.userId,
portId: audit.portId,
action: 'delete',
entityType: 'email_account',
entityId: accountId,
metadata: { emailAddress: existing.emailAddress },
ipAddress: audit.ipAddress,
userAgent: audit.userAgent,
});
}
// ─── Get Decrypted Credentials (INTERNAL ONLY) ────────────────────────────────
export async function getDecryptedCredentials(
accountId: string,
): Promise<{ username: string; password: string }> {
const account = await db.query.emailAccounts.findFirst({
where: eq(emailAccounts.id, accountId),
});
if (!account) {
throw new NotFoundError('Email account');
}
const { username, password } = JSON.parse(decrypt(account.credentialsEnc)) as {
username: string;
password: string;
};
return { username, password };
}