import { Injectable } from '@nestjs/common'; import { AccessStore } from '../identity/access.store'; import type { Principal } from '../identity/identity.types'; import type { PageInput } from '../identity/identity.schemas'; import type { Prisma } from '../generated/prisma/client'; import { AppError } from '../common/errors/app-error'; import { assertReplay, commandHash } from '../common/idempotency'; import { recordAudit } from '../identity/audit'; import { CHANNELS, PURPOSES, CONSENT_NOTICES, type ConsentInput, type ConsentQuery, } from './consent.schemas'; const receiptSelect = { id: true, channel: true, purpose: true, granted: true, version: true, noticeVersion: true, createdAt: true, }; async function currentConsent( tx: Prisma.TransactionClient, organizationId: string, userId: string, query: ConsentQuery, ) { const decision = await tx.messagingConsentDecision.findFirst({ where: { organizationId, userId, ...query }, orderBy: { version: 'desc' }, select: { granted: true, version: true }, }); return { ...query, granted: decision?.granted ?? false, version: decision?.version ?? 0, }; } // Providers must call this inside their serialized dispatch transaction, not cache a staff preview. export async function messagingEligibility( tx: Prisma.TransactionClient, organizationId: string, userId: string, query: ConsentQuery, ) { const user = await tx.user.findFirst({ where: { id: userId, organizationId }, select: { status: true }, }); if (!user) throw new AppError('MESSAGING_RECIPIENT_NOT_FOUND'); const current = await currentConsent(tx, organizationId, userId, query); return { ...current, eligible: current.granted && user.status === 'ACTIVE' }; } @Injectable() export class ConsentStore { constructor(private readonly access: AccessStore) {} get(actor: Principal) { return this.access.mutate(actor, null, async (tx) => { const preferences = []; for (const channel of CHANNELS) for (const purpose of PURPOSES) preferences.push( await currentConsent(tx, actor.organizationId, actor.userId, { channel, purpose, }), ); return { notices: CONSENT_NOTICES, preferences }; }); } history(actor: Principal, page: PageInput) { return this.access.mutate(actor, null, (tx) => tx.messagingConsentDecision.findMany({ where: { userId: actor.userId, organizationId: actor.organizationId }, orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], skip: page.offset, take: page.limit, select: receiptSelect, }), ); } record(actor: Principal, input: ConsentInput) { const query = { channel: input.channel, purpose: input.purpose }; const requestHash = commandHash( input.channel, input.purpose, Number(input.granted), input.version, input.noticeVersion ?? '', ); return this.access.mutate(actor, null, async (tx) => { const scope = { userId: actor.userId, organizationId: actor.organizationId, }; const previous = await tx.messagingConsentDecision.findUnique({ where: { userId_organizationId_idempotencyKey: { ...scope, idempotencyKey: input.idempotencyKey, }, }, select: { ...receiptSelect, requestHash: true }, }); const current = await currentConsent( tx, actor.organizationId, actor.userId, query, ); if (previous) { const { requestHash: previousHash, ...decision } = previous; assertReplay(previousHash, requestHash); return { decision, current }; } if (current.version !== input.version) throw new AppError('CONSENT_CHANGED'); const decision = await tx.messagingConsentDecision.create({ data: { ...scope, ...query, granted: input.granted, version: input.version + 1, noticeVersion: input.noticeVersion ?? null, idempotencyKey: input.idempotencyKey, requestHash, }, select: receiptSelect, }); await recordAudit( tx, actor.organizationId, actor.userId, 'messaging.consent.recorded', decision.id, ); return { decision, current: { ...query, granted: decision.granted, version: decision.version, }, }; }); } eligibility(actor: Principal, userId: string, query: ConsentQuery) { return this.access.mutate(actor, 'messaging.read', (tx) => messagingEligibility(tx, actor.organizationId, userId, query), ); } }