feat(client-groups): CM-1 data layer — groups entity, membership, service, Mailchimp scaffold
- client_groups + client_group_members tables (migration 0094, port_id cascade) - client_groups permission resource (view/manage) in catalog + role backfill - service: CRUD + wipe-and-rewrite membership + member email resolution - mailchimp.service scaffold: config reader + inert one-way sync (mapping deferred until the client's MC account is wired, per CM-1 decision) - 4 integration tests (CRUD, membership, email resolution, port-scope guard) Backend only — API routes + UI to follow. tsc clean, 1635 vitest pass. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
205
src/lib/services/client-groups.service.ts
Normal file
205
src/lib/services/client-groups.service.ts
Normal file
@@ -0,0 +1,205 @@
|
||||
/**
|
||||
* CM-1: client groups (mailing/segment lists) service.
|
||||
*
|
||||
* CRUD for `client_groups` + membership management on `client_group_members`,
|
||||
* plus a member viewer that resolves each client's primary email for the
|
||||
* copy-emails feature. All reads/writes are port-scoped. Membership replace is
|
||||
* a wipe-and-rewrite transaction (same shape as setEntityTags).
|
||||
*/
|
||||
|
||||
import { and, desc, eq, inArray, sql } from 'drizzle-orm';
|
||||
|
||||
import { createAuditLog, toAuditJson, type AuditMeta } from '@/lib/audit';
|
||||
import { db } from '@/lib/db';
|
||||
import { clientGroupMembers, clientGroups, clients } from '@/lib/db/schema';
|
||||
import { withTransaction } from '@/lib/db/utils';
|
||||
import { NotFoundError, ValidationError } from '@/lib/errors';
|
||||
import { syncGroupToMailchimp } from '@/lib/services/mailchimp.service';
|
||||
import type {
|
||||
CreateClientGroupInput,
|
||||
UpdateClientGroupInput,
|
||||
} from '@/lib/validators/client-groups';
|
||||
|
||||
export interface ClientGroupWithCount {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
color: string;
|
||||
mailchimpTag: string | null;
|
||||
memberCount: number;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface GroupMember {
|
||||
clientId: string;
|
||||
fullName: string;
|
||||
email: string | null;
|
||||
}
|
||||
|
||||
async function assertGroup(id: string, portId: string) {
|
||||
const group = await db.query.clientGroups.findFirst({
|
||||
where: and(eq(clientGroups.id, id), eq(clientGroups.portId, portId)),
|
||||
});
|
||||
if (!group || group.archivedAt) throw new NotFoundError('Client group not found');
|
||||
return group;
|
||||
}
|
||||
|
||||
export async function listClientGroups(portId: string): Promise<ClientGroupWithCount[]> {
|
||||
const groups = await db
|
||||
.select()
|
||||
.from(clientGroups)
|
||||
.where(and(eq(clientGroups.portId, portId), sql`${clientGroups.archivedAt} IS NULL`))
|
||||
.orderBy(desc(clientGroups.createdAt));
|
||||
|
||||
// Member counts in one grouped query (port-scoped).
|
||||
const counts = await db
|
||||
.select({ groupId: clientGroupMembers.groupId, n: sql<number>`count(*)::int` })
|
||||
.from(clientGroupMembers)
|
||||
.where(eq(clientGroupMembers.portId, portId))
|
||||
.groupBy(clientGroupMembers.groupId);
|
||||
const countMap = new Map(counts.map((c) => [c.groupId, c.n]));
|
||||
|
||||
return groups.map((g) => ({
|
||||
id: g.id,
|
||||
name: g.name,
|
||||
description: g.description,
|
||||
color: g.color,
|
||||
mailchimpTag: g.mailchimpTag,
|
||||
memberCount: countMap.get(g.id) ?? 0,
|
||||
createdAt: g.createdAt,
|
||||
updatedAt: g.updatedAt,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function getClientGroupById(id: string, portId: string) {
|
||||
return assertGroup(id, portId);
|
||||
}
|
||||
|
||||
export async function createClientGroup(
|
||||
portId: string,
|
||||
data: CreateClientGroupInput,
|
||||
meta: AuditMeta,
|
||||
) {
|
||||
const [group] = await db
|
||||
.insert(clientGroups)
|
||||
.values({
|
||||
portId,
|
||||
name: data.name,
|
||||
description: data.description ?? null,
|
||||
color: data.color ?? '#6B7280',
|
||||
mailchimpTag: data.mailchimpTag ?? null,
|
||||
})
|
||||
.returning();
|
||||
if (!group) throw new ValidationError('Failed to create client group');
|
||||
void createAuditLog({
|
||||
...meta,
|
||||
action: 'create',
|
||||
entityType: 'client_group',
|
||||
entityId: group.id,
|
||||
newValue: toAuditJson(group),
|
||||
});
|
||||
return group;
|
||||
}
|
||||
|
||||
export async function updateClientGroup(
|
||||
id: string,
|
||||
portId: string,
|
||||
data: UpdateClientGroupInput,
|
||||
meta: AuditMeta,
|
||||
) {
|
||||
await assertGroup(id, portId);
|
||||
const [updated] = await db
|
||||
.update(clientGroups)
|
||||
.set({
|
||||
...(data.name !== undefined ? { name: data.name } : {}),
|
||||
...(data.description !== undefined ? { description: data.description } : {}),
|
||||
...(data.color !== undefined ? { color: data.color } : {}),
|
||||
...(data.mailchimpTag !== undefined ? { mailchimpTag: data.mailchimpTag } : {}),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(and(eq(clientGroups.id, id), eq(clientGroups.portId, portId)))
|
||||
.returning();
|
||||
if (!updated) throw new NotFoundError('Client group not found');
|
||||
void createAuditLog({
|
||||
...meta,
|
||||
action: 'update',
|
||||
entityType: 'client_group',
|
||||
entityId: id,
|
||||
newValue: toAuditJson(data),
|
||||
});
|
||||
return updated;
|
||||
}
|
||||
|
||||
export async function archiveClientGroup(id: string, portId: string, meta: AuditMeta) {
|
||||
await assertGroup(id, portId);
|
||||
await db
|
||||
.update(clientGroups)
|
||||
.set({ archivedAt: new Date(), updatedAt: new Date() })
|
||||
.where(and(eq(clientGroups.id, id), eq(clientGroups.portId, portId)));
|
||||
void createAuditLog({
|
||||
...meta,
|
||||
action: 'archive',
|
||||
entityType: 'client_group',
|
||||
entityId: id,
|
||||
});
|
||||
}
|
||||
|
||||
/** Members of a group, each with their primary email (for copy-emails). */
|
||||
export async function listGroupMembers(groupId: string, portId: string): Promise<GroupMember[]> {
|
||||
await assertGroup(groupId, portId);
|
||||
const rows = await db
|
||||
.select({
|
||||
clientId: clients.id,
|
||||
fullName: clients.fullName,
|
||||
email: sql<string | null>`(
|
||||
SELECT cc.value FROM client_contacts cc
|
||||
WHERE cc.client_id = ${clients.id} AND cc.channel = 'email'
|
||||
ORDER BY cc.is_primary DESC
|
||||
LIMIT 1
|
||||
)`,
|
||||
})
|
||||
.from(clientGroupMembers)
|
||||
.innerJoin(clients, eq(clientGroupMembers.clientId, clients.id))
|
||||
.where(and(eq(clientGroupMembers.groupId, groupId), eq(clientGroupMembers.portId, portId)))
|
||||
.orderBy(clients.fullName);
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** Replace a group's membership with exactly `clientIds` (wipe-and-rewrite). */
|
||||
export async function setGroupMembers(
|
||||
groupId: string,
|
||||
portId: string,
|
||||
clientIds: string[],
|
||||
meta: AuditMeta,
|
||||
): Promise<void> {
|
||||
await assertGroup(groupId, portId);
|
||||
const unique = Array.from(new Set(clientIds));
|
||||
// Tenant-scope guard: every client must belong to this port.
|
||||
if (unique.length > 0) {
|
||||
const valid = await db
|
||||
.select({ id: clients.id })
|
||||
.from(clients)
|
||||
.where(and(inArray(clients.id, unique), eq(clients.portId, portId)));
|
||||
if (valid.length !== unique.length) {
|
||||
throw new ValidationError('One or more clients are not in this port');
|
||||
}
|
||||
}
|
||||
await withTransaction(async (tx) => {
|
||||
await tx.delete(clientGroupMembers).where(eq(clientGroupMembers.groupId, groupId));
|
||||
if (unique.length > 0) {
|
||||
await tx
|
||||
.insert(clientGroupMembers)
|
||||
.values(unique.map((clientId) => ({ groupId, clientId, portId })));
|
||||
}
|
||||
});
|
||||
void createAuditLog({
|
||||
...meta,
|
||||
action: 'update',
|
||||
entityType: 'client_group_members',
|
||||
entityId: groupId,
|
||||
newValue: toAuditJson({ clientIds: unique }),
|
||||
});
|
||||
// CM-1 Mailchimp: fire-and-forget one-way push (inert until configured).
|
||||
void syncGroupToMailchimp(groupId, portId).catch(() => {});
|
||||
}
|
||||
67
src/lib/services/mailchimp.service.ts
Normal file
67
src/lib/services/mailchimp.service.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* CM-1: Mailchimp Marketing API integration (one-way push, CRM → Mailchimp).
|
||||
*
|
||||
* SCOPE NOTE: per the locked CM-1 decision, the exact group → tag/segment
|
||||
* mapping is finalised only once we have the client's actual Mailchimp account.
|
||||
* So this module ships the config plumbing + an inert sync that no-ops until
|
||||
* (a) an admin stores an API key + audience ID and (b) the mapping is wired.
|
||||
* The members viewer + copy-emails features do NOT depend on Mailchimp.
|
||||
*
|
||||
* Settings keys (per-port, in system_settings):
|
||||
* - `mailchimp_api_key` (AES-encrypted at rest, like SMTP/IMAP creds)
|
||||
* - `mailchimp_audience_id` (the single audience all groups map into)
|
||||
*/
|
||||
|
||||
import { logger } from '@/lib/logger';
|
||||
import { getSetting } from '@/lib/services/settings.service';
|
||||
import { decrypt } from '@/lib/utils/encryption';
|
||||
|
||||
export interface MailchimpConfig {
|
||||
apiKey: string;
|
||||
audienceId: string;
|
||||
/** Datacenter prefix derived from the key suffix (e.g. `us21`). */
|
||||
serverPrefix: string;
|
||||
}
|
||||
|
||||
/** Resolve + decrypt the per-port Mailchimp config, or null when unset. */
|
||||
export async function getMailchimpConfig(portId: string): Promise<MailchimpConfig | null> {
|
||||
const keyRow = await getSetting('mailchimp_api_key', portId);
|
||||
const audRow = await getSetting('mailchimp_audience_id', portId);
|
||||
const encKey = typeof keyRow?.value === 'string' ? keyRow.value : null;
|
||||
const audienceId = typeof audRow?.value === 'string' ? audRow.value : null;
|
||||
if (!encKey || !audienceId) return null;
|
||||
let apiKey: string;
|
||||
try {
|
||||
apiKey = decrypt(encKey);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
// Mailchimp keys are `<hex>-<dc>`; the datacenter is the API host prefix.
|
||||
const serverPrefix = apiKey.split('-')[1] ?? '';
|
||||
if (!serverPrefix) return null;
|
||||
return { apiKey, audienceId, serverPrefix };
|
||||
}
|
||||
|
||||
export async function isMailchimpConfigured(portId: string): Promise<boolean> {
|
||||
return (await getMailchimpConfig(portId)) !== null;
|
||||
}
|
||||
|
||||
export type MailchimpSyncResult = { skipped: string } | { synced: true; count: number };
|
||||
|
||||
/**
|
||||
* Push a group's members to Mailchimp as a tag/segment on the port's audience.
|
||||
* Inert until configured AND the mapping is confirmed (see SCOPE NOTE).
|
||||
*/
|
||||
export async function syncGroupToMailchimp(
|
||||
groupId: string,
|
||||
portId: string,
|
||||
): Promise<MailchimpSyncResult> {
|
||||
const config = await getMailchimpConfig(portId);
|
||||
if (!config) return { skipped: 'not-configured' };
|
||||
// TODO(CM-1): mapping pending the client's Mailchimp account. Once confirmed,
|
||||
// upsert each member via
|
||||
// PUT https://{serverPrefix}.api.mailchimp.com/3.0/lists/{audienceId}/members/{md5(lowercased-email)}
|
||||
// then apply the group's tag. Only push subscribed/opted-in contacts (GDPR).
|
||||
logger.info({ groupId, portId }, 'Mailchimp sync requested (mapping pending client account)');
|
||||
return { skipped: 'mapping-pending' };
|
||||
}
|
||||
Reference in New Issue
Block a user