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

@@ -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;
}