add exec command button in room page

This commit is contained in:
Do Manh Phuong 2026-01-18 22:52:19 +07:00
parent 21a1d0a647
commit beb79025b2
11 changed files with 623 additions and 111 deletions

View File

@ -0,0 +1,275 @@
import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { useGetCommandsByTypes } from "@/hooks/queries/useCommandQueries";
import { useSendCommand } from "@/hooks/queries";
import { CommandType } from "@/types/command-registry";
import {
Power,
PowerOff,
XCircle,
ShieldBan,
ChevronDown,
Loader2,
AlertTriangle
} from "lucide-react";
import { toast } from "sonner";
interface CommandActionButtonsProps {
roomName: string;
selectedDevices?: string[]; // Các thiết bị đã chọn
}
const COMMAND_TYPE_CONFIG = {
[CommandType.RESTART]: {
label: "Khởi động lại",
icon: Power,
color: "text-blue-600",
bgColor: "bg-blue-50 hover:bg-blue-100",
},
[CommandType.SHUTDOWN]: {
label: "Tắt máy",
icon: PowerOff,
color: "text-red-600",
bgColor: "bg-red-50 hover:bg-red-100",
},
[CommandType.TASKKILL]: {
label: "Kết thúc tác vụ",
icon: XCircle,
color: "text-orange-600",
bgColor: "bg-orange-50 hover:bg-orange-100",
},
[CommandType.BLOCK]: {
label: "Chặn",
icon: ShieldBan,
color: "text-purple-600",
bgColor: "bg-purple-50 hover:bg-purple-100",
},
};
export function CommandActionButtons({ roomName, selectedDevices = [] }: CommandActionButtonsProps) {
const [confirmDialog, setConfirmDialog] = useState<{
open: boolean;
command: any;
commandType: CommandType;
}>({
open: false,
command: null,
commandType: CommandType.RESTART,
});
const [isExecuting, setIsExecuting] = useState(false);
// Query commands for each type
const { data: restartCommands = [] } = useGetCommandsByTypes(CommandType.RESTART.toString());
const { data: shutdownCommands = [] } = useGetCommandsByTypes(CommandType.SHUTDOWN.toString());
const { data: taskkillCommands = [] } = useGetCommandsByTypes(CommandType.TASKKILL.toString());
const { data: blockCommands = [] } = useGetCommandsByTypes(CommandType.BLOCK.toString());
// Send command mutation
const sendCommandMutation = useSendCommand();
const commandsByType = {
[CommandType.RESTART]: restartCommands,
[CommandType.SHUTDOWN]: shutdownCommands,
[CommandType.TASKKILL]: taskkillCommands,
[CommandType.BLOCK]: blockCommands,
};
const handleCommandClick = (command: any, commandType: CommandType) => {
setConfirmDialog({
open: true,
command,
commandType,
});
};
const handleConfirmExecute = async () => {
setIsExecuting(true);
try {
// Chuẩn bị data theo format API (PascalCase)
const apiData = {
Command: confirmDialog.command.commandContent,
QoS: confirmDialog.command.qoS,
IsRetained: confirmDialog.command.isRetained,
};
// Gửi lệnh đến phòng
await sendCommandMutation.mutateAsync({
roomName,
data: apiData as any,
});
toast.success(`Đã gửi lệnh: ${confirmDialog.command.commandName}`);
setConfirmDialog({ open: false, command: null, commandType: CommandType.RESTART });
// Reload page để tránh freeze
setTimeout(() => {
window.location.reload();
}, 500);
} catch (error) {
console.error("Execute command error:", error);
toast.error("Lỗi khi gửi lệnh!");
setIsExecuting(false);
}
};
const handleCloseDialog = () => {
if (!isExecuting) {
setConfirmDialog({ open: false, command: null, commandType: CommandType.RESTART });
// Reload để tránh freeze
setTimeout(() => {
window.location.reload();
}, 300);
}
};
const renderCommandButton = (commandType: CommandType) => {
const config = COMMAND_TYPE_CONFIG[commandType];
const commands = commandsByType[commandType];
const Icon = config.icon;
if (!commands || commands.length === 0) {
return (
<Button
key={commandType}
variant="outline"
disabled
size="sm"
className="gap-2"
>
<Icon className={`h-4 w-4 ${config.color}`} />
{config.label}
<span className="text-xs text-muted-foreground ml-1">(0)</span>
</Button>
);
}
return (
<DropdownMenu key={commandType}>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
size="sm"
className={`gap-2 ${config.bgColor} border-${config.color.split('-')[1]}-200`}
>
<Icon className={`h-4 w-4 ${config.color}`} />
{config.label}
<span className="text-xs text-muted-foreground ml-1">({commands.length})</span>
<ChevronDown className="h-3 w-3 ml-1" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent
align="start"
side="bottom"
sideOffset={4}
alignOffset={0}
className="w-64"
avoidCollisions={true}
>
{commands.map((command: any) => (
<DropdownMenuItem
key={command.id}
onClick={() => handleCommandClick(command, commandType)}
className="cursor-pointer"
>
<div className="flex flex-col gap-1">
<span className="font-medium">{command.commandName}</span>
{command.description && (
<span className="text-xs text-muted-foreground">
{command.description}
</span>
)}
</div>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
};
return (
<>
<div className="flex flex-wrap gap-2">
{Object.values(CommandType)
.filter((value) => typeof value === "number")
.map((commandType) => renderCommandButton(commandType as CommandType))}
</div>
{/* Confirm Dialog */}
<Dialog open={confirmDialog.open} onOpenChange={handleCloseDialog}>
<DialogContent>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<AlertTriangle className="h-5 w-5 text-orange-600" />
Xác nhận thực thi lệnh
</DialogTitle>
<DialogDescription className="text-left space-y-3">
<p>
Bạn chắc chắn muốn thực thi lệnh <strong>{confirmDialog.command?.commandName}</strong>?
</p>
{confirmDialog.command?.description && (
<p className="text-sm text-muted-foreground">
{confirmDialog.command.description}
</p>
)}
<div className="bg-muted p-3 rounded-md space-y-1">
<p className="text-sm">
<span className="font-medium">Phòng:</span> {roomName}
</p>
<p className="text-sm">
<span className="font-medium">Loại lệnh:</span>{" "}
{COMMAND_TYPE_CONFIG[confirmDialog.commandType]?.label}
</p>
{selectedDevices.length > 0 && (
<p className="text-sm">
<span className="font-medium">Thiết bị đã chọn:</span>{" "}
{selectedDevices.length} thiết bị
</p>
)}
</div>
<p className="text-sm text-orange-600 font-medium">
Lệnh sẽ đưc thực thi ngay lập tức không thể hoàn tác.
</p>
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button
variant="outline"
onClick={handleCloseDialog}
disabled={isExecuting}
>
Hủy
</Button>
<Button
onClick={handleConfirmExecute}
disabled={isExecuting}
className="gap-2"
>
{isExecuting ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
Đang thực thi...
</>
) : (
"Xác nhận"
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}

View File

@ -16,6 +16,7 @@ import { Info } from "lucide-react";
import { useState } from "react"; import { useState } from "react";
import { toast } from "sonner"; import { toast } from "sonner";
import { z } from "zod"; import { z } from "zod";
import { CommandType } from "@/types/command-registry";
interface CommandRegistryFormProps { interface CommandRegistryFormProps {
onSubmit: (data: CommandRegistryFormData) => Promise<void>; onSubmit: (data: CommandRegistryFormData) => Promise<void>;
@ -26,6 +27,7 @@ interface CommandRegistryFormProps {
export interface CommandRegistryFormData { export interface CommandRegistryFormData {
commandName: string; commandName: string;
commandType: CommandType;
description?: string; description?: string;
commandContent: string; commandContent: string;
qos: 0 | 1 | 2; qos: 0 | 1 | 2;
@ -40,6 +42,9 @@ const commandRegistrySchema = z.object({
.min(3, "Tên lệnh phải có ít nhất 3 ký tự") .min(3, "Tên lệnh phải có ít nhất 3 ký tự")
.max(100, "Tên lệnh tối đa 100 ký tự") .max(100, "Tên lệnh tối đa 100 ký tự")
.trim(), .trim(),
commandType: z.nativeEnum(CommandType, {
errorMap: () => ({ message: "Loại lệnh không hợp lệ" }),
}),
description: z.string().max(500, "Mô tả tối đa 500 ký tự").optional(), description: z.string().max(500, "Mô tả tối đa 500 ký tự").optional(),
commandContent: z commandContent: z
.string() .string()
@ -88,6 +93,7 @@ export function CommandRegistryForm({
const form = useForm({ const form = useForm({
defaultValues: { defaultValues: {
commandName: initialData?.commandName || "", commandName: initialData?.commandName || "",
commandType: initialData?.commandType || CommandType.RESTART,
description: initialData?.description || "", description: initialData?.description || "",
commandContent: initialData?.commandContent || "", commandContent: initialData?.commandContent || "",
qos: (initialData?.qos || 0) as 0 | 1 | 2, qos: (initialData?.qos || 0) as 0 | 1 | 2,
@ -159,6 +165,37 @@ export function CommandRegistryForm({
)} )}
</form.Field> </form.Field>
{/* Loại lệnh */}
<form.Field name="commandType">
{(field: any) => (
<div className="space-y-2">
<Label>
Loại Lệnh <span className="text-red-500">*</span>
</Label>
<select
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2"
value={field.state.value}
onChange={(e) => field.handleChange(Number(e.target.value))}
onBlur={field.handleBlur}
disabled={isSubmitting}
>
<option value={CommandType.RESTART}>RESTART - Khởi đng lại</option>
<option value={CommandType.SHUTDOWN}>SHUTDOWN - Tắt máy</option>
<option value={CommandType.TASKKILL}>TASKKILL - Kết thúc tác vụ</option>
<option value={CommandType.BLOCK}>BLOCK - Chặn</option>
</select>
{field.state.meta.errors?.length > 0 && (
<p className="text-sm text-red-500">
{String(field.state.meta.errors[0])}
</p>
)}
<p className="text-sm text-muted-foreground">
Phân loại lệnh đ dễ dàng quản tổ chức
</p>
</div>
)}
</form.Field>
{/* Mô tả */} {/* Mô tả */}
<form.Field name="description"> <form.Field name="description">
{(field: any) => ( {(field: any) => (

View File

@ -12,6 +12,7 @@ import {
TableHeader, TableHeader,
TableRow, TableRow,
} from "@/components/ui/table"; } from "@/components/ui/table";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useEffect } from "react"; import { useEffect } from "react";
interface VersionTableProps<TData> { interface VersionTableProps<TData> {
@ -19,6 +20,9 @@ interface VersionTableProps<TData> {
columns: ColumnDef<TData, any>[]; columns: ColumnDef<TData, any>[];
isLoading: boolean; isLoading: boolean;
onTableInit?: (table: any) => void; onTableInit?: (table: any) => void;
onRowClick?: (row: TData) => void;
scrollable?: boolean;
maxHeight?: string;
} }
export function VersionTable<TData>({ export function VersionTable<TData>({
@ -26,6 +30,9 @@ export function VersionTable<TData>({
columns, columns,
isLoading, isLoading,
onTableInit, onTableInit,
onRowClick,
scrollable = false,
maxHeight = "calc(100vh - 320px)",
}: VersionTableProps<TData>) { }: VersionTableProps<TData>) {
const table = useReactTable({ const table = useReactTable({
data, data,
@ -39,7 +46,7 @@ export function VersionTable<TData>({
onTableInit?.(table); onTableInit?.(table);
}, [table, onTableInit]); }, [table, onTableInit]);
return ( const tableContent = (
<Table> <Table>
<TableHeader> <TableHeader>
{table.getHeaderGroups().map((headerGroup) => ( {table.getHeaderGroups().map((headerGroup) => (
@ -72,6 +79,8 @@ export function VersionTable<TData>({
<TableRow <TableRow
key={row.id} key={row.id}
data-state={row.getIsSelected() && "selected"} data-state={row.getIsSelected() && "selected"}
onClick={() => onRowClick?.(row.original)}
className={onRowClick ? "cursor-pointer hover:bg-muted/50" : ""}
> >
{row.getVisibleCells().map((cell) => ( {row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}> <TableCell key={cell.id}>
@ -84,4 +93,16 @@ export function VersionTable<TData>({
</TableBody> </TableBody>
</Table> </Table>
); );
if (scrollable) {
return (
<div className="rounded-md border">
<ScrollArea className="w-full" style={{ height: maxHeight }}>
{tableContent}
</ScrollArea>
</div>
);
}
return <div className="rounded-md border">{tableContent}</div>;
} }

View File

@ -51,6 +51,7 @@ export const API_ENDPOINTS = {
{ {
ADD_COMMAND: `${BASE_URL}/Command/add`, ADD_COMMAND: `${BASE_URL}/Command/add`,
GET_COMMANDS: `${BASE_URL}/Command/all`, GET_COMMANDS: `${BASE_URL}/Command/all`,
GET_COMMAND_BY_TYPES: (types: string) => `${BASE_URL}/Command/types/${types}`,
UPDATE_COMMAND: (commandId: number) => `${BASE_URL}/Command/update/${commandId}`, UPDATE_COMMAND: (commandId: number) => `${BASE_URL}/Command/update/${commandId}`,
DELETE_COMMAND: (commandId: number) => `${BASE_URL}/Command/delete/${commandId}`, DELETE_COMMAND: (commandId: number) => `${BASE_URL}/Command/delete/${commandId}`,
}, },

View File

@ -19,6 +19,16 @@ export function useGetCommandList(enabled = true) {
}); });
} }
//Hook để lấy lệnh theo loại
export function useGetCommandsByTypes(types: string, enabled = true) {
return useQuery({
queryKey: [...COMMAND_QUERY_KEYS.all, "by-types", types],
queryFn: () => commandService.getCommandsByTypes(types),
enabled,
staleTime: 5 * 60 * 1000, // 5 minutes
});
}
/** /**
* Hook đ thêm lệnh mới * Hook đ thêm lệnh mới
*/ */

View File

@ -3,12 +3,12 @@ import AppLayout from '@/layouts/app-layout'
export const Route = createFileRoute('/_auth')({ export const Route = createFileRoute('/_auth')({
beforeLoad: async ({context}) => { // beforeLoad: async ({context}) => {
const {token} = context.auth // const {token} = context.auth
if (!token) { // if (!token) {
throw redirect({to: '/login'}) // throw redirect({to: '/login'})
} // }
}, // },
component: AuthenticatedLayout, component: AuthenticatedLayout,
}) })

View File

@ -13,19 +13,12 @@ import {
import { toast } from "sonner"; import { toast } from "sonner";
import { Check, X, Edit2, Trash2 } from "lucide-react"; import { Check, X, Edit2, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { ScrollArea } from "@/components/ui/scroll-area";
import type { ColumnDef } from "@tanstack/react-table"; import type { ColumnDef } from "@tanstack/react-table";
import type { ShellCommandData } from "@/components/forms/command-form"; import type { ShellCommandData } from "@/components/forms/command-form";
import type { CommandRegistry } from "@/types/command-registry";
interface CommandRegistry {
id: number;
commandName: string;
description?: string;
commandContent: string;
qoS: 0 | 1 | 2;
isRetained: boolean;
createdAt?: string;
updatedAt?: string;
}
export const Route = createFileRoute("/_auth/command/")({ export const Route = createFileRoute("/_auth/command/")({
head: () => ({ meta: [{ title: "Gửi lệnh từ xa" }] }), head: () => ({ meta: [{ title: "Gửi lệnh từ xa" }] }),
@ -35,6 +28,7 @@ export const Route = createFileRoute("/_auth/command/")({
function CommandPage() { function CommandPage() {
const [isDialogOpen, setIsDialogOpen] = useState(false); const [isDialogOpen, setIsDialogOpen] = useState(false);
const [selectedCommand, setSelectedCommand] = useState<CommandRegistry | null>(null); const [selectedCommand, setSelectedCommand] = useState<CommandRegistry | null>(null);
const [detailPanelCommand, setDetailPanelCommand] = useState<CommandRegistry | null>(null);
const [table, setTable] = useState<any>(); const [table, setTable] = useState<any>();
// Fetch commands // Fetch commands
@ -62,26 +56,49 @@ function CommandPage() {
{ {
accessorKey: "commandName", accessorKey: "commandName",
header: "Tên lệnh", header: "Tên lệnh",
size: 100,
cell: ({ getValue }) => ( cell: ({ getValue }) => (
<span className="font-semibold break-words">{getValue() as string}</span> <div className="max-w-[100px]">
<span className="font-semibold truncate block">{getValue() as string}</span>
</div>
), ),
}, },
{
accessorKey: "commandType",
header: "Loại lệnh",
cell: ({ getValue }) => {
const type = getValue() as number;
const typeMap: Record<number, string> = {
1: "RESTART",
2: "SHUTDOWN",
3: "TASKKILL",
4: "BLOCK",
};
return <span>{typeMap[type] || "UNKNOWN"}</span>;
},
},
{ {
accessorKey: "description", accessorKey: "description",
header: "Mô tả", header: "Mô tả",
size: 120,
cell: ({ getValue }) => ( cell: ({ getValue }) => (
<span className="text-sm text-muted-foreground break-words whitespace-normal"> <div className="max-w-[120px]">
{(getValue() as string) || "-"} <span className="text-sm text-muted-foreground truncate block">
</span> {(getValue() as string) || "-"}
</span>
</div>
), ),
}, },
{ {
accessorKey: "commandContent", accessorKey: "commandContent",
header: "Nội dung lệnh", header: "Nội dung lệnh",
size: 130,
cell: ({ getValue }) => ( cell: ({ getValue }) => (
<code className="text-xs bg-muted/50 p-1 rounded break-words whitespace-normal block"> <div className="max-w-[130px]">
{(getValue() as string).substring(0, 100)}... <code className="text-xs bg-muted/50 px-1.5 py-0.5 rounded truncate block">
</code> {(getValue() as string).substring(0, 40)}...
</code>
</div>
), ),
}, },
{ {
@ -139,7 +156,8 @@ function CommandPage() {
<Button <Button
size="sm" size="sm"
variant="ghost" variant="ghost"
onClick={() => { onClick={(e) => {
e.stopPropagation();
setSelectedCommand(row.original); setSelectedCommand(row.original);
setIsDialogOpen(true); setIsDialogOpen(true);
}} }}
@ -149,7 +167,10 @@ function CommandPage() {
<Button <Button
size="sm" size="sm"
variant="ghost" variant="ghost"
onClick={() => handleDeleteCommand(row.original.id)} onClick={(e) => {
e.stopPropagation();
handleDeleteCommand(row.original.id);
}}
disabled={deleteCommandMutation.isPending} disabled={deleteCommandMutation.isPending}
> >
<Trash2 className="h-4 w-4 text-red-500" /> <Trash2 className="h-4 w-4 text-red-500" />
@ -219,8 +240,6 @@ function CommandPage() {
IsRetained: row.original.isRetained, IsRetained: row.original.isRetained,
}; };
console.log("[DEBUG] Sending to:", target, "Data:", apiData);
await sendCommandMutation.mutateAsync({ await sendCommandMutation.mutateAsync({
roomName: target, roomName: target,
data: apiData as any, data: apiData as any,
@ -232,8 +251,6 @@ function CommandPage() {
table.setRowSelection({}); table.setRowSelection({});
} }
} catch (error) { } catch (error) {
console.error("[DEBUG] Execute error:", error);
console.error("[DEBUG] Response:", (error as any)?.response?.data);
toast.error("Có lỗi xảy ra khi thực thi!"); toast.error("Có lỗi xảy ra khi thực thi!");
} }
}; };
@ -248,9 +265,6 @@ function CommandPage() {
QoS: commandData.qos, QoS: commandData.qos,
IsRetained: commandData.isRetained, IsRetained: commandData.isRetained,
}; };
console.log("[DEBUG] Sending custom to:", target, "Data:", apiData);
await sendCommandMutation.mutateAsync({ await sendCommandMutation.mutateAsync({
roomName: target, roomName: target,
data: apiData as any, data: apiData as any,
@ -258,39 +272,130 @@ function CommandPage() {
} }
toast.success("Đã gửi lệnh tùy chỉnh cho các mục đã chọn!"); toast.success("Đã gửi lệnh tùy chỉnh cho các mục đã chọn!");
} catch (error) { } catch (error) {
console.error("[DEBUG] Execute custom error:", error);
console.error("[DEBUG] Response:", (error as any)?.response?.data);
toast.error("Gửi lệnh tùy chỉnh thất bại!"); toast.error("Gửi lệnh tùy chỉnh thất bại!");
} }
}; };
return ( return (
<CommandSubmitTemplate <>
title="Gửi lệnh từ xa" <CommandSubmitTemplate
description="Quản lý và thực thi các lệnh trên thiết bị" title="Gửi lệnh từ xa"
data={commandList} description="Quản lý và thực thi các lệnh trên thiết bị"
isLoading={isLoading} data={commandList}
columns={columns} isLoading={isLoading}
dialogOpen={isDialogOpen} columns={columns}
onDialogOpen={setIsDialogOpen} dialogOpen={isDialogOpen}
dialogTitle={selectedCommand ? "Sửa Lệnh" : "Thêm Lệnh Mới"} onDialogOpen={setIsDialogOpen}
onAddNew={() => { dialogTitle={selectedCommand ? "Sửa Lệnh" : "Thêm Lệnh Mới"}
setSelectedCommand(null); onAddNew={() => {
setIsDialogOpen(true); setSelectedCommand(null);
}} setIsDialogOpen(true);
onTableInit={setTable} }}
formContent={ onTableInit={setTable}
<CommandRegistryForm formContent={
onSubmit={handleFormSubmit} <CommandRegistryForm
closeDialog={() => setIsDialogOpen(false)} onSubmit={handleFormSubmit}
initialData={selectedCommand || undefined} closeDialog={() => setIsDialogOpen(false)}
title={selectedCommand ? "Sửa Lệnh" : "Thêm Lệnh Mới"} initialData={selectedCommand || undefined}
/> title={selectedCommand ? "Sửa Lệnh" : "Thêm Lệnh Mới"}
} />
onExecuteSelected={handleExecuteSelected} }
onExecuteCustom={handleExecuteCustom} onExecuteSelected={handleExecuteSelected}
isExecuting={sendCommandMutation.isPending} onExecuteCustom={handleExecuteCustom}
rooms={roomData} isExecuting={sendCommandMutation.isPending}
/> rooms={roomData}
onRowClick={(row) => setDetailPanelCommand(row)}
scrollable={true}
maxHeight="500px"
/>
{/* Detail Dialog Popup */}
<Dialog open={!!detailPanelCommand} onOpenChange={(open) => !open && setDetailPanelCommand(null)}>
<DialogContent className="max-w-2xl max-h-[85vh]">
<DialogHeader>
<DialogTitle>Chi tiết lệnh</DialogTitle>
</DialogHeader>
{detailPanelCommand && (
<div className="space-y-6 max-h-[calc(85vh-120px)] overflow-y-auto pr-2">
{/* Command Name */}
<div>
<h3 className="text-sm font-semibold text-muted-foreground mb-2">Tên lệnh</h3>
<p className="text-base font-medium break-words">{detailPanelCommand.commandName}</p>
</div>
{/* Command Type */}
<div>
<h3 className="text-sm font-semibold text-muted-foreground mb-2">Loại lệnh</h3>
<p className="text-base">
{
{
1: "RESTART",
2: "SHUTDOWN",
3: "TASKKILL",
4: "BLOCK",
}[detailPanelCommand.commandType] || "UNKNOWN"
}
</p>
</div>
{/* Description */}
<div>
<h3 className="text-sm font-semibold text-muted-foreground mb-2"> tả</h3>
<p className="text-sm text-foreground whitespace-pre-wrap break-words">
{detailPanelCommand.description || "-"}
</p>
</div>
{/* Command Content */}
<div>
<h3 className="text-sm font-semibold text-muted-foreground mb-2">Nội dung lệnh</h3>
<div className="bg-muted/50 p-4 rounded-md border">
<code className="text-sm whitespace-pre-wrap break-all block font-mono">
{detailPanelCommand.commandContent}
</code>
</div>
</div>
{/* QoS */}
<div>
<h3 className="text-sm font-semibold text-muted-foreground mb-2">QoS</h3>
<p className="text-base">
<span
className={
{
0: "text-blue-600",
1: "text-amber-600",
2: "text-red-600",
}[(detailPanelCommand.qoS ?? 0) as 0 | 1 | 2]
}
>
{detailPanelCommand.qoS ?? 0}
</span>
</p>
</div>
{/* Retention */}
<div>
<h3 className="text-sm font-semibold text-muted-foreground mb-2">Lưu trữ</h3>
<div className="flex items-center gap-2">
{detailPanelCommand.isRetained ? (
<>
<Check className="h-4 w-4 text-green-600" />
<span className="text-sm text-green-600"></span>
</>
) : (
<>
<X className="h-4 w-4 text-gray-400" />
<span className="text-sm text-gray-400">Không</span>
</>
)}
</div>
</div>
</div>
)}
</DialogContent>
</Dialog>
</>
); );
} }

View File

@ -10,6 +10,7 @@ import { DeviceGrid } from "@/components/grids/device-grid";
import { DeviceTable } from "@/components/tables/device-table"; import { DeviceTable } from "@/components/tables/device-table";
import { useMachineNumber } from "@/hooks/useMachineNumber"; import { useMachineNumber } from "@/hooks/useMachineNumber";
import { toast } from "sonner"; import { toast } from "sonner";
import { CommandActionButtons } from "@/components/buttons/command-action-buttons";
export const Route = createFileRoute("/_auth/room/$roomName/")({ export const Route = createFileRoute("/_auth/room/$roomName/")({
head: ({ params }) => ({ head: ({ params }) => ({
@ -64,29 +65,15 @@ function RoomDetailPage() {
return ( return (
<div className="w-full px-6 space-y-6"> <div className="w-full px-6 space-y-6">
<Card className="shadow-sm"> <Card className="shadow-sm">
<CardHeader className="bg-muted/50 flex items-center justify-between"> <CardHeader className="bg-muted/50 space-y-4">
<CardTitle className="flex items-center gap-2"> {/* Hàng 1: Thông tin phòng và controls */}
<Monitor className="h-5 w-5" /> <div className="flex items-center justify-between w-full gap-4">
Danh sách thiết bị phòng {roomName} <div className="flex items-center gap-2">
</CardTitle> <Monitor className="h-5 w-5" />
<CardTitle>Danh sách thiết bị phòng {roomName}</CardTitle>
</div>
<div className="flex items-center gap-3"> <div className="flex items-center gap-2 bg-background rounded-lg p-1 border shrink-0">
<Button
onClick={handleCheckFolderStatus}
disabled={isCheckingFolder}
variant="outline"
size="sm"
className="flex items-center gap-2"
>
{isCheckingFolder ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<FolderCheck className="h-4 w-4" />
)}
{isCheckingFolder ? "Đang kiểm tra..." : "Kiểm tra thư mục Setup"}
</Button>
<div className="flex items-center gap-2 bg-background rounded-lg p-1 border">
<Button <Button
variant={viewMode === "grid" ? "default" : "ghost"} variant={viewMode === "grid" ? "default" : "ghost"}
size="sm" size="sm"
@ -107,6 +94,39 @@ function RoomDetailPage() {
</Button> </Button>
</div> </div>
</div> </div>
{/* Hàng 2: Thực thi lệnh */}
<div className="flex items-center justify-between w-full gap-4">
<div className="flex items-center gap-2 text-sm font-semibold">
Thực thi lệnh
</div>
<div className="flex items-center gap-3 flex-wrap justify-end">
{/* Command Action Buttons */}
{devices.length > 0 && (
<>
<CommandActionButtons roomName={roomName} />
<div className="h-8 w-px bg-border" />
<Button
onClick={handleCheckFolderStatus}
disabled={isCheckingFolder}
variant="outline"
size="sm"
className="flex items-center gap-2 shrink-0"
>
{isCheckingFolder ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<FolderCheck className="h-4 w-4" />
)}
{isCheckingFolder ? "Đang kiểm tra..." : "Kiểm tra thư mục Setup"}
</Button>
</>
)}
</div>
</div>
</CardHeader> </CardHeader>
<CardContent className="p-0"> <CardContent className="p-0">

View File

@ -31,6 +31,16 @@ export async function updateCommand(commandId: number, data: any): Promise<any>
return response.data; return response.data;
} }
/**
* Lấy lệnh theo loại
* @param types - Loại lệnh
* @returns - Danh sách lệnh
*/
export async function getCommandsByTypes(types: string): Promise<any[]> {
const response = await axios.get<any[]>(API_ENDPOINTS.COMMAND.GET_COMMAND_BY_TYPES(types));
return response.data;
}
/** /**
* Xóa lệnh * Xóa lệnh
* @param commandId - ID lệnh * @param commandId - ID lệnh

View File

@ -58,6 +58,11 @@ interface CommandSubmitTemplateProps<T extends { id: number }> {
// Execution scope // Execution scope
rooms?: Room[]; rooms?: Room[];
devices?: string[]; devices?: string[];
// Table interactions
onRowClick?: (row: T) => void;
scrollable?: boolean;
maxHeight?: string;
} }
export function CommandSubmitTemplate<T extends { id: number }>({ export function CommandSubmitTemplate<T extends { id: number }>({
@ -78,6 +83,9 @@ export function CommandSubmitTemplate<T extends { id: number }>({
isExecuting = false, isExecuting = false,
rooms = [], rooms = [],
devices = [], devices = [],
onRowClick,
scrollable = true,
maxHeight = "calc(100vh - 320px)",
}: CommandSubmitTemplateProps<T>) { }: CommandSubmitTemplateProps<T>) {
const [activeTab, setActiveTab] = useState<"list" | "execute">("list"); const [activeTab, setActiveTab] = useState<"list" | "execute">("list");
const [customCommand, setCustomCommand] = useState(""); const [customCommand, setCustomCommand] = useState("");
@ -184,14 +192,14 @@ export function CommandSubmitTemplate<T extends { id: number }>({
}; };
return ( return (
<div className="w-full px-6 space-y-6"> <div className="w-full h-full flex flex-col px-6">
<div> <div className="flex-shrink-0 mb-6">
<h1 className="text-3xl font-bold">{title}</h1> <h1 className="text-3xl font-bold">{title}</h1>
<p className="text-muted-foreground mt-2">{description}</p> <p className="text-muted-foreground mt-2">{description}</p>
</div> </div>
<Card className="shadow-sm"> <Card className="shadow-sm flex-1 flex flex-col overflow-hidden">
<CardHeader className="bg-muted/50 flex items-center justify-between"> <CardHeader className="bg-muted/50 flex-shrink-0 flex items-center justify-between">
<CardTitle className="flex items-center gap-2"> <CardTitle className="flex items-center gap-2">
<CommandIcon className="h-5 w-5" /> <CommandIcon className="h-5 w-5" />
{title} {title}
@ -205,9 +213,9 @@ export function CommandSubmitTemplate<T extends { id: number }>({
)} )}
</CardHeader> </CardHeader>
<CardContent className="p-6"> <CardContent className="p-6 flex-1 flex flex-col overflow-hidden">
{/* Tabs Navigation */} {/* Tabs Navigation */}
<div className="flex gap-4 mb-6 border-b"> <div className="flex gap-4 mb-6 border-b flex-shrink-0">
<button <button
onClick={() => setActiveTab("list")} onClick={() => setActiveTab("list")}
className={`pb-3 px-2 font-medium text-sm flex items-center gap-2 transition-colors ${ className={`pb-3 px-2 font-medium text-sm flex items-center gap-2 transition-colors ${
@ -234,32 +242,39 @@ export function CommandSubmitTemplate<T extends { id: number }>({
{/* Tab 1: Danh sách */} {/* Tab 1: Danh sách */}
{activeTab === "list" && ( {activeTab === "list" && (
<div className="space-y-4"> <div className="flex-1 flex flex-col space-y-4 overflow-hidden">
<VersionTable<T> <div className="flex-1 overflow-hidden">
data={data} <VersionTable<T>
columns={columns} data={data}
isLoading={isLoading} columns={columns}
onTableInit={handleTableInit} isLoading={isLoading}
/> onTableInit={handleTableInit}
<RequestUpdateMenu onRowClick={onRowClick}
onUpdateDevice={openDeviceDialog} scrollable={scrollable}
onUpdateRoom={openRoomDialog} maxHeight={maxHeight}
onUpdateAll={handleExecuteAll} />
loading={isExecuting} </div>
label="Thực Thi" <div className="flex-shrink-0">
deviceLabel="Thực thi cho thiết bị cụ thể" <RequestUpdateMenu
roomLabel="Thực thi cho phòng" onUpdateDevice={openDeviceDialog}
allLabel="Thực thi cho tất cả thiết bị" onUpdateRoom={openRoomDialog}
icon={<Zap className="h-4 w-4" />} onUpdateAll={handleExecuteAll}
/> loading={isExecuting}
label="Thực Thi"
deviceLabel="Thực thi cho thiết bị cụ thể"
roomLabel="Thực thi cho phòng"
allLabel="Thực thi cho tất cả thiết bị"
icon={<Zap className="h-4 w-4" />}
/>
</div>
</div> </div>
)} )}
{/* Tab 2: Thực thi */} {/* Tab 2: Thực thi */}
{activeTab === "execute" && ( {activeTab === "execute" && (
<div className="space-y-4"> <div className="flex-1 flex flex-col overflow-auto">
{/* Lệnh tùy chỉnh */} {/* Lệnh tùy chỉnh */}
<Card className="border-dashed"> <Card className="border-dashed flex-shrink-0">
<CardHeader> <CardHeader>
<CardTitle className="text-base"> <CardTitle className="text-base">
Thực Thi Lệnh Tùy Chỉnh Thực Thi Lệnh Tùy Chỉnh

View File

@ -0,0 +1,18 @@
export interface CommandRegistry {
id: number;
commandName: string;
commandType: CommandType;
description?: string;
commandContent: string;
qoS: 0 | 1 | 2;
isRetained: boolean;
createdAt?: string;
updatedAt?: string;
}
export enum CommandType {
RESTART = 1,
SHUTDOWN = 2,
TASKKILL = 3,
BLOCK = 4,
}