You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Add Stock Report by Location documentation with SQL query and parameters - #171
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Unresolved query defects can misstate inventory quantities and values, assign movements to incorrect locations, and include soft-deleted records or retired identifiers in outpatient debt reports.
Adds two SSMM report pages to the analytics SQL collection, covering location-level stock balances and outstanding dues for accounts linked to non-inpatient encounters.
Changes:
Adds a stock ledger query that calculates quantities and purchase-cost values by product and location.
Adds a patient due query with encounter details, SSMM identifiers, and tags.
Documents report parameters, calculation rules, and deployment-specific assumptions.
File
Description
Care/Inventory/stock_report_by_location_ssmm.md
Adds the stock-by-location query and documents movement handling and date selection.
Care/Accounting/op_patient_due_report_ssmm.md
Adds the non-inpatient account due query and documents parameters and output rules.
The reason will be displayed to describe this comment to others. Learn more.
Analytics SQL Review — Stock report by location (SSMM)
Ticket (ENG-1146, "Stock list by location"): description and comments are empty, so I can't check grain/filters against a spec. Assumed ask: quantity and value on hand per product per location as of a date. The query delivers that shape (name, location, total_qty, stock_value).
Numbers: mostly sound — deleted = FALSE and status exclusions are applied per block, and the ledger-by-union structure avoids fan-out. Open points:
High: LEFT JOIN on emr_deliveryorder in PURCHASES (inline).
Medium: DATE(created_date) filters are not sargable (inline).
Medium: magic location ids need documenting; no facility scoping — confirm intended (inline).
Question: value uses the currentep.purchase_price for historical movements, so a back-dated selected_date is valued at today's price — intended? Worth a line in Notes.
Question: delivery order status isn't checked (only supply delivery status); are cancelled/entered_in_error orders possible with live deliveries?
Lint: no findings. Doc sections, parameters and last-updated date look consistent; file location (Care/Inventory/) and _ssmm suffix are fine.
The reason will be displayed to describe this comment to others. Learn more.
Medium – non-sargable date filter (repeated in every block). DATE(esd.created_date) <= {{selected_date}} defeats the created_date index and scans all history on every run. Use esd.created_date < ({{selected_date}}::date + 1). Note also that DATE() on a timestamptz uses the session timezone — confirm Metabase's timezone matches the intended day boundary.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
The report drops valid orderless dispenses, debits parent locations instead of the actual supplying locations, and uses current movement states for historical cutoffs, producing inaccurate stock balances.
Filtering creation time while testing the current status does not reconstruct stock as of the selected date. A supplier delivery created September 30 as in_progress and completed October 2 is credited in a September 30 report once it completes, even though it was not received then. Use inventory-effective timestamps/status history for historical balances, or describe this as a creation-date cutoff over current movement states rather than an as-of stock report.
The reason will be displayed to describe this comment to others. Learn more.
Analytics SQL Review — Stock report by location (SSMM)
Ticket (ENG-1146): quantity and purchase-cost value of stock on hand per product and storage location, as of a selected date. The description is thin, and the only ticket comment is empty.
Delivers it? Yes. The output has one row per product and location, with total_qty, stock_value and a selected_date parameter. Status filters are sensible: dispenses exclude entered_in_error, cancelled, stopped and declined, deleted = FALSE is applied throughout, and UNION ALL is used correctly. The lint report is clean.
Findings:
High:DATE(created_date) is not sargable, and it appears in every branch.
Medium: the 24 hardcoded location ids need documenting, and I'd like to know about facility scoping.
Low: a misleading comment, an unused CROSS JOIN ex, and valuation at the current purchase_price.
Verdict: the logic reads as sound, and I couldn't run it. Fix the sargability and document the ids before publishing. I'd also check the in-progress transfer and patient-return semantics against real data.
The reason will be displayed to describe this comment to others. Learn more.
High – not sargable.DATE(esd.created_date) <= {{selected_date}} wraps the indexed created_date in a function, so the index is unusable. The same pattern repeats in all six branches (and emr_medicationdispense at line 65). Since this is an "all-time up to date" ledger, it scans the full tables each run. Use a range, which is also still inclusive of the selected day:
The reason will be displayed to describe this comment to others. Learn more.
Analytics SQL Review — Stock report by location (ENG-1146, SSMM)
Ticket: quantity and purchase-cost value of stock on hand per product and storage location as of a selected date. The query delivers this: one row per product × location, total_qty and stock_value, with a selected_date cut-off. Grain, statuses (entered_in_error/cancelled excluded on dispenses; deleted = FALSE throughout) and the movement ledger logic look sound. Lint: parse clean.
Findings (2 inline):
High – DATE(created_date) filters are non-sargable.
Medium – hardcoded location IDs not itemised in Notes; facility scope not explicit.
Minor, not inlined:
Valuation uses the currentep.purchase_price for all historical movements, so "value as of date" is restated at today's price. Worth a Notes line.
The CROSS JOIN ex in the dispense block is unused.
Notes has no output-columns description (name, location, total_qty, stock_value).
Verdict: numbers look trustworthy given the documented assumptions; fix the date filter before putting it on a dashboard.
The reason will be displayed to describe this comment to others. Learn more.
High – non-sargable date filter (repeated in all 6 movement blocks).DATE(esd.created_date) <= {{selected_date}} wraps an indexed column (created_date) in a function, so the index can't be used on these large movement tables. Use a range instead:
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
The report omits valid orderless dispenses, debits parent locations instead of actual stock sources, and credits transfers before completion, producing incorrect stock quantities and values.
The reason will be displayed to describe this comment to others. Learn more.
Analytics SQL Review — Stock report by location (SSMM)
Ask (ENG-1146): quantity and purchase-cost value of stock on hand per product and storage location as of a selected date. The PR delivers the right grain (product × location) and the required selected_date parameter. Lint is clean (parses as Postgres). The doc is well structured, with a movement table and notes.
Concerns before publishing:
The date filter is non-sargable (DATE(created_date)) in all six branches. It also bounds by created_date, not completion date, so "as of" semantics are questionable.
LEFT JOINs combined with WHERE conditions make the intent ambiguous. There is also an unused CROSS JOIN ex.
The 24 hardcoded location IDs are not itemised in Notes, and there is no facility scope.
Valuation uses the current purchase price, and grouping is by name rather than product id.
I could not run the SQL, and I did not verify status values against the care models. The in_progress transfer semantics and the dispense status exclusions look deliberate and are documented. Treat the numbers as plausible but not yet verified until the points above are answered.
The reason will be displayed to describe this comment to others. Learn more.
Medium — undocumented magic IDs and no facility scope. The 24 location IDs in ex are only described as "consumption and error location ids" in Notes. Per house style (see bed_occupancy_ssmm.md), list what each ID is (name, consumption vs error) and when to update it — otherwise nobody can audit the list. Also nothing in the query restricts to the SSMM facility: scoping is implied only by the hardcoded IDs/filename. If emr_facilitylocation holds other facilities' locations, they'll appear in the output; add a facility constraint (e.g. fl.facility_id = ..., documented) or state in Notes that this DB is single-facility.
The reason will be displayed to describe this comment to others. Learn more.
High — non-sargable date filter (repeated in all 6 branches, lines 45/86/107/128/...).DATE(esd.created_date) <= {{selected_date}} wraps the indexed created_date in a function, so the index is unusable and each branch seq-scans the supply-delivery/dispense tables. Rewrite as a range:
Related question on fidelity: "stock as of a date" is bounded by row created_date, not by when the delivery was completed/dispensed. A delivery created before the date but completed after it is counted as on hand. Is created_date the intended proxy?
The reason will be displayed to describe this comment to others. Learn more.
Question — valuation basis. Value uses the currentep.purchase_price for every historical movement, so "value as of a selected date" changes when a product's price is edited later, and mixes batches priced differently. Is current price intended? If so, say so in Notes. Also the final GROUP BY uses the product name (not ep.id), which silently merges distinct products sharing a knowledge name (and all products with NULL epk); consider grouping by ep.id/epk.id and selecting the name.
The reason will be displayed to describe this comment to others. Learn more.
High — LEFT JOINs undone/inverted by the WHERE (purchase branch; same pattern in the dispense branch at the edo/eii/ep joins).LEFT JOIN emr_deliveryorder edo + edo.origin_id IS NULL also matches deliveries with no order at all (the join yields NULL), so they're treated as external purchases, while edo.deleted = FALSE then drops them again — the intent is unclear. ep.purchase_price IS NOT NULL already forces ep to be inner. Make these JOINs so the semantics are explicit, and add an esd.order_id IS NOT NULL-style guarantee via the inner join. Also CROSS JOIN ex in the dispense branch is unused.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
No description provided.