--- alter-ticket-messages-export-add-categories
DROP VIEW ticket_messages_export_view;

CREATE VIEW ticket_messages_export_view AS
SELECT
    m.id,
    m.ticket_id,

    projects.name    AS project,
    channels.title   AS channel,
    categories.title AS category,
    STRING_AGG(cat.title, ', ' ORDER BY cat.id) AS categories,

    m.client_id,
    clients.name     AS client,
    users.name       AS "user",
    users.email      AS user_email,

    m.type,
    m.text,
    files.id AS link,


    m.received,
    m.read,
    m.deleted,
    tickets.created_at as ticket_created_at,
    m.created_at as sent_at,
    m.received_at,
    m.read_at

FROM ticket_messages m
         LEFT JOIN tickets ON tickets.id = m.ticket_id
         LEFT OUTER JOIN projects ON projects.id = tickets.project_id
         LEFT OUTER JOIN channels ON channels.id = tickets.channel_id
         LEFT OUTER JOIN categories ON categories.id = tickets.category_id
         LEFT OUTER JOIN categories cat ON cat.id IN (
            SELECT unnest(cast(string_to_array(tickets.category_ids, ',') as bigint[]))
         )

         LEFT OUTER JOIN files ON files.id = m.file_id
         LEFT OUTER JOIN clients ON clients.id = m.client_id
         LEFT OUTER JOIN users ON users.id = m.user_id

GROUP BY
m.id,
users.id,
files.id,
tickets.id,
projects.id,
clients.id,
channels.id, 
categories.id