# DataProductSpec — ym.stats_orders: ПЕРВЫЙ scope-итерируемый спек. Кампании fbs/fby
# из конфига (scopes): свой campaign_id в path и mp_id 6/8, инжектируемые в item
# (_v3_* — паритет с legacy, эти ключи живут в raw_payload).
apiVersion: specs.gwptd.io/v1alpha1
kind: DataProduct
metadata:
  name: ym.stats_orders
  generation: 1
  lifecycle: active
contract:
  version: 1.0.0

source:
  marketplaceRef: ym
  mpId: 6                          # default CollectionRun; фактический mp per row из scope
  authProfileRef: ym.partner
  originRef: ym.partner

quality:
  # F-62 / A5: compare FBY only to its own sealed runs.  9/49 = 184‰ in
  # June, so 200‰ catches the measured drop; stock 4/2 in July/August is
  # naturally depleted, hence the first separating threshold is 5 units.
  scopeHistoryGuard:
    scope: fby
    historyRuns: 3
    minHistoryItems: 10
    minCurrentPermille: 200
    minAvailableStock: 5
    stockSource: ym.stocks

scopes:
  configRef: ym.campaigns          # YANDEX_MARKET.campaigns: {fbs: id, fby: id}
  pathPlaceholder: campaign_id
  mpByKey: {fbs: 6, fby: 8}
  injectFields:
    mpField: _v3_mp_id
    keyField: _v3_campaign_model

request:
  method: POST
  path: /v2/campaigns/{campaign_id}/stats/orders
  body:
    dateFrom: {var: window.start_date}
    dateTo:   {var: window.end_date}
  window:
    days: 7
    endOffsetDays: 0

transport:
  strategy: http.page_token_query
  limit: 200
  limitParam: limit
  tokenParam: page_token
  tokenPath: "$.result.paging.nextPageToken"
  maxPages: 500

extract:
  itemsPath: "$.result.orders"
  businessKeyPaths: ["$.id"]

outputs:
  intakeByKind:
    # Поле-признак всегда отсутствует в ответе YM — все заказы идут одним
    # kind'ом order. Первый таргет пишет родительскую строку ym_stats_orders,
    # второй разворачивает массив items[] в дочернюю ym_stats_orders_items
    # с двумя вложенными разворотами: details[] → _items_details,
    # prices[] → _items_prices.  warehouse — объект, не массив, ложится
    # колонками в ту же items-таблицу с переименованием поля id.
    field: _always_order
    defaultKind: order
    targets:
      order:
        - table: ym_stats_orders
          fields:
            payload_id:       {var: payload_id}
            mp_id:            {json_path: $._v3_mp_id}        # инжектировано scope'ом (как legacy)
            campaign_model:   {json_path: $._v3_campaign_model}
            order_id:         {python_func: ym_order_id_str}
            status:           {json_path: $.status}
            substatus:        {json_path: $.substatus}
            creation_date_mp: {python_func: ym_order_creation_date}
            updated_at_mp:    {python_func: ym_order_updated_at}
            payment_type:     {json_path: $.paymentType}
            buyer_type:       {json_path: $.buyerType}
            delivery_region:  {json_path: $.deliveryRegion.name}
            delivery_type:    {json_path: $.delivery.type}
            items_count:      {python_func: ym_order_items_count}
            items_json:       {python_func: ym_order_items_json}
            delivery_json:    {python_func: ym_order_delivery_json}
        - table: ym_stats_orders_items
          upsert_keys: []
          explode:
            listField: items
            parentFields:
              mp_id: _v3_mp_id
              campaign_model: _v3_campaign_model
              order_id: id
            children:
              - table: ym_stats_orders_items_details
                upsert_keys: []
                explode:
                  listField: details
                  parentFields:
                    mp_id: mp_id
                    campaign_model: campaign_model
                    order_id: order_id
                fields:
                  payload_id: {var: payload_id}
                  mp_id: {json_path: $.mp_id}
                  campaign_model: {json_path: $.campaign_model}
                  order_id: {json_path: $.order_id}
                  itemCount: {json_path: $.itemCount}
                  itemStatus: {json_path: $.itemStatus}
                  stockType: {json_path: $.stockType}
                  updateDate: {json_path: $.updateDate}
              - table: ym_stats_orders_items_prices
                upsert_keys: []
                explode:
                  listField: prices
                  parentFields:
                    mp_id: mp_id
                    campaign_model: campaign_model
                    order_id: order_id
                fields:
                  payload_id: {var: payload_id}
                  mp_id: {json_path: $.mp_id}
                  campaign_model: {json_path: $.campaign_model}
                  order_id: {json_path: $.order_id}
                  costPerItem: {json_path: $.costPerItem}
                  total: {json_path: $.total}
                  type: {json_path: $.type}
          fields:
            payload_id: {var: payload_id}
            mp_id: {json_path: $.mp_id}
            campaign_model: {json_path: $.campaign_model}
            order_id: {json_path: $.order_id}
            bidFee: {json_path: $.bidFee}
            count: {json_path: $.count}
            marketSku: {json_path: $.marketSku}
            offerName: {json_path: $.offerName}
            shopSku: {json_path: $.shopSku}
            warehouse_id: {json_path: $.warehouse.id}
            warehouse_name: {json_path: $.warehouse.name}

        # ── Денежные потомки заказа: commissions[], payments[], subsidies[] ──
        # Заведены волной 09.08.2026 и до 12.08 стояли ПУСТЫМИ: таблицы были, а
        # разворот в них не объявлен. Замер 11.08 по последним 3000 ответам —
        # непустые commissions у 1291 заказа, payments у 1362, subsidies у 1361,
        # около 45%. Это деньги: комиссия площадки, платежи покупателя, субсидии.
        #
        # Связь с заказом — через order_id (varchar), как у соседнего
        # ym_stats_orders_items. Колонки parent_id и item_index достались тем же
        # трём таблицам от волны DDL; parent_id у соседа пуст во ВСЕХ 833
        # строках, поэтому не объявляем и здесь. item_index заполняем: у заказа
        # бывает несколько комиссий, и при равных значениях строки иначе
        # неразличимы.
        - table: ym_stats_orders_commissions
          upsert_keys: []
          explode:
            listField: commissions
            indexField: item_index
            parentFields:
              mp_id: _v3_mp_id
              campaign_model: _v3_campaign_model
              order_id: id
          fields:
            payload_id: {var: payload_id}
            mp_id: {json_path: $.mp_id}
            campaign_model: {json_path: $.campaign_model}
            order_id: {json_path: $.order_id}
            item_index: {json_path: $.item_index}
            type: {json_path: $.type}
            actual: {json_path: $.actual}

        - table: ym_stats_orders_payments
          upsert_keys: []
          explode:
            listField: payments
            indexField: item_index
            parentFields:
              mp_id: _v3_mp_id
              campaign_model: _v3_campaign_model
              order_id: id
          fields:
            payload_id: {var: payload_id}
            mp_id: {json_path: $.mp_id}
            campaign_model: {json_path: $.campaign_model}
            order_id: {json_path: $.order_id}
            item_index: {json_path: $.item_index}
            date: {json_path: $.date}
            source: {json_path: $.source}
            total: {json_path: $.total}
            type: {json_path: $.type}

        - table: ym_stats_orders_subsidies
          upsert_keys: []
          explode:
            listField: subsidies
            indexField: item_index
            parentFields:
              mp_id: _v3_mp_id
              campaign_model: _v3_campaign_model
              order_id: id
          fields:
            payload_id: {var: payload_id}
            mp_id: {json_path: $.mp_id}
            campaign_model: {json_path: $.campaign_model}
            order_id: {json_path: $.order_id}
            item_index: {json_path: $.item_index}
            type: {json_path: $.type}
            amount: {json_path: $.amount}
            operationType: {json_path: $.operationType}

