Checking stock on an order
The answer to "is there enough stock?" isn't on the order line. It's on the product. We saved three order lines against a product with 10 in stock and watched a plugin step read the product, take the stock and log the movement, or refuse the line, then read the script that does it.

Every rule so far has looked at the record being saved. An expense limit reads the claim's amount; a purchase-order rule reads the claim's amount again. This one can't: whether an order line can be filled depends on another table, the product's stock.
That's a job a form rule can't do. The browser has the order line in front of it, not the product, and even if it looked the stock up, it couldn't stop two people ordering the last ten at the same moment. A plugin step can, because it runs on the server, inside the save.
We used the Order Stock sample, as in the last article.
Import it from samples/solutions/business-rules-order-stock to follow along. It adds an
Orders — Stock app with Products, Order lines and Stock movements.
An order that can be filled
We added one product, WIDGET, with 10 in stock. Then, in Order lines, we saved a line for 3:

Nothing on the order line changed. The other two tables did. The product is down to 7:

And there's a new stock movement saying why:

Two that can't
A line for 50, with 7 left:

And a line for a product code that doesn't exist:

Both refused, both before anything was stored. The product still says 7.
We also sent the second line straight to the API, with no form involved:
POST /environments/{environment}/data/par_order_line
{ "par_name": "Warehouse top-up", "par_product_code": "WIDGET", "par_quantity": 50 }
400 { "title": "modelapps.record.validation_failed",
"detail": "There is not enough WIDGET in stock." }
Same step, same sentence. An import or another app would get the same answer.
The script
In the maker portal: the sample's solution, Plugin steps, select Take the stock, or refuse the line, Edit code:

Without its comments, it's short:
var code = getValue('par_product_code');
var wanted = getValue('par_quantity');
if (countRecords('par_product', 'par_code', code) == 0) {
throwValidationError('No product has the code ' + code + '.');
}
var matches = queryRecords('par_product', 'par_code', code);
var product = matches[0];
if (product.par_in_stock < wanted) {
throwValidationError('There is not enough ' + code + ' in stock.');
}
updateRecord('par_product', product.id, { par_in_stock: product.par_in_stock - wanted });
createRecord('par_stock_movement', {
par_name: 'Taken for ' + getValue('par_name'),
par_product_code: code,
par_quantity: wanted
});
Four functions do the work on other tables:
| Function | What it does here |
|---|---|
countRecords(table, field, value) |
How many products have this code. It asks the database to count, so it's cheap however many rows there are |
queryRecords(table, field, value) |
The matching products, as a list. Each one is an object: product.par_in_stock, and product.id |
updateRecord(table, id, fields) |
Writes the new stock level to that product. Pass every field you're changing in one object |
createRecord(table, fields) |
Adds the stock movement, and gives back its id |
Three things worth knowing
It all happens in one transaction. The step runs before the write, so the stock update, the movement and the order line are stored together or not at all. If the order line then failed to save for any other reason, the stock would come back. The last article showed this with a second step refusing after this one had taken the stock.
It runs as the person saving. The step reads and writes products with the permissions of
whoever saved the order line. If they can't read products, queryRecords returns nothing for
them. A script is never a way around a permission.
It never writes the table it watches. A script's writes go through the ordinary save, with
its plugin steps. If this step updated an order line, that update could start another run of a
step on order lines, and so on. The platform stops after eight levels, and depth() tells a
script how deep it is, but the real fix is not to do it: write another table, as this step does,
or check a condition first.
Saying how many are left
The refusal says there isn't enough, but not how much there is. A template puts the number in the sentence, which saves the person a trip to the Products list:
if (product.par_in_stock < wanted) {
throwValidationError(`There are only ${product.par_in_stock} ${code} in stock. Order that many, or fewer.`);
}
The number goes in through ${…} because BS Lang won't add a number to text with +. The sample's own messages use +
only to join text to text, which is allowed.
A lookup instead of a code
The sample matches products by a typed code, which is why it needs the No product has the code check. A lookup is often the better design: the order line's Product field points at the product record, the form offers a search, and a product that doesn't exist can't be chosen at all. The step then reads the product directly:
var productId = getValue('par_product');
var product = getRecord('par_product', productId);
if (isEmpty(product)) {
throwValidationError('Choose a product for this line.');
}
getRecord is one read by id, and the existence check comes free with the lookup. Keep a typed code when the lines arrive
from another system that only knows codes, such as an import of a supplier's order; use a lookup when people pick products
on a form. Lookups: linking one record to another covers the field.
Giving stock back
Taking stock when a line is created is half of it. A line that is deleted, or whose quantity changes, should give back what it took. Two more steps, on the same table, do that.
On Delete, return the line's quantity:
var code = getPreValue('par_product_code');
var matches = queryRecords('par_product', 'par_code', code);
if (matches.length() > 0) {
var product = matches[0];
updateRecord('par_product', product.id, { par_in_stock: product.par_in_stock + getPreValue('par_quantity') });
createRecord('par_stock_movement', {
par_name: 'Returned from a deleted line',
par_product_code: code,
par_quantity: getPreValue('par_quantity')
});
}
On Update, take or return only the difference, getValue('par_quantity') - getPreValue('par_quantity'), and refuse if
the extra isn't there. Write the three steps' shared work, find the product, move the stock, write the movement, once in a
solution script, so the three can't disagree about how stock moves.
The movements are the history
The Stock movement table is worth more than it looks. Every change to stock writes one row, saying what moved, how much and why. That gives you, for free:
- an explanation for every stock level: add up a product's movements and you get its stock;
- a report of what moved this month, grouped by product, from a saved query with totals;
- a way to find mistakes: a movement for a line that no longer exists points straight at the problem.
This is the pattern to copy whenever a script changes a number on another record: change the number, and write down why, in the same transaction. With auditing on the product table, the log also shows each change to the stock level, with the step named as the agent.
When two orders arrive at once
The sample says it plainly: two lines saved in the same instant can both read 7 and both be filled. For most businesses that is rare enough to live with, and the movements make it easy to spot and correct. Where it can't be tolerated, the answer is not a cleverer script but a different design: reserve stock through a process that a single person or queue works through, or hold stock in a system built for it and ask that system through a Custom API. Treat this step as the pattern for reading and writing other tables, which is what it teaches.
Questions that come up
Why does the step run before the write, not after? Because it may refuse. After the write, the order line would already be stored, and a refusal could only report a problem. Before the write, a refusal undoes the line, the stock and the movement together.
Can the person saving see the product table? They need to, or queryRecords finds nothing for them and the line is refused
as if the product didn't exist. Give the order-takers' role read access to products, and update access if the step's
updateRecord is to work for them.
Could this be a form rule? A form rule can't read the product, can't write the movement, and can't stop an import. Only a step on the server can do all three, every time.
Limits
queryRecordsmatches one field against one value. For ranges, several conditions or a sort, userunQuery, which takes the same query the Advanced Find builder produces.- A query returns at most 200 rows. A question about every row is a report's job.
- The check reads the product and then updates it. Two lines saved at the same instant can both read 7. Treat this step as the pattern, not as a warehouse system.
Try it
Add a second product and a line for each. Then add a plugin step on Stock movement, Create,
that refuses a movement for more than 100, and save a line for 150 of a product you've stocked
with 500. The order-line step's createRecord triggers the movement step, and the refusal
undoes everything, stock included.
Next: a claim approved by the server: a step that doesn't refuse anything, but sets values on the record as it's saved.