60 lines
2.3 KiB
SQL
60 lines
2.3 KiB
SQL
-- Modified version of garfield.inventory_item_overview.
|
|
|
|
CREATE TEMPORARY VIEW all_inventory_item_overview AS
|
|
SELECT
|
|
item_id,
|
|
inventory_items.item_barcode,
|
|
inventory_items.bought,
|
|
inventory_items.name,
|
|
inventory_items.sales_units,
|
|
inventory_items.unit_price,
|
|
inventory_items.available,
|
|
inventory_items.item_group,
|
|
inventory_items.location,
|
|
inventory_item_groups.group_name,
|
|
COALESCE(b.sales::numeric, 0::numeric) - COALESCE(cancel.count::numeric, 0::numeric) AS sales,
|
|
inventory_items.sales_units::numeric - COALESCE(b.sales, 0::bigint)::numeric + COALESCE(c.delta, 0::numeric) + COALESCE(cancel.count::numeric, 0::numeric) AS units_left,
|
|
COALESCE(c.delta, 0::numeric) AS correction_delta,
|
|
COALESCE(m.mappings::numeric, 0::numeric) AS active_mappings,
|
|
m.mappings_array AS active_mappings_array,
|
|
locations.location_name
|
|
FROM garfield.inventory_items
|
|
JOIN garfield.locations ON inventory_items.location = locations.location_id
|
|
LEFT JOIN garfield.inventory_item_groups ON inventory_item_groups.group_id = inventory_items.item_group
|
|
LEFT JOIN (
|
|
SELECT
|
|
snack_sales_log.inventory_line AS item_id,
|
|
count(*) AS sales
|
|
FROM garfield.snack_sales_log
|
|
WHERE snack_sales_log.inventory_line IS NOT NULL
|
|
AND snack_sales_log.type_id::text = 'SNACK_BUY'::text
|
|
GROUP BY snack_sales_log.inventory_line
|
|
) b USING (item_id)
|
|
LEFT JOIN (
|
|
SELECT
|
|
snack_sales_log.inventory_line AS item_id,
|
|
count(*) AS count
|
|
FROM garfield.snack_sales_log
|
|
WHERE snack_sales_log.inventory_line IS NOT NULL
|
|
AND snack_sales_log.type_id::text = 'SNACK_CANCEL'::text
|
|
GROUP BY snack_sales_log.inventory_line
|
|
) cancel USING (item_id)
|
|
LEFT JOIN (
|
|
SELECT
|
|
inventory_correction.item_id,
|
|
sum(inventory_correction.delta) AS delta
|
|
FROM garfield.inventory_correction
|
|
GROUP BY inventory_correction.item_id
|
|
) c USING (item_id)
|
|
LEFT JOIN (
|
|
SELECT
|
|
count(inventory_map.snack_id) AS mappings,
|
|
array_agg(inventory_map.snack_id) AS mappings_array,
|
|
inventory_map.inventory_id AS item_id
|
|
FROM garfield.inventory_map
|
|
JOIN garfield.snacks_available ON snacks_available.snack_available AND snacks_available.snack_id = inventory_map.snack_id
|
|
GROUP BY inventory_map.inventory_id
|
|
) m USING (item_id)
|
|
ORDER BY inventory_items.name;
|
|
|