@managetunit/marketplace-manager 1.3.1 → 1.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,7 +4,9 @@
4
4
 
5
5
  - **панель «Менеджер маркетплейсов»** — KPI, динамика, товары и реклама кабинетов WB/Ozon;
6
6
  - **режим «Менеджер маркетплейсов»** — вопросы по своим кабинетам, финансовый и рекламный
7
- разборы, графики в чате;
7
+ разборы, графики в чате; пресет собран как расширение штатного набора Harness:
8
+ терминал, файлы, веб, планировщик, субагенты, workflow и офисные инструменты на месте,
9
+ сверху — инструменты продавца и справочники площадок;
8
10
  - **обычный режим Harness** — инструменты и инструкции Юнита добавляются к текущему
9
11
  агенту без замены его пресета, штатных инструментов и навыков; сохранённый
10
12
  пользовательский навык остаётся видимым;
package/client.js CHANGED
@@ -63,6 +63,8 @@ window.__ModuleLoader__.load({
63
63
  'state.auth': ['Подключите Юнит', 'Connect Unit'],
64
64
  'state.authBody': ['Войдите в Юнит, чтобы видеть продажи, прибыль и рекламу своих кабинетов.', 'Sign in to Unit to see sales, profit and advertising for your cabinets.'],
65
65
  'state.authButton': ['Войти в Юнит', 'Sign in to Unit'],
66
+ 'state.signOut': ['Выйти', 'Sign out'],
67
+ 'skus.enriching': ['Считаем выкупы, прибыль и рекламу — до минуты', 'Calculating buyouts, profit and ads — up to a minute'],
66
68
  'state.error': ['Не удалось загрузить данные', 'Could not load the data'],
67
69
  'state.errorBody': ['Попробуйте ещё раз или выберите другой период.', 'Try again or choose another period.'],
68
70
  'state.empty': ['За этот период данных нет', 'No data for this period'],
@@ -782,7 +784,7 @@ window.__ModuleLoader__.load({
782
784
  });
783
785
  }
784
786
 
785
- function ProductTable({ items, status, cabinet, retry, t, locale }) {
787
+ function ProductTable({ items, status, cabinet, retry, t, locale, enriching }) {
786
788
  const [search, setSearch] = React.useState('');
787
789
  const [sort, setSort] = React.useState({ field: 'revenue', direction: 'descending' });
788
790
  const [notice, setNotice] = React.useState('');
@@ -873,6 +875,7 @@ window.__ModuleLoader__.load({
873
875
  h('button', { type: 'button', className: 'so-button', onClick: () => setSearch('') }, t('skus.clear')),
874
876
  ),
875
877
  h('p', { className: 'so-meta so-trend-note' }, t('skus.limit').replace('{count}', items.length)),
878
+ enriching ? h('p', { className: 'so-meta so-trend-note', role: 'status' }, t('skus.enriching')) : null,
876
879
  ) : h(BlockStatus, { part: 'skus', status, retry, t }),
877
880
  );
878
881
  }
@@ -1007,6 +1010,44 @@ window.__ModuleLoader__.load({
1007
1010
  const serverSelected = React.useRef('');
1008
1011
  const locale = t('panel') === RU.panel ? 'ru-RU' : 'en-GB';
1009
1012
 
1013
+ // Прибыль, выкупы и реклама по SKU считаются на сервере долго (до минуты),
1014
+ // поэтому таблица сразу показывает заказы и выручку, а эти колонки
1015
+ // догружаются отдельным блоком и сливаются по nmId.
1016
+ const profitRequest = React.useRef({ key: '', controller: null });
1017
+ React.useEffect(() => {
1018
+ const rows = list(state.skus);
1019
+ if (state.blocks?.skus !== 'done' || rows.length === 0) return;
1020
+ const scope = state.blockScope ?? { period, accounts: selected ? [selected] : [] };
1021
+ const key = `${scope.period}|${(scope.accounts || []).join(',')}|${rows.map((row) => row.nmId).filter(Boolean).slice(0, 30).join(',')}`;
1022
+ if (profitRequest.current.key === key) return;
1023
+ profitRequest.current.controller?.abort();
1024
+ const controller = new AbortController();
1025
+ profitRequest.current = { key, controller };
1026
+ const params = new URLSearchParams({ part: 'skus_profit', period: scope.period });
1027
+ if (scope.accounts?.length) params.set('accounts', scope.accounts.join(','));
1028
+ const wanted = rows.map((row) => row.nmId).filter(Boolean).slice(0, 30);
1029
+ if (wanted.length) params.set('nmIds', wanted.join(','));
1030
+ if (wanted.length === 0) return;
1031
+ setState((current) => ({ ...current, blocks: { ...current.blocks, skus_profit: 'loading' } }));
1032
+ fetch(`/plugin/marketplace-manager/api/block?${params}`, { headers: { accept: 'application/json' }, signal: controller.signal })
1033
+ .then((response) => (response.ok ? response.json() : null))
1034
+ .then((block) => {
1035
+ if (controller.signal.aborted || !block) return;
1036
+ const byNm = new Map(list(block.rows).map((row) => [row.nmId, row]));
1037
+ setState((current) => ({
1038
+ ...current,
1039
+ blocks: { ...current.blocks, skus_profit: 'done' },
1040
+ skus: list(current.skus).map((row) => ({ ...row, ...(byNm.get(row.nmId) ?? {}) })),
1041
+ }));
1042
+ })
1043
+ .catch(() => {
1044
+ if (!controller.signal.aborted) {
1045
+ setState((current) => ({ ...current, blocks: { ...current.blocks, skus_profit: 'error' } }));
1046
+ }
1047
+ });
1048
+ return () => controller.abort();
1049
+ }, [state.blocks?.skus, state.skus, period, selected, state.blockScope]);
1050
+
1010
1051
  const fetchBlock = React.useCallback(async (part, scope, signal) => {
1011
1052
  const params = new URLSearchParams({ part, period: scope.period });
1012
1053
  if (scope.accounts.length) params.set('accounts', scope.accounts.join(','));
@@ -1222,6 +1263,15 @@ window.__ModuleLoader__.load({
1222
1263
  h('option', { value: '' }, t('accounts.all')),
1223
1264
  cabinets.map((cabinet) => h('option', { key: cabinet.id, value: cabinet.id }, cabinet.name)),
1224
1265
  ) : null,
1266
+ h('button', {
1267
+ type: 'button', className: 'so-chip so-signout', title: t('state.signOut'),
1268
+ onClick: async () => {
1269
+ try {
1270
+ await fetch('/plugin/marketplace-manager/api/logout', { method: 'POST', headers: { accept: 'application/json' } });
1271
+ } catch (_) { /* панель всё равно перечитает состояние */ }
1272
+ window.location.reload();
1273
+ },
1274
+ }, t('state.signOut')),
1225
1275
  ) : null;
1226
1276
 
1227
1277
  let body;
@@ -1252,6 +1302,7 @@ window.__ModuleLoader__.load({
1252
1302
  body = h(ProductTable, {
1253
1303
  items: list(state.skus), status: state.blocks?.skus, cabinet: blockCabinet(state.skuCabinet),
1254
1304
  retry: () => retryBlock('skus'), t, locale, key: effectiveAccountKey,
1305
+ enriching: state.blocks?.skus_profit === 'loading',
1255
1306
  });
1256
1307
  } else if (tab === 'ads') {
1257
1308
  body = h(AdsCard, {
package/cordis.patch.yml CHANGED
@@ -32,59 +32,134 @@
32
32
  config:
33
33
  id: seller
34
34
  name: 'Менеджер маркетплейсов'
35
- description: 'Менеджер маркетплейсов: панель продавца, вопросы по своим кабинетам WB и Ozon, финансовый и рекламный разборы внутренними специалистами.'
35
+ description: 'Менеджер маркетплейсов: панель продавца, вопросы по своим кабинетам WB и Ozon, финансовый и рекламный разборы. Пресет расширяет штатный набор Harness инструментами и справочниками Юнита, ничего не отнимая у стандартного агента.'
36
36
  order: 20
37
37
  plugins:
38
38
  - id: persona
39
39
  name: '@deepseek-ai/dsh-persona'
40
40
  config:
41
41
  prefix: !!js "process.getBuiltinModule('node:fs').readFileSync(process.getBuiltinModule('node:path').join(process.getBuiltinModule('node:path').dirname(process.getBuiltinModule('node:module').createRequire(baseUrl).resolve('@managetunit/marketplace-manager/package.json')), 'prompts', 'lead.md'), 'utf8')"
42
-
42
+ - id: agent-instructions
43
+ name: '@deepseek-ai/dsh-agent-instructions'
44
+ config:
45
+ maxBytes: 65536
43
46
  - id: time-context
44
47
  name: '@deepseek-ai/dsh-time-context'
45
-
46
- # Правила площадок и визуализации: общая рамка, WB, Ozon и
47
- # seller-visualization. Сканируются только эти каталоги.
48
- - id: skill-filesystem
49
- name: '@deepseek-ai/dsh-skill-filesystem'
50
- config:
51
- includeDefaultRoots: false
52
- customSkillDirs:
53
- - !!js "process.getBuiltinModule('node:path').join(process.getBuiltinModule('node:path').dirname(process.getBuiltinModule('node:module').createRequire(baseUrl).resolve('@managetunit/marketplace-manager/package.json')), 'handbooks')"
54
- - id: tool-skill
55
- name: '@deepseek-ai/dsh-tool-skill'
56
-
48
+ - id: tool-bash
49
+ name: '@deepseek-ai/dsh-tool-bash'
50
+ disabled: !!js process.platform === 'win32'
51
+ - id: tool-pwsh
52
+ name: '@deepseek-ai/dsh-tool-pwsh'
53
+ disabled: !!js process.platform !== 'win32'
57
54
  - id: tool-fs
58
55
  name: '@deepseek-ai/dsh-tool-fs'
59
56
  config:
60
- write: true
61
- edit: true
57
+ # Set false to drop the apply_patch tool beside edit.
62
58
  applyPatch: false
63
- readImage: false
64
-
65
59
  - id: tool-fs-search
66
60
  name: '@deepseek-ai/dsh-tool-fs-search'
67
61
  config:
68
62
  sampleOverCapGlobResults: false
69
-
70
- - id: tool-web
71
- name: '@deepseek-ai/dsh-tool-web'
63
+ - id: tool-jobs
64
+ name: '@deepseek-ai/dsh-tool-jobs'
65
+ - id: tool-schedule
66
+ name: '@deepseek-ai/dsh-tool-schedule'
67
+ - id: skill-filesystem
68
+ name: '@deepseek-ai/dsh-skill-filesystem'
72
69
  config:
73
- search: false
74
- fetch: true
70
+ customSkillDirs:
71
+ - !!js process.getBuiltinModule('node:path').join(process.getBuiltinModule('node:path').dirname(process.getBuiltinModule('node:module').createRequire(baseUrl).resolve('@deepseek-ai/dsh-agent-preset/package.json')), 'skills')
72
+ - !!js process.getBuiltinModule('node:path').join(process.getBuiltinModule('node:path').dirname(process.getBuiltinModule('node:module').createRequire(baseUrl).resolve('@managetunit/marketplace-manager/package.json')), 'handbooks')
73
+ - id: tool-skill
74
+ name: '@deepseek-ai/dsh-tool-skill'
75
+ - id: command-goal
76
+ name: '@deepseek-ai/dsh-command-goal'
77
+ - id: tool-goal
78
+ name: '@deepseek-ai/dsh-tool-goal'
79
+ - id: planning
80
+ name: cordis:group
81
+ group: true
82
+ isolate:
83
+ planMode: true
84
+ config:
85
+ - id: plan-mode
86
+ name: '@deepseek-ai/dsh-plan-mode'
87
+ config:
88
+ section: |
89
+ You are in plan mode. Stay in plan mode until the user approves your plan through exit_plan_mode or switches the session mode. Imperative language to implement changes means plan the implementation, not execute it. A user's conversational agreement — including an answer confirming something you asked — approves nothing and does not end plan mode; fold the confirmed decision into the plan and submit it through exit_plan_mode.
90
+
91
+ Explore first. Use non-mutating reads, searches, static analysis, and checks to ground the plan in the actual repository. Do not edit or write files, change configuration, run formatters or code generation that rewrites tracked files, commit, or otherwise carry out the plan. Prefer existing functions and patterns over new machinery.
92
+
93
+ The tool catalog stays the same across modes for request-cache stability. These plan-mode rules override any later tool description or guidance that suggests using mutation tools; those tools remain listed to keep the tool catalog unchanged. Do not use todo_write to track this planning phase: it tracks implementation after an approved plan, while the plan itself belongs in exit_plan_mode.
94
+
95
+ Resolve discoverable facts by inspection. Use ask_user_question only for user-owned choices or material ambiguity that inspection cannot answer. Do not ask the user where code lives or how current behavior works when you can find out.
75
96
 
97
+ Make the plan decision-complete: state the goal and success criteria; group implementation changes by subsystem; identify public API, schema, and data-flow changes; cover edge cases, failure modes, tests, acceptance criteria, and explicit assumptions. Keep it concise enough to review but detailed enough that another engineer can implement it without making design decisions.
98
+
99
+ When ready, call exit_plan_mode with the complete plan markdown, starting with a # title. Make exit_plan_mode the only and final tool call in that assistant response: it presents the plan for approval, and implementation begins only in a later step after approval. Do not paste the final plan as a plain reply or ask "should I proceed?" through prose or ask_user_question. If review rejects it, incorporate the feedback and present again. If the review channel is unavailable or aborted, stay in plan mode and ask the user to switch modes manually; do not proceed with implementation.
100
+ - id: compaction
101
+ name: cordis:group
102
+ group: true
103
+ isolate:
104
+ compaction: true
105
+ toolResultPruner: true
106
+ config:
107
+ - id: compaction-basic
108
+ name: '@deepseek-ai/dsh-compaction-basic'
109
+ - id: command-compact
110
+ name: '@deepseek-ai/dsh-command-compact'
111
+ - id: tool-result-pruner
112
+ name: '@deepseek-ai/dsh-compaction-tool-result-pruner'
113
+ config:
114
+ thresholdChars: 8192
115
+ headChars: 4096
116
+ tailChars: 1024
117
+ - id: delegation
118
+ name: cordis:group
119
+ group: true
120
+ isolate:
121
+ workflowEngine: true
122
+ config:
123
+ - id: tool-subagent-control
124
+ name: '@deepseek-ai/dsh-tool-subagent-control'
125
+ config:
126
+ interrupt: false
127
+ - id: tool-subagent
128
+ name: '@deepseek-ai/dsh-tool-subagent'
129
+ config:
130
+ provider: spawn
131
+ toolName: subagent
132
+ modelSelection: true
133
+ modelDiscovery: true
134
+ - id: tool-subagent-fork
135
+ name: '@deepseek-ai/dsh-tool-subagent'
136
+ config:
137
+ provider: fork
138
+ toolName: subagent_fork
139
+ - id: workflow-ptc
140
+ name: '@deepseek-ai/dsh-workflow-ptc'
141
+ config:
142
+ provider: spawn
143
+ - id: tool-workflow
144
+ name: '@deepseek-ai/dsh-tool-workflow'
76
145
  - id: tool-ask-user
77
146
  name: '@deepseek-ai/dsh-tool-ask-user'
78
-
79
147
  - id: tool-todo
80
148
  name: '@deepseek-ai/dsh-tool-todo'
81
149
  config:
82
150
  allowParallelInProgress: true
83
-
151
+ - id: tool-web
152
+ name: '@deepseek-ai/dsh-tool-web'
153
+ config:
154
+ fetch: true
155
+ searchTimeoutMs: 60000
84
156
  - id: present
85
157
  name: '@deepseek-ai/dsh-tool-present'
86
-
87
- # Инструменты «Менеджера маркетплейсов» в роли лида: seller_* + seller_chart.
158
+ - id: tool-office
159
+ name: '@deepseek-ai/dsh-tool-office'
160
+ - id: tool-plugin-manager
161
+ name: '@deepseek-ai/dsh-plugin-manager/tools'
162
+ disabled: !!js "!ctx.get('profileContext')"
88
163
  - id: seller-tools
89
164
  name: '@managetunit/marketplace-manager/tools'
90
165
  config:
@@ -107,21 +182,6 @@
107
182
  modelSelection: true
108
183
  maxDepth: 1
109
184
 
110
- - id: compaction
111
- name: cordis:group
112
- group: true
113
- isolate:
114
- compaction: true
115
- toolResultPruner: true
116
- config:
117
- - id: compaction-basic
118
- name: '@deepseek-ai/dsh-compaction-basic'
119
- - id: tool-result-pruner
120
- name: '@deepseek-ai/dsh-compaction-tool-result-pruner'
121
- config:
122
- thresholdChars: 8192
123
- headChars: 4096
124
- tailChars: 1024
125
185
 
126
186
  # ── Сохранённый пользовательский навык в обычном режиме ─────────────────
127
187
  # Стандартный пресет DSH 0.2.2-rc.3 не всегда показывает корень
package/index.js CHANGED
@@ -758,7 +758,11 @@ export function apply(ctx, config) {
758
758
  .map((item) => item.trim())
759
759
  .filter(Boolean);
760
760
  const metricId = url.searchParams.get("metric") ?? "";
761
- if (!["skus", "ads", "profit", "trend"].includes(part) ||
761
+ const nmIds = (url.searchParams.get("nmIds") ?? "")
762
+ .split(",")
763
+ .map((item) => item.trim())
764
+ .filter(Boolean);
765
+ if (!["skus", "skus_profit", "ads", "profit", "trend"].includes(part) ||
762
766
  (part === "trend" && !KPI_METRICS.some((metric) => metric.id === metricId))) {
763
767
  sendJson(res, 400, {
764
768
  status: "error",
@@ -766,7 +770,7 @@ export function apply(ctx, config) {
766
770
  });
767
771
  return;
768
772
  }
769
- const cacheKey = `${part}|${part === "trend" ? metricId : ""}|${period}|${accounts.join(",")}`;
773
+ const cacheKey = `${part}|${part === "trend" ? metricId : ""}|${period}|${accounts.join(",")}|${part === "skus_profit" ? nmIds.join(",") : ""}`;
770
774
  // Блок читается и пишется только в рамках действующей пары
771
775
  // (подключение, поколение); без входа кэш не отдаётся.
772
776
  const boundary = await currentBoundary();
@@ -784,6 +788,7 @@ export function apply(ctx, config) {
784
788
  const loaders = {
785
789
  profit: () => sellerData.profitKpi(period, accounts),
786
790
  skus: () => sellerData.blockSkus(period, accounts),
791
+ skus_profit: () => sellerData.blockSkusProfit(period, accounts, nmIds),
787
792
  ads: () => sellerData.blockAds(period, accounts),
788
793
  trend: () => sellerData.blockTrend(period, accounts, metricId),
789
794
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@managetunit/marketplace-manager",
3
- "version": "1.3.1",
3
+ "version": "1.3.3",
4
4
  "description": "Unit: панель продавца и режим «Менеджер маркетплейсов» для DeepSeek Harness",
5
5
  "author": {
6
6
  "name": "Unit",
package/service.js CHANGED
@@ -517,6 +517,7 @@ export function createSellerData(ctx, config) {
517
517
  let cabinetCache = null;
518
518
  const productCatalogs = new Map();
519
519
  const photoCache = new Map();
520
+ const skusProfitCache = new Map();
520
521
 
521
522
  async function cabinetsAndCapabilities() {
522
523
  if (cabinetCache && Date.now() - cabinetCache.at < 30000) {
@@ -2446,7 +2447,7 @@ export function createSellerData(ctx, config) {
2446
2447
  };
2447
2448
  },
2448
2449
 
2449
- /** One lazy panel block: the SKU rating with money, orders and ads per SKU. */
2450
+ /** One lazy panel block: the SKU rating by orders, realization and sales (fast). */
2450
2451
  async blockSkus(period = "7d", accounts = []) {
2451
2452
  const window = periodWindow(period);
2452
2453
  const { cabinetsCall } = await cabinetsAndCapabilities();
@@ -2468,34 +2469,140 @@ export function createSellerData(ctx, config) {
2468
2469
  },
2469
2470
  };
2470
2471
  }
2471
- const scope = scopeArgs([cabinet.id]);
2472
- // Прибыль по SKU живёт в sku_profitability, реклама — в query_ads: у
2473
- // metrics_query разрез nmId не несёт этих семейств источников, поэтому
2474
- // колонки прибыли, маржи и рекламы там всегда пустые.
2475
- const [profitCall, adsCall] = await Promise.all([
2476
- call("sku_profitability", { dateFrom: window.from, dateTo: window.to, ...scope }),
2477
- call("query_ads", {
2478
- dateFrom: window.from, dateTo: window.to,
2479
- dimensions: ["campaign", "nmId"], limit: 200, ...scope,
2480
- }),
2481
- ]);
2482
- if (!profitCall.ok) {
2472
+ const response = await call("metrics_query", {
2473
+ metricIds: ["orders_units", "realization_minor", "sales_minor"],
2474
+ dateFrom: window.from,
2475
+ dateTo: window.to,
2476
+ grain: "total",
2477
+ queryVersion: "metric-query-v3",
2478
+ groupBy: ["nmId"],
2479
+ ...scopeArgs([cabinet.id]),
2480
+ });
2481
+ if (!response.ok) {
2483
2482
  return {
2484
2483
  status: "unavailable",
2485
2484
  rows: [],
2486
- note: profitCall.error?.message ?? "Таблица SKU недоступна.",
2485
+ note: response.error?.message ?? "Таблица SKU недоступна.",
2487
2486
  };
2488
2487
  }
2489
- const profitData = unwrap(profitCall).data ?? {};
2490
- const adsRows = adsCall.ok ? firstArray(unwrap(adsCall).data?.rows) ?? [] : [];
2491
- const rows = withAds(profitRows(profitData.items, 40), adsRows);
2488
+ const data = unwrap(response).data ?? {};
2489
+ const items = [];
2490
+ for (const row of firstArray(data.rows) ?? []) {
2491
+ const cells = Array.isArray(row?.cells) ? row.cells : [];
2492
+ const pick = (id) => cells.find((cell) => cell?.metricId === id);
2493
+ const nmId = row?.dimensions?.nmId ?? null;
2494
+ const revenueCell = pick("sales_minor");
2495
+ if (nmId === null && !revenueCell) continue;
2496
+ const rub = (cell) => {
2497
+ if (!cell || typeof cell.value !== "number" || !Number.isFinite(cell.value)) return null;
2498
+ return normalizeUnit(cell.unit) === "RUB_minor" ? Math.round(cell.value) / 100 : cell.value;
2499
+ };
2500
+ items.push({
2501
+ nmId: nmId === null ? null : String(nmId),
2502
+ sellerSku: null,
2503
+ name: null,
2504
+ orders: pick("orders_units")?.value ?? null,
2505
+ buyouts: null,
2506
+ returns: null,
2507
+ revenue: rub(revenueCell),
2508
+ realization: rub(pick("realization_minor")),
2509
+ profit: null,
2510
+ profit_after_ads: null,
2511
+ margin_pct: null,
2512
+ ad_spend: null,
2513
+ drr_pct: null,
2514
+ ad_status: null,
2515
+ });
2516
+ }
2517
+ const products = items.length ? await matchCatalog(cabinet, items.map((item) => ({ sku: item.nmId }))) : new Map();
2518
+ const rows = items
2519
+ .map((item) => {
2520
+ const product = products.get(item.nmId);
2521
+ return { ...item, sellerSku: product?.sellerSku ?? null, name: product?.name ?? null };
2522
+ })
2523
+ .sort((a, b) => (b.revenue ?? -Infinity) - (a.revenue ?? -Infinity))
2524
+ .slice(0, 40);
2492
2525
  return {
2493
- status: profitData.status === "partial" ? "partial" : rows.length ? "ok" : "empty",
2526
+ status: rows.length ? "ok" : "empty",
2494
2527
  cabinet: { id: cabinet.id, name: cabinet.name, marketplace: cabinet.marketplace },
2495
2528
  period: window,
2496
- dataAsOf: profitData.dataAsOf ?? null,
2529
+ dataAsOf: data.dataAsOf ?? null,
2530
+ rows,
2531
+ };
2532
+ },
2533
+
2534
+ /**
2535
+ * Прибыль, выкупы и реклама по SKU. Считается по списку nmId, который
2536
+ * передала панель: на всём каталоге сервер отвечает около полутора минут,
2537
+ * а на тридцати SKU — секунды. Результат кэшируется на десять минут.
2538
+ */
2539
+ async blockSkusProfit(period = "7d", accounts = [], nmIds = []) {
2540
+ const window = periodWindow(period);
2541
+ const wanted = (Array.isArray(nmIds) ? nmIds : [])
2542
+ .map((value) => Number(value))
2543
+ .filter((value) => Number.isInteger(value) && value > 0)
2544
+ .slice(0, 40);
2545
+ if (wanted.length === 0) return { status: "empty", rows: [] };
2546
+ const cacheKey = `${period}|${accounts.join(",")}|${wanted.slice().sort((a, b) => a - b).join(",")}`;
2547
+ const cached = skusProfitCache.get(cacheKey);
2548
+ if (cached && Date.now() - cached.at < 10 * 60 * 1000) return cached.value;
2549
+ const { cabinetsCall } = await cabinetsAndCapabilities();
2550
+ if (!cabinetsCall.ok) return failed(cabinetsCall);
2551
+ const cabinets = extractCabinets(unwrap(cabinetsCall).envelope);
2552
+ const allowed = scopeAccountIds(accounts, cabinets);
2553
+ const cabinet =
2554
+ allowed.find((item) => item.marketplace === "wb") ??
2555
+ (allowed.length === 1 ? allowed[0] : null);
2556
+ if (!cabinet) return { status: "unavailable", rows: [] };
2557
+ const scope = scopeArgs([cabinet.id]);
2558
+ const [profitCall, adsCall] = await Promise.all([
2559
+ call("sku_profitability", {
2560
+ dateFrom: window.from, dateTo: window.to, nmIds: wanted, ...scope,
2561
+ }, { timeoutMs: 120000 }),
2562
+ call("query_ads", {
2563
+ dateFrom: window.from, dateTo: window.to,
2564
+ dimensions: ["campaign", "nmId"], limit: 200, nmIds: wanted, ...scope,
2565
+ }, { timeoutMs: 120000 }),
2566
+ ]);
2567
+ const items = profitCall.ok ? firstArray(unwrap(profitCall).data?.items) ?? [] : [];
2568
+ const adsRows = adsCall.ok ? firstArray(unwrap(adsCall).data?.rows) ?? [] : [];
2569
+ const spendByNm = new Map();
2570
+ for (const ad of adsRows) {
2571
+ const nmId = ad?.nmId === undefined || ad?.nmId === null ? null : String(ad.nmId);
2572
+ if (nmId === null) continue;
2573
+ const value = typeof ad?.spendRub === "number" && Number.isFinite(ad.spendRub) ? ad.spendRub : 0;
2574
+ spendByNm.set(nmId, (spendByNm.get(nmId) ?? 0) + value);
2575
+ }
2576
+ const rows = items.map((item) => {
2577
+ const nmId = item?.nmId === undefined || item?.nmId === null ? null : String(item.nmId);
2578
+ const revenue = typeof item?.revenue === "number" ? item.revenue : null;
2579
+ const profit = item?.contributionBeforeAdsProven === undefined || item?.contributionBeforeAdsProven === null
2580
+ ? (typeof item?.contributionBeforeAds === "number" ? item.contributionBeforeAds : null)
2581
+ : item.contributionBeforeAdsProven;
2582
+ const spend = nmId === null ? null : spendByNm.get(nmId) ?? null;
2583
+ return {
2584
+ nmId,
2585
+ sellerSku: typeof item?.sellerSku === "string" ? item.sellerSku : null,
2586
+ buyouts: typeof item?.buyoutUnits === "number" ? item.buyoutUnits : null,
2587
+ returns: typeof item?.returnsUnits === "number" ? item.returnsUnits : null,
2588
+ profit,
2589
+ margin_pct: revenue && revenue !== 0 && profit !== null
2590
+ ? Math.round((profit / revenue) * 1000) / 10 : null,
2591
+ ad_spend: spend === null ? null : Math.round(spend * 100) / 100,
2592
+ drr_pct: spend !== null && revenue
2593
+ ? Math.round((spend / revenue) * 1000) / 10 : null,
2594
+ ad_status: adsCall.ok ? unwrap(adsCall).data?.status ?? null : null,
2595
+ };
2596
+ });
2597
+ const value = {
2598
+ status: rows.length ? "ok" : "empty",
2497
2599
  rows,
2600
+ period: window,
2601
+ cabinet: { id: cabinet.id, name: cabinet.name, marketplace: cabinet.marketplace },
2602
+ dataAsOf: profitCall.ok ? unwrap(profitCall).data?.dataAsOf ?? null : null,
2498
2603
  };
2604
+ skusProfitCache.set(cacheKey, { at: Date.now(), value });
2605
+ return value;
2499
2606
  },
2500
2607
 
2501
2608
  /** One lazy panel block: ad campaigns with their per-SKU contributions. */