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 { useLocation } from 'react-router-dom'
import { useAuth } from '@/hooks/useAuth' import { useAuth } from '@/hooks/useAuth'
import { findTrail } from './navigation' import { findTrail } from './navigation'
import { ColorSchemeToggle } from '@/components/ui/ColorSchemeToggle'
interface HeaderProps { interface HeaderProps {
toggleMobile: () => void toggleMobile: () => void
@ -15,20 +16,6 @@ interface HeaderProps {
desktopOpened: boolean 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) { export default function Header({ toggleMobile, toggleDesktop, mobileOpened, desktopOpened }: HeaderProps) {
const { user, logout } = useAuth() const { user, logout } = useAuth()
const { pathname } = useLocation() 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 { useState } from 'react'
import { import { Alert, Box, Button, Paper, PasswordInput, Stack, Text, TextInput, Title } from '@mantine/core'
Container,
Paper,
Title,
Text,
TextInput,
PasswordInput,
Button,
Group,
} from '@mantine/core'
import { useForm } from '@mantine/form' import { useForm } from '@mantine/form'
import { notifications } from '@mantine/notifications' import { IconAlertCircle } from '@tabler/icons-react'
import { useAuth } from '@/hooks/useAuth' import { useAuth } from '@/hooks/useAuth'
import { ColorSchemeToggle } from '@/components/ui/ColorSchemeToggle'
export default function Login() { export default function Login() {
const { login } = useAuth() const { login } = useAuth()
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [capsLock, setCapsLock] = useState(false)
const form = useForm({ const form = useForm({
initialValues: { initialValues: { login: '', password: '' },
login: '',
password: '',
},
validate: { validate: {
login: (value: string | any[]) => (value.length < 3 ? 'Логин должен содержать минимум 3 символа' : null), login: (v) => (v.trim().length < 3 ? 'Минимум 3 символа' : null),
password: (value: string | any[]) => (value.length < 4 ? 'Пароль должен содержать минимум 4 символа' : null), password: (v) => (v.length < 4 ? 'Минимум 4 символа' : null),
}, },
}) })
const handleSubmit = async (values: typeof form.values) => { const handleSubmit = async (values: typeof form.values) => {
setLoading(true) setLoading(true)
setError(null)
try { try {
await login(values.login, values.password) await login(values.login.trim(), values.password)
notifications.show({ } catch (e: any) {
title: 'Успешный вход', setError(e.response?.data?.error_description || 'Неверный логин или пароль')
message: `Добро пожаловать, ${values.login}!`,
color: 'green',
})
} catch (error: any) {
notifications.show({
title: 'Ошибка входа',
message: error.response?.data?.error_description || 'Неверный логин или пароль',
color: 'red',
})
} finally { } finally {
setLoading(false) setLoading(false)
} }
} }
return ( return (
<Container size={420} my={40}> <Box
<Title ta="center" mb="md"> mih="100dvh"
Корпоративная панель администратора p="md"
</Title> style={{ background: 'var(--app-bg)', display: 'grid', placeItems: 'center', position: 'relative' }}
<Text c="dimmed" size="sm" ta="center" mb="xl"> >
Введите свои данные для входа в систему <Box style={{ position: 'absolute', top: 16, right: 16 }}>
</Text> <ColorSchemeToggle />
</Box>
<Paper withBorder shadow="md" p={30} mt={30} radius="md"> <Stack w="100%" maw={400} gap="xl">
<form onSubmit={form.onSubmit(handleSubmit)}> <Stack align="center" gap={4}>
<TextInput <Box
label="Логин" w={44}
placeholder="admin" h={44}
required mb="xs"
{...form.getInputProps('login')} 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 <Paper p="xl">
label="Пароль" <form onSubmit={form.onSubmit(handleSubmit)}>
placeholder="your password" <Stack gap="md">
required {error && (
mt="md" <Alert color="red" icon={<IconAlertCircle size={16} />} p="sm">
{...form.getInputProps('password')} {error}
/> </Alert>
)}
<Group justify="space-between" mt="xl"> <TextInput
<Button type="submit" fullWidth loading={loading}> label="Логин"
Войти placeholder="admin"
</Button> autoComplete="username"
</Group> autoFocus
</form> {...form.getInputProps('login')}
</Paper> />
</Container>
<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 { useState } from 'react'
import { import {
Paper, Badge,
Box,
Button,
Center,
Divider,
Group,
PasswordInput,
SegmentedControl,
Stack, Stack,
Text, Text,
PasswordInput, useMantineColorScheme,
Button,
Group,
Alert,
Box,
Title,
Divider,
} from '@mantine/core' } from '@mantine/core'
import { useForm } from '@mantine/form' import { useForm } from '@mantine/form'
import { notifications } from '@mantine/notifications' import { notifications } from '@mantine/notifications'
import { modals } from '@mantine/modals' import { IconDeviceDesktop, IconMoon, IconSun } from '@tabler/icons-react'
import { IconShield, IconAlertCircle, IconKey } from '@tabler/icons-react' import dayjs from 'dayjs'
import { authApi } from '@/api/auth' import { authApi } from '@/api/auth'
import { useAuth } from '@/hooks/useAuth' 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() { export default function SettingsPage() {
const { user, logout } = useAuth()
const { colorScheme, setColorScheme } = useMantineColorScheme()
const [loading, setLoading] = useState(false) 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({ const form = useForm({
initialValues: { initialValues: { current_password: '', new_password: '', confirm_password: '' },
current_password: '',
new_password: '',
confirm_password: '',
},
validate: { validate: {
current_password: (value) => current_password: (v) => (v ? null : 'Введите текущий пароль'),
value.length === 0 ? 'Введите текущий пароль' : null, new_password: (v, values) => {
new_password: (value) => { if (!v) return 'Введите новый пароль'
if (value.length === 0) return 'Введите новый пароль' if (v.length < 6) return 'Минимум 6 символов'
if (value.length < 6) return 'Пароль должен содержать минимум 6 символов' if (v === values.current_password) return 'Новый пароль совпадает с текущим'
return null return null
}, },
confirm_password: (value, values) => confirm_password: (v, values) => (v !== values.new_password ? 'Пароли не совпадают' : null),
value !== values.new_password ? 'Пароли не совпадают' : null,
}, },
}) })
const handleSubmit = async (values: typeof form.values) => { const handleConfirm = async () => {
// Подтверждение через модальное окно setLoading(true)
modals.openConfirmModal({ try {
title: 'Подтвердите смену пароля', await authApi.updateProfile({
children: ( current_password: form.values.current_password,
<Text size="sm"> password: form.values.new_password,
Вы уверены, что хотите изменить пароль? После смены пароля вам нужно будет })
войти заново на всех устройствах. setPending(null)
</Text> form.reset()
), notifications.show({
labels: { confirm: 'Изменить пароль', cancel: 'Отмена' }, title: 'Пароль изменён',
confirmProps: { color: 'red' }, message: 'Сейчас вы будете перенаправлены на страницу входа',
onConfirm: async () => { color: 'green',
setLoading(true) })
try { setTimeout(() => logout(), 1500)
await authApi.updateProfile({ password: values.new_password }) } catch (e: any) {
setPending(null)
notifications.show({ notifications.show({
title: 'Успешно', title: 'Ошибка',
message: 'Пароль успешно изменен', message: e.response?.data?.error_description || 'Не удалось изменить пароль',
color: 'green', color: 'red',
}) })
} finally {
form.reset() setLoading(false)
}
// Разлогиниваем пользователя, чтобы он вошёл заново
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)
}
},
})
} }
return ( return (
<Box maw={600}> <Stack gap="lg" maw={640}>
<Stack gap="lg"> <PageHeader title="Настройки" description="Профиль, оформление и безопасность" />
<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')}
/>
<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 /> <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 <PasswordInput
label="Новый пароль" label="Новый пароль"
placeholder="Минимум 6 символов" description="Минимум 6 символов"
required autoComplete="new-password"
{...form.getInputProps('new_password')} {...form.getInputProps('new_password')}
/> />
<PasswordStrength value={form.values.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>
</Stack> </Stack>
</form>
</Paper> <PasswordInput
</Stack> label="Повторите новый пароль"
</Box> 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>
) )
} }