Files
sam-react-prod/src/components/process-management/ProcessDetail.tsx

469 lines
20 KiB
TypeScript
Raw Normal View History

'use client';
/**
* ()
*
* 1 :
* - 정보: 공정번호, , , , ,
* - 정보: 품목 +
* - 테이블: 드래그& +
*/
import { useState, useEffect, useCallback, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { ArrowLeft, Edit, GripVertical, Plus, Trash2 } from 'lucide-react';
import { ReorderButtons } from '@/components/molecules';
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 '@/stores/menuStore';
import { usePermission } from '@/hooks/usePermission';
import { toast } from 'sonner';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import { useDeleteDialog } from '@/hooks/useDeleteDialog';
import { getProcessSteps, reorderProcessSteps, removeProcessItem, deleteProcess } from './actions';
import type { Process, ProcessStep } from '@/types/process';
interface ProcessDetailProps {
process: Process;
onProcessUpdate?: (process: Process) => void;
}
export function ProcessDetail({ process, onProcessUpdate }: ProcessDetailProps) {
const router = useRouter();
const sidebarCollapsed = useMenuStore((state) => state.sidebarCollapsed);
const { canUpdate } = usePermission();
// 삭제 다이얼로그
const deleteDialog = useDeleteDialog({
onDelete: deleteProcess,
onSuccess: () => router.push('/ko/master-data/process-management'),
entityName: '공정',
});
// 단계 목록 상태
const [steps, setSteps] = useState<ProcessStep[]>([]);
const [isStepsLoading, setIsStepsLoading] = useState(true);
// 드래그 상태
const [dragIndex, setDragIndex] = useState<number | null>(null);
const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);
const dragNodeRef = useRef<HTMLElement | null>(null);
// 개별 품목 목록 추출
const individualItems = process.classificationRules
.filter((r) => r.registrationType === 'individual')
.flatMap((r) => r.items || []);
const itemCount = individualItems.length;
// 단계 목록 로드
useEffect(() => {
const loadSteps = async () => {
setIsStepsLoading(true);
const result = await getProcessSteps(process.id);
if (result.success && result.data) {
setSteps(result.data);
}
setIsStepsLoading(false);
};
loadSteps();
}, [process.id]);
// 품목 삭제
const handleRemoveItem = async (itemId: string) => {
const remainingIds = individualItems
.filter((item) => item.id !== itemId)
.map((item) => parseInt(item.id, 10));
const result = await removeProcessItem(process.id, remainingIds);
if (result.success && result.data) {
toast.success('품목이 제거되었습니다.');
onProcessUpdate?.(result.data);
} else {
toast.error(result.error || '품목 제거에 실패했습니다.');
}
};
// 네비게이션
const handleEdit = () => {
router.push(`/ko/master-data/process-management/${process.id}?mode=edit`);
};
const handleList = () => {
router.push('/ko/master-data/process-management');
};
const handleAddStep = () => {
router.push(`/ko/master-data/process-management/${process.id}/steps/new`);
};
const handleStepClick = (stepId: string) => {
router.push(`/ko/master-data/process-management/${process.id}/steps/${stepId}`);
};
// ===== 드래그&드롭 (HTML5 네이티브) =====
const handleDragStart = useCallback((e: React.DragEvent<HTMLElement>, 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<HTMLElement>, 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<HTMLElement>, dropIndex: number) => {
e.preventDefault();
if (dragIndex === null || dragIndex === dropIndex) return;
setSteps((prev) => {
const updated = [...prev];
const [moved] = updated.splice(dragIndex, 1);
updated.splice(dropIndex, 0, moved);
const reordered = updated.map((step, i) => ({ ...step, order: i + 1 }));
// API 순서 변경 호출
reorderProcessSteps(
process.id,
reordered.map((s) => ({ id: s.id, order: s.order }))
);
return reordered;
});
handleDragEnd();
}, [dragIndex, handleDragEnd, process.id]);
// 화살표 버튼으로 순서 변경
const handleMoveStep = useCallback((fromIndex: number, toIndex: number) => {
setSteps((prev) => {
const updated = [...prev];
const [moved] = updated.splice(fromIndex, 1);
updated.splice(toIndex, 0, moved);
const reordered = updated.map((step, i) => ({ ...step, order: i + 1 }));
reorderProcessSteps(
process.id,
reordered.map((s) => ({ id: s.id, order: s.order }))
);
return reordered;
});
}, [process.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">
{/* Row 1: 공정번호 | 공정명 | 담당부서 | 담당자 */}
<div className="grid grid-cols-2 lg:grid-cols-4 gap-4 md:gap-6">
<div className="space-y-1">
<div className="text-sm text-muted-foreground"></div>
<div className="font-medium">{process.processCode}</div>
</div>
<div className="space-y-1">
<div className="text-sm text-muted-foreground"></div>
<div className="font-medium">{process.processName}</div>
</div>
<div className="space-y-1">
<div className="text-sm text-muted-foreground"></div>
<div className="font-medium">{process.department || '-'}</div>
</div>
<div className="space-y-1">
<div className="text-sm text-muted-foreground"></div>
<div className="font-medium">{process.manager || '-'}</div>
</div>
</div>
{/* Row 2: 구분 | 생산일자 | 상태 */}
<div className="grid grid-cols-2 lg:grid-cols-4 gap-4 md:gap-6 mt-4 md:mt-6">
<div className="space-y-1">
<div className="text-sm text-muted-foreground"></div>
<div className="font-medium">{process.processCategory || '없음'}</div>
</div>
<div className="space-y-1">
<div className="text-sm text-muted-foreground"></div>
<div className="font-medium">
{process.useProductionDate ? '사용' : '미사용'}
</div>
</div>
<div className="space-y-1">
<div className="text-sm text-muted-foreground"></div>
<Badge variant={process.status === '사용중' ? 'default' : 'secondary'}>
{process.status}
</Badge>
</div>
</div>
{/* Row 3: 중간검사여부 | 중간검사양식 | 작업일지여부 | 작업일지양식 */}
<div className="grid grid-cols-2 lg:grid-cols-4 gap-4 md:gap-6 mt-4 md:mt-6">
<div className="space-y-1">
<div className="text-sm text-muted-foreground"> </div>
<Badge variant={process.needsInspection ? 'default' : 'secondary'}>
{process.needsInspection ? '사용' : '미사용'}
</Badge>
</div>
{process.needsInspection && (
<div className="space-y-1">
<div className="text-sm text-muted-foreground"> </div>
<div className="font-medium">{process.documentTemplateName || '-'}</div>
</div>
)}
<div className="space-y-1">
<div className="text-sm text-muted-foreground"> </div>
<Badge variant={process.needsWorkLog ? 'default' : 'secondary'}>
{process.needsWorkLog ? '사용' : '미사용'}
</Badge>
</div>
{process.needsWorkLog && (
<div className="space-y-1">
<div className="text-sm text-muted-foreground"> </div>
<div className="font-medium">{process.workLogTemplateName || '-'}</div>
</div>
)}
</div>
</CardContent>
</Card>
{/* 품목 설정 정보 */}
<Card>
<CardHeader className="bg-muted/50 py-3">
<div className="flex items-center gap-2 flex-wrap">
<CardTitle className="text-base shrink-0">
</CardTitle>
<Badge variant="outline" className="text-xs">
{itemCount}
</Badge>
<Button variant="outline" size="sm" onClick={handleEdit} className="shrink-0">
</Button>
</div>
<p className="text-sm text-muted-foreground mt-1">
</p>
</CardHeader>
{individualItems.length > 0 && (
<CardContent className="pt-4 max-h-[240px] md:max-h-none overflow-y-auto">
<div className="flex flex-wrap gap-1.5">
{individualItems.map((item) => (
<div
key={item.id}
className="inline-flex items-center gap-1.5 rounded-full border bg-muted/30 pl-3 pr-1.5 py-1 text-xs"
>
<span className="font-mono">{item.code}</span>
<button
type="button"
onClick={() => handleRemoveItem(item.id)}
className="shrink-0 rounded-full p-0.5 text-muted-foreground/50 hover:text-destructive transition-colors"
>
<Trash2 className="h-3 w-3" />
</button>
</div>
))}
</div>
</CardContent>
)}
</Card>
{/* 단계 테이블 */}
<Card>
<CardHeader className="bg-muted/50">
<div className="flex items-center justify-between">
<CardTitle className="text-base">
{!isStepsLoading && (
<span className="text-sm font-normal text-muted-foreground ml-2">
{steps.length}
</span>
)}
</CardTitle>
<Button size="sm" onClick={handleAddStep}>
<Plus className="h-4 w-4 mr-1" />
</Button>
</div>
</CardHeader>
<CardContent className="p-0">
{isStepsLoading ? (
<div className="p-8 text-center text-muted-foreground">
...
</div>
) : steps.length === 0 ? (
<div className="p-8 text-center text-muted-foreground">
. [ ] .
</div>
) : (
<>
{/* 모바일: 카드 리스트 */}
<div className="md:hidden divide-y">
{steps.map((step, index) => (
<div
key={step.id}
draggable
onDragStart={(e) => handleDragStart(e, index)}
onDragOver={(e) => handleDragOver(e, index)}
onDragEnd={handleDragEnd}
onDrop={(e) => handleDrop(e, index)}
onClick={() => handleStepClick(step.id)}
className={`flex items-center gap-2 px-3 py-2.5 cursor-pointer hover:bg-muted/50 ${
dragOverIndex === index && dragIndex !== index
? 'border-t-2 border-t-primary'
: ''
}`}
>
<ReorderButtons
onMoveUp={() => handleMoveStep(index, index - 1)}
onMoveDown={() => handleMoveStep(index, index + 1)}
isFirst={index === 0}
isLast={index === steps.length - 1}
size="xs"
/>
<span className="text-xs text-muted-foreground w-5 shrink-0">{index + 1}</span>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1.5">
<span className="text-xs font-mono text-muted-foreground">{step.stepCode}</span>
<span className="text-sm font-medium truncate">{step.stepName}</span>
</div>
</div>
<div className="flex items-center gap-1 shrink-0">
<Badge variant={step.isRequired ? 'default' : 'outline'} className="text-[10px] px-1.5 py-0"></Badge>
<Badge variant={step.needsApproval ? 'default' : 'outline'} className="text-[10px] px-1.5 py-0"></Badge>
<Badge variant={step.needsInspection ? 'default' : 'outline'} className="text-[10px] px-1.5 py-0"></Badge>
</div>
</div>
))}
</div>
{/* 데스크탑: 테이블 */}
<div className="hidden md:block overflow-x-auto">
<table className="w-full">
<thead>
<tr className="border-b bg-muted/30">
<th className="w-16 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="px-3 py-3 text-left text-xs font-medium text-muted-foreground"></th>
<th className="w-20 px-3 py-3 text-center text-xs font-medium text-muted-foreground"></th>
<th className="w-20 px-3 py-3 text-center text-xs font-medium text-muted-foreground"></th>
<th className="w-20 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>
{steps.map((step, index) => (
<tr
key={step.id}
draggable
onDragStart={(e) => handleDragStart(e, index)}
onDragOver={(e) => handleDragOver(e, index)}
onDragEnd={handleDragEnd}
onDrop={(e) => handleDrop(e, index)}
onClick={() => handleStepClick(step.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-16 px-3 py-3 text-center" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center justify-center gap-0.5">
<GripVertical className="h-4 w-4 text-muted-foreground cursor-grab active:cursor-grabbing" />
<ReorderButtons
onMoveUp={() => handleMoveStep(index, index - 1)}
onMoveDown={() => handleMoveStep(index, index + 1)}
isFirst={index === 0}
isLast={index === steps.length - 1}
size="xs"
/>
</div>
</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">{step.stepCode}</td>
<td className="px-3 py-3 text-sm font-medium">{step.stepName}</td>
<td className="w-20 px-3 py-3 text-center">
<Badge variant={step.isRequired ? 'default' : 'outline'} className="text-xs">{step.isRequired ? 'Y' : 'N'}</Badge>
</td>
<td className="w-20 px-3 py-3 text-center">
<Badge variant={step.needsApproval ? 'default' : 'outline'} className="text-xs">{step.needsApproval ? 'Y' : 'N'}</Badge>
</td>
<td className="w-20 px-3 py-3 text-center">
<Badge variant={step.needsInspection ? 'default' : 'outline'} className="text-xs">{step.needsInspection ? 'Y' : 'N'}</Badge>
</td>
<td className="w-16 px-3 py-3 text-center">
<Badge variant={step.isActive ? 'default' : 'secondary'} className="text-xs">{step.isActive ? 'Y' : 'N'}</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="outline"
onClick={() => deleteDialog.single.open(process.id)}
size="sm"
className="md:size-default text-destructive hover:text-destructive"
>
<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={deleteDialog.single.isOpen}
onOpenChange={deleteDialog.single.onOpenChange}
onConfirm={deleteDialog.single.confirm}
loading={deleteDialog.isPending}
description="이 공정을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다."
/>
</PageLayout>
);
}