790 lines
42 KiB
TypeScript
790 lines
42 KiB
TypeScript
import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react'
|
||
import {
|
||
Box, Table, Title, Text, Paper, Button, Group, Badge,
|
||
LoadingOverlay, Select, TextInput, HoverCard, ActionIcon, Stack, Textarea, Checkbox, ScrollArea
|
||
} from '@mantine/core'
|
||
import { notifications } from '@mantine/notifications'
|
||
import { modals } from '@mantine/modals'
|
||
import {
|
||
IconDeviceFloppy, IconSettings, IconSearch,
|
||
IconFilter, IconUserSearch, IconRefresh, IconArrowLeft,
|
||
IconPaperclip, IconSend, IconInfoCircle
|
||
} from '@tabler/icons-react'
|
||
import { useVirtualizer } from '@tanstack/react-virtual'
|
||
import { useNavigate, useParams } from 'react-router-dom'
|
||
import { monthlyOrdersApi } from "../api/monthlyOrders.ts"
|
||
import type { FrontendOrderMatrix, MonthlyOrderClient, NomenclatureItem } from "../types/orders.ts"
|
||
|
||
const DRAFT_KEY = 'orders_matrix_draft';
|
||
const DRAFT_TIME_KEY = 'orders_matrix_draft_time';
|
||
|
||
// Вспомогательная функция для конвертации File в Base64
|
||
const toBase64 = (file: File) => new Promise<string>((resolve, reject) => {
|
||
const reader = new FileReader();
|
||
reader.readAsDataURL(file);
|
||
reader.onload = () => resolve(reader.result as string);
|
||
reader.onerror = error => reject(error);
|
||
});
|
||
|
||
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) : '');
|
||
|
||
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 [editableOrders, setEditableOrders] = useState<Record<string, MonthlyOrderClient>>({})
|
||
const [draftSavedAt, setDraftSavedAt] = useState<Date | null>(null);
|
||
|
||
// Фильтры
|
||
const [searchQuery, setSearchQuery] = useState('');
|
||
const [selectedType, setSelectedType] = useState<string | null>(null);
|
||
const [clientSearchQuery, setClientSearchQuery] = useState('');
|
||
const [selectedBranch, setSelectedBranch] = useState<string | null>(null);
|
||
const [showOnlyWithOrders, setShowOnlyWithOrders] = useState(false);
|
||
const [showOnlyWithoutOrders, setShowOnlyWithoutOrders] = useState(false);
|
||
const [hideEmptyRows, setHideEmptyRows] = useState(false);
|
||
|
||
const tableContainerRef = useRef<HTMLDivElement>(null);
|
||
|
||
// Логика Аналитика
|
||
const navigate = useNavigate();
|
||
const { id } = useParams();
|
||
const targetManagerId = id ? Number(id) : undefined;
|
||
const isReadOnly = !!targetManagerId;
|
||
|
||
const loadData = async (ignoreDraft = false) => {
|
||
try {
|
||
setLoading(true)
|
||
const res = await monthlyOrdersApi.getMatrix(targetManagerId)
|
||
const matrix = res.data
|
||
setData(matrix)
|
||
|
||
if (matrix?.clients) {
|
||
const initialMap: Record<string, MonthlyOrderClient> = {}
|
||
matrix.clients.forEach(c => {
|
||
const clientName = c.google_data.name
|
||
if (c.db_order) {
|
||
c.db_order.items = c.db_order.items || [];
|
||
initialMap[clientName] = c.db_order;
|
||
} else {
|
||
initialMap[clientName] = {
|
||
client_name: clientName, items: [], manager_comment: '',
|
||
decade: null, delivery: null, payment_form: null, conditions: null,
|
||
}
|
||
}
|
||
})
|
||
|
||
const draft = localStorage.getItem(DRAFT_KEY);
|
||
const draftTime = localStorage.getItem(DRAFT_TIME_KEY);
|
||
|
||
if (draft && !matrix.is_locked && !ignoreDraft && !isReadOnly) {
|
||
try {
|
||
const parsedDraft = JSON.parse(draft);
|
||
setEditableOrders({ ...initialMap, ...parsedDraft });
|
||
if (draftTime) setDraftSavedAt(new Date(draftTime));
|
||
notifications.show({ title: 'Черновик восстановлен', message: 'Загружены локальные изменения', color: 'blue' });
|
||
} catch (e) {
|
||
setEditableOrders(initialMap);
|
||
}
|
||
} else {
|
||
setEditableOrders(initialMap)
|
||
}
|
||
}
|
||
} catch (err: any) {
|
||
const errorMsg = err.response?.data?.error_description || 'Ошибка загрузки';
|
||
if (errorMsg.includes('аналитику необходимо передать manager_id')) {
|
||
navigate('/analyst');
|
||
return;
|
||
}
|
||
onError(errorMsg);
|
||
} finally {
|
||
setLoading(false)
|
||
}
|
||
}
|
||
|
||
useEffect(() => { loadData() }, [targetManagerId])
|
||
|
||
const isSupplementaryMode = data?.is_locked === true;
|
||
const inputsDisabled = isReadOnly;
|
||
|
||
useEffect(() => {
|
||
if (loading || saving || isReadOnly) return;
|
||
|
||
if (Object.keys(editableOrders).length > 0 && data && !data.is_locked) {
|
||
localStorage.setItem(DRAFT_KEY, JSON.stringify(editableOrders));
|
||
const now = new Date();
|
||
localStorage.setItem(DRAFT_TIME_KEY, now.toISOString());
|
||
setDraftSavedAt(now);
|
||
}
|
||
}, [editableOrders, data, loading, saving, isReadOnly]);
|
||
|
||
const handleQuantityChange = useCallback((clientName: string, nom: NomenclatureItem, qty: number | null) => {
|
||
if (inputsDisabled) return;
|
||
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 } };
|
||
})
|
||
}, [inputsDisabled]);
|
||
|
||
const updateClientMeta = useCallback((clientName: string, field: keyof MonthlyOrderClient, value: string | null) => {
|
||
if (inputsDisabled) return;
|
||
setEditableOrders(prev => ({
|
||
...prev, [clientName]: { ...prev[clientName], [field]: value }
|
||
}))
|
||
}, [inputsDisabled]);
|
||
|
||
const handleFilesChange = async (clientName: string, event: React.ChangeEvent<HTMLInputElement>) => {
|
||
const files = event.target.files;
|
||
if (!files || files.length === 0) return;
|
||
|
||
const newFiles: { file_name: string; file_base64: string }[] = [];
|
||
|
||
for (let i = 0; i < files.length; i++) {
|
||
const file = files[i];
|
||
const base64 = await toBase64(file);
|
||
const base64Data = base64.split(',')[1] || base64;
|
||
newFiles.push({ file_name: file.name, file_base64: base64Data });
|
||
}
|
||
|
||
setEditableOrders(prev => {
|
||
const currentOrder = prev[clientName] || {};
|
||
const existingFiles = currentOrder.files || [];
|
||
return {
|
||
...prev,
|
||
[clientName]: {
|
||
...currentOrder,
|
||
files: [...existingFiles, ...newFiles]
|
||
}
|
||
};
|
||
});
|
||
|
||
notifications.show({
|
||
title: 'Файлы добавлены',
|
||
message: `Прикреплено новых скринов: ${newFiles.length}`,
|
||
color: 'blue'
|
||
});
|
||
|
||
event.target.value = '';
|
||
};
|
||
|
||
const handleSave = async () => {
|
||
if (inputsDisabled) return;
|
||
|
||
for (const [clientName, order] of Object.entries(editableOrders)) {
|
||
if (!order.manager_comment || order.manager_comment.trim() === '') {
|
||
return notifications.show({
|
||
title: 'Внимание',
|
||
message: `Комментарий обязателен для клиента "${clientName}"!`,
|
||
color: 'yellow'
|
||
});
|
||
}
|
||
|
||
const hasItems = order.items && order.items.some(i => i.quantity && i.quantity > 0);
|
||
|
||
if (hasItems) {
|
||
const missingMeta = [];
|
||
if (!order.decade) missingMeta.push('Декада');
|
||
if (!order.delivery) missingMeta.push('Доставка');
|
||
if (!order.conditions) missingMeta.push('Условия');
|
||
if (!order.payment_form) missingMeta.push('Оплата');
|
||
|
||
if (missingMeta.length > 0) {
|
||
return notifications.show({
|
||
title: 'Неполные данные заказа',
|
||
message: `Для клиента "${clientName}" указан заказ, но не заполнены поля: ${missingMeta.join(', ')}. Настройте их через иконку шестеренки в шапке таблицы.`,
|
||
color: 'red',
|
||
autoClose: 7000
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
try {
|
||
setSaving(true);
|
||
await monthlyOrdersApi.saveOrders(Object.values(editableOrders));
|
||
localStorage.removeItem(DRAFT_KEY);
|
||
localStorage.removeItem(DRAFT_TIME_KEY);
|
||
setDraftSavedAt(null);
|
||
|
||
notifications.show({ title: 'Успешно', message: 'Заказы сохранены', color: 'green' });
|
||
loadData(true);
|
||
} catch {
|
||
notifications.show({ title: 'Ошибка', message: 'Сбой при сохранении', color: 'red' });
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
const handleSendSupplementary = () => {
|
||
const ordersToSend = Object.values(editableOrders).filter(o => o.items && o.items.some(i => i.quantity && i.quantity > 0));
|
||
|
||
if (ordersToSend.length === 0) {
|
||
return notifications.show({ title: 'Пусто', message: 'Вы не добавили ни одного товара для доп. заказа', color: 'yellow' });
|
||
}
|
||
|
||
for (const order of ordersToSend) {
|
||
if (!order.manager_comment || order.manager_comment.trim() === '') {
|
||
return notifications.show({
|
||
title: 'Внимание',
|
||
message: `Для отправки доп. заказа клиенту "${order.client_name}" обязателен комментарий!`,
|
||
color: 'yellow'
|
||
});
|
||
}
|
||
|
||
const missingMeta = [];
|
||
if (!order.decade) missingMeta.push('Декада');
|
||
if (!order.delivery) missingMeta.push('Доставка');
|
||
if (!order.conditions) missingMeta.push('Условия');
|
||
if (!order.payment_form) missingMeta.push('Оплата');
|
||
|
||
if (missingMeta.length > 0) {
|
||
return notifications.show({
|
||
title: 'Неполные данные',
|
||
message: `У клиента "${order.client_name}" не заполнены поля: ${missingMeta.join(', ')}`,
|
||
color: 'red',
|
||
autoClose: 7000
|
||
});
|
||
}
|
||
}
|
||
|
||
modals.openConfirmModal({
|
||
title: 'Отправка дополнительных заказов',
|
||
size: 'lg',
|
||
children: (
|
||
<Stack>
|
||
<Text c="red" fw={500} size="sm">
|
||
Внимание! После отправки ваши текущие черновики будут полностью очищены.
|
||
Заявки будут отправлены на согласование по каждому клиенту отдельно.
|
||
</Text>
|
||
|
||
<Text fw={600}>К отправке:</Text>
|
||
<ScrollArea h={350} offsetScrollbars>
|
||
{ordersToSend.map(o => (
|
||
<Paper key={o.client_name} withBorder p="sm" mb="sm" bg="gray.0">
|
||
<Text fw={700} size="sm">{o.client_name}</Text>
|
||
<Group gap="xs" mt={4} mb="xs">
|
||
<Badge size="xs" variant="outline">{o.decade}</Badge>
|
||
<Badge size="xs" variant="outline">{o.delivery}</Badge>
|
||
<Badge size="xs" variant="outline">{o.payment_form}</Badge>
|
||
<Badge size="xs" variant="outline">{o.conditions}</Badge>
|
||
</Group>
|
||
<Text size="sm"><b>Комментарий:</b> {o.manager_comment}</Text>
|
||
<Text size="sm" mt="xs" fw={600}>Номенклатура:</Text>
|
||
<ul style={{ margin: 0, paddingLeft: 20, fontSize: 13 }}>
|
||
{o.items?.filter(i => i.quantity && i.quantity > 0).map(i => (
|
||
<li key={i.nomenclature_name}>{i.nomenclature_name} — {i.quantity} шт.</li>
|
||
))}
|
||
</ul>
|
||
</Paper>
|
||
))}
|
||
</ScrollArea>
|
||
</Stack>
|
||
),
|
||
labels: { confirm: 'Отправить на согласование', cancel: 'Отмена' },
|
||
confirmProps: { color: 'violet' },
|
||
onConfirm: async () => {
|
||
try {
|
||
setSaving(true);
|
||
await monthlyOrdersApi.submitSupplementaryOrders(ordersToSend);
|
||
|
||
localStorage.removeItem(DRAFT_KEY);
|
||
localStorage.removeItem(DRAFT_TIME_KEY);
|
||
setDraftSavedAt(null);
|
||
|
||
notifications.show({ title: 'Успешно', message: 'Доп. заказы отправлены на согласование', color: 'green' });
|
||
loadData(true);
|
||
} catch (err: any) {
|
||
notifications.show({ title: 'Ошибка', message: err.response?.data?.error_description || 'Сбой при отправке доп. заказов', color: 'red' });
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
}
|
||
});
|
||
};
|
||
|
||
const handleResetDraft = () => {
|
||
if (inputsDisabled) return;
|
||
localStorage.removeItem(DRAFT_KEY);
|
||
localStorage.removeItem(DRAFT_TIME_KEY);
|
||
setDraftSavedAt(null);
|
||
loadData(true);
|
||
notifications.show({ title: 'Черновик сброшен', message: 'Таблица синхронизирована с БД', color: 'teal' });
|
||
}
|
||
|
||
const nomenclatureTypes = useMemo(() => {
|
||
if (!data?.nomenclatures) return [];
|
||
return Array.from(new Set(data.nomenclatures.map(n => n.type))).sort();
|
||
}, [data?.nomenclatures]);
|
||
|
||
const uniqueBranches = useMemo(() => {
|
||
if (!data?.clients) return [];
|
||
return Array.from(new Set(data.clients.map(c => c.google_data.branch).filter(Boolean))) as string[];
|
||
}, [data?.clients]);
|
||
|
||
const filteredClients = useMemo(() => {
|
||
if (!data?.clients) return [];
|
||
return data.clients.filter(c => {
|
||
const matchName = c.google_data.name.toLowerCase().includes(clientSearchQuery.toLowerCase());
|
||
const matchBranch = selectedBranch ? c.google_data.branch === selectedBranch : true;
|
||
|
||
const hasOrders = (editableOrders[c.google_data.name]?.items?.length ?? 0) > 0;
|
||
|
||
if (showOnlyWithOrders && !hasOrders) return false;
|
||
if (showOnlyWithoutOrders && hasOrders) return false;
|
||
|
||
return matchName && matchBranch;
|
||
});
|
||
}, [data?.clients, clientSearchQuery, selectedBranch, showOnlyWithOrders, showOnlyWithoutOrders, editableOrders]);
|
||
|
||
const filteredNom = useMemo(() => {
|
||
if (!data?.nomenclatures) return [];
|
||
const searchWords = searchQuery.toLowerCase().trim().split(/\s+/).filter(Boolean);
|
||
|
||
return data.nomenclatures.map((n, idx) => ({ ...n, originalIndex: idx + 1 })).filter(n => {
|
||
const nomNameLower = n.name.toLowerCase();
|
||
|
||
const matchSearch =
|
||
n.originalIndex.toString() === searchQuery.trim() ||
|
||
(searchWords.length === 0 || searchWords.every(word => nomNameLower.includes(word)));
|
||
|
||
const matchType = selectedType ? n.type === selectedType : true;
|
||
|
||
let matchNotEmpty = true;
|
||
if (hideEmptyRows) {
|
||
matchNotEmpty = filteredClients.some(c => {
|
||
const item = editableOrders[c.google_data.name]?.items?.find(i => i.nomenclature_name === n.name);
|
||
return (item?.quantity ?? 0) > 0;
|
||
});
|
||
}
|
||
|
||
return matchSearch && matchType && matchNotEmpty;
|
||
});
|
||
}, [data?.nomenclatures, searchQuery, selectedType, hideEmptyRows, editableOrders, filteredClients]);
|
||
|
||
const getTotalForNom = useCallback((nomName: string) => {
|
||
let total = 0;
|
||
filteredClients.forEach(c => {
|
||
const order = editableOrders[c.google_data.name];
|
||
const item = order?.items?.find(i => i.nomenclature_name === nomName);
|
||
if (item?.quantity) total += item.quantity;
|
||
});
|
||
return total;
|
||
}, [editableOrders, filteredClients]);
|
||
|
||
const rowVirtualizer = useVirtualizer({
|
||
count: filteredNom.length,
|
||
getScrollElement: () => tableContainerRef.current,
|
||
estimateSize: () => 65,
|
||
overscan: 10,
|
||
});
|
||
|
||
const formatMSKTime = (date: Date) => {
|
||
return new Intl.DateTimeFormat('ru-RU', {
|
||
timeZone: 'Europe/Moscow',
|
||
day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit',
|
||
}).format(date);
|
||
};
|
||
|
||
if (loading) return <LoadingOverlay visible />
|
||
if (!data) return <Text ta="center">Нет данных</Text>
|
||
|
||
// Вычисляем цвета для баннера рынка (Красный - для растущего, Серый - для падающего и стоячего)
|
||
const isGrowing = data.settings?.market_stage?.toLowerCase() === 'растущий';
|
||
const marketColor = isGrowing ? 'red' : 'gray';
|
||
|
||
return (
|
||
<Box display="flex" style={{ flexDirection: 'column', flexGrow: 1, overflow: 'hidden' }}>
|
||
|
||
{isReadOnly && (
|
||
<Group mb="sm">
|
||
<Button variant="subtle" leftSection={<IconArrowLeft size={16} />} onClick={() => navigate('/analyst')}>
|
||
Назад к списку менеджеров
|
||
</Button>
|
||
<Badge color="violet" size="lg">Режим просмотра: Менеджер ID {targetManagerId}</Badge>
|
||
</Group>
|
||
)}
|
||
|
||
{/* НОВЫЙ БЛОК: Заметный баннер-инструкция о состоянии рынка */}
|
||
{data.settings?.market_stage && (
|
||
<Paper
|
||
withBorder
|
||
p="md"
|
||
mb="md"
|
||
radius="md"
|
||
bg={`var(--mantine-color-${marketColor}-0)`}
|
||
style={{
|
||
borderLeft: `6px solid var(--mantine-color-${marketColor}-filled)`
|
||
}}
|
||
>
|
||
<Group align="flex-start" wrap="nowrap">
|
||
<IconInfoCircle
|
||
size={28}
|
||
color={`var(--mantine-color-${marketColor}-filled)`}
|
||
style={{ marginTop: 2 }}
|
||
/>
|
||
<Box>
|
||
<Group align="center" gap="sm">
|
||
<Text fw={600} size="lg" c="dimmed">Рынок сейчас:</Text>
|
||
<Text
|
||
fw={800}
|
||
style={{
|
||
fontSize: '24px', // Размер как у заголовка
|
||
textTransform: 'uppercase',
|
||
color: `var(--mantine-color-${marketColor}-filled)`,
|
||
lineHeight: 1
|
||
}}
|
||
>
|
||
{data.settings.market_stage}
|
||
</Text>
|
||
</Group>
|
||
|
||
{data.settings.market_stage_comment && (
|
||
<Text size="sm" fw={500} mt={8} style={{ whiteSpace: 'pre-wrap', lineHeight: 1.4, color: 'var(--mantine-color-dark-4)' }}>
|
||
{data.settings.market_stage_comment}
|
||
</Text>
|
||
)}
|
||
</Box>
|
||
</Group>
|
||
</Paper>
|
||
)}
|
||
|
||
<Group justify="space-between" align="flex-start" mb="md">
|
||
<Stack gap="xs" style={{ flex: 1 }}>
|
||
<Group align="center" gap="sm">
|
||
<Text size="sm" fw={600} w={120}>Номенклатура:</Text>
|
||
<TextInput
|
||
placeholder="Название или № строки..."
|
||
leftSection={<IconSearch size={16} />}
|
||
value={searchQuery}
|
||
onChange={(e) => setSearchQuery(e.currentTarget.value)}
|
||
w={220}
|
||
size="sm"
|
||
/>
|
||
<Select
|
||
placeholder="Все типы"
|
||
data={['', ...nomenclatureTypes]}
|
||
value={selectedType || ''}
|
||
onChange={(val) => setSelectedType(val === '' ? null : val)}
|
||
leftSection={<IconFilter size={16} />}
|
||
w={180}
|
||
clearable
|
||
size="sm"
|
||
/>
|
||
<Checkbox
|
||
label="Скрыть пустые строки"
|
||
size="sm"
|
||
checked={hideEmptyRows}
|
||
onChange={(e) => setHideEmptyRows(e.currentTarget.checked)}
|
||
/>
|
||
<Badge color="blue" variant="light">Найдено: {filteredNom.length}</Badge>
|
||
</Group>
|
||
|
||
<Group align="center" gap="sm">
|
||
<Text size="sm" fw={600} w={120}>Клиенты:</Text>
|
||
<TextInput
|
||
placeholder="Поиск по клиенту..."
|
||
leftSection={<IconUserSearch size={16} />}
|
||
value={clientSearchQuery}
|
||
onChange={(e) => setClientSearchQuery(e.currentTarget.value)}
|
||
w={220}
|
||
size="sm"
|
||
/>
|
||
<Select
|
||
placeholder="Все филиалы"
|
||
data={['', ...uniqueBranches]}
|
||
value={selectedBranch || ''}
|
||
onChange={(val) => setSelectedBranch(val === '' ? null : val)}
|
||
leftSection={<IconFilter size={16} />}
|
||
w={180}
|
||
clearable
|
||
size="sm"
|
||
/>
|
||
<Checkbox
|
||
label="Только с заказами"
|
||
size="sm"
|
||
checked={showOnlyWithOrders}
|
||
onChange={(e) => {
|
||
setShowOnlyWithOrders(e.currentTarget.checked);
|
||
if (e.currentTarget.checked) setShowOnlyWithoutOrders(false);
|
||
}}
|
||
/>
|
||
<Checkbox
|
||
label="Только без заказов"
|
||
size="sm"
|
||
checked={showOnlyWithoutOrders}
|
||
onChange={(e) => {
|
||
setShowOnlyWithoutOrders(e.currentTarget.checked);
|
||
if (e.currentTarget.checked) setShowOnlyWithOrders(false);
|
||
}}
|
||
/>
|
||
</Group>
|
||
</Stack>
|
||
|
||
{/* КНОПКИ ДЕЙСТВИЙ (Справа) */}
|
||
<Stack align="flex-end" gap="sm">
|
||
<Group align="center" gap="md">
|
||
{!isReadOnly && (
|
||
isSupplementaryMode ? (
|
||
<>
|
||
<Badge color="violet" size="lg" leftSection={<IconSend size={14} />}>Режим доп. заказов</Badge>
|
||
{draftSavedAt && (
|
||
<Text size="xs" c="dimmed">
|
||
Локальный черновик:<br/>
|
||
<Text span fw={500} c="gray.7">{formatMSKTime(draftSavedAt)} (МСК)</Text>
|
||
</Text>
|
||
)}
|
||
<Button variant="default" onClick={handleResetDraft} leftSection={<IconRefresh size={16} />}>Сбросить</Button>
|
||
<Button color="violet" onClick={handleSendSupplementary} loading={saving} leftSection={<IconSend size={16} />}>
|
||
Отправить на согласование
|
||
</Button>
|
||
</>
|
||
) : (
|
||
<>
|
||
{draftSavedAt && (
|
||
<Text size="xs" c="dimmed">
|
||
Локальный черновик:<br/>
|
||
<Text span fw={500} c="gray.7">{formatMSKTime(draftSavedAt)} (МСК)</Text>
|
||
</Text>
|
||
)}
|
||
<Button variant="default" onClick={handleResetDraft} leftSection={<IconRefresh size={16} />}>
|
||
Сбросить черновик
|
||
</Button>
|
||
<Button onClick={handleSave} loading={saving} leftSection={<IconDeviceFloppy size={16} />}>
|
||
Сохранить в базу
|
||
</Button>
|
||
</>
|
||
)
|
||
)}
|
||
</Group>
|
||
</Stack>
|
||
</Group>
|
||
|
||
<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 w={60} style={{ position: 'sticky', left: 0, zIndex: 3, background: 'var(--mantine-color-body)' }}>№</Table.Th>
|
||
<Table.Th w={300} style={{ position: 'sticky', left: 60, zIndex: 3, background: 'var(--mantine-color-body)' }}>Номенклатура</Table.Th>
|
||
<Table.Th w={100} style={{ position: 'sticky', left: 360, zIndex: 3, background: 'var(--mantine-color-body)', borderRight: '2px solid var(--mantine-color-gray-3)' }}>Итого</Table.Th>
|
||
|
||
{filteredClients.map(c => {
|
||
const clientName = c.google_data.name;
|
||
const branch = c.google_data.branch;
|
||
const order = editableOrders[clientName];
|
||
|
||
const hasItems = (order?.items?.length ?? 0) > 0 && order!.items!.some(i => (i.quantity ?? 0) > 0);
|
||
const hasComment = !!order?.manager_comment && order.manager_comment.trim() !== '';
|
||
|
||
const isCommentError = isSupplementaryMode ? (hasItems && !hasComment) : !hasComment;
|
||
|
||
return (
|
||
<Table.Th key={clientName} w={240} style={{ textAlign: 'center', verticalAlign: 'top', padding: '10px 8px' }}>
|
||
<Group justify="space-between" align="center" mb={2} wrap="nowrap">
|
||
<Text size="sm" fw={600} style={{ whiteSpace: 'normal', wordBreak: 'break-word', lineHeight: 1.2, flex: 1 }}>
|
||
{clientName}
|
||
</Text>
|
||
|
||
<Group gap={4} wrap="nowrap">
|
||
<input
|
||
type="file"
|
||
multiple
|
||
accept="image/*"
|
||
id={`file-${clientName}`}
|
||
style={{ display: 'none' }}
|
||
disabled={inputsDisabled}
|
||
onChange={(e) => handleFilesChange(clientName, e)}
|
||
/>
|
||
|
||
<ActionIcon
|
||
variant="light"
|
||
color={order?.files && order.files.length > 0 ? "teal" : "gray"}
|
||
size="sm"
|
||
title="Прикрепить скрин(ы) подтверждения"
|
||
disabled={inputsDisabled}
|
||
onClick={() => document.getElementById(`file-${clientName}`)?.click()}
|
||
>
|
||
<IconPaperclip size={14} />
|
||
</ActionIcon>
|
||
|
||
{order?.files && order.files.length > 0 && (
|
||
<Badge
|
||
size="sm"
|
||
color="teal"
|
||
variant="filled"
|
||
style={{ cursor: inputsDisabled ? 'default' : 'pointer' }}
|
||
title="Кликните, чтобы очистить прикрепленные файлы"
|
||
onClick={() => !inputsDisabled && updateClientMeta(clientName, 'files', null)}
|
||
>
|
||
{order.files.length}
|
||
</Badge>
|
||
)}
|
||
|
||
<ClientSettingsPopover
|
||
clientName={clientName}
|
||
order={order}
|
||
updateClientMeta={updateClientMeta}
|
||
isLocked={inputsDisabled}
|
||
/>
|
||
</Group>
|
||
</Group>
|
||
|
||
{branch && (
|
||
<Text size="xs" c="dimmed" mb={6} style={{ lineHeight: 1 }}>
|
||
Филиал: {branch}
|
||
</Text>
|
||
)}
|
||
|
||
<Group gap={4} justify="center" mb="xs">
|
||
{order?.decade && <Badge size="xs" variant="outline" color="blue">{order.decade}</Badge>}
|
||
{order?.delivery && <Badge size="xs" variant="outline" color="teal">{order.delivery}</Badge>}
|
||
{order?.payment_form && <Badge size="xs" variant="outline" color="violet">{order.payment_form}</Badge>}
|
||
</Group>
|
||
|
||
<Textarea
|
||
size="xs"
|
||
placeholder="Комментарий (обязательно) *"
|
||
disabled={inputsDisabled}
|
||
value={order?.manager_comment || ''}
|
||
onChange={e => updateClientMeta(clientName, 'manager_comment', e.currentTarget.value)}
|
||
autosize
|
||
minRows={1}
|
||
maxRows={3}
|
||
error={isCommentError}
|
||
/>
|
||
{isCommentError && (
|
||
<Text size="10px" c="red" mt={2} ta="left">
|
||
{isSupplementaryMode ? "Обязателен при доп. заказе" : "Заполните для разблокировки"}
|
||
</Text>
|
||
)}
|
||
</Table.Th>
|
||
)
|
||
})}
|
||
</Table.Tr>
|
||
</Table.Thead>
|
||
|
||
<Table.Tbody>
|
||
{rowVirtualizer.getVirtualItems().length > 0 && (
|
||
<tr>
|
||
<td colSpan={filteredClients.length + 3} style={{ height: `${rowVirtualizer.getVirtualItems()[0].start}px`, padding: 0, border: 0 }} />
|
||
</tr>
|
||
)}
|
||
|
||
{rowVirtualizer.getVirtualItems().map(virtualRow => {
|
||
const nom = filteredNom[virtualRow.index];
|
||
const total = getTotalForNom(nom.name);
|
||
|
||
return (
|
||
<Table.Tr
|
||
key={virtualRow.key}
|
||
data-index={virtualRow.index}
|
||
ref={rowVirtualizer.measureElement}
|
||
>
|
||
<Table.Td style={{ position: 'sticky', left: 0, background: 'var(--mantine-color-body)', zIndex: 1, borderRight: '1px solid var(--mantine-color-gray-2)', textAlign: 'center' }}>
|
||
<Text size="xs" c="dimmed">{nom.originalIndex}</Text>
|
||
</Table.Td>
|
||
<Table.Td style={{ position: 'sticky', left: 60, background: 'var(--mantine-color-body)', zIndex: 1, borderRight: '1px solid var(--mantine-color-gray-2)' }}>
|
||
<Text size="sm" fw={500} style={{ whiteSpace: 'normal', wordBreak: 'break-word', lineHeight: 1.2 }}>{nom.name}</Text>
|
||
<Text size="xs" c="dimmed" mt={2}>{nom.type}</Text>
|
||
</Table.Td>
|
||
<Table.Td style={{ position: 'sticky', left: 360, background: 'var(--mantine-color-body)', zIndex: 1, borderRight: '2px solid var(--mantine-color-gray-3)', textAlign: 'center' }}>
|
||
<Badge color={total > 0 ? 'blue' : 'gray'} variant={total > 0 ? 'filled' : 'light'}>
|
||
{total > 0 ? total : '-'}
|
||
</Badge>
|
||
</Table.Td>
|
||
|
||
{filteredClients.map(c => {
|
||
const clientName = c.google_data.name;
|
||
const order = editableOrders[clientName];
|
||
const hasComment = !!order?.manager_comment && order.manager_comment.trim() !== '';
|
||
|
||
const isNomenclatureDisabled = isSupplementaryMode
|
||
? inputsDisabled
|
||
: (inputsDisabled || !hasComment);
|
||
|
||
const item = order?.items?.find(i => i.nomenclature_name === nom.name);
|
||
return (
|
||
<Table.Td key={clientName} align="center">
|
||
<CellInput
|
||
initialValue={item?.quantity || null}
|
||
disabled={isNomenclatureDisabled}
|
||
onCommit={(val) => handleQuantityChange(clientName, nom, val)}
|
||
/>
|
||
</Table.Td>
|
||
)
|
||
})}
|
||
</Table.Tr>
|
||
)
|
||
})}
|
||
|
||
{rowVirtualizer.getVirtualItems().length > 0 && (
|
||
<tr>
|
||
<td colSpan={filteredClients.length + 3} style={{ height: `${rowVirtualizer.getTotalSize() - rowVirtualizer.getVirtualItems()[rowVirtualizer.getVirtualItems().length - 1].end}px`, padding: 0, border: 0 }} />
|
||
</tr>
|
||
)}
|
||
</Table.Tbody>
|
||
</Table>
|
||
</div>
|
||
</Paper>
|
||
</Box>
|
||
)
|
||
}
|
||
|
||
function ClientSettingsPopover({ clientName, order, updateClientMeta, isLocked }: any) {
|
||
return (
|
||
<HoverCard width={300} position="bottom" withArrow shadow="md" openDelay={200} closeDelay={300}>
|
||
<HoverCard.Target>
|
||
<ActionIcon variant="light" color="blue" size="sm" disabled={isLocked}>
|
||
<IconSettings size={14} />
|
||
</ActionIcon>
|
||
</HoverCard.Target>
|
||
<HoverCard.Dropdown>
|
||
<Title order={6} mb="sm" style={{ whiteSpace: 'normal' }}>Настройки: {clientName}</Title>
|
||
<Stack gap="xs">
|
||
<Group grow>
|
||
<Select label="Декада" size="xs" disabled={isLocked} data={['1-я', '2-я', '3-я']} value={order?.decade || null} onChange={v => updateClientMeta(clientName, 'decade', v)} comboboxProps={{ withinPortal: false }} clearable />
|
||
<Select label="Доставка" size="xs" disabled={isLocked} data={['Склад', 'Клиент']} value={order?.delivery || null} onChange={v => updateClientMeta(clientName, 'delivery', v)} comboboxProps={{ withinPortal: false }} clearable />
|
||
</Group>
|
||
<Group grow>
|
||
<Select label="Условия" size="xs" disabled={isLocked} data={['Предоплата', 'Отсрочка']} value={order?.conditions || null} onChange={v => updateClientMeta(clientName, 'conditions', v)} comboboxProps={{ withinPortal: false }} clearable />
|
||
<Select label="Оплата" size="xs" disabled={isLocked} data={['Ф1-Ф1', 'Ф1-Ф2', 'Ф2-Ф1', 'Ф2-Ф2']} value={order?.payment_form || null} onChange={v => updateClientMeta(clientName, 'payment_form', v)} comboboxProps={{ withinPortal: false }} clearable />
|
||
</Group>
|
||
</Stack>
|
||
</HoverCard.Dropdown>
|
||
</HoverCard>
|
||
)
|
||
} |