USE hahn;
/* OPERANALYTICS-1168
История настроек стратегий
*/
PRAGMA yt.ParallelOperationsLimit = "7";  -- дефолтный лимит на пользователя 10
PRAGMA yt.DefaultOperationWeight = "0.5"; -- дефолт 1.0
PRAGMA yt.PoolTrees = "physical";
PRAGMA yt.TentativePoolTrees = "cloud";
USE hahn;

$FINISH = CAST(CurrentUTCDate() - Interval("P1D") AS String);
$START = CAST(CurrentUTCDate() - Interval("P365D") AS String);

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

-- Создание аккаунта в Директе
$direct_creation_date = (
SELECT 
  order_id
, SOME(c.ClientID) AS client_id
, SOME(oi.ExportID) AS direct_camapign_id
, MIN(DateTime::MakeDate($parse_datetime(create_date))) AS client_create_date
FROM hahn.`home/direct/db/clients` AS c
JOIN `//home/yabs/dict/CaesarOrderInfo` AS oi
  ON c.ClientID = oi.ClientID
WHERE oi.EngineID = 7  -- Директ
  AND oi.OrderType = 1  -- Коммерция
  AND c.ClientID > 0
GROUP BY oi.OrderID AS order_id
);

$order_strategy_log_pre = (
SELECT
  order_id
, cube_date
, CAST(CAST(cube_date AS Date) - Interval("P1D") AS String) AS cube_date_prev
-- параметры стратегии
, nvl(SOME(campaign_strategy_name), "unknown") AS campaign_strategy_name
, nvl(SOME(campaign_strategy_name_original), "unk") AS campaign_strategy_name_original
, SOME(campaign_is_auto_strategy) AS campaign_is_auto_strategy
, SOME(campaign_autobudget_goal_id) AS campaign_autobudget_goal_id
, SOME(client_wallet_is_day_budget_capped) AS client_wallet_is_day_budget_capped
, SOME(campaign_day_budget_sum) AS campaign_day_budget_sum
-- модель оплаты
, nvl(SOME(campaign_pay_for_conversion), False) AS campaign_pay_for_conversion
-- статусы
, SOME(campaign_is_status_archived) AS campaign_is_status_archived
, SOME(campaign_is_status_active) AS campaign_is_status_active
, SOME(campaign_is_status_show) AS campaign_is_status_show
FROM RANGE(`//statbox/cube/daily/comdep/banners/v1`, $START, $FINISH)
WHERE order_id > 0
  AND client_id > 0
GROUP BY
  order_id
, TableName() AS cube_date
);

$order_strategy_log = (
SELECT
  c.*
-- параметры стратегии предыдущего дня
, p.campaign_strategy_name AS campaign_strategy_name_prev
, p.campaign_strategy_name_original AS campaign_strategy_name_original_prev
, p.campaign_is_auto_strategy AS campaign_is_auto_strategy_prev
, p.campaign_autobudget_goal_id AS campaign_autobudget_goal_id_prev
, p.client_wallet_is_day_budget_capped AS client_wallet_is_day_budget_capped_prev
, p.campaign_day_budget_sum AS campaign_day_budget_sum_prev
-- модель оплаты
, p.campaign_pay_for_conversion AS campaign_pay_for_conversion_prev
-- статусы предыдущего дня
, p.campaign_is_status_archived AS campaign_is_status_archived_prev
, p.campaign_is_status_active AS campaign_is_status_active_prev
, p.campaign_is_status_show AS campaign_is_status_show_prev
FROM $order_strategy_log_pre AS c
JOIN $order_strategy_log_pre AS p
  ON c.order_id = p.order_id
  AND c.cube_date_prev = p.cube_date
);


$client_campaign_strategy_usage = (
SELECT
  client_id
, MAX(ListHas(ListMap(String::SplitToList(opts, ','), String::Strip), "is_simplified_strategy_view_enabled")) AS has_simplified_strategy_use
, NOT MIN(ListHas(ListMap(String::SplitToList(opts, ','), String::Strip), "is_simplified_strategy_view_enabled")) AS has_pro_strategy_use
FROM `//home/direct/db/campaigns`
WHERE ClientID > 0
GROUP BY ClientID AS client_id
);

$client_default_strategy_view = (
SELECT
  ClientID AS client_id
, ListHas(ListMap(String::SplitToList(client_flags, ','), String::Strip), "is_pro_strategy_view_enabled") AS is_pro_strategy_view_enabled
FROM `//home/direct/db/clients`
WHERE ClientID > 0
);

INSERT INTO `//home/vipplanners/dashboard_strategy_balance/daily/order_strategy_log` WITH TRUNCATE
SELECT
  l.*
, MAX_OF(0, DateTime::ToDays(CAST(l.cube_date AS Date) - c.client_create_date)) AS client_age_days
, c.client_id AS client_id
, c.direct_camapign_id AS direct_camapign_id
-- атрибуты для фильтрации на дашборде
, NVL(crm.curr_counterparty_reporting_tier.name, "unkown") AS curr_client_tier
, NVL(crm.client_type, "unkown") AS client_type
, NVL(crm.client_first_date, "1970-01-01") AS client_first_day
, NVL(crm.curr_counterparty_industry.industry, "unkown") AS curr_industry
-- опции на клиенте
, NVL(cu.has_pro_strategy_use, False) AS has_pro_strategy_use
, NVL(cu.has_simplified_strategy_use, True) AS has_simplified_strategy_use  -- дефолт True
, NVL(cv.is_pro_strategy_view_enabled, False) AS is_pro_strategy_view_enabled
FROM $order_strategy_log AS l
JOIN $direct_creation_date AS c
  ON l.order_id = c.order_id
JOIN `//home/comdep-analytics/public/client_tiers/fact/latest_v2` AS crm
  ON c.client_id = crm.client_id
LEFT JOIN $client_campaign_strategy_usage AS cu
  ON c.client_id = cu.client_id
LEFT JOIN $client_default_strategy_view AS cv
  ON c.client_id = cv.client_id
ORDER BY
  cube_date
, client_id
;
