24 min read · ERP and CRM

Sales sees 50 units in the system and promises the customer delivery, but the warehouse says 30 of them are already reserved for another sales order. In another case, the online store shows the item in stock, two customers order at the same time, and only one unit is left. Or the warehouse counts stock and finds 4 units missing while 8 are already reserved, so the sellable quantity turns negative. All three problems come from using one number to answer three different questions.
This article builds a stock movement table (a ledger) and uses SQL to compute three quantities from that one table. There is code you can run yourself, real output, and a reconciliation query for when you keep a cached balance for fast reads. Executives can read the explanations and tables to see which number answers which question. Engineers can run it right away.
The real problem: one quantity column cannot say how much you can sell
A first stock system usually has a single quantity column in the product table. Receiving adds to it and selling subtracts from it. The problem is that this column has no history. You cannot tell why it holds this number, and it does not separate goods on the shelf from goods someone has already reserved. When the number is wrong, there is no way to trace when it went wrong.
Consider three hypothetical scenarios, not projects of any BT San customer.
- A parts distributor: two salespeople quote the same lot of bolts to two customers. The system shows the total warehouse quantity without subtracting reservations. Both promise delivery, but there is enough stock for only one.
- An online store with two warehouses: stock is transferred from the Bangkok warehouse to Chiang Mai. During the transfer, the company total drops temporarily because the outbound and inbound entries are recorded on different days. The manager thinks goods are missing.
- A factory that counts raw material stock periodically: it finds less on hand than in the system and overwrites the number. Production orders that reserved that material are now over-reserved against real stock, and no one knows. There is no record of who changed it or when.
All three cases are solved by one structure: store every event that brings goods in, takes them out or reserves them as a row in a ledger, and make every balance a sum over the ledger.
Three questions, three numbers, and the names ERP systems use
| Number | Answers the question | Definition in this example |
|---|---|---|
| on-hand | How many units are physically in the warehouse? | Sum of on_hand_delta |
| reserved | How many units are already reserved for other orders? | Sum of reserved_delta |
| available | How many units can sales promise to a new customer? | on-hand minus reserved |
Names and definitions differ by product. In the Odoo documentation (version 19), on the Forecasted report page, On Hand is the stock that physically exists in the warehouse. Incoming is the quantity expected from confirmed purchase orders or manufacturing orders. Outgoing is the quantity reserved for sales orders or other outbound operations. Forecasted is the stock level expected from confirmed and planned operations. The Reservation methods page describes how products are reserved on a delivery order, for example reserving when the sales order is confirmed if stock is available, or reserving manually.
| Topic | What the documentation says | Effect on our design |
|---|---|---|
| On Hand in Odoo | Stock that physically exists in the warehouse (Forecasted report page, version 19) | Matches our on-hand |
| Forecasted in Odoo | The stock level expected from confirmed and planned operations, including incoming goods | A different question from available. This example does not calculate incoming goods |
| Reservation | Odoo has several reservation methods, for example reserving when the sales order is confirmed, or reserving manually (Reservation methods page, version 18) | You must define when to reserve. In the example, the reserve() function does it |
| SQLite writes one transaction at a time | The SQLite documentation states that many transactions can read at once but only one can write, and BEGIN IMMEDIATE starts a write transaction right away | The example uses BEGIN IMMEDIATE to prevent overlapping reservations |
| PostgreSQL SELECT FOR UPDATE | Locks the selected rows until the end of the transaction. Others who try to lock or modify the same rows must wait | Use it when you move to a real database |
| Window functions in SQLite | Supported since version 3.25.0, including SUM() OVER (ORDER BY ...) | Used to show the running balance after each row |
The numbers in this article are hypothetical. In this article, available = on-hand minus reserved, but some real systems also subtract quarantined goods or goods awaiting inspection, or add incoming goods. Write the definition down clearly before writing the query.
Overview of the example
All the code is in the folder examples/on-hand-reserved-available-stock/. It uses only Node 24 built-ins, namely node:sqlite, with no npm install. The database lives in memory and is rebuilt on every run.
| File | Purpose |
|---|---|
| schema.sql | The tables items, warehouses, stock_moves (the ledger) and stock_balance (the cached balance) |
| seed.sql | 12 hypothetical events, and a cached balance that is deliberately wrong |
| queries.sql | Four sets of queries: availability, negative_available, history, reconcile |
| stock.ts | Opens the database, runs queries by name, and reserve(), which reserves in a single transaction |
| demo.ts / stock.test.ts | A script that prints the results, and a node:test suite of 5 tests |
Step 1: Design the ledger: add rows only, never overwrite
One row is one event. It has two numeric columns: on_hand_delta (how much the physical stock changed) and reserved_delta (how much the reservation changed). Shipping is the only event that reduces both columns at once, because the goods leave the warehouse and the reservation is used up.
-- ledger: เพิ่มแถวอย่างเดียว ไม่แก้ ไม่ลบ
-- on_hand_delta = การเปลี่ยนของที่อยู่ในคลังจริง, reserved_delta = การเปลี่ยนของที่ถูกจอง
CREATE TABLE stock_moves (
id INTEGER PRIMARY KEY,
item_id INTEGER NOT NULL REFERENCES items(id),
warehouse_id INTEGER NOT NULL REFERENCES warehouses(id),
kind TEXT NOT NULL CHECK (kind IN
('receipt','reserve','unreserve','ship','return','adjust','transfer_out','transfer_in')),
on_hand_delta INTEGER NOT NULL DEFAULT 0,
reserved_delta INTEGER NOT NULL DEFAULT 0,
ref TEXT NOT NULL,
note TEXT,
-- ประเภทกับเครื่องหมายต้องไปทางเดียวกัน กันบันทึกผิดทิศ
CHECK (kind <> 'receipt' OR (on_hand_delta > 0 AND reserved_delta = 0)),
CHECK (kind <> 'reserve' OR (on_hand_delta = 0 AND reserved_delta > 0)),
CHECK (kind <> 'unreserve' OR (on_hand_delta = 0 AND reserved_delta < 0)),
CHECK (kind <> 'ship' OR (on_hand_delta < 0 AND reserved_delta <= 0)),
CHECK (kind <> 'return' OR (on_hand_delta > 0 AND reserved_delta = 0)),
CHECK (kind <> 'transfer_out' OR (on_hand_delta < 0 AND reserved_delta = 0)),
CHECK (kind <> 'transfer_in' OR (on_hand_delta > 0 AND reserved_delta = 0))
);- There is no UPDATE or DELETE on stock_moves. If an entry is wrong, add a correcting row (adjust) with a note. The history is always complete.
- CHECK prevents entries with the wrong sign, for example a receipt with a negative quantity. The database rejects it by itself, so you do not have to hope every screen writes it correctly.
- ref holds the source document number (PO, SO, TR, CNT) so you can trace back to the document.
- A transfer between warehouses is two rows: transfer_out at the source and transfer_in at the destination. This example writes both rows at once. A real system where goods take time to travel should have a separate in-transit status.
Step 2: Hypothetical data: every event that changes a balance
INSERT INTO stock_moves (item_id, warehouse_id, kind, on_hand_delta, reserved_delta, ref, note) VALUES
-- BOLT-M8 ที่ BKK
(1, 1, 'receipt', 100, 0, 'PO-001', 'รับเข้าจากผู้ขาย'),
(1, 1, 'reserve', 0, 30, 'SO-101', 'ใบสั่งขาย A จอง 30'),
(1, 1, 'reserve', 0, 20, 'SO-102', 'ใบสั่งขาย B จอง 20'),
(1, 1, 'ship', -30, -30, 'SO-101', 'หยิบและส่ง SO-101 ตัดของจริงพร้อมคืนยอดจอง'),
(1, 1, 'unreserve', 0, -20, 'SO-102', 'ลูกค้ายกเลิก SO-102'),
(1, 1, 'return', 5, 0, 'SO-101', 'ลูกค้าคืน 5 ชิ้น สภาพดี'),
(1, 1, 'transfer_out', -25, 0, 'TR-01', 'ส่งไปคลัง CNX'),
(1, 2, 'transfer_in', 25, 0, 'TR-01', 'รับจากคลัง BKK'),
(1, 2, 'reserve', 0, 10, 'SO-103', 'จอง 10 ที่ CNX'),
-- SENSOR-A ที่ BKK: ของ 10 ชิ้น จอง 8 แล้วนับสต็อกพบว่าหายไป 4
(2, 1, 'receipt', 10, 0, 'PO-002', 'รับเข้า'),
(2, 1, 'reserve', 0, 8, 'SO-104', 'จอง 8'),
(2, 1, 'adjust', -4, 0, 'CNT-01', 'นับสต็อกพบขาด 4 ชิ้น');| Event | kind | on_hand | reserved |
|---|---|---|---|
| Receive 100 | receipt | +100 | 0 |
| Sales orders reserve 30 and 20 | reserve | 0 | +30, +20 |
| Pick and ship 30 | ship | -30 | -30 |
| Customer cancels the order that reserved 20 | unreserve | 0 | -20 |
| Customer returns 5 (good condition) | return | +5 | 0 |
| Transfer 25 to CNX | transfer_out / transfer_in | -25 at BKK, +25 at CNX | 0 |
| Stock count finds 4 missing | adjust | -4 | 0 |
The example deliberately gives SENSOR-A 10 units on hand and 8 reserved, then finds 4 missing, to show the case where available goes negative.
Step 3: Queries for the three balances from the ledger
-- name: availability
-- ยอดต่อสินค้าต่อคลังจาก ledger: on_hand, reserved, available
SELECT i.sku, w.code AS wh,
SUM(m.on_hand_delta) AS on_hand,
SUM(m.reserved_delta) AS reserved,
SUM(m.on_hand_delta - m.reserved_delta) AS available
FROM stock_moves m
JOIN items i ON i.id = m.item_id
JOIN warehouses w ON w.id = m.warehouse_id
GROUP BY m.item_id, m.warehouse_id
ORDER BY i.sku, w.code;GROUP BY item and warehouse, then sum the two columns. available is the sum of on_hand_delta minus reserved_delta over all rows. Nothing stores this number anywhere, so there is no chance of storing it wrong. The cost is that you sum the rows on every query. Speed is covered in the section on real systems.
-- name: history
-- ประวัติของสินค้า 1 รายการที่คลัง 1 พร้อมยอดสะสมหลังแต่ละแถว (window function)
SELECT id, kind, on_hand_delta AS d_on_hand, reserved_delta AS d_res, ref,
SUM(on_hand_delta) OVER (ORDER BY id) AS on_hand_after,
SUM(reserved_delta) OVER (ORDER BY id) AS reserved_after
FROM stock_moves
WHERE item_id = 1 AND warehouse_id = 1
ORDER BY id;This query answers the question of why the number is what it is. Every row has the balance after that event. It helps when someone asks when the goods went missing.
Step 4: Reserve in a single transaction: two orders fight for the last unit
If you read the available quantity and then write the reservation row separately, two requests that read at the same time see the same available quantity and both reservations pass. The check and the write must be in one transaction that others cannot interleave with.
// จองของ: อ่านยอดและเขียนใน transaction เดียว
// BEGIN IMMEDIATE = ขอสิทธิ์เขียนก่อน ทำให้ใบสั่งสองใบไม่อ่านยอดเดียวกันพร้อมกัน
// ข้อจำกัด: SQLite ล็อกทั้งฐาน; PostgreSQL ใช้ SELECT ... FOR UPDATE บนแถวยอดแทน
export function reserve(db: DatabaseSync, itemId: number, whId: number, qty: number, ref: string): boolean {
db.exec("BEGIN IMMEDIATE");
try {
const row = db.prepare(
`SELECT COALESCE(SUM(on_hand_delta - reserved_delta), 0) AS available
FROM stock_moves WHERE item_id = ? AND warehouse_id = ?`,
).get(itemId, whId) as { available: number };
if (row.available < qty) {
db.exec("ROLLBACK");
return false;
}
db.prepare(
`INSERT INTO stock_moves (item_id, warehouse_id, kind, reserved_delta, ref)
VALUES (?, ?, 'reserve', ?, ?)`,
).run(itemId, whId, qty, ref);
db.exec("COMMIT");
return true;
} catch (e) {
db.exec("ROLLBACK");
throw e;
}
}- BEGIN IMMEDIATE takes the write lock before reading. The SQLite documentation states that BEGIN IMMEDIATE starts a write transaction right away, and you may get SQLITE_BUSY if someone else is writing. A real system needs a retry or a wait.
- If available is less than the amount requested, ROLLBACK and tell the caller the reservation failed. No row is written at all.
- In PostgreSQL, use SELECT ... FOR UPDATE on a row that represents that item and warehouse (for example, the row in stock_balance), so the second request waits until the first one finishes.
Step 5: Reconcile: the ledger against the cached balance
When data grows large, systems often keep a stock_balance table with the balances for fast reads. This table is a copy and it can be wrong. So the example deliberately has part of the code inflate the cached balance of BOLT-M8 at BKK by 3 units, then uses the fourth set of queries to find the row that does not match. The ledger is always the one that is right.
-- name: reconcile
-- กระทบยอด: ledger เทียบยอดแคช แสดงเฉพาะแถวที่ไม่ตรง
SELECT i.sku, w.code AS wh,
l.on_hand AS ledger_on_hand, b.on_hand AS cached_on_hand,
l.reserved AS ledger_reserved, b.reserved AS cached_reserved
FROM (SELECT item_id, warehouse_id,
SUM(on_hand_delta) AS on_hand, SUM(reserved_delta) AS reserved
FROM stock_moves GROUP BY item_id, warehouse_id) l
LEFT JOIN stock_balance b
ON b.item_id = l.item_id AND b.warehouse_id = l.warehouse_id
JOIN items i ON i.id = l.item_id
JOIN warehouses w ON w.id = l.warehouse_id
WHERE b.item_id IS NULL OR b.on_hand <> l.on_hand OR b.reserved <> l.reserved
ORDER BY i.sku, w.code;Real run: balances, negatives, history, reconciliation and a reservation fight
The command node demo.ts gives the output below. The warning line about MODULE_TYPELESS_PACKAGE_JSON goes to stderr and is not in the file, and this run did not show the experimental warning for node:sqlite.
== 1 ยอดจาก ledger (on_hand / reserved / available)
sku=BOLT-M8 wh=BKK on_hand=50 reserved=0 available=50
sku=BOLT-M8 wh=CNX on_hand=25 reserved=10 available=15
sku=SENSOR-A wh=BKK on_hand=6 reserved=8 available=-2
== 2 รายการ available ติดลบ
sku=SENSOR-A wh=BKK on_hand=6 reserved=8 available=-2
== 3 ประวัติ BOLT-M8 ที่ BKK พร้อมยอดสะสม
id=1 kind=receipt d_on_hand=100 d_res=0 ref=PO-001 on_hand_after=100 reserved_after=0
id=2 kind=reserve d_on_hand=0 d_res=30 ref=SO-101 on_hand_after=100 reserved_after=30
id=3 kind=reserve d_on_hand=0 d_res=20 ref=SO-102 on_hand_after=100 reserved_after=50
id=4 kind=ship d_on_hand=-30 d_res=-30 ref=SO-101 on_hand_after=70 reserved_after=20
id=5 kind=unreserve d_on_hand=0 d_res=-20 ref=SO-102 on_hand_after=70 reserved_after=0
id=6 kind=return d_on_hand=5 d_res=0 ref=SO-101 on_hand_after=75 reserved_after=0
id=7 kind=transfer_out d_on_hand=-25 d_res=0 ref=TR-01 on_hand_after=50 reserved_after=0
== 4 กระทบยอด ledger กับยอดแคช
sku=BOLT-M8 wh=BKK ledger_on_hand=50 cached_on_hand=53 ledger_reserved=0 cached_reserved=0
== 5 จองชิ้นสุดท้าย (BOLT-M8 ที่ BKK เหลือ available 50)
SO-201 ขอ 40 -> true
SO-202 ขอ 40 -> false (เหลือแค่ 10)
SO-203 ขอ 10 -> true
== 6 ยอดหลังจอง
sku=BOLT-M8 wh=BKK on_hand=50 reserved=50 available=0
sku=BOLT-M8 wh=CNX on_hand=25 reserved=10 available=15
sku=SENSOR-A wh=BKK on_hand=6 reserved=8 available=-2
- Part 1: BOLT-M8 at BKK has 50 on hand, none reserved, so 50 are sellable. At CNX it has 25 on hand and 10 reserved, so 15 are sellable. The company total of 75 does not change because of the transfer.
- Part 2: SENSOR-A has 6 on hand (10 received minus 4 missing) and 8 reserved. available is -2, which means more was promised than exists.
- Part 3: the running balance from the history. Shipping 30 drops on_hand_after from 100 to 70 and reserved_after from 50 to 20 in a single row. Unreserving 20 brings reserved to 0 while physical stock does not change. The return adds 5 to on_hand.
- Part 4: reconciliation finds one row: BOLT-M8 at BKK, ledger 50 but cache 53, which matches the 3 units of error put in on purpose.
- Part 5: available is 50. SO-201 requests 40 and passes. SO-202 requests another 40 and is rejected because only 10 remain. SO-203 requests 10 and passes. Part 6 shows available as 0.
What to do when available goes negative
A negative number is not a bug in the SQL. It is a signal that reality changed after the reservation, for example a stock count found items missing, goods were damaged in storage, or a return was received under the wrong type. Show it as a list so a person can decide. Do not hide it by rounding to zero.
- First check that the adjustment is correct. Recount, or look at the adjust row through the ref column.
- Choose which order to unreserve, looking at the delivery date and the importance of the customer. The cancellation is an unreserve row, not an edit of the original row.
- Or find more stock, for example expedite a purchase or transfer from another warehouse. That goes in as a new row.
- Notify sales and the customers concerned, and record the reason.
The negative_available query in the example builds this report. A real system should run it periodically and alert the responsible team.
The test suite
import { test } from "node:test";
import assert from "node:assert/strict";
import { openDb, query, reserve } from "./stock.ts";
const find = (rows: Record<string, unknown>[], sku: string, wh: string) =>
rows.find((r) => r.sku === sku && r.wh === wh)!;
test("ยอดจาก ledger ตรงกับที่คำนวณมือ", () => {
const rows = query(openDb(), "availability");
// BOLT BKK: 100-30+5-25 = 50 ; จอง 30+20-30-20 = 0
assert.deepEqual([find(rows, "BOLT-M8", "BKK").on_hand, find(rows, "BOLT-M8", "BKK").reserved, find(rows, "BOLT-M8", "BKK").available], [50, 0, 50]);
// BOLT CNX: 25 ; จอง 10
assert.equal(find(rows, "BOLT-M8", "CNX").available, 15);
// การโอนไม่ทำให้ยอดรวมเปลี่ยน
const total = rows.filter((r) => r.sku === "BOLT-M8").reduce((s, r) => s + Number(r.on_hand), 0);
assert.equal(total, 75);
});
test("available ติดลบถูกตรวจพบ", () => {
const neg = query(openDb(), "negative_available");
assert.equal(neg.length, 1);
assert.deepEqual([neg[0].sku, neg[0].on_hand, neg[0].reserved, neg[0].available], ["SENSOR-A", 6, 8, -2]);
});
test("reconcile เจอแถวที่แคชผิดเพียงแถวเดียว", () => {
const diff = query(openDb(), "reconcile");
assert.equal(diff.length, 1);
assert.equal(diff[0].sku, "BOLT-M8");
assert.equal(Number(diff[0].cached_on_hand) - Number(diff[0].ledger_on_hand), 3);
});
test("จองเกินยอด available ไม่ได้ และไม่เขียน ledger", () => {
const db = openDb();
assert.equal(reserve(db, 1, 1, 40, "A"), true);
assert.equal(reserve(db, 1, 1, 40, "B"), false);
const n = db.prepare("SELECT COUNT(*) AS n FROM stock_moves WHERE ref = 'B'").get() as { n: number };
assert.equal(n.n, 0);
});
test("ledger แก้ไม่ได้ผิดทิศ: CHECK ปฏิเสธ", () => {
const db = openDb();
assert.throws(() => db.exec(
"INSERT INTO stock_moves (item_id, warehouse_id, kind, on_hand_delta, ref) VALUES (1,1,'receipt',-5,'X')"));
});Each test compares against numbers calculated by hand from the hypothetical data. If you change a query and the balances drift, or you add an event type and forget to count it, the suite fails immediately. Run it with node --test stock.test.ts. All 5 tests pass.
Real systems: indexes, cached balances, locking, units of measure and lots
- Indexes: the example has an index on item_id and warehouse_id. When the ledger grows to millions of rows, summing everything each time gets slow. Keep a summary balance per period (a snapshot), for example a closing balance at the end of each day, and add up only the rows after the closing point.
- Cached balance table: update it in the same transaction as the ledger write, or use a trigger, and run reconcile periodically. If a mismatch is found, rebuild the balance from the ledger.
- Concurrent reservations: in PostgreSQL, lock the balance row of that item and warehouse with SELECT FOR UPDATE before checking available. Keep transactions short, because the PostgreSQL documentation states that anyone waiting for a lock keeps waiting until the holder finishes.
- Units of measure: if you sell in cases but store in pieces, convert to the storage unit before writing to the ledger, and handle decimals correctly. Use an exact numeric type, not float, for quantities that must match exactly.
- Lots and expiry dates: add a lot_id column to the ledger and calculate available per lot. Goods close to expiry or held for inspection should not count as available. Write that as a rule in the definition.
- Incoming goods: if you want the Forecasted style, add confirmed purchase order quantities as another column. Do not mix them with on-hand.
Hypothetical examples: adapting it to three businesses
Retail and online stores
Reserve when the customer's payment succeeds, and release the reservation automatically if the order expires. The storefront shows available, not on-hand. For low-stock items, reserve with a transaction that locks the row.
A distributor with several warehouses
The complicated parts are transfers and cross-warehouse reservations. Show available per warehouse and in total, with a rule for which warehouse a sales order reserves from first.
A factory that uses raw materials
A production order reserves raw materials according to the bill of materials (BOM). Actual consumption is a ship that reduces both on-hand and reserved. If actual consumption differs from the BOM, record the difference as a separate event so you can analyze waste later.
Common mistakes and a checklist
- Storing one quantity column and overwriting it, with no history and no way to reconcile.
- Answering customers with on-hand when the goods are already reserved.
- Checking available and writing in separate transactions, so two orders reserve at the same time and both pass.
- Shipping goods but not releasing the reservation, so stale reservations pile up until nothing can be sold even though stock exists.
- Recording only the outbound side of a transfer, so goods disappear in transit in the reports.
- Fixing a stock count with an UPDATE instead of writing an adjust row.
- Rounding a negative value to zero to make the report look clean.
- Write definitions of on-hand, reserved, available and incoming goods that sales, the warehouse and accounting all agree on.
- Separate an append-only ledger from a cached balance that can be rebuilt.
- Define the event types and their signs in a CHECK.
- Have reservation check and write in a single transaction.
- Write a rule for when available goes negative: who decides, and within what time.
- Set up a periodic reconciliation job and alert when a difference appears.
- Write a test suite from hand-calculated numbers.
This example is for learning and is not production code. All data is hypothetical. It does not yet cover an in-transit status, lots, quarantined goods, multiple units of measure, or retrying on SQLITE_BUSY. The Odoo field names are cited from the documentation version read on 2026-11-21. The system you use may differ.
References
- Odoo 19 — Forecasted report (On Hand, Incoming, Outgoing, Forecasted) (accessed 2026-11-21)
- Odoo 18 — Reservation methods (accessed 2026-11-21)
- SQLite — Transactions (BEGIN IMMEDIATE, one write transaction at a time) (accessed 2026-11-21)
- SQLite — Window functions (SUM OVER, since 3.25.0) (accessed 2026-11-21)
- PostgreSQL — Explicit locking (row-level locks, SELECT FOR UPDATE) (accessed 2026-11-21)
- Node.js — node:sqlite (Database, DatabaseSync alias, :memory:) (accessed 2026-11-21)




