/* Показатели частных специалистов

Тикет: OKK-2930
*/

USE hahn;

PRAGMA yt.QueryCacheMode = "normal";
PRAGMA yt.DefaultMaxJobFails = "15";
PRAGMA yt.DataSizePerJob = "10G";
PRAGMA yt.Owners = "n-bar";


$YT_DIRECT_FL_PATH = "//home/direct/export/freelancers/freelancers_projects";

-- BSDEV-70569
$YT_BS_SCORE_FOLDER = "//home/bs/freelancers/direct/export";

-- PLANNERSDEVTA-97
-- QA = Query Analysis
$YT_QA_SRC_PATH = "//home/vipplanners/ta_report/30d/search_queries.data";
$YT_QA_INFO_PATH = "//home/vipplanners/ta_report/30d/search_queries.info";

-- Результат OKK-2930
$YT_SPECIALIST_RESULT_FOLDER = "//home/vipplanners/freelance_info/specialist";
$YT_CLIENT_RESULT_FOLDER = "//home/vipplanners/freelance_info/client";
$YT_CAMPAIGN_RESULT_FOLDER = "//home/vipplanners/freelance_info/campaign";

$INFO = (
    SELECT SOME(TableRow())
    FROM $YT_QA_INFO_PATH
);
$BEGIN = $INFO.DateBegin;
$BEGIN_DT = DateTime::TimestampFromStringFormat($BEGIN, "%F");
$FINISH = $INFO.DateFinish;
$FINISH_DT = DateTime::TimestampFromStringFormat($FINISH, "%F") + Interval("P1DT");

-- до 2018-12-02 данные не актуальны совсем
DISCARD SELECT Ensure(
  True,
  $FINISH_DT >= Date("2018-12-02"),
  "Неверная дата в $YT_BS_SCORE_PATH"
);
$YT_BS_SCORE_PATH = $YT_BS_SCORE_FOLDER || '/' || $FINISH;
$YT_SPECIALILST_RESULT_PATH = $YT_SPECIALIST_RESULT_FOLDER || '/' || $FINISH;
$YT_CLIENT_RESULT_PATH = $YT_CLIENT_RESULT_FOLDER || '/' || $FINISH;
$YT_CAMPAIGN_RESULT_PATH = $YT_CAMPAIGN_RESULT_FOLDER || '/' || $FINISH;

-- Справочник специалистов и клиентов
-- только открытые сотрудничества
$OPEN_PROJECT = (
SELECT 
  ClientID
, FLClientID
, freelancer_name AS FLName
FROM (
    SELECT SOME(TableRow())
    FROM $YT_DIRECT_FL_PATH
    WHERE
    -- проект актуален, специалист сотрудничает с клиентом
      finish_date IS NULL
    GROUP BY
      customer_client_id AS ClientID
    , freelancer_client_id AS FLClientID
)
FLATTEN COLUMNS
);

$ACTIVE_FL = (
SELECT DISTINCT 
  FLClientID
, FLName
FROM $OPEN_PROJECT
);

$CAMPAIGN_GOOD_SHOWS = (
SELECT
  QAClientID
, QACampaignID
, FLClientID
, SOME(FLName) AS FLName
, SUM(Shows) AS QAShows
, SUM(Clicks) AS QAClicks
, SUM(CostUnit) AS QACostUnit
, SUM(Shows * DSSMScore) AS QAPrGoodShows
FROM $YT_QA_SRC_PATH AS d
JOIN $OPEN_PROJECT AS op
  USING (ClientID)
GROUP BY 
  d.ClientID AS QAClientID
, d.CampaignID AS QACampaignID
, op.FLClientID AS FLClientID
);

INSERT INTO $YT_CAMPAIGN_RESULT_PATH WITH TRUNCATE 
SELECT 
  QAClientID
, QACampaignID
, FLClientID
, FLName
, QAShows
, QAClicks
, QACostUnit
, QAPrGoodShows
FROM $CAMPAIGN_GOOD_SHOWS
ORDER BY QAClientID, QACampaignID
;

$CLIENT_GOOD_SHOWS = (
SELECT
  QAClientID
, FLClientID
, SOME(FLName) AS FLName
, SUM(QAShows) AS QAShows
, SUM(QAClicks) AS QAClicks
, SUM(QACostUnit) AS QACostUnit
, SUM(QAPrGoodShows) AS QAPrGoodShows
FROM $CAMPAIGN_GOOD_SHOWS
GROUP BY 
  QAClientID
, FLClientID
);

INSERT INTO $YT_CLIENT_RESULT_PATH WITH TRUNCATE 
SELECT 
  QAClientID
, FLClientID
, FLName
, QAShows
, QAClicks
, QACostUnit
, QAPrGoodShows
FROM $CLIENT_GOOD_SHOWS
ORDER BY FLClientID, QAClientID
;

$CA_RANK = (
SELECT 
  FLClientID
, FLName
, QATopClientCost
, QAClientCount
, QAClientCostUnit
, QAShows
, QAClicks
, QAPrGoodShows / QAShows AS QAPrGoodShowsShare
, ROW_NUMBER() OVER good_shows_w AS QAPrGoodShowsRank
FROM (
  SELECT
    FLClientID
  , SOME(FLName) AS FLName
  , SUM(QAShows) AS QAShows
  , SUM(QAClicks) AS QAClicks
  , SUM(QACostUnit) AS QAClientCostUnit
  , SUM(QAPrGoodShows) AS QAPrGoodShows
  , ToDict(
    ListTake(ListSortDesc(LIST(AsTuple(QAClientID, QACostUnit)), ($x)-> {RETURN $x.1}), 10)
  ) AS QATopClientCost
  , COUNT(QAClientID) AS QAClientCount
  FROM $CLIENT_GOOD_SHOWS
  GROUP BY FLClientID
)
WINDOW 
  good_shows_w AS (ORDER BY QAPrGoodShows / QAShows DESC)
);

-- с актуальным скором и рангом от ОКР
$ADD_BS_SCORE = (
SELECT
  FLClientID
, FLName
, QATopClientCost
, QAShows
, QAClicks
, QAClientCostUnit
, QAClientCount
, QAPrGoodShowsShare
, QAPrGoodShowsRank
, Yson::ConvertToDoubleDict(bs.ratings){bs.production_freelancer_rating} AS BSFLScore
, bs.freelancer_rank AS BSFLRank
FROM $CA_RANK AS ca
LEFT JOIN $YT_BS_SCORE_PATH AS bs
  ON ca.FLClientID = bs.client_id
);

INSERT INTO $YT_SPECIALILST_RESULT_PATH WITH TRUNCATE 
SELECT 
  FLClientID
, FLName
, QAPrGoodShowsRank
, BSFLRank
, QAPrGoodShowsShare
, BSFLScore
, QAShows
, QAClicks
, QAClientCostUnit
, QAClientCount
, QATopClientCost
FROM $ADD_BS_SCORE
;
