DROP VIEW tickets_export_view;

CREATE VIEW tickets_export_view AS
SELECT
    t.created_at,

    t.id,
    t.project_id,
    t.channel_id,
    t.chat_id,
    t.category_id,
    t.client_id,
    t.assignee_id,
    t.accepter_id,
    t.rating_id,
    t.state,

    projects.name    AS project,
    clients.name     AS client,

    channels.title   AS channel,
    categories.title AS category,
    groups.id        AS group_id,
    groups.title     AS "group",
    assignees.name   AS assignee,
    assignees.email  AS assignee_email,
    accepters.name   AS accepter,
    accepters.email  AS accepter_email,
    ratings.value    AS rating,
    ratings.state    AS rating_state,

    (case
         when t.violation_id is not null then true
         else false
        end) as violation,

    CAST((CASE
         WHEN t.accept_time IS NULL OR t.accept_time = 0 THEN 0
         ELSE t.accept_time
    END) AS INTEGER) as accept_time,

    t.assign_time,
    t.response_time,
    t.total_response_time,
    t.total_time,

    t.total_messages,
    t.total_members,

    t.open,
    t.closed_at,

    t.ip,
    t.ip_city,
    t.ip_country,

    t.ua,
    t.ua_browser,
    t.ua_browser_version,
    t.ua_mobile,
    t.ua_os,
    t.ua_os_version,
    t.ua_platform

FROM tickets t
         JOIN projects ON projects.id = t.project_id
         JOIN clients ON clients.id = t.client_id

         LEFT OUTER JOIN channels ON channels.id = t.channel_id
         LEFT OUTER JOIN categories ON categories.id = t.category_id
         LEFT OUTER JOIN groups ON groups.id = t.group_id
         LEFT OUTER JOIN ratings ON ratings.id = t.rating_id
         LEFT OUTER JOIN users assignees ON assignees.id = t.assignee_id
         LEFT OUTER JOIN users accepters ON accepters.id = t.accepter_id;
