Files
sam-react-prod/src/components/process-management/ProcessForm.tsx
유병철 62ef2b1ff9 feat(WEB): IntegratedDetailTemplate 통합 템플릿 구현 및 Phase 1~8 마이그레이션
- Phase 1: 기안함(DocumentCreate) 마이그레이션
- Phase 2: 작업지시(WorkOrderCreate/Edit) 마이그레이션
- Phase 3: 출하(ShipmentCreate/Edit) 마이그레이션
- Phase 4: 사원(EmployeeForm) 마이그레이션
- Phase 5: 게시판(BoardForm) 마이그레이션
- Phase 6: 1:1문의(InquiryForm) 마이그레이션
- Phase 7: 공정(ProcessForm) 마이그레이션
- Phase 8: 수입검사/품질검사(InspectionCreate) 마이그레이션
- DetailActions에 showSave 옵션 추가
- 각 도메인별 config 파일 생성

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-20 19:31:07 +09:00

475 lines
17 KiB
TypeScript

'use client';
/**
* 공정 등록/수정 폼 컴포넌트
* IntegratedDetailTemplate 마이그레이션 (2025-01-20)
*/
import { useState, useCallback, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Plus, Wrench, Trash2, Pencil } from 'lucide-react';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { processCreateConfig, processEditConfig } from './processConfig';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Checkbox } from '@/components/ui/checkbox';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { RuleModal } from './RuleModal';
import { toast } from 'sonner';
import type { Process, ClassificationRule, ProcessType } from '@/types/process';
import { PROCESS_TYPE_OPTIONS, MATCHING_TYPE_OPTIONS } from '@/types/process';
import { createProcess, updateProcess, getDepartmentOptions, type DepartmentOption } from './actions';
// 작업일지 양식 옵션 (추후 API 연동 가능)
const WORK_LOG_OPTIONS = [
{ value: '스크린 작업일지', label: '스크린 작업일지' },
{ value: '절곡 작업일지', label: '절곡 작업일지' },
{ value: '슬랫 작업일지', label: '슬랫 작업일지' },
{ value: '재고생산 작업일지', label: '재고생산 작업일지' },
{ value: '포장 작업일지', label: '포장 작업일지' },
];
interface ProcessFormProps {
mode: 'create' | 'edit';
initialData?: Process;
}
export function ProcessForm({ mode, initialData }: ProcessFormProps) {
const router = useRouter();
const isEdit = mode === 'edit';
// 폼 상태
const [processName, setProcessName] = useState(initialData?.processName || '');
const [processType, setProcessType] = useState<ProcessType>(
initialData?.processType || '생산'
);
const [department, setDepartment] = useState(initialData?.department || '');
const [workLogTemplate, setWorkLogTemplate] = useState(
initialData?.workLogTemplate || ''
);
const [classificationRules, setClassificationRules] = useState<ClassificationRule[]>(
initialData?.classificationRules || []
);
const [requiredWorkers, setRequiredWorkers] = useState(
initialData?.requiredWorkers || 1
);
const [equipmentInfo, setEquipmentInfo] = useState(initialData?.equipmentInfo || '');
const [workSteps, setWorkSteps] = useState(initialData?.workSteps?.join(', ') || '');
const [note, setNote] = useState(initialData?.note || '');
const [isActive, setIsActive] = useState(initialData ? initialData.status === '사용중' : true);
const [isLoading, setIsLoading] = useState(false);
// 부서 목록 상태
const [departmentOptions, setDepartmentOptions] = useState<DepartmentOption[]>([]);
const [isDepartmentsLoading, setIsDepartmentsLoading] = useState(true);
// 규칙 모달 상태
const [ruleModalOpen, setRuleModalOpen] = useState(false);
const [editingRule, setEditingRule] = useState<ClassificationRule | undefined>(undefined);
// 부서 목록 로드
useEffect(() => {
const loadDepartments = async () => {
setIsDepartmentsLoading(true);
const departments = await getDepartmentOptions();
setDepartmentOptions(departments);
setIsDepartmentsLoading(false);
};
loadDepartments();
}, []);
// 규칙 추가/수정
const handleSaveRule = useCallback(
(ruleData: Omit<ClassificationRule, 'id' | 'createdAt'>) => {
if (editingRule) {
// 수정 모드
setClassificationRules((prev) =>
prev.map((r) =>
r.id === editingRule.id
? { ...r, ...ruleData }
: r
)
);
} else {
// 추가 모드
const newRule: ClassificationRule = {
...ruleData,
id: `rule-${Date.now()}`,
createdAt: new Date().toISOString(),
};
setClassificationRules((prev) => [...prev, newRule]);
}
setEditingRule(undefined);
},
[editingRule]
);
// 규칙 수정 모달 열기
const handleEditRule = useCallback((rule: ClassificationRule) => {
setEditingRule(rule);
setRuleModalOpen(true);
}, []);
// 규칙 삭제
const handleDeleteRule = useCallback((ruleId: string) => {
setClassificationRules((prev) => prev.filter((r) => r.id !== ruleId));
}, []);
// 모달 닫기
const handleModalClose = useCallback((open: boolean) => {
setRuleModalOpen(open);
if (!open) {
setEditingRule(undefined);
}
}, []);
// 제출
const handleSubmit = async () => {
if (!processName.trim()) {
toast.error('공정명을 입력해주세요.');
return;
}
if (!department) {
toast.error('담당부서를 선택해주세요.');
return;
}
const formData = {
processName: processName.trim(),
processType,
department,
workLogTemplate: workLogTemplate || undefined,
classificationRules: classificationRules.map((rule) => ({
registrationType: rule.registrationType,
ruleType: rule.ruleType,
matchingType: rule.matchingType,
conditionValue: rule.conditionValue,
priority: rule.priority,
description: rule.description,
isActive: rule.isActive,
})),
requiredWorkers,
equipmentInfo: equipmentInfo.trim() || undefined,
workSteps: workSteps,
note: note.trim() || undefined,
isActive,
};
setIsLoading(true);
try {
if (isEdit && initialData?.id) {
const result = await updateProcess(initialData.id, formData);
if (result.success) {
toast.success('공정이 수정되었습니다.');
router.push('/ko/master-data/process-management');
} else {
toast.error(result.error || '수정에 실패했습니다.');
}
} else {
const result = await createProcess(formData);
if (result.success) {
toast.success('공정이 등록되었습니다.');
router.push('/ko/master-data/process-management');
} else {
toast.error(result.error || '등록에 실패했습니다.');
}
}
} catch {
toast.error('처리 중 오류가 발생했습니다.');
} finally {
setIsLoading(false);
}
};
// 취소
const handleCancel = () => {
router.back();
};
// ===== 폼 콘텐츠 렌더링 =====
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 md:grid-cols-2 gap-6">
<div className="space-y-2">
<Label htmlFor="processName"> *</Label>
<Input
id="processName"
value={processName}
onChange={(e) => setProcessName(e.target.value)}
placeholder="예: 스크린"
/>
</div>
<div className="space-y-2">
<Label></Label>
<Select
value={processType}
onValueChange={(v) => setProcessType(v as ProcessType)}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{PROCESS_TYPE_OPTIONS.map((opt) => (
<SelectItem key={opt.value} value={opt.value}>
{opt.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label> *</Label>
<Select value={department} onValueChange={setDepartment} disabled={isDepartmentsLoading}>
<SelectTrigger>
<SelectValue placeholder={isDepartmentsLoading ? "로딩 중..." : "선택하세요"} />
</SelectTrigger>
<SelectContent>
{departmentOptions.map((opt) => (
<SelectItem key={opt.value} value={opt.value}>
{opt.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label> </Label>
<Select value={workLogTemplate} onValueChange={setWorkLogTemplate}>
<SelectTrigger>
<SelectValue placeholder="선택하세요" />
</SelectTrigger>
<SelectContent>
{WORK_LOG_OPTIONS.map((opt) => (
<SelectItem key={opt.value} value={opt.value}>
{opt.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</CardContent>
</Card>
{/* 자동 분류 규칙 */}
<Card>
<CardHeader className="bg-muted/50">
<div className="flex items-center justify-between">
<div>
<CardTitle className="text-base"> </CardTitle>
<p className="text-sm text-muted-foreground mt-1">
.
</p>
</div>
<Button onClick={() => setRuleModalOpen(true)}>
<Plus className="h-4 w-4 mr-2" />
</Button>
</div>
</CardHeader>
<CardContent className="pt-6">
{classificationRules.length === 0 ? (
<div className="text-center py-12 text-muted-foreground">
<Wrench className="h-12 w-12 mx-auto mb-4 opacity-30" />
<p className="font-medium"> </p>
<p className="text-sm mt-1">
</p>
</div>
) : (
<div className="space-y-3">
{classificationRules.map((rule, index) => {
// 개별 품목인 경우 품목 개수 계산
const isIndividual = rule.registrationType === 'individual';
const itemCount = isIndividual
? rule.conditionValue.split(',').filter(Boolean).length
: 0;
return (
<div
key={rule.id}
className="flex items-start justify-between p-4 border rounded-lg"
>
<div className="flex gap-3">
{/* 번호 */}
<span className="text-muted-foreground font-medium mt-0.5">
{index + 1}.
</span>
<div className="space-y-1">
{/* 제목 */}
<div className="font-medium">
{isIndividual ? (
<> - {itemCount} </>
) : (
<>
{rule.ruleType}{' '}
{
MATCHING_TYPE_OPTIONS.find(
(o) => o.value === rule.matchingType
)?.label
}{' '}
"{rule.conditionValue}"
</>
)}
</div>
{/* 뱃지 + 우선순위 */}
<div className="flex items-center gap-2">
<Badge variant="secondary" className="text-xs">
{isIndividual
? `${itemCount}개 품목 배정됨`
: rule.isActive
? '활성'
: '비활성'}
</Badge>
<span className="text-sm text-muted-foreground">
: {rule.priority}
</span>
</div>
{/* 설명 */}
<div className="text-sm text-muted-foreground">
{isIndividual
? `직접 선택한 품목 ${itemCount}`
: rule.description || ''}
</div>
</div>
</div>
{/* 수정/삭제 버튼 */}
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
onClick={() => handleEditRule(rule)}
className="h-8 w-8"
>
<Pencil className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="icon"
onClick={() => handleDeleteRule(rule.id)}
className="h-8 w-8 text-muted-foreground hover:text-destructive"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
);
})}
</div>
)}
</CardContent>
</Card>
{/* 작업 정보 */}
<Card>
<CardHeader className="bg-muted/50">
<CardTitle className="text-base"> </CardTitle>
</CardHeader>
<CardContent className="pt-6 space-y-6">
<div className="space-y-2">
<Label></Label>
<Input
type="number"
value={requiredWorkers}
onChange={(e) => setRequiredWorkers(Number(e.target.value))}
min={1}
className="w-32"
/>
</div>
<div className="space-y-2">
<Label></Label>
<Input
value={equipmentInfo}
onChange={(e) => setEquipmentInfo(e.target.value)}
placeholder="예: 미싱기 3대, 절단기 1대"
/>
</div>
<div className="space-y-2">
<Label> ( )</Label>
<Input
value={workSteps}
onChange={(e) => setWorkSteps(e.target.value)}
placeholder="예: 원단절단, 미싱, 핸드작업, 중간검사, 포장"
/>
</div>
</CardContent>
</Card>
{/* 설명 */}
<Card>
<CardHeader className="bg-muted/50">
<CardTitle className="text-base"></CardTitle>
</CardHeader>
<CardContent className="pt-6 space-y-6">
<div className="space-y-2">
<Label></Label>
<Textarea
value={note}
onChange={(e) => setNote(e.target.value)}
placeholder="공정에 대한 설명"
rows={4}
/>
</div>
<div className="flex items-center gap-2">
<Checkbox
id="isActive"
checked={isActive}
onCheckedChange={(checked) => setIsActive(checked as boolean)}
/>
<Label htmlFor="isActive" className="font-normal">
</Label>
</div>
</CardContent>
</Card>
</div>
{/* 규칙 추가/수정 모달 */}
<RuleModal
open={ruleModalOpen}
onOpenChange={handleModalClose}
onAdd={handleSaveRule}
editRule={editingRule}
/>
</>
), [
processName, processType, department, workLogTemplate, classificationRules,
requiredWorkers, equipmentInfo, workSteps, note, isActive, ruleModalOpen,
editingRule, departmentOptions, isDepartmentsLoading, handleSaveRule,
handleEditRule, handleDeleteRule, handleModalClose,
]);
// Config 선택 (create/edit)
const config = isEdit ? processEditConfig : processCreateConfig;
return (
<IntegratedDetailTemplate
config={config}
mode={isEdit ? 'edit' : 'create'}
isLoading={isDepartmentsLoading}
isSubmitting={isLoading}
onBack={handleCancel}
onCancel={handleCancel}
onSubmit={handleSubmit}
renderForm={renderFormContent}
/>
);
}