feat(WEB): 공정관리 드래그 순서변경, 수주서/출고증 리디자인, 체크리스트 관리 추가
- 공정관리: 드래그&드롭 순서 변경 기능 추가 (reorderProcesses API) - 수주서(SalesOrderDocument): 기획서 D1.8 기준 리디자인, 출고증과 동일 자재 섹션 구조 - 출고증(ShipmentOrderDocument): 레이아웃 개선 - 체크리스트 관리 페이지 신규 추가 (master-data/checklist-management) - QMS 품질감사: 타입 및 목데이터 수정 - menuRefresh 유틸 정리 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
315
src/components/checklist-management/ChecklistDetail.tsx
Normal file
315
src/components/checklist-management/ChecklistDetail.tsx
Normal file
@@ -0,0 +1,315 @@
|
||||
'use client';
|
||||
|
||||
/**
|
||||
* 점검표 상세 뷰 컴포넌트
|
||||
*
|
||||
* 기획서 스크린샷 2 기준:
|
||||
* - 기본 정보: 점검표 번호, 점검표명, 상태
|
||||
* - 항목 목록 테이블: 드래그&드롭 순서변경 + 항목 등록 버튼
|
||||
* - 하단: 삭제, 수정 버튼
|
||||
*/
|
||||
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { ArrowLeft, Edit, GripVertical, Plus, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { PageLayout } from '@/components/organisms/PageLayout';
|
||||
import { PageHeader } from '@/components/organisms/PageHeader';
|
||||
import { useMenuStore } from '@/store/menuStore';
|
||||
import { usePermission } from '@/hooks/usePermission';
|
||||
import { toast } from 'sonner';
|
||||
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
|
||||
import { getChecklistItems, reorderChecklistItems, deleteChecklist } from './actions';
|
||||
import type { Checklist, ChecklistItem } from '@/types/checklist';
|
||||
|
||||
interface ChecklistDetailProps {
|
||||
checklist: Checklist;
|
||||
}
|
||||
|
||||
export function ChecklistDetail({ checklist }: ChecklistDetailProps) {
|
||||
const router = useRouter();
|
||||
const sidebarCollapsed = useMenuStore((state) => state.sidebarCollapsed);
|
||||
const { canUpdate } = usePermission();
|
||||
|
||||
const [items, setItems] = useState<ChecklistItem[]>([]);
|
||||
const [isItemsLoading, setIsItemsLoading] = useState(true);
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
|
||||
// 드래그 상태
|
||||
const [dragIndex, setDragIndex] = useState<number | null>(null);
|
||||
const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);
|
||||
const dragNodeRef = useRef<HTMLTableRowElement | null>(null);
|
||||
|
||||
// 항목 목록 로드
|
||||
useEffect(() => {
|
||||
const loadItems = async () => {
|
||||
setIsItemsLoading(true);
|
||||
const result = await getChecklistItems(checklist.id);
|
||||
if (result.success && result.data) {
|
||||
setItems(result.data);
|
||||
}
|
||||
setIsItemsLoading(false);
|
||||
};
|
||||
loadItems();
|
||||
}, [checklist.id]);
|
||||
|
||||
// 네비게이션
|
||||
const handleEdit = () => {
|
||||
router.push(`/ko/master-data/checklist-management/${checklist.id}?mode=edit`);
|
||||
};
|
||||
|
||||
const handleList = () => {
|
||||
router.push('/ko/master-data/checklist-management');
|
||||
};
|
||||
|
||||
const handleAddItem = () => {
|
||||
router.push(`/ko/master-data/checklist-management/${checklist.id}/items/new`);
|
||||
};
|
||||
|
||||
const handleItemClick = (itemId: string) => {
|
||||
router.push(`/ko/master-data/checklist-management/${checklist.id}/items/${itemId}`);
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
setIsDeleting(true);
|
||||
try {
|
||||
const result = await deleteChecklist(checklist.id);
|
||||
if (result.success) {
|
||||
toast.success('점검표가 삭제되었습니다.');
|
||||
router.push('/ko/master-data/checklist-management');
|
||||
} else {
|
||||
toast.error(result.error || '삭제에 실패했습니다.');
|
||||
}
|
||||
} catch {
|
||||
toast.error('삭제 중 오류가 발생했습니다.');
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
setDeleteDialogOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
// ===== 드래그&드롭 =====
|
||||
const handleDragStart = useCallback(
|
||||
(e: React.DragEvent<HTMLTableRowElement>, index: number) => {
|
||||
setDragIndex(index);
|
||||
dragNodeRef.current = e.currentTarget;
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
requestAnimationFrame(() => {
|
||||
if (dragNodeRef.current) dragNodeRef.current.style.opacity = '0.4';
|
||||
});
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const handleDragOver = useCallback(
|
||||
(e: React.DragEvent<HTMLTableRowElement>, index: number) => {
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = 'move';
|
||||
setDragOverIndex(index);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const handleDragEnd = useCallback(() => {
|
||||
if (dragNodeRef.current) dragNodeRef.current.style.opacity = '1';
|
||||
setDragIndex(null);
|
||||
setDragOverIndex(null);
|
||||
dragNodeRef.current = null;
|
||||
}, []);
|
||||
|
||||
const handleDrop = useCallback(
|
||||
(e: React.DragEvent<HTMLTableRowElement>, dropIndex: number) => {
|
||||
e.preventDefault();
|
||||
if (dragIndex === null || dragIndex === dropIndex) return;
|
||||
|
||||
setItems((prev) => {
|
||||
const updated = [...prev];
|
||||
const [moved] = updated.splice(dragIndex, 1);
|
||||
updated.splice(dropIndex, 0, moved);
|
||||
const reordered = updated.map((item, i) => ({ ...item, order: i + 1 }));
|
||||
|
||||
reorderChecklistItems(
|
||||
checklist.id,
|
||||
reordered.map((it) => ({ id: it.id, order: it.order }))
|
||||
);
|
||||
|
||||
return reordered;
|
||||
});
|
||||
|
||||
handleDragEnd();
|
||||
},
|
||||
[dragIndex, handleDragEnd, checklist.id]
|
||||
);
|
||||
|
||||
return (
|
||||
<PageLayout>
|
||||
<PageHeader title="점검표 상세" />
|
||||
|
||||
<div className="space-y-6 pb-24">
|
||||
{/* 기본 정보 */}
|
||||
<Card>
|
||||
<CardHeader className="bg-muted/50">
|
||||
<CardTitle className="text-base">기본 정보</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-6">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-6">
|
||||
<div className="space-y-1">
|
||||
<div className="text-sm text-muted-foreground">점검표 번호</div>
|
||||
<div className="font-medium font-mono">{checklist.checklistCode}</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="text-sm text-muted-foreground">점검표</div>
|
||||
<div className="font-medium">{checklist.checklistName}</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="text-sm text-muted-foreground">상태</div>
|
||||
<Badge variant={checklist.status === '사용' ? 'default' : 'secondary'}>
|
||||
{checklist.status}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 항목 테이블 */}
|
||||
<Card>
|
||||
<CardHeader className="bg-muted/50">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-base">
|
||||
항목 목록
|
||||
{!isItemsLoading && (
|
||||
<span className="text-sm font-normal text-muted-foreground ml-2">
|
||||
총 {items.length}건
|
||||
</span>
|
||||
)}
|
||||
</CardTitle>
|
||||
<Button size="sm" onClick={handleAddItem}>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
항목 등록
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0">
|
||||
{isItemsLoading ? (
|
||||
<div className="p-8 text-center text-muted-foreground">로딩 중...</div>
|
||||
) : items.length === 0 ? (
|
||||
<div className="p-8 text-center text-muted-foreground">
|
||||
등록된 항목이 없습니다. [항목 등록] 버튼으로 추가해주세요.
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full">
|
||||
<thead>
|
||||
<tr className="border-b bg-muted/30">
|
||||
<th className="w-10 px-3 py-3 text-center text-xs font-medium text-muted-foreground" />
|
||||
<th className="w-14 px-3 py-3 text-center text-xs font-medium text-muted-foreground">
|
||||
No.
|
||||
</th>
|
||||
<th className="px-3 py-3 text-left text-xs font-medium text-muted-foreground">
|
||||
항목 번호
|
||||
</th>
|
||||
<th className="w-16 px-3 py-3 text-center text-xs font-medium text-muted-foreground">
|
||||
순서
|
||||
</th>
|
||||
<th className="px-3 py-3 text-left text-xs font-medium text-muted-foreground">
|
||||
항목명
|
||||
</th>
|
||||
<th className="w-16 px-3 py-3 text-center text-xs font-medium text-muted-foreground">
|
||||
문서
|
||||
</th>
|
||||
<th className="w-16 px-3 py-3 text-center text-xs font-medium text-muted-foreground">
|
||||
사용
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{items.map((item, index) => (
|
||||
<tr
|
||||
key={item.id}
|
||||
draggable
|
||||
onDragStart={(e) => handleDragStart(e, index)}
|
||||
onDragOver={(e) => handleDragOver(e, index)}
|
||||
onDragEnd={handleDragEnd}
|
||||
onDrop={(e) => handleDrop(e, index)}
|
||||
onClick={() => handleItemClick(item.id)}
|
||||
className={`border-b cursor-pointer transition-colors hover:bg-muted/50 ${
|
||||
dragOverIndex === index && dragIndex !== index
|
||||
? 'border-t-2 border-t-primary'
|
||||
: ''
|
||||
}`}
|
||||
>
|
||||
<td
|
||||
className="w-10 px-3 py-3 text-center cursor-grab active:cursor-grabbing"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<GripVertical className="h-4 w-4 text-muted-foreground mx-auto" />
|
||||
</td>
|
||||
<td className="w-14 px-3 py-3 text-center text-sm text-muted-foreground">
|
||||
{index + 1}
|
||||
</td>
|
||||
<td className="px-3 py-3 text-sm font-mono">{item.itemCode}</td>
|
||||
<td className="w-16 px-3 py-3 text-center text-sm">
|
||||
{item.order}
|
||||
</td>
|
||||
<td className="px-3 py-3 text-sm font-medium">{item.itemName}</td>
|
||||
<td className="w-16 px-3 py-3 text-center text-sm">
|
||||
{item.documentCount}
|
||||
</td>
|
||||
<td className="w-16 px-3 py-3 text-center">
|
||||
<Badge
|
||||
variant={item.status === '사용' ? 'default' : 'secondary'}
|
||||
className="text-xs"
|
||||
>
|
||||
{item.status}
|
||||
</Badge>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* 하단 액션 버튼 (sticky) */}
|
||||
<div
|
||||
className={`fixed bottom-4 left-4 right-4 px-4 py-3 bg-background/95 backdrop-blur rounded-xl border shadow-lg z-50 transition-all duration-300 md:bottom-6 md:px-6 md:right-[48px] ${sidebarCollapsed ? 'md:left-[156px]' : 'md:left-[316px]'} flex items-center justify-between`}
|
||||
>
|
||||
<Button variant="outline" onClick={handleList} size="sm" className="md:size-default">
|
||||
<ArrowLeft className="h-4 w-4 md:mr-2" />
|
||||
<span className="hidden md:inline">목록으로</span>
|
||||
</Button>
|
||||
{canUpdate && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() => setDeleteDialogOpen(true)}
|
||||
size="sm"
|
||||
className="md:size-default"
|
||||
>
|
||||
<Trash2 className="h-4 w-4 md:mr-2" />
|
||||
<span className="hidden md:inline">삭제</span>
|
||||
</Button>
|
||||
<Button onClick={handleEdit} size="sm" className="md:size-default">
|
||||
<Edit className="h-4 w-4 md:mr-2" />
|
||||
<span className="hidden md:inline">수정</span>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DeleteConfirmDialog
|
||||
open={deleteDialogOpen}
|
||||
onOpenChange={setDeleteDialogOpen}
|
||||
description="이 점검표를 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다."
|
||||
loading={isDeleting}
|
||||
onConfirm={handleDelete}
|
||||
/>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
122
src/components/checklist-management/ChecklistDetailClient.tsx
Normal file
122
src/components/checklist-management/ChecklistDetailClient.tsx
Normal file
@@ -0,0 +1,122 @@
|
||||
'use client';
|
||||
|
||||
/**
|
||||
* 점검표 상세 클라이언트 컴포넌트
|
||||
*
|
||||
* 라우팅:
|
||||
* - /[id] → 상세 보기 (view)
|
||||
* - /[id]?mode=edit → 수정 (edit)
|
||||
* - ?mode=new → 등록 (create)
|
||||
*/
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { ChecklistDetail } from './ChecklistDetail';
|
||||
import { ChecklistForm } from './ChecklistForm';
|
||||
import { getChecklistById } from './actions';
|
||||
import type { Checklist } from '@/types/checklist';
|
||||
import { DetailPageSkeleton } from '@/components/ui/skeleton';
|
||||
import { ErrorCard } from '@/components/ui/error-card';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
type DetailMode = 'view' | 'edit' | 'create';
|
||||
|
||||
interface ChecklistDetailClientProps {
|
||||
checklistId?: string;
|
||||
}
|
||||
|
||||
const BASE_PATH = '/ko/master-data/checklist-management';
|
||||
|
||||
export function ChecklistDetailClient({ checklistId }: ChecklistDetailClientProps) {
|
||||
const searchParams = useSearchParams();
|
||||
const modeFromQuery = searchParams.get('mode') as DetailMode | null;
|
||||
const isNewMode = !checklistId || checklistId === 'new';
|
||||
|
||||
const [mode, setMode] = useState<DetailMode>(() => {
|
||||
if (isNewMode) return 'create';
|
||||
if (modeFromQuery === 'edit') return 'edit';
|
||||
return 'view';
|
||||
});
|
||||
|
||||
const [checklistData, setChecklistData] = useState<Checklist | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(!isNewMode);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (isNewMode) {
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const loadData = async () => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await getChecklistById(checklistId!);
|
||||
if (result.success && result.data) {
|
||||
setChecklistData(result.data);
|
||||
} else {
|
||||
setError(result.error || '점검표 정보를 찾을 수 없습니다.');
|
||||
toast.error('점검표를 불러오는데 실패했습니다.');
|
||||
}
|
||||
} catch {
|
||||
setError('점검표 정보를 불러오는 중 오류가 발생했습니다.');
|
||||
toast.error('점검표를 불러오는데 실패했습니다.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadData();
|
||||
}, [checklistId, isNewMode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isNewMode && modeFromQuery === 'edit') {
|
||||
setMode('edit');
|
||||
} else if (!isNewMode && !modeFromQuery) {
|
||||
setMode('view');
|
||||
}
|
||||
}, [modeFromQuery, isNewMode]);
|
||||
|
||||
if (isLoading) {
|
||||
return <DetailPageSkeleton sections={1} fieldsPerSection={3} />;
|
||||
}
|
||||
|
||||
if (error && !isNewMode) {
|
||||
return (
|
||||
<ErrorCard
|
||||
type="network"
|
||||
title="점검표 정보를 불러올 수 없습니다"
|
||||
description={error}
|
||||
tips={[
|
||||
'해당 점검표가 존재하는지 확인해주세요',
|
||||
'인터넷 연결 상태를 확인해주세요',
|
||||
]}
|
||||
homeButtonLabel="목록으로 이동"
|
||||
homeButtonHref={BASE_PATH}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (mode === 'create') {
|
||||
return <ChecklistForm mode="create" />;
|
||||
}
|
||||
|
||||
if (mode === 'edit' && checklistData) {
|
||||
return <ChecklistForm mode="edit" initialData={checklistData} />;
|
||||
}
|
||||
|
||||
if (mode === 'view' && checklistData) {
|
||||
return <ChecklistDetail checklist={checklistData} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<ErrorCard
|
||||
type="not-found"
|
||||
title="점검표를 찾을 수 없습니다"
|
||||
description="요청하신 점검표 정보가 존재하지 않습니다."
|
||||
homeButtonLabel="목록으로 이동"
|
||||
homeButtonHref={BASE_PATH}
|
||||
/>
|
||||
);
|
||||
}
|
||||
172
src/components/checklist-management/ChecklistForm.tsx
Normal file
172
src/components/checklist-management/ChecklistForm.tsx
Normal file
@@ -0,0 +1,172 @@
|
||||
'use client';
|
||||
|
||||
/**
|
||||
* 점검표 등록/수정 폼 컴포넌트
|
||||
*
|
||||
* 기획서 스크린샷 2 기준:
|
||||
* - 기본 정보: 점검표 번호(자동), 점검표명, 상태
|
||||
*/
|
||||
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
|
||||
import { toast } from 'sonner';
|
||||
import type { Checklist } from '@/types/checklist';
|
||||
import { createChecklist, updateChecklist } from './actions';
|
||||
import type { DetailConfig } from '@/components/templates/IntegratedDetailTemplate/types';
|
||||
|
||||
const createConfig: DetailConfig = {
|
||||
title: '점검표',
|
||||
description: '새로운 점검표를 등록합니다',
|
||||
basePath: '',
|
||||
fields: [],
|
||||
actions: {
|
||||
showBack: true,
|
||||
showEdit: false,
|
||||
showDelete: false,
|
||||
showSave: true,
|
||||
submitLabel: '등록',
|
||||
},
|
||||
};
|
||||
|
||||
const editConfig: DetailConfig = {
|
||||
...createConfig,
|
||||
description: '점검표 정보를 수정합니다',
|
||||
actions: {
|
||||
...createConfig.actions,
|
||||
submitLabel: '저장',
|
||||
},
|
||||
};
|
||||
|
||||
interface ChecklistFormProps {
|
||||
mode: 'create' | 'edit';
|
||||
initialData?: Checklist;
|
||||
}
|
||||
|
||||
export function ChecklistForm({ mode, initialData }: ChecklistFormProps) {
|
||||
const router = useRouter();
|
||||
const isEdit = mode === 'edit';
|
||||
|
||||
const [checklistName, setChecklistName] = useState(initialData?.checklistName || '');
|
||||
const [status, setStatus] = useState<string>(initialData?.status || '사용');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const handleSubmit = async (): Promise<{ success: boolean; error?: string }> => {
|
||||
if (!checklistName.trim()) {
|
||||
toast.error('점검표명을 입력해주세요.');
|
||||
return { success: false, error: '점검표명을 입력해주세요.' };
|
||||
}
|
||||
|
||||
const formData = {
|
||||
checklistName: checklistName.trim(),
|
||||
status: status as '사용' | '미사용',
|
||||
};
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
if (isEdit && initialData?.id) {
|
||||
const result = await updateChecklist(initialData.id, formData);
|
||||
if (result.success) {
|
||||
toast.success('점검표가 수정되었습니다.');
|
||||
router.push(`/ko/master-data/checklist-management/${initialData.id}`);
|
||||
return { success: true };
|
||||
} else {
|
||||
toast.error(result.error || '수정에 실패했습니다.');
|
||||
return { success: false, error: result.error };
|
||||
}
|
||||
} else {
|
||||
const result = await createChecklist(formData);
|
||||
if (result.success && result.data) {
|
||||
toast.success('점검표가 등록되었습니다.');
|
||||
router.push(`/ko/master-data/checklist-management/${result.data.id}`);
|
||||
return { success: true };
|
||||
} else {
|
||||
toast.error(result.error || '등록에 실패했습니다.');
|
||||
return { success: false, error: result.error };
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
toast.error('처리 중 오류가 발생했습니다.');
|
||||
return { success: false, error: '처리 중 오류가 발생했습니다.' };
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
if (isEdit && initialData?.id) {
|
||||
router.push(`/ko/master-data/checklist-management/${initialData.id}`);
|
||||
} else {
|
||||
router.push('/ko/master-data/checklist-management');
|
||||
}
|
||||
};
|
||||
|
||||
const renderFormContent = useCallback(
|
||||
() => (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader className="bg-muted/50">
|
||||
<CardTitle className="text-base">기본 정보</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-6">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-6">
|
||||
<div className="space-y-2">
|
||||
<Label>점검표 번호</Label>
|
||||
<Input
|
||||
value={initialData?.checklistCode || '자동생성'}
|
||||
disabled
|
||||
className="bg-muted"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="checklistName">점검표 *</Label>
|
||||
<Input
|
||||
id="checklistName"
|
||||
value={checklistName}
|
||||
onChange={(e) => setChecklistName(e.target.value)}
|
||||
placeholder="점검표명을 입력하세요"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>상태</Label>
|
||||
<Select value={status} onValueChange={setStatus}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="사용">사용</SelectItem>
|
||||
<SelectItem value="미사용">미사용</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
),
|
||||
[checklistName, status, initialData?.checklistCode]
|
||||
);
|
||||
|
||||
const config = isEdit ? editConfig : createConfig;
|
||||
|
||||
return (
|
||||
<IntegratedDetailTemplate
|
||||
config={config}
|
||||
mode={isEdit ? 'edit' : 'create'}
|
||||
isLoading={false}
|
||||
onCancel={handleCancel}
|
||||
onSubmit={handleSubmit}
|
||||
renderForm={renderFormContent}
|
||||
/>
|
||||
);
|
||||
}
|
||||
519
src/components/checklist-management/ChecklistListClient.tsx
Normal file
519
src/components/checklist-management/ChecklistListClient.tsx
Normal file
@@ -0,0 +1,519 @@
|
||||
'use client';
|
||||
|
||||
/**
|
||||
* 점검표 목록 - UniversalListPage 기반
|
||||
*
|
||||
* 공정 목록(ProcessListClient)과 동일한 패턴:
|
||||
* - 클라이언트 사이드 필터링 (상태별)
|
||||
* - 드래그&드롭 순서 변경
|
||||
* - 상태 토글
|
||||
*/
|
||||
|
||||
import { useState, useMemo, useCallback, useEffect, useRef } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { ClipboardList, Plus, GripVertical } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { TableCell, TableRow, TableHead } from '@/components/ui/table';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
UniversalListPage,
|
||||
type UniversalListConfig,
|
||||
type SelectionHandlers,
|
||||
type RowClickHandlers,
|
||||
type ListParams,
|
||||
} from '@/components/templates/UniversalListPage';
|
||||
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
|
||||
import { toast } from 'sonner';
|
||||
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
|
||||
import type { Checklist } from '@/types/checklist';
|
||||
import {
|
||||
getChecklistList,
|
||||
deleteChecklist,
|
||||
deleteChecklists,
|
||||
toggleChecklistStatus,
|
||||
getChecklistStats,
|
||||
reorderChecklists,
|
||||
} from './actions';
|
||||
|
||||
export default function ChecklistListClient() {
|
||||
const router = useRouter();
|
||||
|
||||
// ===== 상태 =====
|
||||
const [allChecklists, setAllChecklists] = useState<Checklist[]>([]);
|
||||
const [stats, setStats] = useState({ total: 0, active: 0, inactive: 0 });
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
|
||||
|
||||
// 날짜 범위 상태
|
||||
const [startDate, setStartDate] = useState('2025-01-01');
|
||||
const [endDate, setEndDate] = useState('2025-12-31');
|
||||
|
||||
// 검색어 상태
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
|
||||
// 드래그&드롭 순서 변경 상태
|
||||
const [isOrderChanged, setIsOrderChanged] = useState(false);
|
||||
const dragIdRef = useRef<string | null>(null);
|
||||
const dragNodeRef = useRef<HTMLTableRowElement | null>(null);
|
||||
const allChecklistsRef = useRef(allChecklists);
|
||||
allChecklistsRef.current = allChecklists;
|
||||
|
||||
// ===== 데이터 로드 =====
|
||||
const loadData = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const [listResult, statsResult] = await Promise.all([
|
||||
getChecklistList(),
|
||||
getChecklistStats(),
|
||||
]);
|
||||
|
||||
if (listResult.success && listResult.data) {
|
||||
setAllChecklists(listResult.data.items);
|
||||
}
|
||||
if (statsResult.success && statsResult.data) {
|
||||
setStats(statsResult.data);
|
||||
}
|
||||
} catch {
|
||||
toast.error('데이터 로드에 실패했습니다.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, [loadData]);
|
||||
|
||||
// ===== 핸들러 =====
|
||||
const handleRowClick = useCallback(
|
||||
(checklist: Checklist) => {
|
||||
router.push(`/ko/master-data/checklist-management/${checklist.id}`);
|
||||
},
|
||||
[router]
|
||||
);
|
||||
|
||||
const handleCreate = useCallback(() => {
|
||||
router.push('/ko/master-data/checklist-management?mode=new');
|
||||
}, [router]);
|
||||
|
||||
const handleDeleteConfirm = useCallback(async () => {
|
||||
if (!deleteTargetId) return;
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const result = await deleteChecklist(deleteTargetId);
|
||||
if (result.success) {
|
||||
toast.success('점검표가 삭제되었습니다.');
|
||||
setAllChecklists((prev) => prev.filter((c) => c.id !== deleteTargetId));
|
||||
} else {
|
||||
toast.error(result.error || '삭제에 실패했습니다.');
|
||||
}
|
||||
} catch {
|
||||
toast.error('삭제 중 오류가 발생했습니다.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
setDeleteDialogOpen(false);
|
||||
setDeleteTargetId(null);
|
||||
}
|
||||
}, [deleteTargetId]);
|
||||
|
||||
const handleBulkDelete = useCallback(
|
||||
async (selectedIds: string[]) => {
|
||||
if (selectedIds.length === 0) {
|
||||
toast.warning('삭제할 항목을 선택해주세요.');
|
||||
return;
|
||||
}
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const result = await deleteChecklists(selectedIds);
|
||||
if (result.success) {
|
||||
toast.success(`${result.deletedCount}개 항목이 삭제되었습니다.`);
|
||||
await loadData();
|
||||
} else {
|
||||
toast.error(result.error || '일괄 삭제에 실패했습니다.');
|
||||
}
|
||||
} catch {
|
||||
toast.error('일괄 삭제 중 오류가 발생했습니다.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
},
|
||||
[loadData]
|
||||
);
|
||||
|
||||
const handleToggleStatus = useCallback(
|
||||
async (checklistId: string) => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const result = await toggleChecklistStatus(checklistId);
|
||||
if (result.success && result.data) {
|
||||
toast.success('상태가 변경되었습니다.');
|
||||
setAllChecklists((prev) =>
|
||||
prev.map((c) => (c.id === checklistId ? result.data! : c))
|
||||
);
|
||||
} else {
|
||||
toast.error(result.error || '상태 변경에 실패했습니다.');
|
||||
}
|
||||
} catch {
|
||||
toast.error('상태 변경 중 오류가 발생했습니다.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
// ===== 드래그&드롭 =====
|
||||
const handleDragStart = useCallback(
|
||||
(e: React.DragEvent<HTMLTableRowElement>, id: string) => {
|
||||
dragIdRef.current = id;
|
||||
dragNodeRef.current = e.currentTarget;
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
requestAnimationFrame(() => {
|
||||
if (dragNodeRef.current) dragNodeRef.current.style.opacity = '0.4';
|
||||
});
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const handleDragOver = useCallback(
|
||||
(e: React.DragEvent<HTMLTableRowElement>) => {
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = 'move';
|
||||
e.currentTarget.classList.add('border-t-2', 'border-t-primary');
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const handleDragLeave = useCallback(
|
||||
(e: React.DragEvent<HTMLTableRowElement>) => {
|
||||
const related = e.relatedTarget as Node;
|
||||
if (!e.currentTarget.contains(related)) {
|
||||
e.currentTarget.classList.remove('border-t-2', 'border-t-primary');
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const handleDragEnd = useCallback(() => {
|
||||
if (dragNodeRef.current) dragNodeRef.current.style.opacity = '1';
|
||||
dragIdRef.current = null;
|
||||
dragNodeRef.current = null;
|
||||
}, []);
|
||||
|
||||
const handleDrop = useCallback(
|
||||
(e: React.DragEvent<HTMLTableRowElement>, dropId: string) => {
|
||||
e.preventDefault();
|
||||
e.currentTarget.classList.remove('border-t-2', 'border-t-primary');
|
||||
const dragId = dragIdRef.current;
|
||||
if (!dragId || dragId === dropId) {
|
||||
handleDragEnd();
|
||||
return;
|
||||
}
|
||||
setAllChecklists((prev) => {
|
||||
const updated = [...prev];
|
||||
const dragIdx = updated.findIndex((c) => c.id === dragId);
|
||||
const dropIdx = updated.findIndex((c) => c.id === dropId);
|
||||
if (dragIdx === -1 || dropIdx === -1) return prev;
|
||||
const [moved] = updated.splice(dragIdx, 1);
|
||||
updated.splice(dropIdx, 0, moved);
|
||||
return updated;
|
||||
});
|
||||
setIsOrderChanged(true);
|
||||
handleDragEnd();
|
||||
},
|
||||
[handleDragEnd]
|
||||
);
|
||||
|
||||
const handleSaveOrder = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const orderData = allChecklistsRef.current.map((c, idx) => ({
|
||||
id: c.id,
|
||||
order: idx + 1,
|
||||
}));
|
||||
const result = await reorderChecklists(orderData);
|
||||
if (result.success) {
|
||||
toast.success('순서가 저장되었습니다.');
|
||||
setIsOrderChanged(false);
|
||||
} else {
|
||||
toast.error(result.error || '순서 저장에 실패했습니다.');
|
||||
}
|
||||
} catch {
|
||||
toast.error('순서 저장 중 오류가 발생했습니다.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// ===== UniversalListPage Config =====
|
||||
const config: UniversalListConfig<Checklist> = useMemo(
|
||||
() => ({
|
||||
title: '점검표 목록',
|
||||
icon: ClipboardList,
|
||||
basePath: '/master-data/checklist-management',
|
||||
idField: 'id',
|
||||
|
||||
actions: {
|
||||
getList: async (params?: ListParams) => {
|
||||
try {
|
||||
const [listResult, statsResult] = await Promise.all([
|
||||
getChecklistList(),
|
||||
getChecklistStats(),
|
||||
]);
|
||||
if (listResult.success && listResult.data) {
|
||||
setAllChecklists(listResult.data.items);
|
||||
if (statsResult.success && statsResult.data) {
|
||||
setStats(statsResult.data);
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
data: listResult.data.items,
|
||||
totalCount: listResult.data.items.length,
|
||||
totalPages: 1,
|
||||
};
|
||||
}
|
||||
return { success: false, error: '데이터 로드에 실패했습니다.' };
|
||||
} catch {
|
||||
return { success: false, error: '서버 오류가 발생했습니다.' };
|
||||
}
|
||||
},
|
||||
deleteItem: async (id: string) => {
|
||||
const result = await deleteChecklist(id);
|
||||
return { success: result.success, error: result.error };
|
||||
},
|
||||
deleteBulk: async (ids: string[]) => {
|
||||
const result = await deleteChecklists(ids);
|
||||
return { success: result.success, error: result.error };
|
||||
},
|
||||
},
|
||||
|
||||
// 테이블 컬럼 (showCheckbox: false → 수동 관리)
|
||||
showCheckbox: false,
|
||||
columns: [
|
||||
{ key: 'drag', label: '', className: 'w-[40px]' },
|
||||
{ key: 'checkbox', label: '', className: 'w-[50px]' },
|
||||
{ key: 'no', label: 'No.', className: 'w-[60px] text-center' },
|
||||
{ key: 'checklistCode', label: '점검표 번호', className: 'w-[120px]' },
|
||||
{ key: 'checklistName', label: '점검표', className: 'min-w-[200px]' },
|
||||
{ key: 'items', label: '항목', className: 'w-[80px] text-center' },
|
||||
{ key: 'documents', label: '문서', className: 'w-[80px] text-center' },
|
||||
{ key: 'status', label: '상태', className: 'w-[80px] text-center' },
|
||||
],
|
||||
|
||||
// 커스텀 테이블 헤더 (드래그 → 전체선택 체크박스 → No. → 데이터 순)
|
||||
renderCustomTableHeader: ({ displayData, selectedItems, onToggleSelectAll }) => (
|
||||
<>
|
||||
<TableHead className="w-[40px]" />
|
||||
<TableHead className="w-[50px] text-center">
|
||||
<Checkbox
|
||||
checked={displayData.length > 0 && selectedItems.size === displayData.length}
|
||||
onCheckedChange={onToggleSelectAll}
|
||||
/>
|
||||
</TableHead>
|
||||
<TableHead className="w-[60px] text-center">No.</TableHead>
|
||||
<TableHead className="w-[120px]">점검표 번호</TableHead>
|
||||
<TableHead className="min-w-[200px]">점검표</TableHead>
|
||||
<TableHead className="w-[80px] text-center">항목</TableHead>
|
||||
<TableHead className="w-[80px] text-center">문서</TableHead>
|
||||
<TableHead className="w-[80px] text-center">상태</TableHead>
|
||||
</>
|
||||
),
|
||||
|
||||
clientSideFiltering: true,
|
||||
itemsPerPage: 20,
|
||||
|
||||
hideSearch: true,
|
||||
searchValue: searchQuery,
|
||||
onSearchChange: setSearchQuery,
|
||||
|
||||
dateRangeSelector: {
|
||||
enabled: true,
|
||||
showPresets: true,
|
||||
startDate,
|
||||
endDate,
|
||||
onStartDateChange: setStartDate,
|
||||
onEndDateChange: setEndDate,
|
||||
},
|
||||
|
||||
filterConfig: [
|
||||
{
|
||||
key: 'status',
|
||||
label: '상태',
|
||||
type: 'single' as const,
|
||||
options: [
|
||||
{ value: '사용', label: '사용' },
|
||||
{ value: '미사용', label: '미사용' },
|
||||
],
|
||||
allOptionLabel: '전체',
|
||||
},
|
||||
],
|
||||
initialFilters: { status: '' },
|
||||
|
||||
customFilterFn: (
|
||||
items: Checklist[],
|
||||
filterValues: Record<string, string | string[]>
|
||||
) => {
|
||||
const statusFilter = filterValues.status as string;
|
||||
if (!statusFilter) return items;
|
||||
return items.filter((item) => item.status === statusFilter);
|
||||
},
|
||||
|
||||
searchFilter: (item, searchValue) => {
|
||||
if (!searchValue || !searchValue.trim()) return true;
|
||||
const search = searchValue.toLowerCase().trim();
|
||||
return (
|
||||
(item.checklistCode || '').toLowerCase().includes(search) ||
|
||||
(item.checklistName || '').toLowerCase().includes(search)
|
||||
);
|
||||
},
|
||||
|
||||
headerActions: () => (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleSaveOrder}
|
||||
disabled={!isOrderChanged}
|
||||
>
|
||||
순서 변경 저장
|
||||
</Button>
|
||||
),
|
||||
|
||||
createButton: {
|
||||
label: '점검표 등록',
|
||||
onClick: handleCreate,
|
||||
icon: Plus,
|
||||
},
|
||||
|
||||
onBulkDelete: handleBulkDelete,
|
||||
|
||||
renderTableRow: (
|
||||
checklist: Checklist,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
handlers: SelectionHandlers & RowClickHandlers<Checklist>
|
||||
) => (
|
||||
<TableRow
|
||||
key={checklist.id}
|
||||
draggable
|
||||
onDragStart={(e) => handleDragStart(e, checklist.id)}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDragEnd={handleDragEnd}
|
||||
onDrop={(e) => handleDrop(e, checklist.id)}
|
||||
className={`cursor-pointer hover:bg-muted/50 ${handlers.isSelected ? 'bg-blue-50' : ''}`}
|
||||
onClick={() => handleRowClick(checklist)}
|
||||
>
|
||||
<TableCell
|
||||
className="text-center cursor-grab active:cursor-grabbing"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<GripVertical className="h-4 w-4 text-muted-foreground mx-auto" />
|
||||
</TableCell>
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
<Checkbox
|
||||
checked={handlers.isSelected}
|
||||
onCheckedChange={handlers.onToggle}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="text-center text-muted-foreground">
|
||||
{globalIndex}
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">{checklist.checklistCode}</TableCell>
|
||||
<TableCell>{checklist.checklistName}</TableCell>
|
||||
<TableCell className="text-center">{checklist.itemCount}</TableCell>
|
||||
<TableCell className="text-center">{checklist.documentCount}</TableCell>
|
||||
<TableCell
|
||||
className="text-center"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Badge
|
||||
variant={checklist.status === '사용' ? 'default' : 'secondary'}
|
||||
className="cursor-pointer"
|
||||
onClick={() => handleToggleStatus(checklist.id)}
|
||||
>
|
||||
{checklist.status}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
),
|
||||
|
||||
renderMobileCard: (
|
||||
checklist: Checklist,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
handlers: SelectionHandlers & RowClickHandlers<Checklist>
|
||||
) => (
|
||||
<ListMobileCard
|
||||
key={checklist.id}
|
||||
id={checklist.id}
|
||||
isSelected={handlers.isSelected}
|
||||
onToggleSelection={handlers.onToggle}
|
||||
onClick={() => handleRowClick(checklist)}
|
||||
headerBadges={
|
||||
<>
|
||||
<Badge variant="outline" className="text-xs">
|
||||
#{globalIndex}
|
||||
</Badge>
|
||||
<Badge variant="outline" className="text-xs font-mono">
|
||||
{checklist.checklistCode}
|
||||
</Badge>
|
||||
</>
|
||||
}
|
||||
title={checklist.checklistName}
|
||||
statusBadge={
|
||||
<Badge
|
||||
variant={checklist.status === '사용' ? 'default' : 'secondary'}
|
||||
className="cursor-pointer"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleToggleStatus(checklist.id);
|
||||
}}
|
||||
>
|
||||
{checklist.status}
|
||||
</Badge>
|
||||
}
|
||||
infoGrid={
|
||||
<div className="grid grid-cols-2 gap-x-4 gap-y-3">
|
||||
<InfoField label="항목" value={`${checklist.itemCount}개`} />
|
||||
<InfoField label="문서" value={`${checklist.documentCount}개`} />
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
),
|
||||
}),
|
||||
[
|
||||
handleCreate,
|
||||
handleRowClick,
|
||||
handleToggleStatus,
|
||||
handleBulkDelete,
|
||||
startDate,
|
||||
endDate,
|
||||
searchQuery,
|
||||
isOrderChanged,
|
||||
handleSaveOrder,
|
||||
handleDragStart,
|
||||
handleDragOver,
|
||||
handleDragLeave,
|
||||
handleDragEnd,
|
||||
handleDrop,
|
||||
]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<UniversalListPage
|
||||
config={config}
|
||||
initialData={allChecklists}
|
||||
onSearchChange={setSearchQuery}
|
||||
/>
|
||||
<DeleteConfirmDialog
|
||||
open={deleteDialogOpen}
|
||||
onOpenChange={setDeleteDialogOpen}
|
||||
description="선택한 점검표를 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다."
|
||||
loading={isLoading}
|
||||
onConfirm={handleDeleteConfirm}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
223
src/components/checklist-management/ItemDetail.tsx
Normal file
223
src/components/checklist-management/ItemDetail.tsx
Normal file
@@ -0,0 +1,223 @@
|
||||
'use client';
|
||||
|
||||
/**
|
||||
* 항목 상세 뷰 컴포넌트
|
||||
*
|
||||
* 기획서 스크린샷 3 기준:
|
||||
* - 기본 정보: 항목 번호, 항목명, 소개, 상태
|
||||
* - 문서 정보: 순서, 문서 번호, 문서, 개정, 시행일
|
||||
* - 하단: 삭제, 수정 버튼
|
||||
*/
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { ArrowLeft, Edit, GripVertical, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { PageLayout } from '@/components/organisms/PageLayout';
|
||||
import { PageHeader } from '@/components/organisms/PageHeader';
|
||||
import { useMenuStore } from '@/store/menuStore';
|
||||
import { usePermission } from '@/hooks/usePermission';
|
||||
import { toast } from 'sonner';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { deleteChecklistItem } from './actions';
|
||||
import type { ChecklistItem } from '@/types/checklist';
|
||||
|
||||
interface ItemDetailProps {
|
||||
item: ChecklistItem;
|
||||
checklistId: string;
|
||||
}
|
||||
|
||||
export function ItemDetail({ item, checklistId }: ItemDetailProps) {
|
||||
const router = useRouter();
|
||||
const sidebarCollapsed = useMenuStore((state) => state.sidebarCollapsed);
|
||||
const { canUpdate, canDelete } = usePermission();
|
||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
|
||||
const handleEdit = () => {
|
||||
router.push(
|
||||
`/ko/master-data/checklist-management/${checklistId}/items/${item.id}?mode=edit`
|
||||
);
|
||||
};
|
||||
|
||||
const handleBack = () => {
|
||||
router.push(`/ko/master-data/checklist-management/${checklistId}`);
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
setIsDeleting(true);
|
||||
try {
|
||||
const result = await deleteChecklistItem(checklistId, item.id);
|
||||
if (result.success) {
|
||||
toast.success('항목이 삭제되었습니다.');
|
||||
router.push(`/ko/master-data/checklist-management/${checklistId}`);
|
||||
} else {
|
||||
toast.error(result.error || '삭제에 실패했습니다.');
|
||||
}
|
||||
} catch {
|
||||
toast.error('삭제 중 오류가 발생했습니다.');
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
setShowDeleteDialog(false);
|
||||
}
|
||||
};
|
||||
|
||||
const documents = item.documents || [];
|
||||
|
||||
return (
|
||||
<PageLayout>
|
||||
<PageHeader title="항목 상세" />
|
||||
|
||||
<div className="space-y-6 pb-24">
|
||||
{/* 기본 정보 */}
|
||||
<Card>
|
||||
<CardHeader className="bg-muted/50">
|
||||
<CardTitle className="text-base">기본 정보</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-6">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||
<div className="space-y-1">
|
||||
<div className="text-sm text-muted-foreground">항목 번호</div>
|
||||
<div className="font-medium font-mono">{item.itemCode}</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="text-sm text-muted-foreground">항목명</div>
|
||||
<div className="font-medium">{item.itemName}</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="text-sm text-muted-foreground">소개</div>
|
||||
<div className="font-medium">{item.description || '-'}</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="text-sm text-muted-foreground">상태</div>
|
||||
<Badge variant={item.status === '사용' ? 'default' : 'secondary'}>
|
||||
{item.status}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 문서 정보 */}
|
||||
<Card>
|
||||
<CardHeader className="bg-muted/50">
|
||||
<CardTitle className="text-base">문서 정보</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0">
|
||||
{documents.length === 0 ? (
|
||||
<div className="p-8 text-center text-muted-foreground">
|
||||
등록된 문서가 없습니다.
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full">
|
||||
<thead>
|
||||
<tr className="border-b bg-muted/30">
|
||||
<th className="w-10 px-3 py-3 text-center text-xs font-medium text-muted-foreground" />
|
||||
<th className="w-14 px-3 py-3 text-center text-xs font-medium text-muted-foreground">
|
||||
순서
|
||||
</th>
|
||||
<th className="px-3 py-3 text-left text-xs font-medium text-muted-foreground">
|
||||
문서 번호
|
||||
</th>
|
||||
<th className="px-3 py-3 text-left text-xs font-medium text-muted-foreground">
|
||||
문서
|
||||
</th>
|
||||
<th className="px-3 py-3 text-left text-xs font-medium text-muted-foreground">
|
||||
개정
|
||||
</th>
|
||||
<th className="px-3 py-3 text-left text-xs font-medium text-muted-foreground">
|
||||
시행일
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{documents.map((doc) => (
|
||||
<tr key={doc.id} className="border-b hover:bg-muted/50">
|
||||
<td className="w-10 px-3 py-3 text-center">
|
||||
<GripVertical className="h-4 w-4 text-muted-foreground mx-auto" />
|
||||
</td>
|
||||
<td className="w-14 px-3 py-3 text-center text-sm">
|
||||
{doc.order}
|
||||
</td>
|
||||
<td className="px-3 py-3 text-sm font-mono">
|
||||
{doc.documentCode}
|
||||
</td>
|
||||
<td className="px-3 py-3 text-sm text-primary underline cursor-pointer">
|
||||
{doc.documentName}
|
||||
</td>
|
||||
<td className="px-3 py-3 text-sm">{doc.revision}</td>
|
||||
<td className="px-3 py-3 text-sm">{doc.effectiveDate}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* 하단 액션 버튼 (sticky) */}
|
||||
<div
|
||||
className={`fixed bottom-4 left-4 right-4 px-4 py-3 bg-background/95 backdrop-blur rounded-xl border shadow-lg z-50 transition-all duration-300 md:bottom-6 md:px-6 md:right-[48px] ${sidebarCollapsed ? 'md:left-[156px]' : 'md:left-[316px]'} flex items-center justify-between`}
|
||||
>
|
||||
<Button variant="outline" onClick={handleBack} size="sm" className="md:size-default">
|
||||
<ArrowLeft className="h-4 w-4 md:mr-2" />
|
||||
<span className="hidden md:inline">점검표로 돌아가기</span>
|
||||
</Button>
|
||||
<div className="flex items-center gap-2">
|
||||
{canDelete && (
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() => setShowDeleteDialog(true)}
|
||||
size="sm"
|
||||
className="md:size-default"
|
||||
>
|
||||
<Trash2 className="h-4 w-4 md:mr-2" />
|
||||
<span className="hidden md:inline">삭제</span>
|
||||
</Button>
|
||||
)}
|
||||
{canUpdate && (
|
||||
<Button onClick={handleEdit} size="sm" className="md:size-default">
|
||||
<Edit className="h-4 w-4 md:mr-2" />
|
||||
<span className="hidden md:inline">수정</span>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>항목 삭제</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
'{item.itemName}' 항목을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isDeleting}>취소</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleDelete}
|
||||
disabled={isDeleting}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{isDeleting ? '삭제 중...' : '삭제'}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
110
src/components/checklist-management/ItemDetailClient.tsx
Normal file
110
src/components/checklist-management/ItemDetailClient.tsx
Normal file
@@ -0,0 +1,110 @@
|
||||
'use client';
|
||||
|
||||
/**
|
||||
* 항목 상세 클라이언트 컴포넌트
|
||||
*
|
||||
* 라우팅:
|
||||
* - /[id]/items/[itemId] → 상세 보기
|
||||
* - /[id]/items/[itemId]?mode=edit → 수정
|
||||
* - /[id]/items/new → 등록
|
||||
*/
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { ItemDetail } from './ItemDetail';
|
||||
import { ItemForm } from './ItemForm';
|
||||
import { getChecklistItemById } from './actions';
|
||||
import type { ChecklistItem } from '@/types/checklist';
|
||||
import { DetailPageSkeleton } from '@/components/ui/skeleton';
|
||||
import { ErrorCard } from '@/components/ui/error-card';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
type DetailMode = 'view' | 'edit' | 'create';
|
||||
|
||||
interface ItemDetailClientProps {
|
||||
checklistId: string;
|
||||
itemId: string;
|
||||
}
|
||||
|
||||
export function ItemDetailClient({ checklistId, itemId }: ItemDetailClientProps) {
|
||||
const searchParams = useSearchParams();
|
||||
const modeFromQuery = searchParams.get('mode') as DetailMode | null;
|
||||
const isNewMode = itemId === 'new';
|
||||
|
||||
const [mode] = useState<DetailMode>(() => {
|
||||
if (isNewMode) return 'create';
|
||||
if (modeFromQuery === 'edit') return 'edit';
|
||||
return 'view';
|
||||
});
|
||||
|
||||
const [itemData, setItemData] = useState<ChecklistItem | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(!isNewMode);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (isNewMode) {
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const loadData = async () => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await getChecklistItemById(checklistId, itemId);
|
||||
if (result.success && result.data) {
|
||||
setItemData(result.data);
|
||||
} else {
|
||||
setError(result.error || '항목 정보를 찾을 수 없습니다.');
|
||||
toast.error('항목을 불러오는데 실패했습니다.');
|
||||
}
|
||||
} catch {
|
||||
setError('항목 정보를 불러오는 중 오류가 발생했습니다.');
|
||||
toast.error('항목을 불러오는데 실패했습니다.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadData();
|
||||
}, [checklistId, itemId, isNewMode]);
|
||||
|
||||
if (isLoading) {
|
||||
return <DetailPageSkeleton sections={1} fieldsPerSection={4} />;
|
||||
}
|
||||
|
||||
if (error && !isNewMode) {
|
||||
return (
|
||||
<ErrorCard
|
||||
type="network"
|
||||
title="항목 정보를 불러올 수 없습니다"
|
||||
description={error}
|
||||
tips={['해당 항목이 존재하는지 확인해주세요']}
|
||||
homeButtonLabel="점검표로 돌아가기"
|
||||
homeButtonHref={`/ko/master-data/checklist-management/${checklistId}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (mode === 'create') {
|
||||
return <ItemForm mode="create" checklistId={checklistId} />;
|
||||
}
|
||||
|
||||
if (mode === 'edit' && itemData) {
|
||||
return <ItemForm mode="edit" checklistId={checklistId} initialData={itemData} />;
|
||||
}
|
||||
|
||||
if (mode === 'view' && itemData) {
|
||||
return <ItemDetail item={itemData} checklistId={checklistId} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<ErrorCard
|
||||
type="not-found"
|
||||
title="항목을 찾을 수 없습니다"
|
||||
description="요청하신 항목 정보가 존재하지 않습니다."
|
||||
homeButtonLabel="점검표로 돌아가기"
|
||||
homeButtonHref={`/ko/master-data/checklist-management/${checklistId}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
350
src/components/checklist-management/ItemForm.tsx
Normal file
350
src/components/checklist-management/ItemForm.tsx
Normal file
@@ -0,0 +1,350 @@
|
||||
'use client';
|
||||
|
||||
/**
|
||||
* 항목 등록/수정 폼 컴포넌트
|
||||
*
|
||||
* 기획서 스크린샷 3 기준:
|
||||
* - 기본 정보: 항목 번호(자동), 항목명, 소개, 상태
|
||||
* - 문서 정보: 순서, 문서 번호, 문서, 개정, 시행일 + 행 추가/삭제
|
||||
*/
|
||||
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { Plus, Trash2, GripVertical } from 'lucide-react';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
|
||||
import { toast } from 'sonner';
|
||||
import type { ChecklistItem, ChecklistDocumentFormData } from '@/types/checklist';
|
||||
import { createChecklistItem, updateChecklistItem } from './actions';
|
||||
import type { DetailConfig } from '@/components/templates/IntegratedDetailTemplate/types';
|
||||
|
||||
const itemCreateConfig: DetailConfig = {
|
||||
title: '항목',
|
||||
description: '새로운 항목을 등록합니다',
|
||||
basePath: '',
|
||||
fields: [],
|
||||
actions: {
|
||||
showBack: true,
|
||||
showEdit: false,
|
||||
showDelete: false,
|
||||
showSave: true,
|
||||
submitLabel: '등록',
|
||||
},
|
||||
};
|
||||
|
||||
const itemEditConfig: DetailConfig = {
|
||||
...itemCreateConfig,
|
||||
description: '항목 정보를 수정합니다',
|
||||
actions: {
|
||||
...itemCreateConfig.actions,
|
||||
submitLabel: '저장',
|
||||
},
|
||||
};
|
||||
|
||||
interface ItemFormProps {
|
||||
mode: 'create' | 'edit';
|
||||
checklistId: string;
|
||||
initialData?: ChecklistItem;
|
||||
}
|
||||
|
||||
export function ItemForm({ mode, checklistId, initialData }: ItemFormProps) {
|
||||
const router = useRouter();
|
||||
const isEdit = mode === 'edit';
|
||||
|
||||
const [itemName, setItemName] = useState(initialData?.itemName || '');
|
||||
const [description, setDescription] = useState(initialData?.description || '');
|
||||
const [status, setStatus] = useState<string>(initialData?.status || '사용');
|
||||
|
||||
// 문서 목록 상태
|
||||
const [documents, setDocuments] = useState<ChecklistDocumentFormData[]>(() => {
|
||||
if (initialData?.documents && initialData.documents.length > 0) {
|
||||
return initialData.documents.map((doc) => ({
|
||||
id: doc.id,
|
||||
documentCode: doc.documentCode,
|
||||
documentName: doc.documentName,
|
||||
revision: doc.revision,
|
||||
effectiveDate: doc.effectiveDate,
|
||||
order: doc.order,
|
||||
}));
|
||||
}
|
||||
return [];
|
||||
});
|
||||
|
||||
const handleAddDocument = () => {
|
||||
setDocuments((prev) => [
|
||||
...prev,
|
||||
{
|
||||
documentCode: '',
|
||||
documentName: '',
|
||||
revision: '',
|
||||
effectiveDate: '',
|
||||
order: prev.length + 1,
|
||||
},
|
||||
]);
|
||||
};
|
||||
|
||||
const handleRemoveDocument = (index: number) => {
|
||||
setDocuments((prev) => {
|
||||
const updated = prev.filter((_, i) => i !== index);
|
||||
return updated.map((doc, i) => ({ ...doc, order: i + 1 }));
|
||||
});
|
||||
};
|
||||
|
||||
const handleDocumentChange = (
|
||||
index: number,
|
||||
field: keyof ChecklistDocumentFormData,
|
||||
value: string | number
|
||||
) => {
|
||||
setDocuments((prev) =>
|
||||
prev.map((doc, i) => (i === index ? { ...doc, [field]: value } : doc))
|
||||
);
|
||||
};
|
||||
|
||||
const handleSubmit = async (): Promise<{ success: boolean; error?: string }> => {
|
||||
if (!itemName.trim()) {
|
||||
toast.error('항목명을 입력해주세요.');
|
||||
return { success: false, error: '항목명을 입력해주세요.' };
|
||||
}
|
||||
|
||||
const formData = {
|
||||
itemName: itemName.trim(),
|
||||
description: description.trim(),
|
||||
status: status as '사용' | '미사용',
|
||||
documents,
|
||||
};
|
||||
|
||||
try {
|
||||
if (isEdit && initialData?.id) {
|
||||
const result = await updateChecklistItem(checklistId, initialData.id, formData);
|
||||
if (result.success) {
|
||||
toast.success('항목이 수정되었습니다.');
|
||||
router.push(
|
||||
`/ko/master-data/checklist-management/${checklistId}/items/${initialData.id}`
|
||||
);
|
||||
return { success: true };
|
||||
} else {
|
||||
toast.error(result.error || '수정에 실패했습니다.');
|
||||
return { success: false, error: result.error };
|
||||
}
|
||||
} else {
|
||||
const result = await createChecklistItem(checklistId, formData);
|
||||
if (result.success && result.data) {
|
||||
toast.success('항목이 등록되었습니다.');
|
||||
router.push(`/ko/master-data/checklist-management/${checklistId}`);
|
||||
return { success: true };
|
||||
} else {
|
||||
toast.error(result.error || '등록에 실패했습니다.');
|
||||
return { success: false, error: result.error };
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
toast.error('처리 중 오류가 발생했습니다.');
|
||||
return { success: false, error: '처리 중 오류가 발생했습니다.' };
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
if (isEdit && initialData?.id) {
|
||||
router.push(
|
||||
`/ko/master-data/checklist-management/${checklistId}/items/${initialData.id}`
|
||||
);
|
||||
} else {
|
||||
router.push(`/ko/master-data/checklist-management/${checklistId}`);
|
||||
}
|
||||
};
|
||||
|
||||
const renderFormContent = useCallback(
|
||||
() => (
|
||||
<div className="space-y-6">
|
||||
{/* 기본 정보 */}
|
||||
<Card>
|
||||
<CardHeader className="bg-muted/50">
|
||||
<CardTitle className="text-base">기본 정보</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-6">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||
<div className="space-y-2">
|
||||
<Label>항목 번호</Label>
|
||||
<Input
|
||||
value={initialData?.itemCode || '자동생성'}
|
||||
disabled
|
||||
className="bg-muted"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="itemName">항목명 *</Label>
|
||||
<Input
|
||||
id="itemName"
|
||||
value={itemName}
|
||||
onChange={(e) => setItemName(e.target.value)}
|
||||
placeholder="항목명을 입력하세요"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="description">소개</Label>
|
||||
<Input
|
||||
id="description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="소개를 입력하세요"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>상태</Label>
|
||||
<Select value={status} onValueChange={setStatus}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="사용">사용</SelectItem>
|
||||
<SelectItem value="미사용">미사용</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 문서 정보 */}
|
||||
<Card>
|
||||
<CardHeader className="bg-muted/50">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-base">
|
||||
문서 정보
|
||||
<span className="text-sm font-normal text-muted-foreground ml-2">
|
||||
총 {documents.length}건
|
||||
</span>
|
||||
</CardTitle>
|
||||
<Button size="sm" type="button" onClick={handleAddDocument}>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
문서 추가
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0">
|
||||
{documents.length === 0 ? (
|
||||
<div className="p-8 text-center text-muted-foreground">
|
||||
등록된 문서가 없습니다. [문서 추가] 버튼으로 추가해주세요.
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full">
|
||||
<thead>
|
||||
<tr className="border-b bg-muted/30">
|
||||
<th className="w-10 px-3 py-3 text-center text-xs font-medium text-muted-foreground" />
|
||||
<th className="w-14 px-3 py-3 text-center text-xs font-medium text-muted-foreground">
|
||||
순서
|
||||
</th>
|
||||
<th className="px-3 py-3 text-left text-xs font-medium text-muted-foreground">
|
||||
문서 번호
|
||||
</th>
|
||||
<th className="px-3 py-3 text-left text-xs font-medium text-muted-foreground">
|
||||
문서
|
||||
</th>
|
||||
<th className="px-3 py-3 text-left text-xs font-medium text-muted-foreground">
|
||||
개정
|
||||
</th>
|
||||
<th className="px-3 py-3 text-left text-xs font-medium text-muted-foreground">
|
||||
시행일
|
||||
</th>
|
||||
<th className="w-14 px-3 py-3 text-center text-xs font-medium text-muted-foreground">
|
||||
삭제
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{documents.map((doc, index) => (
|
||||
<tr key={`doc-${index}`} className="border-b">
|
||||
<td className="w-10 px-3 py-2 text-center">
|
||||
<GripVertical className="h-4 w-4 text-muted-foreground mx-auto" />
|
||||
</td>
|
||||
<td className="w-14 px-3 py-2 text-center text-sm">
|
||||
{doc.order}
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
<Input
|
||||
value={doc.documentCode}
|
||||
onChange={(e) =>
|
||||
handleDocumentChange(index, 'documentCode', e.target.value)
|
||||
}
|
||||
placeholder="문서 번호"
|
||||
className="h-8"
|
||||
/>
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
<Input
|
||||
value={doc.documentName}
|
||||
onChange={(e) =>
|
||||
handleDocumentChange(index, 'documentName', e.target.value)
|
||||
}
|
||||
placeholder="문서명"
|
||||
className="h-8"
|
||||
/>
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
<Input
|
||||
value={doc.revision}
|
||||
onChange={(e) =>
|
||||
handleDocumentChange(index, 'revision', e.target.value)
|
||||
}
|
||||
placeholder="REV"
|
||||
className="h-8"
|
||||
/>
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
<Input
|
||||
type="date"
|
||||
value={doc.effectiveDate}
|
||||
onChange={(e) =>
|
||||
handleDocumentChange(index, 'effectiveDate', e.target.value)
|
||||
}
|
||||
className="h-8"
|
||||
/>
|
||||
</td>
|
||||
<td className="w-14 px-3 py-2 text-center">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 text-destructive hover:text-destructive"
|
||||
onClick={() => handleRemoveDocument(index)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
),
|
||||
[itemName, description, status, documents, initialData?.itemCode]
|
||||
);
|
||||
|
||||
const config = isEdit ? itemEditConfig : itemCreateConfig;
|
||||
|
||||
return (
|
||||
<IntegratedDetailTemplate
|
||||
config={config}
|
||||
mode={isEdit ? 'edit' : 'create'}
|
||||
isLoading={false}
|
||||
onCancel={handleCancel}
|
||||
onSubmit={handleSubmit}
|
||||
renderForm={renderFormContent}
|
||||
/>
|
||||
);
|
||||
}
|
||||
342
src/components/checklist-management/actions.ts
Normal file
342
src/components/checklist-management/actions.ts
Normal file
@@ -0,0 +1,342 @@
|
||||
'use server';
|
||||
|
||||
/**
|
||||
* 점검표 관리 Server Actions
|
||||
*
|
||||
* 현재: Mock 데이터 기반
|
||||
* 추후: executeServerAction으로 백엔드 API 연동 전환
|
||||
*/
|
||||
|
||||
import type {
|
||||
Checklist,
|
||||
ChecklistFormData,
|
||||
ChecklistItem,
|
||||
ChecklistItemFormData,
|
||||
ChecklistDocument,
|
||||
} from '@/types/checklist';
|
||||
|
||||
// ============================================================================
|
||||
// Mock 데이터
|
||||
// ============================================================================
|
||||
|
||||
const MOCK_DOCUMENTS: ChecklistDocument[] = [
|
||||
{
|
||||
id: 'doc-1',
|
||||
itemId: 'item-1',
|
||||
documentCode: 'QM-std-1-1-1',
|
||||
documentName: '문서명.pdf',
|
||||
revision: 'REV12',
|
||||
effectiveDate: '2026-01-05',
|
||||
order: 1,
|
||||
},
|
||||
{
|
||||
id: 'doc-2',
|
||||
itemId: 'item-1',
|
||||
documentCode: 'QM-std-1-1-1',
|
||||
documentName: '문서명.pdf',
|
||||
revision: 'REV12',
|
||||
effectiveDate: '2026-01-06',
|
||||
order: 2,
|
||||
},
|
||||
];
|
||||
|
||||
const MOCK_ITEMS: ChecklistItem[] = [
|
||||
{
|
||||
id: 'item-1',
|
||||
checklistId: 'cl-1',
|
||||
itemCode: '123123',
|
||||
itemName: '1. 수입검사 기준 확인',
|
||||
description: '소개 문구',
|
||||
documentCount: 3,
|
||||
status: '사용',
|
||||
order: 1,
|
||||
documents: MOCK_DOCUMENTS,
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
updatedAt: '2026-01-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'item-2',
|
||||
checklistId: 'cl-1',
|
||||
itemCode: '123123',
|
||||
itemName: '항목명',
|
||||
description: '',
|
||||
documentCount: 3,
|
||||
status: '사용',
|
||||
order: 2,
|
||||
documents: [],
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
updatedAt: '2026-01-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'item-3',
|
||||
checklistId: 'cl-1',
|
||||
itemCode: '123123',
|
||||
itemName: '항목명',
|
||||
description: '',
|
||||
documentCount: 3,
|
||||
status: '사용',
|
||||
order: 3,
|
||||
documents: [],
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
updatedAt: '2026-01-01T00:00:00Z',
|
||||
},
|
||||
];
|
||||
|
||||
const MOCK_CHECKLISTS: Checklist[] = [
|
||||
{
|
||||
id: 'cl-1',
|
||||
checklistCode: '변호명',
|
||||
checklistName: '점검표명',
|
||||
itemCount: 3,
|
||||
documentCount: 6,
|
||||
status: '사용',
|
||||
order: 1,
|
||||
createdAt: '2025-09-01T00:00:00Z',
|
||||
updatedAt: '2025-09-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'cl-2',
|
||||
checklistCode: '변호명',
|
||||
checklistName: '점검표명',
|
||||
itemCount: 3,
|
||||
documentCount: 6,
|
||||
status: '미사용',
|
||||
order: 2,
|
||||
createdAt: '2025-09-01T00:00:00Z',
|
||||
updatedAt: '2025-09-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'cl-3',
|
||||
checklistCode: '변호명',
|
||||
checklistName: '점검표명',
|
||||
itemCount: 3,
|
||||
documentCount: 6,
|
||||
status: '사용',
|
||||
order: 3,
|
||||
createdAt: '2025-09-01T00:00:00Z',
|
||||
updatedAt: '2025-09-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'cl-4',
|
||||
checklistCode: '변호명',
|
||||
checklistName: '점검표명',
|
||||
itemCount: 3,
|
||||
documentCount: 6,
|
||||
status: '미사용',
|
||||
order: 4,
|
||||
createdAt: '2025-09-01T00:00:00Z',
|
||||
updatedAt: '2025-09-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'cl-5',
|
||||
checklistCode: '변호명',
|
||||
checklistName: '점검표명',
|
||||
itemCount: 3,
|
||||
documentCount: 6,
|
||||
status: '사용',
|
||||
order: 5,
|
||||
createdAt: '2025-09-01T00:00:00Z',
|
||||
updatedAt: '2025-09-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'cl-6',
|
||||
checklistCode: '변호명',
|
||||
checklistName: '점검표명',
|
||||
itemCount: 3,
|
||||
documentCount: 6,
|
||||
status: '미사용',
|
||||
order: 6,
|
||||
createdAt: '2025-09-01T00:00:00Z',
|
||||
updatedAt: '2025-09-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'cl-7',
|
||||
checklistCode: '변호명',
|
||||
checklistName: '점검표명',
|
||||
itemCount: 3,
|
||||
documentCount: 6,
|
||||
status: '사용',
|
||||
order: 7,
|
||||
createdAt: '2025-09-01T00:00:00Z',
|
||||
updatedAt: '2025-09-01T00:00:00Z',
|
||||
},
|
||||
];
|
||||
|
||||
// ============================================================================
|
||||
// 점검표 CRUD
|
||||
// ============================================================================
|
||||
|
||||
export async function getChecklistList(): Promise<{
|
||||
success: boolean;
|
||||
data?: { items: Checklist[] };
|
||||
error?: string;
|
||||
}> {
|
||||
return { success: true, data: { items: [...MOCK_CHECKLISTS] } };
|
||||
}
|
||||
|
||||
export async function getChecklistById(id: string): Promise<{
|
||||
success: boolean;
|
||||
data?: Checklist;
|
||||
error?: string;
|
||||
}> {
|
||||
const checklist = MOCK_CHECKLISTS.find((c) => c.id === id);
|
||||
if (!checklist) return { success: false, error: '점검표를 찾을 수 없습니다.' };
|
||||
return { success: true, data: { ...checklist } };
|
||||
}
|
||||
|
||||
export async function createChecklist(data: ChecklistFormData): Promise<{
|
||||
success: boolean;
|
||||
data?: Checklist;
|
||||
error?: string;
|
||||
}> {
|
||||
const newChecklist: Checklist = {
|
||||
id: `cl-${Date.now()}`,
|
||||
checklistCode: `CL-${String(MOCK_CHECKLISTS.length + 1).padStart(3, '0')}`,
|
||||
checklistName: data.checklistName,
|
||||
itemCount: 0,
|
||||
documentCount: 0,
|
||||
status: data.status,
|
||||
order: MOCK_CHECKLISTS.length + 1,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
return { success: true, data: newChecklist };
|
||||
}
|
||||
|
||||
export async function updateChecklist(
|
||||
id: string,
|
||||
data: ChecklistFormData
|
||||
): Promise<{ success: boolean; data?: Checklist; error?: string }> {
|
||||
const checklist = MOCK_CHECKLISTS.find((c) => c.id === id);
|
||||
if (!checklist) return { success: false, error: '점검표를 찾을 수 없습니다.' };
|
||||
const updated = {
|
||||
...checklist,
|
||||
checklistName: data.checklistName,
|
||||
status: data.status,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
return { success: true, data: updated };
|
||||
}
|
||||
|
||||
export async function deleteChecklist(id: string): Promise<{
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}> {
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function deleteChecklists(ids: string[]): Promise<{
|
||||
success: boolean;
|
||||
deletedCount?: number;
|
||||
error?: string;
|
||||
}> {
|
||||
return { success: true, deletedCount: ids.length };
|
||||
}
|
||||
|
||||
export async function toggleChecklistStatus(id: string): Promise<{
|
||||
success: boolean;
|
||||
data?: Checklist;
|
||||
error?: string;
|
||||
}> {
|
||||
const checklist = MOCK_CHECKLISTS.find((c) => c.id === id);
|
||||
if (!checklist) return { success: false, error: '점검표를 찾을 수 없습니다.' };
|
||||
const toggled = {
|
||||
...checklist,
|
||||
status: checklist.status === '사용' ? '미사용' as const : '사용' as const,
|
||||
};
|
||||
return { success: true, data: toggled };
|
||||
}
|
||||
|
||||
export async function reorderChecklists(
|
||||
items: { id: string; order: number }[]
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function getChecklistStats(): Promise<{
|
||||
success: boolean;
|
||||
data?: { total: number; active: number; inactive: number };
|
||||
error?: string;
|
||||
}> {
|
||||
const active = MOCK_CHECKLISTS.filter((c) => c.status === '사용').length;
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
total: MOCK_CHECKLISTS.length,
|
||||
active,
|
||||
inactive: MOCK_CHECKLISTS.length - active,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 점검표 항목 CRUD
|
||||
// ============================================================================
|
||||
|
||||
export async function getChecklistItems(checklistId: string): Promise<{
|
||||
success: boolean;
|
||||
data?: ChecklistItem[];
|
||||
error?: string;
|
||||
}> {
|
||||
return { success: true, data: [...MOCK_ITEMS] };
|
||||
}
|
||||
|
||||
export async function getChecklistItemById(
|
||||
checklistId: string,
|
||||
itemId: string
|
||||
): Promise<{ success: boolean; data?: ChecklistItem; error?: string }> {
|
||||
const item = MOCK_ITEMS.find((i) => i.id === itemId);
|
||||
if (!item) return { success: false, error: '항목을 찾을 수 없습니다.' };
|
||||
return { success: true, data: { ...item, documents: [...MOCK_DOCUMENTS] } };
|
||||
}
|
||||
|
||||
export async function createChecklistItem(
|
||||
checklistId: string,
|
||||
data: ChecklistItemFormData
|
||||
): Promise<{ success: boolean; data?: ChecklistItem; error?: string }> {
|
||||
const newItem: ChecklistItem = {
|
||||
id: `item-${Date.now()}`,
|
||||
checklistId,
|
||||
itemCode: String(Date.now()).slice(-6),
|
||||
itemName: data.itemName,
|
||||
description: data.description,
|
||||
documentCount: data.documents.length,
|
||||
status: data.status,
|
||||
order: MOCK_ITEMS.length + 1,
|
||||
documents: [],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
return { success: true, data: newItem };
|
||||
}
|
||||
|
||||
export async function updateChecklistItem(
|
||||
checklistId: string,
|
||||
itemId: string,
|
||||
data: ChecklistItemFormData
|
||||
): Promise<{ success: boolean; data?: ChecklistItem; error?: string }> {
|
||||
const item = MOCK_ITEMS.find((i) => i.id === itemId);
|
||||
if (!item) return { success: false, error: '항목을 찾을 수 없습니다.' };
|
||||
const updated = {
|
||||
...item,
|
||||
itemName: data.itemName,
|
||||
description: data.description,
|
||||
status: data.status,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
return { success: true, data: updated };
|
||||
}
|
||||
|
||||
export async function deleteChecklistItem(
|
||||
checklistId: string,
|
||||
itemId: string
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function reorderChecklistItems(
|
||||
checklistId: string,
|
||||
items: { id: string; order: number }[]
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
return { success: true };
|
||||
}
|
||||
7
src/components/checklist-management/index.ts
Normal file
7
src/components/checklist-management/index.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export { default as ChecklistListClient } from './ChecklistListClient';
|
||||
export { ChecklistDetailClient } from './ChecklistDetailClient';
|
||||
export { ChecklistDetail } from './ChecklistDetail';
|
||||
export { ChecklistForm } from './ChecklistForm';
|
||||
export { ItemDetailClient } from './ItemDetailClient';
|
||||
export { ItemDetail } from './ItemDetail';
|
||||
export { ItemForm } from './ItemForm';
|
||||
Reference in New Issue
Block a user