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>
162 lines
11 KiB
JavaScript
162 lines
11 KiB
JavaScript
/**
|
|
* 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;
|
|
`);
|
|
};
|