The situation
You are on the backend team of an online shop. The checkout function handles POST /api/checkout: it takes the lines of a customer's cart, reduces stock, creates a paid order and writes an invoice. So you can run it in the browser, the database here is a plain in-memory store object.
Support and finance have both escalated problems:
"The customer was told their checkout failed, but the water bottles they ordered are now out of stock and there's no order on their account."
"We found an order for 1.5 notebooks, and one for -2 water bottles that increased our stock."
The current code changes stock line by line and gives up as soon as a later line fails, so earlier changes are left behind. It also never checks the quantities it is given.
Your tasks
Task 1: Make checkout all or nothing
A successful checkout returns status 201 and creates all of:
- an order with status
paid - a stock decrease for each product
- an invoice
{ orderId, totalCents } with the order total
If any line can't be fulfilled (unknown product or not enough stock), return 409 and leave stock, orders and invoices exactly as they were.
Task 2: Validate the input
- A quantity that is not a positive whole number (
0, -1, 1.5) returns 400 and changes nothing. - Lines for the same product are added together before checking stock. Two lines of 1 notebook need 2 in stock.
Keep the result shape: { ok: true, status, order } on success and { ok: false, status, error } on failure. Make every test in checkout.test.js pass.
Task 3: Explain
At the top of checkout, add a short comment on how your version stays safe, and what would change with a real database where two checkouts can run at the same time.
Project files
index.html
index.js
store.js
checkout.js
checkout.test.js
store.js: createStore() returns a fresh in-memory database: products (with priceCents and stock), orders and invoices.checkout.js: the checkout(store, items) handler you are fixing.index.js: runs one sample checkout (2 Water Bottles and 1 Notebook) and prints the result and the remaining stock.index.html: the page index.js prints into (#out).checkout.test.js: the tests for checkout. Each test starts from a fresh store.styles.css, package.json: project setup. You don't need to change these.
How to check your work
- Tests: press ▶ Run tests next to the Tests heading in the bottom panel. They don't re-run on their own, so run them again after each change. PASS means every visible test passed.
- Preview: the bottom-left panel shows the running app and rebuilds as you type. Use Open in new tab above it, or Copy link and paste it into a new tab, to see it full size. That tab follows your edits.
- Your work is saved in this browser. Reset (top right) puts the starting code back.