1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
|
"use client"
import * as React from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"
import { Plus, X, ChevronUp, ChevronDown } from "lucide-react"
import { useRouter } from "next/navigation"
import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { useToast } from "@/hooks/use-toast"
import { createDocument, CreateDocumentInputType, invalidateDocumentCache } from "../service"
// 스테이지 객체로 변경
type StageItem = {
name: string;
order: number;
}
// Zod 스키마 정의 - 스테이지 구조 변경
const createDocumentSchema = z.object({
docNumber: z.string().min(1, "Document number is required"),
title: z.string().min(1, "Title is required"),
stages: z.array(z.object({
name: z.string().min(1, "Stage name cannot be empty"),
order: z.number().int().positive("Order must be a positive integer")
}))
.min(1, "At least one stage is required")
.refine(stages => !stages.some(stage => stage.name.trim() === ""), {
message: "Stage names cannot be empty"
})
.refine(stages => {
// 중복된 order 값이 없는지 확인
const orders = stages.map(s => s.order);
return orders.length === new Set(orders).size;
}, {
message: "Stage orders must be unique"
})
});
type CreateDocumentSchema = z.infer<typeof createDocumentSchema>;
interface AddDocumentListDialogProps {
projectType: "ship" | "plant";
contractId: number;
onSuccess?: () => void;
}
export function AddDocumentListDialog({ projectType, contractId, onSuccess }: AddDocumentListDialogProps) {
const [open, setOpen] = React.useState(false);
const [isSubmitting, setIsSubmitting] = React.useState(false);
const router = useRouter();
const { toast } = useToast()
// 기본 스테이지 설정 - 객체 배열로 변경
const defaultStages: StageItem[] = projectType === "ship"
? [
{ name: "For Approval", order: 1 },
{ name: "For Working", order: 2 }
]
: [{ name: "", order: 1 }];
// react-hook-form 설정
const form = useForm<CreateDocumentSchema>({
resolver: zodResolver(createDocumentSchema),
defaultValues: {
docNumber: "",
title: "",
stages: defaultStages
},
});
// 스테이지 추가 기능
const addStage = () => {
const currentStages = form.getValues().stages;
const nextOrder = Math.max(...currentStages.map(s => s.order), 0) + 1;
form.setValue('stages', [...currentStages, { name: "", order: nextOrder }], { shouldValidate: true });
};
// 스테이지 제거 기능
const removeStage = (index: number) => {
const currentStages = form.getValues().stages;
const newStages = currentStages.filter((_, i) => i !== index);
// 순서 재정렬
const reorderedStages = newStages.map((stage, i) => ({ ...stage, order: i + 1 }));
form.setValue('stages', reorderedStages, { shouldValidate: true });
};
// 스테이지 순서 이동 기능
const moveStage = (index: number, direction: 'up' | 'down') => {
const currentStages = [...form.getValues().stages];
const targetIndex = direction === 'up' ? index - 1 : index + 1;
if (targetIndex < 0 || targetIndex >= currentStages.length) return;
// 스테이지 위치 교환
[currentStages[index], currentStages[targetIndex]] = [currentStages[targetIndex], currentStages[index]];
// order 값 재정렬
const reorderedStages = currentStages.map((stage, i) => ({ ...stage, order: i + 1 }));
form.setValue('stages', reorderedStages, { shouldValidate: true });
};
async function onSubmit(data: CreateDocumentSchema) {
try {
setIsSubmitting(true);
// 빈 문자열 필터링 및 순서 정렬
const filteredStages = data.stages
.filter(stage => stage.name.trim() !== "")
.sort((a, b) => a.order - b.order);
if (filteredStages.length === 0) {
toast({
title: "Error",
description: "At least one valid stage name is required",
variant: "destructive",
});
return;
}
// 서버로 전달할 데이터 형태 변환
const result = await createDocument({
docNumber: data.docNumber,
title: data.title,
stages: filteredStages, // { name, order } 객체 배열로 전달
status: "pending",
contractId,
} as CreateDocumentInputType);
if (result.success) {
// 캐시 무효화 시도
try {
await invalidateDocumentCache(contractId);
} catch (cacheError) {
console.warn('Cache invalidation failed:', cacheError);
}
toast({
title: "Success",
description: "Document created successfully",
variant: "default",
});
// 모달 닫기 및 폼 리셋
form.reset({
docNumber: "",
title: "",
stages: defaultStages
});
setOpen(false);
if (onSuccess) {
onSuccess();
}
setTimeout(() => {
router.refresh();
}, 100);
} else {
toast({
title: "Error",
description: result.message || "Failed to create document",
variant: "destructive",
});
}
} catch (error) {
console.error('Error creating document:', error);
toast({
title: "Error",
description: "An unexpected error occurred",
variant: "destructive",
});
} finally {
setIsSubmitting(false);
}
}
function handleDialogOpenChange(nextOpen: boolean) {
if (!nextOpen) {
form.reset({
docNumber: "",
title: "",
stages: defaultStages
});
}
setOpen(nextOpen);
}
return (
<Dialog open={open} onOpenChange={handleDialogOpenChange}>
<DialogTrigger asChild>
<Button variant="default" size="sm">
<Plus className="size-4 mr-1"/>
Add Document
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle>Create New Document</DialogTitle>
<DialogDescription>
새 문서 정보를 입력하고 <b>Create</b> 버튼을 누르세요.
</DialogDescription>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
{/* 문서 번호 필드 */}
<FormField
control={form.control}
name="docNumber"
render={({ field }) => (
<FormItem>
<FormLabel>Document Number</FormLabel>
<FormControl>
<Input placeholder="Enter document number" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{/* 문서 제목 필드 */}
<FormField
control={form.control}
name="title"
render={({ field }) => (
<FormItem>
<FormLabel>Title</FormLabel>
<FormControl>
<Input placeholder="Enter document title" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{/* 스테이지 섹션 */}
<div>
<div className="flex items-center justify-between mb-2">
<FormLabel>Stages</FormLabel>
{projectType === "plant" && (
<Button
type="button"
variant="outline"
size="sm"
onClick={addStage}
className="h-8 px-2"
>
<Plus className="h-4 w-4 mr-1" /> Add Stage
</Button>
)}
</div>
{form.watch("stages").map((stage, index) => (
<div key={index} className="flex items-center gap-2 mb-2">
{/* 순서 표시 */}
<div className="flex flex-col items-center">
<span className="text-xs text-muted-foreground font-medium w-6 text-center">
{stage.order}
</span>
{projectType === "plant" && (
<div className="flex flex-col">
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => moveStage(index, 'up')}
disabled={index === 0}
className="h-4 w-4 p-0"
>
<ChevronUp className="h-3 w-3" />
</Button>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => moveStage(index, 'down')}
disabled={index === form.watch("stages").length - 1}
className="h-4 w-4 p-0"
>
<ChevronDown className="h-3 w-3" />
</Button>
</div>
)}
</div>
{/* 스테이지 이름 입력 */}
<FormField
control={form.control}
name={`stages.${index}.name`}
render={({ field }) => (
<FormItem className="flex-1">
<FormControl>
<Input
placeholder="Enter stage name"
{...field}
disabled={projectType === "ship"}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{/* 제거 버튼 */}
{projectType === "plant" && index > 0 && (
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => removeStage(index)}
className="h-8 w-8 p-0"
>
<X className="h-4 w-4" />
</Button>
)}
</div>
))}
<FormMessage>
{form.formState.errors.stages?.message}
</FormMessage>
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => setOpen(false)}
>
Cancel
</Button>
<Button
type="submit"
disabled={isSubmitting || form.formState.isSubmitting}
>
{isSubmitting ? "Creating..." : "Create"}
</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
);
}
|