summaryrefslogtreecommitdiff
path: root/components/vendor-regular-registrations/additional-info-dialog.tsx
blob: 303c6d7e53edc02c40a11e6f368ad0c2ed595a0d (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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
"use client";

import * as React from "react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";

import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Plus, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { 
  saveVendorBusinessContacts, 
  saveVendorAdditionalInfo,
  fetchVendorRegistrationStatus 
} from "@/lib/vendor-regular-registrations/service";

// 업무담당자 정보 스키마
const businessContactSchema = z.object({
  contactType: z.enum(["sales", "design", "delivery", "quality", "tax_invoice"]),
  contactName: z.string().min(1, "담당자명은 필수입니다"),
  position: z.string().min(1, "직급은 필수입니다"),
  department: z.string().min(1, "부서는 필수입니다"),
  responsibility: z.string().min(1, "담당업무는 필수입니다"),
  email: z.string().email("올바른 이메일 형식이 아닙니다"),
});

// 추가정보 스키마
const additionalInfoSchema = z.object({
  businessType: z.string().min(1, "사업유형은 필수입니다"),
  industryType: z.string().min(1, "산업유형은 필수입니다"),
  companySize: z.string().min(1, "기업규모는 필수입니다"),
  revenue: z.string().min(1, "매출액은 필수입니다"),
  factoryEstablishedDate: z.string().min(1, "공장설립일은 필수입니다"),
  preferredContractTerms: z.string().min(1, "선호계약조건은 필수입니다"),
});

// 전체 폼 스키마
const formSchema = z.object({
  businessContacts: z.array(businessContactSchema).min(5, "모든 업무담당자 정보를 입력해주세요"),
  additionalInfo: additionalInfoSchema,
});

type FormData = z.infer<typeof formSchema>;

interface AdditionalInfoDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  vendorId: number;
  onSave?: () => void;
  readonly?: boolean;
}

const contactTypes = [
  { value: "sales", label: "영업", required: true },
  { value: "design", label: "설계", required: true },
  { value: "delivery", label: "납기", required: true },
  { value: "quality", label: "품질", required: true },
  { value: "tax_invoice", label: "세금계산서", required: true },
];



export function AdditionalInfoDialog({
  open,
  onOpenChange,
  vendorId,
  onSave,
  readonly = false,
}: AdditionalInfoDialogProps) {
  const [saving, setSaving] = useState(false);
  const [loading, setLoading] = useState(false);

  const form = useForm<FormData>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      businessContacts: contactTypes.map(type => ({
        contactType: type.value as any,
        contactName: "",
        position: "",
        department: "",
        responsibility: "",
        email: "",
      })),
      additionalInfo: {
        businessType: "",
        industryType: "",
        companySize: "",
        revenue: "",
        factoryEstablishedDate: "",
        preferredContractTerms: "",
      },
    },
  });

  // 기존 데이터 로드
  const loadExistingData = async () => {
    if (!vendorId || !open) return;
    
    setLoading(true);
    try {
      const result = await fetchVendorRegistrationStatus(vendorId);
      if (result.success && result.data) {
        const { businessContacts, additionalInfo } = result.data;
        
        // 업무담당자 데이터 설정
        const contactsData = contactTypes.map(type => {
          const existingContact = businessContacts.find(c => c.contactType === type.value);
          return existingContact ? {
            contactType: existingContact.contactType,
            contactName: existingContact.contactName,
            position: existingContact.position,
            department: existingContact.department,
            responsibility: existingContact.responsibility,
            email: existingContact.email,
          } : {
            contactType: type.value as any,
            contactName: "",
            position: "",
            department: "",
            responsibility: "",
            email: "",
          };
        });
        
        // 추가정보 데이터 설정  
        const additionalInfoData = additionalInfo as any;
        const additionalData = {
          businessType: additionalInfoData?.businessType || "",
          industryType: additionalInfoData?.industryType || "",
          companySize: additionalInfoData?.companySize || "",
          revenue: additionalInfoData?.revenue || "",
          factoryEstablishedDate: additionalInfoData?.factoryEstablishedDate 
            ? new Date(additionalInfoData.factoryEstablishedDate).toISOString().split('T')[0] 
            : "",
          preferredContractTerms: additionalInfoData?.preferredContractTerms || "",
        };
        
        // 폼 데이터 업데이트
        form.reset({
          businessContacts: contactsData,
          additionalInfo: additionalData,
        });
      }
    } catch (error) {
      console.error("Error loading existing data:", error);
      toast.error("기존 데이터를 불러오는 중 오류가 발생했습니다.");
    } finally {
      setLoading(false);
    }
  };

  // 다이얼로그가 열릴 때 데이터 로드
  React.useEffect(() => {
    loadExistingData();
  }, [vendorId, open]);

  const handleSave = async (data: FormData) => {
    setSaving(true);
    try {
      // 업무담당자 정보 저장
      const contactsResult = await saveVendorBusinessContacts(vendorId, data.businessContacts);
      if (!contactsResult.success) {
        throw new Error(contactsResult.error);
      }

      // 추가정보 저장
      const additionalResult = await saveVendorAdditionalInfo(vendorId, data.additionalInfo);
      if (!additionalResult.success) {
        throw new Error(additionalResult.error);
      }
      
      toast.success("추가정보가 저장되었습니다.");
      onSave?.();
      onOpenChange(false);
    } catch (error) {
      console.error("Error saving additional info:", error);
      toast.error(error instanceof Error ? error.message : "추가정보 저장 중 오류가 발생했습니다.");
    } finally {
      setSaving(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{readonly ? "추가정보 조회" : "추가정보 입력"}</DialogTitle>
          <p className="text-sm text-muted-foreground">
            {readonly 
              ? "정규업체 등록을 위한 추가 정보를 조회합니다."
              : "정규업체 등록을 위한 추가정보를 입력해주세요. * 표시는 필수 입력 항목입니다."
            }
          </p>
        </DialogHeader>

        {loading ? (
          <div className="p-8 text-center">
            <div className="text-sm text-muted-foreground">데이터를 불러오는 중...</div>
          </div>
        ) : (

        <Form {...form}>
          <form onSubmit={form.handleSubmit(handleSave)}>
            <Tabs defaultValue="contacts" className="w-full">
              <TabsList className="grid w-full grid-cols-2">
                <TabsTrigger value="contacts">업무담당자 정보</TabsTrigger>
                <TabsTrigger value="additional">추가정보</TabsTrigger>
              </TabsList>

              <TabsContent value="contacts" className="space-y-4">
                <div className="space-y-4">
                  {contactTypes.map((contactType, index) => (
                    <Card key={contactType.value}>
                      <CardHeader className="pb-3">
                        <CardTitle className="text-lg flex items-center gap-2">
                          {contactType.label} 담당자
                        </CardTitle>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        <div className="grid grid-cols-2 gap-4">
                          <FormField
                            control={form.control}
                            name={`businessContacts.${index}.contactName`}
                            render={({ field }) => (
                              <FormItem>
                                <FormLabel>담당자명 {!readonly && "*"}</FormLabel>
                                <FormControl>
                                  <Input 
                                    placeholder={readonly ? "" : "담당자명 입력"} 
                                    readOnly={readonly}
                                    {...field} 
                                  />
                                </FormControl>
                                <FormMessage />
                              </FormItem>
                            )}
                          />
                          <FormField
                            control={form.control}
                            name={`businessContacts.${index}.position`}
                            render={({ field }) => (
                              <FormItem>
                                <FormLabel>직급 {!readonly && "*"}</FormLabel>
                                <FormControl>
                                  <Input 
                                    placeholder={readonly ? "" : "직급 입력"} 
                                    readOnly={readonly}
                                    {...field} 
                                  />
                                </FormControl>
                                <FormMessage />
                              </FormItem>
                            )}
                          />
                        </div>
                        <div className="grid grid-cols-2 gap-4">
                          <FormField
                            control={form.control}
                            name={`businessContacts.${index}.department`}
                            render={({ field }) => (
                              <FormItem>
                                <FormLabel>부서 {!readonly && "*"}</FormLabel>
                                <FormControl>
                                  <Input 
                                    placeholder={readonly ? "" : "부서명 입력"} 
                                    readOnly={readonly}
                                    {...field} 
                                  />
                                </FormControl>
                                <FormMessage />
                              </FormItem>
                            )}
                          />
                          <FormField
                            control={form.control}
                            name={`businessContacts.${index}.email`}
                            render={({ field }) => (
                              <FormItem>
                                <FormLabel>Email {!readonly && "*"}</FormLabel>
                                <FormControl>
                                  <Input 
                                    placeholder={readonly ? "" : "이메일 입력"} 
                                    type="email" 
                                    readOnly={readonly}
                                    {...field} 
                                  />
                                </FormControl>
                                <FormMessage />
                              </FormItem>
                            )}
                          />
                        </div>
                        <FormField
                          control={form.control}
                          name={`businessContacts.${index}.responsibility`}
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>담당업무 {!readonly && "*"}</FormLabel>
                              <FormControl>
                                <Textarea 
                                  placeholder={readonly ? "" : "담당업무 상세 입력"} 
                                  className="h-20"
                                  readOnly={readonly}
                                  {...field} 
                                />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                      </CardContent>
                    </Card>
                  ))}
                </div>
              </TabsContent>

              <TabsContent value="additional" className="space-y-4">
                <Card>
                  <CardHeader>
                    <CardTitle>회사 추가정보</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      <FormField
                        control={form.control}
                        name="additionalInfo.businessType"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>사업유형 {!readonly && "*"}</FormLabel>
                            <FormControl>
                              <Input 
                                placeholder={readonly ? "" : "사업유형 입력"} 
                                readOnly={readonly}
                                {...field} 
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={form.control}
                        name="additionalInfo.industryType"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>산업유형 {!readonly && "*"}</FormLabel>
                            <FormControl>
                              <Input 
                                placeholder={readonly ? "" : "산업유형 입력"} 
                                readOnly={readonly}
                                {...field} 
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <FormField
                        control={form.control}
                        name="additionalInfo.companySize"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>기업규모 {!readonly && "*"}</FormLabel>
                            <FormControl>
                              <Input 
                                placeholder={readonly ? "" : "기업규모 입력"} 
                                readOnly={readonly}
                                {...field} 
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={form.control}
                        name="additionalInfo.revenue"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>매출액 (억원) {!readonly && "*"}</FormLabel>
                            <FormControl>
                              <Input 
                                placeholder={readonly ? "" : "매출액 입력"} 
                                type="number"
                                readOnly={readonly}
                                {...field} 
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <FormField
                        control={form.control}
                        name="additionalInfo.factoryEstablishedDate"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>공장설립일 {!readonly && "*"}</FormLabel>
                            <FormControl>
                              <Input 
                                placeholder={readonly ? "" : "YYYY-MM-DD"} 
                                type="date"
                                readOnly={readonly}
                                {...field} 
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>
                    <FormField
                      control={form.control}
                      name="additionalInfo.preferredContractTerms"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>선호계약조건 {!readonly && "*"}</FormLabel>
                          <FormControl>
                            <Textarea 
                              placeholder={readonly ? "" : "선호하는 계약조건을 상세히 입력해주세요"} 
                              className="h-32"
                              readOnly={readonly}
                              {...field} 
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </CardContent>
                </Card>
              </TabsContent>
            </Tabs>

            <DialogFooter className="mt-6">
              {readonly ? (
                <Button
                  type="button"
                  onClick={() => onOpenChange(false)}
                >
                  닫기
                </Button>
              ) : (
                <>
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => onOpenChange(false)}
                    disabled={saving}
                  >
                    취소
                  </Button>
                  <Button type="submit" disabled={saving}>
                    {saving ? "저장 중..." : "저장"}
                  </Button>
                </>
              )}
            </DialogFooter>
          </form>
        </Form>
        )}
      </DialogContent>
    </Dialog>
  );
}