From 9701eb0b3f5810d16441554c3a95e706611d8568 Mon Sep 17 00:00:00 2001 From: romanskijdev Date: Wed, 26 Aug 2026 10:17:27 +0300 Subject: [PATCH] Add znzt module --- package-lock.json | 13 + package.json | 1 + src/App.tsx | 67 ++-- src/api/client.ts | 4 +- src/main.tsx | 14 +- src/pages/OrdersPage.tsx | 644 +++++++++++++-------------------------- 6 files changed, 282 insertions(+), 461 deletions(-) diff --git a/package-lock.json b/package-lock.json index 9638c7f..3c4ca76 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,7 @@ "@mantine/dates": "^9.5.2", "@mantine/form": "^9.5.2", "@mantine/hooks": "^9.5.2", + "@mantine/modals": "^9.5.2", "@mantine/notifications": "^9.5.2", "@tabler/icons-react": "^3.46.0", "@tanstack/react-virtual": "^3.14.10", @@ -641,6 +642,18 @@ "react": "^19.2.0" } }, + "node_modules/@mantine/modals": { + "version": "9.5.2", + "resolved": "https://registry.npmjs.org/@mantine/modals/-/modals-9.5.2.tgz", + "integrity": "sha512-mB+A9uk6U/1+e9khNCWrblE4cvrYA3H5eKp7iuz1KE472HXWp+A4h50Wb2WcN0FDIEU7+bTHWa167LUA/5jXwA==", + "license": "MIT", + "peerDependencies": { + "@mantine/core": "9.5.2", + "@mantine/hooks": "9.5.2", + "react": "^19.2.0", + "react-dom": "^19.2.0" + } + }, "node_modules/@mantine/notifications": { "version": "9.5.2", "resolved": "https://registry.npmjs.org/@mantine/notifications/-/notifications-9.5.2.tgz", diff --git a/package.json b/package.json index 4732cb8..4e4782c 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "@mantine/dates": "^9.5.2", "@mantine/form": "^9.5.2", "@mantine/hooks": "^9.5.2", + "@mantine/modals": "^9.5.2", "@mantine/notifications": "^9.5.2", "@tabler/icons-react": "^3.46.0", "@tanstack/react-virtual": "^3.14.10", diff --git a/src/App.tsx b/src/App.tsx index 2a77472..8a41120 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,35 +1,56 @@ -import { useState } from 'react'; -import { ErrorScreen } from './components/ErrorScreen'; +import { Routes, Route, useNavigate } from 'react-router-dom'; +import { AppShell, Button, Group, Title } from '@mantine/core'; +import { modals } from '@mantine/modals'; +import { IconLogout } from '@tabler/icons-react'; import OrdersPage from './pages/OrdersPage'; +import Login from './pages/Login'; export function App() { - const [authError, setAuthError] = useState(null); + const navigate = useNavigate(); const handleLogout = () => { - localStorage.clear(); - sessionStorage.clear(); - window.location.href = '/'; + modals.openConfirmModal({ + title: 'Подтверждение выхода', + children: 'Вы уверены, что хотите выйти? Несохраненные данные могут быть потеряны.', + labels: { confirm: 'Выйти', cancel: 'Отмена' }, + confirmProps: { color: 'red' }, + onConfirm: () => { + localStorage.clear(); + sessionStorage.clear(); + navigate('/login'); // 👈 Правильный SPA-редирект + }, + }); }; - // Если возникла критическая ошибка доступа — показываем экран с кнопкой выхода - if (authError) { - return ; - } + const token = localStorage.getItem('token'); return ( -
-
- -
+ + + + Управление заказами + {token && ( + + )} + + -
- setAuthError(msg)} /> -
-
+ + + } /> + navigate('/login')} />} /> + + + ); } \ No newline at end of file diff --git a/src/api/client.ts b/src/api/client.ts index 561b2f6..8ee4216 100644 --- a/src/api/client.ts +++ b/src/api/client.ts @@ -52,10 +52,8 @@ apiClient.interceptors.response.use( const errorDesc = error.response?.data?.error_description || ''; if (error.response?.status === 401 || errorDesc.includes('Telegram') || errorDesc.includes('аккаунт не привязан')) { - // Принудительно очищаем токен, чтобы приложение сбросило авторизацию localStorage.removeItem('token'); - // Можно сразу перенаправить на корень или страницу входа - window.location.href = '/'; + window.location.href = '/login'; // 👈 Направляем именно на страницу логина } return Promise.reject(error); } diff --git a/src/main.tsx b/src/main.tsx index 831e14a..4da7e7a 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -1,9 +1,10 @@ import React from 'react' import ReactDOM from 'react-dom/client' import { BrowserRouter } from 'react-router-dom' -import { MantineProvider } from '@mantine/core' // 👈 Импортируем провайдер -import '@mantine/core/styles.css' // 👈 Обязательно подключаем стили Mantine! -import { Notifications } from '@mantine/notifications' // если используете нотификации +import { MantineProvider } from '@mantine/core' +import { Notifications } from '@mantine/notifications' +import { ModalsProvider } from '@mantine/modals' +import '@mantine/core/styles.css' import '@mantine/notifications/styles.css' import { App } from './App'; @@ -11,10 +12,11 @@ import { App } from './App'; ReactDOM.createRoot(document.getElementById('root')!).render( - {/* Обязательно оборачиваем приложение в MantineProvider */} - - + + + + , diff --git a/src/pages/OrdersPage.tsx b/src/pages/OrdersPage.tsx index 2ce1684..1402128 100644 --- a/src/pages/OrdersPage.tsx +++ b/src/pages/OrdersPage.tsx @@ -1,495 +1,281 @@ -import React, { useState, useEffect, useCallback } from 'react' +import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react' import { - Box, Table, Title, Text, Paper, Stack, Button, Group, - MultiSelect, Textarea, Badge, LoadingOverlay, Card, Divider, - CheckIcon, Select + Box, Table, Title, Text, Paper, Button, Group, Badge, + LoadingOverlay, Select, TextInput, Popover, ActionIcon, Stack, Textarea } from '@mantine/core' -import { useMediaQuery } from '@mantine/hooks' import { notifications } from '@mantine/notifications' -import { IconDeviceFloppy, IconLock } from '@tabler/icons-react' -import type { FrontendOrderMatrix, MonthlyOrderClient, NomenclatureItem } from "../types/orders.ts"; -import { monthlyOrdersApi } from "../api/monthlyOrders.ts"; +import { IconDeviceFloppy, IconLock, IconSettings, IconSearch } from '@tabler/icons-react' +import { useVirtualizer } from '@tanstack/react-virtual' +import { monthlyOrdersApi } from "../api/monthlyOrders.ts" +import type { FrontendOrderMatrix, MonthlyOrderClient, NomenclatureItem } from "../types/orders.ts" -// Константы для селекторов -const DECADE_OPTIONS = ['1-я', '2-я', '3-я', 'Склад', 'Клиент']; -const DELIVERY_OPTIONS = ['Предоплата', 'Отсрочка']; -const CONDITIONS_OPTIONS = ['Стандарт', 'Спец. условия', 'Акция']; -const PAYMENT_OPTIONS = ['Ф1-Ф1', 'Ф1-Ф2', 'Ф2-Ф1', 'Ф2-Ф2']; +const DRAFT_KEY = 'orders_matrix_draft'; -interface OrdersPageProps { - onError: (msg: string) => void; -} +// --- Локализованный инпут для мгновенного ввода без лагов всей таблицы --- +const CellInput = React.memo(({ initialValue, disabled, onCommit }: { initialValue: number | null, disabled: boolean, onCommit: (val: number | null) => void }) => { + const [val, setVal] = useState(initialValue !== null && initialValue !== undefined ? String(initialValue) : ''); -export default function OrdersPage({ onError }: OrdersPageProps) { + useEffect(() => { + setVal(initialValue !== null && initialValue !== undefined ? String(initialValue) : ''); + }, [initialValue]); + + return ( + setVal(e.target.value)} + onBlur={() => { + const num = val.trim() === '' ? null : Number(val); + if (num !== initialValue) onCommit(num); + }} + style={{ + width: '60px', textAlign: 'center', padding: '6px', + borderRadius: '4px', border: '1px solid #ced4da', + backgroundColor: disabled ? '#f1f3f5' : '#fff' + }} + /> + ) +}) + +export default function OrdersPage({ onError }: { onError: (msg: string) => void }) { const [data, setData] = useState(null) const [loading, setLoading] = useState(true) const [saving, setSaving] = useState(false) - const [pageError, setPageError] = useState(null) const [editableOrders, setEditableOrders] = useState>({}) - const isMobile = useMediaQuery('(max-width: 768px)') - const [activeClientName, setActiveClientName] = useState(null) + const [searchQuery, setSearchQuery] = useState(''); - const loadData = async (preserveActive = false) => { + const tableContainerRef = useRef(null); + + const loadData = async () => { try { setLoading(true) - setPageError(null) const res = await monthlyOrdersApi.getMatrix() const matrix = res.data setData(matrix) - if (matrix && matrix.clients) { + + if (matrix?.clients) { const initialMap: Record = {} - matrix.clients.forEach((c, idx) => { + matrix.clients.forEach(c => { const clientName = c.google_data.name - if (!preserveActive && idx === 0) { - setActiveClientName(clientName) - } - if (c.db_order) { - initialMap[clientName] = { ...c.db_order } - } else { - initialMap[clientName] = { - client_name: clientName, - items: [], - manager_comment: '', - decade: '1-я', - delivery: 'Предоплата', - payment_form: 'Ф1-Ф1', - conditions: 'Стандарт', - } + initialMap[clientName] = c.db_order || { + client_name: clientName, items: [], manager_comment: '', + decade: '1-я', delivery: 'Предоплата', payment_form: 'Ф1-Ф1', conditions: 'Стандарт', } }) - setEditableOrders(initialMap) + + // Восстановление черновика из localStorage + const draft = localStorage.getItem(DRAFT_KEY); + if (draft && !matrix.is_locked) { + try { + const parsedDraft = JSON.parse(draft); + setEditableOrders({ ...initialMap, ...parsedDraft }); + notifications.show({ title: 'Черновик восстановлен', message: 'Загружены несохраненные данные', color: 'blue' }); + } catch (e) { + setEditableOrders(initialMap); + } + } else { + setEditableOrders(initialMap) + } } } catch (err: any) { - const errorDesc = err.response?.data?.error_description || err.response?.data?.message || 'Не удалось загрузить данные заказов'; - setPageError(errorDesc); - onError(errorDesc); + onError(err.response?.data?.error_description || 'Ошибка загрузки'); } finally { setLoading(false) } } + useEffect(() => { loadData() }, []) + + // Автосохранение черновика при изменении данных useEffect(() => { - loadData(false) - }, []) - - const handleQuantityChange = useCallback((clientName: string, nomName: string, nomType: string, qty: number | null) => { - setEditableOrders(prev => { - const currentOrder = prev[clientName] || { client_name: clientName, items: [] } - const items = [...(currentOrder.items || [])] - const existingIndex = items.findIndex(i => i.nomenclature_name === nomName) - if (existingIndex >= 0) { - if (qty === null || qty === 0) { - items.splice(existingIndex, 1) - } else { - items[existingIndex].quantity = qty - } - } else if (qty !== null && qty > 0) { - items.push({ nomenclature_name: nomName, nomenclature_type: nomType, quantity: qty }) - } - return { - ...prev, - [clientName]: { ...currentOrder, items } - } - }) - }, []) - - // Обработка выбора параметров из MultiSelect - const handleParamsChange = useCallback((clientName: string, values: string[]) => { - setEditableOrders(prev => { - const currentOrder = prev[clientName] || { - client_name: clientName, - items: [], - decade: '1-я', - delivery: 'Предоплата', - payment_form: 'Ф1-Ф1', - conditions: 'Стандарт', - } - - // Разбираем выбранные значения по категориям - const newDecade = values.find(v => DECADE_OPTIONS.includes(v)) || currentOrder.decade; - const newDelivery = values.find(v => DELIVERY_OPTIONS.includes(v)) || currentOrder.delivery; - const newConditions = values.find(v => CONDITIONS_OPTIONS.includes(v)) || currentOrder.conditions; - const newPayment = values.find(v => PAYMENT_OPTIONS.includes(v)) || currentOrder.payment_form; - - return { - ...prev, - [clientName]: { - ...currentOrder, - decade: newDecade, - delivery: newDelivery, - conditions: newConditions, - payment_form: newPayment, - } - } - }) - }, []) - - // Получаем текущие значения для клиента - const getClientParams = useCallback((clientName: string): string[] => { - const order = editableOrders[clientName]; - if (!order) return ['1-я', 'Предоплата', 'Стандарт', 'Ф1-Ф1']; - - const params: string[] = []; - if (order.decade) params.push(order.decade); - if (order.delivery) params.push(order.delivery); - if (order.conditions) params.push(order.conditions); - if (order.payment_form) params.push(order.payment_form); - - return params; - }, [editableOrders]); - - const validateBeforeSave = (): boolean => { - for (const [clientName, order] of Object.entries(editableOrders)) { - const hasItems = order.items && order.items.length > 0 - if (hasItems && (!order.manager_comment || order.manager_comment.trim() === '')) { - notifications.show({ - title: 'Внимание', - message: `Для клиента "${clientName}" указан заказ, но не заполнен обязательный комментарий!`, - color: 'yellow' - }) - return false - } + if (Object.keys(editableOrders).length > 0 && data && !data.is_locked) { + localStorage.setItem(DRAFT_KEY, JSON.stringify(editableOrders)); } - return true - } + }, [editableOrders, data]); + + const handleQuantityChange = useCallback((clientName: string, nom: NomenclatureItem, qty: number | null) => { + setEditableOrders(prev => { + const currentOrder = prev[clientName]; + const items = [...(currentOrder.items || [])]; + const existingIndex = items.findIndex(i => i.nomenclature_name === nom.name); + + if (existingIndex >= 0) { + if (qty === null || qty === 0) items.splice(existingIndex, 1); + else items[existingIndex].quantity = qty; + } else if (qty !== null && qty > 0) { + items.push({ nomenclature_name: nom.name, nomenclature_type: nom.type, quantity: qty }); + } + return { ...prev, [clientName]: { ...currentOrder, items } }; + }) + }, []); + + const updateClientMeta = useCallback((clientName: string, field: keyof MonthlyOrderClient, value: string) => { + setEditableOrders(prev => ({ + ...prev, [clientName]: { ...prev[clientName], [field]: value } + })) + }, []); const handleSave = async () => { - if (!validateBeforeSave()) return + // Валидация + for (const [clientName, order] of Object.entries(editableOrders)) { + if (order.items && order.items.length > 0 && !order.manager_comment?.trim()) { + return notifications.show({ title: 'Внимание', message: `Укажите комментарий для клиента "${clientName}"!`, color: 'yellow' }) + } + } try { setSaving(true) - const ordersArray = Object.values(editableOrders) - await monthlyOrdersApi.saveOrders(ordersArray) - notifications.show({ title: 'Успешно', message: 'Изменения сохранены', color: 'green' }) - loadData(true) + await monthlyOrdersApi.saveOrders(Object.values(editableOrders)) + localStorage.removeItem(DRAFT_KEY); // Очищаем черновик после успеха + notifications.show({ title: 'Успешно', message: 'Заказы сохранены', color: 'green' }) + loadData() } catch { - notifications.show({ title: 'Ошибка', message: 'Не удалось сохранить заказы', color: 'red' }) + notifications.show({ title: 'Ошибка', message: 'Сбой при сохранении', color: 'red' }) } finally { setSaving(false) } } + // Фильтрация номенклатуры + const filteredNom = useMemo(() => { + if (!data?.nomenclatures) return []; + return data.nomenclatures.filter(n => n.name.toLowerCase().includes(searchQuery.toLowerCase())); + }, [data?.nomenclatures, searchQuery]); + + // Настройка виртуализации + const rowVirtualizer = useVirtualizer({ + count: filteredNom.length, + getScrollElement: () => tableContainerRef.current, + estimateSize: () => 45, + overscan: 15, + }); + if (loading) return - if (pageError) { - return ( - - {pageError} - - ); - } - if (!data) return Нет данных + if (!data) return Нет данных return ( - - -
- Заказ товаров на месяц - {data.settings?.deadline_date && ( - - Дедлайн: {new Date(data.settings.deadline_date).toLocaleString()} - - )} -
+ + - {data.is_locked ? ( - }> - Прием закрыт - - ) : ( - - )} + } + value={searchQuery} + onChange={(e) => setSearchQuery(e.currentTarget.value)} + w={300} + /> + Показано строк: {filteredNom.length} + + {data.is_locked ? ( + }>Прием закрыт + ) : ( + + )} - {isMobile ? ( - - { - const val = e.target.value; - handleQuantityChange( - clientName, - nom.name, - nom.type, - val === '' ? null : Number(val) - ); - }} - style={{ - width: '70px', - textAlign: 'center', - padding: '4px', - borderRadius: '4px', - border: '1px solid #ced4da', - backgroundColor: isLocked ? '#f1f3f5' : '#fff' - }} - /> - - ) - })} - - ); -}); - -// Компонент с MultiSelect для всех параметров -interface BlockMetaProps { - clientName: string - editableOrders: Record - handleParamsChange: (clientName: string, values: string[]) => void - getClientParams: (clientName: string) => string[] - isLocked: boolean -} - -function BlockMeta({ clientName, editableOrders, handleParamsChange, getClientParams, isLocked }: BlockMetaProps) { - const order = editableOrders[clientName] || {} - const currentValue = getClientParams(clientName) - - // Создаем данные для MultiSelect с группировкой - const selectData = [ - { group: 'Декада', items: DECADE_OPTIONS.map(opt => ({ value: opt, label: opt })) }, - { group: 'Доставка', items: DELIVERY_OPTIONS.map(opt => ({ value: opt, label: opt })) }, - { group: 'Условия', items: CONDITIONS_OPTIONS.map(opt => ({ value: opt, label: opt })) }, - { group: 'Оплата', items: PAYMENT_OPTIONS.map(opt => ({ value: opt, label: opt })) }, - ]; - - return ( - - handleParamsChange(clientName, values)} - placeholder="Выберите параметры" - size="xs" - comboboxProps={{ width: 300 }} - maxDropdownHeight={400} - clearable={false} - renderOption={({ option, checked }) => ( - - - {option.label} + + + + + + + + Настройки: {clientName} + + + updateClientMeta(clientName, 'delivery', v)} /> - )} - /> -