Files
warehouse-management-BE/db/queries/dashboard.sql

66 lines
2.5 KiB
SQL

-- name: GetTotalComponentStats :one
SELECT COUNT(DISTINCT ci.component_id) AS total_types, COALESCE(SUM(ci.quantity), 0)::bigint AS total_quantity
FROM component_items ci
JOIN containers con ON ci.container_id = con.id
JOIN shelves s ON con.shelf_id = s.id
JOIN cabinets cab ON s.cabinet_id = cab.id
JOIN rooms r ON cab.room_id = r.id
WHERE sqlc.narg('warehouse_id')::bigint IS NULL OR r.warehouse_id = sqlc.narg('warehouse_id')::bigint;
-- name: CountPendingInvoices :one
SELECT COUNT(*) FROM invoices
WHERE status IN ('draft', 'pending');
-- name: CountLowStockComponents :one
SELECT COUNT(*) FROM components
WHERE total_quantity <= min_quantity;
-- name: GetAbnormalItemCounts :many
SELECT ci.status, COUNT(*) AS count
FROM component_items ci
JOIN containers con ON ci.container_id = con.id
JOIN shelves s ON con.shelf_id = s.id
JOIN cabinets cab ON s.cabinet_id = cab.id
JOIN rooms r ON cab.room_id = r.id
WHERE ci.status != 'normal'
AND (sqlc.narg('warehouse_id')::bigint IS NULL OR r.warehouse_id = sqlc.narg('warehouse_id')::bigint)
GROUP BY ci.status;
-- name: GetTodayInvoiceCounts :many
SELECT type, COUNT(*) AS count
FROM invoices
WHERE created_at::date = CURRENT_DATE
GROUP BY type;
-- name: GetContainerStats :one
SELECT
COUNT(*) AS total_containers,
COUNT(*) - COUNT(DISTINCT ci.container_id) AS empty_containers
FROM containers c
JOIN shelves s ON c.shelf_id = s.id
JOIN cabinets cab ON s.cabinet_id = cab.id
JOIN rooms r ON cab.room_id = r.id
LEFT JOIN component_items ci ON c.id = ci.container_id
WHERE sqlc.narg('warehouse_id')::bigint IS NULL OR r.warehouse_id = sqlc.narg('warehouse_id')::bigint;
-- name: GetStockAlerts :many
SELECT c.id, c.name, c.unit, c.total_quantity, c.min_quantity, c.component_type_id,
ct.name AS component_type_name
FROM components c
LEFT JOIN component_types ct ON c.component_type_id = ct.id
WHERE c.total_quantity <= c.min_quantity
ORDER BY (c.total_quantity - c.min_quantity) ASC;
-- name: GetAnomalyItems :many
SELECT ci.id, ci.component_id, ci.container_id, ci.quantity, ci.status, ci.created_at, ci.updated_at,
c.name AS component_name, c.unit AS component_unit
FROM component_items ci
JOIN components c ON ci.component_id = c.id
JOIN containers con ON ci.container_id = con.id
JOIN shelves s ON con.shelf_id = s.id
JOIN cabinets cab ON s.cabinet_id = cab.id
JOIN rooms r ON cab.room_id = r.id
WHERE ci.status != 'normal'
AND (sqlc.narg('warehouse_id')::bigint IS NULL OR r.warehouse_id = sqlc.narg('warehouse_id')::bigint)
ORDER BY ci.updated_at DESC;