Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Month on Month Purchase Value Difference Analysis for a Specific Supplier - SSMM

> Completed supplier deliveries with product value, location, and creator details

## Purpose

Lists completed supply deliveries for a single supplier and shows the purchase value at product level.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[Critical] Query does not deliver a month-on-month difference analysis.

The title and PR title promise a "Month on Month Purchase Value Difference Analysis", but the SQL is a flat, row-per-delivery itemized list ordered by value DESC — there is no GROUP BY on month, no time-bucketing, and no computed delta comparing one period to the previous one (e.g. LAG() or a self-join). The ## Purpose text ("Lists completed supply deliveries ... at product level") actually matches the SQL, but not the filename/title at all.

ENG-974 could not be fetched to confirm the exact ask (JIRA returned 404/401 for this ticket), but going purely off the stated title: if a real MoM diff was intended, this query doesn't answer it — a dashboard consumer would see a raw delivery list, not a period-over-period comparison. Either the title/purpose need to be rewritten to describe what this query actually is (a supplier delivery drill-down), or the SQL needs monthly aggregation plus a delta calculation.

Suggested direction if a real MoM diff was intended:

WITH monthly AS (
  SELECT date_trunc('month', esd.created_date) AS month,
         epk.id AS product_id,
         epk.name AS product_name,
         SUM(ep.purchase_price * esd.supplied_item_quantity) AS total_value
  FROM emr_supplydelivery esd
  JOIN emr_deliveryorder edo ON esd.order_id = edo.id
  JOIN emr_product ep ON esd.supplied_item_id = ep.id
  JOIN emr_productknowledge epk ON epk.id = ep.product_knowledge_id
  WHERE esd.status = 'completed' AND edo.status = 'completed'
    AND edo.supplier_id = 20697
    AND esd.deleted = FALSE AND edo.deleted = FALSE
  GROUP BY 1, 2, 3
)
SELECT *, total_value - LAG(total_value) OVER (PARTITION BY product_id ORDER BY month) AS value_diff
FROM monthly ORDER BY month, product_name;



## Parameters

| Parameter | Type | Description | Example |
|-----------|------|-------------|---------|
| `start_date` | date | Optional lower bound for `created_date` | `2026-01-01` |
| `end_date` | date | Optional upper bound for `created_date` | `2026-01-31` |

---

## Query

```sql
SELECT
epk.name AS product_name,
esd.supplied_item_quantity AS quantity,
ep.purchase_price AS unit_price,
(ep.purchase_price * esd.supplied_item_quantity) AS 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.

[High] Value is computed from the product's current price, not the price at time of delivery.

emr_supplydelivery has its own total_purchase_price column (a numeric snapshot presumably captured at delivery time), but this query instead multiplies the live emr_product.purchase_price by supplied_item_quantity. If the supplier's price changes after a delivery is recorded, every historical row's value/unit_price silently changes too — which directly undermines a month-on-month comparison (the whole point is to compare against what was actually paid in each period, not what the current price list says). Worth confirming with the author whether esd.total_purchase_price should be used instead (falling back to the computed value only where it's NULL).

COALESCE(esd.total_purchase_price, ep.purchase_price * esd.supplied_item_quantity) AS value

DATE(esd.created_date) AS created_date,
org.name AS supplier_name,
fl.name AS destination_location,
CONCAT(u.first_name, ' ', u.last_name) AS created_by
FROM emr_supplydelivery esd
JOIN emr_deliveryorder edo
ON esd.order_id = edo.id
JOIN emr_product ep
ON esd.supplied_item_id = ep.id
JOIN emr_productknowledge epk
ON epk.id = ep.product_knowledge_id
JOIN users_user u
ON u.id = edo.created_by_id
JOIN emr_organization org
ON org.id = edo.supplier_id
JOIN emr_facilitylocation fl
ON fl.id = edo.destination_id
WHERE esd.status = 'completed'

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] Missing deleted = FALSE on every joined table.

None of emr_supplydelivery, emr_deliveryorder, emr_product, emr_productknowledge, emr_organization, or emr_facilitylocation filter deleted = FALSE here. It's a weak signal on its own (health/inventory records are rarely hard/soft-deleted), but it's cheap, indexed, and the sibling query in this same folder (internalsupplydeliverypurchase_ssmm.md) does include it (fl.deleted = FALSE). Worth adding at least for esd, edo, and fl for consistency with repo convention.

WHERE esd.status = 'completed'
  AND esd.deleted = FALSE
  AND edo.deleted = FALSE
  AND edo.origin_id IS NULL
  AND edo.supplier_id = '20697'
  AND edo.status = 'completed'
  AND ep.purchase_price IS NOT NULL

AND edo.origin_id IS NULL
AND edo.supplier_id = '20697'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[Low] supplier_id compared against a quoted string.

edo.supplier_id is a bigint FK, but the literal is quoted ('20697'). Postgres will implicitly cast this so it won't break the query or the index usage, but it's inconsistent with the sibling query in this folder (internalsupplydeliverypurchase_ssmm.md), which uses the unquoted delivery_order.supplier_id = 20697. Minor, but worth matching repo convention.

AND edo.supplier_id = 20697

AND edo.status = 'completed'
AND ep.purchase_price IS NOT NULL
--AND ({{start_date}} IS NULL OR DATE(esd.created_date) > {{start_date}}::date)
--AND ({{end_date}} IS NULL OR DATE(esd.created_date) <= {{end_date}}::date)
ORDER BY value DESC;
```

## Notes

- **Supplier filter:** `edo.supplier_id = '20697'` is hardcoded, so the query is scoped to one supplier.
- **Completed deliveries only:** Both `esd.status` and `edo.status` must be `completed`.
- **Ordering:** Results are sorted by highest purchase value first.


*Last updated: 2026-08-31*
Loading