<?xml version="1.0" encoding="UTF-8"?>
<pipeline>
  <info>
    <name>total_registered.reg_mil_cat_pr5(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>Table input (person_registry) военком/рег</from>
      <to>Insert / update (total_registered.reg_mil_cat)</to>
      <enabled>Y</enabled>
    </hop>
  </order>
  <transform>
    <name>Insert / update (total_registered.reg_mil_cat)</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>mil_reg</field>
        <name>mil_reg</name>
      </key>
      <schema>total_registered</schema>
      <table>reg_mil_cat</table>
      <value>
        <name>first_reg_17</name>
        <rename>first_reg_17</rename>
        <update>Y</update>
      </value>
      <value>
        <name>first_reg_18</name>
        <rename>first_reg_18</rename>
        <update>Y</update>
      </value>
      <value>
        <name>"mil_spec_W"</name>
        <rename>mil_spec_w</rename>
        <update>Y</update>
      </value>
      <value>
        <name>recruitment_id</name>
        <rename>recruitment_id</rename>
        <update>N</update>
      </value>
      <value>
        <name>returned_dep_liberty</name>
        <rename>returned_dep_liberty</rename>
        <update>Y</update>
      </value>
      <value>
        <name>punished</name>
        <rename>punished</rename>
        <update>Y</update>
      </value>
      <value>
        <name>received_citizenship</name>
        <rename>received_citizenship</rename>
        <update>Y</update>
      </value>
      <value>
        <name>first_reg_17_percent</name>
        <rename>first_reg_17_percent</rename>
        <update>Y</update>
      </value>
      <value>
        <name>first_reg_18_percent</name>
        <rename>first_reg_18_percent</rename>
        <update>Y</update>
      </value>
      <value>
        <name>returned_dep_liberty_percent</name>
        <rename>returned_dep_liberty_percent</rename>
        <update>Y</update>
      </value>
      <value>
        <name>"mil_spec_W_percent"</name>
        <rename>mil_spec_w_percent</rename>
        <update>Y</update>
      </value>
      <value>
        <name>punished_percent</name>
        <rename>punished_percent</rename>
        <update>Y</update>
      </value>
      <value>
        <name>received_citizenship_percent</name>
        <rename>received_citizenship_percent</rename>
        <update>Y</update>
      </value>
      <value>
        <name>mil_reg</name>
        <rename>mil_reg</rename>
        <update>N</update>
      </value>
    </lookup>
    <update_bypassed>N</update_bypassed>
    <attributes/>
    <GUI>
      <xloc>1392</xloc>
      <yloc>288</yloc>
    </GUI>
  </transform>
  <transform>
    <name>Table input (person_registry) военком/рег</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_PR_5}'), ','))::uuid AS recruitment_id
),
/*
last_status_r 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_r 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
),
*/
last_status_n as (select recruit_id,
                     max(date_time) filter (where status in ('1', '12.7', '8.2', '8.3')) max_date_time
                     from recruits_history
                     where status in ('1', '12.7', '8.2', '8.3')
                     group by recruit_id
),
notregistered as (
                    select
                    distinct rh.recruit_id,
                    rh.id as recruit_history_id
                    from recruits_history rh
                    join last_status_n ls on rh.recruit_id=ls. recruit_id and rh.date_time=ls.max_date_time
                    where rh.status in ('1', '12.7', '8.2', '8.3') 
--and rh.source is not null
),
base_data AS (
    -- Основной набор данных с вычислением mil_reg
    SELECT 
        r.registration_reasons, 
        r.gender,
        r.current_recruitment_id AS recruitment_id,
        --coalesce (r.current_recruitment_id, rh.current_recruitment_id) AS recruitment_id,
        1 AS is_military_registered
    FROM public.recruits AS r
    JOIN public.recruits_info AS ri
    ON ri.recruit_id = r.id
    --join public.recruits_history rh on rh.recruit_id=r.id
    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 jsonb_exists_any(registration_reasons, ARRAY[
            '1', -- Освобождение из мест лишения свободы
            '2', -- Приобретение гражданства Российской Федерации
            '3', -- Получение военно-учётной специальности гражданином женского пола
            '4', -- Отбывание наказания в местах лишения свободы
            '5'--, -- Достижение 17 лет в год постановки на воинский учёт
            --'6' -- Первоначальная постановка на воинский учет граждан, не состоящих, но обязанных состоять на воинском учёте
            ])
    UNION ALL
    SELECT 
        r.registration_reasons, 
        r.gender,
        coalesce (r.target_recruitment_id, rh.target_recruitment_id) AS recruitment_id,
        0 AS is_military_registered
    FROM public.recruits AS r
    JOIN public.recruits_info AS ri ON ri.recruit_id = r.id
    JOIN public.recruits_history rh ON rh.recruit_id=r.id
    WHERE
        r.id in (SELECT recruit_id FROM notregistered) and
        rh.id in (SELECT recruit_history_id FROM notregistered)
        and coalesce(r.target_recruitment_id,rh.target_recruitment_id) ::uuid IN (SELECT recruitment_id FROM ids)
        AND r.current_recruitment_id is null
        AND jsonb_exists_any(registration_reasons, ARRAY['1', '2', '3', '4', '5'])
),
t1 AS (
    -- Первоначальная постановка 17 лет
    SELECT 
        recruitment_id,
        is_military_registered,
        COUNT(*) AS first_reg_17
    FROM base_data
    WHERE registration_reasons @> '"5"' -- Достижение 17 лет в год постановки на воинский учёт
    GROUP BY recruitment_id, is_military_registered
),
t2 AS (
    -- Первоначальная постановка 18 лет
    SELECT 
        recruitment_id,
        is_military_registered,
        COUNT(*) AS first_reg_18
    FROM base_data
    WHERE jsonb_exists_any(registration_reasons, ARRAY['1', '2', '3', '4'])
    GROUP BY recruitment_id, is_military_registered
),
t3 AS (
    -- Женщины, получившие ВУС
    SELECT 
        recruitment_id,
        is_military_registered,
        COUNT(*) AS mil_spec_w
    FROM base_data
    WHERE registration_reasons @> '"3"' AND gender = 'FEMALE'
    GROUP BY recruitment_id, is_military_registered
),
t4 AS (
    -- Возвратившиеся из мест лишения свободы
    SELECT 
        recruitment_id,
        is_military_registered,
        COUNT(*) AS returned_dep_liberty
    FROM base_data
    WHERE registration_reasons @> '"1"'
    GROUP BY recruitment_id, is_military_registered
),
t5 AS (
    -- Отбывающие наказание в местах лишения свободы
    SELECT 
        recruitment_id,
        is_military_registered,
        COUNT(*) AS punished
    FROM base_data
    WHERE registration_reasons @> '"4"'
    GROUP BY recruitment_id, is_military_registered
),
t6 AS (
    -- Получившие гражданство
    SELECT 
        recruitment_id,
        is_military_registered,
        COUNT(*) AS received_citizenship
    FROM base_data
    WHERE registration_reasons @> '"2"'
    GROUP BY recruitment_id, is_military_registered
),
total AS (
    -- Общее количество записей
    SELECT 
        recruitment_id,
        is_military_registered,
        COUNT(*) AS total_count
    FROM base_data
    GROUP BY recruitment_id, is_military_registered
),
uniq_ms AS (
    SELECT 
        distinct
        recruitment_id,
        is_military_registered
    FROM base_data
)
-- Основной запрос
SELECT 
    current_date AS recording_date,
    dc.recruitment_id,
    dc.is_military_registered AS mil_reg,
    COALESCE(total.total_count, 0) AS total_count,
    COALESCE(t1.first_reg_17, 0) AS first_reg_17,
    COALESCE(t2.first_reg_18, 0) AS first_reg_18,
    COALESCE(t3.mil_spec_w, 0) AS mil_spec_w,
    COALESCE(t4.returned_dep_liberty, 0) AS returned_dep_liberty,
    COALESCE(t5.punished, 0) AS punished,
    COALESCE(t6.received_citizenship, 0) AS received_citizenship,
    -- Вычисление процентов
    COALESCE(ROUND(COALESCE(t1.first_reg_17, 0) * 100.0 / NULLIF(total.total_count, 0), 2), 0) AS first_reg_17_percent,
    COALESCE(ROUND(COALESCE(t2.first_reg_18, 0) * 100.0 / NULLIF(total.total_count, 0), 2), 0) AS first_reg_18_percent,
    COALESCE(ROUND(COALESCE(t4.returned_dep_liberty, 0) * 100.0 / NULLIF(total.total_count, 0), 2), 0) AS returned_dep_liberty_percent,
    COALESCE(ROUND(COALESCE(t3.mil_spec_w, 0) * 100.0 / NULLIF(total.total_count, 0), 2), 0) AS mil_spec_w_percent,
    COALESCE(ROUND(COALESCE(t5.punished, 0) * 100.0 / NULLIF(total.total_count, 0), 2), 0) AS punished_percent,
    COALESCE(ROUND(COALESCE(t6.received_citizenship, 0) * 100.0 / NULLIF(total.total_count, 0), 2), 0) AS received_citizenship_percent
FROM uniq_ms dc
LEFT JOIN total ON dc.recruitment_id = total.recruitment_id 
                AND dc.is_military_registered = total.is_military_registered
LEFT JOIN t1 ON dc.recruitment_id = t1.recruitment_id 
             AND dc.is_military_registered = t1.is_military_registered
LEFT JOIN t2 ON dc.recruitment_id = t2.recruitment_id 
             AND dc.is_military_registered = t2.is_military_registered
LEFT JOIN t3 ON dc.recruitment_id = t3.recruitment_id 
             AND dc.is_military_registered = t3.is_military_registered
LEFT JOIN t4 ON dc.recruitment_id = t4.recruitment_id 
             AND dc.is_military_registered = t4.is_military_registered
LEFT JOIN t5 ON dc.recruitment_id = t5.recruitment_id 
             AND dc.is_military_registered = t5.is_military_registered
LEFT JOIN t6 ON dc.recruitment_id = t6.recruitment_id 
             AND dc.is_military_registered = t6.is_military_registered;</sql>
    <variables_active>Y</variables_active>
    <attributes/>
    <GUI>
      <xloc>736</xloc>
      <yloc>288</yloc>
    </GUI>
  </transform>
  <transform_error_handling>
  </transform_error_handling>
  <attributes/>
</pipeline>
