-- public.tms_v_terminal_last_heart_beat source

CREATE OR REPLACE VIEW public.tms_v_terminal_last_heart_beat
AS SELECT terminal.id, terminal.id AS terminal_id, terminal.sn AS terminal_sn, 
    heartbeat.create_ts, heartbeat.created_by, heartbeat.battery_temp, 
    heartbeat.battery_percentage, heartbeat.latitude, heartbeat.longitude, 
    heartbeat.version, 
        CASE
            WHEN terminal.heartbeat_status = 3 THEN 'DISCONNECTED'::text
            WHEN terminal.heartbeat_status = 2 THEN 'OFFLINE'::text
            WHEN terminal.heartbeat_status = 1 THEN 'ONLINE'::text
            ELSE 'DISCONNECTED'::text
        END AS state
   FROM tms_terminal terminal
   JOIN tms_device_profile profile ON terminal.profile_id = profile.id
   LEFT JOIN tms_heart_beat heartbeat ON terminal.last_heartbeat_id = heartbeat.id;