40-clients/ucepsa/edge-oee-demo/sql/082_machine_stops_grafana.sql
2026-06-25 18:51:33 +02:00

82 lines
2.3 KiB
SQL

CREATE OR REPLACE VIEW mv_reports_ucepsa_demo.machine_stops_grafana AS
SELECT
s.id,
s.machine_id,
s.started_at,
s.ended_at,
COALESCE(s.ended_at, now()) AS effective_ended_at,
s.status,
s.classification_status,
s.start_event_name,
s.end_event_name,
COALESCE(
s.duration_s,
EXTRACT(EPOCH FROM (COALESCE(s.ended_at, now()) - s.started_at))
) AS duration_s_current,
ROUND(
(
COALESCE(
s.duration_s,
EXTRACT(EPOCH FROM (COALESCE(s.ended_at, now()) - s.started_at))
) / 60.0
)::numeric,
2
) AS duration_min,
COALESCE(s.cost_eur, 0)::numeric AS cost_eur,
COALESCE(
to_jsonb(s) ->> 'cause_code',
to_jsonb(s) ->> 'stop_cause_code',
to_jsonb(s) ->> 'reason_code',
CASE
WHEN s.classification_status = 'PENDING' THEN 'PENDIENTE'
ELSE 'SIN_CAUSA'
END
) AS cause_code,
COALESCE(
to_jsonb(s) ->> 'cause_name',
to_jsonb(s) ->> 'stop_cause_name',
to_jsonb(s) ->> 'reason_name',
CASE
WHEN s.classification_status = 'PENDING' THEN 'Pendiente de clasificar'
ELSE 'Sin causa registrada'
END
) AS cause_name,
to_jsonb(s) ->> 'operator_note' AS operator_note,
to_jsonb(s) ->> 'classified_by' AS classified_by,
to_jsonb(s) ->> 'order_ref' AS order_ref,
to_jsonb(s) ->> 'production_order' AS production_order,
CASE WHEN s.status = 'OPEN' THEN true ELSE false END AS is_open,
CASE
WHEN s.classification_status = 'PENDING' THEN true
ELSE false
END AS is_pending_classification,
CASE
WHEN s.status = 'OPEN' THEN 'ABIERTO'
WHEN s.classification_status = 'PENDING' THEN 'CERRADO SIN CLASIFICAR'
WHEN s.classification_status = 'CLASSIFIED' THEN 'CLASIFICADO'
ELSE COALESCE(s.status, 'SIN_ESTADO')
END AS stop_status_label,
CASE
WHEN s.status = 'OPEN' THEN 3
WHEN s.classification_status = 'PENDING' THEN 2
WHEN s.classification_status = 'CLASSIFIED' THEN 1
ELSE 0
END AS stop_priority_score
FROM mv_hot.edge_oee_machine_stops s;
GRANT SELECT ON mv_reports_ucepsa_demo.machine_stops_grafana TO grafana_ucepsa_ro;