Compare commits
4 Commits
ea02e8b019
...
f10e69f964
| Author | SHA1 | Date |
|---|---|---|
|
|
f10e69f964 | |
|
|
052d42faeb | |
|
|
6b5f3f9496 | |
|
|
0b25a1d932 |
2
.env
2
.env
|
|
@ -1,5 +1,5 @@
|
|||
# API Configuration
|
||||
#VITE_API_BASE_URL=http://localhost:1726/api
|
||||
VITE_API_BASE_URL=https://api.ruspet-preforma.ru:45373/api
|
||||
VITE_API_KEY=test
|
||||
VITE_API_PUBLIC_KEY=ruspet_public_key_2026
|
||||
VITE_API_PRIVATE_KEY=ruspet_private_key_SUPER_SECRET_2026
|
||||
|
|
|
|||
|
|
@ -0,0 +1,146 @@
|
|||
const BALANCER_URL = 'https://72.56.235.246.nip.io/balancer/api/balancer/send';
|
||||
const BALANCER_PUBLIC = '68929830b9a07e7c6fa1d4bdfbcafe798a50de4da2969e743fee690dfaec3fb4';
|
||||
const BALANCER_PRIVATE = '89bab1c15544e7bb667b773df786e65f9aed0bf173a84e66e2a88aec3f0014d89a289807c34f71c876b79f67997c9ac281ffd19d00fe8582ebcda97660bddaa3';
|
||||
const BITRIX_WEBHOOK = 'https://thebest.bitrix24.ru/rest/{USER}/{METHOD_ID}/';
|
||||
|
||||
function generateBalancerSignature_(timestampStr) {
|
||||
const message = `${BALANCER_PUBLIC}:${timestampStr}`;
|
||||
const signature = Utilities.computeHmacSha256Signature(message, BALANCER_PRIVATE);
|
||||
return signature.map(b => ('0' + (b & 0xFF).toString(16)).slice(-2)).join('');
|
||||
}
|
||||
|
||||
// ── Балансировщик: одиночный запрос
|
||||
// Используется для get, update, add, delete и любых методов
|
||||
// которые не возвращают next (не список).
|
||||
function balancerPost_(method, body) {
|
||||
const timestamp = Math.floor(Date.now() / 1000).toString();
|
||||
|
||||
const payload = {
|
||||
url: BITRIX_WEBHOOK + method + '.json',
|
||||
method: 'POST',
|
||||
body: body || {},
|
||||
};
|
||||
|
||||
const options = {
|
||||
method: 'post',
|
||||
contentType: 'application/json',
|
||||
headers: {
|
||||
'X-Timestamp': timestamp,
|
||||
'X-Signature': generateBalancerSignature_(timestamp),
|
||||
},
|
||||
payload: JSON.stringify(payload),
|
||||
muteHttpExceptions: true,
|
||||
};
|
||||
|
||||
let attempt = 0;
|
||||
const maxRetries = 5;
|
||||
const baseRetryMs = 1000;
|
||||
const limitWaitMs = 5000;
|
||||
|
||||
while (attempt <= maxRetries) {
|
||||
let res, data;
|
||||
try {
|
||||
res = UrlFetchApp.fetch(BALANCER_URL, options);
|
||||
const httpCode = res.getResponseCode();
|
||||
const rawText = res.getContentText();
|
||||
|
||||
if (httpCode === 401) throw new Error(`Балансировщик: ошибка авторизации — ${rawText}. Проверьте BALANCER_PUBLIC / BALANCER_PRIVATE`);
|
||||
if (httpCode === 500) throw new Error(`Балансировщик: внутренняя ошибка — ${rawText}`);
|
||||
if (httpCode !== 200) throw new Error(`Балансировщик: HTTP ${httpCode} — ${rawText}`);
|
||||
|
||||
data = JSON.parse(rawText);
|
||||
} catch (e) {
|
||||
attempt++;
|
||||
const wait = baseRetryMs * attempt;
|
||||
Logger.log(`⚠️ balancerPost_ сетевая ошибка (попытка ${attempt}): ${e} — ждём ${wait}ms`);
|
||||
if (attempt > maxRetries) throw new Error(`Сетевая ошибка после ${maxRetries} попыток: ${e}`);
|
||||
Utilities.sleep(wait);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (res.getResponseCode() !== 200) {
|
||||
attempt++;
|
||||
const wait = baseRetryMs * attempt;
|
||||
Logger.log(`🔴 balancerPost_ HTTP ${res.getResponseCode()} (попытка ${attempt}) — ждём ${wait}ms`);
|
||||
if (attempt > maxRetries) throw new Error(`balancer HTTP ${res.getResponseCode()}`);
|
||||
Utilities.sleep(wait);
|
||||
continue;
|
||||
}
|
||||
|
||||
const bitrixBody = data?.body;
|
||||
const errCode = bitrixBody?.error;
|
||||
|
||||
if (errCode === 'QUERY_LIMIT_EXCEEDED') {
|
||||
attempt++;
|
||||
const wait = limitWaitMs * attempt;
|
||||
Logger.log(`🚦 QUERY_LIMIT_EXCEEDED (попытка ${attempt}) — ждём ${wait}ms`);
|
||||
if (attempt > maxRetries) throw new Error('QUERY_LIMIT_EXCEEDED: превышен лимит');
|
||||
Utilities.sleep(wait);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (errCode === 'INTERNAL_SERVER_ERROR') {
|
||||
attempt++;
|
||||
const wait = baseRetryMs * attempt;
|
||||
Logger.log(`🔴 INTERNAL_SERVER_ERROR (попытка ${attempt}) — ждём ${wait}ms`);
|
||||
if (attempt > maxRetries) throw new Error('INTERNAL_SERVER_ERROR после нескольких попыток');
|
||||
Utilities.sleep(wait);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (errCode) {
|
||||
throw new Error(`Битрикс API [${method}]: ${errCode} — ${bitrixBody?.error_description || ''}`);
|
||||
}
|
||||
|
||||
Logger.log(`🟢 balancerPost_ [${method}] OK`);
|
||||
|
||||
return bitrixBody;
|
||||
}
|
||||
|
||||
throw new Error('balancerPost_: исчерпаны все попытки');
|
||||
}
|
||||
|
||||
// Выполняет рекуррентный запрос через балансировщик.
|
||||
// Балансировщик сам крутит пагинацию и возвращает все записи одним массивом.
|
||||
function balancerRecurrentPost_(method, body, resultKey) {
|
||||
const timestamp = Math.floor(Date.now() / 1000).toString();
|
||||
|
||||
const payload = {
|
||||
url: BITRIX_WEBHOOK + method + '.json',
|
||||
method: 'POST',
|
||||
is_recurrent: true,
|
||||
result_key: resultKey || null,
|
||||
body: body,
|
||||
};
|
||||
|
||||
const options = {
|
||||
method: 'post',
|
||||
contentType: 'application/json',
|
||||
headers: {
|
||||
'X-Timestamp': timestamp,
|
||||
'X-Signature': generateBalancerSignature_(timestamp),
|
||||
},
|
||||
payload: JSON.stringify(payload),
|
||||
muteHttpExceptions: true,
|
||||
};
|
||||
|
||||
const sig = generateBalancerSignature_(timestamp);
|
||||
Logger.log('Timestamp: ' + timestamp);
|
||||
Logger.log('Signature: ' + sig);
|
||||
Logger.log('Message: ' + BALANCER_PUBLIC + ':' + timestamp);
|
||||
|
||||
res = UrlFetchApp.fetch(BALANCER_URL, options);
|
||||
const httpCode = res.getResponseCode();
|
||||
const rawText = res.getContentText();
|
||||
|
||||
if (httpCode === 401) throw new Error(`Балансировщик: ошибка авторизации — ${rawText}. Проверьте BALANCER_PUBLIC / BALANCER_PRIVATE`);
|
||||
if (httpCode === 500) throw new Error(`Балансировщик: внутренняя ошибка — ${rawText}`);
|
||||
if (httpCode !== 200) throw new Error(`Балансировщик: HTTP ${httpCode} — ${rawText}`);
|
||||
|
||||
data = JSON.parse(rawText);
|
||||
|
||||
if (data.error) throw new Error(`balancer error [${method}]: ${JSON.stringify(data.error)}`);
|
||||
|
||||
// Возвращает { body: [...], total_fetched: N, quota_left: N }
|
||||
return data.body || [];
|
||||
}
|
||||
|
|
@ -64,7 +64,7 @@ function getCorrectedTimestamp(): string {
|
|||
}
|
||||
|
||||
const apiClient = axios.create({
|
||||
baseURL: '/api',
|
||||
baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import axios from 'axios'
|
|||
|
||||
// Изолированный клиент ТОЛЬКО для сервера менеджеров
|
||||
const managerApiClient = axios.create({
|
||||
baseURL: 'https://37.252.5.229.nip.io/tg-api/api',
|
||||
baseURL: 'https://38.180.230.177.nip.io/tg-api/api',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': 'supersecretkey',
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import axios from 'axios'
|
||||
|
||||
const publicApiClient = axios.create({
|
||||
baseURL: '/api',
|
||||
baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import axios from 'axios'
|
||||
|
||||
const waApiClient = axios.create({
|
||||
baseURL: 'https://37.252.5.229.nip.io/wa-api/api',
|
||||
baseURL: 'https://38.180.230.177.nip.io/wa-api/api',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': 'supersecretkey',
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { useEffect } from 'react'
|
||||
import { Box, Button, Group, NumberInput, Paper, Stack, Title, Text } from '@mantine/core'
|
||||
import { Box, Button, Group, NumberInput, Paper, Stack, Title, Text, Select, Textarea } from '@mantine/core'
|
||||
import { DateTimePicker } from '@mantine/dates'
|
||||
import { useForm } from '@mantine/form'
|
||||
import { useMonthlyOrderSettings, useSaveMonthlyOrderSettings } from '@/features/monthlyOrders/hooks/useMonthlyOrderSettings'
|
||||
|
|
@ -9,6 +9,8 @@ import { IconDeviceFloppy } from '@tabler/icons-react'
|
|||
interface SettingsFormValues {
|
||||
deadline_date: Date | null
|
||||
assembly_time_days: number
|
||||
market_stage: string | null
|
||||
market_stage_comment: string
|
||||
}
|
||||
|
||||
export default function MonthlyOrdersSettingsPage() {
|
||||
|
|
@ -19,6 +21,8 @@ export default function MonthlyOrdersSettingsPage() {
|
|||
initialValues: {
|
||||
deadline_date: null,
|
||||
assembly_time_days: 3,
|
||||
market_stage: null,
|
||||
market_stage_comment: '',
|
||||
},
|
||||
validate: {
|
||||
deadline_date: (value) => (!value ? 'Укажите граничную дату и время' : null),
|
||||
|
|
@ -31,6 +35,8 @@ export default function MonthlyOrdersSettingsPage() {
|
|||
form.setValues({
|
||||
deadline_date: currentSettings.deadline_date ? new Date(currentSettings.deadline_date) : null,
|
||||
assembly_time_days: currentSettings.assembly_time_days || 3,
|
||||
market_stage: currentSettings.market_stage || null,
|
||||
market_stage_comment: currentSettings.market_stage_comment || '',
|
||||
})
|
||||
}
|
||||
}, [currentSettings])
|
||||
|
|
@ -39,6 +45,8 @@ export default function MonthlyOrdersSettingsPage() {
|
|||
saveSettings({
|
||||
deadline_date: values.deadline_date ? dayjs(values.deadline_date).format() : null,
|
||||
assembly_time_days: values.assembly_time_days,
|
||||
market_stage: values.market_stage,
|
||||
market_stage_comment: values.market_stage_comment,
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -56,14 +64,34 @@ export default function MonthlyOrdersSettingsPage() {
|
|||
</Text>
|
||||
|
||||
<DateTimePicker
|
||||
label="Граничная дата и время (Дедлайн)"
|
||||
description="После этого времени менеджеры не смогут редактировать заказы, и они отправятся на согласование."
|
||||
label="Крайняя дата и время"
|
||||
description="После этого времени менеджеры не смогут редактировать заказы на месяц и они отправятся на согласование."
|
||||
placeholder="Выберите дату и время"
|
||||
valueFormat="DD.MM.YYYY HH:mm"
|
||||
withSeconds={false}
|
||||
{...form.getInputProps('deadline_date')}
|
||||
/>
|
||||
|
||||
<Select
|
||||
label="Стадия рынка"
|
||||
placeholder="Выберите текущую стадию"
|
||||
data={[
|
||||
{ value: 'растущий', label: 'Растущий' },
|
||||
{ value: 'падающий', label: 'Падающий' },
|
||||
{ value: 'стоячий', label: 'Стоячий' },
|
||||
]}
|
||||
clearable
|
||||
{...form.getInputProps('market_stage')}
|
||||
/>
|
||||
|
||||
<Textarea
|
||||
label="Комментарий к стадии рынка"
|
||||
placeholder="Опишите подробности текущей ситуации на рынке"
|
||||
minRows={3}
|
||||
autosize
|
||||
{...form.getInputProps('market_stage_comment')}
|
||||
/>
|
||||
|
||||
<Group justify="flex-end" mt="md">
|
||||
<Button
|
||||
type="submit"
|
||||
|
|
|
|||
|
|
@ -354,6 +354,8 @@ export interface MonthlyOrderSetting {
|
|||
year?: number
|
||||
deadline_date: string | null
|
||||
assembly_time_days: number
|
||||
market_stage?: string | null
|
||||
market_stage_comment?: string | null
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
Loading…
Reference in New Issue