@managetunit/marketplace-manager 1.3.0 → 1.3.2

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.
Files changed (4) hide show
  1. package/client.js +52 -1
  2. package/index.js +7 -2
  3. package/package.json +1 -1
  4. package/service.js +126 -19
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/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.0",
3
+ "version": "1.3.2",
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. */