Добавлен новый компонент AccountIntegration для управления интеграциями и токенами. Обновлена страница аккаунта для интеграции нового компонента, добавлены функции создания, редактирования и удаления токенов. Также добавлены компоненты CreateTokenDialog и IntegrationTokensTable для улучшения взаимодействия с пользователем и отображения токенов.

This commit is contained in:
Redsandyg 2025-06-09 12:53:07 +03:00
parent 5614894e49
commit 9ea671b57c
4 changed files with 414 additions and 1 deletions

View File

@ -17,13 +17,15 @@ import {
Lock as KeyIcon,
Visibility as EyeIcon,
VisibilityOff as EyeOffIcon,
Notifications as BellIcon
Notifications as BellIcon,
IntegrationInstructions as IntegrationIcon
} from "@mui/icons-material";
import AccountProfile from "../../components/AccountProfile";
import AccountSecurity from "../../components/AccountSecurity";
import AccountNotifications from "../../components/AccountNotifications";
import AccountAgentTransactionSection from "../../components/AccountAgentTransactionSection";
import TabsNav from "../../components/TabsNav";
import AccountIntegration from "../../components/AccountIntegration";
const initialNotifications = {
emailNotifications: true,
@ -48,6 +50,7 @@ export default function AccountPage() {
{ id: "security", label: "Безопасность", icon: <KeyIcon fontSize="small" /> },
{ id: "notifications", label: "Уведомления", icon: <BellIcon fontSize="small" /> },
{ id: "agent-transactions", label: "Транзакции агентов", icon: <WorkIcon fontSize="small" /> },
{ id: "integration", label: "Интеграции", icon: <IntegrationIcon fontSize="small" /> },
];
return (
@ -69,6 +72,9 @@ export default function AccountPage() {
{activeTab === "agent-transactions" && (
<AccountAgentTransactionSection />
)}
{activeTab === "integration" && (
<AccountIntegration />
)}
</div>
</AuthGuard>
);

View File

@ -0,0 +1,121 @@
"use client";
import React, { useState, useMemo } from "react";
import {
Box,
Button,
Typography,
Dialog,
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
IconButton
} from "@mui/material";
import CreateTokenDialog from "./CreateTokenDialog";
import IntegrationTokensTable from "./IntegrationTokensTable";
import styles from "../styles/account.module.css";
// Компонент для управления интеграциями и токенами
interface Token {
id: string;
description: string;
token: string;
createdAt: string;
lastUsedAt?: string;
}
const AccountIntegration = () => {
const [tokens, setTokens] = useState<Token[]>([]);
const [openCreateDialog, setOpenCreateDialog] = useState(false);
const [tokenDescription, setTokenDescription] = useState("");
const [showTokenWarning, setShowTokenWarning] = useState(false);
const [showTokenCreatedSuccess, setShowTokenCreatedSuccess] = useState(false);
const [openEditDialog, setOpenEditDialog] = useState(false);
const [editingToken, setEditingToken] = useState<Token | null>(null);
const handleOpenCreateDialog = () => {
setOpenCreateDialog(true);
setTokenDescription("");
setShowTokenWarning(false);
};
const handleCloseCreateDialog = () => {
setOpenCreateDialog(false);
};
const handleOpenEditDialog = (token: Token) => {
setEditingToken(token);
setOpenEditDialog(true);
};
const handleCloseEditDialog = () => {
setOpenEditDialog(false);
setEditingToken(null);
};
const handleTokenGenerate = (description: string, newTokenValue: string) => {
const newToken: Token = {
id: (tokens.length + 1).toString(),
description: description,
token: newTokenValue,
createdAt: new Date().toLocaleString(),
lastUsedAt: "Никогда",
};
setTokens([...tokens, newToken]);
setShowTokenCreatedSuccess(true);
setTimeout(() => setShowTokenCreatedSuccess(false), 1500);
};
const handleTokenUpdate = (updatedDescription: string) => {
if (editingToken) {
setTokens(prevTokens =>
prevTokens.map(token =>
token.id === editingToken.id ? { ...token, description: updatedDescription } : token
)
);
setOpenEditDialog(false);
setEditingToken(null);
}
};
const handleDeleteToken = (tokenId: string) => {
setTokens(prevTokens => prevTokens.filter(token => token.id !== tokenId));
};
return (
<Box sx={{ padding: 2 }}>
<Typography variant="h5" gutterBottom>
Управление токенами интеграции
</Typography>
<IntegrationTokensTable
tokens={tokens}
onOpenCreateDialog={handleOpenCreateDialog}
onOpenEditDialog={handleOpenEditDialog}
onDeleteToken={handleDeleteToken}
/>
<CreateTokenDialog
open={openCreateDialog}
onClose={handleCloseCreateDialog}
onTokenGenerate={handleTokenGenerate}
/>
<CreateTokenDialog
open={openEditDialog}
onClose={handleCloseEditDialog}
isEditMode={true}
initialDescription={editingToken?.description || ""}
onTokenUpdate={handleTokenUpdate}
/>
{showTokenCreatedSuccess && (
<div className={styles.copySuccessToast}>
Токен успешно создан!
</div>
)}
</Box>
);
};
export default AccountIntegration;

View File

@ -0,0 +1,157 @@
"use client";
import React, { useState, useEffect } from "react";
import {
Box,
Button,
TextField,
Typography,
Dialog,
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
Snackbar,
Alert,
} from "@mui/material";
import { ContentCopy as ContentCopyIcon } from "@mui/icons-material";
import styles from "../styles/account.module.css";
interface CreateTokenDialogProps {
open: boolean;
onClose: () => void;
onTokenGenerate?: (description: string, token: string) => void;
isEditMode?: boolean;
initialDescription?: string;
onTokenUpdate?: (updatedDescription: string) => void;
}
const CreateTokenDialog: React.FC<CreateTokenDialogProps> = ({
open,
onClose,
onTokenGenerate,
isEditMode,
initialDescription,
onTokenUpdate,
}) => {
const [tokenDescription, setTokenDescription] = useState("");
const [generatedToken, setGeneratedToken] = useState("");
const [showTokenWarning, setShowTokenWarning] = useState(false);
const [showCopySuccess, setShowCopySuccess] = useState(false);
useEffect(() => {
if (!open) {
setTokenDescription("");
setGeneratedToken("");
setShowTokenWarning(false);
setShowCopySuccess(false);
} else if (isEditMode && initialDescription) {
setTokenDescription(initialDescription);
} else {
setTokenDescription("");
setGeneratedToken("");
setShowTokenWarning(false);
setShowCopySuccess(false);
}
}, [open, isEditMode, initialDescription]);
const handleGenerateToken = () => {
if (tokenDescription.trim() === "") return;
const newTokenValue = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
setGeneratedToken(newTokenValue);
setShowTokenWarning(true);
if (onTokenGenerate) {
onTokenGenerate(tokenDescription, newTokenValue);
}
};
const handleUpdateDescription = () => {
if (tokenDescription.trim() === "") return;
if (onTokenUpdate) {
onTokenUpdate(tokenDescription);
}
onClose();
};
const handleCopy = () => {
if (!generatedToken) return;
if (typeof navigator !== "undefined" && navigator.clipboard) {
navigator.clipboard.writeText(generatedToken);
} else {
const textarea = document.createElement("textarea");
textarea.value = generatedToken;
document.body.appendChild(textarea);
textarea.select();
document.execCommand("copy");
document.body.removeChild(textarea);
}
setShowCopySuccess(true);
setTimeout(() => setShowCopySuccess(false), 1500);
};
return (
<Dialog open={open} onClose={onClose}>
<DialogTitle>{isEditMode ? "Редактировать описание токена" : "Создать новый токен"}</DialogTitle>
<DialogContent>
{isEditMode || !generatedToken ? (
<>
<DialogContentText>
{isEditMode ? "Введите новое описание для токена." : "Пожалуйста, введите описание для вашего нового токена."}
</DialogContentText>
<TextField
autoFocus
margin="dense"
label="Описание токена"
type="text"
fullWidth
variant="outlined"
value={tokenDescription}
onChange={(e) => setTokenDescription(e.target.value)}
/>
</>
) : (
<Box sx={{ marginTop: 2, padding: 1, border: '1px dashed grey', borderRadius: 1 }}>
<Typography variant="subtitle1">Ваш новый токен:</Typography>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Typography variant="h6" color="primary" sx={{ wordBreak: 'break-all' }}>
{generatedToken}
</Typography>
<Button
variant="outlined"
size="small"
onClick={handleCopy}
startIcon={<ContentCopyIcon fontSize="small" />}
>
Копировать
</Button>
</Box>
{showTokenWarning && (
<Typography variant="body2" color="error" sx={{ marginTop: 1 }}>
Внимание: Этот токен не может быть восстановлен. Пожалуйста, скопируйте его сейчас!
</Typography>
)}
{showCopySuccess && (
<div className={styles.copySuccessToast}>
Токен скопирован!
</div>
)}
</Box>
)}
</DialogContent>
<DialogActions>
{!(isEditMode || generatedToken) ? (
<Button onClick={onClose}>Отмена</Button>
) : null}
<Button
onClick={isEditMode ? handleUpdateDescription : (!generatedToken ? handleGenerateToken : onClose)}
disabled={!tokenDescription && !(isEditMode || generatedToken)}
variant="contained"
>
{isEditMode ? "Сохранить" : (!generatedToken ? "Создать" : "ОК")}
</Button>
</DialogActions>
</Dialog>
);
};
export default CreateTokenDialog;

View File

@ -0,0 +1,129 @@
"use client";
import React, { useMemo } from "react";
import {
Box,
Button,
Typography,
IconButton
} from "@mui/material";
import { MaterialReactTable, type MRT_ColumnDef, useMaterialReactTable } from "material-react-table";
import { Add as AddIcon, Edit as EditIcon, Delete as DeleteIcon } from "@mui/icons-material";
interface Token {
id: string;
description: string;
token: string;
createdAt: string;
lastUsedAt?: string;
}
interface IntegrationTokensTableProps {
tokens: Token[];
onOpenCreateDialog: () => void;
onOpenEditDialog: (token: Token) => void;
onDeleteToken: (tokenId: string) => void;
}
const IntegrationTokensTable: React.FC<IntegrationTokensTableProps> = ({
tokens,
onOpenCreateDialog,
onOpenEditDialog,
onDeleteToken,
}) => {
const columns = useMemo<MRT_ColumnDef<Token>[]>(
() => [
{
accessorKey: "description",
header: "Описание",
size: 200,
Cell: ({ renderedCellValue }) => renderedCellValue,
},
{
accessorKey: "token",
header: "Токен",
size: 250,
Cell: ({ renderedCellValue }) => {
const tokenValue = renderedCellValue as string;
const maskedToken = tokenValue.substring(0, 5) + "***********************" + tokenValue.substring(tokenValue.length - 4);
return (
<Typography sx={{ overflowWrap: 'break-word' }}>
{maskedToken}
</Typography>
);
},
},
{
accessorKey: "createdAt",
header: "Дата создания",
size: 150,
Cell: ({ renderedCellValue }) => renderedCellValue,
},
{
accessorKey: "lastUsedAt",
header: "Последнее использование",
size: 150,
Cell: ({ renderedCellValue }) => renderedCellValue,
},
{
id: 'actions',
header: 'Действия',
size: 100,
Cell: ({ row }) => (
<Box sx={{ display: 'flex', gap: '0.5rem' }}>
<IconButton
onClick={() => onOpenEditDialog(row.original)}
color="primary"
>
<EditIcon />
</IconButton>
<IconButton
onClick={() => onDeleteToken(row.original.id)}
color="error"
>
<DeleteIcon />
</IconButton>
</Box>
),
},
],
[onOpenEditDialog, onDeleteToken],
);
const table = useMaterialReactTable({
columns,
data: tokens,
enableColumnActions: false,
enableColumnFilters: true,
enablePagination: true,
enableSorting: true,
enableBottomToolbar: true,
enableTopToolbar: true,
enableDensityToggle: true,
enableGlobalFilter: true,
enableHiding: true,
renderEmptyRowsFallback: () => (
<Box sx={{ padding: 2, textAlign: 'center' }}>
<Typography variant="body1">
У вас пока нет созданных токенов.
</Typography>
</Box>
),
muiTableBodyCellProps: { sx: { fontSize: 14 } },
muiTableHeadCellProps: { sx: { fontWeight: 700 } },
initialState: { pagination: { pageSize: 10, pageIndex: 0 } },
renderTopToolbarCustomActions: () => (
<Button
variant="contained"
startIcon={<AddIcon />}
onClick={onOpenCreateDialog}
sx={{ marginBottom: 0 }}
>
Создать новый токен
</Button>
),
});
return <MaterialReactTable table={table} />;
};
export default IntegrationTokensTable;