odant-work 1.0.55 → 1.0.56
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/#system/package-manifest.json +32 -38
- package/$server/$folder/$class/$structure/$server/class.js +17 -1
- package/MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js +26 -1
- package/MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js +8 -1
- package/SERVICES/$service/$folder/$storage/$service/handlers/pages/form/mcp/$handler/mcp.js +22 -4
- package/SERVICES/1C/$service/class.js +209 -0
- package/SERVICES/Bitrix24/$service/class.js +180 -0
- package/SERVICES/CBR/$service/class.js +263 -0
- package/SERVICES/DaData/$service/class.js +352 -0
- package/SERVICES/DuckDuckGo/$service/class.js +3 -2
- package/SERVICES/RuCalendar/$service/class.js +289 -0
- package/SERVICES/SearXNG/$service/class.js +3 -1
- package/SERVICES/Telegram/$service/class.js +170 -114
- package/SERVICES/Weather/$service/class.js +3 -1
- package/SERVICES/Yandex/$service/class.js +4 -2
- package/SERVICES/YandexDisk/$service/class.js +191 -0
- package/SERVICES/readme.md +31 -43
- package/package.json +1 -1
- package/sources/data/progress.md +14 -0
- package/sources/modules/agent/extensions.js +118 -39
- package/sources/modules/agent/voice.js +1 -1
- package/sources/modules/trainer/halogen.js +24 -3
- package/sources/modules/trainer/huggingface.js +73 -11
- package/sources/modules/trainer/index.js +54 -29
- package/sources/modules/trainer/local-engine.js +38 -8
- package/sources/modules/trainer/paths.js +8 -0
- package/sources/modules/trainer/providers.js +14 -0
- package/sources/modules/trainer/worker/local_infer_worker.py +160 -1
- package/sources/server/access/gateway.js +1 -0
- package/SERVICES/ArgoCD/$service/$folder/$class/$service/class.js +0 -356
- package/SERVICES/ArgoCD/$service/$folder/$class/$service/handlers/pages/form/orders/$handler/class.js +0 -244
- package/SERVICES/ArgoCD/$service/$folder/$class/$service/handlers/pages/form/settings/$handler/class.js +0 -135
- package/SERVICES/ArgoCD/$service/class.js +0 -4
- package/SERVICES/ArgoCD/$service/readme.md +0 -63
- package/SERVICES/ArgoCD/PaaS/$service/$folder/$class/$service/class.js +0 -10
- package/SERVICES/ArgoCD/PaaS/$service/$folder/$class/$service/methods/checkDomain/$method/class.js +0 -33
- package/SERVICES/ArgoCD/PaaS/$service/$folder/$class/$service/methods/provision/$method/class.js +0 -225
- package/SERVICES/ArgoCD/PaaS/$service/$folder/$class/$service/methods/submitOrder/$method/class.js +0 -77
- package/SERVICES/ArgoCD/PaaS/$service/$folder/$class/$service/readme.md +0 -33
- package/SERVICES/ArgoCD/PaaS/$service/class.js +0 -347
- package/SERVICES/ArgoCD/PaaS/$service/order/pass.order +0 -9
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bitrix24 — интеграция с CRM и задачами «Битрикс24» через стандартный входящий вебхук.
|
|
3
|
+
*
|
|
4
|
+
* Настройка подключения:
|
|
5
|
+
* - Создайте в Битрикс24 («Разработчикам» -> «Другое» -> «Входящий вебхук») вебхук с правами `crm` и `task`;
|
|
6
|
+
* - Сохраните URL вебхука (`https://<портал>.bitrix24.ru/rest/<user>/<код>/`) в `#secret/bitrix24.json`
|
|
7
|
+
* (`{ "webhookUrl": "https://..." }`) или в поле `baseUrl` сервиса `/SERVICES/Bitrix24`.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
async function resolveBitrixWebhook(service) {
|
|
11
|
+
try {
|
|
12
|
+
const sec = await service.read_secret({ filename: 'bitrix24.json' });
|
|
13
|
+
if (sec?.webhookUrl || sec?.url)
|
|
14
|
+
return String(sec.webhookUrl || sec.url).trim().replace(/\/+$/, '');
|
|
15
|
+
}
|
|
16
|
+
catch { /* ignore */ }
|
|
17
|
+
const direct = String(service?.baseUrl || service?.DATA?.baseUrl || '').trim().replace(/\/+$/, '');
|
|
18
|
+
if (direct && /^https?:\/\/.+\/rest\//i.test(direct))
|
|
19
|
+
return direct;
|
|
20
|
+
return '';
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async function callBitrix(service, method, payload = {}) {
|
|
24
|
+
const webhook = await resolveBitrixWebhook(service);
|
|
25
|
+
if (!webhook) {
|
|
26
|
+
return {
|
|
27
|
+
notConfigured: true,
|
|
28
|
+
hint: 'Укажите URL входящего вебхука Битрикс24 (https://<портал>.bitrix24.ru/rest/<id>/<код>/) в #secret/bitrix24.json ({ "webhookUrl": "..." }) или в поле baseUrl сервиса /SERVICES/Bitrix24.',
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
const url = `${webhook}/${method}.json`;
|
|
32
|
+
const res = await fetch(url, {
|
|
33
|
+
method: 'POST',
|
|
34
|
+
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
|
35
|
+
body: JSON.stringify(payload),
|
|
36
|
+
signal: AbortSignal.timeout(15000),
|
|
37
|
+
});
|
|
38
|
+
const data = await res.json().catch(() => null);
|
|
39
|
+
if (!res.ok || data?.error) {
|
|
40
|
+
return { error: `Битрикс24 (${method}): ${data?.error_description || data?.error || ('HTTP ' + res.status)}` };
|
|
41
|
+
}
|
|
42
|
+
return data;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export default {
|
|
46
|
+
icon: 'carbon:collaborate',
|
|
47
|
+
label: 'Битрикс24 CRM',
|
|
48
|
+
description: 'Работа с лидами, сделками, клиентами и задачами в корпоративном портале Битрикс24 через входящий вебхук',
|
|
49
|
+
baseUrl: '',
|
|
50
|
+
capabilities: ['crm', 'bitrix24', 'leads', 'deals', 'tasks'],
|
|
51
|
+
enabled: true,
|
|
52
|
+
|
|
53
|
+
SCHEMA: {
|
|
54
|
+
list_deals: {
|
|
55
|
+
readonly: true,
|
|
56
|
+
description: 'Получить список сделок из CRM Битрикс24 (crm.deal.list) с суммами, стадиями и ответственными.',
|
|
57
|
+
params: {
|
|
58
|
+
type: 'object',
|
|
59
|
+
properties: {
|
|
60
|
+
stageId: { type: 'string', description: 'Фильтр по стадии сделки (STAGE_ID), если нужен' },
|
|
61
|
+
search: { type: 'string', description: 'Поиск по названию сделки (TITLE)' },
|
|
62
|
+
limit: { type: 'number', description: 'Максимум записей (по умолчанию 20)' },
|
|
63
|
+
},
|
|
64
|
+
},
|
|
65
|
+
},
|
|
66
|
+
list_leads: {
|
|
67
|
+
readonly: true,
|
|
68
|
+
description: 'Получить список лидов из CRM Битрикс24 (crm.lead.list).',
|
|
69
|
+
params: {
|
|
70
|
+
type: 'object',
|
|
71
|
+
properties: {
|
|
72
|
+
statusId: { type: 'string', description: 'Статус лида (STATUS_ID), например NEW, IN_PROCESS' },
|
|
73
|
+
search: { type: 'string', description: 'Поиск по названию или имени' },
|
|
74
|
+
limit: { type: 'number', description: 'Максимум записей (по умолчанию 20)' },
|
|
75
|
+
},
|
|
76
|
+
},
|
|
77
|
+
},
|
|
78
|
+
create_lead: {
|
|
79
|
+
readonly: false,
|
|
80
|
+
description: 'Создать новый лид в CRM Битрикс24 (crm.lead.add).',
|
|
81
|
+
params: {
|
|
82
|
+
type: 'object',
|
|
83
|
+
properties: {
|
|
84
|
+
title: { type: 'string', description: 'Название лида' },
|
|
85
|
+
name: { type: 'string', description: 'Имя контактного лица' },
|
|
86
|
+
phone: { type: 'string', description: 'Телефон клиента' },
|
|
87
|
+
email: { type: 'string', description: 'Email клиента' },
|
|
88
|
+
companyTitle: { type: 'string', description: 'Название компании клиента' },
|
|
89
|
+
opportunity: { type: 'number', description: 'Предполагаемая сумма сделки в рублях' },
|
|
90
|
+
comments: { type: 'string', description: 'Комментарий к лиду' },
|
|
91
|
+
},
|
|
92
|
+
required: ['title'],
|
|
93
|
+
},
|
|
94
|
+
},
|
|
95
|
+
create_task: {
|
|
96
|
+
readonly: false,
|
|
97
|
+
description: 'Поставить задачу сотруднику в Битрикс24 (tasks.task.add).',
|
|
98
|
+
params: {
|
|
99
|
+
type: 'object',
|
|
100
|
+
properties: {
|
|
101
|
+
title: { type: 'string', description: 'Название задачи' },
|
|
102
|
+
description: { type: 'string', description: 'Подробное описание задачи' },
|
|
103
|
+
responsibleId: { type: 'number', description: 'ID ответственного сотрудника в Битрикс24 (по умолчанию 1)' },
|
|
104
|
+
deadline: { type: 'string', description: 'Крайний срок YYYY-MM-DD' },
|
|
105
|
+
},
|
|
106
|
+
required: ['title'],
|
|
107
|
+
},
|
|
108
|
+
},
|
|
109
|
+
},
|
|
110
|
+
|
|
111
|
+
async list_deals(params = {}) {
|
|
112
|
+
const filter = {};
|
|
113
|
+
if (params.stageId) filter.STAGE_ID = String(params.stageId).trim();
|
|
114
|
+
if (params.search) filter['%TITLE'] = String(params.search).trim();
|
|
115
|
+
const limit = Math.min(Math.max(Number(params.limit) || 20, 1), 50);
|
|
116
|
+
const res = await callBitrix(this, 'crm.deal.list', {
|
|
117
|
+
order: { ID: 'DESC' },
|
|
118
|
+
filter,
|
|
119
|
+
select: ['ID', 'TITLE', 'STAGE_ID', 'OPPORTUNITY', 'CURRENCY_ID', 'COMPANY_ID', 'CONTACT_ID', 'ASSIGNED_BY_ID', 'DATE_CREATE'],
|
|
120
|
+
});
|
|
121
|
+
if (res?.notConfigured || res?.error)
|
|
122
|
+
return res;
|
|
123
|
+
const deals = Array.isArray(res?.result) ? res.result.slice(0, limit) : [];
|
|
124
|
+
return { source: 'Bitrix24', count: deals.length, total: res?.total ?? deals.length, deals };
|
|
125
|
+
},
|
|
126
|
+
|
|
127
|
+
async list_leads(params = {}) {
|
|
128
|
+
const filter = {};
|
|
129
|
+
if (params.statusId) filter.STATUS_ID = String(params.statusId).trim();
|
|
130
|
+
if (params.search) filter['%TITLE'] = String(params.search).trim();
|
|
131
|
+
const limit = Math.min(Math.max(Number(params.limit) || 20, 1), 50);
|
|
132
|
+
const res = await callBitrix(this, 'crm.lead.list', {
|
|
133
|
+
order: { ID: 'DESC' },
|
|
134
|
+
filter,
|
|
135
|
+
select: ['ID', 'TITLE', 'NAME', 'LAST_NAME', 'COMPANY_TITLE', 'STATUS_ID', 'OPPORTUNITY', 'CURRENCY_ID', 'DATE_CREATE'],
|
|
136
|
+
});
|
|
137
|
+
if (res?.notConfigured || res?.error)
|
|
138
|
+
return res;
|
|
139
|
+
const leads = Array.isArray(res?.result) ? res.result.slice(0, limit) : [];
|
|
140
|
+
return { source: 'Bitrix24', count: leads.length, total: res?.total ?? leads.length, leads };
|
|
141
|
+
},
|
|
142
|
+
|
|
143
|
+
async create_lead(params = {}) {
|
|
144
|
+
const title = String(params.title || '').trim();
|
|
145
|
+
if (!title)
|
|
146
|
+
return { error: 'create_lead: укажите название лида title' };
|
|
147
|
+
const fields = {
|
|
148
|
+
TITLE: title,
|
|
149
|
+
CURRENCY_ID: 'RUB',
|
|
150
|
+
};
|
|
151
|
+
if (params.name) fields.NAME = String(params.name).trim();
|
|
152
|
+
if (params.companyTitle) fields.COMPANY_TITLE = String(params.companyTitle).trim();
|
|
153
|
+
if (params.opportunity != null) fields.OPPORTUNITY = Number(params.opportunity) || 0;
|
|
154
|
+
if (params.comments) fields.COMMENTS = String(params.comments).trim();
|
|
155
|
+
if (params.phone) fields.PHONE = [{ VALUE: String(params.phone).trim(), VALUE_TYPE: 'WORK' }];
|
|
156
|
+
if (params.email) fields.EMAIL = [{ VALUE: String(params.email).trim(), VALUE_TYPE: 'WORK' }];
|
|
157
|
+
|
|
158
|
+
const res = await callBitrix(this, 'crm.lead.add', { fields });
|
|
159
|
+
if (res?.notConfigured || res?.error)
|
|
160
|
+
return res;
|
|
161
|
+
return { ok: true, leadId: res?.result, title };
|
|
162
|
+
},
|
|
163
|
+
|
|
164
|
+
async create_task(params = {}) {
|
|
165
|
+
const title = String(params.title || '').trim();
|
|
166
|
+
if (!title)
|
|
167
|
+
return { error: 'create_task: укажите название задачи title' };
|
|
168
|
+
const fields = {
|
|
169
|
+
TITLE: title,
|
|
170
|
+
DESCRIPTION: String(params.description || '').trim(),
|
|
171
|
+
RESPONSIBLE_ID: Number(params.responsibleId) || 1,
|
|
172
|
+
};
|
|
173
|
+
if (params.deadline)
|
|
174
|
+
fields.DEADLINE = String(params.deadline).trim();
|
|
175
|
+
const res = await callBitrix(this, 'tasks.task.add', { fields });
|
|
176
|
+
if (res?.notConfigured || res?.error)
|
|
177
|
+
return res;
|
|
178
|
+
return { ok: true, task: res?.result?.task || res?.result };
|
|
179
|
+
},
|
|
180
|
+
};
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CBR — официальные курсы валют, конвертация и ключевая ставка Банка России (ЦБ РФ).
|
|
3
|
+
*
|
|
4
|
+
* Работает сразу «из коробки» без ключей через официальные сервисы cbr.ru
|
|
5
|
+
* (XML_daily.asp / KeyRate) с резервным зеркалом cbr-xml-daily.ru.
|
|
6
|
+
*/
|
|
7
|
+
const CBR_XML_URL = 'https://www.cbr.ru/scripts/XML_daily.asp';
|
|
8
|
+
const CBR_DAILY_JSON_URL = 'https://www.cbr-xml-daily.ru/daily_json.js';
|
|
9
|
+
const CBR_MAIN_URL = 'https://www.cbr.ru/';
|
|
10
|
+
|
|
11
|
+
const POPULAR_CODES = ['USD', 'EUR', 'CNY', 'BYN', 'KZT', 'AED', 'TRY', 'GBP', 'CHF', 'JPY', 'INR'];
|
|
12
|
+
|
|
13
|
+
/** Форматирование даты YYYY-MM-DD или DD.MM.YYYY в формат ЦБ РФ DD/MM/YYYY */
|
|
14
|
+
function toCbrDateParam(raw = '') {
|
|
15
|
+
const s = String(raw || '').trim();
|
|
16
|
+
if (!s)
|
|
17
|
+
return '';
|
|
18
|
+
const iso = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s);
|
|
19
|
+
if (iso)
|
|
20
|
+
return `${iso[3]}/${iso[2]}/${iso[1]}`;
|
|
21
|
+
const ru = /^(\d{2})[./](\d{2})[./](\d{4})$/.exec(s);
|
|
22
|
+
if (ru)
|
|
23
|
+
return `${ru[1]}/${ru[2]}/${ru[3]}`;
|
|
24
|
+
return '';
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function xmlTag(block, tag) {
|
|
28
|
+
const m = String(block || '').match(new RegExp(`<${tag}[^>]*>([\\s\\S]*?)</${tag}>`, 'i'));
|
|
29
|
+
return m ? m[1].trim() : '';
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function parseCbrXml(xmlText = '') {
|
|
33
|
+
const dateMatch = /Date="([^"]+)"/i.exec(xmlText);
|
|
34
|
+
const rateDate = dateMatch ? dateMatch[1] : new Date().toISOString().slice(0, 10);
|
|
35
|
+
const rates = {};
|
|
36
|
+
const valuteRe = /<Valute\b[\s\S]*?<\/Valute>/gi;
|
|
37
|
+
let m;
|
|
38
|
+
while ((m = valuteRe.exec(xmlText))) {
|
|
39
|
+
const block = m[0];
|
|
40
|
+
const code = xmlTag(block, 'CharCode').toUpperCase();
|
|
41
|
+
if (!code)
|
|
42
|
+
continue;
|
|
43
|
+
const numCode = xmlTag(block, 'NumCode');
|
|
44
|
+
const nominal = Number(xmlTag(block, 'Nominal').replace(',', '.')) || 1;
|
|
45
|
+
const name = xmlTag(block, 'Name');
|
|
46
|
+
const value = Number(xmlTag(block, 'Value').replace(',', '.'));
|
|
47
|
+
if (!Number.isFinite(value) || value <= 0)
|
|
48
|
+
continue;
|
|
49
|
+
rates[code] = {
|
|
50
|
+
code,
|
|
51
|
+
numCode,
|
|
52
|
+
name,
|
|
53
|
+
nominal,
|
|
54
|
+
value,
|
|
55
|
+
unitRate: Number((value / nominal).toFixed(6)),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
return { date: rateDate, source: 'cbr.ru', rates };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function fetchCbrRates(dateStr = '') {
|
|
62
|
+
const dateReq = toCbrDateParam(dateStr);
|
|
63
|
+
const url = dateReq ? `${CBR_XML_URL}?date_req=${encodeURIComponent(dateReq)}` : CBR_XML_URL;
|
|
64
|
+
try {
|
|
65
|
+
const res = await fetch(url, {
|
|
66
|
+
headers: { 'User-Agent': 'Mozilla/5.0 ODANT-WORK/2.0', Accept: 'application/xml,text/xml,*/*' },
|
|
67
|
+
signal: AbortSignal.timeout(10000),
|
|
68
|
+
});
|
|
69
|
+
if (res.ok) {
|
|
70
|
+
const buf = Buffer.from(await res.arrayBuffer());
|
|
71
|
+
// ЦБ РФ отдаёт XML в windows-1251 или utf-8
|
|
72
|
+
let text = buf.toString('utf8');
|
|
73
|
+
if (/encoding=["']windows-1251["']/i.test(text)) {
|
|
74
|
+
try {
|
|
75
|
+
text = new TextDecoder('windows-1251').decode(buf);
|
|
76
|
+
}
|
|
77
|
+
catch { /* fallback utf8 */ }
|
|
78
|
+
}
|
|
79
|
+
const parsed = parseCbrXml(text);
|
|
80
|
+
if (Object.keys(parsed.rates).length > 0)
|
|
81
|
+
return parsed;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
catch { /* резервный JSON ниже */ }
|
|
85
|
+
|
|
86
|
+
if (!dateReq) {
|
|
87
|
+
const res = await fetch(CBR_DAILY_JSON_URL, {
|
|
88
|
+
headers: { Accept: 'application/json' },
|
|
89
|
+
signal: AbortSignal.timeout(10000),
|
|
90
|
+
});
|
|
91
|
+
if (res.ok) {
|
|
92
|
+
const data = await res.json();
|
|
93
|
+
const rates = {};
|
|
94
|
+
for (const [code, v] of Object.entries(data?.Valute || {})) {
|
|
95
|
+
const nominal = Number(v.Nominal) || 1;
|
|
96
|
+
const value = Number(v.Value) || 0;
|
|
97
|
+
rates[code] = {
|
|
98
|
+
code,
|
|
99
|
+
numCode: String(v.NumCode || ''),
|
|
100
|
+
name: String(v.Name || code),
|
|
101
|
+
nominal,
|
|
102
|
+
value,
|
|
103
|
+
previous: Number(v.Previous) || undefined,
|
|
104
|
+
unitRate: Number((value / nominal).toFixed(6)),
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
return {
|
|
108
|
+
date: String(data?.Date || '').slice(0, 10) || new Date().toISOString().slice(0, 10),
|
|
109
|
+
source: 'cbr-xml-daily.ru',
|
|
110
|
+
rates,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
throw new Error('Сервис курсов Банка России временно недоступен');
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export default {
|
|
118
|
+
icon: 'carbon:currency',
|
|
119
|
+
label: 'Банк России (ЦБ РФ)',
|
|
120
|
+
description: 'Официальные курсы валют ЦБ РФ на любую дату, валютный калькулятор и ключевая ставка Банка России',
|
|
121
|
+
baseUrl: 'https://www.cbr.ru',
|
|
122
|
+
capabilities: ['finance', 'currency', 'cbr'],
|
|
123
|
+
enabled: true,
|
|
124
|
+
|
|
125
|
+
SCHEMA: {
|
|
126
|
+
get_rates: {
|
|
127
|
+
readonly: true,
|
|
128
|
+
description: 'Официальные курсы валют Банка России (ЦБ РФ) в рублях на указанную дату. По умолчанию возвращает основные валюты (USD, EUR, CNY, BYN, KZT, AED, TRY и др.).',
|
|
129
|
+
params: {
|
|
130
|
+
type: 'object',
|
|
131
|
+
properties: {
|
|
132
|
+
date: { type: 'string', description: 'Дата курса в формате YYYY-MM-DD или DD.MM.YYYY (необязательно, по умолчанию — сегодня)' },
|
|
133
|
+
codes: { type: 'string', description: 'Коды валют через запятую, например "USD,EUR,CNY" (или "ALL" для всех валют ЦБ)' },
|
|
134
|
+
},
|
|
135
|
+
},
|
|
136
|
+
},
|
|
137
|
+
convert_currency: {
|
|
138
|
+
readonly: true,
|
|
139
|
+
description: 'Пересчёт суммы из одной валюты в другую (включая российский рубль RUB) строго по официальному курсу ЦБ РФ на указанную дату.',
|
|
140
|
+
params: {
|
|
141
|
+
type: 'object',
|
|
142
|
+
properties: {
|
|
143
|
+
amount: { type: 'number', description: 'Сумма для конвертации' },
|
|
144
|
+
from: { type: 'string', description: 'Исходная валюта (например USD, EUR, CNY, RUB)' },
|
|
145
|
+
to: { type: 'string', description: 'Целевая валюта (по умолчанию RUB)' },
|
|
146
|
+
date: { type: 'string', description: 'Дата курса YYYY-MM-DD (по умолчанию — сегодня)' },
|
|
147
|
+
},
|
|
148
|
+
required: ['amount', 'from'],
|
|
149
|
+
},
|
|
150
|
+
},
|
|
151
|
+
get_key_rate: {
|
|
152
|
+
readonly: true,
|
|
153
|
+
description: 'Получить действующую ключевую ставку Банка России (ЦБ РФ) для расчёта пеней (ст. 395 ГК РФ, 1/300 ставки), процентов и финансовых условий.',
|
|
154
|
+
params: {
|
|
155
|
+
type: 'object',
|
|
156
|
+
properties: {},
|
|
157
|
+
},
|
|
158
|
+
},
|
|
159
|
+
},
|
|
160
|
+
|
|
161
|
+
async get_rates(params = {}) {
|
|
162
|
+
try {
|
|
163
|
+
const data = await fetchCbrRates(params.date);
|
|
164
|
+
const rawCodes = String(params.codes || '').trim().toUpperCase();
|
|
165
|
+
const wantAll = rawCodes === 'ALL' || rawCodes === '*';
|
|
166
|
+
const codeList = (!rawCodes || wantAll)
|
|
167
|
+
? POPULAR_CODES
|
|
168
|
+
: rawCodes.split(/[\s,;]+/).filter(Boolean);
|
|
169
|
+
|
|
170
|
+
const selected = {};
|
|
171
|
+
if (wantAll) {
|
|
172
|
+
Object.assign(selected, data.rates);
|
|
173
|
+
}
|
|
174
|
+
else {
|
|
175
|
+
for (const c of codeList) {
|
|
176
|
+
if (c === 'RUB' || c === 'RUR') {
|
|
177
|
+
selected.RUB = { code: 'RUB', name: 'Российский рубль', nominal: 1, value: 1, unitRate: 1 };
|
|
178
|
+
}
|
|
179
|
+
else if (data.rates[c]) {
|
|
180
|
+
selected[c] = data.rates[c];
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return {
|
|
185
|
+
source: data.source,
|
|
186
|
+
date: data.date,
|
|
187
|
+
base: 'RUB',
|
|
188
|
+
count: Object.keys(selected).length,
|
|
189
|
+
rates: selected,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
catch (e) {
|
|
193
|
+
return { error: String(e?.message || e) };
|
|
194
|
+
}
|
|
195
|
+
},
|
|
196
|
+
|
|
197
|
+
async convert_currency(params = {}) {
|
|
198
|
+
const amount = Number(params.amount);
|
|
199
|
+
if (!Number.isFinite(amount))
|
|
200
|
+
return { error: 'convert_currency: укажите числовую сумму amount' };
|
|
201
|
+
const from = String(params.from || 'USD').trim().toUpperCase();
|
|
202
|
+
const to = String(params.to || 'RUB').trim().toUpperCase();
|
|
203
|
+
try {
|
|
204
|
+
const data = await fetchCbrRates(params.date);
|
|
205
|
+
const getRubRate = (code) => {
|
|
206
|
+
if (code === 'RUB' || code === 'RUR')
|
|
207
|
+
return 1;
|
|
208
|
+
const item = data.rates[code];
|
|
209
|
+
if (!item)
|
|
210
|
+
throw new Error(`Валюта «${code}» не найдена в котировках ЦБ РФ`);
|
|
211
|
+
return item.unitRate;
|
|
212
|
+
};
|
|
213
|
+
const fromRub = getRubRate(from);
|
|
214
|
+
const toRub = getRubRate(to);
|
|
215
|
+
const amountInRub = amount * fromRub;
|
|
216
|
+
const result = amountInRub / toRub;
|
|
217
|
+
return {
|
|
218
|
+
source: data.source,
|
|
219
|
+
date: data.date,
|
|
220
|
+
amount,
|
|
221
|
+
from,
|
|
222
|
+
to,
|
|
223
|
+
rateFromRub: Number(fromRub.toFixed(6)),
|
|
224
|
+
rateToRub: Number(toRub.toFixed(6)),
|
|
225
|
+
crossRate: Number((fromRub / toRub).toFixed(6)),
|
|
226
|
+
result: Number(result.toFixed(2)),
|
|
227
|
+
amountInRub: Number(amountInRub.toFixed(2)),
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
catch (e) {
|
|
231
|
+
return { error: String(e?.message || e) };
|
|
232
|
+
}
|
|
233
|
+
},
|
|
234
|
+
|
|
235
|
+
async get_key_rate() {
|
|
236
|
+
try {
|
|
237
|
+
const res = await fetch(CBR_MAIN_URL, {
|
|
238
|
+
headers: { 'User-Agent': 'Mozilla/5.0 ODANT-WORK/2.0', Accept: 'text/html' },
|
|
239
|
+
signal: AbortSignal.timeout(10000),
|
|
240
|
+
});
|
|
241
|
+
if (res.ok) {
|
|
242
|
+
const html = await res.text();
|
|
243
|
+
const m = /Ключевая ставка[\s\S]{0,400}?(\d{1,2}[,.]\d{1,2})\s*%/i.exec(html);
|
|
244
|
+
if (m) {
|
|
245
|
+
const rate = Number(m[1].replace(',', '.'));
|
|
246
|
+
return {
|
|
247
|
+
source: 'cbr.ru',
|
|
248
|
+
keyRatePercent: rate,
|
|
249
|
+
dailyPenalty1300: Number((rate / 300).toFixed(5)),
|
|
250
|
+
date: new Date().toISOString().slice(0, 10),
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
catch { /* fallback */ }
|
|
256
|
+
return {
|
|
257
|
+
source: 'cbr.ru (справочно)',
|
|
258
|
+
keyRatePercent: 21.0,
|
|
259
|
+
dailyPenalty1300: Number((21.0 / 300).toFixed(5)),
|
|
260
|
+
note: 'Для онлайн-сверки проверьте доступ сервера к cbr.ru',
|
|
261
|
+
};
|
|
262
|
+
},
|
|
263
|
+
};
|