Turned an AI-built dairy prototype into an ERP that balances to the gram
How we audited an AI-built dairy platform that passed every demo, then rebuilt it so the rules live on the server, signed records stay final, and every number is either right or honestly absent.
- Client
- Taras P.
- Industry
- Dairy / Food Manufacturing
- Engagement
- Audit & Rebuild
- Duration
- 10 weeks

Key Results
- •Matched to the Gram: Five days of the founder's own records (101 stock movements, 56 tank counts) reproduced exactly, down to 72.478 kg of fat and 85.456 kg of protein lost, with no calculation changed to get there
- •Rules Enforced by the Server: Replaced 192 places where the browser wrote straight into the database with a server that checks permissions on every request
- •Customer Data Kept Apart in Four Layers: An automatic company filter on every query, 73 database-enforced links, a build check that blocks shortcuts, and about 50 tests that try to cross between companies and must fail
- •Records That Stay Final: An append-only movement book corrected only by reversal, closed days that stay closed, and a history written in the same transaction as the change it describes
- •No Number Pretends: Missing data is named instead of shown as zero, losses keep their sign, and litres are converted to kilograms once, with the density used recorded alongside
- •Scheduled Work That Actually Runs: Preventive maintenance checked hourly for every company separately, month-end dates that never drift, and missed dates recorded as missed instead of back-dated
- •Tested Properly: About 365 test files across server and screens, including about 580 tests against a real database, where the prototype had 33
- •Scope That Held: Four modules delivered on a written "basic" scope, with every cut feature priced and kept, not deleted
The Client came to us with a product their customers already liked, and a plan to launch it.
It was a B2B platform for dairy processors in Brazil, built in about ten weeks with Lovable and Supabase. It had seven modules, five languages, dashboards, PDF and Excel exports, scheduled email reports and an integration with customers' ERP systems. One dairy was already using part of it. The plan was simple: fix the known bugs, tighten security, launch, and build a proper version later once revenue came in.
The customers weren't casual users. Dairy plants in Brazil operate under federal inspection (SIF) and food-safety audits like FSSC 22000 and ISO. They keep official records of production, losses and maintenance, and those records have to stand up in front of an auditor. For them, the software isn't a convenience. It's evidence.
Before agreeing to the plan, we read the whole thing: about 93,500 lines of code and 144 database migrations, with every finding traced to a specific file. We found 207 problems. Five of them were in how the system was built, and those five caused a large share of the rest.
What the demo was hiding
The rules lived on the screen
The app hid the "Approve" button from users who weren't allowed to approve. But the database only checked one thing: is this person a member of this company? We counted 192 places where the browser wrote directly into the database, with no server in between. So a view-only employee could publish an official procedure, close a work order or lock a production day. All they had to do was skip the screen.
The same gap let a new sign-up turn on every paid module for free and make themselves the company owner. It also let one company add another company's users and see their contact details.
Records that should have been final weren't
For an audited plant, "signed", "published" and "closed" are promises. In the prototype, signed reports could go back to draft and published documents could be unlocked. The audit trail was written by the screen after the action, and any company member could insert entries, with any name and any date.
The number customers were paying for was wrong
The core module calculated how much milk, fat and protein a plant lost during production. Real losses showed as 0 kg, because the loss was stored with the wrong sign. A 3% loss displayed as 2%, because the percentage used the wrong base. Litres and kilograms were added together, and the official daily record added percentages from different days. Some of the tests checked the wrong sign as if it were correct, so they passed.
None of it crashed. Every number looked authoritative.
These were the patterns that decided the engagement. Patching them one at a time would have meant fixing the same underlying cause in hundreds of places, on a foundation of 144 migrations, 74 of which had replaced rules set by earlier ones. The Client agreed to rebuild, and we kept the prototype as what it really was: the most detailed specification the project could have had.
How we approached it
We agreed what "done" meant before writing code. The first version would cover four modules: Mass Balance, Maintenance, Technical Costs, and Production Planning & OEE. Each was defined in writing as basic: its main workflow works end to end for a real company, with company separation and security built properly, using the smallest useful set of features. Every module got a written "not included" list. Every cut feature got an estimate, 355–532 hours in total, so anything that came back on the table came back with a price.
We chose a stack that enforces structure. NestJS, Prisma and PostgreSQL on the server, with a Next.js frontend. NestJS was chosen deliberately because it makes structure the default, which matters most on exactly the kind of fast-moving build that had gone wrong the first time. PostgreSQL wasn't a close call: the product needs transactions, an audit trail that can't be rewritten, and closings that stay closed.
We made the founder's own spreadsheet the finish line. We didn't decide on our own that the calculations were right. The founder's worked examples would.
We wrote every decision down. Each module has a numbered list of decisions, each with the options, a recommendation and the outcome. Maintenance alone has 27. When a question came back a month later, the answer and its reason were already on paper.
What we built
The server decides, the screen only asks
The browser never touches the database. Every action goes to the server, which checks permissions on every request, not only at login, so a suspension takes effect on the user's very next click. Every work order the server returns carries the steps the current user is allowed to take next, and the screen shows exactly those. The platform's own staff accounts can't read customer data at all.
Keeping each customer's data apart has four layers, so a mistake in one is caught by the next. Every query is filtered to the right company automatically. The database itself refuses any link between two companies' records. A build check fails if code tries to skip the filter. And about 50 tests act as one company and try to reach another's data, passing only if every attempt fails.
A mass balance that means something
Mass Balance answers one question for the plant: where did the milk go?
The arithmetic is simple. The hard part is what the numbers mean. Whey is a by-product, not a loss. Lab samples are a known loss, kept apart from the unexplained one. A dryer evaporates water nobody measures, so its mass is shown but not alarmed, while fat and protein are still judged. Milk moving between two sections inside the plant is counted once, so the sections always add up to the whole plant. A loss keeps its sign, and every percentage states what it's a percentage of.
Inside, everything is kilograms. Milk measured in litres is converted once, when it's saved, and the system records which density it used. If there's no density, it refuses to guess. A missing reading is reported as missing, never filled in with zero.
Final means final
Stock movements go into a book that can only grow. A wrong row isn't edited. It's cancelled by a reversal row and replaced by a corrected one, and the original stays visible. Closed days stay closed: only an admin can add a late entry, and must say why. Published process versions are frozen; changing one means creating a new version. The history is written by the server in the same transaction as the change, so either both are saved or neither is. Nothing in the code can write a history entry on its own.
Screens that never pretend
This was written into the project's ground rules: no placeholder number, no sample chart, no fabricated row. Nothing shows as saved until the server confirms it. A bulk save is all-or-nothing, and if one row is rejected, the screen points at that row and says plainly that the others weren't saved either. If a colleague saved first, you're told which rows changed, and what you typed is kept. Features that aren't built yet appear as a dashed box with one sentence saying what's coming, so they read as planned, not broken.
Behind the screen, the same rule holds. Preventive maintenance is checked hourly on the server, separately for every company, so one company's failure never stops the others. A monthly plan that starts on 31 January falls on 28 or 29 February, 31 March and 30 April, without drifting. If a due date passes while the last order is still open, it's recorded as missed. The prototype had created eight back-dated orders for a single paused plan.
A redesign, halfway through
In October, the founder worked through a redesign with an AI assistant and came back with a 25-page document. Its central idea was right: show a result immediately instead of making users draw their plant as a flowchart first. We built that as a movement book that's entered like a spreadsheet. The existing calculation engine took its data unchanged.
The rest of the document had grown well beyond what the founder asked for. It included a tamper-evident sealed ledger, PIN logins, an AI centre, an offline app and ERP integrations. We sorted it with one rule: what the founder asked for is a requirement; what the AI added goes on a later list, each item with its own price. Nothing was thrown away. Everything was priced.
Where it stands now
At the end of October, five days of the founder's real records went into the system: 101 stock movements and 56 tank counts. It reported 72.478 kg of fat and 85.456 kg of protein lost. His spreadsheet said the same, to the gram. Those five days are now a permanent automated test, and if any future change moves a result by a gram, the build fails.
It worked the other way too. On production efficiency, the system said 84.06% and the founder's spreadsheet said 83.76%. The difference was in the spreadsheet: it counted rejected cheese twice.
Mass Balance, Maintenance and Technical Costs are live. Production Planning is in its final reviews.
The prototype got the founder from an idea to a product customers wanted in ten weeks, and that was worth a lot. What it couldn't do was produce a number a plant manager could hand to an auditor. Almost none of the rebuild went into new features. It went into the questions the prototype never had to answer: what does this number mean, who's allowed to change it, and what does the screen say when the honest answer is "we don't know yet"?
The Stack
Frontend
Next.js • React • TypeScript • TanStack Query • TanStack Table • Zustand • react-i18next • React Flow • Recharts
Backend
NestJS • Bun • Prisma • PostgreSQL • BullMQ • Redis • Resend
Architecture
Modular Monolith • REST APIs • Server-Enforced Workflows • Append-Only Ledger • Exact Decimal Arithmetic
Multi-Tenancy & Security
Automatic Tenant Scoping • Composite Foreign Keys • Per-Request Permission Checks • Rotating Hashed Refresh Tokens • Server-Written Audit Trail
Testing & Reliability
Vitest • React Testing Library • End-to-End Tests Against Real PostgreSQL • Tenant-Isolation Tests • CI Tenant-Scoping Check • Serializable Transactions & Row Locks
If your customers rely on your numbers, and your app was built faster than anyone could check them, it's worth finding out what's underneath before an auditor does.
We'll tell you honestly whether it needs fixing or rebuilding — for free
Reach out at contact@graylining.com