summaryrefslogtreecommitdiff
path: root/lib/pq/table/add-pq-dialog.tsx
blob: 1f374cd0868edf2fe5126c23926123f6ce4d5603 (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
"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 { Checkbox } from "@/components/ui/checkbox"
import { useToast } from "@/hooks/use-toast"
import { createPq, invalidatePqCache } from "../service"
import { ProjectSelector } from "@/components/ProjectSelector"
import { type Project } from "@/lib/rfqs/service"
import { ScrollArea } from "@/components/ui/scroll-area"

// 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"),
  description: z.string().optional(),
  remarks: z.string().optional(),
  // 프로젝트별 PQ 여부 체크박스
  isProjectSpecific: z.boolean().default(false),
  // 프로젝트 관련 추가 필드는 isProjectSpecific가 true일 때만 필수
  contractInfo: z.string().optional(),
  additionalRequirement: z.string().optional(),
});

type CreatePqFormType = z.infer<typeof createPqSchema>;

// 그룹 이름 옵션
const groupOptions = [
  "GENERAL",
  "Quality Management System",
  "Workshop & Environment",
  "Warranty",
];

// 설명 예시 텍스트
const descriptionExample = `Address :
Tel. / Fax :
e-mail :`;

interface AddPqDialogProps {
  currentProjectId?: number | null;  // 현재 선택된 프로젝트 ID (옵션)
}

export function AddPqDialog({ currentProjectId }: AddPqDialogProps) {
  const [open, setOpen] = React.useState(false)
  const [isSubmitting, setIsSubmitting] = React.useState(false)
  const [selectedProject, setSelectedProject] = React.useState<Project | null>(null)
  const router = useRouter()
  const { toast } = useToast()

  // react-hook-form 설정
  const form = useForm<CreatePqFormType>({
    resolver: zodResolver(createPqSchema),
    defaultValues: {
      code: "",
      checkPoint: "",
      groupName: groupOptions[0],
      description: "",
      remarks: "",
      isProjectSpecific: !!currentProjectId, // 현재 프로젝트 ID가 있으면 기본값 true
      contractInfo: "",
      additionalRequirement: "",
    },
  })

  // 프로젝트별 PQ 여부 상태 감시
  const isProjectSpecific = form.watch("isProjectSpecific")

  // 현재 프로젝트 ID가 있으면 선택된 프로젝트 설정
  React.useEffect(() => {
    if (currentProjectId) {
      form.setValue("isProjectSpecific", true)
    }
  }, [currentProjectId, form])

  // 예시 텍스트를 description 필드에 채우는 함수
  const fillExampleText = () => {
    form.setValue("description", descriptionExample);
  };

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

      // 서버 액션 호출용 데이터 준비
      const submitData = {
        ...data,
        projectId: data.isProjectSpecific ? selectedProject?.id || currentProjectId : null,
      }

      // 프로젝트별 PQ인데 프로젝트가 선택되지 않은 경우 검증
      if (data.isProjectSpecific && !submitData.projectId) {
        toast({
          title: "Error",
          description: "Please select a project",
          variant: "destructive",
        })
        setIsSubmitting(false)
        return
      }

      // 서버 액션 호출
      const result = await createPq(submitData)

      if (!result.success) {
        toast({
          title: "Error",
          description: result.message || "Failed to create PQ criteria",
          variant: "destructive",
        })
        return
      }

      await invalidatePqCache();

      // 성공 시 처리
      toast({
        title: "Success",
        description: result.message || "PQ criteria created successfully",
      })

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

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

    } catch (error) {
      console.error('Error creating PQ criteria:', error)
      toast({
        title: "Error",
        description: "An unexpected error occurred",
        variant: "destructive",
      })
    } finally {
      setIsSubmitting(false)
    }
  }

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

  // 프로젝트 선택 핸들러
  const handleProjectSelect = (project: Project | null) => {
    // project가 null인 경우 선택 해제를 의미
    if (project === null) {
      setSelectedProject(null);
      // 필요한 경우 추가 처리
      return;
    }
    
    // 기존 처리 - 프로젝트가 선택된 경우
    setSelectedProject(project);
  }

  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]">
        <DialogHeader>
          <DialogTitle>Create New PQ Criteria</DialogTitle>
          <DialogDescription>
            새 PQ 기준 정보를 입력하고 <b>Create</b> 버튼을 누르세요.
          </DialogDescription>
        </DialogHeader>

        {/* shadcn/ui Form을 이용해 react-hook-form과 연결 */}
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4 py-2 flex flex-col">
            {/* 프로젝트별 PQ 여부 체크박스 */}

            <div className="flex-1 overflow-auto px-4 space-y-4">
              <FormField
                control={form.control}
                name="isProjectSpecific"
                render={({ field }) => (
                  <FormItem className="flex flex-row items-start space-x-3 space-y-0 rounded-md border p-4">
                    <FormControl>
                      <Checkbox
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </FormControl>
                    <div className="space-y-1 leading-none">
                      <FormLabel>프로젝트별 PQ 생성</FormLabel>
                      <FormDescription>
                        특정 프로젝트에만 적용되는 PQ 항목을 생성합니다
                      </FormDescription>
                    </div>
                  </FormItem>
                )}
              />

              {/* 프로젝트 선택 필드 (프로젝트별 PQ 선택 시에만 표시) */}
              {isProjectSpecific && (
                <div className="space-y-2">
                  <FormLabel>Project <span className="text-destructive">*</span></FormLabel>
                  <ProjectSelector
                    selectedProjectId={currentProjectId || selectedProject?.id}
                    onProjectSelect={handleProjectSelect}
                    placeholder="프로젝트를 선택하세요"
                  />
                  <FormDescription>
                    PQ 항목을 적용할 프로젝트를 선택하세요
                  </FormDescription>
                </div>
              )}

              <div className="flex-1 overflow-auto px-2 py-2 space-y-4" style={{maxHeight:420}}>


                {/* 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>
                      <FormDescription>
                        PQ 항목의 고유 코드를 입력하세요 (예: "1-1", "A.2.3")
                      </FormDescription>
                      <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>
                      <FormDescription>
                        PQ 항목의 분류 그룹을 선택하세요
                      </FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {/* Description 필드 - 예시 템플릿 버튼 추가 */}
                <FormField
                  control={form.control}
                  name="description"
                  render={({ field }) => (
                    <FormItem>
                      <div className="flex items-center justify-between">
                        <FormLabel>Description</FormLabel>
                        <Button
                          type="button"
                          variant="outline"
                          size="sm"
                          onClick={fillExampleText}
                        >
                          예시 채우기
                        </Button>
                      </div>
                      <FormControl>
                        <Textarea
                          placeholder={`줄바꿈을 포함한 상세 설명을 입력하세요\n예:\n${descriptionExample}`}
                          className="min-h-[120px] font-mono"
                          {...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>
                  )}
                />

                {/* 프로젝트별 PQ일 경우 추가 필드 */}
                {isProjectSpecific && (
                  <>
                    {/* 계약 정보 필드 */}
                    <FormField
                      control={form.control}
                      name="contractInfo"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Contract Info</FormLabel>
                          <FormControl>
                            <Textarea
                              placeholder="계약 관련 정보를 입력하세요"
                              className="min-h-[80px]"
                              {...field}
                              value={field.value || ""}
                            />
                          </FormControl>
                          <FormDescription>
                            해당 프로젝트의 계약 관련 특이사항
                          </FormDescription>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    {/* 추가 요구사항 필드 */}
                    <FormField
                      control={form.control}
                      name="additionalRequirement"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Additional Requirements</FormLabel>
                          <FormControl>
                            <Textarea
                              placeholder="추가 요구사항을 입력하세요"
                              className="min-h-[80px]"
                              {...field}
                              value={field.value || ""}
                            />
                          </FormControl>
                          <FormDescription>
                            프로젝트별 추가 요구사항
                          </FormDescription>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </>
                )}
              </div>

            </div>
            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => {
                  form.reset();
                  setSelectedProject(null);
                  setOpen(false);
                }}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                disabled={isSubmitting}
              >
                {isSubmitting ? "Creating..." : "Create"}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}