Обновлен компонент 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";
import React, { useState, useMemo } from "react";
import React, { useState, useMemo, useEffect } from "react";
import {
Box,
Button,
@ -14,29 +14,57 @@ import {
import CreateTokenDialog from "./CreateTokenDialog";
import IntegrationTokensTable from "./IntegrationTokensTable";
import styles from "../styles/account.module.css";
import Cookies from "js-cookie";
import { Token } from "../types/tokens";
// Компонент для управления интеграциями и токенами
interface Token {
id: string;
description: string;
token: string;
createdAt: string;
lastUsedAt?: string;
}
// interface Token {
// description: string;
// masked_token: string;
// rawToken?: string;
// create_dttm: string;
// use_dttm?: 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 [createdRawToken, setCreatedRawToken] = useState<string | null>(null);
const [openEditDialog, setOpenEditDialog] = useState(false);
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 = () => {
setOpenCreateDialog(true);
setTokenDescription("");
setShowTokenWarning(false);
setCreatedRawToken(null);
};
const handleCloseCreateDialog = () => {
@ -53,33 +81,96 @@ const AccountIntegration = () => {
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 handleTokenGenerate = async (description: string) => {
try {
const authToken = Cookies.get("access_token");
if (!authToken) {
console.error("Access token not found");
return;
}
const handleTokenUpdate = (updatedDescription: string) => {
if (editingToken) {
setTokens(prevTokens =>
prevTokens.map(token =>
token.id === editingToken.id ? { ...token, description: updatedDescription } : token
)
);
setOpenEditDialog(false);
setEditingToken(null);
const res = await fetch("/api/account/integration-tokens", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${authToken}`
},
body: JSON.stringify({ description: description })
});
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) => {
setTokens(prevTokens => prevTokens.filter(token => token.id !== tokenId));
const handleTokenUpdate = async (id: number, updatedDescription: string) => {
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 (
@ -99,6 +190,7 @@ const AccountIntegration = () => {
open={openCreateDialog}
onClose={handleCloseCreateDialog}
onTokenGenerate={handleTokenGenerate}
generatedToken={createdRawToken}
/>
<CreateTokenDialog
@ -106,14 +198,9 @@ const AccountIntegration = () => {
onClose={handleCloseEditDialog}
isEditMode={true}
initialDescription={editingToken?.description || ""}
editingTokenId={editingToken?.id || 0}
onTokenUpdate={handleTokenUpdate}
/>
{showTokenCreatedSuccess && (
<div className={styles.copySuccessToast}>
Токен успешно создан!
</div>
)}
</Box>
);
};

View File

@ -8,147 +8,110 @@ import {
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";
import { Token } from "../types/tokens";
interface CreateTokenDialogProps {
open: boolean;
onClose: () => void;
onTokenGenerate?: (description: string, token: string) => void;
onTokenGenerate?: (description: string) => Promise<void>;
isEditMode?: boolean;
initialDescription?: string;
onTokenUpdate?: (updatedDescription: string) => void;
editingTokenId?: number;
onTokenUpdate?: (id: number, description: string) => void;
generatedToken?: string | null;
}
const CreateTokenDialog: React.FC<CreateTokenDialogProps> = ({
open,
onClose,
onTokenGenerate,
isEditMode,
initialDescription,
isEditMode = false,
initialDescription = "",
onTokenUpdate,
generatedToken,
editingTokenId,
}) => {
const [tokenDescription, setTokenDescription] = useState("");
const [generatedToken, setGeneratedToken] = useState("");
const [showTokenWarning, setShowTokenWarning] = useState(false);
const [showCopySuccess, setShowCopySuccess] = useState(false);
const [description, setDescription] = useState(initialDescription);
const [showWarning, setShowWarning] = useState(false);
useEffect(() => {
if (!open) {
setTokenDescription("");
setGeneratedToken("");
setShowTokenWarning(false);
setShowCopySuccess(false);
} else if (isEditMode && initialDescription) {
setTokenDescription(initialDescription);
} else {
setTokenDescription("");
setGeneratedToken("");
setShowTokenWarning(false);
setShowCopySuccess(false);
if (open) {
setDescription(initialDescription);
setShowWarning(false);
}
}, [open, isEditMode, initialDescription]);
}, [open, 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 handleGenerateClick = async () => {
if (description.trim() === "") {
setShowWarning(true);
return;
}
await onTokenGenerate?.(description);
};
const handleUpdateDescription = () => {
if (tokenDescription.trim() === "") return;
if (onTokenUpdate) {
onTokenUpdate(tokenDescription);
const handleUpdateClick = () => {
if (description.trim() === "") {
setShowWarning(true);
return;
}
onClose();
};
const handleCopy = () => {
if (!generatedToken) return;
if (typeof navigator !== "undefined" && navigator.clipboard) {
navigator.clipboard.writeText(generatedToken);
console.log("Attempting to update token. editingTokenId:", editingTokenId, "Description:", description);
if (onTokenUpdate && typeof editingTokenId === 'number') {
onTokenUpdate(editingTokenId, description);
onClose();
} else {
const textarea = document.createElement("textarea");
textarea.value = generatedToken;
document.body.appendChild(textarea);
textarea.select();
document.execCommand("copy");
document.body.removeChild(textarea);
console.error("Cannot update token: onTokenUpdate is missing or editingTokenId is invalid.", {onTokenUpdateExists: !!onTokenUpdate, editingTokenIdValue: editingTokenId});
}
setShowCopySuccess(true);
setTimeout(() => setShowCopySuccess(false), 1500);
};
return (
<Dialog open={open} onClose={onClose}>
<DialogTitle>{isEditMode ? "Редактировать описание токена" : "Создать новый токен"}</DialogTitle>
<Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
<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' }}>
{showWarning && (
<Typography color="error" variant="body2" sx={{ mb: 2 }}>
Пожалуйста, введите описание токена.
</Typography>
)}
<TextField
autoFocus
margin="dense"
label="Описание токена"
type="text"
fullWidth
variant="outlined"
value={description}
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'}}>
<Typography variant="subtitle2">Созданный токен:</Typography>
<Box sx={{ display: 'flex', alignItems: 'center', gap: '8px'}}>
<Typography variant="body2" 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>
)}
<Typography variant="caption" color="textSecondary">
Скопируйте этот токен. Он будет виден только сейчас.
</Typography>
</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>
{!generatedToken && <Button onClick={onClose}>Отмена</Button>}
{isEditMode ? (
<Button onClick={handleUpdateClick} variant="contained">
Сохранить
</Button>
) : (
<Button onClick={generatedToken ? onClose : handleGenerateClick} variant="contained">
{generatedToken ? "ОК" : "Создать"}
</Button>
)}
</DialogActions>
</Dialog>
);

View File

@ -8,20 +8,13 @@ import {
} 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;
}
import { Token } from "../types/tokens";
interface IntegrationTokensTableProps {
tokens: Token[];
onOpenCreateDialog: () => void;
onOpenEditDialog: (token: Token) => void;
onDeleteToken: (tokenId: string) => void;
onDeleteToken: (id: number) => void;
}
const IntegrationTokensTable: React.FC<IntegrationTokensTableProps> = ({
@ -36,87 +29,60 @@ const IntegrationTokensTable: React.FC<IntegrationTokensTableProps> = ({
accessorKey: "description",
header: "Описание",
size: 200,
Cell: ({ renderedCellValue }) => renderedCellValue,
},
{
accessorKey: "token",
accessorKey: "masked_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}
Cell: ({ cell }) => (
<Box sx={{ display: 'flex', alignItems: 'center', gap: '8px'}}>
<Typography variant="body2">
{cell.getValue<string>()}
</Typography>
);
},
</Box>
)
},
{
accessorKey: "createdAt",
accessorKey: "create_dttm",
header: "Дата создания",
size: 150,
Cell: ({ renderedCellValue }) => renderedCellValue,
Cell: ({ cell }) => new Date(cell.getValue<string>()).toLocaleString(),
},
{
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>
),
accessorKey: "use_dttm",
header: "Дата последнего использования",
size: 200,
Cell: ({ cell }) => cell.getValue() ? new Date(cell.getValue<string>()).toLocaleString() : "Никогда",
},
],
[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>
enableRowActions: true,
positionActionsColumn: "last",
renderRowActions: ({ row }) => (
<Box sx={{ display: "flex", flexWrap: "nowrap", gap: "8px" }}>
<IconButton
color="primary"
onClick={() => onOpenEditDialog(row.original)}
>
<EditIcon />
</IconButton>
<IconButton
color="error"
onClick={() => onDeleteToken(row.original.id)}
>
<DeleteIcon />
</IconButton>
</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 }}
variant="contained"
>
Создать новый токен
</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;
}