summaryrefslogtreecommitdiff
path: root/lib/pq/pq-criteria/add-pq-dialog.tsx
blob: 33e656c21145485efb0922c93114e9a8b3235033 (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
"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 } 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 { Textarea } from "@/components/ui/textarea"
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"

import { useToast } from "@/hooks/use-toast"
import { createPqCriteria } from "../service"

// PQ 생성을 위한 Zod 스키마 정의
const createPqSchema = 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"),
  subGroupName: z.string().optional(),
  description: z.string().optional(),
  remarks: z.string().optional(),
  inputFormat: z.string().default("TEXT"),

});

type CreatePqFormType = z.infer<typeof createPqSchema>;

// 그룹 이름 옵션
export const groupOptions = [
  "GENERAL",
  "QMS",
  "Warranty",
  "HSE+",
  "기타",
];

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

interface AddPqDialogProps {
  pqListId: number;
}

export function AddPqDialog({ pqListId }: AddPqDialogProps) {
  const [open, setOpen] = React.useState(false)
  const [isSubmitting, setIsSubmitting] = React.useState(false)
  const router = useRouter()
  const { toast } = useToast()

  // react-hook-form 설정
  const form = useForm<CreatePqFormType>({
    resolver: zodResolver(createPqSchema),
    defaultValues: {
      code: "",
      checkPoint: "",
      groupName: groupOptions[0],
      subGroupName: "",
      description: "",
      remarks: "",
      inputFormat: "TEXT",

    },
  })
  const formState = form.formState

  async function onSubmit(data: CreatePqFormType) {
    try {
      setIsSubmitting(true)

      // 서버 액션 호출
      const result = await createPqCriteria(pqListId, data)

      if (!result.success) {
        toast({
          title: "오류",
          description: result.message || "PQ 항목 생성에 실패했습니다",
          variant: "destructive",
        })
        return
      }

      // 성공 시 처리
      toast({
        title: "성공",
        description: result.message || "PQ 항목이 성공적으로 생성되었습니다",
      })

      // 모달 닫고 폼 리셋
      form.reset()
      setOpen(false)

      // 페이지 새로고침
      router.refresh()

    } catch (error) {
      console.error('Error creating PQ criteria:', error)
      toast({
        title: "오류",
        description: "예상치 못한 오류가 발생했습니다",
        variant: "destructive",
      })
    } finally {
      setIsSubmitting(false)
    }
  }

  function handleDialogOpenChange(nextOpen: boolean) {
    if (!nextOpen) {
      form.reset()
    }
    setOpen(nextOpen)
  }

  return (
    <Dialog open={open} onOpenChange={handleDialogOpenChange}>
      <DialogTrigger asChild>
        <Button variant="default" size="sm">
          <Plus className="size-4" />
          Add PQ
        </Button>
      </DialogTrigger>

      <DialogContent className="sm:max-w-[600px] max-h-[80vh] flex flex-col">
        <DialogHeader>
          <DialogTitle>PQ 항목 생성</DialogTitle>
          <DialogDescription>
            새 PQ 항목을 추가합니다.
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="flex-1 overflow-auto space-y-4">
            <div className="space-y-4 px-1">
              {/* Group Name 필드 */}
              <FormField
                control={form.control}
                name="groupName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>대분류 <span className="text-destructive">*</span></FormLabel>
                    <Select onValueChange={field.onChange} defaultValue={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>소분류</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="서브 그룹명을 입력하세요"
                        {...field}
                        value={field.value || ""}
                      />
                    </FormControl>
                    <FormDescription>
                      세부 분류를 위한 서브 그룹명을 입력하세요 (선택사항)
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />
              {/* Code 필드 */}
              <FormField
                control={form.control}
                name="code"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>일련번호 <span className="text-destructive">*</span></FormLabel>
                    <FormControl>
                      <Input
                        placeholder="예: 1-1, A.2.3"
                        {...field}
                      />
                    </FormControl>
                    <FormDescription>
                      PQ 항목의 고유 코드를 입력하세요
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />
              {/* Check Point 필드 */}
              <FormField
                control={form.control}
                name="checkPoint"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>PQ 항목 <span className="text-destructive">*</span></FormLabel>
                    <FormControl>
                      <Input
                        placeholder="PQ 항목을 입력하세요"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Input Format 필드 */}
              <FormField
                control={form.control}
                name="inputFormat"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>협력업체 입력사항 <span className="text-destructive">*</span></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>
                )}
              />

              {/* Description 필드 */}
              <FormField
                control={form.control}
                name="description"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>설명</FormLabel>
                    <FormControl>
                      <Textarea
                        placeholder="상세 설명을 입력하세요"
                        className="min-h-[100px]"
                        {...field}
                        value={field.value || ""}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

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

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => {
                  form.reset();
                  setOpen(false);
                }}
              >
                취소
              </Button>
              <Button
                type="submit"
                disabled={isSubmitting || !formState.isValid}
              >
                {isSubmitting ? "생성 중..." : "생성"}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}