CREATE OR REPLACE VIEW users_subject AS

        (SELECT u.id,
                u.id AS user_id,
                NULL AS group_id,
                u.username,
                u.first_name,
                u.last_name,
                dep.name AS parent_name,
                CONCAT(u.first_name, ' ', u.last_name) AS full_name,
                CONCAT(u.first_name_en, ' ', u.last_name_en) AS full_name_en,
                FALSE AS is_group,
                'user' AS subject_type,
                NULL AS group_type,
                u.username AS external_id
           FROM upravlyator_user u
     INNER JOIN users_group dep
             ON u.department_group_id = dep.id
          WHERE u.department_group_id IS NOT NULL)

          UNION

        (SELECT -users_group.id AS id,
                NULL AS user_id,
                users_group.id AS group_id,
                users_group.slug AS username,
                '' AS first_name,
                '' AS last_name,
                parent.name AS parent_name,
                users_group.name AS full_name,
                users_group.name_en AS full_name_en,
                TRUE AS is_group,
                'group' AS subject_type,
                users_group.type AS group_type,
                users_group.external_id::text AS external_id
           FROM users_group
LEFT OUTER JOIN users_group parent
             ON users_group.parent_id = parent.id
          WHERE users_group.state = 'active'
            AND users_group.type != 'tvm_service')

          UNION

        (SELECT u.id,
                u.id AS user_id,
                NULL AS group_id,
                u.username,
                u.first_name,
                u.last_name,
                g.name AS parent_name,
                CONCAT(u.first_name, ' ', u.last_name) AS full_name,
                CONCAT(u.first_name_en, ' ', u.last_name_en) AS full_name_en,
                FALSE AS is_group,
                'tvm_app' AS subject_type,
                NULL AS group_type,
                u.username AS external_id
           FROM upravlyator_user u
           JOIN users_groupmembership as mb
             ON u.id = mb.user_id
           JOIN users_group as g
             ON mb.group_id = g.id

          WHERE u.type = 'tvm_app'
            AND mb.state = 'active'
            AND g.type = 'tvm_service')
;
