Shipped on Branch feat/bundled-template-defaults api · 8a9a299 client · c8d08443 Nov 24, 2026 · ~7 min read

Bundled Defaults + Custom Overrides: Inside Our New PPAT Template Architecture

We refactored how notaris-ppat-module stores, resolves, previews, customizes, and deploys DOCX templates across both api and client. Instead of treating Postgres + R2 as a mandatory upload gate for every built-in letter, git-committed defaults now ship directly inside the container and DB/R2 acts strictly as an optional customization layer.

Repos per new doc
2 → 1
API-only changes
Manual prod uploads
1 → 0
Live on deploy
Template registries
4 → 1
Single config file
DB migrations needed
0
100% backwards-safe

01 · Core Mental Model

Two-Layer Template Resolution

Think of templates like application configuration with environment overrides. Every built-in PPAT document has a base layer baked into the Docker image (api/templates/*.docx). Postgres + Cloudflare R2 sits on top as an override layer that only activates when the notary office explicitly customizes a template.

Interactive Runtime Simulator Pick a template state to trace every endpoint

02 · Under the Hood

Five Engineering Decisions That Made It Clean

1. One Registry to Rule Them All (PPAT_DOCUMENTS_CONFIG)

api/src/config/ppat-documents.config.ts

Previously, template paths lived inside two separate arrays in templates.service.ts (which even had subtle name mismatches like formulir-permohonan-peralihan-hak-bpn vs permohonan-peralihan-hak-bpn). Now each entry in PPAT_DOCUMENTS_CONFIG declares its own optional defaultTemplatePath, and Dockerfile copies templates/ into the final runtime stage:

{
  docType: 'keterangan-hibah',
  title: 'Surat Keterangan Hibah',
  requirements: ['sertifikat', 'pihakPertama', 'pihakKedua'],
  defaultTemplatePath: 'templates/surat-keterangan-hibah.docx',
  allowedJenisBerkas: ['HIBAH'],
  selectData: buildKeteranganHibahData,
}

A dedicated unit test in templates.service.spec.ts iterates over listBundledTemplateConfigs() and asserts that every declared file exists on disk and starts with a valid ZIP/DOCX header (PK)—so broken paths are caught in CI before deploy.

2. Virtual IDs (default:<docType>) Without Any Schema Migration

api/src/templates/bundled-templates.ts

Rather than seeding rows into Postgres on boot (which creates startup race conditions and goes stale whenever a default file changes in git), uncustomized defaults are synthesized on read with a deterministic virtual ID: default:keterangan-hibah.

  • Zero DB migration: The templates Prisma table is completely untouched.
  • Unified REST contract: Existing routes (GET /templates/:id, GET /templates/:id/file, PUT /templates/:id, POST /templates/:id/reset) accept both ULIDs and default:<docType> seamlessly.
  • Automatic promotion: Calling PUT /templates/default:keterangan-hibah with an uploaded .docx validates the file against TemplateValidationService, uploads it to R2, inserts the DB row, and returns the real ULID—so the UI transitions smoothly to the new CUSTOM override.

3. Shared Fallback Across Both PPAT Docs and Pengecekan

generated-document.service.ts · pengecekan.service.ts

Both GeneratedDocumentService (Berkas PPAT documents) and PengecekanService (Surat Pengantar, Kuasa, Pernyataan Pengecekan) follow the exact same precedence rule:

const templateMeta = await this.prisma.template.findUnique({ where: { name: docType } });
let templateBuffer: Buffer;
if (templateMeta) {
  templateBuffer = await this.s3service.getFileAsBuffer(templateMeta.fileUrl);
} else if (config.defaultTemplatePath) {
  templateBuffer = await readBundledTemplateBuffer(config.defaultTemplatePath);
} else {
  throw new NotFoundException(`Template file for '${docType}' has not been uploaded...`);
}

As a bonus performance win, uncustomized templates load straight from local disk with zero R2 network round-trip.

4. Cross-Origin Safe Preview & Download for Bundled Files

templates.controller.ts · client/src/api/template.api.ts

Custom overrides live in R2, so GET /templates/:id/download returns a 5-minute presigned S3 URL. Bundled defaults live on the API container's filesystem—there is no R2 key to presign. Because the frontend and API can run on separate origins in production, returning a relative path for window.open() would break.

Instead, for source === "DEFAULT", GET /templates/:id/download returns { url: null, useFileEndpoint: true, displayFileName }. The client detects that flag, fetches GET /api/templates/:id/file?download=1 through the authenticated fetchRequest helper, and triggers a browser download via URL.createObjectURL(blob).

5. API-Driven Client (Zero Frontend PRs for Future Docs)

client/src/api/berkas-ppat-generate-documents.ts

Previously, client validated docType against a strict hardcoded z.enum(...) and rendered PpatDocumentLabels[doc.docType] without a fallback—meaning any backend-only document would either fail validation or render a blank title cell.

Now PpatDocumentTypeSchema accepts any non-empty string, PpatDocumentLabels is an optional short-label map, and GeneratedDocumentsSection renders PpatDocumentLabels[doc.docType] ?? doc.displayName. Any new document added to PPAT_DOCUMENTS_CONFIG in api immediately shows up, generates, converts to PDF, and downloads in client with zero frontend changes.

03 · Zero-Downtime Compatibility

What Happens to Existing Production Templates?

Deploying this branch requires zero database cleanup and preserves every uploaded file in R2.

Matching Name

e.g. sppkkd, kuasa-peralihan-hak

Your uploaded R2 file continues to take priority over the bundled default. In /template, it merges cleanly into one row badged Kustom, and gains a Reset ke Bawaan button if you ever want to switch to the bundled version.

Standalone Custom

e.g. invoice, apht

Appended as-is in /template with badge Kustom and hasBundledDefault: false. Preview, download, and edit work unchanged, and Reset ke Bawaan is hidden (and blocked with 400 on the API) so it cannot be accidentally deleted.

Legacy Mismatched Names

e.g. old seeder names

Old rows like formulir-permohonan-peralihan-hak-bpn stay untouched as standalone custom rows, while the canonical docType (permohonan-peralihan-hak-bpn) activates automatically as Bawaan.

04 · Day-2 Operations

How Templating Works Going Forward

Switch between the Developer Playbook and the Notaris/Staff Playbook to see the new end-to-end lifecycle.

05 · Looking Ahead

Where This Architecture Can Grow Next

Bundle APHT & SKMHT Defaults

apht and skmht-internal currently omit defaultTemplatePath. Whenever baseline Word templates are finalized, dropping the files in api/templates/ and setting their paths activates them automatically.

Hybrid Deeds vs. Letters

Keep simple office letters (Hibah, Kuasa, SPPKKD, Permohonan BPN) as bundled DOCX templates that staff can tweak in Word, while complex conditional deeds (like AJB) can continue using dedicated TypeScript builders.

Optional Override History

Right now resetting reverts straight to the bundled default. If the office later wants to compare or roll back between multiple custom edits, adding a version column to templates slots neatly onto the override layer.

Want to read the trade-off analysis that led to this architecture? Read: 4 Ways to Manage PPAT DOCX Templates →