summaryrefslogtreecommitdiff
path: root/lib/pq/pq-criteria/update-pq-sheet.tsx
blob: 1d8092cd2334867620bbf46888c02e6ccc1c78f7 (plain)
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
"use client"

import * as React from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import { Loader, Save } from "lucide-react"
import { useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod"
import { useRouter } from "next/navigation"

import { Button } from "@/components/ui/button"
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import {
  Select,
  SelectContent,
  // SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Sheet,
  SheetClose,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"

import { updatePqCriteria } from "../service"
import { groupOptions } from "./add-pq-dialog"
import { Checkbox } from "@/components/ui/checkbox"
import { uploadPqCriteriaFileAction, getPqCriteriaAttachments } from "@/lib/pq/service"
import { Dropzone, DropzoneInput, DropzoneZone, DropzoneUploadIcon, DropzoneTitle, DropzoneDescription } from "@/components/ui/dropzone"
import { FileList, FileListHeader, FileListInfo, FileListItem, FileListName, FileListDescription, FileListAction } from "@/components/ui/file-list"
import { X, Loader2 } from "lucide-react"

// PQ 수정을 위한 Zod 스키마 정의
const updatePqSchema = z.object({
  code: z.string().min(1, "Code is required"),
  checkPoint: z.string().min(1, "Check point is required"),
  groupName: z.string().min(1, "Group is required"),
  description: z.string().optional(),
  remarks: z.string().optional(),
  inputFormat: z.string().default("TEXT"),

  subGroupName: z.string().optional(),
  type: z.string().optional(),
});

type UpdatePqSchema = z.infer<typeof updatePqSchema>;

// 입력 형식 옵션
const inputFormatOptions = [
  { value: "TEXT", label: "텍스트" },
  { value: "FILE", label: "파일" },
  { value: "EMAIL", label: "이메일" },
  { value: "PHONE", label: "전화번호" },
  { value: "NUMBER", label: "숫자" },
  { value: "NUMBER_WITH_UNIT", label: "숫자+단위" },
  { value: "TEXT_FILE", label: "텍스트 + 파일" }
];

const typeOptions = [
  { value: "내자", label: "내자" },
  { value: "외자", label: "외자" },
  { value: "내외자", label: "내외자" },
];

interface UpdatePqSheetProps
  extends React.ComponentPropsWithRef<typeof Sheet> {
  pq: {
    id: number;
    code: string;
    checkPoint: string;
    description: string | null;
    remarks: string | null;
    groupName: string | null;
    inputFormat: string;
  
    subGroupName: string | null;
    type?: string | null;
  } | null
}

export function UpdatePqSheet({ pq, ...props }: UpdatePqSheetProps) {
  const [isUpdatePending, startUpdateTransition] = React.useTransition()
  const [isUploading, setIsUploading] = React.useState(false)
  const [attachments, setAttachments] = React.useState<
    { fileName: string; url: string; size?: number; originalFileName?: string }[]
  >([])
  const router = useRouter()

  const form = useForm<UpdatePqSchema>({
    resolver: zodResolver(updatePqSchema),
    defaultValues: {
      code: pq?.code ?? "",
      checkPoint: pq?.checkPoint ?? "",
      groupName: pq?.groupName ?? groupOptions[0],
      description: pq?.description ?? "",
      remarks: pq?.remarks ?? "",
      inputFormat: pq?.inputFormat ?? "TEXT",

      subGroupName: pq?.subGroupName ?? "",
      type: pq?.type ?? "내외자",
    },
  })

  // 폼 초기화 (pq가 변경될 때)
  React.useEffect(() => {
    if (pq) {
      form.reset({
        code: pq.code,
        checkPoint: pq.checkPoint,
        groupName: pq.groupName ?? groupOptions[0],
        description: pq.description ?? "",
        remarks: pq.remarks ?? "",
        inputFormat: pq.inputFormat ?? "TEXT",
  
        subGroupName: pq.subGroupName ?? "",
        type: pq.type ?? "내외자",
      });

      // 기존 첨부 로드
      getPqCriteriaAttachments(pq.id).then((res) => {
        if (res.success && res.data) {
          setAttachments(
            res.data.map((a) => ({
              fileName: a.fileName,
              url: a.filePath,
              size: a.fileSize ?? undefined,
              originalFileName: a.originalFileName || a.fileName,
            }))
          )
        } else {
          setAttachments([])
        }
      })
    }
  }, [pq, form]);

  const handleUpload = async (files: File[]) => {
    try {
      setIsUploading(true)
      for (const file of files) {
        const uploaded = await uploadPqCriteriaFileAction(file)
        setAttachments((prev) => [...prev, uploaded])
      }
      toast.success("첨부파일이 업로드되었습니다")
    } catch (error) {
      console.error(error)
      toast.error("첨부파일 업로드에 실패했습니다")
    } finally {
      setIsUploading(false)
    }
  }

  function onSubmit(input: UpdatePqSchema) {
    startUpdateTransition(async () => {
      if (!pq) return
  
      const result = await updatePqCriteria(pq.id, {
        ...input,
        attachments,
      })
  
      if (!result.success) {
        toast.error(result.message || "PQ 항목 수정에 실패했습니다")
        return
      }
  
      toast.success(result.message || "PQ 항목이 성공적으로 수정되었습니다")
      form.reset()
      props.onOpenChange?.(false)
      router.refresh()
    })
  }
  return (
    <Sheet {...props}>
      <SheetContent className="flex flex-col gap-6 sm:max-w-md">
        <SheetHeader className="text-left">
          <SheetTitle>Update PQ Criteria</SheetTitle>
          <SheetDescription>
            Update the PQ criteria details and save the changes
          </SheetDescription>
        </SheetHeader>
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="flex flex-col gap-4"
          >
            {/* Code 필드 */}
            <FormField
              control={form.control}
              name="code"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Code <span className="text-destructive">*</span></FormLabel>
                  <FormControl>
                    <Input
                      placeholder="예: 1-1, A.2.3"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Check Point 필드 */}
            <FormField
              control={form.control}
              name="checkPoint"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Check Point <span className="text-destructive">*</span></FormLabel>
                  <FormControl>
                    <Input
                      placeholder="검증 항목을 입력하세요"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Group Name 필드 (Select) */}
            <FormField
              control={form.control}
              name="groupName"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Group <span className="text-destructive">*</span></FormLabel>
                  <Select 
                    onValueChange={field.onChange} 
                    defaultValue={field.value}
                    value={field.value}
                  >
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="그룹을 선택하세요" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {groupOptions.map((group) => (
                        <SelectItem key={group} value={group}>
                          {group}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />
            {/* Sub Group Name 필드 */}
            <FormField
              control={form.control}
              name="subGroupName"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Sub Group Name</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="서브 그룹명을 입력하세요"
                      {...field}
                      value={field.value || ""}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Type 필드 */}
            <FormField
              control={form.control}
              name="type"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>내/외자 구분</FormLabel>
                  <Select onValueChange={field.onChange} value={field.value}>
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="구분을 선택하세요" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {typeOptions.map((option) => (
                        <SelectItem key={option.value} value={option.value}>
                          {option.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormDescription>미선택 시 기본값은 내외자입니다.</FormDescription>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Input Format 필드 */}
            <FormField
              control={form.control}
              name="inputFormat"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>입력 형식</FormLabel>
                  <Select onValueChange={field.onChange} defaultValue={field.value}>
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="입력 형식을 선택하세요" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {inputFormatOptions.map((option) => (
                        <SelectItem key={option.value} value={option.value}>
                          {option.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* 첨부 파일 업로드 */}
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <FormLabel>첨부 파일</FormLabel>
                {isUploading && (
                  <div className="flex items-center text-xs text-muted-foreground">
                    <Loader2 className="mr-1 h-3 w-3 animate-spin" /> 업로드 중...
                  </div>
                )}
              </div>
              <Dropzone
                maxSize={6e8}
                onDropAccepted={(files) => handleUpload(files)}
                onDropRejected={() =>
                  toast.error("파일 크기/형식을 확인하세요.")
                }
                disabled={isUploading}
              >
                {() => (
                  <FormItem>
                    <DropzoneZone className="flex justify-center h-24">
                      <FormControl>
                        <DropzoneInput />
                      </FormControl>
                      <div className="flex items-center gap-4">
                        <DropzoneUploadIcon />
                        <div className="grid gap-0.5">
                          <DropzoneTitle>파일을 드래그하거나 클릭하여 업로드</DropzoneTitle>
                          <DropzoneDescription>PDF, 이미지, 문서 (최대 600MB)</DropzoneDescription>
                        </div>
                      </div>
                    </DropzoneZone>
                    <FormDescription>기준 문서 첨부가 필요한 경우 업로드하세요.</FormDescription>
                  </FormItem>
                )}
              </Dropzone>

              {attachments.length > 0 && (
                <div className="space-y-2">
                  <p className="text-sm font-medium">첨부된 파일 ({attachments.length})</p>
                  <FileList>
                    {attachments.map((file, idx) => (
                      <FileListItem key={idx}>
                        <FileListHeader>
                          <FileListInfo>
                            <FileListName>{file.originalFileName || file.fileName}</FileListName>
                            {file.size && (
                              <FileListDescription>{`${file.size} bytes`}</FileListDescription>
                            )}
                          </FileListInfo>
                          <FileListAction
                            onClick={() =>
                              setAttachments((prev) => prev.filter((_, i) => i !== idx))
                            }
                          >
                            <X className="h-4 w-4" />
                            <span className="sr-only">Remove</span>
                          </FileListAction>
                        </FileListHeader>
                      </FileListItem>
                    ))}
                  </FileList>
                </div>
              )}
            </div>

            {/* Required 체크박스 */}


            {/* Description 필드 */}
            <FormField
              control={form.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Description</FormLabel>
                  <FormControl>
                    <Textarea
                      placeholder="상세 설명을 입력하세요"
                      className="min-h-[120px] whitespace-pre-wrap"
                      {...field}
                      value={field.value || ""}
                    />
                  </FormControl>
                  <FormDescription>
                    줄바꿈이 필요한 경우 Enter 키를 누르세요. 입력한 대로 저장됩니다.
                  </FormDescription>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Remarks 필드 */}
            <FormField
              control={form.control}
              name="remarks"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Remarks</FormLabel>
                  <FormControl>
                    <Textarea
                      placeholder="비고 사항을 입력하세요"
                      className="min-h-[80px]"
                      {...field}
                      value={field.value || ""}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <SheetFooter className="gap-2 pt-2 sm:space-x-0">
              <SheetClose asChild>
                <Button 
                  type="button" 
                  variant="outline"
                  onClick={() => form.reset()}
                >
                  Cancel
                </Button>
              </SheetClose>
              <Button disabled={isUpdatePending}>
                {isUpdatePending && (
                  <Loader
                    className="mr-2 size-4 animate-spin"
                    aria-hidden="true"
                  />
                )}
                <Save className="mr-2 size-4" /> Save
              </Button>
            </SheetFooter>
          </form>
        </Form>
      </SheetContent>
    </Sheet>
  )
}