use hahn; 
PRAGMA AnsiInForEmptyOrNullableItemsCollections;

$date_today = cast(CurrentUtcDate() as string);
-- $prev_date = cast(cast($date_today as date) - Interval('P1D') as string);

-- $date_start = cast(cast($date_today as date) - Interval('P7D') as string);
$date_start = '2022-01-01';
$tail_ts = 'T08:00:00Z';

$begin = $date_start || $tail_ts;
$end = $date_today || $tail_ts;


$invoice_service_id = 
    select 
        id, 
        service_id
        -- Идентификатор сервиса, на котором создан заказ; T_SERVICE.ID
    from `home/balance/prod/bo/t_invoice` as i
    join `home/balance/prod/bo/t_consume` as c 
        on c.invoice_id = i.id 
        -- invoice_id - Идентификатор счета (из T_INVOICE.ID), с которого средства зачислены на заказ
        -- id - Идентификатор счета (внутренний)
    join `home/balance/prod/bo/t_order` as o on 
        c.parent_order_id = o.id
        -- 	parent_order_id - Идентификатор заказа, на который перенесены средства с данной заявки
    where 
        i.hidden < 2 
            -- Состояние счета
            -- Default=0, 0 и 1 - нормальный, 2 - удален
        and o.service_id == 7 and
        -- Идентификатор сервиса, на котором создан заказ; T_SERVICE.ID
        i.dt >= $begin and i.dt <= $end
        -- Дата, которой счет проводится по бухгалтерии.
        -- Дата документа в бухгалтерском понимании:
        -- * либо дата выставления счета,
        -- * либо дата заданная в интерфейсе вручную, например для счетов на погашение
    group compact by
        i.id as id, 
        o.service_id as service_id;

$invoices = 
    select
        id,
        cast(client_id as uint64) as client_id,
        dt,
        if (dt like '%T21:00:00Z',
            SUBSTRING(dt, 0, 8) || "01",
            SUBSTRING(dt, 0, 10)) as `date`,
        if (dt like '%T21:00:00Z',
            'auto',
            'simple') as `type`,
        receipt_dt,
        SUBSTRING(receipt_dt, 0, 10) as receipt_date,
        internal_rate,
        -- Курс фишки
        consume_sum,
        -- Сумма, зачисленная на заказы, в фишках
        receipt_sum,
        -- Сумма в фишках, зачисленная в систему при включении счета
        receipt_sum_1c,
        -- Сумма приходов из бухгалтерской системы

    from `home/balance/prod/bo/t_invoice` as a
    left semi join $invoice_service_id as b using (id)
    where
        type == 'overdraft' and

        a.iso_currency == 'RUB' and

        cast(dt as datetime) between cast($begin as datetime) and cast($end as datetime);

insert into `//home/geo-analytics/miankova/overdraft/intervals` WITH TRUNCATE 
select * from $invoices;


$interval = ($a, $b) ->
    {return DateTime::ToDays(cast($a as date) - cast($b as date))}; 

$clients = 
select 
    `client_id`,
    client_first_date,
    `curr_counterparty_crm_tier`.name as tier,
    curr_counterparty_geo.rus_macroregion_name as rus_macroregion_name,
    curr_counterparty_geo.rus_region_name as rus_region_name,
    curr_counterparty_industry.industry as industry,
    curr_counterparty_industry.macroindustry as macroindustry,
    curr_client_domains,
    curr_client_main_domain,
    curr_counterparty_id,
    `agency_id`,
    `client_type`
from 
    `//home/comdep-crm-advisor/prod/common/clients/latest`
;

$avg_money = 
SELECT 
    clientid, 
    avg(money) as avg_money
from
    (SELECT  
        `clientid`,
        month, 
        sum(`money`) as money
    from
        `//statbox/cube/daily/comdep/cd_reporting/cd_all_with_tiers` 
    where
        scale = 'months'
        and money > 0
        and month like '2022%'
        and currency = 'rur'
        and product = 'Общая выручка'
        and product_1 like 'Директ%'
    group by 
        clientid,
        month)
group by 
    clientid
;

$res = 
select 
    intervals.*,
    intervals.type as overdraft_type,
    $interval($date_today, intervals.`date`) as days_before_today,
    if(receipt_sum_1c = 0,receipt_sum,  if(receipt_sum = 0, receipt_sum_1c, receipt_sum ))  as receipt_sum_new,
    clients.*,
    clients1.`overdraft_lim` as overdraft_lim,
    clients1.`statusBalanceBanned` as statusBalanceBanned,
    money.avg_money as avg_money_22
    without 
        clients.`client_id`,
        intervals.`dt`,
        intervals.`receipt_dt`,
        intervals.type
from 
    $invoices as intervals
left join 
    $clients as clients
    on clients.`client_id` = intervals.client_id
left join 
    `//home/direct/db/clients` as clients1 
    on intervals.client_id = clients1.ClientID
left join 
    $avg_money as money 
    on money.clientid = intervals.client_id
;


$diff = ($date_invoice, $day) -> 
{   return
    DateTime::ToDays(cast($day as date) - cast($date_invoice as date))
}
;




$clients = 
select 
    distinct `client_id`
from 
    $res
;

$days = 
SELECT 
        `clientid`,
        day, 
        sum(`money`) as money,
    from
        `//statbox/cube/daily/comdep/cd_reporting/cd_all_with_tiers` 
    where
        scale = 'days'
        and (day like '2022%')
        and money > 0
        and currency = 'rur'
        and product = 'Общая выручка'
        and product_1 like 'Директ%'
        and clientid in $clients
    group by 
        clientid,
        day
;


$res_money = 
select 
    clientid, 
    day, 
    money,
    count(id) as invoices, 
    count_if($diff(c.`date`, d.day) < 15) as invoices_15,
    count_if($diff(c.`date`, d.day) < 20) as invoices_20,
    count_if($diff(c.`date`, d.day) < 28) as invoices_28
from 
    $res as c
join 
    $days as d 
    on c.client_id = d.clientid 
where 
    d.day >= c.`date`
    and (d.day<= c.`receipt_date` or `receipt_date` is null)
group by 
    d.clientid as clientid, 
    d.day as day, 
    d.money as money

;
$res_new = 
SELECT 
    id,
    sum(money/invoices) as direct_money,
    sum_if(money/invoices_15, $diff(c.`date`, m.day) < 15) as direct_money_15,
    sum_if(money/invoices_20, $diff(c.`date`, m.day) < 20) as direct_money_20,
    sum_if(money/invoices_28, $diff(c.`date`, m.day) < 28) as direct_money_28
from 
    $res as c 
left join 
    $res_money as m 
    on c.client_id = m.clientid
where  
    m.day >= c.`date`
    and (m.day <= c.`receipt_date` or `receipt_date` is null)
group by 
    c.`id` as `id`
;


INSERT INTO `//home/geo-analytics/miankova/overdraft/intervals_geo_tier` WITH TRUNCATE 
select 
    *
from 
    $res
;


INSERT INTO `//home/geo-analytics/miankova/overdraft/additional_money`  WITH TRUNCATE 
select 
    invoices.* ,
    money.* 
    without 
        money.id
from 
    $res as invoices
join 
    $res_new as money
    using(id)
;
