summaryrefslogtreecommitdiff
path: root/lib/basic-contract/gtc-vendor/update-gtc-clause-sheet.tsx
blob: 3487ebbf578ed86368081617b066e6200ef2b7b1 (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
// update-vendor-gtc-clause-sheet.tsx
"use client"

import * as React from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import { Loader, Info, AlertCircle } from "lucide-react"
import { useForm } from "react-hook-form"
import { toast } from "sonner"

import {
  Sheet,
  SheetClose,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Badge } from "@/components/ui/badge"
import { Label } from "@/components/ui/label"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  FormDescription,
} from "@/components/ui/form"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Separator } from "@/components/ui/separator"

import { type GtcClauseTreeView } from "@/db/schema/gtc"
import { updateVendorGtcClauseSchema, type UpdateVendorGtcClauseSchema } from "@/lib/gtc-contract/gtc-clauses/validations"
import { updateVendorGtcClause } from "@/lib/gtc-contract/gtc-clauses/service"
import { useSession } from "next-auth/react"
import { MarkdownImageEditor } from "./markdown-image-editor"
import { Checkbox } from "@/components/ui/checkbox"

interface ClauseImage {
  id: string
  url: string
  fileName: string
  size: number
  savedName?: string
  mimeType?: string
  width?: number
  height?: number
  hash?: string
}

export interface UpdateVendorGtcClauseSheetProps
  extends React.ComponentPropsWithRef<typeof Sheet> {
  gtcClause: GtcClauseTreeView | null
  vendorInfo?: any // 벤더 조항 정보
  documentId: number
  vendorId: number
  vendorName?: string
}

export function UpdateGtcClauseSheet ({ 
  gtcClause, 
  vendorInfo,
  documentId, 
  vendorId,
  vendorName,
  ...props 
}: UpdateVendorGtcClauseSheetProps) {
  const [isUpdatePending, startUpdateTransition] = React.useTransition()
  const { data: session } = useSession()
  const [images, setImages] = React.useState<ClauseImage[]>([])

  console.log(vendorInfo,"vendorInfo")
  
  const currentUserId = React.useMemo(() => {
    return session?.user?.id ? Number(session.user.id) : null
  }, [session])
  
  const form = useForm<UpdateVendorGtcClauseSchema>({
    resolver: zodResolver(updateVendorGtcClauseSchema),
    defaultValues: {
      modifiedItemNumber: "",
      modifiedCategory: "",
      modifiedSubtitle: "",
      modifiedContent: "",
      isNumberModified: false,
      isCategoryModified: false,
      isSubtitleModified: false,
      isContentModified: false,
      reviewStatus: "draft",
      negotiationNote: "",
      isExcluded: false,
    },
  })

  // 벤더 정보가 있으면 초기값 세팅
  React.useEffect(() => {
    if (vendorInfo) {
      form.reset({
        modifiedItemNumber: vendorInfo.modifiedItemNumber || "",
        modifiedCategory: vendorInfo.modifiedCategory || "",
        modifiedSubtitle: vendorInfo.modifiedSubtitle || "",
        modifiedContent: vendorInfo.modifiedContent || "",
        isNumberModified: vendorInfo.isNumberModified || false,
        isCategoryModified: vendorInfo.isCategoryModified || false,
        isSubtitleModified: vendorInfo.isSubtitleModified || false,
        isContentModified: vendorInfo.isContentModified || false,
        reviewStatus: vendorInfo.reviewStatus || "draft",
        negotiationNote: vendorInfo.negotiationNote || "",
        isExcluded: vendorInfo.isExcluded || false,
      })
      setImages((vendorInfo.images as any[]) || [])
    }
  }, [vendorInfo, form])

  async function onSubmit(input: UpdateVendorGtcClauseSchema) {
    startUpdateTransition(async () => {
      if (!gtcClause || !currentUserId) {
        toast.error("조항 정보를 찾을 수 없습니다.")
        return
      }

      try {
        const result = await updateVendorGtcClause({
          baseClauseId: gtcClause.id,
          documentId,
          vendorId,
          ...input,
          images,
          updatedById: currentUserId,
        })

        if (result.error) {
          toast.error(result.error)
          return
        }

        form.reset()
        props.onOpenChange?.(false)
        toast.success("벤더 협의 내용이 저장되었습니다!")
      } catch (error) {
        toast.error("벤더 협의 저장 중 오류가 발생했습니다.")
      }
    })
  }

  const getDepthBadge = (depth: number) => {
    const levels = ["1단계", "2단계", "3단계", "4단계", "5단계+"]
    return levels[depth] || levels[4]
  }

  const handleContentImageChange = (content: string, newImages: ClauseImage[]) => {
    form.setValue("modifiedContent", content)
    setImages(newImages)
  }

  return (
    <Sheet {...props}>
      <SheetContent className="flex flex-col sm:max-w-2xl h-full">
        <SheetHeader className="text-left flex-shrink-0">
          <SheetTitle>벤더 GTC 조항 협의</SheetTitle>
          <SheetDescription>
            {vendorName ? `${vendorName}과(와)의 조항 협의 내용을 입력하세요` : '벤더별 조항 수정사항을 입력하세요'}
          </SheetDescription>
        </SheetHeader>

        <div className="flex-1 overflow-y-auto">
          {/* 기존 조항 정보 (읽기 전용) */}
          <div className="space-y-4 p-4 bg-muted/30 rounded-lg mb-4">
            <div className="flex items-center justify-between">
              <h3 className="text-sm font-semibold">표준 조항 내용</h3>
              <Badge variant="outline">
                {getDepthBadge(gtcClause?.depth || 0)}
              </Badge>
            </div>
            
            <div className="space-y-3">
              <div>
                <Label className="text-xs text-muted-foreground">채번</Label>
                <div className="text-sm font-mono mt-1">{gtcClause?.itemNumber}</div>
              </div>
              
              {gtcClause?.category && (
                <div>
                  <Label className="text-xs text-muted-foreground">분류</Label>
                  <div className="text-sm mt-1">{gtcClause.category}</div>
                </div>
              )}
              
              <div>
                <Label className="text-xs text-muted-foreground">소제목</Label>
                <div className="text-sm font-medium mt-1">{gtcClause?.subtitle}</div>
              </div>
              
              {gtcClause?.content && (
                <div>
                  <Label className="text-xs text-muted-foreground">상세항목</Label>
                  <div className="text-sm mt-1 p-2 bg-background rounded border">
                    <pre className="whitespace-pre-wrap font-sans">{gtcClause.content}</pre>
                  </div>
                </div>
              )}
            </div>
          </div>

          <Separator className="my-4" />

          {/* 벤더별 수정 폼 */}
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4 p-4">
              <div className="flex items-center gap-2 mb-4">
                <AlertCircle className="h-4 w-4 text-blue-500" />
                <p className="text-sm text-muted-foreground">
                  수정할 항목에 체크하고 내용을 입력하세요. 체크하지 않은 항목은 표준 조항의 내용을 그대로 사용합니다.
                </p>
              </div>

              {/* 협의 상태 */}
              <FormField
                control={form.control}
                name="reviewStatus"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>협의 상태</FormLabel>
                    <Select onValueChange={field.onChange} defaultValue={field.value}>
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="협의 상태를 선택하세요" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="draft">초안</SelectItem>
                        <SelectItem value="pending">협의 대기</SelectItem>
                        <SelectItem value="reviewing">협의 중</SelectItem>
                        <SelectItem value="approved">승인됨</SelectItem>
                        <SelectItem value="rejected">거부됨</SelectItem>
                        <SelectItem value="revised">수정됨</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 제외 여부 */}
              <FormField
                control={form.control}
                name="isExcluded"
                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>
                        이 조항을 벤더 계약에서 제외
                      </FormLabel>
                      <FormDescription>
                        체크하면 최종 계약서에서 이 조항이 제외됩니다
                      </FormDescription>
                    </div>
                  </FormItem>
                )}
              />

              {/* 채번 수정 */}
              <div className="space-y-2 border rounded-lg p-3">
                <FormField
                  control={form.control}
                  name="isNumberModified"
                  render={({ field }) => (
                    <FormItem className="flex flex-row items-center space-x-3 space-y-0">
                      <FormControl>
                        <Checkbox
                          checked={field.value}
                          onCheckedChange={field.onChange}
                        />
                      </FormControl>
                      <FormLabel className="font-normal cursor-pointer">
                        채번 수정
                      </FormLabel>
                    </FormItem>
                  )}
                />
                
                {form.watch("isNumberModified") && (
                  <FormField
                    control={form.control}
                    name="modifiedItemNumber"
                    render={({ field }) => (
                      <FormItem>
                        <FormControl>
                          <Input 
                            placeholder="수정할 채번 입력"
                            {...field} 
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                )}
              </div>

              {/* 분류 수정 */}
              <div className="space-y-2 border rounded-lg p-3">
                <FormField
                  control={form.control}
                  name="isCategoryModified"
                  render={({ field }) => (
                    <FormItem className="flex flex-row items-center space-x-3 space-y-0">
                      <FormControl>
                        <Checkbox
                          checked={field.value}
                          onCheckedChange={field.onChange}
                        />
                      </FormControl>
                      <FormLabel className="font-normal cursor-pointer">
                        분류 수정
                      </FormLabel>
                    </FormItem>
                  )}
                />
                
                {form.watch("isCategoryModified") && (
                  <FormField
                    control={form.control}
                    name="modifiedCategory"
                    render={({ field }) => (
                      <FormItem>
                        <FormControl>
                          <Input 
                            placeholder="수정할 분류 입력"
                            {...field} 
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                )}
              </div>

              {/* 소제목 수정 */}
              <div className="space-y-2 border rounded-lg p-3">
                <FormField
                  control={form.control}
                  name="isSubtitleModified"
                  render={({ field }) => (
                    <FormItem className="flex flex-row items-center space-x-3 space-y-0">
                      <FormControl>
                        <Checkbox
                          checked={field.value}
                          onCheckedChange={field.onChange}
                        />
                      </FormControl>
                      <FormLabel className="font-normal cursor-pointer">
                        소제목 수정
                      </FormLabel>
                    </FormItem>
                  )}
                />
                
                {form.watch("isSubtitleModified") && (
                  <FormField
                    control={form.control}
                    name="modifiedSubtitle"
                    render={({ field }) => (
                      <FormItem>
                        <FormControl>
                          <Input 
                            placeholder="수정할 소제목 입력"
                            {...field} 
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                )}
              </div>

              {/* 내용 수정 */}
              <div className="space-y-2 border rounded-lg p-3">
                <FormField
                  control={form.control}
                  name="isContentModified"
                  render={({ field }) => (
                    <FormItem className="flex flex-row items-center space-x-3 space-y-0">
                      <FormControl>
                        <Checkbox
                          checked={field.value}
                          onCheckedChange={field.onChange}
                        />
                      </FormControl>
                      <FormLabel className="font-normal cursor-pointer">
                        상세항목 수정
                      </FormLabel>
                    </FormItem>
                  )}
                />
                
                {form.watch("isContentModified") && (
                  <FormField
                    control={form.control}
                    name="modifiedContent"
                    render={({ field }) => (
                      <FormItem>
                        <FormControl>
                          <MarkdownImageEditor
                            content={field.value || ""}
                            images={images}
                            onChange={handleContentImageChange}
                            placeholder="수정할 내용을 입력하세요..."
                            rows={6}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                )}
              </div>

              {/* 협의 이력 표시 섹션 */}
{vendorInfo?.negotiationHistory && vendorInfo.negotiationHistory.length > 0 && (
  <div className="space-y-3 mb-4">
    <h3 className="text-sm font-semibold">협의 이력</h3>
    <div className="border rounded-lg p-3 max-h-64 overflow-y-auto space-y-3">
      {vendorInfo.negotiationHistory.map((history, index) => (
        <div key={index} className="border-b pb-3 last:border-b-0 last:pb-0">
          <div className="flex justify-between text-xs text-muted-foreground mb-1">
            <div className="font-medium">
              {history.actorName || "시스템"}
              {history.previousStatus && history.newStatus && (
                <span className="ml-2 text-xs">
                  ({history.previousStatus} → {history.newStatus})
                </span>
              )}
            </div>
            <div>
              {new Date(history.createdAt).toLocaleString('ko-KR', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
              })}
            </div>
          </div>
          {history.comment && (
            <div className="text-sm p-2 bg-muted/30 rounded">
              {history.comment}
            </div>
          )}
        </div>
      ))}
    </div>
  </div>
)}

              {/* 협의 노트 */}
              <FormField
                control={form.control}
                name="negotiationNote"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>협의 메모</FormLabel>
                    <FormControl>
                      <Textarea
                        placeholder="협의 과정에서의 메모나 특이사항을 기록하세요..."
                        {...field}
                        rows={3}
                      />
                    </FormControl>
                    <FormDescription>
                      벤더와의 협의 내용이나 변경 사유를 기록합니다
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </form>
          </Form>
        </div>

        <SheetFooter className="gap-2 pt-2 sm:space-x-0 flex-shrink-0">
          <SheetClose asChild>
            <Button type="button" variant="outline">
              취소
            </Button>
          </SheetClose>

          <Button 
            onClick={form.handleSubmit(onSubmit)} 
            disabled={isUpdatePending}
          >
            {isUpdatePending && (
              <Loader
                className="mr-2 size-4 animate-spin"
                aria-hidden="true"
              />
            )}
            저장
          </Button>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  )
}