summaryrefslogtreecommitdiff
path: root/lib/basic-contract/template/create-revision-dialog.tsx
blob: 262df6ba4a1b9c441808e35db2ae35b87122b0c5 (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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
"use client";

import * as React from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { toast } from "sonner";
import { v4 as uuidv4 } from 'uuid';
import { Copy, FileText, Loader } from "lucide-react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  FormDescription,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Switch } from "@/components/ui/switch";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Dropzone,
  DropzoneZone,
  DropzoneUploadIcon,
  DropzoneTitle,
  DropzoneDescription,
  DropzoneInput
} from "@/components/ui/dropzone";
import { Progress } from "@/components/ui/progress";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { Badge } from "@/components/ui/badge";
import { useRouter } from "next/navigation";
import { BUSINESS_UNITS } from "@/config/basicContractColumnsConfig";
import { BasicContractTemplate } from "@/db/schema";

// 템플릿 이름 옵션 정의
const TEMPLATE_NAME_OPTIONS = [
  "준법서약 (한글)",
  "준법서약 (영문)",
  "기술자료 요구서", 
  "비밀유지 계약서",
  "표준하도급기본 계약서",
  "General GTC",
  "안전보건관리 약정서",
  "동반성장",
  "윤리규범 준수 서약서",
  "기술자료 동의서",
  "내국신용장 미개설 합의서",
  "직납자재 하도급대급등 연동제 의향서"
] as const;

// 리비전 생성 스키마 정의
const createRevisionSchema = z.object({
  revision: z.coerce.number().int().min(1),
  legalReviewRequired: z.boolean().default(false),
  
  // 적용 범위
  shipBuildingApplicable: z.boolean().default(false),
  windApplicable: z.boolean().default(false),
  pcApplicable: z.boolean().default(false),
  nbApplicable: z.boolean().default(false),
  rcApplicable: z.boolean().default(false),
  gyApplicable: z.boolean().default(false),
  sysApplicable: z.boolean().default(false),
  infraApplicable: z.boolean().default(false),
  
  file: z
    .instanceof(File, { message: "파일을 업로드해주세요." })
    .refine((file) => file.size <= 100 * 1024 * 1024, {
      message: "파일 크기는 100MB 이하여야 합니다.",
    })
    .refine(
      (file) => 
        file.type === 'application/msword' || 
        file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      { message: "워드 파일(.doc, .docx)만 업로드 가능합니다." }
    ),
}).refine((data) => {
  // 적어도 하나의 적용 범위는 선택되어야 함
  const scopeFields = [
    'shipBuildingApplicable', 'windApplicable', 'pcApplicable', 'nbApplicable',
    'rcApplicable', 'gyApplicable', 'sysApplicable', 'infraApplicable'
  ];
  
  const hasAnyScope = scopeFields.some(field => data[field as keyof typeof data] === true);
  return hasAnyScope;
}, {
  message: "적어도 하나의 적용 범위를 선택해야 합니다.",
  path: ["shipBuildingApplicable"],
});

type CreateRevisionFormValues = z.infer<typeof createRevisionSchema>;

interface CreateRevisionDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  baseTemplate: BasicContractTemplate | null;
  onSuccess?: () => void;
}

export function CreateRevisionDialog({ 
  open, 
  onOpenChange, 
  baseTemplate, 
  onSuccess 
}: CreateRevisionDialogProps) {
  const [isLoading, setIsLoading] = React.useState(false);
  const [selectedFile, setSelectedFile] = React.useState<File | null>(null);
  const [uploadProgress, setUploadProgress] = React.useState(0);
  const [showProgress, setShowProgress] = React.useState(false);
  const [suggestedRevision, setSuggestedRevision] = React.useState<number>(1);
  const router = useRouter();

  // 기본 템플릿의 다음 리비전 번호 계산
  React.useEffect(() => {
    if (baseTemplate) {
      setSuggestedRevision(baseTemplate.revision + 1);
    }
  }, [baseTemplate]);

  // 기본값 설정 (기존 템플릿의 설정을 상속)
  const defaultValues: Partial<CreateRevisionFormValues> = React.useMemo(() => {
    if (!baseTemplate) return {};
    
    return {
      revision: suggestedRevision,
      legalReviewRequired: baseTemplate.legalReviewRequired,
      shipBuildingApplicable: baseTemplate.shipBuildingApplicable,
      windApplicable: baseTemplate.windApplicable,
      pcApplicable: baseTemplate.pcApplicable,
      nbApplicable: baseTemplate.nbApplicable,
      rcApplicable: baseTemplate.rcApplicable,
      gyApplicable: baseTemplate.gyApplicable,
      sysApplicable: baseTemplate.sysApplicable,
      infraApplicable: baseTemplate.infraApplicable,
    };
  }, [baseTemplate, suggestedRevision]);

  // 폼 초기화
  const form = useForm<CreateRevisionFormValues>({
    resolver: zodResolver(createRevisionSchema),
    defaultValues,
    mode: "onChange",
  });

  // baseTemplate이 변경될 때 폼 값 재설정
  React.useEffect(() => {
    if (baseTemplate && defaultValues) {
      form.reset(defaultValues);
    }
  }, [baseTemplate, defaultValues, form]);

  // 파일 선택 핸들러
  const handleFileChange = (files: File[]) => {
    if (files.length > 0) {
      const file = files[0];
      setSelectedFile(file);
      form.setValue("file", file);
    }
  };

  // 모든 적용 범위 선택/해제
  const handleSelectAllScopes = (checked: boolean) => {
    BUSINESS_UNITS.forEach(unit => {
      form.setValue(unit.key as keyof CreateRevisionFormValues, checked);
    });
  };

  // 이전 설정 복사
  const handleCopyPreviousSettings = () => {
    if (!baseTemplate) return;
    
    BUSINESS_UNITS.forEach(unit => {
      const value = baseTemplate[unit.key as keyof BasicContractTemplate] as boolean;
      form.setValue(unit.key as keyof CreateRevisionFormValues, value);
    });
    
    form.setValue("legalReviewRequired", baseTemplate.legalReviewRequired);
    toast.success("이전 설정이 복사되었습니다.");
  };

  // 청크 크기 설정 (1MB)
  const CHUNK_SIZE = 1 * 1024 * 1024;

  // 파일을 청크로 분할하여 업로드하는 함수
  const uploadFileInChunks = async (file: File, fileId: string) => {
    const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
    setShowProgress(true);
    setUploadProgress(0);
    
    for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
      const start = chunkIndex * CHUNK_SIZE;
      const end = Math.min(start + CHUNK_SIZE, file.size);
      const chunk = file.slice(start, end);
      
      const formData = new FormData();
      formData.append('chunk', chunk);
      formData.append('filename', file.name);
      formData.append('chunkIndex', chunkIndex.toString());
      formData.append('totalChunks', totalChunks.toString());
      formData.append('fileId', fileId);
      
      try {
        const response = await fetch('/api/upload/basicContract/chunk', {
          method: 'POST',
          body: formData,
        });
        
        if (!response.ok) {
          throw new Error(`청크 업로드 실패: ${response.statusText}`);
        }
        
        // 진행률 업데이트
        const progress = Math.round(((chunkIndex + 1) / totalChunks) * 100);
        setUploadProgress(progress);
        
        const result = await response.json();
        
        // 마지막 청크인 경우 파일 경로 반환
        if (chunkIndex === totalChunks - 1) {
          return result;
        }
      } catch (error) {
        console.error(`청크 ${chunkIndex} 업로드 오류:`, error);
        throw error;
      }
    }
  };

  // 폼 제출 핸들러
  async function onSubmit(formData: CreateRevisionFormValues) {
    if (!baseTemplate) return;
    
    setIsLoading(true);
    try {
      if (!formData.file) {
        throw new Error("파일이 선택되지 않았습니다.");
      }
      
      // 고유 파일 ID 생성
      const fileId = uuidv4();
      
      // 파일 청크 업로드
      const uploadResult = await uploadFileInChunks(formData.file, fileId);
      
      if (!uploadResult.success) {
        throw new Error("파일 업로드에 실패했습니다.");
      }
      
      // 새 리비전 생성 API 호출
      const createResponse = await fetch('/api/basicContract/create-revision', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          baseTemplateId: baseTemplate.id,
          templateName: baseTemplate.templateName,
          revision: formData.revision,
          legalReviewRequired: formData.legalReviewRequired,
          shipBuildingApplicable: formData.shipBuildingApplicable,
          windApplicable: formData.windApplicable,
          pcApplicable: formData.pcApplicable,
          nbApplicable: formData.nbApplicable,
          rcApplicable: formData.rcApplicable,
          gyApplicable: formData.gyApplicable,
          sysApplicable: formData.sysApplicable,
          infraApplicable: formData.infraApplicable,
          fileName: uploadResult.fileName,
          filePath: uploadResult.filePath,
        }),
        next: { tags: ["basic-contract-templates"] },
      });
      
      const createResult = await createResponse.json();
      
      if (!createResult.success) {
        throw new Error(createResult.error || "리비전 생성에 실패했습니다.");
      }
      
      toast.success(`${baseTemplate.templateName} v${formData.revision} 리비전이 성공적으로 생성되었습니다.`);
      form.reset();
      setSelectedFile(null);
      onOpenChange(false);
      setShowProgress(false);
      onSuccess?.();
      router.refresh();
    } catch (error) {
      console.error("Submit error:", error);
      toast.error("리비전 생성 중 오류가 발생했습니다.");
    } finally {
      setIsLoading(false);
    }
  }

  // 모달이 닫힐 때 폼 초기화
  React.useEffect(() => {
    if (!open) {
      form.reset();
      setSelectedFile(null);
      setShowProgress(false);
      setUploadProgress(0);
    }
  }, [open, form]);

  // 현재 선택된 적용 범위 수
  const selectedScopesCount = BUSINESS_UNITS.filter(unit => 
    form.watch(unit.key as keyof CreateRevisionFormValues)
  ).length;

  if (!baseTemplate) return null;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px] h-[90vh] flex flex-col p-0">
        {/* 고정된 헤더 */}
        <DialogHeader className="p-6 pb-4 border-b">
          <DialogTitle className="flex items-center gap-2">
            <Copy className="h-5 w-5" />
            새 리비전 생성
          </DialogTitle>
          <DialogDescription>
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <FileText className="h-4 w-4" />
                <span className="font-medium">{baseTemplate.templateName}</span>
                <Badge variant="outline">현재 v{baseTemplate.revision}</Badge>
                <span>→</span>
                <Badge variant="default">새 v{form.watch("revision")}</Badge>
              </div>
              <p className="text-sm">
                기존 템플릿을 기반으로 새로운 리비전을 생성합니다.
                <span className="text-red-500 mt-1 block">* 표시된 항목은 필수 입력사항입니다.</span>
              </p>
            </div>
          </DialogDescription>
        </DialogHeader>

        {/* 스크롤 가능한 컨텐츠 영역 */}
        <div className="flex-1 overflow-y-auto px-6">
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6 py-4">
              {/* 리비전 정보 */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-lg">리비전 정보</CardTitle>
                  <CardDescription>
                    새로 생성할 리비전의 번호를 설정하세요
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <FormField
                    control={form.control}
                    name="revision"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>
                          리비전 번호 <span className="text-red-500">*</span>
                        </FormLabel>
                        <FormControl>
                          <Input 
                            type="number" 
                            min={baseTemplate.revision + 1}
                            {...field}
                            onChange={(e) => field.onChange(parseInt(e.target.value) || suggestedRevision)}
                          />
                        </FormControl>
                        <FormDescription>
                          권장 리비전: {suggestedRevision} (현재 리비전보다 큰 숫자여야 합니다)
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="legalReviewRequired"
                    render={({ field }) => (
                      <FormItem className="flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm">
                        <div className="space-y-0.5">
                          <FormLabel>법무검토 필요</FormLabel>
                          <FormDescription>
                            법무팀 검토가 필요한 템플릿인지 설정
                          </FormDescription>
                        </div>
                        <FormControl>
                          <Switch
                            checked={field.value}
                            onCheckedChange={field.onChange}
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />
                </CardContent>
              </Card>

              {/* 적용 범위 */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-lg">
                    적용 범위 <span className="text-red-500">*</span>
                  </CardTitle>
                  <CardDescription>
                    이 리비전이 적용될 사업부를 선택하세요. ({selectedScopesCount}개 선택됨)
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-2">
                      <Checkbox 
                        id="select-all"
                        checked={selectedScopesCount === BUSINESS_UNITS.length}
                        onCheckedChange={handleSelectAllScopes}
                      />
                      <label htmlFor="select-all" className="text-sm font-medium">
                        전체 선택
                      </label>
                    </div>
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      onClick={handleCopyPreviousSettings}
                    >
                      <Copy className="h-4 w-4 mr-1" />
                      이전 설정 복사
                    </Button>
                  </div>
                  
                  <Separator />
                  
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                    {BUSINESS_UNITS.map((unit) => (
                      <FormField
                        key={unit.key}
                        control={form.control}
                        name={unit.key as keyof CreateRevisionFormValues}
                        render={({ field }) => (
                          <FormItem className="flex flex-row items-start space-x-3 space-y-0">
                            <FormControl>
                              <Checkbox
                                checked={field.value as boolean}
                                onCheckedChange={field.onChange}
                              />
                            </FormControl>
                            <div className="space-y-1 leading-none">
                              <FormLabel className="text-sm font-normal">
                                {unit.label}
                              </FormLabel>
                            </div>
                          </FormItem>
                        )}
                      />
                    ))}
                  </div>
                  
                  {form.formState.errors.shipBuildingApplicable && (
                    <p className="text-sm text-destructive">
                      {form.formState.errors.shipBuildingApplicable.message}
                    </p>
                  )}
                </CardContent>
              </Card>

              {/* 파일 업로드 */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-lg">파일 업로드</CardTitle>
                  <CardDescription>
                    새 리비전의 템플릿 파일을 업로드하세요
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <FormField
                    control={form.control}
                    name="file"
                    render={() => (
                      <FormItem>
                        <FormLabel>
                          템플릿 파일 <span className="text-red-500">*</span>
                        </FormLabel>
                        <FormControl>
                          <Dropzone
                            onDrop={handleFileChange}
                            accept={{
                              'application/msword': ['.doc'],
                              'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['.docx']
                            }}
                          >
                            <DropzoneZone>
                              <DropzoneUploadIcon className="h-10 w-10 text-muted-foreground" />
                              <DropzoneTitle>
                                {selectedFile ? selectedFile.name : "워드 파일을 여기에 드래그하세요"}
                              </DropzoneTitle>
                              <DropzoneDescription>
                                {selectedFile
                                  ? `파일 크기: ${(selectedFile.size / (1024 * 1024)).toFixed(2)} MB`
                                  : "또는 클릭하여 워드 파일(.doc, .docx)을 선택하세요 (최대 100MB)"}
                              </DropzoneDescription>
                              <DropzoneInput />
                            </DropzoneZone>
                          </Dropzone>
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  
                  {showProgress && (
                    <div className="space-y-2 mt-4">
                      <div className="flex justify-between text-sm">
                        <span>업로드 진행률</span>
                        <span>{uploadProgress}%</span>
                      </div>
                      <Progress value={uploadProgress} />
                    </div>
                  )}
                </CardContent>
              </Card>
            </form>
          </Form>
        </div>

        {/* 고정된 푸터 */}
        <DialogFooter className="p-6 pt-4 border-t">
          <Button
            type="button"
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={isLoading}
          >
            취소
          </Button>
          <Button
            type="button"
            onClick={form.handleSubmit(onSubmit)}
            disabled={
              isLoading || 
              !form.watch("file") ||
              !BUSINESS_UNITS.some(unit => form.watch(unit.key as keyof CreateRevisionFormValues)) ||
              form.watch("revision") <= baseTemplate.revision
            }
          >
            {isLoading && <Loader className="mr-2 h-4 w-4 animate-spin" />}
            {isLoading ? "처리 중..." : "리비전 생성"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}