Consumables Developer Guide - edmozley/freeitsm GitHub Wiki
๐ ๏ธ Consumables - Developer Guide
The internals of Assets โ Consumables (5.8.0). Design and decisions: Consumables - design.
In one sentence: one service, ConsumablesService, is the only writer of eleven tables; stock is an append-only ledger with a running total kept in step inside the same locked transaction, and every other feature - tickets, Watchtower, the bell, Forms, stock takes - reads or writes through that service.
1. ๐ Files
| File | What |
|---|---|
๐ฃ includes/services/consumables.php |
ConsumablesService - items, types, the ledger (move(), reverse()), low stock (checkLow()), stock takes, the differences report, verify() |
๐ฃ api/assets/consumables.php |
GET list, item, meta, movements, people, counts, count, differences, verify; POST save_item, save_type, move, reverse, count_start, count_line, count_finish, count_cancel |
๐ฃ asset-management/consumables/index.php + assets/js/consumables.js |
The list, the item panel, the dialogs; ?item=, ?status=low, ?ticket= |
๐ฃ asset-management/consumables/deliveries.php |
Deliveries: the list, New (lines), one delivery with its Documents panel (inline script) |
๐ฃ asset-management/consumables/stocktake.php |
Stock takes (inline script) |
๐ฃ asset-management/consumables/report.php |
Differences, with an SVG chart drawn in the page - no library |
๐จ assets/css/consumables.css |
All three pages; theme tokens only |
๐ฃ asset-management/settings/index.php, manifest.php |
The Consumables tab; Cap::ASSETS_CONSUMABLES (the tab) and the actions entry for Cap::ASSETS_CONSUMABLES_ADJUST |
๐ฃ includes/capabilities.php |
The two caps |
๐ฃ includes/services/record_fields.php |
A third entity, consumable, scoped by consumable_type_id |
๐ฃ system/custom-fields/index.php, api/system/custom_fields.php |
The Consumables tab, with a type per field |
๐ฃ assets/js/inbox.js, lang/*/tickets.php |
Link to... โ Consumables opens consumables/?ticket=N |
๐ฃ includes/watchtower_queries.php, watchtower/index.php |
Low stock on the Assets card |
๐ฃ includes/services/notifications.php, includes/entity_links.php |
consumable.low_stock; entity consumable โ asset-management/consumables/?item=N |
๐ฃ forms/fill.php |
Reads a Reorder hand-over from sessionStorage |
๐๏ธ database/freeitsm.sql, includes/db_verify_schema.php, api/system/db_verify.php, includes/db_verify_indexes.php (generated), includes/db_verify_modules.php, includes/analyst_lifecycle.php |
The tables, keys, module and lifecycle rows |
๐งช tests/consumables.php |
37 checks on the ledger's rules |
2. ๐๏ธ The tables
| Table | Holds |
|---|---|
consumable_types |
Types; retired (is_active = 0), never deleted |
consumable_stores |
A store per company (tenant_id); location_id waits for stores per site |
consumable_items |
Items: company, type, name, part number, unit, supplier, unit_cost, notes |
consumable_stock |
UNIQUE (item_id, store_id): on_hand, min_level, reorder_point, low_notified_datetime |
consumable_deliveries |
One order: store, company (tenant_id, for the documents' scope), supplier, order_ref (optional), invoice number and date, received_date, note |
consumable_movements |
The ledger - see below; a receipt (and its undo) carries delivery_id |
consumable_counts, consumable_count_lines |
Stock takes; per item expected, counted, difference, unit_cost, value_difference, movement_id |
consumable_audit |
Field-by-field changes to items, types and stock takes |
consumable_fields, consumable_field_options, consumable_field_values |
Custom fields (TypedFields) |
CREATE TABLE IF NOT EXISTS `consumable_movements` (
`id` INT NOT NULL AUTO_INCREMENT,
`item_id` INT NOT NULL,
`store_id` INT NOT NULL,
`kind` VARCHAR(12) NOT NULL, -- receive | issue | return | adjust | count | reverse
`quantity` INT NOT NULL, -- signed: + into the store, - out of it
`balance_after` INT NOT NULL,
`unit_cost` DECIMAL(12,2) NULL, -- valued at this, for ever
`ticket_id`, `recipient_user_id`, `supplier_id`, `invoice_ref`, `invoice_date`, `reason`,
`reverses_id` INT NULL, -- the movement this one undoes
`count_id` INT NULL, -- the stock take that posted it
`analyst_id` INT NULL,
`source` VARCHAR(20) NOT NULL DEFAULT 'app', -- app | ticket | api
`created_datetime` DATETIME NOT NULL, -- UTC
UNIQUE KEY `uq_consumable_movements_reverses` (`reverses_id`), -- undone once, never twice
...
);
The ledger's foreign keys are RESTRICT: an item or a store with history is retired, never deleted - deleting would take the books with it.
3. ๐ The ledger's rules
TRAP: nothing updates or deletes a movement. Not the service, not the API, not a migration. A mistake is undone with reverse(), which writes the opposite quantity with reverses_id pointing back; the unique key makes a second undo impossible even under a race.
Every change of stock goes the same way:
$owns = !$conn->inTransaction();
if ($owns) $conn->beginTransaction();
$s = self::lockStock($conn, $itemId, $store); // INSERT IGNORE, then SELECT ... FOR UPDATE
$after = (int)$s['on_hand'] + $signed;
if ($after < 0) throw new ServiceError('conflict', 'not_enough', 'Only ' . (int)$s['on_hand'] . ' in stock.');
$mid = self::insertMovement($conn, $ctx, [... 'quantity' => $signed, 'balance_after' => $after, 'unit_cost' => $cost ...]);
$conn->prepare("UPDATE consumable_stock SET on_hand = ? ... WHERE id = ?")->execute([$after, $s['id']]);
if ($owns) $conn->commit();
- Locked: two analysts issuing the last toner at once - the second waits, then sees 0 and is refused.
- Never below zero (Ed): the check is on the locked figure.
balance_afterlets anybody audit a single item's history line by line; the test checks it adds up.verify()returns every stock row whoseon_handdiffers fromSUM(quantity)of its ledger. It never fixes anything; it is for the API's?action=verify, the tests, and anybody wondering.- Price: a receipt with a unit cost different from the item's updates the item's
unit_cost(recorded inconsumable_audit) - Ed: value at the latest receipt. Every movement stores the cost it was valued at.
3b. ๐ฆ Deliveries
Every receipt belongs to a delivery. move('receive', ...) without a delivery_id makes a one-line delivery inside its own transaction (newDelivery()); receiveDelivery() makes the delivery and calls move() per line with its delivery_id. The API's move action unsets delivery_id, so a browser cannot attach a receipt to somebody else's delivery - only receive_delivery creates that link.
public static function receiveDelivery(PDO $conn, ActorContext $ctx, array $in): array
// lines [{item_id, quantity, unit_cost}] - every line's item, company, quantity and price is
// checked BEFORE anything is written, so a bad line never leaves half a delivery booked in -
// even when the caller holds the transaction (the test does) and cannot roll back.
- One company per delivery: every item must belong to the same company, whose store it goes into.
reverseDelivery()reverses every receipt on it not already reversed, with one reason, all or nothing; each undo keeps thedelivery_id, so a delivery's page shows both.saveDelivery()changes supplier, order number, invoice, dates and note, recording each change inconsumable_audit.delivery_id.- Documents:
documentEntityRegistry()['consumable_delivery']-canchecks the delivery's company withanalystCanAccessTenant(),filterisactiveTenantFilter()onconsumable_deliveries.tenant_id,title_sqlfalls back to Delivery #N when there is no order number. The page callsrenderDocumentsPanel('consumable_delivery', $id); nothing else was needed.
3c. ๐ซ Using consumables on tickets, and asking for them on forms
ConsumablesService::ticketItems($ticketId)- the active items of the TICKET's company (not the analyst's active one) with on hand;?action=ticket_items. The right-click flyout#ctxConsumablesSubmenu(populateContextConsumablesSubmenu()ininbox.js) draws them and callsFreeitsmSelectSearch.filterList(sub, ..., {cap: 10, always: true})-alwaysis new: the search box whatever the length.select-search.jsis only loaded on multi-company pages, soensureSelectSearch()fetches it the first time the menu needs it.issueToTicket($ticketId, $itemId, $qty)-move('issue')against the ticket, totickets.user_id,source = 'ticket';POST action=issue_to_ticket.move()refuses an item from another company's stock than the ticket's (ticketTenant(), NULL = Default) - a ticket only ever takes from its own company's store, whichever door was used.forTicket($ticketId)-issued: the ticket's issue / return / reverse movements;requested: the items named by alookupanswer on theconsumablesource in a form submission for the ticket (form_submissions.ticket_id, orticket_forms.submission_id), each withissued_here.loadTicketConsumables()draws both in#stripConsumablePills; the โ on a used one callsreversewith a reason fromshowConfirm({textarea}).- Forms:
FormsService::LOOKUP_SOURCES['consumable']-consumable_items, labelname, searchname+part_number,tenant_coltenant_id,whereis_active = 1,portal_safetrue (item names are what a customer asks for). The builder'sLOOKUP_SOURCESlist and the AI form generator's prompt name it too. A lookup answer is stored{"id", "label"}, so a request keeps saying what was asked for even if the item is renamed. - Asking never moves stock - deliberately no workflow or form action that issues: "issued" means a person handed it over.
4. ๐ Who may do what
| Action | Check |
|---|---|
| Read anything | requireModuleAccessJson('assets') |
| Items, receive, issue, return, undo those, counting a line | plus requireModuleWriteJson('assets') (read-only Assets cannot) |
| Types | plus requireCapabilityJson(Cap::ASSETS_CONSUMABLES) |
| Adjust, undo an adjustment, finish a stock take | Cap::ASSETS_CONSUMABLES_ADJUST - checked in the service (mayAdjust()), so it holds whatever calls it |
ASSETS_CONSUMABLES_ADJUST is declared in the manifest's actions with no restrict: an always-restricted everyday-work capability. Administrators hold it (is_admin holds every capability); anybody else needs a role with it - System โ Roles shows it as Adjust consumable stock and finish stock takes, sensitive.
Company scope: items carry tenant_id; lists use activeTenantFilter(); one item is checked with analystCanAccessTenant(); a ticket with analystCanAccessTicket(); a person with analystCanAccessUser().
5. ๐ Low stock
checkLow() runs after every movement and every save, and never stops the movement that caused it (it catches and logs):
- at or below
reorder_pointandlow_notified_datetime IS NULLโ notify everyone inconsumables_low_notify(a list of analyst ids, ticked in Settings), then set it; - above
reorder_pointโ clear it, so the next dip tells again.
Watchtower's number is ConsumablesService::lowCount() - the same listItems(['status' => 'low']) the link opens, so the count and the list agree (the rule from Watchtower links).
6. ๐ซ From a ticket
inbox.js adds Consumables to Link to... (linkAddChoose('consumables')), opening asset-management/consumables/?ticket=N in a new tab. The page resolves the ticket on the server (analystCanAccessTicket(), its number, subject and requester tickets.user_id) and hands it to the script as CONSUMABLES.ticket; the rows get Issue, and the dialog sends ticket_id, the requester as recipient_user_id, and source: 'ticket'. ticketNote() writes a ticket_audit line (Consumable issued: "1 x USB mouse to Sam Taylor").
7. ๐งพ Reorder
Settings stores consumables_reorder_form (a form id) and consumables_reorder_map (JSON {item, part_number, supplier, quantity, unit_cost, note} โ form field ids), chosen from drop-downs - nothing typed. Reorder:
const target = Math.max(item.reorder_point || 0, item.min_level || 0, 1) * 2;
const suggest = Math.max(1, target - item.on_hand);
sessionStorage.setItem('freeitsm.formPrefill.' + formId, JSON.stringify(answers)); // {field id: value}
location.href = '../../forms/fill.php?id=' + formId;
forms/fill.php (loadForm()) reads that key once, deletes it, and hands it to the existing applyDraftValues() - the function drafts already use. Same tab on purpose: sessionStorage does not follow a link opened with noopener.
8. ๐ Stock takes
startCount()- one open stock take per store.countLine()- expected is what the ledger says at that moment;difference = counted - expectedand its value are fixed then. Counting again replaces the line; both are inconsumable_audit.finishCount()- posts each non-zero difference as acountmovement. It posts the difference, not the counted figure, so stock issued between counting and finishing still comes out right. Clamped at zero (the movement's quantity is what actually changed; the reason keeps expected and counted).differences()- finished stock takes only; by month (built in UTC withDateTimeImmutable-strtotime()in the server's zone gave one month twice and lost another across summer time) and by item, losses and gains summed separately.
9. ๐งฉ Custom fields
RecordFieldsService::ENTITIES['consumable'] with scope_col => 'consumable_type_id' (NULL = every type). fieldsFor($conn, 'consumable', $typeId) returns the shared fields plus that type's; saveItem() drops answers for fields the item's type does not have, and write() records each change in consumable_audit. The person entity's company scope works as before (scope_col => 'tenant_id'); tests/record-fields.php still passes.
10. ๐งช Tests
FREEITSM_TEST_DATABASE=<throwaway db> php tests/consumables.php
57 checks, in a transaction that is always rolled back - including using one on a ticket (to its requester, listed as used, another company's item refused) and a form's lookup asking for one (listed, no stock moved, marked used once used), and deliveries: three lines booked in as one delivery with its order number and value, the order number from the item's side, all or nothing, a single Receive making its own delivery, the order number optional, a header change recorded, documents registered, the list finding a delivery by an item on it, and undoing a whole delivery once: fields per type and their history; receive, issue, the new price; too many refused; 0 and negatives refused; adjust needs the permission and a reason; undo once, an undo cannot be undone, the original never changes; the bell once per dip and again after recovering; one stock take at a time, expected/counted/difference/value, finishing posts the difference with stock issued in between, a stock take's posting cannot be undone, the report; on hand equals the ledger, verify() is clean, and balance_after adds up line by line.