Files
sam-react-prod/src/components/production/WorkerScreen/ProcessDetailSection.tsx
byeongcheolryu e56b7d53a4 fix(WEB): 토큰 만료 시 무한 로딩 대신 로그인 리다이렉트 처리
- 52개 이상의 컴포넌트에 isNextRedirectError 처리 추가
- Server Action의 redirect() 에러가 catch 블록에서 삼켜지는 문제 해결
- access_token + refresh_token 모두 만료 시 정상적으로 로그인 페이지로 리다이렉트

수정된 영역:
- accounting: 10개 컴포넌트
- production: 12개 컴포넌트
- hr: 5개 컴포넌트
- settings: 8개 컴포넌트
- approval: 5개 컴포넌트
- items: 20개+ 컴포넌트
- board: 5개 컴포넌트
- quality: 4개 컴포넌트
- material, outbound, quotes 등 기타 컴포넌트

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-11 17:19:11 +09:00

391 lines
12 KiB
TypeScript

'use client';
/**
* 공정상세 섹션 컴포넌트
* API 연동 완료 (2025-12-26)
*
* 기획 화면에 맞춘 레이아웃:
* - 자재 투입 필요 섹션 (흰색 박스, 검은색 전체너비 버튼)
* - 공정 단계 (N단계) + N/N 완료
* - 숫자 뱃지 + 공정명 + 검사 뱃지 + 진행률
* - 검사 항목: 검사 요청 버튼
* - 상세 정보: 위치, 규격, LOT, 자재
*/
import { useState, useEffect, useCallback } from 'react';
import { ChevronDown, Loader2 } from 'lucide-react';
import { ContentLoadingSpinner } from '@/components/ui/loading-spinner';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
AlertDialog,
AlertDialogAction,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { getProcessSteps, requestInspection, type ProcessStep, type ProcessStepItem } from './actions';
interface ProcessDetailSectionProps {
workOrderId: string;
isExpanded: boolean;
materialRequired: boolean;
onMaterialInput: () => void;
}
export function ProcessDetailSection({
workOrderId,
isExpanded,
materialRequired,
onMaterialInput,
}: ProcessDetailSectionProps) {
const [steps, setSteps] = useState<ProcessStep[]>([]);
const [expandedSteps, setExpandedSteps] = useState<Set<string>>(new Set());
const [inspectionDialogOpen, setInspectionDialogOpen] = useState(false);
const [inspectionStepName, setInspectionStepName] = useState('');
const [pendingInspectionStepId, setPendingInspectionStepId] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
// API로 공정 단계 로드
const loadProcessSteps = useCallback(async () => {
if (!workOrderId) return;
setIsLoading(true);
try {
const result = await getProcessSteps(workOrderId);
if (result.success) {
setSteps(result.data);
// 첫 번째 단계 자동 펼치기
if (result.data.length > 0) {
setExpandedSteps(new Set([result.data[0].id]));
}
} else {
toast.error(result.error || '공정 단계 조회에 실패했습니다.');
}
} catch (error) {
if (isNextRedirectError(error)) throw error;
console.error('[ProcessDetailSection] loadProcessSteps error:', error);
toast.error('공정 단계 로드 중 오류가 발생했습니다.');
} finally {
setIsLoading(false);
}
}, [workOrderId]);
// 섹션이 펼쳐질 때 데이터 로드
useEffect(() => {
if (isExpanded && workOrderId) {
loadProcessSteps();
}
}, [isExpanded, workOrderId, loadProcessSteps]);
const totalSteps = steps.length;
const completedSteps = steps.filter((s) => s.completed === s.total).length;
const toggleStep = (stepId: string) => {
setExpandedSteps((prev) => {
const next = new Set(prev);
if (next.has(stepId)) {
next.delete(stepId);
} else {
next.add(stepId);
}
return next;
});
};
// 검사 요청 핸들러
const handleInspectionRequest = (step: ProcessStep) => {
setInspectionStepName(step.name);
setPendingInspectionStepId(step.id);
setInspectionDialogOpen(true);
};
// 검사 요청 확인 후 API 호출
const handleInspectionConfirm = async () => {
if (!pendingInspectionStepId) {
setInspectionDialogOpen(false);
return;
}
setIsSubmitting(true);
try {
const result = await requestInspection(workOrderId, pendingInspectionStepId);
if (result.success) {
// 로컬 상태 업데이트
setSteps((prev) =>
prev.map((step) =>
step.id === pendingInspectionStepId
? { ...step, completed: step.total }
: step
)
);
// 다음 단계 펼치기
const stepIndex = steps.findIndex((s) => s.id === pendingInspectionStepId);
if (stepIndex < steps.length - 1) {
setExpandedSteps((prev) => new Set([...prev, steps[stepIndex + 1].id]));
}
toast.success('검사 요청이 전송되었습니다.');
} else {
toast.error(result.error || '검사 요청에 실패했습니다.');
}
} catch (error) {
if (isNextRedirectError(error)) throw error;
console.error('[ProcessDetailSection] handleInspectionConfirm error:', error);
toast.error('검사 요청 중 오류가 발생했습니다.');
} finally {
setIsSubmitting(false);
setInspectionDialogOpen(false);
setPendingInspectionStepId(null);
}
};
if (!isExpanded) return null;
return (
<div className="mt-4 pt-4 border-t border-gray-200 space-y-4">
{/* 자재 투입 필요 섹션 */}
{materialRequired && (
<div className="border border-gray-200 rounded-lg p-4">
<p className="text-sm font-medium text-gray-900 mb-3"> </p>
<Button
onClick={onMaterialInput}
className="w-full bg-gray-900 hover:bg-gray-800 text-white font-medium py-3 rounded-lg"
>
</Button>
</div>
)}
{/* 공정 단계 헤더 */}
<div className="flex items-center justify-between">
<h4 className="text-sm font-semibold text-gray-900">
({totalSteps})
</h4>
<span className="text-sm text-gray-500">
{completedSteps} / {totalSteps}
</span>
</div>
{/* 공정 단계 목록 */}
<div className="space-y-2">
{isLoading ? (
<ContentLoadingSpinner text="공정 단계를 불러오는 중..." />
) : steps.length === 0 ? (
<div className="py-8 text-center text-gray-500">
.
</div>
) : (
steps.map((step) => (
<ProcessStepCard
key={step.id}
step={step}
isExpanded={expandedSteps.has(step.id)}
onToggle={() => toggleStep(step.id)}
onInspectionRequest={() => handleInspectionRequest(step)}
/>
))
)}
</div>
{/* 검사 요청 확인 다이얼로그 */}
<AlertDialog open={inspectionDialogOpen} onOpenChange={setInspectionDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle> </AlertDialogTitle>
<AlertDialogDescription>
{inspectionStepName} ?
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<Button
variant="outline"
onClick={() => setInspectionDialogOpen(false)}
disabled={isSubmitting}
>
</Button>
<Button
onClick={handleInspectionConfirm}
disabled={isSubmitting}
className="bg-gray-900 hover:bg-gray-800"
>
{isSubmitting ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
...
</>
) : (
'요청하기'
)}
</Button>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
// ===== 하위 컴포넌트 =====
interface ProcessStepCardProps {
step: ProcessStep;
isExpanded: boolean;
onToggle: () => void;
onInspectionRequest: () => void;
}
function ProcessStepCard({ step, isExpanded, onToggle, onInspectionRequest }: ProcessStepCardProps) {
const isCompleted = step.completed === step.total;
const hasItems = step.items.length > 0;
return (
<div
className={cn(
'border rounded-lg overflow-hidden',
isCompleted ? 'bg-gray-50 border-gray-300' : 'bg-white border-gray-200'
)}
>
{/* 헤더 */}
<div
onClick={onToggle}
className="flex items-center justify-between p-3 cursor-pointer"
>
<div className="flex items-center gap-3">
{/* 숫자 뱃지 */}
<div
className={cn(
'flex items-center justify-center w-7 h-7 rounded-full text-sm font-medium',
isCompleted
? 'bg-gray-400 text-white'
: 'bg-gray-900 text-white'
)}
>
{step.stepNo}
</div>
{/* 공정명 + 검사 뱃지 */}
<div className="flex items-center gap-2">
<span className="text-sm font-medium text-gray-900">{step.name}</span>
{step.isInspection && (
<Badge
variant="secondary"
className="text-xs bg-gray-200 text-gray-700 px-2 py-0.5"
>
</Badge>
)}
</div>
</div>
{/* 진행률 + 완료 표시 */}
<div className="flex items-center gap-2">
{isCompleted && (
<span className="text-xs font-medium text-gray-600"></span>
)}
<span className="text-sm text-gray-500">
{step.completed}/{step.total}
</span>
{(hasItems || step.isInspection) && (
<ChevronDown
className={cn(
'h-4 w-4 text-gray-400 transition-transform',
isExpanded && 'rotate-180'
)}
/>
)}
</div>
</div>
{/* 검사 요청 버튼 (검사 항목일 때만) */}
{step.isInspection && !isCompleted && isExpanded && (
<div className="px-3 pb-3">
<Button
onClick={(e) => {
e.stopPropagation();
onInspectionRequest();
}}
className="w-full bg-gray-900 hover:bg-gray-800 text-white font-medium py-2.5 rounded-lg"
>
</Button>
</div>
)}
{/* 상세 항목 리스트 */}
{hasItems && isExpanded && (
<div className="border-t border-gray-100">
{step.items.map((item, index) => (
<ProcessStepItemCard
key={item.id}
item={item}
index={index + 1}
isCompleted={index < step.completed}
/>
))}
</div>
)}
</div>
);
}
interface ProcessStepItemCardProps {
item: ProcessStepItem;
index: number;
isCompleted: boolean;
}
function ProcessStepItemCard({ item, index, isCompleted }: ProcessStepItemCardProps) {
return (
<div className="flex gap-3 p-3 border-b border-gray-50 last:border-b-0">
{/* 인덱스 뱃지 */}
<div
className={cn(
'flex items-center justify-center w-7 h-7 rounded-lg text-sm font-bold flex-shrink-0',
isCompleted
? 'bg-gray-300 text-gray-600'
: 'bg-gray-100 text-gray-900'
)}
>
{index}
</div>
{/* 상세 정보 */}
<div className="flex-1 min-w-0">
{/* 첫 번째 줄: #N + 위치 + 선행생산 + 완료 */}
<div className="flex items-center gap-2 mb-1.5">
<span className="text-sm font-semibold text-gray-900">{item.itemNo}</span>
<Badge
variant="outline"
className="text-xs bg-gray-100 border-gray-300 text-gray-700 px-2 py-0.5"
>
{item.location}
</Badge>
{item.isPriority && (
<Badge className="text-xs bg-yellow-400 hover:bg-yellow-400 text-yellow-900 px-2 py-0.5">
</Badge>
)}
{isCompleted && (
<span className="text-xs font-medium text-gray-500 ml-auto"></span>
)}
</div>
{/* 두 번째 줄: 규격 + 자재 */}
<div className="flex items-center justify-between text-xs text-gray-600">
<span>: {item.spec}</span>
<span>: {item.material}</span>
</div>
{/* 세 번째 줄: LOT */}
<div className="text-xs text-gray-500 mt-0.5">
LOT: {item.lot}
</div>
</div>
</div>
);
}