-- OPERANALYTICS-264
-- График помесячных откруток заблокированных клиентов
USE hahn;

PRAGMA yson.DisableStrict;

$format = DateTime::Format("%Y-%m-%d");
$datetime_parse = DateTime::Parse("%Y-%m-%d %H:%M:%S");

--папка с таблицами логов
$LOG_TABLE = "//home/direct/logs/ppclog_cmd";

$old_format = (
SELECT
  DateTime::MakeDatetime($datetime_parse(MAX(Yson::ConvertToString(log_time)))) AS date_of_block
, user_uid
FROM RANGE($LOG_TABLE, `2017-01-01`, `2017-08-31`)
WHERE (
      Yson::ConvertToString(cmd) == "blockUserSpam"
  AND (Yson::ConvertToString(Yson::Parse(_other["param"])["action"]) == "block")
  ) OR (Yson::ConvertToString(cmd) == "_block_user")
GROUP BY
  Yson::ConvertToInt64(Yson::Parse(_other["cluid"])[0]) AS user_uid
);

$new_format = (
SELECT
  DateTime::MakeDatetime($datetime_parse(MAX(log_time))) AS date_of_block
, user_uid
FROM RANGE($LOG_TABLE, `2017-09-01`)
WHERE (cmd == "blockUserSpam"
  AND Yson::ConvertToString (param.action) == "block"
) OR cmd == "_block_user"
GROUP BY
  Yson::ConvertToInt64(cluid[0]) AS user_uid
);

$blocked_log_table = (
SELECT *
FROM $old_format
UNION ALL
SELECT *
FROM $new_format
);

INSERT INTO @client_blocked WITH TRUNCATE
SELECT
  ub.date_of_block AS date_of_block
, ui.ClientID AS client_id
FROM $blocked_log_table AS ub
LEFT JOIN `//home/direct/db/users` AS ui
  ON ub.user_uid == ui.uid
; COMMIT;

$client_stat = (
SELECT
  client_id
, date_of_stat
-- по состоянию на 2020-01-15, внутри системы НДС всегда 18%
, nvl(SUM(c.Cost) / 1e6 * 30 / 1.18, 0.00) AS cost_rub_wo_nds
FROM `//home/yabs/stat/OrderStatDay` AS c
JOIN (
  SELECT OrderID, ClientID
  FROM `//home/yabs/dict/path_to_dict_order_info_table`
  WHERE EngineID == 7  -- Заказы из Директа
) AS o
  ON c.OrderID == o.OrderID
GROUP BY
  o.ClientID AS client_id
, DateTIme::MakeDatetime(DateTime::FromSeconds(Cast(c.UpdateTime + 3600 * 3 AS Uint32))) AS date_of_stat
);

-- список заблокированных клиентов со статистикой и датой блокировки
INSERT INTO @client_blocked_stat WITH TRUNCATE
SELECT
  $format(date_of_block) AS date_of_block
, client_id
, nvl(SUM(cs.cost_rub_wo_nds), 0) AS LTV_rub_wo_nds
, nvl(SUM_IF(cs.cost_rub_wo_nds, (cb.date_of_block - cs.date_of_stat) <= Interval("P30D")), 0) AS LTV30_rub_wo_nds
, nvl(SUM_IF(cs.cost_rub_wo_nds, (cb.date_of_block - cs.date_of_stat) <= Interval("P90D")), 0) AS LTV90_rub_wo_nds
, MIN(cs.date_of_stat) AS date_of_start
, date_of_block - MIN(cs.date_of_stat) AS lifetime_to_block
FROM $client_stat AS cs
JOIN @client_blocked AS cb
  ON cs.client_id == cb.client_id
WHERE cs.date_of_stat <= cb.date_of_block
GROUP BY
  cb.date_of_block AS date_of_block
, cs.client_id AS client_id
; COMMIT;


$client_id_prepared = (
SELECT
  lifetime_to_block
, LTV_rub_wo_nds
, LTV30_rub_wo_nds
, LTV90_rub_wo_nds
, Datetime::ToDays(lifetime_to_block) AS days_to_block
, Datetime::GetYear(CAST(date_of_block AS Date)) AS year_of_block
, Datetime::GetMonth(CAST(date_of_block AS Date)) AS month_of_block
FROM @client_blocked_stat
);

$dummy_date = DateTime::Split(Date("1970-01-01"));

INSERT INTO `//home/vipplanners/dashboard_blocked_client_id/stat_blocked` WITH TRUNCATE
SELECT
  year_of_block
, month_of_block
, DateTime::MakeDate(DateTime::Update($dummy_date, year_of_block, month_of_block, 1)) AS date_of_block
, LEAD(TableRow()) OVER year_month_w IS NOT NULL AS is_full_month
, med_days_to_block
, avg_days_to_block
, LTV30_rub_wo_nds
, LTV90_rub_wo_nds
, LTV_rub_wo_nds
, blocked_total
, blocked_active
, blocked_0d_7d
, blocked_7d_30d
, blocked_30d_90d
, blocked_90d_inf
, blocked_0k_10k_rub_wo_nds
, blocked_10k_30k_rub_wo_nds
, blocked_30k_100k_rub_wo_nds
, blocked_100k_inf_rub_wo_nds
FROM (
  SELECT
    year_of_block
  , month_of_block
  , MEDIAN(days_to_block) AS med_days_to_block
  , AVG(days_to_block) AS avg_days_to_block
  , SUM(LTV30_rub_wo_nds) AS LTV30_rub_wo_nds
  , SUM(LTV90_rub_wo_nds) AS LTV90_rub_wo_nds
  , SUM(LTV_rub_wo_nds) AS LTV_rub_wo_nds
  , COUNT(*) AS blocked_total
  , COUNT_IF(LTV30_rub_wo_nds > 0) AS blocked_active
  , COUNT_IF(lifetime_to_block <= Interval("P7D")) AS blocked_0d_7d
  , COUNT_IF(lifetime_to_block <= Interval("P30D") AND lifetime_to_block > Interval("P7D")) AS blocked_7d_30d
  , COUNT_IF(lifetime_to_block <= Interval("P90D") AND lifetime_to_block > Interval("P30D")) AS blocked_30d_90d
  , COUNT_IF(lifetime_to_block > Interval("P90D")) AS blocked_90d_inf
  , COUNT_IF(LTV30_rub_wo_nds <= 1e4) AS blocked_0k_10k_rub_wo_nds
  , COUNT_IF(LTV30_rub_wo_nds > 1e4 AND LTV30_rub_wo_nds <= 3e4) AS blocked_10k_30k_rub_wo_nds
  , COUNT_IF(LTV30_rub_wo_nds > 3e4 AND LTV30_rub_wo_nds <= 1e5) AS blocked_30k_100k_rub_wo_nds
  , COUNT_IF(LTV30_rub_wo_nds > 1e5) AS blocked_100k_inf_rub_wo_nds
  FROM $client_id_prepared
  GROUP BY
    month_of_block
  , year_of_block
)
WINDOW year_month_w AS (
  ORDER BY year_of_block, month_of_block
)
ORDER BY date_of_block
;
