Stage 2 · First Version · Chapter 14

How to Build a Sales Invoice That Never Saves Half a Sale

A sale touches stock, cash, customer balance and the books. Here is how to make it all-or-nothing with one database transaction, and what broke when we did not.

Dr. Yahia Elkhouli · November 5, 2026 · 7 min read

In April 2026, a small cash sale was made at the cashier screen in one of our own testing accounts. The invoice was saved. The cashier's shift showed the sale. But the cash box never received the money. There was no error on the screen. Nobody would have known until the drawer was counted, and in a real shop the cashier might have been blamed for stealing.

The cause was the way the sale was built. Completing a sale made four separate calls to the database, one after another: create the invoice, add its items, update the shift totals, record the money in the cash box. The fourth call failed, probably a short network drop, and the code caught the error and wrote it to a log nobody reads. Three of four steps had happened. Half a sale is worse than no sale, because it looks finished.

A few weeks later I checked a real customer's drawer by hand and found two opposite half-writes on the same day: one sale that never reached the cash box, and one expense that never left it. They almost canceled each other, leaving a difference that looked like rounding. Matching totals are not proof of correct data.

The short answer

Build each sale as one database function that receives the whole invoice and runs every step inside a single transaction. A transaction is a group of steps the database treats as one unit: if any step fails, it undoes all of them. That way a sale either happens completely or not at all, and the invoice, stock, cash box, customer statement and journal entry always agree.

What one sale really touches

Beginners think a sales invoice is a document with a total. In a business system it is the start of a chain of changes. An invoice has a header (number, date, customer, seller, payment method), lines (product, quantity, unit, price, an optional discount) and totals (subtotal, whole-invoice discount, tax, delivery, final total, amount paid now, amount remaining).

Saving it changes all of this at once:

If any one of these is missing, some screen will show a wrong number. The hard part is that nothing crashes. The data just quietly disagrees with itself.

Why "all or nothing" is the idea that holds it together

Think of a bank transfer. Either the money leaves your account and arrives in the other one, or neither happens. Nobody accepts a bank that sometimes does only the first half.

The same idea has a name in databases: an atomic operation, from the Greek for "cannot be split". You get it by putting all the steps inside one transaction, usually inside one database function. If the stock step fails because stock is short, the database undoes the invoice that was already inserted, and the user sees a clear refusal instead of a half-finished sale.

Calling the steps one by one from the app is the opposite. Four or five separate calls mean a failure in the middle leaves half a sale. Errors are easy to hide in a log. And "it worked when I tried it" says nothing about the day the network drops.

Step 1: Move the sale into one function

Today the main sales paths in KashBoss are all-or-nothing: the cashier's sale goes through one function that receives the whole basket, and the sales rep's sale goes through another. This is the prompt we use to ask for it:

THE PROMPT
Build the sale as one database function called [FUNCTION NAME].
It receives the whole invoice: header, lines, payments, in one call.
Inside one transaction it must: save the invoice and lines, deduct stock
in the right warehouse, record cash in the right cash box, update the customer
statement for any unpaid part, and post the journal entry.
If any step fails, everything is undone and a clear message is returned.
Take the company and user from the login session, never from the request.
Then show me a test where the stock step fails, and prove nothing was saved.

The last line matters most. A test that forces one step to fail is the only real proof that the rollback works.

Step 2: Put discount limits in every place

In August 2026 we found two invoices with negative totals, caused by a discount larger than the invoice. The web screen had a guard against it. The mobile screen did not. The fix has to cover web, mobile, the cashier and the database itself, with two rules that never bend: a discount cannot make the total negative, and a percentage cannot exceed 100.

There is a second trap about where a discount is stored. Most of our customers discount line by line, so the invoice-level discount field is zero. Our return screens read only that field, so customers who returned discounted goods were refunded the full price. We wrote one shared calculation for the remaining value and made every return screen use it.

Step 3: Cash, credit and the customer statement

A cash sale is paid now. A credit sale means the customer pays later and his balance grows. Between them sit partial payments, prepayments and split payments. All of them must end with the same truth in three places: the invoice, the cash box and the customer statement.

Two real bugs lived here. The point-of-sale screen filled the prepayment box with the full total even for credit sales, so an invoice was recorded as paid and money appeared in a cash box that nobody had received. And a sales rep's function wrote a statement line only when something remained unpaid, so fully paid invoices never appeared in the customer's detailed statement. Our settled rule is one statement line per invoice: debit equal to the total, credit equal to what was received at the time of sale.

Step 4: Edit by reversing and redoing

Never edit an issued invoice in place, and never delete it. Reverse every effect of the old version (stock, journal, cash box, customer statement), then apply the new version as if it were new. Inside one transaction, a failure leaves the old invoice untouched.

THE MISTAKE WE MADE

Two months after we built invoice editing, we found that canceling an invoice that had been edited reversed every version it ever had, not only the live one. One invoice was created, then edited five times, each edit correctly reversing the previous version. When it was canceled, the system reversed all of them again at once: eleven reversals and 27 journal entries for a single invoice. The books for every edited-then-canceled invoice were distorted, and about 350 more invoices were exposed. The fix writes one reversing entry with the net effect on each account, so the invoice's total effect becomes zero however many edits it had.

Testing that fix with a real call found a second, separate bug that no code reading had found: at some companies, cancellation could not find the fiscal period, and it had been undoing money and stock while leaving the books untouched.

Measure before you fix

In May 2026 I asked the AI to audit why some operations were missing journal entries. It read the code and reported five places that swallow errors silently. I pushed back, because I make invoices every day and the journal worked. When we measured on real data, only 1 of 117 sales invoices was missing its entry. But sales returns were failing every time since a certain date, because the app sent a parameter the database function did not have. The code-reading audit found the theoretical pattern and missed the real frequency.

So before any fix, count how often the problem happens on real production data, and sort the work by measured failure rate. In September the AI also called one invoice service "not atomic" and the most dangerous item on the list. The code it quoted really was careless, but no screen called it. It was dead code. Now I always ask for one extra check: show me that this code actually runs.

Key takeaways

Chapter 14 of the book covers returns without an original invoice, canceling paid invoices and the full checklist.

Frequently asked questions

What is an atomic transaction in an invoicing system?

It is a group of database steps that succeed or fail together. If saving the invoice, deducting stock and recording the cash all sit in one transaction, a failure in any step undoes the others. The user never ends up with a saved invoice and missing money.

Should I delete a wrong invoice or cancel it?

Cancel it. Deleting destroys the history you need when numbers disagree, and it breaks invoice numbering. A canceled invoice stays visible and marked, and its effects on stock, cash and the books are reversed.

Can an AI assistant build a safe invoicing module?

Yes, if you ask for the right structure. Tell it to put the whole sale in one database function, take the user from the login session, and prove with a forced failure that nothing is saved. Then measure the result on real data instead of trusting a confident summary.