USE hahn;

INSERT INTO @page WITH TRUNCATE
SELECT
  PageID
, SOME(Name) AS Name
FROM `home/yabs/dict/Page`
GROUP BY PageID
;

INSERT INTO @chevent_agg_1 WITH TRUNCATE
SELECT
  pageid
, width
, height
, smart_type
, eventdate
, orderid
, SUM(e.shows_parent) ?? 0 AS shows_parent
, SUM(e.shows_child) ?? 0 AS shows_child
, SUM(e.clicks) ?? 0 AS clicks
, SUM(e.cost_rub_wo_nds) ?? 0 AS cost_rub_wo_nds
FROM RANGE(`//home/vipplanners/dashboard_smartbanners/daily_v2/chevent`) AS e
GROUP BY
  e.pageid AS pageid
, e.width AS width
, e.height AS height
, e.smart_type AS smart_type
, e.eventdate AS eventdate
, e.orderid AS orderid
; COMMIT;

INSERT INTO @chevent_agg_2 WITH TRUNCATE
SELECT
  pageid
, width
, height
, smart_type
, eventdate
, client_id
, SUM(e.shows_parent) ?? 0 AS shows_parent
, SUM(e.shows_child) ?? 0 AS shows_child
, SUM(e.clicks) ?? 0 AS clicks
, SUM(e.cost_rub_wo_nds) ?? 0 AS cost_rub_wo_nds
FROM @chevent_agg_1 AS e
JOIN `//home/yabs/dict/CaesarOrderInfo` AS oi
  ON e.orderid = oi.OrderID
GROUP BY
  e.pageid AS pageid
, e.width AS width
, e.height AS height
, e.smart_type AS smart_type
, e.eventdate AS eventdate
, oi.ClientID AS client_id
; COMMIT;

INSERT INTO `//home/vipplanners/dashboard_smartbanners/cube/smarttype_page_wh_daily` WITH TRUNCATE
SELECT
  e.*
, p.Name AS pagename
, nvl(crm.curr_client_main_domain, "не определено") AS curr_client_main_domain
, nvl(crm.curr_counterparty_reporting_tier.name, "не определено") AS curr_client_tier
, nvl(crm.client_login, "не определено") AS client_login
FROM @chevent_agg_2 AS e
JOIN @page AS p
  ON e.pageid == p.PageID
JOIN `//home/comdep-analytics/public/client_tiers/fact/latest_v2` AS crm
  ON e.client_id = crm.client_id
ORDER BY
  eventdate
, client_id
, pageid
, smart_type
, width
, height
;


INSERT INTO `//home/vipplanners/dashboard_smartbanners/cube/client_daily` WITH TRUNCATE
SELECT
  s.*
, nvl(crm.curr_client_main_domain, "не определено") AS curr_client_main_domain
, nvl(crm.curr_counterparty_reporting_tier.name, "не определено") AS curr_client_tier
, nvl(crm.client_login, "не определено") AS client_login
FROM (
  SELECT
    ClientID
  , eventdate
  , SUM(cost_rub_wo_nds) AS cost_rub_wo_nds
  FROM @chevent_agg_2
  GROUP BY
    client_id AS ClientID
  , eventdate
) AS s
JOIN `//home/comdep-analytics/public/client_tiers/fact/latest_v2` AS crm
  ON s.ClientID = crm.client_id
ORDER BY eventdate, ClientID
;