SYSTEMS & DATA2026-08 · TECHNICAL CASE

Institutional POA & Budget Planning System

Institutional platform for annual operational plan (POA) formulation and expenditure ceiling controls for 500+ decentralized operating units. Decoupled hexagonal architecture in NestJS 11, arbitrary-precision arithmetic with Big.js, transactional PostgreSQL (45 tables with RLS and triggers), 4-phase ETL pipeline, enterprise observability, and multi-agent AI acceleration.

NestJS 11Next.js 16PostgreSQLTypeORMBig.jsRedisDockerOpenCode Agents

[!NOTE] Confidential Visual Assets: In compliance with statutory confidentiality, institutional data privacy regulations, and public financial system governance, internal UI screenshots are not publicly exhibited.

Executive Summary: Problem, Solution & Engineering Impact

Dimension Project Insight
Role Performed Systems Development Consultant (External technical consulting covering full-stack architecture and implementation).
Institutional Problem Decentralized annual budget planning across manual spreadsheets for over 500 operating units, causing accounting discrepancies, bureaucratic bottlenecks with central IT, and legal risks of exceeding statutory budget ceilings.
Engineering Solution Decoupled modular monolith with lightweight hexagonal architecture (NestJS 11), arbitrary-precision decimal engine (Big.js), 45-table relational PostgreSQL schema with dynamic RLS, invariant triggers, and a resilient 4-phase ETL pipeline.
Technical Impact 100% functional and tested codebase, complete eradication of cent rounding errors (Σ Expenditures = Σ Ceiling exact), immutable auditability per user/IP, and a synchronized dual document generation engine (PDF & Excel).

1. Context: Budget Formulation Against the Clock

In university public administration, deadlines to finalize and submit the Annual Operating Plan (POA) and consolidated budget to national fiscal oversight bodies are firmly governed by statutory fiscal calendars.

In this institution, the Financial Directorate supervised budget planning across more than 500 decentralized operating units (faculties, academic departments, research institutes, and central administrative offices). However, the directorate faced chronic operational paralysis due to dependence on a centralized IT department whose bureaucratic procedures took months to deliver minor updates to budgetary classification catalogs and submission forms.

To achieve operational autonomy, the financial leadership contracted an external technical consultancy to build an independent, modern, dedicated software platform. I was brought on board as a Systems Development Consultant under two demanding constraints:

  1. Unmovable hard deadline: We had a tight window of only a few weeks before the statutory fiscal submission window closed permanently.
  2. High operational scale and non-technical users: The platform had to support hundreds of concurrent submissions by administrative personnel aged between 35 and 65 years with varying levels of computer literacy. This demanded a structured step-by-step wizard, spreadsheet-like keyboard shortcuts, and ironclad guards against data entry mistakes.

Engineering Stack, Resiliency & Tooling

Arquitectura de Software
NestJS
NestJSv11.0

Decoupled modular monolith with ports & adapters (lightweight hexagonal), conceptual CQRS, and role/scope guards.

Next.js
Next.jsv16.3

React 19 frontend with Tailwind CSS v4, Zustand (Slices pattern), route Error Boundaries, and accessible wizard.

PostgreSQL
PostgreSQLv16 / TypeORM

45-table relational schema, dynamic Row-Level Security (RLS), PL/pgSQL invariant triggers, and optimistic locking.

Python
Big.jsv7.0

Arbitrary-precision decimal arithmetic guaranteeing exact cent balance across multi-tiered expenditure ceilings.

Redis
Redisv6.0

In-memory event bus, concurrency controls, and high-performance cache for budgetary classification items.

Docker
Docker & TestcontainersCompose / v12

Infrastructure containerization and automated integration testing against real ephemeral PostgreSQL instances.

Python
Pino & Observabilityv10.3

Structured JSON logging with request correlation IDs, latency interceptors, and immutable transaction audits.

Python
OpenCode Multi-AgentWorkflow

Collaborative multi-agent pipeline pairing specialized AI agents (Backend Coder + Backend Reviewer) under formal specs.


2. Engineering Post-Mortem: The Domain Logic Wall

This project yielded one of the most defining professional lessons of my engineering career regarding software architecture and the realistic capabilities and limitations of AI-assisted engineering.

Weeks 1 and 2: Hitting the Wall of Coding Without Domain Mastery

Facing aggressive delivery timelines, I initially made a classic engineering mistake: jumping straight into code and attempting to model the system by relying heavily on AI generation. However, governmental budgetary formulation cannot be simplified into basic CRUD endpoints; it is a rigid hierarchical tree mandated by strict public finance laws:

Institutional Strategic Directives
  └─► Programs & Strategic Projects
        └─► Operational Activities
              └─► Institutional Job Description Manual (MOF) Tasks
                    └─► Budget Items, Financing Sources & Line-Item Ceilings

I encountered a stark reality: AI is an extraordinary force multiplier for code generation, but if the engineer does not deeply comprehend the domain rules and invariants, AI simply generates disposable code at high velocity. The first two weeks were lost in frustration trying to patch abstractions that failed to capture statutory financial requirements.

Weeks 3 and 4: Stepping Back to Paper, Pencil, and Critical Data Modeling

We hit the brakes immediately. Putting our keyboards aside, my teammate and I spent focused days reading administrative regulations, public financial statutes, and institutional org charts using pen and paper alongside the directorate’s senior financial analysts.

We realized that the relational database schema was the foundation that would either sustain or collapse the entire initiative: if the data model and its mathematical constraints did not guarantee integrity, no application-layer checks could prevent accounting anomalies. We formalized the contract into 45 relational tables in DBML (consolidated v22 specification), specifying not just entities, but triggers, analytical views, and invariant verification functions.


3. System Architecture & Core Design Patterns

To ensure that the platform remained maintainable, robust, and extensible across future fiscal years, we engineered the codebase under formal structural patterns:

┌────────────────────────────────────────────────────────────────────────┐
│                        PRESENTATION (NEXT.JS 16)                       │
│    Features (POA, DAF, Auth) │ Zustand Slices │ Error Boundaries      │
└───────────────────────────────────┬────────────────────────────────────┘
                                    │ HTTP / REST / HttpOnly Cookies
┌───────────────────────────────────▼────────────────────────────────────┐
│                       MODULAR BACKEND (NESTJS 11)                      │
│                                                                        │
│   ┌──────────────────────────────────────────────────────────────┐    │
│   │                     CROSS-CUTTING CORE (PORTS)               │    │
│   │   AuthPort │ WorkflowPort │ DocumentPort │ FilePort (S3)     │    │
│   │   AuditPort │ EventBusPort │ CatalogPort │ ScopePort          │    │
│   └──────────────────────────────▲───────────────────────────────┘    │
│                                  │ Implements ports                    │
│   ┌──────────────────────────────┴───────────────────────────────┐    │
│   │                DOMAIN & USE CASES (ADAPTERS)                 │    │
│   │   use-cases/ (Commands)    │ queries/ (CQRS with SQL CTEs)   │    │
│   │   Money Pattern (Big.js)   │ Facade Services (poa.service)   │    │
│   └──────────────────────────────┬───────────────────────────────┘    │
└──────────────────────────────────┼────────────────────────────────────┘
                                   │ TransactionService (SET LOCAL app.*)
┌──────────────────────────────────▼────────────────────────────────────┐
│                       DATABASE (POSTGRESQL 16)                         │
│   45 Tables │ Dynamic Row-Level Security (RLS) │ Transition Triggers  │
│   Historical Immutability Guards │ Strict Mathematical Ceiling Balance│
└────────────────────────────────────────────────────────────────────────┘

3.1 Decoupled Modular Monolith (Lightweight Hexagonal)

  • Ports and Adapters Isolation: Core infrastructure modules (auth, identity, workflow, document, file, catalog, import, audit, events) contain zero references to domain-specific poa concepts. They interact strictly via typed interfaces bound to Symbol injection tokens. The architectural decoupling was proven when a second independent module (reforma_presupuestaria) was integrated, reusing 100% of the core modules without modifying a single internal line.
  • Conceptual CQRS: Clean structural separation between mutating write commands (guardar-arbol.use-case.ts, delegar-poa.use-case.ts) and read-heavy queries (obtener-arbol.query.ts). Complex hierarchical data structures are assembled in single optimized queries utilizing recursive Common Table Expressions (CTEs) in PostgreSQL.

3.2 Key Design Patterns

  • Money Pattern (Big.js): In public institutional finance, standard JavaScript float and number types introduce impermissible rounding drift. All monetary amounts are ingested as validated 2-decimal string DTOs (@IsMontoDecimal), calculated via Big.js in memory, and stored in numeric(18,2) database columns with strict CHECK (monto >= 0) constraints.
  • State Machine & Governed Workflow: The statutory lifecycle of a plan (Draft $\rightarrow$ Under Review $\rightarrow$ Observed / Bounced $\rightarrow$ Approved $\rightarrow$ Homologated) is governed by an explicit state machine verified both in application service layers and in the database engine via the fn_validar_transicion BEFORE trigger.
  • Unified Canonical Model (Document Builder): A single canonical data snapshot (DatosPoaParaPdf) fuels both the generation of official 11-section legal PDF documents and matching 5-sheet formatted Excel workbooks, eliminating data discrepancy across export formats.
  • Strategy Pattern for Ingestion: Polymorphic ETL execution strategies tailored for specific spreadsheet variants (TECHO, MATRIZ_PEI, PLANTILLA_POA, MOF).

4. Resilience, Fault Tolerance & Observability

The platform was built assuming that network partitions, concurrent writes, and user input inconsistencies are inevitable in high-volume enterprise environments.

4.1 Fault Handling & Transactional Integrity

  • RLS Context & Unit of Work: Every database mutation must execute through TransactionService.run(actor, cb). Upon opening a transaction, the service injects session variables locally into PostgreSQL:
    SELECT set_config('app.current_user_id', :userId, true);
    SELECT set_config('app.current_rol', :rol, true);
    SELECT set_config('app.observacion', :observacion, true);
    SELECT set_config('app.client_ip', :clientIp, true);
    This ensures that Row-Level Security (RLS) policies and audit triggers verify the real authenticated actor rather than the generic database connection pool user. Unhandled exceptions trigger an immediate, complete transaction ROLLBACK.
  • Optimistic Locking: Core entities enforce optimistic concurrency via @VersionColumn. Concurrent updates to the same budget line or plan trigger a controlled concurrency exception, instructing the user to fetch the latest state without overwriting parallel edits.
  • Storage Compensation and Version Retry (S3/MinIO): Emitting versioned and digitally hashed documents relies on Advisory Locks (pg_advisory_xact_lock) with up to 3 automatic retries upon unique constraint collision (23505). If a database transaction fails after an artifact is staged in S3/MinIO object storage, a compensating cleanup routine purges the orphaned file.
  • Post-Commit Side Effects: Domain events, email alerts, and outbound webhooks fire strictly after a successful database commit. Heavy background PDF generation tasks operate in a best-effort pattern post-commit: an auxiliary rendering failure never aborts or generates a 500 status on an already-committed financial transaction.

4.2 Four-Phase ETL Ingestion Pipeline

To ingest historical spreadsheets submitted by operating units, we developed an ETL engine with strict defensive isolation:

  1. Phase A (Header Syntax Validation): In-memory structural validation of column headers, aliases, and template versions.
  2. Phase B (Pure Row Validation): High-speed in-memory validation of data types, constraints, and formulas without I/O or database round-trips.
  3. Phase C (Relational Cross-Checking): Relational verification against active database records (ensuring valid institutional unit codes and active budget lines).
  4. Phase D (Idempotent Persistence or Total Rollback): Batch upserts using unnest and ON CONFLICT DO UPDATE inside an isolated transaction. A single integrity violation triggers a full rollback and returns up to 100 typed error diagnostics [row, column, code, message] for rapid user correction.

4.3 Runtime Observability & Tamper-Resistant Auditing

  • Structured Logging with Pino: Runtime logs emitted in structured JSON format, tagged with request correlation IDs (requestId), user IDs, and endpoint execution latency metrics.
  • Engine-Enforced Audit Trails: Historical tables (poa_movimiento, poa_documento, auditoria) are guarded by database triggers that systematically reject UPDATE and DELETE queries (reject_immutable_mutation). Every approval, modification, and comment is cryptographically hashed with SHA-256 fingerprints.
  • Frontend Error Boundaries: The Next.js client encapsulates route segments with error.tsx boundary boundaries and uniform ApiError normalization, preventing catastrophic blank crashes and surfacing actionable Toast feedback.

5. Acceleration via Specialized AI Multi-Agent Pipeline (OpenCode)

Once relational schemas and business requirements were solidified into formal Markdown specifications, we deployed a collaborative workflow powered by two specialized AI agents:

  1. Backend Coder Agent: Governed by strict NestJS architecture rules and DBML data contracts. It generated modular services, TypeORM entities, DTOs with validation rules, and facades complying with architectural boundary linters.
  2. Backend Reviewer Agent: An automated code auditor running in read-only mode (temperature: 0). It reviewed Pull Requests, verified that database triggers remained unbypassed, prohibited untyped any syntax, and confirmed that automated test suites passed green against real PostgreSQL instances via Testcontainers.

This multi-agent loop enabled us to build and verify over 26,000 lines of production TypeScript in just 1.5 weeks of active implementation, proving that AI acts as a monumental accelerator when guided by rigorous engineering foundations.


6. Project Wrap-Up & Consulting Takeaways

  • Project Outcome: The complete codebase (NestJS backend, 45-table database, Next.js frontend, and dual document exporters) was delivered, fully tested, and technically verified. In the final stretch of the consultancy, however, parsing and cleaning legacy Excel matrices from more than 500 decentralized operating units proved to require extensive manual data reconciliation that collided with the unmovable university fiscal deadline. With the statutory submission window closed and no administrative leeway to extend external contracts or deploy the live pilot with end-users, the institution temporarily continued with its inherited manual procedures.
  • Senior Engineering Lessons:
    • Domain mastery takes precedence over code: Attempting to code before thoroughly understanding governmental financial regulations cost us two weeks of throwaway work. Working through domain rules with pen, paper, and business analysts was what ultimately unlocked the solution.
    • The database is the ultimate invariant defender: In platforms managing public finances, enforcing constraints, state transitions, and RLS inside PostgreSQL triggers prevents the systemic fragility of application-only validations.
    • Agentic software engineering: Coupling formal architectural specifications with specialized builder and reviewer AI agents allows small engineering teams to deliver enterprise-grade, rigorously tested software under demanding timelines without sacrificing code quality.