Case study
Tulip ERP — digitizing deliveries and billing for a water plant
I designed and built an ERP for a reverse osmosis (RO) water plant in Karachi serving about a hundred regular customers. The system replaces paper-based delivery records and manual monthly billing with customer management, daily dispatch, billing, and revenue reporting. Daily dispatch preparation fell from approximately twenty minutes to under five minutes.
20 min → under 5 min
daily dispatch preparation · used daily by the plant
Architecture: business rules in PostgreSQL
Almost all the business logic lives in PL/pgSQL, not Python. The FastAPI layer is a thin
HTTP-to-CALL adapter; most endpoints are a single line:
cursor.execute("call schema_sales.add_sales(%s)", (sale.model_dump_json(),))
Procedures accept a jsonb argument and unpack it internally. Partial updates
are handled in SQL without constructing dynamic queries. The ? key-existence
operator checks whether a field was supplied; COALESCE retains the existing value
when the new SQL value is null. Supporting explicit field clearing requires separate handling.
Why. Three things write to this database: the API, seed scripts, and direct maintenance queries in psql. Rules enforced in Python only hold
for the first one. Putting the invariants in the database means they hold for all three,
including future callers that use the same database procedures and constraints.
What it cost. Validation errors arrive as a database round-trip instead of a fast 422, and the Pydantic models ended up as little more than shape declarations — which leaves validation responsibilities less clear to someone reading the API code. If I were starting again I'd mirror the cheap checks (ranges, enums, required fields) in Pydantic for fast feedback and keep the database as the authority, rather than treating it as either/or.
Billing and audit decisions
1. Bills are snapshots, not live sums
The naive version recomputes a month's bill from current sales every time you look at it. That's wrong: delete a sale from March and March's history silently changes. But freezing too early is also wrong — a sale added after the bill was generated would never get charged.
The resolution is three-way:
CASE
WHEN bfm.amt IS NULL THEN COALESCE(sfm.amt, 0) -- no bill yet: live total
WHEN bfm.status = 'paid' THEN bfm.amt -- paid: frozen for good
ELSE GREATEST(bfm.amt, COALESCE(sfm.amt, 0)) -- unpaid: new sales count,
END -- deletions never do
GREATEST is the load-bearing word. It makes the number move in one direction
only, which is the behaviour the plant owner actually needs.
2. Cash sales must survive a billing reversal
A sale paid in cash at the counter and a sale paid through the monthly bill are both
status = 'paid', but they are not the same thing. If the owner reverses a month's
billing, the counter sales must not be dragged back to unpaid.
I added a billing_locked flag maintained by two BEFORE triggers:
anything inserted or updated to paid gets locked. The billing module, which
legitimately needs to override that, sets a transaction-local flag its own trigger checks:
IF current_setting('app.skip_billing_lock', true) = 'on' THEN
RETURN NEW;
END IF;
So a human clicking “paid” in the UI marks the row as locked against billing reversal; the billing module flipping the same column leaves it reversible. Same column, same trigger, different meaning depending on who is writing — and the distinction is enforced rather than remembered.
3. Audit attribution without touching every UPDATE
Every row records who last changed it. Rather than threading modified_by through
a dozen UPDATE statements, each procedure sets a transaction-local PostgreSQL setting once:
PERFORM set_config('app.user_id', v_user_id::text, true);
and a single trigger on customers, sales and bills
stamps modified_at and modified_by from it. The true
matters — it scopes the setting to the transaction, so it can't leak across a pooled
connection into someone else's request.
Keeping dispatch batches atomic
The daily dispatch writes a lock row plus one sale per customer in a single batch. If insert thirty fails validation, a half-dispatched day is worse than no dispatch: the lock says “done”, the sales say otherwise, and nobody can tell which customers were recorded.
The request uses one transaction so dispatch records succeed or fail together. This simplified excerpt shows the success path; error handling and connection cleanup are omitted:
def GET_DB():
connection = connect(**DB_CONFIG)
cursor = connection.cursor()
yield cursor
connection.commit()
A RAISE EXCEPTION on any sale rolls back the lock row with it. The day stays
unlocked and the operator retries cleanly.
Elsewhere I leaned on constraints rather than locks. send_bills_for_month uses
INSERT ... ON CONFLICT DO NOTHING RETURNING bill_id inside a CTE and counts the
rows returned, so “send all bills” is safely re-clickable and honestly reports how many were
actually new. The uniqueness guarantee is
UNIQUE (cust_id, bill_month, bill_year) — the database refuses the duplicate, so
the application never has to check for one.
Current limitations and planned improvements
The current implementation has limitations in database setup, query performance, and concurrent dispatch handling. The following changes are proposed improvements, not completed fixes.
Date filtering and indexing
Date filters apply functions to created_at, including casts to dates and
month extraction. These expressions can prevent direct use of a conventional index on the
timestamp column. I would rewrite the filters as half-open date ranges and evaluate indexes
on created_at and (cust_id, created_at) using query plans and representative data.
The benefit needs measurement as the dataset grows.
The migration set can't rebuild the database
The repository’s SQL files do not yet reproduce the production database: one file is
commented out, and the sales table definition is incomplete. Some routines were
created directly in production. This makes a clean setup unreliable and is the highest-priority
improvement: bring all definitions into version control and verify a complete rebuild through
ordered migrations.
Reducing database round trips
Dispatch currently makes one CALL round trip per customer. Passing a jsonb array
and looping server-side would make it one.
Preventing duplicate dispatches
The check for an existing daily dispatch happens separately from dispatch submission, and the dispatch log has no unique constraint for the business date. Concurrent requests can therefore create duplicate dispatches. I would enforce uniqueness in the database using an explicit business date, with the plant’s timezone defined, and handle duplicate submissions within the transaction.
Stack
Written by Muzamil Ali