@managetunit/marketplace-manager 0.0.0-stage → 1.3.0
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 +88 -2
- package/chart.js +346 -0
- package/client.js +1402 -0
- package/cordis.patch.yml +145 -0
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.ru.md +1 -0
- package/docs/TECHNICAL.md +117 -0
- package/docs/UPDATE-ARCHIVE.md +47 -0
- package/docs/UPDATE-CHANNELS.md +57 -0
- package/docs/seller-hq-preview.webp +0 -0
- package/handbooks/marketplace-rules/SKILL.md +71 -0
- package/handbooks/ozon-handbook/SKILL.md +71 -0
- package/handbooks/seller-ads-analyst/SKILL.md +60 -0
- package/handbooks/seller-finance-analyst/SKILL.md +68 -0
- package/handbooks/seller-visualization/SKILL.md +81 -0
- package/handbooks/unit-data/SKILL.md +167 -0
- package/handbooks/wb-handbook/SKILL.md +65 -0
- package/icon.png +0 -0
- package/icon.svg +4 -0
- package/index.js +1237 -0
- package/locale/en.json +7 -0
- package/locale/ru.json +7 -0
- package/mapping.js +320 -0
- package/mcp.js +295 -0
- package/package.json +64 -4
- package/prompts/ads.md +11 -0
- package/prompts/finance.md +11 -0
- package/prompts/lead.md +203 -0
- package/prompts/standard.md +75 -0
- package/rows.js +112 -0
- package/service.js +2918 -0
- package/standard.js +285 -0
- package/tools.js +818 -0
package/README.md
CHANGED
|
@@ -1,3 +1,89 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @managetunit/marketplace-manager — «Менеджер маркетплейсов» для DeepSeek Harness
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Один пакет для панели и режима:
|
|
4
|
+
|
|
5
|
+
- **панель «Менеджер маркетплейсов»** — KPI, динамика, товары и реклама кабинетов WB/Ozon;
|
|
6
|
+
- **режим «Менеджер маркетплейсов»** — вопросы по своим кабинетам, финансовый и рекламный
|
|
7
|
+
разборы, графики в чате;
|
|
8
|
+
- **обычный режим Harness** — инструменты и инструкции Юнита добавляются к текущему
|
|
9
|
+
агенту без замены его пресета, штатных инструментов и навыков; сохранённый
|
|
10
|
+
пользовательский навык остаётся видимым;
|
|
11
|
+
- **вход в Unit** — OAuth 2.0 + PKCE, токен хранится в credentials DSH;
|
|
12
|
+
- **пятнадцать инструментов** — восемь read-only `seller_*`, `seller_freshness`, `seller_forecast` и `seller_chart`.
|
|
13
|
+
|
|
14
|
+
Пакет публикуется в npm под именем `@managetunit/marketplace-manager`. Страница установки —
|
|
15
|
+
<https://crm.mypowcan.ru/marketplace-manager>.
|
|
16
|
+
|
|
17
|
+
## Установка
|
|
18
|
+
|
|
19
|
+
1. Откройте <https://crm.mypowcan.ru/marketplace-manager>.
|
|
20
|
+
2. Вставьте ссылку на страницу в чат DeepSeek Harness и напишите «Установи плагин»:
|
|
21
|
+
агент прочитает машинные данные страницы и поставит пакет из npm.
|
|
22
|
+
3. Подтвердите установку — DSH покажет имя пакета и источник.
|
|
23
|
+
4. Откройте «Менеджер маркетплейсов» в боковой панели и нажмите «Войти в Юнит».
|
|
24
|
+
|
|
25
|
+
Вручную то же самое: **«Плагины» → «Добавить плагин» → `@managetunit/marketplace-manager` →
|
|
26
|
+
«Установить» → «Включить сейчас»**. Из командной строки —
|
|
27
|
+
`dsh plugin --profile <profile> add @managetunit/marketplace-manager`.
|
|
28
|
+
|
|
29
|
+
Перед установкой удалите прежние `@local/seller-os` и `@local/seller-team`,
|
|
30
|
+
если они установлены: у нового пакета тот же id пресета `seller`.
|
|
31
|
+
|
|
32
|
+
## Обновления
|
|
33
|
+
|
|
34
|
+
Установка из реестра обновляется штатно: когда в npm появляется новая версия, в карточке
|
|
35
|
+
плагина возникает «Доступно обновление до X» и кнопка «Обновление до X». Удалять пакет,
|
|
36
|
+
перезапускать Harness и заново входить в Юнит не нужно. Список версий показывает даты,
|
|
37
|
+
предрелизы и совместимость с текущей версией DSH; несовместимую версию DSH ставить не даст.
|
|
38
|
+
|
|
39
|
+
Кнопка обновления есть только у реестровой установки. Если пакет поставлен из `.tgz` по
|
|
40
|
+
HTTPS-ссылке, карточка показывает источник и текущую версию, но обновление выполняют
|
|
41
|
+
вручную — см. [docs/UPDATE-CHANNELS.md](docs/UPDATE-CHANNELS.md).
|
|
42
|
+
|
|
43
|
+
## Резервный путь: архив
|
|
44
|
+
|
|
45
|
+
Если реестр недоступен, пакет можно поставить файлом:
|
|
46
|
+
|
|
47
|
+
```text
|
|
48
|
+
https://crm.mypowcan.ru/marketplace-manager/marketplace-manager-1.2.3.tgz
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Контрольная сумма и размер — в `latest.json` рядом со страницей. Такая установка работает,
|
|
52
|
+
но кнопки обновления не получает: следующую версию ставят повторной установкой архива.
|
|
53
|
+
|
|
54
|
+
## Переход с архивной установки на реестровую
|
|
55
|
+
|
|
56
|
+
1. «Плагины» → карточка «Менеджер маркетплейсов» → «Удалить».
|
|
57
|
+
2. «Добавить плагин» → `@managetunit/marketplace-manager` → «Установить» → «Включить сейчас».
|
|
58
|
+
3. Откройте панель: токен входа хранится в credentials DSH, а не в пакете.
|
|
59
|
+
|
|
60
|
+
Установить реестровое имя поверх архивной копии нельзя — DSH ответит, что пакет уже
|
|
61
|
+
установлен, поэтому удаление обязательно. Подробнее — в
|
|
62
|
+
[docs/UPDATE-CHANNELS.md](docs/UPDATE-CHANNELS.md).
|
|
63
|
+
|
|
64
|
+
## Что внутри
|
|
65
|
+
|
|
66
|
+
| Файл | Назначение |
|
|
67
|
+
|---|---|
|
|
68
|
+
| `cordis.patch.yml` | вставляет host-строку `marketplace-manager`, пресет `preset-seller` и аддитивные строки обычного режима |
|
|
69
|
+
| `index.js` | OAuth, `sellerData`, маршруты `/plugin/marketplace-manager/*` |
|
|
70
|
+
| `standard.js` | аддитивные Unit tools, handbooks и инструкция для обычного агента; seller-пресет пропускается |
|
|
71
|
+
| `service.js` | MCP-клиент, снимок, блоки панели |
|
|
72
|
+
| `mcp.js` | минимальный MCP Streamable-HTTP клиент |
|
|
73
|
+
| `mapping.js` | карта инструментов и read-allowlist |
|
|
74
|
+
| `tools.js` | пятнадцать инструментов, включая `seller_forecast`, `seller_chart`, `seller_profile`, `seller_products`, `seller_sku_table`, `seller_audit` |
|
|
75
|
+
| `chart.js` | детерминированный SVG-график без зависимостей |
|
|
76
|
+
| `client.js` | панель в слотах `sidebar.panellist` и `main` |
|
|
77
|
+
| `prompts/` | персона Лида и специалистов, инструкция для обычного режима |
|
|
78
|
+
| `handbooks/` | `marketplace-rules`, `wb-handbook`, `ozon-handbook`, `seller-visualization` и ролевые навыки |
|
|
79
|
+
| `docs/UPDATE-CHANNELS.md` | чем отличается реестровая установка от архивной и как перейти |
|
|
80
|
+
| `docs/UPDATE-ARCHIVE.md` | замена архивной сборки новой версией без ручного удаления |
|
|
81
|
+
|
|
82
|
+
## Проверка
|
|
83
|
+
|
|
84
|
+
```sh
|
|
85
|
+
dsh plugin --profile <profile> add @managetunit/marketplace-manager
|
|
86
|
+
dsh --profile <profile> --dump-config
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Пакет не содержит зависимостей и не выполняет install-скриптов.
|
package/chart.js
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deterministic SVG charts for the «Менеджер маркетплейсов» chat.
|
|
3
|
+
*
|
|
4
|
+
* No dependencies: the module runs inside the DSH host process, and an
|
|
5
|
+
* out-of-tree bundle cannot import @deepseek-ai packages. It renders a single
|
|
6
|
+
* self-contained SVG (960×460 by default) with an explicit light/dark theme,
|
|
7
|
+
* Russian number formatting, gaps for missing values and a readable legend.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const DEFAULT_WIDTH = 960;
|
|
11
|
+
const DEFAULT_HEIGHT = 460;
|
|
12
|
+
const PAD = { left: 68, right: 30, top: 104, bottom: 70 };
|
|
13
|
+
const COLORS = ["#2f5fb3", "#2a9d8f", "#d19a2a", "#c0504d", "#7b61a8"];
|
|
14
|
+
const MAX_SERIES = 5;
|
|
15
|
+
const MAX_POINTS = 60;
|
|
16
|
+
|
|
17
|
+
const TYPES = new Set(["line", "bar", "stacked_bar"]);
|
|
18
|
+
const UNITS = new Set(["rub", "percent", "count"]);
|
|
19
|
+
|
|
20
|
+
function escapeXml(value) {
|
|
21
|
+
return String(value)
|
|
22
|
+
.replace(/&/g, "&")
|
|
23
|
+
.replace(/</g, "<")
|
|
24
|
+
.replace(/>/g, ">")
|
|
25
|
+
.replace(/"/g, """);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function isFiniteNumber(value) {
|
|
29
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function decimal(value, digits = 1) {
|
|
33
|
+
return new Intl.NumberFormat("ru-RU", {
|
|
34
|
+
minimumFractionDigits: 0,
|
|
35
|
+
maximumFractionDigits: digits,
|
|
36
|
+
}).format(value);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Russian short number: 1,24 млрд ₽, 345 тыс. ₽, 12,3%. */
|
|
40
|
+
export function formatValue(value, unit = "rub", compact = true) {
|
|
41
|
+
if (!isFiniteNumber(value)) return "—";
|
|
42
|
+
const sign = value < 0 ? "−" : "";
|
|
43
|
+
const abs = Math.abs(value);
|
|
44
|
+
if (unit === "percent") return `${sign}${decimal(abs, 1)}%`;
|
|
45
|
+
if (unit === "count") {
|
|
46
|
+
if (compact && abs >= 1_000_000) return `${sign}${decimal(abs / 1_000_000, 2)} млн`;
|
|
47
|
+
if (compact && abs >= 10_000) return `${sign}${decimal(abs / 1_000, 1)} тыс.`;
|
|
48
|
+
return `${sign}${decimal(abs, 0)}`;
|
|
49
|
+
}
|
|
50
|
+
if (compact && abs >= 1_000_000_000) return `${sign}${decimal(abs / 1_000_000_000, 2)} млрд ₽`;
|
|
51
|
+
if (compact && abs >= 1_000_000) return `${sign}${decimal(abs / 1_000_000, 2)} млн ₽`;
|
|
52
|
+
if (compact && abs >= 10_000) return `${sign}${decimal(abs / 1_000, 0)} тыс. ₽`;
|
|
53
|
+
return `${sign}${decimal(abs, 0)} ₽`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function niceStep(span, targetTicks) {
|
|
57
|
+
if (!(span > 0)) return 1;
|
|
58
|
+
const rough = span / Math.max(1, targetTicks);
|
|
59
|
+
const power = 10 ** Math.floor(Math.log10(rough));
|
|
60
|
+
const normalized = rough / power;
|
|
61
|
+
const step = normalized <= 1 ? 1 : normalized <= 2 ? 2 : normalized <= 2.5 ? 2.5 : normalized <= 5 ? 5 : 10;
|
|
62
|
+
return step * power;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function truncate(text, max) {
|
|
66
|
+
const value = String(text);
|
|
67
|
+
return value.length <= max ? value : `${value.slice(0, Math.max(1, max - 1))}…`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function slug(value) {
|
|
71
|
+
return String(value ?? "")
|
|
72
|
+
.toLowerCase()
|
|
73
|
+
.replace(/[^a-z0-9а-яё-]+/gi, "-")
|
|
74
|
+
.replace(/^-+|-+$/g, "")
|
|
75
|
+
.slice(0, 48);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Validate and normalise a chart spec.
|
|
80
|
+
* @param {object} input - model-supplied spec.
|
|
81
|
+
* @returns {object} normalised spec.
|
|
82
|
+
*/
|
|
83
|
+
export function normalizeSpec(input) {
|
|
84
|
+
const spec = input && typeof input === "object" ? input : {};
|
|
85
|
+
const type = TYPES.has(spec.type) ? spec.type : "line";
|
|
86
|
+
const unit = UNITS.has(spec.unit) ? spec.unit : "rub";
|
|
87
|
+
const x = Array.isArray(spec.x) ? spec.x.map((value) => String(value)) : [];
|
|
88
|
+
if (x.length === 0) throw new Error("chart: x must contain at least one label");
|
|
89
|
+
if (x.length > MAX_POINTS) throw new Error(`chart: at most ${MAX_POINTS} x labels`);
|
|
90
|
+
const rawSeries = Array.isArray(spec.series) ? spec.series : [];
|
|
91
|
+
if (rawSeries.length === 0) throw new Error("chart: series must contain at least one series");
|
|
92
|
+
if (rawSeries.length > MAX_SERIES) throw new Error(`chart: at most ${MAX_SERIES} series`);
|
|
93
|
+
const series = rawSeries.map((item, index) => {
|
|
94
|
+
const source = item && typeof item === "object" ? item : {};
|
|
95
|
+
const values = Array.isArray(source.values) ? source.values : [];
|
|
96
|
+
if (values.length !== x.length) {
|
|
97
|
+
throw new Error(`chart: series ${index + 1} has ${values.length} values for ${x.length} x labels`);
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
name: String(source.name ?? `Ряд ${index + 1}`),
|
|
101
|
+
values: values.map((value) => (isFiniteNumber(value) ? value : null)),
|
|
102
|
+
kind: source.kind === "bar" || source.kind === "line" ? source.kind : null,
|
|
103
|
+
color: typeof source.color === "string" && /^#[0-9a-f]{6}$/i.test(source.color)
|
|
104
|
+
? source.color
|
|
105
|
+
: COLORS[index % COLORS.length],
|
|
106
|
+
};
|
|
107
|
+
});
|
|
108
|
+
const width = Math.min(1400, Math.max(640, Number(spec.width) || DEFAULT_WIDTH));
|
|
109
|
+
const height = Math.min(900, Math.max(320, Number(spec.height) || DEFAULT_HEIGHT));
|
|
110
|
+
return {
|
|
111
|
+
type,
|
|
112
|
+
unit,
|
|
113
|
+
x,
|
|
114
|
+
series,
|
|
115
|
+
title: String(spec.title ?? "Показатели"),
|
|
116
|
+
subtitle: typeof spec.subtitle === "string" ? spec.subtitle : "",
|
|
117
|
+
note: typeof spec.note === "string" ? spec.note : "",
|
|
118
|
+
width,
|
|
119
|
+
height,
|
|
120
|
+
filename: slug(spec.filename),
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function stackedTotals(spec) {
|
|
125
|
+
return spec.x.map((_, index) =>
|
|
126
|
+
spec.series.reduce((sum, serie) => sum + (serie.values[index] ?? 0), 0),
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function valueRange(spec) {
|
|
131
|
+
const values =
|
|
132
|
+
spec.type === "stacked_bar"
|
|
133
|
+
? stackedTotals(spec)
|
|
134
|
+
: spec.series.flatMap((serie) => serie.values.filter(isFiniteNumber));
|
|
135
|
+
if (values.length === 0) return { min: 0, max: 1 };
|
|
136
|
+
let min = Math.min(0, ...values);
|
|
137
|
+
let max = Math.max(0, ...values);
|
|
138
|
+
if (min === max) {
|
|
139
|
+
max = min + 1;
|
|
140
|
+
}
|
|
141
|
+
const span = max - min;
|
|
142
|
+
const padding = span * 0.08;
|
|
143
|
+
if (min < 0) min -= padding;
|
|
144
|
+
if (max > 0) max += padding;
|
|
145
|
+
return { min, max };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function grid(spec, box, range) {
|
|
149
|
+
const step = niceStep(range.max - range.min, 5);
|
|
150
|
+
const ticks = [];
|
|
151
|
+
const start = Math.ceil(range.min / step) * step;
|
|
152
|
+
for (let value = start; value <= range.max + step * 0.001; value += step) {
|
|
153
|
+
ticks.push(value);
|
|
154
|
+
}
|
|
155
|
+
if (ticks.length < 2) ticks.push(start + step);
|
|
156
|
+
const y = (value) =>
|
|
157
|
+
box.top + box.height - ((value - range.min) / (range.max - range.min)) * box.height;
|
|
158
|
+
const lines = ticks
|
|
159
|
+
.map((value) => {
|
|
160
|
+
const top = y(value);
|
|
161
|
+
return `<line x1="${box.left}" y1="${top.toFixed(2)}" x2="${(box.left + box.width).toFixed(2)}" y2="${top.toFixed(2)}" class="grid"/>` +
|
|
162
|
+
`<text x="${box.left - 12}" y="${(top + 4).toFixed(2)}" text-anchor="end" class="tick">${escapeXml(formatValue(value, spec.unit, true))}</text>`;
|
|
163
|
+
})
|
|
164
|
+
.join("");
|
|
165
|
+
return { ticks, y, markup: lines };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function xAxis(spec, box) {
|
|
169
|
+
const count = spec.x.length;
|
|
170
|
+
const step = Math.max(1, Math.ceil(count / 8));
|
|
171
|
+
const items = [];
|
|
172
|
+
for (let index = 0; index < count; index += step) {
|
|
173
|
+
const center = box.left + ((index + 0.5) / count) * box.width;
|
|
174
|
+
items.push(
|
|
175
|
+
`<text x="${center.toFixed(2)}" y="${(box.top + box.height + 26).toFixed(2)}" text-anchor="middle" class="tick">${escapeXml(truncate(spec.x[index], 18))}</text>`,
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
return items.join("");
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function lineMarkup(spec, box, range) {
|
|
182
|
+
const y = (value) =>
|
|
183
|
+
box.top + box.height - ((value - range.min) / (range.max - range.min)) * box.height;
|
|
184
|
+
const x = (index) =>
|
|
185
|
+
box.left + ((index + 0.5) / spec.x.length) * box.width;
|
|
186
|
+
const parts = [];
|
|
187
|
+
for (const [serieIndex, serie] of spec.series.entries()) {
|
|
188
|
+
let segment = [];
|
|
189
|
+
const segments = [];
|
|
190
|
+
for (let index = 0; index < serie.values.length; index += 1) {
|
|
191
|
+
const value = serie.values[index];
|
|
192
|
+
if (isFiniteNumber(value)) {
|
|
193
|
+
segment.push(`${x(index).toFixed(2)},${y(value).toFixed(2)}`);
|
|
194
|
+
} else if (segment.length > 0) {
|
|
195
|
+
segments.push(segment);
|
|
196
|
+
segment = [];
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (segment.length > 0) segments.push(segment);
|
|
200
|
+
for (const points of segments) {
|
|
201
|
+
if (points.length === 1) {
|
|
202
|
+
const [cx, cy] = points[0].split(",");
|
|
203
|
+
parts.push(`<circle cx="${cx}" cy="${cy}" r="3.2" fill="${serie.color}"/>`);
|
|
204
|
+
} else {
|
|
205
|
+
parts.push(
|
|
206
|
+
`<polyline points="${points.join(" ")}" fill="none" stroke="${serie.color}" stroke-width="${serieIndex === 0 ? 2.6 : 2}" stroke-linejoin="round" stroke-linecap="round"/>`,
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
if (spec.x.length <= 16) {
|
|
211
|
+
for (let index = 0; index < serie.values.length; index += 1) {
|
|
212
|
+
const value = serie.values[index];
|
|
213
|
+
if (isFiniteNumber(value)) {
|
|
214
|
+
parts.push(
|
|
215
|
+
`<circle cx="${x(index).toFixed(2)}" cy="${y(value).toFixed(2)}" r="3.4" fill="var(--chart-surface)" stroke="${serie.color}" stroke-width="2"/>`,
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
parts.push(
|
|
222
|
+
`<line x1="${box.left}" y1="${y(0).toFixed(2)}" x2="${(box.left + box.width).toFixed(2)}" y2="${y(0).toFixed(2)}" class="axis"/>`,
|
|
223
|
+
);
|
|
224
|
+
return parts.join("");
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function barMarkup(spec, box, range, stacked) {
|
|
228
|
+
const y = (value) =>
|
|
229
|
+
box.top + box.height - ((value - range.min) / (range.max - range.min)) * box.height;
|
|
230
|
+
const slot = box.width / spec.x.length;
|
|
231
|
+
const groupWidth = Math.min(slot * 0.76, 72);
|
|
232
|
+
const barWidth = stacked
|
|
233
|
+
? groupWidth
|
|
234
|
+
: Math.max(3, groupWidth / spec.series.length - 2);
|
|
235
|
+
const zero = y(0);
|
|
236
|
+
const parts = [];
|
|
237
|
+
if (stacked) {
|
|
238
|
+
for (let index = 0; index < spec.x.length; index += 1) {
|
|
239
|
+
let positive = 0;
|
|
240
|
+
let negative = 0;
|
|
241
|
+
const center = box.left + (index + 0.5) * slot;
|
|
242
|
+
for (const serie of spec.series) {
|
|
243
|
+
const value = serie.values[index];
|
|
244
|
+
if (!isFiniteNumber(value) || value === 0) continue;
|
|
245
|
+
const start = value >= 0 ? positive : negative;
|
|
246
|
+
const end = start + value;
|
|
247
|
+
if (value >= 0) positive = end;
|
|
248
|
+
else negative = end;
|
|
249
|
+
const top = Math.min(y(start), y(end));
|
|
250
|
+
const height = Math.max(1, Math.abs(y(start) - y(end)));
|
|
251
|
+
parts.push(
|
|
252
|
+
`<rect x="${(center - barWidth / 2).toFixed(2)}" y="${top.toFixed(2)}" width="${barWidth.toFixed(2)}" height="${height.toFixed(2)}" rx="2" fill="${serie.color}"><title>${escapeXml(`${serie.name}: ${formatValue(value, spec.unit, false)}`)}</title></rect>`,
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
} else {
|
|
257
|
+
const groupSpan = barWidth * spec.series.length + 2 * (spec.series.length - 1);
|
|
258
|
+
for (let index = 0; index < spec.x.length; index += 1) {
|
|
259
|
+
const center = box.left + (index + 0.5) * slot;
|
|
260
|
+
const left = center - groupSpan / 2;
|
|
261
|
+
for (const [serieIndex, serie] of spec.series.entries()) {
|
|
262
|
+
const value = serie.values[index];
|
|
263
|
+
if (!isFiniteNumber(value)) continue;
|
|
264
|
+
const barLeft = left + serieIndex * (barWidth + 2);
|
|
265
|
+
const top = Math.min(y(0), y(value));
|
|
266
|
+
const height = Math.max(1, Math.abs(y(value) - y(0)));
|
|
267
|
+
parts.push(
|
|
268
|
+
`<rect x="${barLeft.toFixed(2)}" y="${top.toFixed(2)}" width="${barWidth.toFixed(2)}" height="${height.toFixed(2)}" rx="2" fill="${serie.color}"><title>${escapeXml(`${serie.name}: ${formatValue(value, spec.unit, false)}`)}</title></rect>`,
|
|
269
|
+
);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
parts.push(
|
|
274
|
+
`<line x1="${box.left}" y1="${zero.toFixed(2)}" x2="${(box.left + box.width).toFixed(2)}" y2="${zero.toFixed(2)}" class="axis"/>`,
|
|
275
|
+
);
|
|
276
|
+
return parts.join("");
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function legend(spec, box) {
|
|
280
|
+
const items = spec.series
|
|
281
|
+
.map((serie, index) => {
|
|
282
|
+
const x = 30 + index * 168;
|
|
283
|
+
return `<g transform="translate(${x} 74)"><rect width="10" height="10" rx="2" fill="${serie.color}"/><text x="16" y="9" class="legend">${escapeXml(truncate(serie.name, 20))}</text></g>`;
|
|
284
|
+
})
|
|
285
|
+
.join("");
|
|
286
|
+
return items;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Render one chart.
|
|
291
|
+
* @param {object} input - chart spec.
|
|
292
|
+
* @returns {{svg:string, filename:string, width:number, height:number, title:string}}
|
|
293
|
+
*/
|
|
294
|
+
export function renderChart(input) {
|
|
295
|
+
const spec = normalizeSpec(input);
|
|
296
|
+
const box = {
|
|
297
|
+
left: PAD.left,
|
|
298
|
+
top: PAD.top,
|
|
299
|
+
width: spec.width - PAD.left - PAD.right,
|
|
300
|
+
height: spec.height - PAD.top - PAD.bottom,
|
|
301
|
+
};
|
|
302
|
+
const range = valueRange(spec);
|
|
303
|
+
const hasData = spec.series.some((serie) => serie.values.some(isFiniteNumber));
|
|
304
|
+
const gridData = grid(spec, box, range);
|
|
305
|
+
const body = spec.type === "line"
|
|
306
|
+
? lineMarkup(spec, box, range)
|
|
307
|
+
: barMarkup(spec, box, range, spec.type === "stacked_bar");
|
|
308
|
+
const empty = hasData
|
|
309
|
+
? ""
|
|
310
|
+
: `<text x="${box.left + box.width / 2}" y="${box.top + box.height / 2}" text-anchor="middle" class="empty">Нет данных за период</text>`;
|
|
311
|
+
const note = spec.note
|
|
312
|
+
? `<text x="${PAD.left}" y="${spec.height - 20}" class="note">${escapeXml(truncate(spec.note, 120))}</text>`
|
|
313
|
+
: "";
|
|
314
|
+
const subtitle = spec.subtitle
|
|
315
|
+
? `<text x="${PAD.left}" y="52" class="subtitle">${escapeXml(truncate(spec.subtitle, 110))}</text>`
|
|
316
|
+
: "";
|
|
317
|
+
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${spec.width}" height="${spec.height}" viewBox="0 0 ${spec.width} ${spec.height}" role="img" aria-label="${escapeXml(spec.title)}">
|
|
318
|
+
<style>
|
|
319
|
+
:root { --chart-bg:#ffffff; --chart-surface:#ffffff; --chart-ink:#1c2434; --chart-muted:#697386; --chart-grid:#e7eaf1; --chart-axis:#b9c0cf; }
|
|
320
|
+
@media (prefers-color-scheme: dark) {
|
|
321
|
+
:root { --chart-bg:#141821; --chart-surface:#141821; --chart-ink:#eef1f7; --chart-muted:#99a3b7; --chart-grid:#293041; --chart-axis:#46506a; }
|
|
322
|
+
}
|
|
323
|
+
.bg { fill: var(--chart-bg); }
|
|
324
|
+
.title { fill: var(--chart-ink); font: 600 22px/1.2 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; letter-spacing: -0.01em; }
|
|
325
|
+
.subtitle { fill: var(--chart-muted); font: 400 13px/1.3 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }
|
|
326
|
+
.tick { fill: var(--chart-muted); font: 400 11px/1.2 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }
|
|
327
|
+
.legend { fill: var(--chart-ink); font: 500 11px/1.2 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }
|
|
328
|
+
.note { fill: var(--chart-muted); font: 400 11px/1.2 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }
|
|
329
|
+
.empty { fill: var(--chart-muted); font: 400 14px/1.2 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }
|
|
330
|
+
.grid { stroke: var(--chart-grid); stroke-width: 1; }
|
|
331
|
+
.axis { stroke: var(--chart-axis); stroke-width: 1; }
|
|
332
|
+
</style>
|
|
333
|
+
<rect class="bg" width="${spec.width}" height="${spec.height}" rx="14"/>
|
|
334
|
+
<text x="${PAD.left}" y="32" class="title">${escapeXml(truncate(spec.title, 72))}</text>
|
|
335
|
+
${subtitle}
|
|
336
|
+
${legend(spec, box)}
|
|
337
|
+
${gridData.markup}
|
|
338
|
+
${xAxis(spec, box)}
|
|
339
|
+
${body}
|
|
340
|
+
${empty}
|
|
341
|
+
${note}
|
|
342
|
+
<text x="${spec.width - PAD.right}" y="${spec.height - 20}" text-anchor="end" class="note">Unit · Менеджер маркетплейсов</text>
|
|
343
|
+
</svg>`;
|
|
344
|
+
const filename = spec.filename || `marketplace-manager-chart-${Date.now().toString(36)}`;
|
|
345
|
+
return { svg, filename: `${filename}.svg`, width: spec.width, height: spec.height, title: spec.title };
|
|
346
|
+
}
|