Skip to content

Add Stock Report by Location documentation with SQL query and parameters - #171

Open
sonzsara wants to merge 3 commits into
mainfrom
ENG-1146
Open

sonzsara wants to merge 3 commits into
mainfrom
ENG-1146

Conversation

@sonzsara

@sonzsara sonzsara commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

No description provided.

Copilot AI balanced review requested due to automatic review settings November 2, 2026 05:50

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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.

3 open issues
What changed in this PR

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.

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 2, 2026 05:54

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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 current ep.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.

Generated by Analytics SQL Reviewer for #171 · auto · 20.7 AIC · ⊞ 5.1K

AND esd.deleted = FALSE
AND edo.deleted = FALSE
AND ep.purchase_price IS NOT NULL
AND DATE(esd.created_date) <= {{selected_date}}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved stock-accounting errors double-count excluded-location dispenses, omit orderless dispenses, debit incorrect locations, and credit deliveries before receipt.

5 open issues

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 2, 2026 07:19

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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.

5 open issues
1 previously missed issue

In code that hasn't changed since last review

Medium severity Historical balances use current movement status instead of as-of state

Care/​Inventory/​stock_report_by_location_ssmm.md:45

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.

Review effort: Balanced

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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.

Generated by Analytics SQL Reviewer for #171 · auto · 23.9 AIC · ⊞ 5.1K

AND esd.deleted = FALSE
AND edo.deleted = FALSE
AND ep.purchase_price IS NOT NULL
AND DATE(esd.created_date) <= {{selected_date}}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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:

AND esd.created_date < ({{selected_date}}::date + INTERVAL '1 day')

Copilot AI balanced review requested due to automatic review settings November 2, 2026 07:31

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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):

  1. High – DATE(created_date) filters are non-sargable.
  2. Medium – hardcoded location IDs not itemised in Notes; facility scope not explicit.

Minor, not inlined:

  • Valuation uses the current ep.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.

Generated by Analytics SQL Reviewer for #171 · auto · 20.8 AIC · ⊞ 5.1K

AND esd.deleted = FALSE
AND edo.deleted = FALSE
AND ep.purchase_price IS NOT NULL
AND DATE(esd.created_date) <= {{selected_date}}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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:

AND esd.created_date < ({{selected_date}}::date + INTERVAL '1 day')

(same for emd.created_date).

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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.

4 open issues
1 resolved since last review

Review effort: Balanced

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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.

Generated by Analytics SQL Reviewer for #171 · auto · 24 AIC · ⊞ 5.3K

## Query

```sql
WITH ex AS (

Copy link
Copy Markdown

Choose a reason for hiding this comment

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.

AND esd.deleted = FALSE
AND edo.deleted = FALSE
AND ep.purchase_price IS NOT NULL
AND DATE(esd.created_date) <= {{selected_date}}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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:

AND esd.created_date < ({{selected_date}}::date + INTERVAL '1 day')

(same for emd.created_date).

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?

SELECT
ep.id AS product_id,
edo.destination_id AS location_id,
ep.purchase_price * esd.supplied_item_quantity AS purchase_value,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question — valuation basis. Value uses the current ep.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.

0 AS mistake_value, 0 AS mistake_qty
FROM emr_supplydelivery esd
LEFT JOIN emr_deliveryorder edo ON esd.order_id = edo.id
LEFT JOIN emr_product ep ON esd.supplied_item_id = ep.id

Copy link
Copy Markdown

Choose a reason for hiding this comment

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants