<?xml version="1.0" encoding="UTF-8"?>
<pipeline>
  <info>
    <name>m_d.rec_cam(m_c)_to_person_registry</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>Update</to>
      <enabled>Y</enabled>
    </hop>
  </order>
  <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>postgres.person_registry</connection>
    <execute_each_row>N</execute_each_row>
    <limit>0</limit>
    <sql>WITH
ids AS (
    -- Преобразуем строковый массив в таблицу UUID
    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') -- критерии от 03.06.2025
                    --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
),
recruit_data AS (
    SELECT
        r.id AS r_id,
        ri.recruit_id AS recruit_id,
        r.gender,
        r.current_recruitment_id AS recruitment_id,
        -- coalesce (r.current_recruitment_id, rh.current_recruitment_id) AS recruitment_id,
        CASE 
        WHEN (r.birth_date BETWEEN DATE (extract(year from now())-30||'-04-02') and DATE (extract(year from now())-18||'-07-13'))
            THEN 'Весна'
        WHEN (r.birth_date BETWEEN DATE (extract(year from now())-30||'-10-02') and DATE (extract(year from now())-18||'-12-30'))
            THEN 'Осень'
        END AS spring_autumn,
        r.birth_date,
        ddd.hidden--, -- когда фолс отсрочка есть, когда тру или нулл - нет
        --ri.info
    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
    LEFT JOIN (
            SELECT
                ROW_NUMBER() OVER (PARTITION BY ddd.recruit_id ORDER BY COALESCE(ddd.updated_at, ddd.created_at) DESC) AS rn,
                ddd.recruit_id,
                ddd.hidden
            FROM decision_deferment_dto ddd
            WHERE ddd.hidden is true -- когда фолс отсрочка есть, когда тру или нулл - нет (для подсчета подпадающих под призыв)
    ) ddd ON ddd.recruit_id = r.id AND ddd.rn = 1
    WHERE r.gender = 'MALE' AND
/*
        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)
*/
        r.current_recruitment_id::uuid IN (SELECT recruitment_id FROM ids)
        AND 
        ((r.birth_date BETWEEN DATE (extract(year from now())-30||'-04-02') and DATE (extract(year from now())-18||'-07-13'))
        OR
        (r.birth_date BETWEEN DATE (extract(year from now())-30||'-10-02') and DATE (extract(year from now())-18||'-12-30')))

    UNION ALL

    SELECT
        r.id AS r_id,
        ri.recruit_id AS recruit_id,
        r.gender,
        --r.current_recruitment_id AS recruitment_id,
        coalesce (r.target_recruitment_id, rh.target_recruitment_id) AS recruitment_id,
        CASE 
        WHEN (r.birth_date BETWEEN DATE (extract(year from now())-30||'-04-02') and DATE (extract(year from now())-18||'-07-13'))
            THEN 'Весна'
        WHEN (r.birth_date BETWEEN DATE (extract(year from now())-30||'-10-02') and DATE (extract(year from now())-18||'-12-30'))
            THEN 'Осень'
        END AS spring_autumn,
        r.birth_date,
        ddd.hidden--, -- когда фолс отсрочка есть, когда тру или нулл - нет
        --ri.info
    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
    LEFT JOIN (
            SELECT
                ROW_NUMBER() OVER (PARTITION BY ddd.recruit_id ORDER BY COALESCE(ddd.updated_at, ddd.created_at) DESC) AS rn,
                ddd.recruit_id,
                ddd.hidden
            FROM decision_deferment_dto ddd
            WHERE ddd.hidden is true -- когда фолс отсрочка есть, когда тру или нулл - нет (для подсчета подпадающих под призыв)
    ) ddd ON ddd.recruit_id = r.id AND ddd.rn = 1
    WHERE r.gender = 'MALE' AND

        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
       -- r.current_recruitment_id::uuid IN (SELECT recruitment_id FROM ids)
        AND 
        ((r.birth_date BETWEEN DATE (extract(year from now())-30||'-04-02') and DATE (extract(year from now())-18||'-07-13'))
        OR
        (r.birth_date BETWEEN DATE (extract(year from now())-30||'-10-02') and DATE (extract(year from now())-18||'-12-30')))

),
vse as (
    SELECT
        rd.hidden as postponement,
        'Весна' AS spring_autumn,
        --COALESCE(dd.updated_at, dd.created_at) AS postponement_date,
        r.recruit_id,
        rd.postponement_date,
        r.recruitment_id,
        r.hidden
    FROM recruit_data r
    LEFT JOIN (
        SELECT
            ROW_NUMBER() OVER (PARTITION BY rd.recruit_id ORDER BY COALESCE(rd.system_update_date, rd.system_create_date) DESC) AS rn,
            rd.recruit_id,
            rd.hidden,
            rd.postponement_date
        FROM recruits_deferment rd
        WHERE rd.hidden is false
        AND (rd.postponement_date > DATE_TRUNC('year', CURRENT_DATE) + INTERVAL '6 months' + INTERVAL '14 days')
        -- AND (rd.postponement_date > DATE_TRUNC('year', CURRENT_DATE) + INTERVAL '12 months')
    ) rd on rd.recruit_id = r.recruit_id AND rd.rn = 1
    WHERE r.spring_autumn = 'Весна'

    UNION ALL

    SELECT
        rd.hidden as postponement,
        'Осень' AS spring_autumn,
        --COALESCE(dd.updated_at, dd.created_at) AS postponement_date,
        r.recruit_id,
        rd.postponement_date,
        r.recruitment_id,
        r.hidden
    FROM recruit_data r
    LEFT JOIN (
        SELECT
            ROW_NUMBER() OVER (PARTITION BY rd.recruit_id ORDER BY COALESCE(rd.system_update_date, rd.system_create_date) DESC) AS rn,
            rd.recruit_id,
            rd.hidden,
            rd.postponement_date
        FROM recruits_deferment rd
        WHERE rd.hidden is false
        -- AND (rs.postponement_date > DATE_TRUNC('year', CURRENT_DATE) + INTERVAL '6 months' + INTERVAL '14 days')
        AND (rd.postponement_date > DATE_TRUNC('year', CURRENT_DATE) + INTERVAL '12 months')
    ) rd on rd.recruit_id = r.recruit_id AND rd.rn = 1
    WHERE r.spring_autumn = 'Осень'
)
SELECT
    r.recruitment_id,
    r.spring_autumn,
    current_date as recording_date,
    COUNT(r.recruit_id) FILTER (WHERE r.hidden IS NOT true) AS recruit,
    COUNT(r.recruit_id) FILTER (WHERE r.postponement IS NOT null) AS postponement_have_right
FROM vse r
GROUP BY recruitment_id, spring_autumn</sql>
    <variables_active>Y</variables_active>
    <attributes/>
    <GUI>
      <xloc>464</xloc>
      <yloc>320</yloc>
    </GUI>
  </transform>
  <transform>
    <name>Update</name>
    <type>Update</type>
    <description/>
    <distribute>Y</distribute>
    <custom_distribution/>
    <copies>1</copies>
    <partitioning>
      <method>none</method>
      <schema_name/>
    </partitioning>
    <commit>100</commit>
    <connection>ervu-dashboard</connection>
    <error_ignored>Y</error_ignored>
    <lookup>
      <key>
        <condition>=</condition>
        <field>recruitment_id</field>
        <name>recruitment_id</name>
      </key>
      <key>
        <condition>=</condition>
        <field>spring_autumn</field>
        <name>spring_autumn</name>
      </key>
      <key>
        <condition>=</condition>
        <field>recording_date</field>
        <name>recording_date</name>
      </key>
      <schema>main_dashboard</schema>
      <table>recruitment_campaign</table>
      <value>
        <name>new_recruits</name>
        <rename>recruit</rename>
      </value>
      <value>
        <name>postponement_have_right</name>
        <rename>postponement_have_right</rename>
      </value>
    </lookup>
    <skip_lookup>N</skip_lookup>
    <use_batch>Y</use_batch>
    <attributes/>
    <GUI>
      <xloc>1056</xloc>
      <yloc>320</yloc>
    </GUI>
  </transform>
  <transform_error_handling>
  </transform_error_handling>
  <attributes/>
</pipeline>
