PRAGMA yt.PoolTrees = "physical";
PRAGMA yt.TentativePoolTrees = "cloud";

-- OPERANALYTICS-915
-- Дашборд про оплату за конверсии
USE hahn;

$order_cum_cost = (
SELECT
  s.*
, SUM(cost_rub_wo_nds) OVER order_w AS cum_order_total_cost_rub_wo_nds
, WITHOUT cost_rub_wo_nds
FROM (
  SELECT
    client_id
  , order_id
  , stat_date
  , nvl(SUM(os.Cost) / 1e6 / 1.18 * 30, 0) AS cost_rub_wo_nds
  FROM `//home/yabs/stat/OrderStatDay` AS os
  JOIN `//home/yabs/dict/CaesarOrderInfo` AS oi
    ON os.OrderID = oi.OrderID
  WHERE oi.EngineID = 7  -- Direct
    AND oi.OrderType = 1  -- commerce
    AND NOT nvl(oi.ContentTypeMobileContent, False)  -- https://st.yandex-team.ru/OPERANALYTICS-1622
  GROUP BY
    oi.ClientID AS client_id
  , os.OrderID AS order_id
  , CAST(DateTime::MakeDate(DateTime::FromSeconds(CAST(os.UpdateTime + 3600 * 3 AS Uint32))) AS String) AS stat_date
) AS s
WINDOW order_w AS (
  PARTITION BY order_id
  ORDER BY stat_date
)
);

$client_cum_cost = (
SELECT
  client_id
, stat_date
, SUM(cum_order_total_cost_rub_wo_nds) AS cum_client_total_cost_rub_wo_nds
FROM $order_cum_cost
GROUP BY
  client_id
, stat_date
);

$client_cat = (
SELECT client_id, MAX_BY(category, cost) AS category
FROM `//home/comdep-analytics/ndorofeev/adhoc/ClientMediagroup`
WHERE category NOT ILIKE "ВИРТ _%"
  AND client_id > 0
GROUP BY client_id
);
$chevent = (
SELECT
  orderid
, eventdate
, SUM(shows) AS shows
, SUM(clicks) AS clicks
, SUM(cost_rub_wo_nds) AS cost_rub_wo_nds
, SUM(tcost_rub_wo_nds) AS tcost_rub_wo_nds
FROM RANGE(`//home/vipplanners/dashboard_paid_actions/daily/chevent`)
GROUP BY
  orderid
, eventdate
);
$action_daily = (
SELECT
  orderid
, eventdate
, SUM_IF(actions, action_week >= 3) AS actions_old
-- weeks 4+ total
, SUM(actions) AS actions
, SUM(actions_extra) AS actions_extra
, SUM(cost_rub_wo_nds) AS cost_rub_wo_nds
, SUM(tcost_rub_wo_nds) AS tcost_rub_wo_nds
-- weeks 0
, SUM_IF(actions, action_week == 0) AS actions_w0
, SUM_IF(actions_extra, action_week == 0) AS actions_extra_w0
, SUM_IF(cost_rub_wo_nds, action_week == 0) AS cost_rub_wo_nds_w0
, SUM_IF(tcost_rub_wo_nds, action_week == 0) AS tcost_rub_wo_nds_w0
-- weeks 1
, SUM_IF(actions, action_week <= 1) AS actions_w1
, SUM_IF(actions_extra, action_week <= 1) AS actions_extra_w1
, SUM_IF(cost_rub_wo_nds, action_week <= 1) AS cost_rub_wo_nds_w1
, SUM_IF(tcost_rub_wo_nds, action_week <= 1) AS tcost_rub_wo_nds_w1
-- weeks 2
, SUM_IF(actions, action_week <= 2) AS actions_w2
, SUM_IF(actions_extra, action_week <= 2) AS actions_extra_w2
, SUM_IF(cost_rub_wo_nds, action_week <= 2) AS cost_rub_wo_nds_w2
, SUM_IF(tcost_rub_wo_nds, action_week <= 2) AS tcost_rub_wo_nds_w2
-- weeks 3
, SUM_IF(actions, action_week <= 3) AS actions_w3
, SUM_IF(actions_extra, action_week <= 3) AS actions_extra_w3
, SUM_IF(cost_rub_wo_nds, action_week <= 3) AS cost_rub_wo_nds_w3
, SUM_IF(tcost_rub_wo_nds, action_week <= 3) AS tcost_rub_wo_nds_w3
FROM RANGE(`//home/vipplanners/dashboard_paid_actions/daily/action`)
GROUP BY
  orderid
, eventdate
);
$action_5min = (
SELECT
  orderid
, eventdate
, SUM_IF(actions, action_week >= 3) AS actions_old
-- weeks 4+ total
, SUM(actions) AS actions
, SUM(actions_extra) AS actions_extra
, SUM(cost_rub_wo_nds) AS cost_rub_wo_nds
, SUM(tcost_rub_wo_nds) AS tcost_rub_wo_nds
-- weeks 0
, SUM_IF(actions, action_week == 0) AS actions_w0
, SUM_IF(actions_extra, action_week == 0) AS actions_extra_w0
, SUM_IF(cost_rub_wo_nds, action_week == 0) AS cost_rub_wo_nds_w0
, SUM_IF(tcost_rub_wo_nds, action_week == 0) AS tcost_rub_wo_nds_w0
-- weeks 1
, SUM_IF(actions, action_week <= 1) AS actions_w1
, SUM_IF(actions_extra, action_week <= 1) AS actions_extra_w1
, SUM_IF(cost_rub_wo_nds, action_week <= 1) AS cost_rub_wo_nds_w1
, SUM_IF(tcost_rub_wo_nds, action_week <= 1) AS tcost_rub_wo_nds_w1
-- weeks 2
, SUM_IF(actions, action_week <= 2) AS actions_w2
, SUM_IF(actions_extra, action_week <= 2) AS actions_extra_w2
, SUM_IF(cost_rub_wo_nds, action_week <= 2) AS cost_rub_wo_nds_w2
, SUM_IF(tcost_rub_wo_nds, action_week <= 2) AS tcost_rub_wo_nds_w2
-- weeks 3
, SUM_IF(actions, action_week <= 3) AS actions_w3
, SUM_IF(actions_extra, action_week <= 3) AS actions_extra_w3
, SUM_IF(cost_rub_wo_nds, action_week <= 3) AS cost_rub_wo_nds_w3
, SUM_IF(tcost_rub_wo_nds, action_week <= 3) AS tcost_rub_wo_nds_w3
FROM `//home/vipplanners/dashboard_paid_actions/5min/action`
GROUP BY
  orderid
, eventdate
);
$action = (
SELECT
  orderid
, eventdate
, SUM(actions_old) AS actions_old
-- week 4+ total
, SUM(actions) AS actions
, SUM(actions_extra) AS actions_extra
, SUM(cost_rub_wo_nds) AS cost_rub_wo_nds
, SUM(tcost_rub_wo_nds) AS tcost_rub_wo_nds
-- week 0
, SUM(actions_w0) AS actions_w0
, SUM(actions_extra_w0) AS actions_extra_w0
, SUM(cost_rub_wo_nds_w0) AS cost_rub_wo_nds_w0
, SUM(tcost_rub_wo_nds_w0) AS tcost_rub_wo_nds_w0
-- week 1
, SUM(actions_w1) AS actions_w1
, SUM(actions_extra_w1) AS actions_extra_w1
, SUM(cost_rub_wo_nds_w1) AS cost_rub_wo_nds_w1
, SUM(tcost_rub_wo_nds_w1) AS tcost_rub_wo_nds_w1
-- week 2
, SUM(actions_w2) AS actions_w2
, SUM(actions_extra_w2) AS actions_extra_w2
, SUM(cost_rub_wo_nds_w2) AS cost_rub_wo_nds_w2
, SUM(tcost_rub_wo_nds_w2) AS tcost_rub_wo_nds_w2
-- week 3
, SUM(actions_w3) AS actions_w3
, SUM(actions_extra_w3) AS actions_extra_w3
, SUM(cost_rub_wo_nds_w3) AS cost_rub_wo_nds_w3
, SUM(tcost_rub_wo_nds_w3) AS tcost_rub_wo_nds_w3
FROM (
  SELECT * FROM $action_daily UNION ALL
  SELECT * FROM $action_5min
)
GROUP BY
  orderid
, eventdate
);
-- нельзя брать дату создания кампании, оплата за коверсии это стратегия, её можно менять
$paid_action_start = (
SELECT orderid, MIN(eventdate) AS action_start_date
FROM $chevent
WHERE shows > 0
GROUP BY orderid
);
$total_actions = (
SELECT
  orderid
, SUM(actions) AS curr_total_actions
, SUM(actions_extra) AS curr_total_actions_extra
, SUM(tcost_rub_wo_nds) AS curr_total_tcost_rub_wo_nds
, SUM(cost_rub_wo_nds) AS curr_total_cost_rub_wo_nds
FROM $action
GROUP BY orderid
);
INSERT INTO @orderday_1 WITH TRUNCATE
SELECT
  order_id
, eventdate
, SOME(oi.ClientID) AS client_id
, SOME(oi.ExportID) AS CampaignID
, SOME(oi.EngineID) AS ServiceID
, SOME(pa.action_start_date) AS paid_action_start_date
, CAST(DateTime::MakeDate(DateTime::StartOfWeek(SOME(CAST(pa.action_start_date AS Date)))) AS String) AS paid_action_start_week
, CAST(DateTime::MakeDate(DateTime::StartOfMonth(SOME(CAST(pa.action_start_date AS Date)))) AS String) AS paid_action_start_month
, DateTime::ToDays(CAST(eventdate AS Date) - CAST(SOME(pa.action_start_date) AS Date)) + 1 AS paid_action_age_day
, (DateTime::ToDays(CAST(eventdate AS Date) - CAST(SOME(pa.action_start_date) AS Date)) / 7) + 1 AS paid_action_age_week
, (DateTime::ToDays(CAST(eventdate AS Date) - SOME(CAST(pa.action_start_date AS Date))) / 28) + 1 AS paid_action_age_month
, SOME(crm.client_login) AS client_login
, SOME(crm.client_name) ?? '' AS client_name
, SOME(crm.client_type) ?? '' AS client_type
, SOME(crm.curr_counterparty_reporting_tier.name) ?? '' AS curr_client_tier
, SOME(crm.curr_counterparty_geo.country_name) ?? '' AS curr_client_country
, SOME(crm.curr_counterparty_id) ?? 0 AS curr_counterparty_id
, SOME(crm.curr_counterparty_name) ?? '' AS curr_counterparty_name
, SOME(crm.curr_client_main_domain) ?? '' AS curr_client_main_domain
, SOME(crm.curr_counterparty_sales_manager.login) ?? '' AS curr_manager_domain_login
, SOME(crm.curr_counterparty_sales_manager.name) ?? '' AS curr_manager_name
, SOME(cc.category) ?? 'UNKNOWN' AS curr_client_main_mediagroup
, CAST(SUM(e.shows) AS Int64) AS shows
, CAST(SUM(e.clicks) AS Int64) ?? 0 AS clicks
, SUM(e.cost_rub_wo_nds) ?? 0 AS cost_rub_wo_nds_clicks
, nvl(SUM(e.tcost_rub_wo_nds), 0) AS tcost_rub_wo_nds_shows
-- старые конверсии, возраст больше 21 дня
, SUM(a.actions_old) AS actions_old
-- action week 4+ total
, CAST(nvl(SUM(a.actions), 0) AS Int64) AS actions
, MAX_OF(0, CAST(nvl(SUM(a.actions_extra), 0) AS Int64)) AS actions_extra
, nvl(SUM(a.cost_rub_wo_nds), 0) AS cost_rub_wo_nds_actions
, nvl(SUM(a.tcost_rub_wo_nds), 0) AS tcost_rub_wo_nds_actions
-- action week 0
, MAX_OF(0, nvl(SUM(a.actions_w0), 0)) AS actions_w0
, MAX_OF(0, nvl(SUM(a.actions_extra_w0), 0)) AS actions_extra_w0
, nvl(SUM(a.cost_rub_wo_nds_w0), 0) AS cost_rub_wo_nds_w0
, nvl(SUM(a.tcost_rub_wo_nds_w0), 0) AS tcost_rub_wo_nds_w0
-- action week 1
, MAX_OF(0, nvl(SUM(a.actions_w1), 0)) AS actions_w1
, MAX_OF(0, nvl(SUM(a.actions_extra_w1), 0)) AS actions_extra_w1
, nvl(SUM(a.cost_rub_wo_nds_w1), 0) AS cost_rub_wo_nds_w1
, nvl(SUM(a.tcost_rub_wo_nds_w1), 0) AS tcost_rub_wo_nds_w1
-- action week 2
, MAX_OF(0, nvl(SUM(a.actions_w2), 0)) AS actions_w2
, MAX_OF(0, nvl(SUM(a.actions_extra_w2), 0)) AS actions_extra_w2
, nvl(SUM(a.cost_rub_wo_nds_w2), 0) AS cost_rub_wo_nds_w2
, nvl(SUM(a.tcost_rub_wo_nds_w2), 0) AS tcost_rub_wo_nds_w2
-- action week 3
, MAX_OF(0, nvl(SUM(a.actions_w3), 0)) AS actions_w3
, MAX_OF(0, nvl(SUM(a.actions_extra_w3), 0)) AS actions_extra_w3
, nvl(SUM(a.cost_rub_wo_nds_w3), 0) AS cost_rub_wo_nds_w3
, nvl(SUM(a.tcost_rub_wo_nds_w3), 0) AS tcost_rub_wo_nds_w3
-- профит с недельным накоплением по возрасту конверсии
, nvl(SUM(a.cost_rub_wo_nds_w0), 0) - nvl(SUM(e.cost_rub_wo_nds), 0) AS profit_rub_wo_nds_w0
, nvl(SUM(a.cost_rub_wo_nds_w1), 0) - nvl(SUM(e.cost_rub_wo_nds), 0) AS profit_rub_wo_nds_w1
, nvl(SUM(a.cost_rub_wo_nds_w2), 0) - nvl(SUM(e.cost_rub_wo_nds), 0) AS profit_rub_wo_nds_w2
, nvl(SUM(a.cost_rub_wo_nds_w3), 0) - nvl(SUM(e.cost_rub_wo_nds), 0) AS profit_rub_wo_nds_w3
, nvl(SUM(a.cost_rub_wo_nds), 0) - nvl(SUM(e.cost_rub_wo_nds), 0) AS profit_rub_wo_nds
-- текущие суммарные показатели по кампаниям (для фильтрации на дашбордах)
, nvl(SOME(ta.curr_total_actions), 0) AS curr_total_actions
, nvl(SOME(ta.curr_total_actions_extra), 0) AS curr_total_actions_extra
, nvl(SOME(ta.curr_total_cost_rub_wo_nds), 0) AS curr_total_cost_rub_wo_nds
, nvl(SOME(ta.curr_total_tcost_rub_wo_nds), 0) AS curr_total_tcost_rub_wo_nds
-- сколько было потрачено всего в Директе до перехода первый раз на CPA
, nvl(SOME(cumcl.cum_client_total_cost_rub_wo_nds), 0) AS before_cpa_client_total_cost_rub_wo_nds
, nvl(SOME(cumord.cum_order_total_cost_rub_wo_nds), 0) AS cum_order_total_cost_rub_wo_nds
FROM $chevent AS e
LEFT JOIN $paid_action_start AS pa
  ON e.orderid = pa.orderid
LEFT JOIN $total_actions AS ta
  ON e.orderid = ta.orderid
LEFT JOIN $action AS a
  ON e.orderid = a.orderid
 AND e.eventdate = a.eventdate
JOIN `//home/yabs/dict/CaesarOrderInfo` AS oi
  ON e.orderid = oi.OrderID
JOIN `//home/comdep-analytics/public/client_tiers/fact/latest_v2` AS crm
  ON oi.ClientID = crm.client_id
LEFT JOIN $client_cat AS cc
  ON oi.ClientID = cc.client_id
LEFT JOIN $client_cum_cost AS cumcl
  ON pa.action_start_date = cumcl.stat_date
 AND oi.ClientID = cumcl.client_id
LEFT JOIN $order_cum_cost AS cumord
  ON e.eventdate = cumord.stat_date
 AND e.orderid = cumord.order_id
WHERE e.shows > 0
-- https://yql.yandex-team.ru/Operations/YA7fKCyLNR8WscGXWGu1Ck55h0TGAywP_CF2OF8ZOtM=
-- После рефакторинга комдепа таблички с тирами индустрия теперь называется ICO, а не Intercompany units
  AND nvl(crm.curr_counterparty_industry.industry, '') NOT IN ("Intercompany units", "ICO", "ico")
  AND NOT nvl(oi.ContentTypeMobileContent, False)  -- https://st.yandex-team.ru/OPERANALYTICS-1622
  AND NOT nvl(oi.ContentTypeReach, False)  -- https://st.yandex-team.ru/DIRECTANALYTICS-491
GROUP BY
  e.orderid AS order_id
, e.eventdate AS eventdate
;
COMMIT;
$LAST_DATE = (SELECT CAST(MAX(eventdate) AS Date) FROM @orderday_1);
$MAX_PAUSE_DAYS = 7;  -- если следующая активность через 7+ дней, то считаем текущий день остановкой
$is_last_day = ($test_date, $next_date) -> {
  $MAX_INTERVAL = DateTime::IntervalFromDays(CAST($MAX_PAUSE_DAYS AS Int16));
  $is_old_event = ($LAST_DATE - $test_date) >= $MAX_INTERVAL;
  $is_last = nvl(($next_date - $test_date) > $MAX_INTERVAL, True);
  RETURN $is_old_event AND $is_last;
};
INSERT INTO @orderday WITH TRUNCATE
SELECT
  o.*
, SUM(actions) OVER order_w AS cum_actions
, SUM(profit_rub_wo_nds) OVER order_w AS cum_profit_rub_wo_nds_day
, SUM(profit_rub_wo_nds) OVER order_day_cohort AS cum_profit_rub_wo_nds_day_cohort
, SUM(cost_rub_wo_nds_clicks) OVER order_day_cohort AS cum_cost_rub_wo_nds_clicks_day_cohort
, SUM(cost_rub_wo_nds_actions) OVER order_day_cohort AS cum_cost_rub_wo_nds_actions_day_cohort
, $is_last_day(CAST(eventdate AS Date), CAST(LEAD(o.eventdate) OVER order_w AS Date)) AS is_last_day
, oi.OrderType = 1 AS is_commerce
FROM @orderday_1 AS o
JOIN `//home/yabs/dict/CaesarOrderInfo` AS oi
  ON o.order_id = oi.OrderID
WINDOW order_w AS (
  PARTITION BY o.order_id
  ORDER BY eventdate
)
, order_day_cohort AS (
  PARTITION BY o.order_id
  ORDER BY paid_action_age_day
)
;
COMMIT;
INSERT INTO `//home/vipplanners/dashboard_paid_actions/cube/orderday` WITH TRUNCATE
SELECT *
FROM @orderday
WHERE is_commerce
ORDER BY eventdate, order_id
;

INSERT INTO `//home/vipplanners/dashboard_paid_actions/cube/orderday_full` WITH TRUNCATE
SELECT *
FROM @orderday
ORDER BY eventdate, order_id
;

COMMIT;

-- клиент утек, если остановил все кампании с оплатой за конверсии
---------------------
-- вариант с тирами -
---------------------
$new_client_tier = (
SELECT
  eventdate
, curr_client_tier
, CAST(COUNT(*) AS Int64) AS new_clients
-- клиент считается новичком в Директе, если до перехода на CPA потратил менее 1000₽.
, CAST(COUNT_IF((before_cpa_client_total_cost_rub_wo_nds - cost_rub_wo_nds_actions_first_day) < 1000) AS Int64) AS new_direct_clients
, CAST(COUNT_IF((before_cpa_client_total_cost_rub_wo_nds - cost_rub_wo_nds_actions_first_day) BETWEEN 1000 AND 300000) AS Int64) AS sm_direct_clients
, CAST(COUNT_IF((before_cpa_client_total_cost_rub_wo_nds - cost_rub_wo_nds_actions_first_day) > 300000) AS Int64) AS other_direct_clients
FROM (
  SELECT
    client_id
  , SOME(curr_client_tier) AS curr_client_tier
  , MIN(eventdate) AS eventdate
  , SOME(before_cpa_client_total_cost_rub_wo_nds) AS before_cpa_client_total_cost_rub_wo_nds
  , MIN_BY(cost_rub_wo_nds_actions, eventdate) AS cost_rub_wo_nds_actions_first_day
  FROM @orderday
  WHERE is_commerce
  GROUP BY client_id
)
GROUP BY eventdate, curr_client_tier
);

$new_client_week_tier = (
SELECT
  eventweek
, curr_client_tier
, CAST(COUNT(*) AS Int64) AS new_clients
-- клиент считается новичком в Директе, если до перехода на CPA потратил менее 1000₽.
, CAST(COUNT_IF((before_cpa_client_total_cost_rub_wo_nds - cost_rub_wo_nds_actions_first_day) < 1000) AS Int64) AS new_direct_clients
, CAST(COUNT_IF((before_cpa_client_total_cost_rub_wo_nds - cost_rub_wo_nds_actions_first_day) BETWEEN 1000 AND 300000) AS Int64) AS sm_direct_clients
, CAST(COUNT_IF((before_cpa_client_total_cost_rub_wo_nds - cost_rub_wo_nds_actions_first_day) > 300000) AS Int64) AS other_direct_clients
FROM (
  SELECT
    client_id
  , SOME(curr_client_tier) AS curr_client_tier
  , MIN(eventdate) AS eventdate
  , SOME(before_cpa_client_total_cost_rub_wo_nds) AS before_cpa_client_total_cost_rub_wo_nds
  , MIN_BY(cost_rub_wo_nds_actions, eventdate) AS cost_rub_wo_nds_actions_first_day
  FROM @orderday
  WHERE is_commerce
  GROUP BY client_id
)
GROUP BY
  CAST(DateTime::MakeDate(DateTime::StartOfWeek(CAST(eventdate AS Date))) AS String) AS eventweek
, curr_client_tier
);

$new_client_month_tier = (
SELECT
  eventmonth
, curr_client_tier
, CAST(COUNT(*) AS Int64) AS new_clients
-- клиент считается новичком в Директе, если до перехода на CPA потратил менее 1000₽.
, CAST(COUNT_IF((before_cpa_client_total_cost_rub_wo_nds - cost_rub_wo_nds_actions_first_day) < 1000) AS Int64) AS new_direct_clients
, CAST(COUNT_IF((before_cpa_client_total_cost_rub_wo_nds - cost_rub_wo_nds_actions_first_day) BETWEEN 1000 AND 300000) AS Int64) AS sm_direct_clients
, CAST(COUNT_IF((before_cpa_client_total_cost_rub_wo_nds - cost_rub_wo_nds_actions_first_day) > 300000) AS Int64) AS other_direct_clients
FROM (
  SELECT
    client_id
  , SOME(curr_client_tier) AS curr_client_tier
  , MIN(eventdate) AS eventdate
  , SOME(before_cpa_client_total_cost_rub_wo_nds) AS before_cpa_client_total_cost_rub_wo_nds
  , MIN_BY(cost_rub_wo_nds_actions, eventdate) AS cost_rub_wo_nds_actions_first_day
  FROM @orderday
  WHERE is_commerce
  GROUP BY client_id
)
GROUP BY
  CAST(DateTime::MakeDate(DateTime::StartOfMonth(CAST(eventdate AS Date))) AS String) AS eventmonth
, curr_client_tier
);

$new_order_tier = (
SELECT
  eventdate
, curr_client_tier
, CAST(COUNT(*) AS Int64) AS new_orders
FROM (
  SELECT
    MIN(eventdate) AS eventdate
  , SOME(curr_client_tier) AS curr_client_tier
  FROM @orderday
  WHERE is_commerce
  GROUP BY order_id
)
GROUP BY eventdate, curr_client_tier
);
$new_order_week_tier = (
SELECT
  eventweek
, curr_client_tier
, CAST(COUNT(*) AS Int64) AS new_orders
FROM (
  SELECT
    MIN(eventdate) AS eventdate
  , SOME(curr_client_tier) AS curr_client_tier
  FROM @orderday
  WHERE is_commerce
  GROUP BY order_id
)
GROUP BY
  CAST(DateTime::MakeDate(DateTime::StartOfWeek(CAST(eventdate AS Date))) AS String) AS eventweek
, curr_client_tier
);
$new_order_month_tier = (
SELECT
  eventmonth
, curr_client_tier
, CAST(COUNT(*) AS Int64) AS new_orders
FROM (
  SELECT
    MIN(eventdate) AS eventdate
  , SOME(curr_client_tier) AS curr_client_tier
  FROM @orderday
  WHERE is_commerce
  GROUP BY order_id
)
GROUP BY
  CAST(DateTime::MakeDate(DateTime::StartOfMonth(CAST(eventdate AS Date))) AS String) AS eventmonth
, curr_client_tier
);
-- клиент утек, если остановил все кампании с оплатой за конверсии
$stop_client_tier = (
SELECT
  eventdate
, curr_client_tier
, CAST(COUNT_IF(all_stop) AS Int64) AS stopped_clients
FROM (
  SELECT
    eventdate
  , SOME(curr_client_tier) AS curr_client_tier
  , MIN(is_last_day) AS all_stop
  FROM @orderday
  WHERE is_commerce
  GROUP BY client_id, eventdate
)
GROUP BY eventdate, curr_client_tier
);
$stop_client_week_tier = (
SELECT
  eventweek
, curr_client_tier
, CAST(COUNT_IF(all_stop) AS Int64) AS stopped_clients
FROM (
  SELECT
    eventweek
  , SOME(curr_client_tier) AS curr_client_tier
  , MIN(is_last_day) AS all_stop
  FROM @orderday
  WHERE is_commerce
  GROUP BY
    client_id
  , CAST(DateTime::MakeDate(DateTime::StartOfWeek(CAST(eventdate AS Date))) AS String) AS eventweek
)
GROUP BY eventweek, curr_client_tier
);
$stop_client_month_tier = (
SELECT
  eventmonth
, curr_client_tier
, CAST(COUNT_IF(all_stop) AS Int64) AS stopped_clients
FROM (
  SELECT
    eventmonth
  , MIN(is_last_day) AS all_stop
  , SOME(curr_client_tier) AS curr_client_tier
  FROM @orderday
  WHERE is_commerce
  GROUP BY
    client_id
  , CAST(DateTime::MakeDate(DateTime::StartOfMonth(CAST(eventdate AS Date))) AS String) AS eventmonth
)
GROUP BY eventmonth, curr_client_tier
);
-------------
-- агрегаты -
-------------

INSERT INTO `//home/vipplanners/dashboard_paid_actions/cube/daily_tier` WITH TRUNCATE
SELECT
  e.eventdate AS eventdate
, e.curr_client_tier AS curr_client_tier
, nvl(sc.stopped_clients, 0) AS stopped_clients
, e.active_orders AS active_orders
, e.empty_orders AS empty_active_orders
, e.profit_orders AS profit_active_orders
, nvl(no.new_orders, 0) AS new_orders
, e.active_clients AS active_clients
, nvl(nc.new_clients, 0) AS new_clients
, e.shows AS shows
, e.clicks AS clicks
, e.order_stops AS order_stops
, e.actions AS actions
, e.actions_old AS actions_old
, e.actions_extra AS actions_extra
, e.cost_rub_wo_nds_clicks AS cost_rub_wo_nds_clicks
, e.cost_rub_wo_nds_actions AS cost_rub_wo_nds_actions
, e.profit_rub_wo_nds AS profit_rub_wo_nds
, e.profit_rub_wo_nds / e.active_orders AS profit_per_active_order_rub_wo_nds
, e.profit_rub_wo_nds / e.active_clients AS profit_per_active_client_rub_wo_nds
, nvl(nc.new_direct_clients, 0) AS new_direct_clients
, nvl(nc.sm_direct_clients, 0) AS sm_direct_clients
, nvl(nc.other_direct_clients, 0) AS other_direct_clients
FROM (
  SELECT
    eventdate
  , curr_client_tier
  , COUNT(DISTINCT order_id) AS active_orders
  , COUNT(DISTINCT client_id) AS active_clients
  , SUM(shows) AS shows
  , SUM(clicks) AS clicks
  , SUM(actions) AS actions
  , SUM(actions_old) AS actions_old
  , SUM(actions_extra) AS actions_extra
  , COUNT_IF(is_last_day) AS order_stops
  , COUNT_IF(cum_profit_rub_wo_nds_day > 0) AS profit_orders
  , COUNT_IF(cum_actions = 0) AS empty_orders
  , SUM(cost_rub_wo_nds_clicks) AS cost_rub_wo_nds_clicks
  , SUM(cost_rub_wo_nds_actions) AS cost_rub_wo_nds_actions
  , SUM(profit_rub_wo_nds) AS profit_rub_wo_nds
  FROM @orderday
  WHERE is_commerce
  GROUP BY eventdate, curr_client_tier
) AS e
LEFT JOIN $stop_client_tier AS sc
  ON e.eventdate = sc.eventdate
 AND e.curr_client_tier = sc.curr_client_tier
LEFT JOIN $new_client_tier AS nc
  ON e.eventdate = nc.eventdate
 AND e.curr_client_tier = nc.curr_client_tier
LEFT JOIN $new_order_tier AS no
  ON e.eventdate = no.eventdate
 AND e.curr_client_tier = no.curr_client_tier
ORDER BY eventdate
;

$clientstat = (
SELECT
  client_id
, SOME(curr_client_tier) AS curr_client_tier
, eventdate
FROM @orderday
WHERE shows > 0
  AND is_commerce
GROUP BY
  client_id
, eventdate
);


INSERT INTO `//home/vipplanners/dashboard_paid_actions/cube/daily_tier_clients` WITH TRUNCATE
SELECT
  eventdate
, curr_client_tier
, active_clients
, all_clients
, all_clients - active_clients AS stop_clients
FROM (
  SELECT
    eventdate
  , curr_client_tier
  , COUNT(DISTINCT client_id) AS active_clients
  , MAX(clients) AS all_clients
  FROM (
    SELECT
      client_id
    , curr_client_tier
    , eventdate
    , ListLength(AGGREGATE_LIST_DISTINCT(client_id, 10000000) OVER client_w) AS clients
    FROM $clientstat
    WINDOW client_w AS (PARTITION BY curr_client_tier ORDER BY eventdate)
  )
  GROUP BY eventdate, curr_client_tier
)
ORDER BY eventdate
;


INSERT INTO `//home/vipplanners/dashboard_paid_actions/cube/weekly_tier` WITH TRUNCATE
SELECT
  e.eventweek AS eventweek
, e.curr_client_tier AS curr_client_tier
, nvl(sc.stopped_clients, 0) AS stopped_clients
, e.active_orders AS active_orders
, nvl(LAG(e.active_orders) OVER total_w, 0) AS active_orders_prev
, nvl(no.new_orders, 0) AS new_orders
, nvl(LAG(no.new_orders) OVER total_w, 0) AS new_orders_prev
, e.active_clients AS active_clients
, nvl(LAG(e.active_clients) OVER total_w, 0) AS active_clients_prev
, nvl(nc.new_clients, 0) AS new_clients
, nvl(LAG(nc.new_clients) OVER total_w, 0) AS new_clients_prev
, e.shows AS shows
, e.clicks AS clicks
, e.order_stops AS order_stops
, e.actions AS actions
, e.actions_old AS actions_old
, e.actions_extra AS actions_extra
, e.cost_rub_wo_nds_clicks AS cost_rub_wo_nds_clicks
, e.cost_rub_wo_nds_actions AS cost_rub_wo_nds_actions
, nvl(LAG(e.cost_rub_wo_nds_actions) OVER total_w, 0) AS cost_rub_wo_nds_actions_prev
, e.profit_rub_wo_nds AS profit_rub_wo_nds
, nvl(LAG(e.profit_rub_wo_nds) OVER total_w, 0) AS profit_rub_wo_nds_prev
, e.profit_rub_wo_nds / e.active_orders AS profit_per_active_order_rub_wo_nds
, e.profit_rub_wo_nds / e.active_clients AS profit_per_active_client_rub_wo_nds
, nvl(nc.new_direct_clients, 0) AS new_direct_clients
, nvl(nc.sm_direct_clients, 0) AS sm_direct_clients
, nvl(nc.other_direct_clients, 0) AS other_direct_clients
, LEAD(e.eventweek) OVER total_w IS NOT NULL AS has_next_period
FROM (
  SELECT
    eventweek
  , curr_client_tier
  , COUNT(DISTINCT order_id) AS active_orders
  , COUNT(DISTINCT client_id) AS active_clients
  , SUM(shows) AS shows
  , SUM(clicks) AS clicks
  , COUNT_IF(is_last_day) AS order_stops
  , SUM(actions) AS actions
  , NVL(SUM(actions_old), 0) AS actions_old
  , SUM(actions_extra) AS actions_extra
  , SUM(cost_rub_wo_nds_clicks) AS cost_rub_wo_nds_clicks
  , SUM(cost_rub_wo_nds_actions) AS cost_rub_wo_nds_actions
  , SUM(profit_rub_wo_nds) AS profit_rub_wo_nds
  FROM @orderday
  WHERE is_commerce
  GROUP BY
    CAST(DateTime::MakeDate(DateTime::StartOfWeek(CAST(eventdate AS Date))) AS String) AS eventweek
  , curr_client_tier
) AS e
LEFT JOIN $stop_client_week_tier AS sc
  ON e.eventweek = sc.eventweek
 AND e.curr_client_tier = sc.curr_client_tier
LEFT JOIN $new_client_week_tier AS nc
  ON e.eventweek = nc.eventweek
 AND e.curr_client_tier = nc.curr_client_tier
LEFT JOIN $new_order_week_tier AS no
  ON e.eventweek = no.eventweek
 AND e.curr_client_tier = no.curr_client_tier
WINDOW total_w AS (
  PARTITION BY e.curr_client_tier
  ORDER BY e.eventweek
)
ORDER BY eventweek
;

INSERT INTO `//home/vipplanners/dashboard_paid_actions/cube/weekly_tier_clients` WITH TRUNCATE
SELECT
  eventweek
, curr_client_tier
, active_clients
, all_clients
, all_clients - active_clients AS stop_clients
FROM (
  SELECT
    eventweek
  , curr_client_tier
  , COUNT(DISTINCT client_id) AS active_clients
  , MAX(clients) AS all_clients
  FROM (
    SELECT
      client_id
    , curr_client_tier
    , eventdate
    , ListLength(AGGREGATE_LIST_DISTINCT(client_id, 10000000) OVER client_w) AS clients
    FROM $clientstat
    WINDOW client_w AS (PARTITION BY curr_client_tier ORDER BY eventdate)
  )
  GROUP BY
    CAST(DateTime::MakeDate(Datetime::StartOfWeek(CAST(eventdate AS Date))) AS String) AS eventweek
  , curr_client_tier
)
ORDER BY eventweek
;


INSERT INTO `//home/vipplanners/dashboard_paid_actions/cube/monthly_tier` WITH TRUNCATE
SELECT
  e.eventmonth AS eventmonth
, e.curr_client_tier AS curr_client_tier
, nvl(sc.stopped_clients, 0) AS stopped_clients
, e.active_orders AS active_orders
, nvl(no.new_orders, 0) AS new_orders
, e.active_clients AS active_clients
, nvl(nc.new_clients, 0) AS new_clients
, e.shows AS shows
, e.clicks AS clicks
, e.order_stops AS order_stops
, e.actions AS actions
, e.actions_old AS actions_old
, e.actions_extra AS actions_extra
, e.cost_rub_wo_nds_clicks AS cost_rub_wo_nds_clicks
, e.cost_rub_wo_nds_actions AS cost_rub_wo_nds_actions
, e.profit_rub_wo_nds AS profit_rub_wo_nds
, e.profit_rub_wo_nds / e.active_orders AS profit_per_active_order_rub_wo_nds
, e.profit_rub_wo_nds / e.active_clients AS profit_per_active_client_rub_wo_nds
, nvl(nc.new_direct_clients, 0) AS new_direct_clients
, nvl(nc.sm_direct_clients, 0) AS sm_direct_clients
, nvl(nc.other_direct_clients, 0) AS other_direct_clients
FROM (
  SELECT
    eventmonth
  , curr_client_tier
  , COUNT(DISTINCT order_id) AS active_orders
  , COUNT(DISTINCT client_id) AS active_clients
  , SUM(shows) AS shows
  , SUM(clicks) AS clicks
  , COUNT_IF(is_last_day) AS order_stops
  , SUM(actions) AS actions
  , SUM(actions_old) AS actions_old
  , SUM(actions_extra) AS actions_extra
  , SUM(cost_rub_wo_nds_clicks) AS cost_rub_wo_nds_clicks
  , SUM(cost_rub_wo_nds_actions) AS cost_rub_wo_nds_actions
  , SUM(profit_rub_wo_nds) AS profit_rub_wo_nds
  FROM @orderday
  WHERE is_commerce
  GROUP BY
    CAST(DateTime::MakeDate(DateTime::StartOfMonth(CAST(eventdate AS Date))) AS String) AS eventmonth
  , curr_client_tier
) AS e
LEFT JOIN $stop_client_month_tier AS sc
  ON e.eventmonth = sc.eventmonth
 AND e.curr_client_tier = sc.curr_client_tier
LEFT JOIN $new_client_month_tier AS nc
  ON e.eventmonth = nc.eventmonth
 AND e.curr_client_tier = nc.curr_client_tier
LEFT JOIN $new_order_month_tier AS no
  ON e.eventmonth = no.eventmonth
 AND e.curr_client_tier = no.curr_client_tier
ORDER BY eventmonth
;


INSERT INTO `//home/vipplanners/dashboard_paid_actions/cube/monthly_tier_clients` WITH TRUNCATE
SELECT
  eventmonth
, curr_client_tier
, active_clients
, all_clients
, all_clients - active_clients AS stop_clients
FROM (
  SELECT
    eventmonth
  , curr_client_tier
  , COUNT(DISTINCT client_id) AS active_clients
  , MAX(clients) AS all_clients
  FROM (
    SELECT
      client_id
    , eventdate
    , curr_client_tier
    , ListLength(AGGREGATE_LIST_DISTINCT(client_id, 10000000) OVER client_w) AS clients
    FROM $clientstat
    WINDOW client_w AS (PARTITION BY curr_client_tier ORDER BY eventdate)
  )
  GROUP BY
    CAST(DateTime::MakeDate(Datetime::StartOfMonth(CAST(eventdate AS Date))) AS String) AS eventmonth
  , curr_client_tier
)
ORDER BY eventmonth
;

COMMIT;

INSERT INTO `//home/vipplanners/dashboard_paid_actions/cube/last_full_week_tier` WITH TRUNCATE
SELECT *
FROM (
  SELECT MAX_BY(TableRow(), eventweek)
  FROM `//home/vipplanners/dashboard_paid_actions/cube/weekly_tier`
  WHERE has_next_period  -- значит точно полный
  GROUP BY curr_client_tier
)
FLATTEN COLUMNS
;
