summaryrefslogtreecommitdiff
path: root/lib/vendor-candidates/table/add-candidates-dialog.tsx
blob: 733d3716006e300479f600b3325f8a68766518d9 (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
"use client"

import * as React from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { Check, ChevronsUpDown } from "lucide-react"
import i18nIsoCountries from "i18n-iso-countries"
import enLocale from "i18n-iso-countries/langs/en.json"
import koLocale from "i18n-iso-countries/langs/ko.json"
import { cn } from "@/lib/utils"
import { useSession } from "next-auth/react" // next-auth 세션 훅 추가

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 { useToast } from "@/hooks/use-toast"
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover"
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command"

// react-hook-form + shadcn/ui Form
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"


import { createVendorCandidateSchema, CreateVendorCandidateSchema } from "../validations"
import { createVendorCandidate } from "../service"

// Register locales for countries
i18nIsoCountries.registerLocale(enLocale)
i18nIsoCountries.registerLocale(koLocale)

// Generate country array
const locale = "ko"
const countryMap = i18nIsoCountries.getNames(locale, { select: "official" })
const countryArray = Object.entries(countryMap).map(([code, label]) => ({
  code,
  label,
}))

export function AddCandidateDialog() {
  const [open, setOpen] = React.useState(false)
  const [isSubmitting, setIsSubmitting] = React.useState(false)
  const { toast } = useToast()
  const { data: session, status } = useSession()

  // react-hook-form 세팅
  const form = useForm<CreateVendorCandidateSchema>({
    resolver: zodResolver(createVendorCandidateSchema),
    defaultValues: {
      companyName: "",
      contactEmail: "",  // 이제 빈 문자열이 허용됨
      contactPhone: "",
      taxId: "",
      address: "",
      country: "",
      source: "",
      items: "",
      remark: "",
      status: "COLLECTED",
    },
  });

  async function onSubmit(data: CreateVendorCandidateSchema) {
    setIsSubmitting(true)
    try {
      // 세션 유효성 검사
      if (!session || !session.user || !session.user.id) {
        toast({
          title: "인증 오류",
          description: "로그인 정보를 찾을 수 없습니다. 다시 로그인해주세요.",
          variant: "destructive",
        })
        return
      }

      // userId 추출 (세션 구조에 따라 조정 필요)
      const userId = session.user.id

      const result = await createVendorCandidate(data, Number(userId))
      if (result.error) {
        toast({
          title: "오류 발생",
          description: result.error,
          variant: "destructive",
        })
        return
      }
      // 성공 시 모달 닫고 폼 리셋
      toast({
        title: "등록 완료",
        description: "협력업체 후보가 성공적으로 등록되었습니다.",
      })
      form.reset()
      setOpen(false)
    } catch (error) {
      console.error("Failed to create vendor candidate:", 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">
          Add Vendor Candidate
        </Button>
      </DialogTrigger>

      <DialogContent className="sm:max-w-[525px]">
        <DialogHeader>
          <DialogTitle>Create New Vendor Candidate</DialogTitle>
          <DialogDescription>
            새 Vendor Candidate 정보를 입력하고 <b>Create</b> 버튼을 누르세요.
          </DialogDescription>
        </DialogHeader>

        {/* shadcn/ui Form을 이용해 react-hook-form과 연결 */}
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {/* Company Name 필드 */}
              <FormField
                control={form.control}
                name="companyName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Company Name <span className="text-red-500">*</span></FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Enter company name"
                        {...field}
                        disabled={isSubmitting}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Tax ID 필드 (새로 추가) */}
              <FormField
                control={form.control}
                name="taxId"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Tax ID</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Tax identification number"
                        {...field}
                        disabled={isSubmitting}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Contact Email 필드 */}
              <FormField
                control={form.control}
                name="contactEmail"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Contact Email</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="email@example.com"
                        type="email"
                        {...field}
                        disabled={isSubmitting}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Contact Phone 필드 */}
              <FormField
                control={form.control}
                name="contactPhone"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Contact Phone</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="+82-10-1234-5678"
                        {...field}
                        disabled={isSubmitting}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Address 필드 */}
              <FormField
                control={form.control}
                name="address"
                render={({ field }) => (
                  <FormItem className="col-span-full">
                    <FormLabel>Address</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Company address"
                        {...field}
                        disabled={isSubmitting}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Country 필드 */}
              <FormField
                control={form.control}
                name="country"
                render={({ field }) => {
                  const selectedCountry = countryArray.find(
                    (c) => c.code === field.value
                  )
                  return (
                    <FormItem>
                      <FormLabel>Country</FormLabel>
                      <Popover>
                        <PopoverTrigger asChild>
                          <FormControl>
                            <Button
                              variant="outline"
                              role="combobox"
                              className={cn(
                                "w-full justify-between",
                                !field.value && "text-muted-foreground"
                              )}
                              disabled={isSubmitting}
                            >
                              {selectedCountry
                                ? selectedCountry.label
                                : "Select a country"}
                              <ChevronsUpDown className="ml-2 h-4 w-4 opacity-50" />
                            </Button>
                          </FormControl>
                        </PopoverTrigger>
                        <PopoverContent className="w-[300px] p-0">
                          <Command>
                            <CommandInput placeholder="Search country..." />
                            <CommandList>
                              <CommandEmpty>No country found.</CommandEmpty>
                              <CommandGroup className="max-h-[300px] overflow-y-auto">
                                {countryArray.map((country) => (
                                  <CommandItem
                                    key={country.code}
                                    value={country.label}
                                    onSelect={() =>
                                      field.onChange(country.code)
                                    }
                                  >
                                    <Check
                                      className={cn(
                                        "mr-2 h-4 w-4",
                                        country.code === field.value
                                          ? "opacity-100"
                                          : "opacity-0"
                                      )}
                                    />
                                    {country.label}
                                  </CommandItem>
                                ))}
                              </CommandGroup>
                            </CommandList>
                          </Command>
                        </PopoverContent>
                      </Popover>
                      <FormMessage />
                    </FormItem>
                  )
                }}
              />

              {/* Source 필드 */}
              <FormField
                control={form.control}
                name="source"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Source <span className="text-red-500">*</span></FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Where this candidate was found"
                        {...field}
                        disabled={isSubmitting}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />


              {/* Items 필드 (새로 추가) */}
              <FormField
                control={form.control}
                name="items"
                render={({ field }) => (
                  <FormItem className="col-span-full">
                    <FormLabel>Items <span className="text-red-500">*</span></FormLabel>
                    <FormControl>
                      <Textarea
                        placeholder="List of items or products this vendor provides"
                        className="min-h-[80px]"
                        {...field}
                        disabled={isSubmitting}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Remark 필드 (새로 추가) */}
              <FormField
                control={form.control}
                name="remark"
                render={({ field }) => (
                  <FormItem className="col-span-full">
                    <FormLabel>Remarks</FormLabel>
                    <FormControl>
                      <Textarea
                        placeholder="Additional notes or comments"
                        className="min-h-[80px]"
                        {...field}
                        disabled={isSubmitting}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

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