summaryrefslogtreecommitdiff
path: root/lib/tech-vendor-candidates/table/add-candidates-dialog.tsx
diff options
context:
space:
mode:
Diffstat (limited to 'lib/tech-vendor-candidates/table/add-candidates-dialog.tsx')
-rw-r--r--lib/tech-vendor-candidates/table/add-candidates-dialog.tsx394
1 files changed, 394 insertions, 0 deletions
diff --git a/lib/tech-vendor-candidates/table/add-candidates-dialog.tsx b/lib/tech-vendor-candidates/table/add-candidates-dialog.tsx
new file mode 100644
index 00000000..31c39137
--- /dev/null
+++ b/lib/tech-vendor-candidates/table/add-candidates-dialog.tsx
@@ -0,0 +1,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<span className="text-red-500">*</span></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>
+ )
+} \ No newline at end of file