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

This commit is contained in:
Redsandyg 2025-06-09 15:28:01 +03:00
parent 9ea671b57c
commit 5380866af3
4 changed files with 237 additions and 213 deletions

View File

@ -1,5 +1,5 @@
"use client"; "use client";
import React, { useState, useMemo } from "react"; import React, { useState, useMemo, useEffect } from "react";
import { import {
Box, Box,
Button, Button,
@ -14,29 +14,57 @@ import {
import CreateTokenDialog from "./CreateTokenDialog"; import CreateTokenDialog from "./CreateTokenDialog";
import IntegrationTokensTable from "./IntegrationTokensTable"; import IntegrationTokensTable from "./IntegrationTokensTable";
import styles from "../styles/account.module.css"; import styles from "../styles/account.module.css";
import Cookies from "js-cookie";
import { Token } from "../types/tokens";
// Компонент для управления интеграциями и токенами // Компонент для управления интеграциями и токенами
interface Token { // interface Token {
id: string; // description: string;
description: string; // masked_token: string;
token: string; // rawToken?: string;
createdAt: string; // create_dttm: string;
lastUsedAt?: string; // use_dttm?: string;
} // }
const AccountIntegration = () => { const AccountIntegration = () => {
const [tokens, setTokens] = useState<Token[]>([]); const [tokens, setTokens] = useState<Token[]>([]);
const [openCreateDialog, setOpenCreateDialog] = useState(false); const [openCreateDialog, setOpenCreateDialog] = useState(false);
const [tokenDescription, setTokenDescription] = useState("");
const [showTokenWarning, setShowTokenWarning] = useState(false);
const [showTokenCreatedSuccess, setShowTokenCreatedSuccess] = useState(false); const [showTokenCreatedSuccess, setShowTokenCreatedSuccess] = useState(false);
const [createdRawToken, setCreatedRawToken] = useState<string | null>(null);
const [openEditDialog, setOpenEditDialog] = useState(false); const [openEditDialog, setOpenEditDialog] = useState(false);
const [editingToken, setEditingToken] = useState<Token | null>(null); const [editingToken, setEditingToken] = useState<Token | null>(null);
const fetchTokens = async () => {
try {
const token = Cookies.get("access_token");
if (!token) {
console.error("Access token not found");
return;
}
const res = await fetch("/api/account/integration-tokens", {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`
},
});
if (!res.ok) {
throw new Error(`HTTP error! status: ${res.status}`);
}
const data: Token[] = await res.json();
setTokens(data);
} catch (error) {
console.error("Failed to fetch tokens:", error);
}
};
useEffect(() => {
fetchTokens();
}, []);
const handleOpenCreateDialog = () => { const handleOpenCreateDialog = () => {
setOpenCreateDialog(true); setOpenCreateDialog(true);
setTokenDescription(""); setCreatedRawToken(null);
setShowTokenWarning(false);
}; };
const handleCloseCreateDialog = () => { const handleCloseCreateDialog = () => {
@ -53,33 +81,96 @@ const AccountIntegration = () => {
setEditingToken(null); setEditingToken(null);
}; };
const handleTokenGenerate = (description: string, newTokenValue: string) => { const handleTokenGenerate = async (description: string) => {
const newToken: Token = { try {
id: (tokens.length + 1).toString(), const authToken = Cookies.get("access_token");
description: description, if (!authToken) {
token: newTokenValue, console.error("Access token not found");
createdAt: new Date().toLocaleString(), return;
lastUsedAt: "Никогда", }
};
setTokens([...tokens, newToken]);
setShowTokenCreatedSuccess(true);
setTimeout(() => setShowTokenCreatedSuccess(false), 1500);
};
const handleTokenUpdate = (updatedDescription: string) => { const res = await fetch("/api/account/integration-tokens", {
if (editingToken) { method: "POST",
setTokens(prevTokens => headers: {
prevTokens.map(token => "Content-Type": "application/json",
token.id === editingToken.id ? { ...token, description: updatedDescription } : token "Authorization": `Bearer ${authToken}`
) },
); body: JSON.stringify({ description: description })
setOpenEditDialog(false); });
setEditingToken(null);
if (!res.ok) {
const errorData = await res.json();
throw new Error(errorData.detail || "Ошибка генерации токена");
}
const newTokenData: Token = await res.json();
await fetchTokens();
setCreatedRawToken(newTokenData.rawToken || null);
setShowTokenCreatedSuccess(true);
setTimeout(() => setShowTokenCreatedSuccess(false), 3000);
} catch (error: any) {
console.error("Ошибка при генерации токена:", error.message);
} }
}; };
const handleDeleteToken = (tokenId: string) => { const handleTokenUpdate = async (id: number, updatedDescription: string) => {
setTokens(prevTokens => prevTokens.filter(token => token.id !== tokenId)); try {
const authToken = Cookies.get("access_token");
if (!authToken) {
console.error("Access token not found");
return;
}
const res = await fetch("/api/account/integration-tokens/update-description", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${authToken}`
},
body: JSON.stringify({ id: id, description: updatedDescription })
});
if (!res.ok) {
const errorData = await res.json();
throw new Error(errorData.detail || "Ошибка обновления описания токена");
}
// После успешного обновления, обновим список токенов
await fetchTokens();
setOpenEditDialog(false);
setEditingToken(null);
} catch (error: any) {
console.error("Ошибка при обновлении токена:", error.message);
}
};
const handleDeleteToken = async (id: number) => {
try {
const authToken = Cookies.get("access_token");
if (!authToken) {
console.error("Access token not found");
return;
}
const res = await fetch(`/api/account/integration-tokens/${id}`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${authToken}`
},
});
if (!res.ok) {
const errorData = await res.json();
throw new Error(errorData.detail || "Ошибка удаления токена");
}
await fetchTokens();
} catch (error: any) {
console.error("Ошибка при удалении токена:", error.message);
}
}; };
return ( return (
@ -99,6 +190,7 @@ const AccountIntegration = () => {
open={openCreateDialog} open={openCreateDialog}
onClose={handleCloseCreateDialog} onClose={handleCloseCreateDialog}
onTokenGenerate={handleTokenGenerate} onTokenGenerate={handleTokenGenerate}
generatedToken={createdRawToken}
/> />
<CreateTokenDialog <CreateTokenDialog
@ -106,14 +198,9 @@ const AccountIntegration = () => {
onClose={handleCloseEditDialog} onClose={handleCloseEditDialog}
isEditMode={true} isEditMode={true}
initialDescription={editingToken?.description || ""} initialDescription={editingToken?.description || ""}
editingTokenId={editingToken?.id || 0}
onTokenUpdate={handleTokenUpdate} onTokenUpdate={handleTokenUpdate}
/> />
{showTokenCreatedSuccess && (
<div className={styles.copySuccessToast}>
Токен успешно создан!
</div>
)}
</Box> </Box>
); );
}; };

View File

@ -8,96 +8,73 @@ import {
Dialog, Dialog,
DialogActions, DialogActions,
DialogContent, DialogContent,
DialogContentText,
DialogTitle, DialogTitle,
Snackbar,
Alert,
} from "@mui/material"; } from "@mui/material";
import { ContentCopy as ContentCopyIcon } from "@mui/icons-material";
import styles from "../styles/account.module.css"; import styles from "../styles/account.module.css";
import { Token } from "../types/tokens";
interface CreateTokenDialogProps { interface CreateTokenDialogProps {
open: boolean; open: boolean;
onClose: () => void; onClose: () => void;
onTokenGenerate?: (description: string, token: string) => void; onTokenGenerate?: (description: string) => Promise<void>;
isEditMode?: boolean; isEditMode?: boolean;
initialDescription?: string; initialDescription?: string;
onTokenUpdate?: (updatedDescription: string) => void; editingTokenId?: number;
onTokenUpdate?: (id: number, description: string) => void;
generatedToken?: string | null;
} }
const CreateTokenDialog: React.FC<CreateTokenDialogProps> = ({ const CreateTokenDialog: React.FC<CreateTokenDialogProps> = ({
open, open,
onClose, onClose,
onTokenGenerate, onTokenGenerate,
isEditMode, isEditMode = false,
initialDescription, initialDescription = "",
onTokenUpdate, onTokenUpdate,
generatedToken,
editingTokenId,
}) => { }) => {
const [tokenDescription, setTokenDescription] = useState(""); const [description, setDescription] = useState(initialDescription);
const [generatedToken, setGeneratedToken] = useState(""); const [showWarning, setShowWarning] = useState(false);
const [showTokenWarning, setShowTokenWarning] = useState(false);
const [showCopySuccess, setShowCopySuccess] = useState(false);
useEffect(() => { useEffect(() => {
if (!open) { if (open) {
setTokenDescription(""); setDescription(initialDescription);
setGeneratedToken(""); setShowWarning(false);
setShowTokenWarning(false);
setShowCopySuccess(false);
} else if (isEditMode && initialDescription) {
setTokenDescription(initialDescription);
} else {
setTokenDescription("");
setGeneratedToken("");
setShowTokenWarning(false);
setShowCopySuccess(false);
} }
}, [open, isEditMode, initialDescription]); }, [open, initialDescription]);
const handleGenerateToken = () => { const handleGenerateClick = async () => {
if (tokenDescription.trim() === "") return; if (description.trim() === "") {
setShowWarning(true);
const newTokenValue = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); return;
setGeneratedToken(newTokenValue);
setShowTokenWarning(true);
if (onTokenGenerate) {
onTokenGenerate(tokenDescription, newTokenValue);
} }
await onTokenGenerate?.(description);
}; };
const handleUpdateDescription = () => { const handleUpdateClick = () => {
if (tokenDescription.trim() === "") return; if (description.trim() === "") {
if (onTokenUpdate) { setShowWarning(true);
onTokenUpdate(tokenDescription); return;
} }
console.log("Attempting to update token. editingTokenId:", editingTokenId, "Description:", description);
if (onTokenUpdate && typeof editingTokenId === 'number') {
onTokenUpdate(editingTokenId, description);
onClose(); onClose();
};
const handleCopy = () => {
if (!generatedToken) return;
if (typeof navigator !== "undefined" && navigator.clipboard) {
navigator.clipboard.writeText(generatedToken);
} else { } else {
const textarea = document.createElement("textarea"); console.error("Cannot update token: onTokenUpdate is missing or editingTokenId is invalid.", {onTokenUpdateExists: !!onTokenUpdate, editingTokenIdValue: editingTokenId});
textarea.value = generatedToken;
document.body.appendChild(textarea);
textarea.select();
document.execCommand("copy");
document.body.removeChild(textarea);
} }
setShowCopySuccess(true);
setTimeout(() => setShowCopySuccess(false), 1500);
}; };
return ( return (
<Dialog open={open} onClose={onClose}> <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
<DialogTitle>{isEditMode ? "Редактировать описание токена" : "Создать новый токен"}</DialogTitle> <DialogTitle>{isEditMode ? "Редактировать токен" : "Создать новый токен"}</DialogTitle>
<DialogContent> <DialogContent>
{isEditMode || !generatedToken ? ( {showWarning && (
<> <Typography color="error" variant="body2" sx={{ mb: 2 }}>
<DialogContentText> Пожалуйста, введите описание токена.
{isEditMode ? "Введите новое описание для токена." : "Пожалуйста, введите описание для вашего нового токена."} </Typography>
</DialogContentText> )}
<TextField <TextField
autoFocus autoFocus
margin="dense" margin="dense"
@ -105,50 +82,36 @@ const CreateTokenDialog: React.FC<CreateTokenDialogProps> = ({
type="text" type="text"
fullWidth fullWidth
variant="outlined" variant="outlined"
value={tokenDescription} value={description}
onChange={(e) => setTokenDescription(e.target.value)} onChange={(e) => setDescription(e.target.value)}
error={showWarning}
helperText={showWarning ? "Описание не может быть пустым" : ""}
/> />
</> {!isEditMode && generatedToken && (
) : ( <Box sx={{ mt: 2, p: 2, border: '1px solid #ccc', borderRadius: '4px', backgroundColor: '#f0f0f0'}}>
<Box sx={{ marginTop: 2, padding: 1, border: '1px dashed grey', borderRadius: 1 }}> <Typography variant="subtitle2">Созданный токен:</Typography>
<Typography variant="subtitle1">Ваш новый токен:</Typography> <Box sx={{ display: 'flex', alignItems: 'center', gap: '8px'}}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}> <Typography variant="body2" sx={{ wordBreak: 'break-all'}}>
<Typography variant="h6" color="primary" sx={{ wordBreak: 'break-all' }}>
{generatedToken} {generatedToken}
</Typography> </Typography>
<Button
variant="outlined"
size="small"
onClick={handleCopy}
startIcon={<ContentCopyIcon fontSize="small" />}
>
Копировать
</Button>
</Box> </Box>
{showTokenWarning && ( <Typography variant="caption" color="textSecondary">
<Typography variant="body2" color="error" sx={{ marginTop: 1 }}> Скопируйте этот токен. Он будет виден только сейчас.
Внимание: Этот токен не может быть восстановлен. Пожалуйста, скопируйте его сейчас!
</Typography> </Typography>
)}
{showCopySuccess && (
<div className={styles.copySuccessToast}>
Токен скопирован!
</div>
)}
</Box> </Box>
)} )}
</DialogContent> </DialogContent>
<DialogActions> <DialogActions>
{!(isEditMode || generatedToken) ? ( {!generatedToken && <Button onClick={onClose}>Отмена</Button>}
<Button onClick={onClose}>Отмена</Button> {isEditMode ? (
) : null} <Button onClick={handleUpdateClick} variant="contained">
<Button Сохранить
onClick={isEditMode ? handleUpdateDescription : (!generatedToken ? handleGenerateToken : onClose)}
disabled={!tokenDescription && !(isEditMode || generatedToken)}
variant="contained"
>
{isEditMode ? "Сохранить" : (!generatedToken ? "Создать" : "ОК")}
</Button> </Button>
) : (
<Button onClick={generatedToken ? onClose : handleGenerateClick} variant="contained">
{generatedToken ? "ОК" : "Создать"}
</Button>
)}
</DialogActions> </DialogActions>
</Dialog> </Dialog>
); );

View File

@ -8,20 +8,13 @@ import {
} from "@mui/material"; } from "@mui/material";
import { MaterialReactTable, type MRT_ColumnDef, useMaterialReactTable } from "material-react-table"; import { MaterialReactTable, type MRT_ColumnDef, useMaterialReactTable } from "material-react-table";
import { Add as AddIcon, Edit as EditIcon, Delete as DeleteIcon } from "@mui/icons-material"; import { Add as AddIcon, Edit as EditIcon, Delete as DeleteIcon } from "@mui/icons-material";
import { Token } from "../types/tokens";
interface Token {
id: string;
description: string;
token: string;
createdAt: string;
lastUsedAt?: string;
}
interface IntegrationTokensTableProps { interface IntegrationTokensTableProps {
tokens: Token[]; tokens: Token[];
onOpenCreateDialog: () => void; onOpenCreateDialog: () => void;
onOpenEditDialog: (token: Token) => void; onOpenEditDialog: (token: Token) => void;
onDeleteToken: (tokenId: string) => void; onDeleteToken: (id: number) => void;
} }
const IntegrationTokensTable: React.FC<IntegrationTokensTableProps> = ({ const IntegrationTokensTable: React.FC<IntegrationTokensTableProps> = ({
@ -36,87 +29,60 @@ const IntegrationTokensTable: React.FC<IntegrationTokensTableProps> = ({
accessorKey: "description", accessorKey: "description",
header: "Описание", header: "Описание",
size: 200, size: 200,
Cell: ({ renderedCellValue }) => renderedCellValue,
}, },
{ {
accessorKey: "token", accessorKey: "masked_token",
header: "Токен", header: "Токен",
size: 250, size: 250,
Cell: ({ renderedCellValue }) => { Cell: ({ cell }) => (
const tokenValue = renderedCellValue as string; <Box sx={{ display: 'flex', alignItems: 'center', gap: '8px'}}>
const maskedToken = tokenValue.substring(0, 5) + "***********************" + tokenValue.substring(tokenValue.length - 4); <Typography variant="body2">
return ( {cell.getValue<string>()}
<Typography sx={{ overflowWrap: 'break-word' }}>
{maskedToken}
</Typography> </Typography>
); </Box>
}, )
}, },
{ {
accessorKey: "createdAt", accessorKey: "create_dttm",
header: "Дата создания", header: "Дата создания",
size: 150, size: 150,
Cell: ({ renderedCellValue }) => renderedCellValue, Cell: ({ cell }) => new Date(cell.getValue<string>()).toLocaleString(),
}, },
{ {
accessorKey: "lastUsedAt", accessorKey: "use_dttm",
header: "Последнее использование", header: "Дата последнего использования",
size: 150, size: 200,
Cell: ({ renderedCellValue }) => renderedCellValue, Cell: ({ cell }) => cell.getValue() ? new Date(cell.getValue<string>()).toLocaleString() : "Никогда",
},
{
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({ const table = useMaterialReactTable({
columns, columns,
data: tokens, data: tokens,
enableColumnActions: false, enableRowActions: true,
enableColumnFilters: true, positionActionsColumn: "last",
enablePagination: true, renderRowActions: ({ row }) => (
enableSorting: true, <Box sx={{ display: "flex", flexWrap: "nowrap", gap: "8px" }}>
enableBottomToolbar: true, <IconButton
enableTopToolbar: true, color="primary"
enableDensityToggle: true, onClick={() => onOpenEditDialog(row.original)}
enableGlobalFilter: true, >
enableHiding: true, <EditIcon />
renderEmptyRowsFallback: () => ( </IconButton>
<Box sx={{ padding: 2, textAlign: 'center' }}> <IconButton
<Typography variant="body1"> color="error"
У вас пока нет созданных токенов. onClick={() => onDeleteToken(row.original.id)}
</Typography> >
<DeleteIcon />
</IconButton>
</Box> </Box>
), ),
muiTableBodyCellProps: { sx: { fontSize: 14 } },
muiTableHeadCellProps: { sx: { fontWeight: 700 } },
initialState: { pagination: { pageSize: 10, pageIndex: 0 } },
renderTopToolbarCustomActions: () => ( renderTopToolbarCustomActions: () => (
<Button <Button
variant="contained"
startIcon={<AddIcon />}
onClick={onOpenCreateDialog} onClick={onOpenCreateDialog}
sx={{ marginBottom: 0 }} variant="contained"
> >
Создать новый токен Создать новый токен
</Button> </Button>

8
src/types/tokens.ts Normal file
View File

@ -0,0 +1,8 @@
export interface Token {
id: number;
description: string;
masked_token: string;
rawToken?: string;
create_dttm: string;
use_dttm?: string;
}