<?xml version="1.0" encoding="UTF-8"?>
<pipeline>
  <info>
    <name>main_dashboard.total_registered_pr2(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 (main_dashboard.total_registered) 2</to>
      <enabled>Y</enabled>
    </hop>
  </order>
  <transform>
    <name>Insert / update (main_dashboard.total_registered) 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>convicts</field>
        <name>convicts</name>
      </key>
      <schema>main_dashboard</schema>
      <table>total_registered</table>
      <value>
        <name>total_registered</name>
        <rename>total_count</rename>
        <update>Y</update>
      </value>
      <value>
        <name>"total_registered_M"</name>
        <rename>male_count</rename>
        <update>Y</update>
      </value>
      <value>
        <name>"total_registered_W"</name>
        <rename>female_count</rename>
        <update>Y</update>
      </value>
      <value>
        <name>mobilization_criterion</name>
        <rename>mobilization_criterion</rename>
        <update>Y</update>
      </value>
      <value>
        <name>volunteer_criterion</name>
        <rename>volunteer_criterion</rename>
        <update>Y</update>
      </value>
      <value>
        <name>contract_criterion</name>
        <rename>contract_criterion</rename>
        <update>Y</update>
      </value>
      <value>
        <name>mobilization_criterion_percent</name>
        <rename>mobilization_criterion_percent</rename>
        <update>Y</update>
      </value>
      <value>
        <name>volunteer_criterion_percent</name>
        <rename>volunteer_criterion_percent</rename>
        <update>Y</update>
      </value>
      <value>
        <name>contract_criterion_percent</name>
        <rename>contract_criterion_percent</rename>
        <update>Y</update>
      </value>
      <value>
        <name>recruitment_id</name>
        <rename>recruitment_id</rename>
        <update>N</update>
      </value>
      <value>
        <name>convicts</name>
        <rename>convicts</rename>
        <update>N</update>
      </value>
    </lookup>
    <update_bypassed>N</update_bypassed>
    <attributes/>
    <GUI>
      <xloc>1168</xloc>
      <yloc>320</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_2}'), ','))::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
                    ),
*/
vse AS (
    SELECT
    --distinct
        r.id AS r_id,
        ri.recruit_id AS recruit_id,
        CASE
            WHEN r.vu_current_info->>'recruitmentCommercialInfo' = 'true' THEN 'CONVICT'
            ELSE 'NOTCONVICT'
        END AS convicts,
        --coalesce (r.current_recruitment_id, rh.current_recruitment_id) AS r_current_recruitment_id,
        r.current_recruitment_id AS r_current_recruitment_id,
        r.gender,
        r.birth_date,
        --r.conscription,
        CASE 
            WHEN jsonb_typeof(ri.info->'svedFL'->'svedPND'->'svedUchetDisp'->'svedUchet') = 'array' THEN
                EXISTS (
                    SELECT 1
                    FROM jsonb_array_elements(ri.info->'svedFL'->'svedPND'->'svedUchetDisp'->'svedUchet') AS uchet_pnd
                    WHERE uchet_pnd->>'dataSnyatUchet' &lt;= current_date::text
                )
            ELSE 
                false
        END AS uchet_pnd,
        CASE 
            WHEN ddd.hidden IS false THEN ddd.hidden
            ELSE true
        END AS 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.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)
*/
),
extracted_children AS (
    SELECT
        ri.recruit_id,
        jsonb_array_elements_text(ri.info->'svedDeti'->'rebenok') AS child
    FROM vse ri
    WHERE jsonb_typeof(ri.info->'svedDeti'->'rebenok') = 'array'
),
children_birth_dates AS (
    SELECT
        recruit_id,
        (child::jsonb->'svedFLBS'->'dataRozhdDok'->>'den')::int AS day,
        (child::jsonb->'svedFLBS'->'dataRozhdDok'->>'mesyacz')::int AS month,
        (child::jsonb->'svedFLBS'->'dataRozhdDok'->>'god')::int AS year
    FROM extracted_children
),
children_count AS (
    SELECT
        recruit_id,
        COUNT(*) AS children_under_16
    FROM children_birth_dates
    WHERE AGE(make_date(year, month, day)) &lt; interval '16 years'
    GROUP BY recruit_id
),
recruit_data AS (
    SELECT
        ri.r_current_recruitment_id::uuid AS recruitment_id,
        ri.convicts,
        COUNT(distinct ri.recruit_id) AS total_count,
        COUNT(distinct ri.recruit_id) FILTER (WHERE gender = 'MALE') AS male_count,
        COUNT(distinct ri.recruit_id) FILTER (WHERE gender = 'FEMALE') AS female_count,
        COUNT(distinct ri.recruit_id) FILTER (
            WHERE (EXTRACT(YEAR FROM AGE(NOW(), birth_date)) BETWEEN 30 AND 50 AND gender = 'MALE') -- мужчины от 30 до 50 лет
            OR (EXTRACT(YEAR FROM AGE(NOW(), birth_date)) BETWEEN 30 AND 45 AND gender = 'FEMALE') -- женщины от 30 до 45 лет
                AND COALESCE(cc.children_under_16, 0) &lt; 5
        ) AS mobilization_criterion, -- критерии от 03.06.2025

        COUNT(distinct ri.recruit_id) FILTER (
            WHERE EXTRACT(YEAR FROM AGE(NOW(), birth_date)) BETWEEN 18 AND 30
                AND gender = 'MALE'
                AND hidden IS true -- нет отсрочки и нет освобождения от службы
        ) AS volunteer_criterion, -- критерии от 03.06.2025

        COUNT(distinct ri.recruit_id) FILTER (
            WHERE EXTRACT(YEAR FROM AGE(NOW(), birth_date)) BETWEEN 18 AND 50
                AND gender = 'MALE'
                AND (ri.info->'svedFL'->'svedPND'->>'prOtsSvedPND' = '1'
                OR uchet_pnd is false) 
                AND ri.info->'svedFL'->'svedUchetVICH'->>'prOtsSvedUchetVICH' = '1' -- признак отсутствия сведений о заболевании ВИЧ
                --AND ri.info->'svedSudim'->>'prOtsSvedSudim' = '1'
        ) AS contract_criterion -- критерии от 03.06.2025
    FROM vse AS ri
    LEFT JOIN children_count AS cc ON ri.recruit_id = cc.recruit_id
    GROUP BY ri.r_current_recruitment_id, ri.convicts
),
recruit_data_all AS (
    SELECT
        recruitment_id,
        'ALL' AS convicts,
        SUM(total_count) AS total_count,
        SUM(male_count) AS male_count,
        SUM(female_count) AS female_count,
        SUM(mobilization_criterion) AS mobilization_criterion,
        SUM(volunteer_criterion) AS volunteer_criterion,
        SUM(contract_criterion) AS contract_criterion
    FROM recruit_data
    GROUP BY recruitment_id
)
SELECT
    ids.recruitment_id,
    rd.convicts,
    current_date AS recording_date,
    COALESCE(rd.total_count, 0) AS total_count,
    COALESCE(rd.male_count, 0) AS male_count,
    COALESCE(rd.female_count, 0) AS female_count,
    COALESCE(rd.mobilization_criterion, 0) AS mobilization_criterion,
    COALESCE(rd.volunteer_criterion, 0) AS volunteer_criterion,
    COALESCE(rd.contract_criterion, 0) AS contract_criterion,
    CASE
        WHEN rd.total_count > 0 THEN ROUND(rd.mobilization_criterion::NUMERIC / rd.total_count * 100, 2)
        ELSE 0
    END AS mobilization_criterion_percent,
    CASE
        WHEN rd.total_count > 0 THEN ROUND(rd.volunteer_criterion::NUMERIC / rd.total_count * 100, 2)
        ELSE 0
    END AS volunteer_criterion_percent,
    CASE
        WHEN rd.total_count > 0 THEN ROUND(rd.contract_criterion::NUMERIC / rd.total_count * 100, 2)
        ELSE 0
    END AS contract_criterion_percent
FROM ids
JOIN recruit_data AS rd ON ids.recruitment_id = rd.recruitment_id

UNION ALL

SELECT
    ids.recruitment_id,
    rd.convicts,
    current_date AS recording_date,
    COALESCE(rd.total_count, 0) AS total_count,
    COALESCE(rd.male_count, 0) AS male_count,
    COALESCE(rd.female_count, 0) AS female_count,
    COALESCE(rd.mobilization_criterion, 0) AS mobilization_criterion,
    COALESCE(rd.volunteer_criterion, 0) AS volunteer_criterion,
    COALESCE(rd.contract_criterion, 0) AS contract_criterion,
    CASE
        WHEN rd.total_count > 0 THEN ROUND(rd.mobilization_criterion::NUMERIC / rd.total_count * 100, 2)
        ELSE 0
    END AS mobilization_criterion_percent,
    CASE
        WHEN rd.total_count > 0 THEN ROUND(rd.volunteer_criterion::NUMERIC / rd.total_count * 100, 2)
        ELSE 0
    END AS volunteer_criterion_percent,
    CASE
        WHEN rd.total_count > 0 THEN ROUND(rd.contract_criterion::NUMERIC / rd.total_count * 100, 2)
        ELSE 0
    END AS contract_criterion_percent
FROM ids
JOIN recruit_data_all AS rd ON ids.recruitment_id = rd.recruitment_id</sql>
    <variables_active>Y</variables_active>
    <attributes/>
    <GUI>
      <xloc>496</xloc>
      <yloc>320</yloc>
    </GUI>
  </transform>
  <transform_error_handling>
  </transform_error_handling>
  <attributes/>
</pipeline>
