TWIMS — Digitising a Government Department's Approval Chain
How we built a multi-tier approval and inventory operating system for a UP Irrigation tubewell division — 8 roles across 3 divisions, configurable workflow policies, ledger-based stock verification, and a 9-level jurisdiction tree.

Built from the actual codebase. Zero hypothetical claims.
Every architectural statement, data model, and route count below is directly verifiable in the repository specification.
Mongoose schemas with strict lifecycle hooks
Across Field, Store, Workshop + Super Admin
Dedicated routes with isolated authorization
Configurable document-driven approval chains
Nested tree from State down to Village
On-site (12 steps) & Workshop (18 steps)
The challenge: When paperwork delays irrigation water
A tubewell division of the UP Irrigation Department operates hundreds of heavy-discharge government tubewells across a district. When a motor burns out or a starter panel fails, farmers lose critical irrigation water for standing crops. The time elapsed between an initial field breakdown and successful recommissioning is the only metric that matters.
That turnaround time was not being consumed by mechanical engineering — it was being consumed by physical paperwork.
The Statutory Approval Cascade
A breakdown moves through an immutable chain of statutory authority:
- 01.Field Junior Engineer (JE): Inspects physical tubewell on-site, logs fault, and raises formal indent.
- 02.Field Assistant Engineer (AE): Reviews technical validity and forwards through official hierarchy.
- 03.Executive Engineer (EE): Evaluates financial sanction, approves indent, and dispatches division mechanic.
- 04.Workshop Chain (JE & AE): If the motor requires rewinding or lathe work, a second chain triggers — workshop engineers inspect, log spares required, and create a store requisition.
- 05.Central Store Chain (AE & JE): Store AE verifies stock allocation; Store JE issues physical components and drafts the statutory Gate Pass.
None of that hierarchy is negotiable. It is how a government department ensures financial propriety and public accountability. Any software system that tries to “flatten” this hierarchy to save clicks is a system that officers are legally barred from using.
The bottlenecks were purely mechanical: physical files moving between offices across the district, zero real-time visibility on where an indent was pending, store inventory trapped in paper registers with four divergent versions of the item master, manual gate passes that made stock reconciliation nearly impossible, and no audit trail beyond faded ink signatures on paper.
The mandate was not to redesign how the UP Irrigation Department functions. It was to move their exact regulatory workflow onto digital rails — without skipping a single statutory step.
The constraints: Realities of public sector software
Immutable Hierarchy
Eight distinct roles spanning Field, Central Store, and Workshop divisions reporting up to the Executive Engineer and Superintending Engineer. An organizational fact that had to be modeled with surgical accuracy.
Statutory Audit Survival
Public funds govern every rupee. Who approved an indent, when, from which IP, and based on which item master entry must be completely reconstructible by government auditors years into the future.
Field Engineers on Mobile
A Junior Engineer standing in muddy agricultural fields on intermittent 4G mobile data is the primary actor. If the UI requires specialized training or desktop viewports, adoption collapses back to paper registers.
True Bilingual Ingestion
Hindi and English throughout. Official departmental noting occurs in Hindi; technical equipment ratings and part numbers are in English. Both coexist simultaneously on the exact same screens.
Legacy Excel Reality
Existing records resided in heterogeneous spreadsheets and historical registers. The system had to ingest, sanitize, and validate them directly rather than expecting staff to re-type thousands of line items.
Policy Circular Resiliency
Government circulars routinely alter financial sanction ceilings and review routes. Hardcoding workflows into application logic would trigger endless procurement and contract amendment cycles.
The decisions, and why
01.We made approval workflows data, not code
The intuitive developer approach is to hardcode each approval chain in application logic — writing a hardcoded state machine per process. It is faster to prototype and an absolute disaster long-term. Every time the government issues an administrative circular amending an approval ceiling, it forces a code update, code review, redeployment, and an agonizing procurement negotiation.
Instead, we architected workflows as documents. A WorkflowPolicy defines an operation type — on-site repair, workshop repair, indent approval, or central store issuance — as an ordered sequence of declarative steps. Each step enumerates permissible actor roles, specifies whether single or unanimous consensus is required, and defines administrative override rules. Only one policy is active per process type while preserving full historical revision lineage.
02.We modeled jurisdiction as a 9-level tree, not a flat field
Public sector administrative geography is deeply nested, multi-tiered, and irregular:
Each jurisdiction document maintains a self-referencing parent pointer, allowing any subtree query to resolve recursively. The Vidhan Sabha level was the critical detail: it is an electoral constituency rather than an engineering sub-division, yet legislative assemblies and district magistrates frequently demand water discharge and repair logs organized specifically by legislative constituency. A system built purely on engineering administrative tiers would have failed to generate the reports the department actually needs.
03.We built inventory as an immutable ledger, not a quantity integer
The standard web approach to inventory is storing an integer quantityInStock on the item, incrementing on receipt and decrementing on dispatch. This is completely unauditable in a government context. You know what you currently hold, but you have no mathematically verifiable record of how that figure came to be.
We engineered a double-entry ledger architecture: every single movement is recorded as an immutable StockLedgerEntry. Current available inventory is a derived projection. Any stock figure can be verified backwards through every historical receipt, workshop issue, scrap write-off, and return voucher that produced it.
04.Gapless, financial-year document numbering via atomic Counters
Indents, store gate passes, and material requisitions require strictly sequential, gapless numbering scoped by Indian Financial Year (1 April – 31 March). Deriving sequence IDs via database document counts or client timestamps causes catastrophic collisions under concurrent writes. We implemented dedicated MongoDB Counter collections utilizing atomic $inc operations to guarantee non-colliding, audit-compliant identifiers.
05.30 role-scoped dashboard routes rather than one permission-toggled view
Instead of routing all users to a generic dashboard where unauthorized buttons are grayed out or hidden behind client conditionals, we engineered thirty discrete, role-scoped routes (/dashboard/field-je, /dashboard/store-ae, etc.).
When a Field JE logs in from a smartphone, they see only their jurisdiction's tubewells, pending indents, and active breakdown alerts. No clutter, no cognitive overload, and zero confusion. Interfaces that repeatedly show field workers what they are not permitted to do teach them that software is complicated.
What we built
Two Complete Repair Lifecycles
The workshop repair flow spans eighteen discrete steps from field breakdown through workshop mechanical overhaul back to operational sign-off. The on-site flow operates twelve steps. Both were mapped against departmental standing orders and are enforced by server-side policy guards.
Cryptographically Tied Digital Gate Passes
Automated generation of Central Store Gate Passes, Workshop Transport Passes, and Direct Site Passes. Every gate pass is immutably linked to the authorizing indent, verifying driver identity, vehicle registration, and issuing officer signatures before materials exit any government facility.
Instant Multi-Tier Escalation & Completion
When a Field JE inspects a repaired tubewell and records acceptance in the field, notification triggers instantaneously to the Assistant Engineer and Executive Engineer. The previous reliance on delayed postal despatches or manual phone calls was eliminated.
Comprehensive Asset & Inventory Registries
Tubewells, transformer ratings, pump specifications, item masters categorized by units of measure, registered suppliers, and financial purchase orders — with native Excel import pipelines so legacy registers could be uploaded without human transcription errors.
Tamper-Evident State Transition Audit Logs
Every state transition, approval stamp, rejection note, and inventory movement is permanently logged with user ID, role, timestamp, network IP, and pre/post entity state deltas.
Executive Recharts Analytics by Jurisdiction
Real-time operational dashboards visualizing tubewell running hours, active breakdowns, turnaround latency, and critical inventory thresholds — scoped strictly by user jurisdiction hierarchy.
The hard parts: Engineering solutions to complex administrative friction
1. Modeling Authority Without Flattening It
The standard instinct in modern SaaS design is friction reduction: delete approval steps, eliminate intermediary reviews, optimize for speed. In government administrative engineering, that instinct produces software that gets instantly banned. The statutory approval chain is not bureaucratic bloat; it is the constitutional mechanism for public expenditure accountability.
We engineered speed not by bypassing approvals, but by eliminating latency: physical file transit across districts was reduced to zero, approval queues became transparent in real-time, and downstream actors receive instant notifications the moment their prerequisite signature clears.
2. Concurrency Control on Critical Spare Parts
When multiple field breakdowns occur during peak summer irrigation, separate workshop teams requisition the same high-demand spare parts (e.g., thrust bearings, copper winding coils) simultaneously against limited buffer stock. If two approval actions read available inventory concurrently, both would approve issuance, causing negative inventory and field delivery failure.
By combining our immutable StockLedgerEntry structure with MongoDB transactional sessions and atomic reservations, race conditions were mathematically eliminated at the database driver layer.
3. Indian Financial Year (FY) Boundary Logic
Government document sequences reset strictly on 1 April rather than calendar New Year. A naive counter logic breaks between January and March, generating duplicate series numbers that fail annual comptroller audits. We built custom financial year resolvers that determine active FY bounds based on Indian Standard Time (IST) before invoking atomic sequence increments.
4. Field Usability in Low-Connectivity Belts
Junior Engineers operate in rural agricultural terrains with high latency and patchy mobile network coverage. The field interface relies on aggressive client-side caching of static jurisdiction hierarchies, small JSON payload schemas, and optimistic UI transitions that persist state locally until network synchronization succeeds.
Auditing our own build: Standardized security and correctness
On enterprise and government platforms, delivering code that passes basic happy-path testing is insufficient. We conducted a structured, internal security and correctness audit of the entire TWIMS codebase, classifying every architectural finding into standardized severity matrices: Critical, High, and Medium.
The Internal Audit Methodology
- ✓Authentication & Session Isolation: Exhaustive verification that API endpoints validate server-side session tokens rather than trusting client parameters.
- ✓Data Integrity & Concurrency Checks: Stress-testing ledger issuance models under simulated parallel requests to verify isolation guarantees.
- ✓Role Boundary Enforcement: Automated route checks verifying that lower-tier credentials (e.g. Field JE) cannot trigger upper-tier executive actions (e.g. EE sanction).
We treat this audit practice as standard engineering hygiene rather than a reactionary post-incident measure. Every critical finding identified during initial development was documented, systematically resolved, verified with regression test suites, and cataloged alongside deployment checklists before final handover.
Transparent auditing is how high-consequence public platforms remain secure, reliable, and maintainable over years of continuous departmental operation.
What we'd do differently
Technical maturity means acknowledging architectural decisions that should have been modeled cleaner from day one. In our post-delivery retrospective, three specific items stood out:
01.Earlier Normalization of Item Categories & Units
Initially, item categories and units of measure were stored as plain strings directly within the primary Item model. As legacy registers were ingested with slight variations (“mtrs” vs “Meters”), we introduced dedicated ItemCategory and UnitOfMeasure collections. This normalization should have been established on day one to eliminate data sanitization overhead during Excel ingestion.
02.Standardizing Permission Conventions from Kickoff
Early in development, certain create actions were implicitly gated behind view permissions rather than distinct granular flags. As the role matrix expanded to eight separate roles, we refactored to an explicit atomic permission convention (module:action). Establishing this taxonomy before writing initial endpoints would have prevented retrofitting authorization middleware.
03.Schema Object References Over String Constants
In select reporting components, jurisdiction cross-references initially relied on string name matches rather than immutable ObjectId relations. While practical during rapid spreadsheet seeding, it introduced brittle aggregation queries when village names had transliteration discrepancies. Migrating entirely to relational ObjectIds resolved this cleanly.
The stack
| Layer | Technology | Rationale |
|---|---|---|
| Framework | Next.js 16 (React 19) | Server components for fast mobile rendering and secure server actions. |
| Database | MongoDB & Mongoose 9 | Tree-structured jurisdiction hierarchy and nested workflow policy documents. |
| Authentication | NextAuth (RBAC) | Role-scoped session validation and cryptographic token management. |
| Data Visualization | Recharts | Executive telemetry for breakdown rates, discharge curves, and stock levels. |
| Spreadsheet Ingestion | SheetJS (xlsx) | Direct server-side parsing and sanitization of legacy government Excel registers. |
| Security & Hashing | bcryptjs & Audit Logger | Strict credential protection and immutable audit trail persistence. |
Related services & case studies
SaaS & Web App Development
Multi-tenant platforms, custom admin panels, role-based workflows, and complex operational software.
MVP Development for Founders
Production MVPs in 6 to 14 weeks. Built directly by senior product engineers with complete code handover.
Ankuraa Group Case Study
58-field custom real estate CMS, channel partner attribution engine, and 17 operational admin modules.