feat(api,web): fundação de Documentos + EDEN Parceiros/Assinante com login real

Continuação da leva "pelo menos mais 20 etapas" — 2 subagentes em paralelo.

## Documents (apps/api/src/documents/ + migration documents)

Metade "templates + geração" do eden.md módulo 4 (§1.1-1.3): document_templates,
document_template_versions (ciclo draft→publish, no máximo 1 rascunho por
template via índice único parcial, versão publicada imutável), document_generations
(idempotente por (template_version_id, origem), CHECK de origem única). Motor de
merge de variáveis ({{chave}}→valor, nunca lança exceção) como função pura
testável. A metade de Assinatura Eletrônica (envelopes, signatários, OTP,
cadeia de auditoria hash-chain — eden.md §1.4-1.9/§5-7, 9 tabelas satélite)
fica deliberadamente fora — grande e sensível demais para dividir espaço
com esta leva, fica para uma leva própria. PDF real via Chromium também
deferido; document_generations grava rendered_html, pdf_* ficam NULL.

## EDEN Parceiros / EDEN Assinante (apps/reseller-web, apps/subscriber-web)

Replicam o shell autenticado do core-web (leva anterior): login real com
suporte a MFA, sessão, AppShell do Design System — trocando só
applicationKey ("reseller"/"subscriber"), título e chave de localStorage
da sessão. As duas telas "Bootstrap da Fase 1" saem de circulação.

Testado ao vivo contra os containers reais: ciclo completo de template
(criar→draft→409 no segundo draft→editar→publicar→gerar documento com
merge de variáveis funcionando→regeneração idempotente reaproveita o
registro), e login via /v1/auth/login com applicationKey "reseller"/
"subscriber" retornando tokens válidos nos 2 portais reconstruídos.
pnpm turbo run typecheck build (28/28), pnpm --filter @eden/api test
(30/30, sem regressão), trilha de auditoria conferida no Postgres.

Claude-Session: https://claude.ai/code/session_01BcWWuKfykGtUweXmHD6cKx

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-03 17:55:52 -03:00
parent eff515b70d
commit 4d67fe5f1a
42 changed files with 2242 additions and 20 deletions

View File

@@ -0,0 +1,161 @@
/**
* Document Templates + Generation — eden.md module 4 "Templates de
* Documentos, Geração de PDF e Assinatura Eletrônica", lines 2210-2825.
*
* This migration builds ONLY the "templates + generation" half of that
* module (eden.md sections 1.1, 1.2, 1.3):
*
* - document_templates (this migration)
* - document_template_versions (this migration)
* - document_generations (this migration)
*
* Deliberately DEFERRED to a future dedicated leva — the "Assinatura
* Eletrônica" half of eden.md module 4 (sections 1.4-1.9, 5, 6, 7):
* signature_envelopes, signature_signers, signature_documents,
* signature_otp_challenges, signature_audit_events (hash-chain), and the
* remaining satellite tables. That half is cryptographically/legally
* sensitive (hash-chain algorithm, HMAC-protected OTP codes, append-only
* triggers) and large (9 satellite tables) — it needs its own dedicated
* migration and review, not a rider on this one.
*
* Also NOT ported here (see eden.md §1.1): the legacy `body`/
* `updated_by_id` columns on document_templates — client-side
* (html2canvas+jsPDF) text-with-{{placeholder}} storage from the OLD
* generation pipeline, superseded by editor_content (Tiptap JSON) for
* the new visual editor. Not seeded here either: the 7 real production
* templates (eden.md §1.1 table) — that's Handix production data to be
* migrated later, not schema.
*
* Circular-reference resolution (document_templates.current_version_id
* points at document_template_versions, which itself references
* document_templates.id): document_templates is created first WITHOUT a
* foreign key on current_version_id (column present, unconstrained),
* then document_template_versions is created referencing
* document_templates(id), and finally an ALTER TABLE below adds the
* deferred foreign key from document_templates.current_version_id to
* document_template_versions(id). No rows exist yet at that point, so
* there is nothing to backfill.
*/
exports.shorthands = undefined;
exports.up = (pgm) => {
pgm.sql(`
-- =====================================================================
-- document_templates - eden.md section 1.1. Never stores current
-- content directly; always points at a version via current_version_id.
-- =====================================================================
CREATE TABLE document_templates (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
key TEXT UNIQUE NOT NULL,
name TEXT NOT NULL,
doc_group TEXT NOT NULL CHECK (doc_group IN ('cliente', 'revenda')),
active BOOLEAN NOT NULL DEFAULT true,
current_version_id UUID,
created_by UUID REFERENCES users(id)
);
COMMENT ON TABLE document_templates IS
'Modelo de documento (eden.md secao 1.1). current_version_id aponta para a versao PUBLICADA vigente em document_template_versions; NULL enquanto o template nunca foi publicado. A FK de current_version_id e adicionada mais abaixo, depois que document_template_versions existe (dependencia circular resolvida com ALTER TABLE). key e um identificador estavel fixado pelo sistema (ex.: client_software_contract), nunca editavel pelo usuario. Os campos legados body/updated_by_id do OrcaFacil (texto puro com placeholders, geracao client-side) nao foram portados aqui: pertencem ao pipeline antigo, ja substituido pelo editor visual Tiptap (editor_content em document_template_versions).';
COMMENT ON COLUMN document_templates.doc_group IS
'Agrupa a listagem na UI: cliente (contratos/termos voltados ao cliente final) ou revenda (contratos/termos de canal).';
CREATE TRIGGER trg_document_templates_updated_at BEFORE UPDATE ON document_templates
FOR EACH ROW EXECUTE FUNCTION set_updated_at();
CREATE INDEX idx_document_templates_doc_group ON document_templates(doc_group);
-- =====================================================================
-- document_template_versions - eden.md section 1.2. Versionamento
-- IMUTAVEL assim que status='published'.
-- =====================================================================
CREATE TABLE document_template_versions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
template_id UUID NOT NULL REFERENCES document_templates(id) ON DELETE CASCADE,
version INTEGER NOT NULL,
status TEXT NOT NULL CHECK (status IN ('draft', 'published')),
editor_content JSONB NOT NULL,
html_content TEXT DEFAULT '',
css_content TEXT,
page_config JSONB DEFAULT '{}',
created_by UUID REFERENCES users(id),
published_at TIMESTAMPTZ,
published_by UUID REFERENCES users(id),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (template_id, version)
);
COMMENT ON TABLE document_template_versions IS
'Versionamento de conteudo de um document_template (eden.md secao 1.2) - imutavel assim que status=published (nenhuma rota edita uma versao publicada). editor_content e aceito aqui como JSONB generico vindo do cliente da API - esta leva de backend NAO valida a arvore Tiptap (responsabilidade do editor visual, que ainda nao existe). html_content e recalculado a cada PATCH .../draft por uma funcao propria SIMPLIFICADA (apps/api/src/documents/editor-content-renderer.ts) - NAO e o renderToHtml completo do Tiptap do legado (eden.md secao 2.2): se editor_content tiver uma propriedade de nivel raiz plainText (string), ela e usada como texto; senao um placeholder deterministico e serializado. E um stand-in ate o editor visual real existir.';
COMMENT ON COLUMN document_template_versions.status IS
'draft ou published. Invariante central (eden.md secao 1.2): no maximo 1 draft por template - reforcada pelo indice unico parcial uq_document_template_versions_one_draft abaixo. Uma versao published e imutavel; publicar de novo exige um novo draft (POST .../draft), nunca reescreve uma ja publicada.';
COMMENT ON COLUMN document_template_versions.version IS
'Sequencial por template (UNIQUE(template_id, version)), atribuido pela camada de repositorio como MAX(version)+1 no momento da criacao do draft - nunca reaproveita numero, mesmo que versoes antigas nunca sejam apagadas.';
-- Invariante central do eden.md secao 1.2: no maximo 1 rascunho por
-- template, a qualquer momento.
CREATE UNIQUE INDEX uq_document_template_versions_one_draft
ON document_template_versions(template_id) WHERE status = 'draft';
CREATE INDEX idx_document_template_versions_template ON document_template_versions(template_id);
-- Dependencia circular resolvida: agora que document_template_versions
-- existe, adiciona a FK de current_version_id.
ALTER TABLE document_templates
ADD CONSTRAINT fk_document_templates_current_version
FOREIGN KEY (current_version_id) REFERENCES document_template_versions(id);
-- =====================================================================
-- document_generations - eden.md section 1.3. Snapshot de cada PDF
-- definitivo emitido - nunca recalculado depois.
-- =====================================================================
CREATE TABLE document_generations (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
template_id UUID NOT NULL REFERENCES document_templates(id),
template_version_id UUID NOT NULL REFERENCES document_template_versions(id),
client_registration_id UUID,
reseller_id UUID,
render_context JSONB DEFAULT '{}',
rendered_html TEXT,
pdf_s3_key TEXT,
pdf_sha256 TEXT,
pdf_size_bytes INTEGER,
status TEXT NOT NULL DEFAULT 'generating' CHECK (status IN ('generating', 'final', 'error')),
error_message TEXT,
generated_by UUID REFERENCES users(id),
CONSTRAINT chk_document_generations_one_source CHECK (
(client_registration_id IS NOT NULL)::int + (reseller_id IS NOT NULL)::int = 1
)
);
COMMENT ON TABLE document_generations IS
'Snapshot imutavel de cada geracao de documento (eden.md secao 1.3). client_registration_id/reseller_id SEM FK: client_registrations/resellers podem nao existir neste worktree isolado - mesmo padrao de FK cruzada adiada usado por Quotes/Contracts/Support neste monorepo. Nesta leva NAO ha renderizacao real de PDF (Playwright/Chromium fica para uma leva futura - eden.md secao 4.1): pdf_s3_key/pdf_sha256/pdf_size_bytes permanecem sempre NULL aqui; a linha e gravada com status=final e rendered_html preenchido assim que o merge de variaveis (apps/api/src/documents/merge-engine.ts) roda sobre o texto extraido de editor_content.plainText da versao publicada.';
COMMENT ON CONSTRAINT chk_document_generations_one_source ON document_generations IS
'Exatamente uma origem preenchida (client_registration_id XOR reseller_id) - eden.md secao 1.3. O caso especial do Termo de Cessao (cedente/cessionaria, cessionaria sem coluna propria) nao se aplica a esta leva (sem seed/uso de templates reais ainda).';
CREATE INDEX idx_document_generations_template_version ON document_generations(template_version_id);
CREATE INDEX idx_document_generations_client ON document_generations(client_registration_id);
CREATE INDEX idx_document_generations_reseller ON document_generations(reseller_id);
-- Idempotencia simplificada (eden.md secao 1.3 descreve uma regra mais
-- rica com force/extra_fields - fora do escopo desta leva): no maximo
-- uma geracao status=final por (template_version_id, origem). Reforca
-- em nivel de banco a checagem "ja existe -> devolve o existente" feita
-- na camada de repositorio (packages/database/src/repositories/documents.ts).
CREATE UNIQUE INDEX uq_document_generations_client_final
ON document_generations(template_version_id, client_registration_id)
WHERE status = 'final' AND client_registration_id IS NOT NULL;
CREATE UNIQUE INDEX uq_document_generations_reseller_final
ON document_generations(template_version_id, reseller_id)
WHERE status = 'final' AND reseller_id IS NOT NULL;
`);
};
exports.down = (pgm) => {
pgm.sql(`
DROP TABLE IF EXISTS document_generations;
ALTER TABLE IF EXISTS document_templates DROP CONSTRAINT IF EXISTS fk_document_templates_current_version;
DROP TABLE IF EXISTS document_template_versions;
DROP TABLE IF EXISTS document_templates;
`);
};

View File

@@ -15,6 +15,7 @@ export * as supportTicketsRepo from "./repositories/support-tickets.js";
export * as hrTimeclockRepo from "./repositories/hr-timeclock.js";
export * as fiscalRepo from "./repositories/fiscal.js";
export * as billingRepo from "./repositories/billing.js";
export * as documentsRepo from "./repositories/documents.js";
export {
listLeads,
getLead,
@@ -163,3 +164,17 @@ export type {
ListBillingRunsFilter,
ListInvoicesFilter,
} from "./repositories/billing.js";
export type {
DocGroup,
TemplateVersionStatus,
GenerationStatus,
DocumentTemplate,
DocumentTemplateVersion,
DocumentTemplateWithVersions,
DocumentGeneration,
ListTemplatesFilter,
CreateTemplateInput,
UpdateDraftInput,
CreateGenerationInput,
ListGenerationsFilter,
} from "./repositories/documents.js";

View File

@@ -0,0 +1,495 @@
import { query, withTransaction } from "../pool.js";
/**
* Document Templates + Generation — eden.md module 4 "Templates de
* Documentos, Geração de PDF e Assinatura Eletrônica", sections 1.1-1.3
* (lines 2210-2825). Only the "templates + generation" half of that
* module — Assinatura Eletrônica (sections 1.4-1.9) is explicitly
* deferred to a future dedicated leva (see the migration's header
* comment for the full rationale).
*
* Mirrors the conventions of contracts.ts (withTransaction for
* multi-statement writes that must commit/rollback together, custom
* *Error classes mapped to HTTP status in the service layer, snake_case
* rows).
*
* `html_content` on document_template_versions is always recomputed by
* the CALLER (apps/api/src/documents/editor-content-renderer.ts) and
* passed into createDraft/updateDraft as a `renderHtml` callback rather
* than imported here directly — this package must stay free of any
* dependency on the API app layer.
*/
export type DocGroup = "cliente" | "revenda";
export type TemplateVersionStatus = "draft" | "published";
export type GenerationStatus = "generating" | "final" | "error";
export interface DocumentTemplate {
id: string;
created_at: Date;
updated_at: Date;
key: string;
name: string;
doc_group: DocGroup;
active: boolean;
current_version_id: string | null;
created_by: string | null;
}
export interface DocumentTemplateVersion {
id: string;
template_id: string;
version: number;
status: TemplateVersionStatus;
editor_content: unknown;
html_content: string;
css_content: string | null;
page_config: Record<string, unknown>;
created_by: string | null;
published_at: Date | null;
published_by: string | null;
created_at: Date;
}
export interface DocumentTemplateWithVersions extends DocumentTemplate {
versions: DocumentTemplateVersion[];
}
export interface DocumentGeneration {
id: string;
created_at: Date;
template_id: string;
template_version_id: string;
client_registration_id: string | null;
reseller_id: string | null;
render_context: Record<string, unknown>;
rendered_html: string | null;
pdf_s3_key: string | null;
pdf_sha256: string | null;
pdf_size_bytes: number | null;
status: GenerationStatus;
error_message: string | null;
generated_by: string | null;
}
export class TemplateNotFoundError extends Error {
constructor(public readonly templateId: string) {
super(`Document template ${templateId} not found`);
this.name = "TemplateNotFoundError";
}
}
export class TemplateKeyConflictError extends Error {
constructor(public readonly key: string) {
super(`Document template key '${key}' already in use`);
this.name = "TemplateKeyConflictError";
}
}
/** eden.md §1.2 invariant: at most one draft version per template. */
export class DraftAlreadyExistsError extends Error {
constructor(public readonly templateId: string) {
super(`Template ${templateId} already has a draft version`);
this.name = "DraftAlreadyExistsError";
}
}
export class DraftNotFoundError extends Error {
constructor(public readonly templateId: string) {
super(`Template ${templateId} has no draft version`);
this.name = "DraftNotFoundError";
}
}
function isUniqueViolation(err: unknown): boolean {
return typeof err === "object" && err !== null && (err as { code?: string }).code === "23505";
}
// ---------------------------------------------------------------------------
// document_templates
// ---------------------------------------------------------------------------
export interface ListTemplatesFilter {
docGroup?: DocGroup;
active?: boolean;
}
export async function listTemplates(filter: ListTemplatesFilter = {}): Promise<DocumentTemplate[]> {
const conditions: string[] = [];
const params: unknown[] = [];
if (filter.docGroup) {
params.push(filter.docGroup);
conditions.push(`doc_group = $${params.length}`);
}
if (filter.active !== undefined) {
params.push(filter.active);
conditions.push(`active = $${params.length}`);
}
const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
const { rows } = await query<DocumentTemplate>(
`SELECT * FROM document_templates ${where} ORDER BY name ASC`,
params,
);
return rows;
}
export async function getTemplateById(id: string): Promise<DocumentTemplate | null> {
const { rows } = await query<DocumentTemplate>("SELECT * FROM document_templates WHERE id = $1", [id]);
return rows[0] ?? null;
}
export async function listTemplateVersions(templateId: string): Promise<DocumentTemplateVersion[]> {
const { rows } = await query<DocumentTemplateVersion>(
"SELECT * FROM document_template_versions WHERE template_id = $1 ORDER BY version DESC",
[templateId],
);
return rows;
}
export async function getTemplateWithVersions(id: string): Promise<DocumentTemplateWithVersions | null> {
const template = await getTemplateById(id);
if (!template) return null;
const versions = await listTemplateVersions(id);
return { ...template, versions };
}
export interface CreateTemplateInput {
key: string;
name: string;
docGroup: DocGroup;
createdBy?: string | null;
}
/**
* `current_version_id` always starts NULL — a template is never created
* already pointing at a version (eden.md §1.1); it only gets one via
* publishDraft().
*/
export async function createTemplate(input: CreateTemplateInput): Promise<DocumentTemplate> {
try {
const { rows } = await query<DocumentTemplate>(
`INSERT INTO document_templates (key, name, doc_group, created_by)
VALUES ($1, $2, $3, $4)
RETURNING *`,
[input.key, input.name, input.docGroup, input.createdBy ?? null],
);
const created = rows[0];
if (!created) throw new Error("failed to create document template");
return created;
} catch (err) {
if (isUniqueViolation(err)) throw new TemplateKeyConflictError(input.key);
throw err;
}
}
// ---------------------------------------------------------------------------
// document_template_versions — draft/publish lifecycle (eden.md §1.2)
// ---------------------------------------------------------------------------
const EMPTY_DOC_CONTENT: unknown = { type: "doc", content: [{ type: "paragraph", content: [] }] };
/**
* Creates a new draft: clones editor_content/css_content/page_config
* from the currently published version (current_version_id), or starts
* from an empty Tiptap document if the template was never published.
* `version` is always MAX(version)+1 for the template — numbers are
* never reused, even though old versions are never deleted. Throws
* TemplateNotFoundError / DraftAlreadyExistsError instead of silently
* no-oping; the service layer maps these to 404/409.
*/
export async function createDraft(
templateId: string,
createdBy: string | null,
renderHtml: (editorContent: unknown) => string,
): Promise<DocumentTemplateVersion> {
return withTransaction(async (client) => {
const { rows: templateRows } = await client.query<DocumentTemplate>(
"SELECT * FROM document_templates WHERE id = $1 FOR UPDATE",
[templateId],
);
const template = templateRows[0];
if (!template) throw new TemplateNotFoundError(templateId);
const { rows: draftRows } = await client.query(
"SELECT id FROM document_template_versions WHERE template_id = $1 AND status = 'draft'",
[templateId],
);
if (draftRows[0]) throw new DraftAlreadyExistsError(templateId);
let editorContent: unknown = EMPTY_DOC_CONTENT;
let cssContent: string | null = null;
let pageConfig: Record<string, unknown> = {};
if (template.current_version_id) {
const { rows: pubRows } = await client.query<{
editor_content: unknown;
css_content: string | null;
page_config: Record<string, unknown>;
}>(
"SELECT editor_content, css_content, page_config FROM document_template_versions WHERE id = $1",
[template.current_version_id],
);
const published = pubRows[0];
if (published) {
editorContent = published.editor_content;
cssContent = published.css_content;
pageConfig = published.page_config;
}
}
const { rows: verRows } = await client.query<{ next_version: string }>(
"SELECT COALESCE(MAX(version), 0) + 1 AS next_version FROM document_template_versions WHERE template_id = $1",
[templateId],
);
const nextVersion = Number(verRows[0]?.next_version ?? 1);
const htmlContent = renderHtml(editorContent);
const { rows } = await client.query<DocumentTemplateVersion>(
`INSERT INTO document_template_versions
(template_id, version, status, editor_content, html_content, css_content, page_config, created_by)
VALUES ($1, $2, 'draft', $3, $4, $5, $6, $7)
RETURNING *`,
[
templateId,
nextVersion,
JSON.stringify(editorContent),
htmlContent,
cssContent,
JSON.stringify(pageConfig),
createdBy,
],
);
const created = rows[0];
if (!created) throw new Error("failed to create draft version");
return created;
});
}
export interface UpdateDraftInput {
editorContent?: unknown;
cssContent?: string | null;
pageConfig?: Record<string, unknown>;
}
/**
* Overwrites the existing draft only — never creates one, never touches
* a published version (eden.md §1.2 step 2). `undefined` fields in
* `patch` keep the draft's current value; only fields explicitly present
* are replaced (so `cssContent: null` can clear it, distinct from
* omitting the field).
*/
export async function updateDraft(
templateId: string,
patch: UpdateDraftInput,
renderHtml: (editorContent: unknown) => string,
): Promise<DocumentTemplateVersion> {
return withTransaction(async (client) => {
const { rows: templateRows } = await client.query("SELECT id FROM document_templates WHERE id = $1", [
templateId,
]);
if (!templateRows[0]) throw new TemplateNotFoundError(templateId);
const { rows: draftRows } = await client.query<DocumentTemplateVersion>(
"SELECT * FROM document_template_versions WHERE template_id = $1 AND status = 'draft' FOR UPDATE",
[templateId],
);
const draft = draftRows[0];
if (!draft) throw new DraftNotFoundError(templateId);
const editorContent = patch.editorContent !== undefined ? patch.editorContent : draft.editor_content;
const cssContent = patch.cssContent !== undefined ? patch.cssContent : draft.css_content;
const pageConfig = patch.pageConfig !== undefined ? patch.pageConfig : draft.page_config;
const htmlContent = renderHtml(editorContent);
const { rows } = await client.query<DocumentTemplateVersion>(
`UPDATE document_template_versions
SET editor_content = $2, html_content = $3, css_content = $4, page_config = $5
WHERE id = $1
RETURNING *`,
[draft.id, JSON.stringify(editorContent), htmlContent, cssContent, JSON.stringify(pageConfig)],
);
const updated = rows[0];
if (!updated) throw new Error("failed to update draft version");
return updated;
});
}
/**
* Transactionally marks the draft as published (stamping published_at/
* published_by) and repoints document_templates.current_version_id at
* it — eden.md §1.2 step 3. From this point the version is immutable;
* no route in this leva ever edits a version with status='published'.
*/
export async function publishDraft(templateId: string, publishedBy: string | null): Promise<DocumentTemplateVersion> {
return withTransaction(async (client) => {
const { rows: templateRows } = await client.query("SELECT id FROM document_templates WHERE id = $1 FOR UPDATE", [
templateId,
]);
if (!templateRows[0]) throw new TemplateNotFoundError(templateId);
const { rows: draftRows } = await client.query<DocumentTemplateVersion>(
"SELECT * FROM document_template_versions WHERE template_id = $1 AND status = 'draft' FOR UPDATE",
[templateId],
);
const draft = draftRows[0];
if (!draft) throw new DraftNotFoundError(templateId);
const { rows: publishedRows } = await client.query<DocumentTemplateVersion>(
`UPDATE document_template_versions
SET status = 'published', published_at = now(), published_by = $2
WHERE id = $1
RETURNING *`,
[draft.id, publishedBy],
);
const published = publishedRows[0];
if (!published) throw new Error("failed to publish draft version");
await client.query("UPDATE document_templates SET current_version_id = $2 WHERE id = $1", [
templateId,
draft.id,
]);
return published;
});
}
// ---------------------------------------------------------------------------
// document_generations (eden.md §1.3)
// ---------------------------------------------------------------------------
/**
* Resolves the version that a real (non-draft) generation must use —
* always `document_templates.current_version_id` via direct lookup,
* NEVER a draft (eden.md §2.4: a draft only "shadows" the published
* version in internal preview/test screens, never in a real generation).
* Returns null when the template has never been published (the service
* layer maps this to 404), and throws TemplateNotFoundError if the
* template id itself doesn't exist.
*/
export async function getPublishedVersionForTemplate(
templateId: string,
): Promise<{ template: DocumentTemplate; version: DocumentTemplateVersion } | null> {
const template = await getTemplateById(templateId);
if (!template) throw new TemplateNotFoundError(templateId);
if (!template.current_version_id) return null;
const { rows } = await query<DocumentTemplateVersion>(
"SELECT * FROM document_template_versions WHERE id = $1",
[template.current_version_id],
);
const version = rows[0];
if (!version) return null;
return { template, version };
}
export interface CreateGenerationInput {
templateId: string;
templateVersionId: string;
clientRegistrationId?: string | null;
resellerId?: string | null;
renderContext: Record<string, unknown>;
renderedHtml: string;
generatedBy?: string | null;
}
async function findFinalGeneration(
templateVersionId: string,
source: { clientRegistrationId?: string | null; resellerId?: string | null },
): Promise<DocumentGeneration | null> {
if (source.clientRegistrationId) {
const { rows } = await query<DocumentGeneration>(
`SELECT * FROM document_generations
WHERE template_version_id = $1 AND client_registration_id = $2 AND status = 'final'
LIMIT 1`,
[templateVersionId, source.clientRegistrationId],
);
return rows[0] ?? null;
}
const { rows } = await query<DocumentGeneration>(
`SELECT * FROM document_generations
WHERE template_version_id = $1 AND reseller_id = $2 AND status = 'final'
LIMIT 1`,
[templateVersionId, source.resellerId ?? null],
);
return rows[0] ?? null;
}
async function insertGeneration(input: CreateGenerationInput): Promise<DocumentGeneration> {
const { rows } = await query<DocumentGeneration>(
`INSERT INTO document_generations
(template_id, template_version_id, client_registration_id, reseller_id,
render_context, rendered_html, status, generated_by)
VALUES ($1, $2, $3, $4, $5, $6, 'final', $7)
RETURNING *`,
[
input.templateId,
input.templateVersionId,
input.clientRegistrationId ?? null,
input.resellerId ?? null,
JSON.stringify(input.renderContext),
input.renderedHtml,
input.generatedBy ?? null,
],
);
const created = rows[0];
if (!created) throw new Error("failed to create document generation");
return created;
}
/**
* Simplified idempotency (eden.md §1.3 describes a richer rule with
* `force`/`extra_fields` — out of scope for this leva; only the base
* case is implemented): the same (template_version_id, origin) already
* `status='final'` returns the existing row instead of creating another.
* The optimistic read-then-insert below is backed by the partial unique
* indexes uq_document_generations_{client,reseller}_final from the
* migration — on a race between two concurrent requests, the loser's
* insert raises a unique_violation (23505) and re-reads to return the
* winner's row instead of erroring.
*/
export async function createGenerationIdempotent(
input: CreateGenerationInput,
): Promise<{ generation: DocumentGeneration; deduped: boolean }> {
const existing = await findFinalGeneration(input.templateVersionId, input);
if (existing) return { generation: existing, deduped: true };
try {
const created = await insertGeneration(input);
return { generation: created, deduped: false };
} catch (err) {
if (isUniqueViolation(err)) {
const retried = await findFinalGeneration(input.templateVersionId, input);
if (retried) return { generation: retried, deduped: true };
}
throw err;
}
}
export interface ListGenerationsFilter {
templateId?: string;
clientRegistrationId?: string;
resellerId?: string;
}
export async function listGenerations(filter: ListGenerationsFilter = {}): Promise<DocumentGeneration[]> {
const conditions: string[] = [];
const params: unknown[] = [];
if (filter.templateId) {
params.push(filter.templateId);
conditions.push(`template_id = $${params.length}`);
}
if (filter.clientRegistrationId) {
params.push(filter.clientRegistrationId);
conditions.push(`client_registration_id = $${params.length}`);
}
if (filter.resellerId) {
params.push(filter.resellerId);
conditions.push(`reseller_id = $${params.length}`);
}
const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
const { rows } = await query<DocumentGeneration>(
`SELECT * FROM document_generations ${where} ORDER BY created_at DESC`,
params,
);
return rows;
}