Updated users editing UI
Deploy Frontend / build-and-deploy (push) Failing after 41s Details

This commit is contained in:
romanskijdev 2026-11-18 12:23:23 +03:00
parent 63d93d6792
commit baf0929044
4 changed files with 277 additions and 220 deletions

View File

@ -7,6 +7,7 @@ import { IconLogout, IconSearch, IconSun, IconMoon, IconUser } from '@tabler/ico
import { useLocation } from 'react-router-dom'
import { useAuth } from '@/hooks/useAuth'
import { findTrail } from './navigation'
import { ColorSchemeToggle } from '@/components/ui/ColorSchemeToggle'
interface HeaderProps {
toggleMobile: () => void
@ -15,20 +16,6 @@ interface HeaderProps {
desktopOpened: boolean
}
function ColorSchemeToggle() {
const { setColorScheme } = useMantineColorScheme()
const computed = useComputedColorScheme('light', { getInitialValueInEffect: true })
return (
<ActionIcon
size="lg"
aria-label="Переключить тему"
onClick={() => setColorScheme(computed === 'light' ? 'dark' : 'light')}
>
{computed === 'dark' ? <IconSun size={18} stroke={1.6} /> : <IconMoon size={18} stroke={1.6} />}
</ActionIcon>
)
}
export default function Header({ toggleMobile, toggleDesktop, mobileOpened, desktopOpened }: HeaderProps) {
const { user, logout } = useAuth()
const { pathname } = useLocation()

View File

@ -0,0 +1,17 @@
import { ActionIcon, useComputedColorScheme, useMantineColorScheme } from '@mantine/core'
import { IconMoon, IconSun } from '@tabler/icons-react'
export function ColorSchemeToggle() {
const { setColorScheme } = useMantineColorScheme()
const computed = useComputedColorScheme('light', { getInitialValueInEffect: true })
return (
<ActionIcon
size="lg"
aria-label="Переключить тему"
onClick={() => setColorScheme(computed === 'light' ? 'dark' : 'light')}
>
{computed === 'dark' ? <IconSun size={18} stroke={1.6} /> : <IconMoon size={18} stroke={1.6} />}
</ActionIcon>
)
}

View File

@ -1,86 +1,102 @@
import { useState } from 'react'
import {
Container,
Paper,
Title,
Text,
TextInput,
PasswordInput,
Button,
Group,
} from '@mantine/core'
import { Alert, Box, Button, Paper, PasswordInput, Stack, Text, TextInput, Title } from '@mantine/core'
import { useForm } from '@mantine/form'
import { notifications } from '@mantine/notifications'
import { IconAlertCircle } from '@tabler/icons-react'
import { useAuth } from '@/hooks/useAuth'
import { ColorSchemeToggle } from '@/components/ui/ColorSchemeToggle'
export default function Login() {
const { login } = useAuth()
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [capsLock, setCapsLock] = useState(false)
const form = useForm({
initialValues: {
login: '',
password: '',
},
initialValues: { login: '', password: '' },
validate: {
login: (value: string | any[]) => (value.length < 3 ? 'Логин должен содержать минимум 3 символа' : null),
password: (value: string | any[]) => (value.length < 4 ? 'Пароль должен содержать минимум 4 символа' : null),
login: (v) => (v.trim().length < 3 ? 'Минимум 3 символа' : null),
password: (v) => (v.length < 4 ? 'Минимум 4 символа' : null),
},
})
const handleSubmit = async (values: typeof form.values) => {
setLoading(true)
setError(null)
try {
await login(values.login, values.password)
notifications.show({
title: 'Успешный вход',
message: `Добро пожаловать, ${values.login}!`,
color: 'green',
})
} catch (error: any) {
notifications.show({
title: 'Ошибка входа',
message: error.response?.data?.error_description || 'Неверный логин или пароль',
color: 'red',
})
await login(values.login.trim(), values.password)
} catch (e: any) {
setError(e.response?.data?.error_description || 'Неверный логин или пароль')
} finally {
setLoading(false)
}
}
return (
<Container size={420} my={40}>
<Title ta="center" mb="md">
Корпоративная панель администратора
</Title>
<Text c="dimmed" size="sm" ta="center" mb="xl">
Введите свои данные для входа в систему
</Text>
<Box
mih="100dvh"
p="md"
style={{ background: 'var(--app-bg)', display: 'grid', placeItems: 'center', position: 'relative' }}
>
<Box style={{ position: 'absolute', top: 16, right: 16 }}>
<ColorSchemeToggle />
</Box>
<Paper withBorder shadow="md" p={30} mt={30} radius="md">
<form onSubmit={form.onSubmit(handleSubmit)}>
<TextInput
label="Логин"
placeholder="admin"
required
{...form.getInputProps('login')}
/>
<Stack w="100%" maw={400} gap="xl">
<Stack align="center" gap={4}>
<Box
w={44}
h={44}
mb="xs"
style={{
borderRadius: 12,
display: 'grid',
placeItems: 'center',
background: 'var(--mantine-primary-color-filled)',
color: '#fff',
fontWeight: 700,
fontSize: 20,
}}
>
Р
</Box>
<Title order={3}>Вход в систему</Title>
<Text size="sm" c="dimmed">Портал РусПЭТ · панель администратора</Text>
</Stack>
<PasswordInput
label="Пароль"
placeholder="your password"
required
mt="md"
{...form.getInputProps('password')}
/>
<Paper p="xl">
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap="md">
{error && (
<Alert color="red" icon={<IconAlertCircle size={16} />} p="sm">
{error}
</Alert>
)}
<Group justify="space-between" mt="xl">
<Button type="submit" fullWidth loading={loading}>
Войти
</Button>
</Group>
</form>
</Paper>
</Container>
<TextInput
label="Логин"
placeholder="admin"
autoComplete="username"
autoFocus
{...form.getInputProps('login')}
/>
<PasswordInput
label="Пароль"
placeholder="Введите пароль"
autoComplete="current-password"
description={capsLock ? 'Включён Caps Lock' : undefined}
onKeyDown={(e) => setCapsLock(e.getModifierState('CapsLock'))}
onKeyUp={(e) => setCapsLock(e.getModifierState('CapsLock'))}
{...form.getInputProps('password')}
/>
<Button type="submit" fullWidth loading={loading} mt="xs">
Войти
</Button>
</Stack>
</form>
</Paper>
</Stack>
</Box>
)
}

View File

@ -1,180 +1,217 @@
import { useState } from 'react'
import {
Paper,
Badge,
Box,
Button,
Center,
Divider,
Group,
PasswordInput,
SegmentedControl,
Stack,
Text,
PasswordInput,
Button,
Group,
Alert,
Box,
Title,
Divider,
useMantineColorScheme,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import { notifications } from '@mantine/notifications'
import { modals } from '@mantine/modals'
import { IconShield, IconAlertCircle, IconKey } from '@tabler/icons-react'
import { IconDeviceDesktop, IconMoon, IconSun } from '@tabler/icons-react'
import dayjs from 'dayjs'
import { authApi } from '@/api/auth'
import { useAuth } from '@/hooks/useAuth'
import { PageHeader } from '@/components/ui/PageHeader'
import { Panel } from '@/components/ui/Panel'
import { ConfirmModal } from '@/components/ui/ConfirmModal'
const STRENGTH = [
{ label: 'Слабый', color: 'red' },
{ label: 'Средний', color: 'orange' },
{ label: 'Хороший', color: 'lime' },
{ label: 'Надёжный', color: 'green' },
]
// 0 — пусто, 1..4 — уровень
function strengthOf(p: string) {
if (!p) return 0
let s = 1
if (p.length >= 10) s++
if (/[A-ZА-ЯЁ]/.test(p) && /[a-zа-яё]/.test(p)) s++
if (/\d/.test(p) && /[^\p{L}\d\s]/u.test(p)) s++
return s
}
function PasswordStrength({ value }: { value: string }) {
const level = strengthOf(value)
if (level === 0) return null
const meta = STRENGTH[level - 1]
return (
<Box>
<Group gap={4} grow>
{STRENGTH.map((_, i) => (
<Box
key={i}
h={4}
style={{
borderRadius: 2,
background:
i < level
? `var(--mantine-color-${meta.color}-filled)`
: 'var(--mantine-color-default-border)',
}}
/>
))}
</Group>
<Text size="xs" c="dimmed" mt={4}>{meta.label}</Text>
</Box>
)
}
function Row({ label, children }: { label: string; children: React.ReactNode }) {
return (
<Group justify="space-between" wrap="nowrap" py={10}>
<Text size="sm" c="dimmed">{label}</Text>
<Box>{children}</Box>
</Group>
)
}
export default function SettingsPage() {
const { user, logout } = useAuth()
const { colorScheme, setColorScheme } = useMantineColorScheme()
const [loading, setLoading] = useState(false)
const { user } = useAuth()
const [pending, setPending] = useState<string | null>(null)
const role = user?.is_root ? 'Суперадмин' : user?.is_observer ? 'Наблюдатель' : 'Администратор'
const form = useForm({
initialValues: {
current_password: '',
new_password: '',
confirm_password: '',
},
initialValues: { current_password: '', new_password: '', confirm_password: '' },
validate: {
current_password: (value) =>
value.length === 0 ? 'Введите текущий пароль' : null,
new_password: (value) => {
if (value.length === 0) return 'Введите новый пароль'
if (value.length < 6) return 'Пароль должен содержать минимум 6 символов'
current_password: (v) => (v ? null : 'Введите текущий пароль'),
new_password: (v, values) => {
if (!v) return 'Введите новый пароль'
if (v.length < 6) return 'Минимум 6 символов'
if (v === values.current_password) return 'Новый пароль совпадает с текущим'
return null
},
confirm_password: (value, values) =>
value !== values.new_password ? 'Пароли не совпадают' : null,
confirm_password: (v, values) => (v !== values.new_password ? 'Пароли не совпадают' : null),
},
})
const handleSubmit = async (values: typeof form.values) => {
// Подтверждение через модальное окно
modals.openConfirmModal({
title: 'Подтвердите смену пароля',
children: (
<Text size="sm">
Вы уверены, что хотите изменить пароль? После смены пароля вам нужно будет
войти заново на всех устройствах.
</Text>
),
labels: { confirm: 'Изменить пароль', cancel: 'Отмена' },
confirmProps: { color: 'red' },
onConfirm: async () => {
setLoading(true)
try {
await authApi.updateProfile({ password: values.new_password })
notifications.show({
title: 'Успешно',
message: 'Пароль успешно изменен',
color: 'green',
})
form.reset()
// Разлогиниваем пользователя, чтобы он вошёл заново
setTimeout(() => {
localStorage.removeItem('token')
window.location.href = '/login'
}, 1500)
} catch (error: any) {
notifications.show({
title: 'Ошибка',
message: error.response?.data?.error_description || 'Не удалось изменить пароль',
color: 'red',
})
} finally {
setLoading(false)
}
},
})
const handleConfirm = async () => {
setLoading(true)
try {
await authApi.updateProfile({
current_password: form.values.current_password,
password: form.values.new_password,
})
setPending(null)
form.reset()
notifications.show({
title: 'Пароль изменён',
message: 'Сейчас вы будете перенаправлены на страницу входа',
color: 'green',
})
setTimeout(() => logout(), 1500)
} catch (e: any) {
setPending(null)
notifications.show({
title: 'Ошибка',
message: e.response?.data?.error_description || 'Не удалось изменить пароль',
color: 'red',
})
} finally {
setLoading(false)
}
}
return (
<Box maw={600}>
<Stack gap="lg">
<div>
<Title order={2}>Настройки</Title>
<Text c="dimmed" size="sm" mt={4}>
Управление вашим аккаунтом
</Text>
</div>
{/* Информация о профиле */}
<Paper withBorder p="md">
<Stack gap="xs">
<Group justify="space-between">
<Text size="sm" c="dimmed">Логин:</Text>
<Text fw={500}>{user?.login || '—'}</Text>
</Group>
{user?.last_login && (
<Group justify="space-between">
<Text size="sm" c="dimmed">Последний вход:</Text>
<Text size="sm">
{new Date(user.last_login).toLocaleString('ru-RU')}
</Text>
</Group>
)}
{user?.last_ip_login && (
<Group justify="space-between">
<Text size="sm" c="dimmed">Последний IP:</Text>
<Text size="sm" ff="monospace">{user.last_ip_login}</Text>
</Group>
)}
</Stack>
</Paper>
{/* Смена пароля */}
<Paper withBorder p="md">
<Group gap="xs" mb="md">
<IconKey size={20} color="var(--mantine-color-blue-6)" />
<Text fw={600} size="lg">Смена пароля</Text>
</Group>
<Alert
icon={<IconAlertCircle size={16} />}
color="yellow"
variant="light"
mb="md"
>
<Text size="sm">
После смены пароля вам нужно будет войти заново на всех устройствах.
</Text>
</Alert>
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap="md">
<PasswordInput
label="Текущий пароль"
placeholder="Введите текущий пароль"
required
{...form.getInputProps('current_password')}
/>
<Stack gap="lg" maw={640}>
<PageHeader title="Настройки" description="Профиль, оформление и безопасность" />
<Panel title="Профиль" extra={<Badge color="gray">{role}</Badge>}>
<Box mx={-0}>
<Row label="Логин"><Text size="sm" fw={500}>{user?.login || '—'}</Text></Row>
{user?.last_login && (
<>
<Divider />
<Row label="Последний вход">
<Text size="sm">{dayjs(user.last_login).format('D MMM YYYY, HH:mm')}</Text>
</Row>
</>
)}
{user?.last_ip_login && (
<>
<Divider />
<Row label="Последний IP">
<Text size="sm" ff="monospace">{user.last_ip_login}</Text>
</Row>
</>
)}
</Box>
</Panel>
<Panel title="Оформление">
<Group justify="space-between" wrap="wrap" gap="sm">
<Box>
<Text size="sm">Тема интерфейса</Text>
<Text size="xs" c="dimmed">«Системная» следует настройкам вашей ОС</Text>
</Box>
<SegmentedControl
value={colorScheme}
onChange={(v) => setColorScheme(v as 'light' | 'dark' | 'auto')}
data={[
{ value: 'light', label: <Center style={{ gap: 6 }}><IconSun size={14} />Светлая</Center> },
{ value: 'dark', label: <Center style={{ gap: 6 }}><IconMoon size={14} />Тёмная</Center> },
{ value: 'auto', label: <Center style={{ gap: 6 }}><IconDeviceDesktop size={14} />Системная</Center> },
]}
/>
</Group>
</Panel>
<Panel title="Смена пароля">
<form onSubmit={form.onSubmit((v) => setPending(v.new_password))}>
<Stack gap="md">
<PasswordInput
label="Текущий пароль"
autoComplete="current-password"
{...form.getInputProps('current_password')}
/>
<Divider />
<Stack gap="xs">
<PasswordInput
label="Новый пароль"
placeholder="Минимум 6 символов"
required
description="Минимум 6 символов"
autoComplete="new-password"
{...form.getInputProps('new_password')}
/>
<PasswordInput
label="Подтвердите новый пароль"
placeholder="Повторите новый пароль"
required
{...form.getInputProps('confirm_password')}
/>
<Group justify="flex-end" mt="md">
<Button
type="submit"
loading={loading}
leftSection={<IconShield size={16} />}
>
Изменить пароль
</Button>
</Group>
<PasswordStrength value={form.values.new_password} />
</Stack>
</form>
</Paper>
</Stack>
</Box>
<PasswordInput
label="Повторите новый пароль"
autoComplete="new-password"
{...form.getInputProps('confirm_password')}
/>
<Group justify="space-between" mt="xs" wrap="nowrap">
<Text size="xs" c="dimmed">После смены пароля потребуется войти заново</Text>
<Button type="submit">Изменить пароль</Button>
</Group>
</Stack>
</form>
</Panel>
<ConfirmModal
opened={pending !== null}
onClose={() => setPending(null)}
onConfirm={handleConfirm}
title="Изменить пароль?"
message="Вы будете разлогинены на всех устройствах и должны будете войти заново."
confirmLabel="Изменить"
danger
loading={loading}
/>
</Stack>
)
}