Add znzt module
Deploy Manager App / deploy (push) Successful in 19s
Details
Deploy Manager App / deploy (push) Successful in 19s
Details
This commit is contained in:
parent
9609841692
commit
9701eb0b3f
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
67
src/App.tsx
67
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<string | null>(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 <ErrorScreen message={authError} onLogout={handleLogout} />;
|
||||
}
|
||||
const token = localStorage.getItem('token');
|
||||
|
||||
return (
|
||||
<div className="relative min-h-screen bg-gray-100">
|
||||
<div className="absolute top-4 right-4 z-50">
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="bg-red-600 hover:bg-red-700 text-white text-sm font-medium py-2 px-4 rounded-lg shadow transition-colors cursor-pointer"
|
||||
>
|
||||
🚪 Выйти из аккаунта
|
||||
</button>
|
||||
</div>
|
||||
<AppShell
|
||||
header={{ height: 60 }}
|
||||
padding="md"
|
||||
>
|
||||
<AppShell.Header>
|
||||
<Group h="100%" px="md" justify="space-between">
|
||||
<Title order={3}>Управление заказами</Title>
|
||||
{token && (
|
||||
<Button
|
||||
variant="light"
|
||||
color="red"
|
||||
rightSection={<IconLogout size={16} />}
|
||||
onClick={handleLogout}
|
||||
>
|
||||
Выйти
|
||||
</Button>
|
||||
)}
|
||||
</Group>
|
||||
</AppShell.Header>
|
||||
|
||||
<main>
|
||||
<OrdersPage onError={(msg) => setAuthError(msg)} />
|
||||
</main>
|
||||
</div>
|
||||
<AppShell.Main display="flex" style={{ flexDirection: 'column', height: '100vh' }}>
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/" element={<OrdersPage onError={() => navigate('/login')} />} />
|
||||
</Routes>
|
||||
</AppShell.Main>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
14
src/main.tsx
14
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(
|
||||
<React.StrictMode>
|
||||
<BrowserRouter>
|
||||
{/* Обязательно оборачиваем приложение в MantineProvider */}
|
||||
<MantineProvider defaultColorScheme="light">
|
||||
<Notifications />
|
||||
<App />
|
||||
<ModalsProvider>
|
||||
<Notifications position="top-right" />
|
||||
<App />
|
||||
</ModalsProvider>
|
||||
</MantineProvider>
|
||||
</BrowserRouter>
|
||||
</React.StrictMode>,
|
||||
|
|
|
|||
|
|
@ -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<string>(initialValue !== null && initialValue !== undefined ? String(initialValue) : '');
|
||||
|
||||
export default function OrdersPage({ onError }: OrdersPageProps) {
|
||||
useEffect(() => {
|
||||
setVal(initialValue !== null && initialValue !== undefined ? String(initialValue) : '');
|
||||
}, [initialValue]);
|
||||
|
||||
return (
|
||||
<input
|
||||
type="number"
|
||||
disabled={disabled}
|
||||
value={val}
|
||||
min={0}
|
||||
onChange={(e) => 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<FrontendOrderMatrix | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [pageError, setPageError] = useState<string | null>(null)
|
||||
const [editableOrders, setEditableOrders] = useState<Record<string, MonthlyOrderClient>>({})
|
||||
const isMobile = useMediaQuery('(max-width: 768px)')
|
||||
const [activeClientName, setActiveClientName] = useState<string | null>(null)
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
|
||||
const loadData = async (preserveActive = false) => {
|
||||
const tableContainerRef = useRef<HTMLDivElement>(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<string, MonthlyOrderClient> = {}
|
||||
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 <LoadingOverlay visible />
|
||||
if (pageError) {
|
||||
return (
|
||||
<Box p="xl" ta="center">
|
||||
<Text c="red" fw={500} mb="md">{pageError}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (!data) return <Text ta="center" mt="xl">Нет данных</Text>
|
||||
if (!data) return <Text ta="center">Нет данных</Text>
|
||||
|
||||
return (
|
||||
<Box p={{ base: 'xs', md: 'md' }} maw={1600} mx="auto">
|
||||
<Group justify="space-between" mb="lg">
|
||||
<div>
|
||||
<Title order={2} size="h3">Заказ товаров на месяц</Title>
|
||||
{data.settings?.deadline_date && (
|
||||
<Text size="xs" c="dimmed">
|
||||
Дедлайн: {new Date(data.settings.deadline_date).toLocaleString()}
|
||||
</Text>
|
||||
)}
|
||||
</div>
|
||||
<Box display="flex" style={{ flexDirection: 'column', flexGrow: 1, overflow: 'hidden' }}>
|
||||
<Group justify="space-between" mb="md">
|
||||
<Group>
|
||||
{data.is_locked ? (
|
||||
<Badge color="red" size="md" leftSection={<IconLock size={12} />}>
|
||||
Прием закрыт
|
||||
</Badge>
|
||||
) : (
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
loading={saving}
|
||||
size="sm"
|
||||
leftSection={<IconDeviceFloppy size={16} />}
|
||||
>
|
||||
Сохранить
|
||||
</Button>
|
||||
)}
|
||||
<TextInput
|
||||
placeholder="Поиск по номенклатуре..."
|
||||
leftSection={<IconSearch size={16} />}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.currentTarget.value)}
|
||||
w={300}
|
||||
/>
|
||||
<Badge color="gray" variant="light">Показано строк: {filteredNom.length}</Badge>
|
||||
</Group>
|
||||
|
||||
{data.is_locked ? (
|
||||
<Badge color="red" size="lg" leftSection={<IconLock size={14} />}>Прием закрыт</Badge>
|
||||
) : (
|
||||
<Button onClick={handleSave} loading={saving} leftSection={<IconDeviceFloppy size={16} />}>
|
||||
Сохранить в базу
|
||||
</Button>
|
||||
)}
|
||||
</Group>
|
||||
|
||||
{isMobile ? (
|
||||
<Stack gap="md">
|
||||
<Select
|
||||
label="Выберите клиента"
|
||||
data={data.clients?.map(c => c.google_data.name) || []}
|
||||
value={activeClientName}
|
||||
onChange={setActiveClientName}
|
||||
/>
|
||||
{activeClientName && (
|
||||
<ClientCardView
|
||||
clientName={activeClientName}
|
||||
nomenclatures={data.nomenclatures || []}
|
||||
editableOrders={editableOrders}
|
||||
setEditableOrders={setEditableOrders}
|
||||
handleQuantityChange={handleQuantityChange}
|
||||
handleParamsChange={handleParamsChange}
|
||||
getClientParams={getClientParams}
|
||||
isLocked={data.is_locked}
|
||||
/>
|
||||
)}
|
||||
</Stack>
|
||||
) : (
|
||||
<Paper withBorder style={{ overflowX: 'auto', maxHeight: '75vh' }}>
|
||||
<Table stickyHeader striped highlightOnHover>
|
||||
{/* Контейнер таблицы, занимающий всё свободное место */}
|
||||
<Paper withBorder shadow="sm" style={{ flexGrow: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
|
||||
<div ref={tableContainerRef} style={{ overflow: 'auto', flexGrow: 1 }}>
|
||||
<Table stickyHeader striped highlightOnHover style={{ tableLayout: 'fixed', minWidth: 'max-content' }}>
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th style={{ minWidth: 220, position: 'sticky', left: 0, background: 'var(--mantine-color-body)', zIndex: 2 }}>
|
||||
<Table.Th w={300} style={{ position: 'sticky', left: 0, zIndex: 3, background: 'var(--mantine-color-body)' }}>
|
||||
Номенклатура
|
||||
</Table.Th>
|
||||
{data.clients?.map(c => (
|
||||
<Table.Th key={c.google_data.name} style={{ minWidth: 280, textAlign: 'center', verticalAlign: 'top' }}>
|
||||
{c.google_data.name}
|
||||
<BlockMeta
|
||||
clientName={c.google_data.name}
|
||||
editableOrders={editableOrders}
|
||||
handleParamsChange={handleParamsChange}
|
||||
getClientParams={getClientParams}
|
||||
isLocked={data.is_locked}
|
||||
/>
|
||||
<Table.Th key={c.google_data.name} w={180} style={{ textAlign: 'center' }}>
|
||||
<Group justify="center" gap={4} wrap="nowrap">
|
||||
<Text size="sm" fw={600} truncate>{c.google_data.name}</Text>
|
||||
<ClientSettingsPopover
|
||||
clientName={c.google_data.name}
|
||||
order={editableOrders[c.google_data.name]}
|
||||
updateClientMeta={updateClientMeta}
|
||||
isLocked={data.is_locked}
|
||||
/>
|
||||
</Group>
|
||||
</Table.Th>
|
||||
))}
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
<Table.Tbody>
|
||||
{data.nomenclatures?.map(nom => (
|
||||
<MemoizedTableRow
|
||||
key={nom.name}
|
||||
nom={nom}
|
||||
clients={data.clients}
|
||||
editableOrders={editableOrders}
|
||||
isLocked={data.is_locked}
|
||||
handleQuantityChange={handleQuantityChange}
|
||||
/>
|
||||
))}
|
||||
{/* Виртуальные отступы сверху */}
|
||||
{rowVirtualizer.getVirtualItems().length > 0 && (
|
||||
<tr><td colSpan={data.clients.length + 1} style={{ height: rowVirtualizer.getVirtualItems()[0].start }} /></tr>
|
||||
)}
|
||||
|
||||
{/* Виртуализированные строки */}
|
||||
{rowVirtualizer.getVirtualItems().map(virtualRow => {
|
||||
const nom = filteredNom[virtualRow.index];
|
||||
return (
|
||||
<Table.Tr key={nom.name}>
|
||||
<Table.Td style={{ position: 'sticky', left: 0, background: 'var(--mantine-color-body)', zIndex: 1, borderRight: '1px solid var(--mantine-color-gray-3)' }}>
|
||||
<Text size="sm" fw={500} lineClamp={1} title={nom.name}>{nom.name}</Text>
|
||||
<Text size="xs" c="dimmed">{nom.type}</Text>
|
||||
</Table.Td>
|
||||
{data.clients.map(c => {
|
||||
const clientName = c.google_data.name;
|
||||
const item = editableOrders[clientName]?.items?.find(i => i.nomenclature_name === nom.name);
|
||||
return (
|
||||
<Table.Td key={clientName} align="center">
|
||||
<CellInput
|
||||
initialValue={item?.quantity || null}
|
||||
disabled={data.is_locked}
|
||||
onCommit={(val) => handleQuantityChange(clientName, nom, val)}
|
||||
/>
|
||||
</Table.Td>
|
||||
)
|
||||
})}
|
||||
</Table.Tr>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* Виртуальные отступы снизу */}
|
||||
{rowVirtualizer.getVirtualItems().length > 0 && (
|
||||
<tr>
|
||||
<td colSpan={data.clients.length + 1} style={{ height: rowVirtualizer.getTotalSize() - rowVirtualizer.getVirtualItems()[rowVirtualizer.getVirtualItems().length - 1].end }} />
|
||||
</tr>
|
||||
)}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
</Paper>
|
||||
)}
|
||||
</div>
|
||||
</Paper>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
// Мемоизированная строка таблицы
|
||||
interface MemoizedTableRowProps {
|
||||
nom: NomenclatureItem;
|
||||
clients: any[];
|
||||
editableOrders: Record<string, MonthlyOrderClient>;
|
||||
isLocked: boolean;
|
||||
handleQuantityChange: (clientName: string, nomName: string, nomType: string, qty: number | null) => void;
|
||||
}
|
||||
|
||||
const MemoizedTableRow = React.memo(({ nom, clients, editableOrders, isLocked, handleQuantityChange }: MemoizedTableRowProps) => {
|
||||
// Выпадающее меню параметров клиента для компактности заголовка
|
||||
function ClientSettingsPopover({ clientName, order, updateClientMeta, isLocked }: any) {
|
||||
return (
|
||||
<Table.Tr>
|
||||
<Table.Td style={{ position: 'sticky', left: 0, background: 'var(--mantine-color-body)', fontWeight: 500, zIndex: 1 }}>
|
||||
{nom.name} <Text span size="xs" c="dimmed">({nom.type})</Text>
|
||||
</Table.Td>
|
||||
{clients.map(c => {
|
||||
const clientName = c.google_data.name
|
||||
const order = editableOrders[clientName]
|
||||
const item = order?.items?.find(i => i.nomenclature_name === nom.name)
|
||||
const qty = item && item.quantity !== null ? item.quantity : ''
|
||||
return (
|
||||
<Table.Td key={clientName} align="center">
|
||||
<input
|
||||
type="number"
|
||||
disabled={isLocked}
|
||||
value={qty}
|
||||
min={0}
|
||||
onChange={(e) => {
|
||||
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'
|
||||
}}
|
||||
/>
|
||||
</Table.Td>
|
||||
)
|
||||
})}
|
||||
</Table.Tr>
|
||||
);
|
||||
});
|
||||
|
||||
// Компонент с MultiSelect для всех параметров
|
||||
interface BlockMetaProps {
|
||||
clientName: string
|
||||
editableOrders: Record<string, MonthlyOrderClient>
|
||||
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 (
|
||||
<Stack gap={4} mt={8}>
|
||||
<MultiSelect
|
||||
disabled={isLocked}
|
||||
data={selectData}
|
||||
value={currentValue}
|
||||
onChange={(values) => handleParamsChange(clientName, values)}
|
||||
placeholder="Выберите параметры"
|
||||
size="xs"
|
||||
comboboxProps={{ width: 300 }}
|
||||
maxDropdownHeight={400}
|
||||
clearable={false}
|
||||
renderOption={({ option, checked }) => (
|
||||
<Group gap="sm" justify="flex-start">
|
||||
<CheckIcon style={{ opacity: checked ? 1 : 0 }} />
|
||||
<Text size="xs">{option.label}</Text>
|
||||
<Popover width={300} position="bottom" withArrow shadow="md">
|
||||
<Popover.Target>
|
||||
<ActionIcon variant="subtle" color="gray" size="sm">
|
||||
<IconSettings size={14} />
|
||||
</ActionIcon>
|
||||
</Popover.Target>
|
||||
<Popover.Dropdown>
|
||||
<Title order={6} mb="sm">Настройки: {clientName}</Title>
|
||||
<Stack gap="xs">
|
||||
<Group grow>
|
||||
<Select label="Декада" size="xs" disabled={isLocked} data={['1-я', '2-я', '3-я', 'Склад', 'Клиент']} value={order?.decade || '1-я'} onChange={v => updateClientMeta(clientName, 'decade', v)} />
|
||||
<Select label="Доставка" size="xs" disabled={isLocked} data={['Предоплата', 'Отсрочка']} value={order?.delivery || 'Предоплата'} onChange={v => updateClientMeta(clientName, 'delivery', v)} />
|
||||
</Group>
|
||||
)}
|
||||
/>
|
||||
<Textarea
|
||||
disabled={isLocked}
|
||||
size="xs"
|
||||
placeholder="Комментарий (обязательно)"
|
||||
value={order.manager_comment || ''}
|
||||
onChange={(e) => {
|
||||
const newOrders = { ...editableOrders };
|
||||
if (!newOrders[clientName]) {
|
||||
newOrders[clientName] = {
|
||||
client_name: clientName,
|
||||
items: [],
|
||||
decade: '1-я',
|
||||
delivery: 'Предоплата',
|
||||
payment_form: 'Ф1-Ф1',
|
||||
conditions: 'Стандарт',
|
||||
};
|
||||
}
|
||||
newOrders[clientName] = { ...newOrders[clientName], manager_comment: e.currentTarget.value };
|
||||
// Используем прямой setState чтобы избежать циклических обновлений
|
||||
// В реальном коде лучше использовать useCallback
|
||||
}}
|
||||
autosize
|
||||
minRows={1}
|
||||
/>
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
||||
// Для мобильной версии
|
||||
interface ClientCardViewProps {
|
||||
clientName: string
|
||||
nomenclatures: NomenclatureItem[]
|
||||
editableOrders: Record<string, MonthlyOrderClient>
|
||||
setEditableOrders: React.Dispatch<React.SetStateAction<Record<string, MonthlyOrderClient>>>
|
||||
handleQuantityChange: (clientName: string, nomName: string, nomType: string, qty: number | null) => void
|
||||
handleParamsChange: (clientName: string, values: string[]) => void
|
||||
getClientParams: (clientName: string) => string[]
|
||||
isLocked: boolean
|
||||
}
|
||||
|
||||
function ClientCardView({
|
||||
clientName,
|
||||
nomenclatures,
|
||||
editableOrders,
|
||||
setEditableOrders,
|
||||
handleQuantityChange,
|
||||
handleParamsChange,
|
||||
getClientParams,
|
||||
isLocked
|
||||
}: ClientCardViewProps) {
|
||||
const order = editableOrders[clientName] || {}
|
||||
const currentValue = getClientParams(clientName)
|
||||
|
||||
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 (
|
||||
<Card withBorder padding="md" radius="md">
|
||||
<Text fw={700} size="lg" mb="sm">{clientName}</Text>
|
||||
<Stack gap="sm" mb="md">
|
||||
<MultiSelect
|
||||
disabled={isLocked}
|
||||
data={selectData}
|
||||
value={currentValue}
|
||||
onChange={(values) => handleParamsChange(clientName, values)}
|
||||
placeholder="Выберите параметры"
|
||||
size="sm"
|
||||
label="Параметры заказа"
|
||||
renderOption={({ option, checked }) => (
|
||||
<Group gap="sm" justify="flex-start">
|
||||
<CheckIcon style={{ opacity: checked ? 1 : 0 }} />
|
||||
<Text size="sm">{option.label}</Text>
|
||||
</Group>
|
||||
)}
|
||||
/>
|
||||
<Textarea
|
||||
disabled={isLocked}
|
||||
label="Комментарий менеджера"
|
||||
placeholder="Укажите комментарий или причину отсутствия заказа..."
|
||||
value={order.manager_comment || ''}
|
||||
onChange={(e) => setEditableOrders((prev) => ({
|
||||
...prev,
|
||||
[clientName]: { ...prev[clientName], manager_comment: e.currentTarget.value }
|
||||
}))}
|
||||
required
|
||||
/>
|
||||
</Stack>
|
||||
<Divider mb="md" label="Номенклатура товаров" labelPosition="center" />
|
||||
<Stack gap="xs">
|
||||
{nomenclatures.map((nom) => {
|
||||
const item = order?.items?.find((i) => i.nomenclature_name === nom.name)
|
||||
const qty = item && item.quantity !== null ? item.quantity : ''
|
||||
return (
|
||||
<Group key={nom.name} justify="space-between" align="center">
|
||||
<Box style={{ flex: 1 }}>
|
||||
<Text size="sm" fw={500}>{nom.name}</Text>
|
||||
<Text size="xs" c="dimmed">{nom.type}</Text>
|
||||
</Box>
|
||||
<input
|
||||
type="number"
|
||||
disabled={isLocked}
|
||||
value={qty}
|
||||
min={0}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
handleQuantityChange(
|
||||
clientName,
|
||||
nom.name,
|
||||
nom.type,
|
||||
val === '' ? null : Number(val)
|
||||
);
|
||||
}}
|
||||
style={{
|
||||
width: '80px',
|
||||
textAlign: 'center',
|
||||
padding: '6px',
|
||||
borderRadius: '4px',
|
||||
border: '1px solid #ced4da',
|
||||
backgroundColor: isLocked ? '#f1f3f5' : '#fff'
|
||||
}}
|
||||
/>
|
||||
</Group>
|
||||
)
|
||||
})}
|
||||
</Stack>
|
||||
</Card>
|
||||
<Group grow>
|
||||
<Select label="Условия" size="xs" disabled={isLocked} data={['Стандарт', 'Спец. условия', 'Акция']} value={order?.conditions || 'Стандарт'} onChange={v => updateClientMeta(clientName, 'conditions', v)} />
|
||||
<Select label="Оплата" size="xs" disabled={isLocked} data={['Ф1-Ф1', 'Ф1-Ф2', 'Ф2-Ф1', 'Ф2-Ф2']} value={order?.payment_form || 'Ф1-Ф1'} onChange={v => updateClientMeta(clientName, 'payment_form', v)} />
|
||||
</Group>
|
||||
<Textarea
|
||||
label="Комментарий (Обязательно при заказе)"
|
||||
size="xs"
|
||||
disabled={isLocked}
|
||||
value={order?.manager_comment || ''}
|
||||
onChange={e => updateClientMeta(clientName, 'manager_comment', e.currentTarget.value)}
|
||||
/>
|
||||
</Stack>
|
||||
</Popover.Dropdown>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
Loading…
Reference in New Issue