diff --git a/result.txt b/result.txt
index 6d8f9d2..2ae845d 100644
--- a/result.txt
+++ b/result.txt
@@ -170,7 +170,7 @@
│ │ ├── notifications
│ │ │ ├── NotificationsPage.tsx
│ │ │ ├── components
-│ │ │ │ ├── NotificationDetailsModal.tsx
+│ │ │ │ ├── NotificationDetailsDrawer.tsx
│ │ │ │ ├── NotificationsHistoryTable.tsx
│ │ │ │ ├── SendNotificationForm.tsx
│ │ ├── permissions
diff --git a/src/pages/monthlyOrders/MonthlyOrdersSettingsPage.tsx b/src/pages/monthlyOrders/MonthlyOrdersSettingsPage.tsx
index 7335782..58c4400 100644
--- a/src/pages/monthlyOrders/MonthlyOrdersSettingsPage.tsx
+++ b/src/pages/monthlyOrders/MonthlyOrdersSettingsPage.tsx
@@ -1,10 +1,12 @@
import { useEffect } from 'react'
-import { Box, Button, Group, NumberInput, Paper, Stack, Title, Text, Select, Textarea } from '@mantine/core'
+import { Box, Button, Group, NumberInput, Paper, Stack, Text, Select, Textarea, Skeleton } from '@mantine/core'
import { DateTimePicker } from '@mantine/dates'
import { useForm } from '@mantine/form'
-import { useMonthlyOrderSettings, useSaveMonthlyOrderSettings } from '@/features/monthlyOrders/hooks/useMonthlyOrderSettings'
+import { IconDeviceFloppy, IconInfoCircle } from '@tabler/icons-react'
import dayjs from 'dayjs'
-import { IconDeviceFloppy } from '@tabler/icons-react'
+
+import { useMonthlyOrderSettings, useSaveMonthlyOrderSettings } from '@/features/monthlyOrders/hooks/useMonthlyOrderSettings'
+import { PageHeader } from '@/components/ui/PageHeader'
interface SettingsFormValues {
deadline_date: Date | null
@@ -34,76 +36,112 @@ export default function MonthlyOrdersSettingsPage() {
if (currentSettings) {
form.setValues({
deadline_date: currentSettings.deadline_date ? new Date(currentSettings.deadline_date) : null,
- assembly_time_days: currentSettings.assembly_time_days || 3,
+ assembly_time_days: currentSettings.assembly_time_days ?? 3,
market_stage: currentSettings.market_stage || null,
market_stage_comment: currentSettings.market_stage_comment || '',
})
+ form.resetDirty() // Сбрасываем флаг изменений после загрузки данных
}
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentSettings])
const handleSubmit = (values: SettingsFormValues) => {
- 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,
- })
+ 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,
+ },
+ {
+ onSuccess: () => form.resetDirty(), // После успешного сохранения кнопка снова блокируется
+ }
+ )
}
- if (isLoading) return Загрузка...
-
return (
-
- Настройки: Заказ товаров на месяц
+
+
-
-
-
-
+
+ ) : (
+
+
+
+ )}
+
)
}
\ No newline at end of file
diff --git a/src/pages/notifications/NotificationsPage.tsx b/src/pages/notifications/NotificationsPage.tsx
index 791f4a4..141fd98 100644
--- a/src/pages/notifications/NotificationsPage.tsx
+++ b/src/pages/notifications/NotificationsPage.tsx
@@ -1,6 +1,8 @@
-import { Stack, Tabs, Text, Alert } from '@mantine/core'
+import { Stack, Tabs, Alert } from '@mantine/core'
import { IconSend, IconHistory, IconLock } from '@tabler/icons-react'
+
import { useAuth } from '@/hooks/useAuth'
+import { PageHeader } from '@/components/ui/PageHeader'
import SendNotificationForm from './components/SendNotificationForm'
import NotificationsHistoryTable from './components/NotificationsHistoryTable'
@@ -9,8 +11,17 @@ export default function NotificationsPage() {
const isObserver = user?.is_observer === true
return (
-
- Уведомления
+
+
+
+ {isObserver && (
+ }>
+ В режиме наблюдателя доступен только просмотр истории уведомлений
+
+ )}
@@ -34,12 +45,6 @@ export default function NotificationsPage() {
-
- {isObserver && (
- }>
- В режиме наблюдателя доступен только просмотр истории уведомлений
-
- )}
)
}
\ No newline at end of file
diff --git a/src/pages/notifications/components/NotificationDetailsDrawer.tsx b/src/pages/notifications/components/NotificationDetailsDrawer.tsx
new file mode 100644
index 0000000..b20db54
--- /dev/null
+++ b/src/pages/notifications/components/NotificationDetailsDrawer.tsx
@@ -0,0 +1,97 @@
+import { useNotification } from '@/features/notifications/hooks/useNotifications'
+import { Drawer, Stack, Text, Badge, Skeleton, Box, Group } from '@mantine/core'
+import { DataTable, type Column } from '@/components/ui/DataTable'
+import classes from '@/components/UserDrawer.module.css'
+
+interface Props {
+ notificationId: number | null
+ opened: boolean
+ onClose: () => void
+}
+
+const RECIPIENT_STATUS_LABELS: Record = {
+ pending: { label: 'В очереди', color: 'gray' },
+ sent: { label: 'Доставлено', color: 'green' },
+ failed: { label: 'Ошибка', color: 'red' },
+}
+
+export default function NotificationDetailsDrawer({ notificationId, opened, onClose }: Props) {
+ const { data: notification, isLoading } = useNotification(notificationId)
+
+ const columns: Column[] = [
+ {
+ key: 'user',
+ header: 'Пользователь',
+ cell: (r) => {r.user?.full_name || `ID ${r.user_id}`}
+ },
+ {
+ key: 'status',
+ header: 'Статус',
+ width: 120,
+ cell: (r) => {
+ const statusInfo = RECIPIENT_STATUS_LABELS[r.status || ''] || { label: r.status || '—', color: 'gray' }
+ return {statusInfo.label}
+ }
+ },
+ {
+ key: 'error',
+ header: 'Лог ошибки',
+ cell: (r) => {r.error_message || '—'}
+ }
+ ]
+
+ return (
+
+
+
+
+
+
+ Детали уведомления
+ {notification && ID {notification.id}}
+
+
+
+
+
+
+ {isLoading ? (
+
+
+
+
+
+ ) : !notification ? (
+ Уведомление не найдено
+ ) : (
+
+
+ Содержимое
+
+ {notification.title}
+
+
+
+
+
+ Получатели ({notification.recipients?.length || 0})
+
+ r.id}
+ minWidth={400}
+ empty={{ title: 'Нет получателей' }}
+ />
+
+
+
+ )}
+
+
+
+ )
+}
\ No newline at end of file
diff --git a/src/pages/notifications/components/NotificationDetailsModal.tsx b/src/pages/notifications/components/NotificationDetailsModal.tsx
deleted file mode 100644
index 544472f..0000000
--- a/src/pages/notifications/components/NotificationDetailsModal.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-import { useNotification } from '@/features/notifications/hooks/useNotifications'
-import { Modal, Stack, Text, Badge, ScrollArea, Table, Divider, Loader, Center } from '@mantine/core'
-
-interface Props {
- notificationId: number | null
- opened: boolean
- onClose: () => void
-}
-
-const RECIPIENT_STATUS_LABELS: Record = {
- pending: { label: 'В очереди', color: 'gray' },
- sent: { label: 'Доставлено', color: 'green' },
- failed: { label: 'Ошибка', color: 'red' },
-}
-
-export default function NotificationDetailsModal({ notificationId, opened, onClose }: Props) {
- const { data: notification, isLoading } = useNotification(notificationId)
-
- return (
-
- {isLoading || !notification ? (
-
-
-
- ) : (
-
-
- {notification.title}
-
-
-
-
-
-
-
-
-
- Пользователь
- Статус
- Ошибка
-
-
-
- {(notification.recipients || []).map((r) => {
- const statusInfo = RECIPIENT_STATUS_LABELS[r.status || ''] || {
- label: r.status || '—',
- color: 'gray',
- }
- return (
-
- {r.user?.full_name || `ID ${r.user_id}`}
-
-
- {statusInfo.label}
-
-
-
-
- {r.error_message || ''}
-
-
-
- )
- })}
-
-
-
-
- )}
-
- )
-}
\ No newline at end of file
diff --git a/src/pages/notifications/components/NotificationsHistoryTable.tsx b/src/pages/notifications/components/NotificationsHistoryTable.tsx
index fc0a9e2..760d67a 100644
--- a/src/pages/notifications/components/NotificationsHistoryTable.tsx
+++ b/src/pages/notifications/components/NotificationsHistoryTable.tsx
@@ -1,9 +1,8 @@
import { useState } from 'react'
-import {
- Paper, Table, Badge, Group, Text, Pagination, Loader, Center, Box, Stack,
-} from '@mantine/core'
-import NotificationDetailsModal from './NotificationDetailsModal'
+import { Badge, Group, Text } from '@mantine/core'
import { useNotifications } from '@/features/notifications/hooks/useNotifications'
+import { DataTable, type Column } from '@/components/ui/DataTable'
+import NotificationDetailsDrawer from './NotificationDetailsDrawer'
const LIMIT = 20
@@ -18,108 +17,72 @@ export default function NotificationsHistoryTable() {
const [page, setPage] = useState(1)
const [selectedId, setSelectedId] = useState(null)
- const { data, isLoading } = useNotifications({
+ const { data, isLoading, isFetching } = useNotifications({
offset: (page - 1) * LIMIT,
limit: LIMIT,
})
- const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
+ const total = data?.total_count ?? 0
+
+ const columns: Column[] = [
+ {
+ key: 'id',
+ header: 'ID',
+ width: 80,
+ cell: (r) => #{r.id}
+ },
+ {
+ key: 'title',
+ header: 'Заголовок',
+ cell: (r) => {r.title}
+ },
+ {
+ key: 'status',
+ header: 'Статус',
+ width: 140,
+ cell: (r) => {
+ const statusInfo = STATUS_LABELS[r.status || ''] || { label: r.status || '—', color: 'gray' }
+ return {statusInfo.label}
+ }
+ },
+ {
+ key: 'delivery',
+ header: 'Доставлено',
+ width: 180,
+ cell: (r) => (
+
+ {r.sent_count ?? 0}
+ {(r.failed_count ?? 0) > 0 && {r.failed_count} ошибок}
+ из {r.total_count ?? 0}
+
+ )
+ },
+ {
+ key: 'date',
+ header: 'Дата отправки',
+ width: 160,
+ cell: (r) => {r.sent_at ? new Date(r.sent_at).toLocaleString('ru-RU') : '—'}
+ },
+ ]
return (
-
-
- {isLoading ? (
-
-
-
- ) : (
- <>
-
-
-
- ID
- Заголовок
- Статус
- Доставлено
- Дата отправки
-
-
-
- {data?.data?.length === 0 ? (
-
-
-
- Уведомления не отправлялись
-
-
-
- ) : (
- (data?.data || []).map((n) => {
- const statusInfo = STATUS_LABELS[n.status || ''] || {
- label: n.status || '—',
- color: 'gray',
- }
- return (
- setSelectedId(n.id!)}
- >
- {n.id}
-
- {n.title}
-
-
-
- {statusInfo.label}
-
-
-
-
-
- {n.sent_count ?? 0}
-
- {(n.failed_count ?? 0) > 0 && (
-
- {n.failed_count} ошибок
-
- )}
-
- из {n.total_count ?? 0}
-
-
-
-
-
- {n.sent_at ? new Date(n.sent_at).toLocaleString('ru-RU') : '—'}
-
-
-
- )
- })
- )}
-
-
+ <>
+ r.id}
+ loading={isLoading}
+ refreshing={isFetching}
+ onRowClick={(r) => setSelectedId(r.id)}
+ empty={{ title: 'Уведомления не отправлялись' }}
+ pagination={{ page, pageSize: LIMIT, total, onChange: setPage }}
+ />
- {totalPages > 1 && (
-
-
-
- Страница {page} из {totalPages}
-
-
-
-
- )}
- >
- )}
-
-
- setSelectedId(null)}
/>
-
+ >
)
}
\ No newline at end of file
diff --git a/src/pages/notifications/components/SendNotificationForm.tsx b/src/pages/notifications/components/SendNotificationForm.tsx
index 46bab67..9f55db0 100644
--- a/src/pages/notifications/components/SendNotificationForm.tsx
+++ b/src/pages/notifications/components/SendNotificationForm.tsx
@@ -1,8 +1,7 @@
import { useState, useMemo } from 'react'
import {
Paper, Stack, TextInput, Button, Group, MultiSelect, Checkbox,
- Text, FileButton, Image, ActionIcon, Divider, Alert, Badge, Grid,
- ThemeIcon,
+ Text, FileButton, Image, ActionIcon, Alert, Badge, Grid, ThemeIcon, Tabs
} from '@mantine/core'
import {
IconPhoto, IconX, IconSend, IconAlertCircle, IconUsers,
@@ -13,15 +12,16 @@ import { useEditor } from '@tiptap/react'
import StarterKit from '@tiptap/starter-kit'
import Underline from '@tiptap/extension-underline'
import { useDebouncedValue } from '@mantine/hooks'
-import { useUsers } from '@/features/users/hooks/useUsers'
-import { useDepartments } from '@/features/departments/hooks/useDepartments'
-import { useAllRoles } from '@/features/roles/hooks/useAllRoles'
-import { useCreateNotification } from '@/features/notifications/hooks/useNotifications.ts'
-import { convertHtmlToTelegram } from '@/features/notifications/utils/telegramHtml.ts'
import { notifications } from '@mantine/notifications'
import { Modal } from '@mantine/core'
import '@mantine/tiptap/styles.css'
+import { useUsers } from '@/features/users/hooks/useUsers'
+import { useDepartments } from '@/features/departments/hooks/useDepartments'
+import { useAllRoles } from '@/features/roles/hooks/useAllRoles'
+import { useCreateNotification } from '@/features/notifications/hooks/useNotifications'
+import { convertHtmlToTelegram } from '@/features/notifications/utils/telegramHtml'
+
const ROLE_TYPE_OPTIONS = [
{ value: 'director', label: 'Директора', icon: '👔' },
{ value: 'approver', label: 'Согласующие', icon: '✅' },
@@ -68,16 +68,8 @@ export default function SendNotificationForm() {
})),
[usersData],
)
- const roleOptions = useMemo(
- () => roles.map((r) => ({ value: String(r.id), label: r.name })),
- [roles],
- )
- const departmentOptions = useMemo(
- () => departments.map((d) => ({ value: String(d.id), label: d.name })),
- [departments],
- )
-
- const MAX_ASPECT_RATIO = 20
+ const roleOptions = useMemo(() => roles.map((r) => ({ value: String(r.id), label: r.name })), [roles])
+ const departmentOptions = useMemo(() => departments.map((d) => ({ value: String(d.id), label: d.name })), [departments])
const handlePhotoChange = (file: File | null) => {
if (!file) {
@@ -92,13 +84,8 @@ export default function SendNotificationForm() {
const img = new window.Image()
img.onload = () => {
const ratio = Math.max(img.width, img.height) / Math.min(img.width, img.height)
- const sumDimensions = img.width + img.height
- if (ratio > MAX_ASPECT_RATIO || sumDimensions > 10000) {
- notifications.show({
- title: 'Некорректное изображение',
- message: `Telegram не примет это фото: слишком вытянутые пропорции (${img.width}×${img.height}).`,
- color: 'red',
- })
+ if (ratio > 20 || img.width + img.height > 10000) {
+ notifications.show({ title: 'Ошибка', message: 'Telegram не примет это фото из-за пропорций.', color: 'red' })
return
}
setPhotoBase64(result.split(',')[1] || '')
@@ -110,30 +97,16 @@ export default function SendNotificationForm() {
reader.readAsDataURL(file)
}
- const hasAnyTarget =
- selectedUserIds.length > 0 ||
- selectedRoleIds.length > 0 ||
- selectedRoleFlags.length > 0 ||
- selectedDepartmentIds.length > 0
-
- const messageHtml = editor?.getHTML() ?? ''
- const messageText = editor?.getText() ?? ''
+ const hasAnyTarget = selectedUserIds.length > 0 || selectedRoleIds.length > 0 || selectedRoleFlags.length > 0 || selectedDepartmentIds.length > 0
const isMessageEmpty = editor?.isEmpty ?? true
-
const canSubmit = title.trim().length > 0 && !isMessageEmpty && hasAnyTarget
- const totalCriteria =
- (selectedUserIds.length > 0 ? 1 : 0) +
- (selectedRoleIds.length > 0 ? 1 : 0) +
- (selectedRoleFlags.length > 0 ? 1 : 0) +
- (selectedDepartmentIds.length > 0 ? 1 : 0)
-
const doSubmit = () => {
setConfirmOpen(false)
createNotification.mutate(
{
title: title.trim(),
- message_html: convertHtmlToTelegram(messageHtml),
+ message_html: convertHtmlToTelegram(editor?.getHTML() ?? ''),
photo_base64: photoBase64 || undefined,
photo_file_name: photoFileName || undefined,
targets: {
@@ -152,11 +125,7 @@ export default function SendNotificationForm() {
setSelectedRoleFlags([])
setSelectedDepartmentIds([])
handlePhotoChange(null)
- notifications.show({
- title: 'Успешно',
- message: 'Уведомление отправлено',
- color: 'green',
- })
+ notifications.show({ title: 'Успешно', message: 'Уведомление отправлено', color: 'green' })
},
},
)
@@ -164,7 +133,6 @@ export default function SendNotificationForm() {
return (
- {/* ===== HEADER ===== */}
@@ -175,11 +143,6 @@ export default function SendNotificationForm() {
Отправится через Telegram Bot
- {totalCriteria > 0 && (
-
- {totalCriteria} {totalCriteria === 1 ? 'критерий' : 'критериев'}
-
- )}
@@ -195,15 +158,10 @@ export default function SendNotificationForm() {
size="md"
/>
- {/* Редактор */}
Текст сообщения
- {!isMessageEmpty && (
- }>
- Заполнено
-
- )}
+ {!isMessageEmpty && }>Заполнено}
@@ -225,12 +183,8 @@ export default function SendNotificationForm() {
-
- жирный · курсив · подчёркнутый · зачёркнутый · код · ссылки — остальное Telegram не отобразит
-
- {/* Фото */}
Фото (опционально)
{photoPreviewUrl ? (
@@ -242,20 +196,12 @@ export default function SendNotificationForm() {
{photoFileName}
Готово к отправке
- handlePhotoChange(null)}
- >
-
-
+ handlePhotoChange(null)}>
) : (
{(props) => (
- }>
- Прикрепить фото
-
+ }>Прикрепить фото
)}
)}
@@ -263,181 +209,108 @@ export default function SendNotificationForm() {
- {/* ===== ПРАВАЯ КОЛОНКА: ПОЛУЧАТЕЛИ + ПРЕВЬЮ ===== */}
-
- {/* Получатели */}
-
+
+
-
-
-
+
Получатели
- {hasAnyTarget && (
-
- Настроено
-
- )}
+ {hasAnyTarget && Настроено}
-
-
-
- Конкретные пользователи
- {selectedUserIds.length > 0 && (
- {selectedUserIds.length}
- )}
-
- }
- placeholder="Начните вводить имя..."
- data={userOptions}
- value={selectedUserIds}
- onChange={setSelectedUserIds}
- searchable
- searchValue={userSearch}
- onSearchChange={setUserSearch}
- clearable
- nothingFoundMessage="Никого не найдено"
- size="xs"
- />
+
+
+ }>Точечно
+ }>Массово
+
-
-
- Роли
- {selectedRoleIds.length > 0 && (
- {selectedRoleIds.length}
- )}
-
- }
- placeholder="Выберите роли"
- data={roleOptions}
- value={selectedRoleIds}
- onChange={setSelectedRoleIds}
- searchable
- clearable
- size="xs"
- />
+
+
+
-
-
-
- Тип роли
- {selectedRoleFlags.length > 0 && (
- {selectedRoleFlags.length}
- )}
-
-
+
+
+
+
- {ROLE_TYPE_OPTIONS.map((opt) => (
-
- {opt.icon}
- {opt.label}
-
- }
- />
- ))}
+ Системные типы ролей
+
+
+ {ROLE_TYPE_OPTIONS.map((opt) => (
+ {opt.icon}{opt.label}}
+ />
+ ))}
+
+
-
-
-
-
-
- Отделы
- {selectedDepartmentIds.length > 0 && (
- {selectedDepartmentIds.length}
- )}
-
- }
- placeholder="Выберите отделы"
- data={departmentOptions}
- value={selectedDepartmentIds}
- onChange={setSelectedDepartmentIds}
- searchable
- clearable
- size="xs"
- />
-
- {!hasAnyTarget && (
- } p="xs">
- Выберите хотя бы один способ определения получателей
-
- )}
-
+
+
+
- {/* Кнопка отправки */}
- }
- onClick={() => setConfirmOpen(true)}
- loading={createNotification.isPending}
- disabled={!canSubmit}
- >
- Отправить уведомление
-
+
+ {!hasAnyTarget && (
+ } p="xs">
+ Выберите хотя бы один способ определения получателей для отправки
+
+ )}
+ }
+ onClick={() => setConfirmOpen(true)}
+ loading={createNotification.isPending}
+ disabled={!canSubmit}
+ >
+ Отправить уведомление
+
+
- {/* ===== МОДАЛКА ПОДТВЕРЖДЕНИЯ ===== */}
- setConfirmOpen(false)}
- title="Подтверждение отправки"
- centered
- >
+ setConfirmOpen(false)} title="Подтверждение отправки" centered>
-
- Отправить уведомление «{title.trim()}»?
-
+ Отправить уведомление «{title.trim()}»?
- {selectedUserIds.length > 0 && (
-
- Пользователей
- {selectedUserIds.length}
-
- )}
- {selectedRoleIds.length > 0 && (
-
- Ролей
- {selectedRoleIds.length}
-
- )}
- {selectedRoleFlags.length > 0 && (
-
- Типов ролей
- {selectedRoleFlags.length}
-
- )}
- {selectedDepartmentIds.length > 0 && (
-
- Отделов
- {selectedDepartmentIds.length}
-
- )}
+ {selectedUserIds.length > 0 && Пользователей{selectedUserIds.length}}
+ {selectedRoleIds.length > 0 && Ролей{selectedRoleIds.length}}
+ {selectedRoleFlags.length > 0 && Типов ролей{selectedRoleFlags.length}}
+ {selectedDepartmentIds.length > 0 && Отделов{selectedDepartmentIds.length}}
-
-
+
+