00 / ABSTRACT
The software grew as my understanding did.
I didn’t start with a complete ERP in my head. I started with CMO orders, mapped the work in Miro, and built from there. Each new workflow exposed a different part of the business—and a different set of things I needed to learn.
PCD brought stock, client-specific rates, taxes and invoices. Manufacturing brought formulations, materials and production stages. LRM and CRM brought the people on either side of an order: the lead who might become a client, and the client a rep needs to keep looking after.
My work ended up spanning the interface, database, integrations and business rules. This case study follows that progression, including the early coding struggles, the database restructure and the places where AI helped—and needed checking.
Workflow design · Data modelling · Legacy integration · Operational software · AI-assisted development
START WITH THE WORK
CMO was the simpler
place to begin.
CMO started with a straightforward question: what does the client want to make, and how does that fit the company’s manufacturing capabilities? It still needed approvals, rates and handoffs, but it gave me a more contained workflow to start with.
Before thinking about screens, I mapped the pipeline in Miro. Who places the order? Who reviews the commercial details? When does Purchase take over? Where does approval happen? Drawing those handoffs made the design problem easier to see.
My first attempt at coding it by hand was rough. I wasn’t a particularly strong coder at that point, and trying to work out the business process and the implementation at the same time became a mess.
Then I found Claude. It helped me write code much faster, especially when I could give it a small, well-defined piece of a complex problem. It also hallucinated things. I learned to use it in bounded sections, inspect the result and check it against the workflow, rather than assume a confident answer was a correct one.
The rate-check workflow became more involved too. A rep can request a composition with its quantity and packing; Purchase collects manufacturer offers before an authorized reviewer sets the billing price. The code also normalizes free-text compositions: changing the ingredient order or spacing should not create another identity, but changing the strength must still matter. Suggestions help someone find a match; they do not automatically approve a formulation.
- 01The brief
What does the client want made?
- 02Commercial review
Can we make it, and at what rate?
- 03Purchase & approval
A manufacturer, a PO and a commitment.
- 04Make & deliver
Track the handoffs through to receipt.
THE PROBLEM GETS BIGGER
PCD made “place an order”
a much bigger sentence.
After CMO came PCD: selling the company’s own stock, at rates that could differ from one client to another. Now the order form depended on inventory, batch expiry, pricing and the information needed to generate an invoice.
I had to learn the vocabulary as I went: HSN codes, GST, IGST, CGST and SGST, and how those details belonged in the billing workflow. This part took me a couple of weeks. A form that looked simple on the surface had a lot of accounting assumptions underneath it.
The company already used Marg, its legacy ERP. I needed to understand the API, interpret its responses and turn that data into something the web application could use. Stock, rates and party references had to make sense on both sides. I was connecting the existing accounting system to the new workflow, rather than pretending it could be ignored.
The stock problem also needed more precision than a single product quantity. An allocation has to know which batch it came from, whether that batch is usable, and what to restore if the bill is reversed. Two people billing at once should not both get the same last box.
Client rate, margin and approval
Available batch, quantity and expiry
HSN, tax treatment and billing details
Marg stock, rates and party references
IMPLEMENTATION NOTE / STOCK INTEGRITY
A small SQL clause with a real job.
I keep stock allocation inside a transaction. Eligible batches are locked before they are consumed, and the allocation history is recorded with the billing change. A failed operation rolls back together.
select sb.* from public.stock_batches sb
where sb.product_id = v_order.product_id
and sb.qty_remaining > 0
and not public.stock_batch_expired(sb.expiry_date)
order by sb.received_at asc for update;Excerpt: the repository’s PCD billing transaction. The surrounding function validates the order and records the allocation.The rate calculators grew out of the same distinction. CMO pricing starts from materials and manufacturing inputs. PCD pricing follows a different commercial route, including the client’s rates. Treating them as one generic calculation would have hidden the part that mattered.
LEARNING THE FACTORY
Manufacturing needed
its own mental model.
Manufacturing was another substantial undertaking. I had to map the production process, learn what the terms meant and understand the rules and controls people worked with. It wasn’t enough to copy the trading pipeline and rename a few stages.
Formulations, BOMs, raw materials, packaging and finished goods describe different things. I needed a model that could retain a formulation or material plan for a similar product later, and support calculations for individual compounds at the required batch scale.
The distinction I kept coming back to was definition, plan and execution. What is the product? What should be used to make it? What actually happened in this batch? Mixing those questions together would make reuse, corrections and traceability harder.
What is the item?
Finished goods, raw materials, packaging and intermediate / WIP.
What should go into it?
BOM quantities, formulation, batch scale and the process route.
What actually happened?
Batch identity, material use, stage confirmations, packing and QA.
In the ERP, the production workflow already coordinates release, material readiness, artwork, production approval, dosage-specific stages, packing and QA dispatch. Those handoffs make the process visible across the people involved, with recorded confirmations instead of an order simply appearing to be “in production.”
Partial quantities are a good example of why the model matters. Packing can stay open while an already-packed portion moves to dispatch. The logic keeps the ordered, packed and dispatched amounts separate, caps dispatch at the available packed quantity and distinguishes “the rest will follow” from an explicitly final short quantity. That gives the team a way to describe what actually happened without quietly rewriting the original order.
I’m taking the deeper formulation, BOM and batch-record model forward in the dedicated Stellar MFG app. That is ongoing work; the existing ERP’s production coordination and the app’s direction are related parts of the project, at different stages.
BEFORE THE FIRST ORDER
350-plus leads a week.
Each one needs a next step.
LRM came after the order and manufacturing workflows. The company receives more than 350 leads in a week, and reps need to follow through with each one. I wanted the system to make the owner, history and next action visible.
The enquiry type matters here too. CMO and PCD leads need separate routing. I built intake, assignment and redistribution around that distinction, with notes and history attached to the lead rather than scattered across individual follow-ups.
A returning IndiaMART enquiry creates another subtle problem: a new message is not necessarily a new person. The intake code normalizes the phone number and can reuse the existing lead identity across sources, while preserving earlier enquiry and note history. An active conversation also needs protection from being casually reset by a fresh enquiry.
An unanswered call should leave the team with another action. The shuffle moves an unreached lead through an eligible rep pool, respecting the configured contact window and limits and remembering who has already held it. Managers can inspect the leads that exhaust that route.
I also built an Android calling companion that reps use as their default caller. It brings the contact’s notes and history into the calling workflow and connects call outcomes back to LRM. The idea was to make the context available where the conversation happens.
The KPIs help us inspect what happens after assignment: who is working the leads, where follow-ups are sitting, how sources perform and how enquiries progress. I reported an 80% improvement in pickup rate after automatic redistribution. That is my reported operational outcome, rather than a controlled measurement.
AFTER THE FIRST ORDER
A client profile should help
the next conversation.
CRM serves the existing customer. In the company’s PCD model, maintaining orders also matters to maintaining territorial exclusivity—the “monopoly rights” the business works with. Reps need to know who to contact, when an order is expected and what that client normally buys.
I brought client history, products, order patterns and weekly planning into that view. The aim was to help a rep call with intent: to understand the relationship before asking for the next order.
The monopoly-rights map extends that context across India: zones, the party associated with an area, whether the relationship is active and the relevant products. It makes a commercial relationship easier to inspect spatially, rather than leaving it buried in a list.
Weekly targets, rep KPIs and order history connect planning to recorded activity. Stock calculations and recommendations sit alongside that work: what is available, what needs attention and what may need replenishing. These are different views of the same business, so keeping their dates, ownership and definitions consistent matters.
The weekly target calculation has its own business rules. It divides a month by its Monday–Saturday working days while preserving the monthly total after rounding. A closed week’s shortfall carries into the next week once that week starts; surplus reduces the last remaining week first. Explicit management overrides remain commitments rather than being silently redistributed.
WHAT HAD TO CHANGE UNDERNEATH
The database had to grow up
with the application.
There were plenty of bugs along the way: in my SQL, in Supabase integrations and in the UI. Early on, I also had to restructure the database so the system had room to grow. Adding screens wasn’t going to solve a data model that no longer fit the work.
I worked across the database, application and interface rather than treating them as separate projects. A rep’s visible queue has to agree with the records they can read. An approval has to be valid when it reaches the database. A KPI has to mean the same thing in a report as it does in the workflow.
That led to row-level access policies, guarded transitions and transactional stock operations. Purchase costs stay out of restricted rep responses; permissions are checked beyond the visible buttons. Those details became part of the design, because they determine what the interface can honestly promise.
I also built a read-only MCP connector for LRM analysis. It is limited to authorized management accounts and exposes reporting rather than a write path. Contact columns are excluded from the selected data, and free-text output is scrubbed for phone numbers and email addresses—because leaving those columns out does not help if someone typed the same details into a note.
Next.js, React, TypeScript, Tailwind and Zustand for the role-specific screens and shared application state.
PostgreSQL and Supabase for authentication, row access, workflow checks, realtime updates and inventory transactions.
Marg for the accounting connection; IndiaMART enquiry intake for the lead workflow.
Android / Java for calling; maps, document and spreadsheet handling where the workflow needed them.
Vitest business-rule checks, Playwright browser flows and SQL permission / transition probes.
THE CHANGE LOG
Four months,
as the log tells it.
I kept a change log beside the code: an entry for every change someone using the system would notice, written for them rather than for me. Reading it back in order is the most honest account of how Stellar grew. It is less tidy than the chapters above. Things arrive in the order the business asked for them, and the bugs are written down next to the features.
The best entries start with what was wrong. Several begin with “Fixed:” and a sentence that explains why nobody noticed.
- Commits
- 1,226
- Log entries
- 565
- Database migrations
- 606
- Unit + SQL test files
- 108 + 66
July
Getting it to work at all
- Shipped
Initial commit.
The first week’s commit messages read like notes to myself: “PCD”, “new billing”, “xyz”. Orders, billing, purchase orders and printable invoices came first, imported from the spreadsheets the team already used.
Admin control and more RLS.
Row-level security arrived in the first week, before most of the screens did. By the end of the month the messages had become full sentences, and each one said what changed for the person using it.
August
Meeting the legacy system
- Shipped
Marg, end to end.
Encrypted credentials, a from-scratch reading of Marg’s response encoding instead of a vendor DLL, and six separate sync bugs that only showed up once real data started flowing through.
- Found
Every incremental Marg sync had been failing silently.
Marg answered a wrongly formatted date cursor with five bytes of junk instead of an error, which surfaced much later as an unrelated decryption crash. Only a full resync had ever worked. I found it by probing the live API by hand.
- Rule
The rules moved into the database.
Access rules that the app had been checking became checks the database enforces itself, so a request that skips the interface meets the same answer. The app also became installable.
September
Finding out what was really happening
- Found
Stock had never actually been deducted from a batch.
Two billing functions referred to a column name that was also the name of their own output, so Postgres refused every call as ambiguous. The app caught the error and reported “0 units consumed”, which looks exactly like an empty shelf. Every bill so far had gone through without moving a single batch.
Added Vitest.
Business rules started getting tests of their own: target splits, packing quantities, rate matching.
- Shipped
Lead management replaced two spreadsheets.
Two linked Google Sheets, kept in step by a sync job every ten minutes, became one table with a status that only moves forward, and a call-attempt state machine behind it.
- Rule
Status history, written only by the database.
An order’s history stopped being something the app remembered to record. It got a table of its own that only the database writes to.
- Found
A review pass over three days of solo changes.
Builds, lint and tests were clean. The real problem was a rollout gap: one date rule had reached two screens but not the other six, so the same order could land in different weeks depending on which screen was open.
October
Making speed safe
- Rule
A plan for the codebase, written down.
One folder per business flow, data loaded on demand, real URLs so the back button works on a phone, and a throwaway test project that mirrors the live schema. Write flows are never tested on live data.
Both order pipelines enforced in the database.
Billing, stock restore and cancellation each became a single transaction. A Playwright suite started walking every role’s menu and the main order paths against the test project.
- Rule
Agent work verified before merge.
Coding agents worked on their own branches. Before merging one, I replayed its 52 migrations on the test project inside a transaction and rolled it back, so the check ran against the real schema and left nothing behind.
- Found
Requests started timing out.
The incident below.
- Shipped
Calls moved to the phone.
Calling left the browser for the Stellar Phone app, and recordings and transcripts started arriving in the lead’s own history.
Marg became the source of truth for party rates.
Rather than keep two places that could disagree, the ERP follows Marg’s latest rate, with a written tie-break for same-day changes.
November
So far
- Rule
Read-only accounts.
A new person can see what their role sees and change nothing. Every write is refused by statement-level triggers on every table, so the database’s own privileged functions are covered too, not just the screens.
INCIDENT NOTE / 19 OCTOBER
One lookup, run once per row.
The database was up, but requests across the app were failing with timeouts. The logs pointed at the manufacturing orders a sales rep is allowed to read. The policy that decides that called a user-specific lookup for every row it checked, so the cost grew with the table.
Wrapping the lookup so Postgres evaluates it once per query fixed it. For the affected account, the same read went from 158 ms to 11 ms on a quiet database, with the same two rows visible. Before calling it done, a test in a rolled-back transaction compared every account’s visibility with the original rules. The first few minutes after the fix showed thousands of requests and no server errors.
-- before: evaluated for each row
using (id in (select my_order_ids()))
-- after: one evaluation per statement
using (id in (select (select my_order_ids())))Simplified sketch of the change; names shortened. The written incident report also listed three unrelated workflow errors from the same logs, filed for later rather than fixed in a hurry.WHAT THE LOG KEPT SAYING
Silent failures cost the most.
The stock bug, the Marg cursor and early notification failures all looked like normal results. Now errors are surfaced, and a zero that might mean “broken” is treated as suspicious.
Rules belong where they can’t be skipped.
Access, working hours, status history, pipeline transitions and read-only accounts all moved from the interface into the database over the four months.
Speed needs a test bench.
AI agents made the pace possible. A test project, a migration replay and browser tests are what made it safe to merge their work into a system people use every day.
WHAT CHANGED
I got better at asking
what happens next.
Trading made orders easier to follow and plan around, and gave us a way to inspect bottlenecks and places where money was being lost. Manufacturing made the production process more transparent across the people doing the work. LRM brought calling and lead follow-through into view. CRM helped reps maintain contact and plan a more useful conversation with clients.
Across all of them, KPIs give us feedback about the workflow. They are useful when the underlying definitions are clear: an order placed is not a bill made, an assigned lead is not a completed conversation, and a planned quantity is not the actual output of a batch.
I started this work while learning a lot of the domain and the implementation at the same time. The biggest change in how I approach a system is that I now spend more time understanding the work before reaching for the screen. The interface gets easier to design once I know what needs to happen, who owns it and what could go wrong.
Most of the design work was figuring out what a person needed to know before they could take the next step.
NOTES & SCOPE
About this account.
- This is a personal account of a private operational system. The workflow figures are explanatory redraws, not production records or screenshots of the original Miro board.
- The formulation, BOM and batch-record model is part of the dedicated Stellar MFG direction; the existing ERP’s production handoffs are described separately.
- The reported lead volume and pickup improvement come from my account of the project. This page does not present an independently audited impact study.
- The seasonal forecast is implemented with a complete-history gate. Its presence in the code is not a claim of validated forecasting performance or that the necessary history is currently available.
- The demo below is a separate browser-local replica with fictional records. It illustrates role-specific navigation and selected workflows; it is not the live ERP and some screens differ from the current system.
Implementation references behind these details
- Composition matching
src/modules/cmo/logic/composition.tsIngredient parsing, unit normalization and strength-sensitive matching.
- Packing and dispatch
src/lib/packing.tsSeparate quantities, dispatch ceilings and explicit short closure.
- Weekly planning
src/lib/weeklyTargets.tsWorking-day shares, carry-forward and management overrides.
- Seasonal outlook
src/lib/seasonalForecast.tsLead-time-aware forecasting and insufficient-history gating.
- Read-only analysis
src/lib/mcp/lrmMcp.tsContact exclusion, free-text scrubbing and reporting-only tools.
- Workflow context
PROJECT_INSTRUCTIONS.mdPCD billing, usable-stock recommendations, returning enquiries and role boundaries.
I’m interested in work where understanding the problem matters as much as building the answer.