586 lines
23 KiB
TypeScript
586 lines
23 KiB
TypeScript
"use client";
|
|
|
|
/**
|
|
* 플로우 관리 메인 페이지
|
|
* - 플로우 정의 목록
|
|
* - 플로우 생성/수정/삭제
|
|
* - 플로우 편집기로 이동
|
|
*/
|
|
|
|
import { useState, useEffect } from "react";
|
|
import { useRouter } from "next/navigation";
|
|
import { Plus, Edit2, Trash2, Play, Workflow, Table, Calendar, User, Check, ChevronsUpDown } from "lucide-react";
|
|
import { Button } from "@/components/ui/button";
|
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
|
import { Badge } from "@/components/ui/badge";
|
|
import {
|
|
Dialog,
|
|
DialogContent,
|
|
DialogDescription,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
} from "@/components/ui/dialog";
|
|
import { Input } from "@/components/ui/input";
|
|
import { Label } from "@/components/ui/label";
|
|
import { Textarea } from "@/components/ui/textarea";
|
|
import { useToast } from "@/hooks/use-toast";
|
|
import { getFlowDefinitions, createFlowDefinition, deleteFlowDefinition } from "@/lib/api/flow";
|
|
import { FlowDefinition } from "@/types/flow";
|
|
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
|
|
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
|
import { cn } from "@/lib/utils";
|
|
import { tableManagementApi } from "@/lib/api/tableManagement";
|
|
|
|
export default function FlowManagementPage() {
|
|
const router = useRouter();
|
|
const { toast } = useToast();
|
|
|
|
// 상태
|
|
const [flows, setFlows] = useState<FlowDefinition[]>([]);
|
|
const [loading, setLoading] = useState(true);
|
|
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
|
|
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
|
|
const [selectedFlow, setSelectedFlow] = useState<FlowDefinition | null>(null);
|
|
|
|
// 테이블 목록 관련 상태
|
|
const [tableList, setTableList] = useState<any[]>([]); // 내부 DB 테이블
|
|
const [loadingTables, setLoadingTables] = useState(false);
|
|
const [openTableCombobox, setOpenTableCombobox] = useState(false);
|
|
const [selectedDbSource, setSelectedDbSource] = useState<"internal" | number>("internal"); // "internal" 또는 외부 DB connection ID
|
|
const [externalConnections, setExternalConnections] = useState<any[]>([]);
|
|
const [externalTableList, setExternalTableList] = useState<string[]>([]);
|
|
const [loadingExternalTables, setLoadingExternalTables] = useState(false);
|
|
|
|
// 생성 폼 상태
|
|
const [formData, setFormData] = useState({
|
|
name: "",
|
|
description: "",
|
|
tableName: "",
|
|
});
|
|
|
|
// 플로우 목록 조회
|
|
const loadFlows = async () => {
|
|
setLoading(true);
|
|
try {
|
|
const response = await getFlowDefinitions({ isActive: true });
|
|
if (response.success && response.data) {
|
|
setFlows(response.data);
|
|
} else {
|
|
toast({
|
|
title: "조회 실패",
|
|
description: response.error || "플로우 목록을 불러올 수 없습니다.",
|
|
variant: "destructive",
|
|
});
|
|
}
|
|
} catch (error: any) {
|
|
toast({
|
|
title: "오류 발생",
|
|
description: error.message,
|
|
variant: "destructive",
|
|
});
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
useEffect(() => {
|
|
loadFlows();
|
|
}, []);
|
|
|
|
// 테이블 목록 로드 (내부 DB)
|
|
useEffect(() => {
|
|
const loadTables = async () => {
|
|
try {
|
|
setLoadingTables(true);
|
|
const response = await tableManagementApi.getTableList();
|
|
if (response.success && response.data) {
|
|
setTableList(response.data);
|
|
}
|
|
} catch (error) {
|
|
console.error("Failed to load tables:", error);
|
|
} finally {
|
|
setLoadingTables(false);
|
|
}
|
|
};
|
|
loadTables();
|
|
}, []);
|
|
|
|
// 외부 DB 연결 목록 로드
|
|
useEffect(() => {
|
|
const loadConnections = async () => {
|
|
try {
|
|
const token = localStorage.getItem("authToken");
|
|
if (!token) {
|
|
console.warn("No auth token found");
|
|
return;
|
|
}
|
|
|
|
const response = await fetch("/api/external-db-connections/control/active", {
|
|
headers: {
|
|
Authorization: `Bearer ${token}`,
|
|
},
|
|
});
|
|
|
|
if (response && response.ok) {
|
|
const data = await response.json();
|
|
if (data.success && data.data) {
|
|
// 메인 데이터베이스(현재 시스템) 제외 - connection_name에 "메인" 또는 "현재 시스템"이 포함된 것 필터링
|
|
const filtered = data.data.filter(
|
|
(conn: any) => !conn.connection_name.includes("메인") && !conn.connection_name.includes("현재 시스템"),
|
|
);
|
|
setExternalConnections(filtered);
|
|
}
|
|
}
|
|
} catch (error) {
|
|
console.error("Failed to load external connections:", error);
|
|
setExternalConnections([]);
|
|
}
|
|
};
|
|
loadConnections();
|
|
}, []);
|
|
|
|
// 외부 DB 테이블 목록 로드
|
|
useEffect(() => {
|
|
if (selectedDbSource === "internal" || !selectedDbSource) {
|
|
setExternalTableList([]);
|
|
return;
|
|
}
|
|
|
|
const loadExternalTables = async () => {
|
|
try {
|
|
setLoadingExternalTables(true);
|
|
const token = localStorage.getItem("authToken");
|
|
|
|
const response = await fetch(`/api/multi-connection/connections/${selectedDbSource}/tables`, {
|
|
headers: {
|
|
Authorization: `Bearer ${token}`,
|
|
},
|
|
});
|
|
|
|
if (response && response.ok) {
|
|
const data = await response.json();
|
|
if (data.success && data.data) {
|
|
const tables = Array.isArray(data.data) ? data.data : [];
|
|
const tableNames = tables
|
|
.map((t: any) => (typeof t === "string" ? t : t.tableName || t.table_name || t.tablename || t.name))
|
|
.filter(Boolean);
|
|
setExternalTableList(tableNames);
|
|
} else {
|
|
setExternalTableList([]);
|
|
}
|
|
} else {
|
|
setExternalTableList([]);
|
|
}
|
|
} catch (error) {
|
|
console.error("외부 DB 테이블 목록 조회 오류:", error);
|
|
setExternalTableList([]);
|
|
} finally {
|
|
setLoadingExternalTables(false);
|
|
}
|
|
};
|
|
|
|
loadExternalTables();
|
|
}, [selectedDbSource]);
|
|
|
|
// 플로우 생성
|
|
const handleCreate = async () => {
|
|
console.log("🚀 handleCreate called with formData:", formData);
|
|
|
|
if (!formData.name || !formData.tableName) {
|
|
console.log("❌ Validation failed:", { name: formData.name, tableName: formData.tableName });
|
|
toast({
|
|
title: "입력 오류",
|
|
description: "플로우 이름과 테이블 이름은 필수입니다.",
|
|
variant: "destructive",
|
|
});
|
|
return;
|
|
}
|
|
|
|
try {
|
|
// DB 소스 정보 추가
|
|
const requestData = {
|
|
...formData,
|
|
dbSourceType: selectedDbSource === "internal" ? "internal" : "external",
|
|
dbConnectionId: selectedDbSource === "internal" ? undefined : Number(selectedDbSource),
|
|
};
|
|
|
|
console.log("✅ Calling createFlowDefinition with:", requestData);
|
|
const response = await createFlowDefinition(requestData);
|
|
if (response.success && response.data) {
|
|
toast({
|
|
title: "생성 완료",
|
|
description: "플로우가 성공적으로 생성되었습니다.",
|
|
});
|
|
setIsCreateDialogOpen(false);
|
|
setFormData({ name: "", description: "", tableName: "" });
|
|
setSelectedDbSource("internal");
|
|
loadFlows();
|
|
} else {
|
|
toast({
|
|
title: "생성 실패",
|
|
description: response.error || response.message,
|
|
variant: "destructive",
|
|
});
|
|
}
|
|
} catch (error: any) {
|
|
toast({
|
|
title: "오류 발생",
|
|
description: error.message,
|
|
variant: "destructive",
|
|
});
|
|
}
|
|
};
|
|
|
|
// 플로우 삭제
|
|
const handleDelete = async () => {
|
|
if (!selectedFlow) return;
|
|
|
|
try {
|
|
const response = await deleteFlowDefinition(selectedFlow.id);
|
|
if (response.success) {
|
|
toast({
|
|
title: "삭제 완료",
|
|
description: "플로우가 삭제되었습니다.",
|
|
});
|
|
setIsDeleteDialogOpen(false);
|
|
setSelectedFlow(null);
|
|
loadFlows();
|
|
} else {
|
|
toast({
|
|
title: "삭제 실패",
|
|
description: response.error,
|
|
variant: "destructive",
|
|
});
|
|
}
|
|
} catch (error: any) {
|
|
toast({
|
|
title: "오류 발생",
|
|
description: error.message,
|
|
variant: "destructive",
|
|
});
|
|
}
|
|
};
|
|
|
|
// 플로우 편집기로 이동
|
|
const handleEdit = (flowId: number) => {
|
|
router.push(`/admin/flow-management/${flowId}`);
|
|
};
|
|
|
|
return (
|
|
<div className="container mx-auto space-y-4 p-3 sm:space-y-6 sm:p-4 lg:p-6">
|
|
{/* 헤더 */}
|
|
<div className="flex flex-col items-start justify-between gap-4 sm:flex-row sm:items-center">
|
|
<div className="flex-1">
|
|
<h1 className="flex items-center gap-2 text-xl font-bold sm:text-2xl lg:text-3xl">
|
|
<Workflow className="h-6 w-6 sm:h-7 sm:w-7 lg:h-8 lg:w-8" />
|
|
플로우 관리
|
|
</h1>
|
|
<p className="text-muted-foreground mt-1 text-xs sm:text-sm">업무 프로세스 플로우를 생성하고 관리합니다</p>
|
|
</div>
|
|
<Button onClick={() => setIsCreateDialogOpen(true)} className="w-full sm:w-auto">
|
|
<Plus className="mr-2 h-4 w-4" />
|
|
<span className="hidden sm:inline">새 플로우 생성</span>
|
|
<span className="sm:hidden">생성</span>
|
|
</Button>
|
|
</div>
|
|
|
|
{/* 플로우 카드 목록 */}
|
|
{loading ? (
|
|
<div className="py-8 text-center sm:py-12">
|
|
<p className="text-muted-foreground text-sm sm:text-base">로딩 중...</p>
|
|
</div>
|
|
) : flows.length === 0 ? (
|
|
<Card>
|
|
<CardContent className="py-8 text-center sm:py-12">
|
|
<Workflow className="text-muted-foreground mx-auto mb-3 h-10 w-10 sm:mb-4 sm:h-12 sm:w-12" />
|
|
<p className="text-muted-foreground mb-3 text-sm sm:mb-4 sm:text-base">생성된 플로우가 없습니다</p>
|
|
<Button onClick={() => setIsCreateDialogOpen(true)} className="w-full sm:w-auto">
|
|
<Plus className="mr-2 h-4 w-4" />첫 플로우 만들기
|
|
</Button>
|
|
</CardContent>
|
|
</Card>
|
|
) : (
|
|
<div className="grid grid-cols-1 gap-4 sm:gap-5 md:grid-cols-2 lg:gap-6 xl:grid-cols-3">
|
|
{flows.map((flow) => (
|
|
<Card
|
|
key={flow.id}
|
|
className="cursor-pointer transition-shadow hover:shadow-lg"
|
|
onClick={() => handleEdit(flow.id)}
|
|
>
|
|
<CardHeader className="p-4 sm:p-6">
|
|
<div className="flex items-start justify-between">
|
|
<div className="min-w-0 flex-1">
|
|
<CardTitle className="flex flex-col gap-1 text-base sm:flex-row sm:items-center sm:gap-2 sm:text-lg">
|
|
<span className="truncate">{flow.name}</span>
|
|
{flow.isActive && (
|
|
<Badge variant="success" className="self-start">
|
|
활성
|
|
</Badge>
|
|
)}
|
|
</CardTitle>
|
|
<CardDescription className="mt-1 line-clamp-2 text-xs sm:mt-2 sm:text-sm">
|
|
{flow.description || "설명 없음"}
|
|
</CardDescription>
|
|
</div>
|
|
</div>
|
|
</CardHeader>
|
|
<CardContent className="p-4 pt-0 sm:p-6">
|
|
<div className="space-y-1.5 text-xs sm:space-y-2 sm:text-sm">
|
|
<div className="text-muted-foreground flex items-center gap-1.5 sm:gap-2">
|
|
<Table className="h-3.5 w-3.5 shrink-0 sm:h-4 sm:w-4" />
|
|
<span className="truncate">{flow.tableName}</span>
|
|
</div>
|
|
<div className="text-muted-foreground flex items-center gap-1.5 sm:gap-2">
|
|
<User className="h-3.5 w-3.5 shrink-0 sm:h-4 sm:w-4" />
|
|
<span className="truncate">생성자: {flow.createdBy}</span>
|
|
</div>
|
|
<div className="text-muted-foreground flex items-center gap-1.5 sm:gap-2">
|
|
<Calendar className="h-3.5 w-3.5 shrink-0 sm:h-4 sm:w-4" />
|
|
<span>{new Date(flow.updatedAt).toLocaleDateString("ko-KR")}</span>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="mt-3 flex gap-2 sm:mt-4">
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
className="h-8 flex-1 text-xs sm:h-9 sm:text-sm"
|
|
onClick={(e) => {
|
|
e.stopPropagation();
|
|
handleEdit(flow.id);
|
|
}}
|
|
>
|
|
<Edit2 className="mr-1 h-3 w-3 sm:mr-2 sm:h-4 sm:w-4" />
|
|
편집
|
|
</Button>
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
className="h-8 px-2 text-xs sm:h-9 sm:px-3 sm:text-sm"
|
|
onClick={(e) => {
|
|
e.stopPropagation();
|
|
setSelectedFlow(flow);
|
|
setIsDeleteDialogOpen(true);
|
|
}}
|
|
>
|
|
<Trash2 className="h-3 w-3 sm:h-4 sm:w-4" />
|
|
</Button>
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
))}
|
|
</div>
|
|
)}
|
|
|
|
{/* 생성 다이얼로그 */}
|
|
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
|
|
<DialogContent className="max-w-[95vw] sm:max-w-[500px]">
|
|
<DialogHeader>
|
|
<DialogTitle className="text-base sm:text-lg">새 플로우 생성</DialogTitle>
|
|
<DialogDescription className="text-xs sm:text-sm">
|
|
새로운 업무 프로세스 플로우를 생성합니다
|
|
</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
<div className="space-y-3 sm:space-y-4">
|
|
<div>
|
|
<Label htmlFor="name" className="text-xs sm:text-sm">
|
|
플로우 이름 *
|
|
</Label>
|
|
<Input
|
|
id="name"
|
|
value={formData.name}
|
|
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
|
placeholder="예: 제품 수명주기 관리"
|
|
className="h-8 text-xs sm:h-10 sm:text-sm"
|
|
/>
|
|
</div>
|
|
|
|
{/* DB 소스 선택 */}
|
|
<div>
|
|
<Label className="text-xs sm:text-sm">데이터베이스 소스</Label>
|
|
<Select
|
|
value={selectedDbSource.toString()}
|
|
onValueChange={(value) => {
|
|
const dbSource = value === "internal" ? "internal" : parseInt(value);
|
|
setSelectedDbSource(dbSource);
|
|
// DB 소스 변경 시 테이블 선택 초기화
|
|
setFormData({ ...formData, tableName: "" });
|
|
}}
|
|
>
|
|
<SelectTrigger className="h-8 text-xs sm:h-10 sm:text-sm">
|
|
<SelectValue placeholder="데이터베이스 선택" />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
<SelectItem value="internal">내부 데이터베이스</SelectItem>
|
|
{externalConnections.map((conn: any) => (
|
|
<SelectItem key={conn.id} value={conn.id.toString()}>
|
|
{conn.connection_name} ({conn.db_type?.toUpperCase()})
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
<p className="text-muted-foreground mt-1 text-[10px] sm:text-xs">
|
|
플로우에서 사용할 데이터베이스를 선택합니다
|
|
</p>
|
|
</div>
|
|
|
|
{/* 테이블 선택 */}
|
|
<div>
|
|
<Label htmlFor="tableName" className="text-xs sm:text-sm">
|
|
연결 테이블 *
|
|
</Label>
|
|
<Popover open={openTableCombobox} onOpenChange={setOpenTableCombobox}>
|
|
<PopoverTrigger asChild>
|
|
<Button
|
|
variant="outline"
|
|
role="combobox"
|
|
aria-expanded={openTableCombobox}
|
|
className="h-8 w-full justify-between text-xs sm:h-10 sm:text-sm"
|
|
disabled={loadingTables || (selectedDbSource !== "internal" && loadingExternalTables)}
|
|
>
|
|
{formData.tableName
|
|
? selectedDbSource === "internal"
|
|
? tableList.find((table) => table.tableName === formData.tableName)?.displayName ||
|
|
formData.tableName
|
|
: formData.tableName
|
|
: loadingTables || loadingExternalTables
|
|
? "로딩 중..."
|
|
: "테이블 선택"}
|
|
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
|
</Button>
|
|
</PopoverTrigger>
|
|
<PopoverContent className="p-0" style={{ width: "var(--radix-popover-trigger-width)" }} align="start">
|
|
<Command>
|
|
<CommandInput placeholder="테이블 검색..." className="text-xs sm:text-sm" />
|
|
<CommandList>
|
|
<CommandEmpty className="text-xs sm:text-sm">테이블을 찾을 수 없습니다.</CommandEmpty>
|
|
<CommandGroup>
|
|
{selectedDbSource === "internal"
|
|
? // 내부 DB 테이블 목록
|
|
tableList.map((table) => (
|
|
<CommandItem
|
|
key={table.tableName}
|
|
value={table.tableName}
|
|
onSelect={(currentValue) => {
|
|
console.log("📝 Internal table selected:", {
|
|
tableName: table.tableName,
|
|
currentValue,
|
|
});
|
|
setFormData({ ...formData, tableName: currentValue });
|
|
setOpenTableCombobox(false);
|
|
}}
|
|
className="text-xs sm:text-sm"
|
|
>
|
|
<Check
|
|
className={cn(
|
|
"mr-2 h-4 w-4",
|
|
formData.tableName === table.tableName ? "opacity-100" : "opacity-0",
|
|
)}
|
|
/>
|
|
<div className="flex flex-col">
|
|
<span className="font-medium">{table.displayName || table.tableName}</span>
|
|
{table.description && (
|
|
<span className="text-[10px] text-gray-500">{table.description}</span>
|
|
)}
|
|
</div>
|
|
</CommandItem>
|
|
))
|
|
: // 외부 DB 테이블 목록
|
|
externalTableList.map((tableName, index) => (
|
|
<CommandItem
|
|
key={`external-${selectedDbSource}-${tableName}-${index}`}
|
|
value={tableName}
|
|
onSelect={(currentValue) => {
|
|
setFormData({ ...formData, tableName: currentValue });
|
|
setOpenTableCombobox(false);
|
|
}}
|
|
className="text-xs sm:text-sm"
|
|
>
|
|
<Check
|
|
className={cn(
|
|
"mr-2 h-4 w-4",
|
|
formData.tableName === tableName ? "opacity-100" : "opacity-0",
|
|
)}
|
|
/>
|
|
<div>{tableName}</div>
|
|
</CommandItem>
|
|
))}
|
|
</CommandGroup>
|
|
</CommandList>
|
|
</Command>
|
|
</PopoverContent>
|
|
</Popover>
|
|
<p className="text-muted-foreground mt-1 text-[10px] sm:text-xs">
|
|
플로우의 모든 단계에서 사용할 기본 테이블입니다 (단계마다 상태 컬럼만 지정합니다)
|
|
</p>
|
|
</div>
|
|
|
|
<div>
|
|
<Label htmlFor="description" className="text-xs sm:text-sm">
|
|
설명
|
|
</Label>
|
|
<Textarea
|
|
id="description"
|
|
value={formData.description}
|
|
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
|
|
placeholder="플로우에 대한 설명을 입력하세요"
|
|
rows={3}
|
|
className="text-xs sm:text-sm"
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<DialogFooter className="gap-2 sm:gap-0">
|
|
<Button
|
|
variant="outline"
|
|
onClick={() => setIsCreateDialogOpen(false)}
|
|
className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
|
|
>
|
|
취소
|
|
</Button>
|
|
<Button onClick={handleCreate} className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm">
|
|
생성
|
|
</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
|
|
{/* 삭제 확인 다이얼로그 */}
|
|
<Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
|
|
<DialogContent className="max-w-[95vw] sm:max-w-[500px]">
|
|
<DialogHeader>
|
|
<DialogTitle className="text-base sm:text-lg">플로우 삭제</DialogTitle>
|
|
<DialogDescription className="text-xs sm:text-sm">
|
|
정말로 "{selectedFlow?.name}" 플로우를 삭제하시겠습니까?
|
|
<br />이 작업은 되돌릴 수 없습니다.
|
|
</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
<DialogFooter className="gap-2 sm:gap-0">
|
|
<Button
|
|
variant="outline"
|
|
onClick={() => {
|
|
setIsDeleteDialogOpen(false);
|
|
setSelectedFlow(null);
|
|
}}
|
|
className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
|
|
>
|
|
취소
|
|
</Button>
|
|
<Button
|
|
variant="destructive"
|
|
onClick={handleDelete}
|
|
className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
|
|
>
|
|
삭제
|
|
</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
</div>
|
|
);
|
|
}
|