USE chyt.hahn/ba_cpa;

DROP TABLE IF EXISTS `{table_path}`;
CREATE TABLE `{table_path}` ENGINE = YtTable() AS
SELECT
    `Date`,
    CampaignName,
    Place,
    Device,
    BannerType,
    TargetingType,
    SUM((sign * actioncost) * 30 / 1000000 / 1.18) AS DirectCost
FROM
    (
        SELECT
            eventtime,
            orderid,
            targettype,
            devicetype,
            hitdevicetype,
            options,
            producttype,
            selecttype,
            contexttype,
            simdistance,
            sign,
            actioncost
        FROM concatYtTablesRange('//home/logfeller/logs/bs-action-checked-log/stream/1d', '{from_date_max}', '{to_date_next}')
        WHERE
            NOT match(options, 'mobile-app')
            AND {date_func}(toDate(eventtime)) >= '{from_date}' AND {date_func}(toDate(eventtime)) < '{to_date}'
            AND (match(autobudgetoptions, '(^|,)paid-actions(,|$)') AND isgoodconversion)
            {clids_condition}
            {cids_condition}
            {domains_condition}
            {regions_condition}
    ) AS o
{campaigns_table}
GROUP BY
    toString({date_func}(toDate(eventtime))) AS `Date`,
    {campaign_field} AS CampaignName,
    if(targettype = 3, 'Networks', 'Search') AS Place,
    multiIf(
      toDate(eventtime) < '2017-10-01' AND devicetype < 4, 'Mobile',
      toDate(eventtime) < '2017-10-01', 'Desktop',
      hitdevicetype < 4, 'Mobile',
      'Desktop'
    ) AS Device,
    multiIf(
        match(options, 'performance'), 'smart_banner',
        producttype = 'video-creative', 'video_ad',
        producttype IN ('auto-video-direct', 'video-motion'), 'video_extensions',
        producttype IN ('media-image', 'media-creative') AND Place = 'Search', 'search_banner',
        producttype IN ('media-image', 'media-creative') AND Place = 'Networks', 'image_ad',
        match(options, 'dynamic-banner'), 'dynamic_banner',
        'text_image_ad'
    ) AS BannerType,
    multiIf(
        selecttype IN (27, 45, 67) OR contexttype = 2, 'retargeting',
        contexttype = 3 AND simdistance in (8, 44, 45, 48, 308, 341, 342, 343, 344, 345, 408, 508, 908, 941, 942, 943, 944, 945, 1108, 1408, 1508, 1608, 1708, 1808, 1908, 2008), 'synonym',
        contexttype = 3, 'broadmatch',
        match(options, 'navig-source') OR match(options, 'navig-list-match'), 'navig',
        Place = 'Search', 'phrase_other',
        'phrase'
    ) AS TargetingType
