-- OPERANALYTICS-46
-- Доработать факторы недельный и дневной бюджет для загрузки в CRM
PRAGMA yt.DefaultCluster = "senecavla";
USE senecavla;

$daily_recs = (
SELECT 
  client_id
, cid
, direct_export_timestamp
, Yson::LookupDouble(data, "currentDailyBudget") AS current_daily_budget
, Yson::LookupDouble(data, "recommendedDailyBudget") AS recommended_daily_budget
FROM (
  SELECT client_id, cid, Yson::ParseJson(data) as data, `timestamp` AS direct_export_timestamp
    FROM `//home/direct/recommendations/current` 
    WHERE type = 1
)
);

$weekly_recs = (
SELECT 
  client_id
, cid
, Yson::LookupDouble(data, "currentWeeklyBudget") AS current_weekly_budget
, Yson::LookupDouble(data, "recommendedWeeklyBudget") AS recommended_weekly_budget
, direct_export_timestamp
FROM (
  SELECT client_id, cid, Yson::ParseJson(data) as data, `timestamp` AS direct_export_timestamp
    FROM `//home/direct/recommendations/current` 
    WHERE type = 25
)
);

INSERT INTO `//home/operanalytics/share/recommendations/budget_factors` WITH TRUNCATE
SELECT
  nvl(d.client_id, w.client_id) AS client_id
, nvl(d.cid, w.cid) AS cid
, d.direct_export_timestamp AS direct_export_timestamp_daily_budget
, w.direct_export_timestamp AS direct_export_timestamp_weekly_budget
, d.current_daily_budget AS current_daily_budget
, d.recommended_daily_budget AS recommended_daily_budget
, w.current_weekly_budget AS current_weekly_budget
, w.recommended_weekly_budget AS recommended_weekly_budget
FROM $daily_recs AS d
FULL JOIN $weekly_recs AS w
  ON d.cid = w.cid
ORDER BY client_id, cid
;
