<?xml version="1.0" encoding="UTF-8"?>
<pipeline>
  <info>
    <name>total_registered.driver_license(m_c)</name>
    <name_sync_with_filename>Y</name_sync_with_filename>
    <description/>
    <extended_description/>
    <pipeline_version/>
    <pipeline_type>Normal</pipeline_type>
    <pipeline_status>0</pipeline_status>
    <parameters>
    </parameters>
    <capture_transform_performance>N</capture_transform_performance>
    <transform_performance_capturing_delay>1000</transform_performance_capturing_delay>
    <transform_performance_capturing_size_limit>100</transform_performance_capturing_size_limit>
    <created_user>-</created_user>
    <created_date>2024/08/02 11:56:22.507</created_date>
    <modified_user>-</modified_user>
    <modified_date>2024/08/02 11:56:22.507</modified_date>
  </info>
  <notepads>
  </notepads>
  <order>
    <hop>
      <from>Get variables 3 2</from>
      <to>Select values 3 2</to>
      <enabled>N</enabled>
    </hop>
    <hop>
      <from>Select values 3 2</from>
      <to>Insert / update (total_registered.driver_license) 2</to>
      <enabled>N</enabled>
    </hop>
    <hop>
      <from>Table input (driver_license) регионы/все</from>
      <to>Get variables 3 2</to>
      <enabled>N</enabled>
    </hop>
    <hop>
      <from>Table input (driver_license) регионы/все</from>
      <to>Insert / update (total_registered.driver_license) 2</to>
      <enabled>Y</enabled>
    </hop>
  </order>
  <transform>
    <name>Get variables 3 2</name>
    <type>GetVariable</type>
    <description/>
    <distribute>Y</distribute>
    <custom_distribution/>
    <copies>1</copies>
    <partitioning>
      <method>none</method>
      <schema_name/>
    </partitioning>
    <fields>
      <field>
        <length>-1</length>
        <name>REC_ID</name>
        <precision>-1</precision>
        <trim_type>none</trim_type>
        <type>String</type>
      </field>
      <field>
        <length>-1</length>
        <name>SCM</name>
        <precision>-1</precision>
        <trim_type>none</trim_type>
        <type>String</type>
      </field>
    </fields>
    <attributes/>
    <GUI>
      <xloc>960</xloc>
      <yloc>496</yloc>
    </GUI>
  </transform>
  <transform>
    <name>Insert / update (total_registered.driver_license) 2</name>
    <type>InsertUpdate</type>
    <description/>
    <distribute>Y</distribute>
    <custom_distribution/>
    <copies>1</copies>
    <partitioning>
      <method>none</method>
      <schema_name/>
    </partitioning>
    <commit>100</commit>
    <connection>ervu-dashboard</connection>
    <lookup>
      <key>
        <condition>=</condition>
        <field>recruitment_id</field>
        <name>recruitment_id</name>
      </key>
      <key>
        <condition>=</condition>
        <field>recording_date</field>
        <name>recording_date</name>
      </key>
      <key>
        <condition>=</condition>
        <field>"all_M_W"</field>
        <name>gender</name>
      </key>
      <key>
        <condition>=</condition>
        <field>convicts</field>
        <name>convicts</name>
      </key>
      <schema>total_registered</schema>
      <table>driver_license</table>
      <value>
        <name>"A"</name>
        <rename>a</rename>
        <update>Y</update>
      </value>
      <value>
        <name>"B"</name>
        <rename>b</rename>
        <update>Y</update>
      </value>
      <value>
        <name>"C"</name>
        <rename>c</rename>
        <update>Y</update>
      </value>
      <value>
        <name>"D"</name>
        <rename>d</rename>
        <update>Y</update>
      </value>
      <value>
        <name>"E"</name>
        <rename>e</rename>
        <update>Y</update>
      </value>
      <value>
        <name>nope</name>
        <rename>nope</rename>
        <update>Y</update>
      </value>
      <value>
        <name>"A_repcent"</name>
        <rename>a_percent</rename>
        <update>Y</update>
      </value>
      <value>
        <name>"B_repcent"</name>
        <rename>b_percent</rename>
        <update>Y</update>
      </value>
      <value>
        <name>"C_repcent"</name>
        <rename>c_percent</rename>
        <update>Y</update>
      </value>
      <value>
        <name>"D_repcent"</name>
        <rename>d_percent</rename>
        <update>Y</update>
      </value>
      <value>
        <name>"E_repcent"</name>
        <rename>e_percent</rename>
        <update>Y</update>
      </value>
      <value>
        <name>"all_M_W"</name>
        <rename>gender</rename>
        <update>N</update>
      </value>
      <value>
        <name>recruitment_id</name>
        <rename>recruitment_id</rename>
        <update>N</update>
      </value>
      <value>
        <name>nope_repcent</name>
        <rename>nope_percent</rename>
        <update>Y</update>
      </value>
      <value>
        <name>total_count</name>
        <rename>total</rename>
        <update>Y</update>
      </value>
      <value>
        <name>convicts</name>
        <rename>convicts</rename>
        <update>N</update>
      </value>
    </lookup>
    <update_bypassed>Y</update_bypassed>
    <attributes/>
    <GUI>
      <xloc>1264</xloc>
      <yloc>384</yloc>
    </GUI>
  </transform>
  <transform>
    <name>Select values 3 2</name>
    <type>SelectValues</type>
    <description/>
    <distribute>Y</distribute>
    <custom_distribution/>
    <copies>1</copies>
    <partitioning>
      <method>none</method>
      <schema_name/>
    </partitioning>
    <fields>
      <select_unspecified>N</select_unspecified>
      <meta>
        <name>REC_ID</name>
        <rename>REC_ID</rename>
        <type>String</type>
        <length>-2</length>
        <precision>-2</precision>
        <conversion_mask/>
        <date_format_lenient>false</date_format_lenient>
        <date_format_locale/>
        <date_format_timezone/>
        <lenient_string_to_number>false</lenient_string_to_number>
        <encoding/>
        <decimal_symbol/>
        <grouping_symbol/>
        <currency_symbol/>
        <storage_type/>
      </meta>
      <meta>
        <name>SCM</name>
        <rename>SCM</rename>
        <type>String</type>
        <length>-2</length>
        <precision>-2</precision>
        <conversion_mask/>
        <date_format_lenient>false</date_format_lenient>
        <date_format_locale/>
        <date_format_timezone/>
        <lenient_string_to_number>false</lenient_string_to_number>
        <encoding/>
        <decimal_symbol/>
        <grouping_symbol/>
        <currency_symbol/>
        <storage_type/>
      </meta>
    </fields>
    <attributes/>
    <GUI>
      <xloc>1104</xloc>
      <yloc>496</yloc>
    </GUI>
  </transform>
  <transform>
    <name>Table input (driver_license) регионы/все</name>
    <type>TableInput</type>
    <description/>
    <distribute>Y</distribute>
    <custom_distribution/>
    <copies>1</copies>
    <partitioning>
      <method>none</method>
      <schema_name/>
    </partitioning>
    <connection>ervu_person_registry</connection>
    <execute_each_row>N</execute_each_row>
    <limit>0</limit>
    <sql>WITH 
ids AS (
    SELECT unnest(string_to_array(trim(both '{}' from '${ARR_MC}'), ','))::uuid AS recruitment_id
),
/*
last_status as (select recruit_id,
                     max(date_time) filter (where status not in ('1', '1.3', '12', '12.1', '12.2', '12.3', '12.4', '12.5', '13')) max_date_time
                     from recruits_history
                     where status not in ('1', '1.3', '12', '12.1', '12.2', '12.3', '12.4', '12.5', '13')
                     group by recruit_id
),
registered as (
                    select
                    distinct rh.recruit_id,
                    rh.id as recruit_history_id
                    from recruits_history rh
                    join last_status ls on rh.recruit_id=ls.recruit_id and rh.date_time=ls.max_date_time
                    where rh.status not in ('1', '1.3', '12', '12.1', '12.2', '12.3', '12.4', '12.5', '13') 
                    --and rh.source is not null
),
*/
categorized AS (
    SELECT
        r.id,
        r.gender,
        r.current_recruitment_id AS recruitment_id,
        CASE
            WHEN r.vu_current_info->>'recruitmentCommercialInfo' = 'true' THEN 'CONVICT'
            ELSE 'NOTCONVICT'
        END AS convicts,
        MAX(CASE WHEN cat->>'naimKatTS' like '%A%' THEN 1 ELSE 0 END) AS has_A,
        MAX(CASE WHEN cat->>'naimKatTS' like '%B%' THEN 1 ELSE 0 END) AS has_B,
        MAX(CASE WHEN cat->>'naimKatTS' like '%C%' THEN 1 ELSE 0 END) AS has_C,
        MAX(CASE WHEN cat->>'naimKatTS' like '%D%' THEN 1 ELSE 0 END) AS has_D,
        MAX(CASE WHEN cat->>'naimKatTS' like '%E%' THEN 1 ELSE 0 END) AS has_E,
        MAX(CASE WHEN cat->>'naimKatTS' like '%M%' THEN 1 ELSE 0 END) AS has_M, -- мопеды
        MAX(CASE WHEN cat->>'naimKatTS' like '%T%' THEN 1 ELSE 0 END) AS has_T -- трамваи и троллейбусы
    FROM public.recruits AS r
    JOIN public.recruits_info ri ON ri.recruit_id = r.id
    --JOIN public.recruits_history rh on rh.recruit_id=r.id
    LEFT JOIN jsonb_array_elements(ri.info->'svedFL'->'svedVoditUdost'->'voditUdost'->'svedKat') AS cat ON true
    WHERE r.current_recruitment_id::uuid IN (SELECT recruitment_id FROM ids)
/*
    r.id in (SELECT recruit_id FROM registered) and
    rh.id in (SELECT recruit_history_id FROM registered)
    and coalesce(r.current_recruitment_id,rh.current_recruitment_id) ::uuid IN (SELECT recruitment_id FROM ids)
*/
    AND r.gender IN ('MALE', 'FEMALE') -- Исключаем NULL
    GROUP BY r.id, r.gender

    UNION ALL 

    SELECT
        r.id,
        r.gender,
        r.current_recruitment_id AS recruitment_id,
        'ALL' AS convicts,
        MAX(CASE WHEN cat->>'naimKatTS' like '%A%' THEN 1 ELSE 0 END) AS has_A,
        MAX(CASE WHEN cat->>'naimKatTS' like '%B%' THEN 1 ELSE 0 END) AS has_B,
        MAX(CASE WHEN cat->>'naimKatTS' like '%C%' THEN 1 ELSE 0 END) AS has_C,
        MAX(CASE WHEN cat->>'naimKatTS' like '%D%' THEN 1 ELSE 0 END) AS has_D,
        MAX(CASE WHEN cat->>'naimKatTS' like '%E%' THEN 1 ELSE 0 END) AS has_E,
        MAX(CASE WHEN cat->>'naimKatTS' like '%M%' THEN 1 ELSE 0 END) AS has_M, -- мопеды
        MAX(CASE WHEN cat->>'naimKatTS' like '%T%' THEN 1 ELSE 0 END) AS has_T -- трамваи и троллейбусы
    FROM public.recruits AS r
    JOIN public.recruits_info ri ON ri.recruit_id = r.id
    --JOIN public.recruits_history rh on rh.recruit_id=r.id
    LEFT JOIN jsonb_array_elements(ri.info->'svedFL'->'svedVoditUdost'->'voditUdost'->'svedKat') AS cat ON true
    WHERE r.current_recruitment_id::uuid IN (SELECT recruitment_id FROM ids)
/*
    r.id in (SELECT recruit_id FROM registered) and
    rh.id in (SELECT recruit_history_id FROM registered)
    and coalesce(r.current_recruitment_id,rh.current_recruitment_id) ::uuid IN (SELECT recruitment_id FROM ids)
*/
    AND r.gender IN ('MALE', 'FEMALE') -- Исключаем NULL
    GROUP BY r.id, r.gender
),
aggregated AS (
    SELECT
        current_date AS recording_date,
        CASE
            WHEN r.gender = 'MALE' THEN 'M'
            ELSE 'W'
        END AS gender,
        r.convicts,
        r.recruitment_id,
        -- Считаем количество уникальных рекрутов с каждой категорией
        COUNT(DISTINCT r.id) FILTER (WHERE has_A > 0) AS a,
        COUNT(DISTINCT r.id) FILTER (WHERE has_B > 0) AS b,
        COUNT(DISTINCT r.id) FILTER (WHERE has_C > 0) AS c,
        COUNT(DISTINCT r.id) FILTER (WHERE has_D > 0) AS d,
        COUNT(DISTINCT r.id) FILTER (WHERE has_E > 0) AS e,
        COUNT(DISTINCT r.id) FILTER (WHERE (has_A + has_B + has_C + has_D + has_E = 0) OR ((has_M + has_T > 0) AND (has_A + has_B + has_C + has_D + has_E = 0))) AS nope, -- условие от 14.03.2025
        COUNT(DISTINCT r.id) AS total
    FROM categorized r
    GROUP BY r.gender, r.recruitment_id, r.convicts
),
aggregated_all AS (
    SELECT
        current_date AS recording_date,
        'ALL' AS gender,
        r.convicts,
        r.recruitment_id,
        COUNT(DISTINCT r.id) FILTER (WHERE has_A > 0) AS a,
        COUNT(DISTINCT r.id) FILTER (WHERE has_B > 0) AS b,
        COUNT(DISTINCT r.id) FILTER (WHERE has_C > 0) AS c,
        COUNT(DISTINCT r.id) FILTER (WHERE has_D > 0) AS d,
        COUNT(DISTINCT r.id) FILTER (WHERE has_E > 0) AS e,
        COUNT(DISTINCT r.id) FILTER (WHERE (has_A + has_B + has_C + has_D + has_E = 0) OR ((has_M + has_T > 0) AND (has_A + has_B + has_C + has_D + has_E = 0))) AS nope, -- условие от 14.03.2025
        COUNT(DISTINCT r.id) AS total
    FROM categorized r
    GROUP BY r.recruitment_id, r.convicts
)

-- Объединение результатов с вычислением процентов
SELECT 
    *,
    COALESCE(ROUND((a * 100.0) / NULLIF(total, 0), 2), 0) AS a_percent,
    COALESCE(ROUND((b * 100.0) / NULLIF(total, 0), 2), 0) AS b_percent,
    COALESCE(ROUND((c * 100.0) / NULLIF(total, 0), 2), 0) AS c_percent,
    COALESCE(ROUND((d * 100.0) / NULLIF(total, 0), 2), 0) AS d_percent,
    COALESCE(ROUND((e * 100.0) / NULLIF(total, 0), 2), 0) AS e_percent,
    COALESCE(ROUND((nope * 100.0) / NULLIF(total, 0), 2), 0) AS nope_percent
FROM aggregated
UNION ALL
SELECT 
    *,
    COALESCE(ROUND((a * 100.0) / NULLIF(total, 0), 2), 0) AS a_percent,
    COALESCE(ROUND((b * 100.0) / NULLIF(total, 0), 2), 0) AS b_percent,
    COALESCE(ROUND((c * 100.0) / NULLIF(total, 0), 2), 0) AS c_percent,
    COALESCE(ROUND((d * 100.0) / NULLIF(total, 0), 2), 0) AS d_percent,
    COALESCE(ROUND((e * 100.0) / NULLIF(total, 0), 2), 0) AS e_percent,
    COALESCE(ROUND((nope * 100.0) / NULLIF(total, 0), 2), 0) AS nope_percent
FROM aggregated_all</sql>
    <variables_active>Y</variables_active>
    <attributes/>
    <GUI>
      <xloc>800</xloc>
      <yloc>384</yloc>
    </GUI>
  </transform>
  <transform_error_handling>
  </transform_error_handling>
  <attributes/>
</pipeline>
