summaryrefslogtreecommitdiff
path: root/lib/esg-check-list/table/esg-evaluation-form-sheet.tsx
blob: be5ea73533e4536b7d1516866337eeb18b362b8e (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
"use client"

import * as React from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm, useFieldArray } from "react-hook-form"
import { z } from "zod"
import { toast } from "sonner"
import { Plus, X, Trash2 } from "lucide-react"
import { useTransition } from "react"

import { Button } from "@/components/ui/button"
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { ScrollArea } from "@/components/ui/scroll-area"

// 기존 서비스 함수 import
import { 
  getEsgEvaluationDetails, 
  createEsgEvaluationWithItemsEnhanced, 
  updateEsgEvaluationWithItems 
} from "../service" // 기존 서비스 파일 경로에 맞게 수정

import { EsgEvaluationsView } from "@/db/schema"

// 폼 스키마 정의
const evaluationFormSchema = z.object({
  serialNumber: z.string().min(1, "시리얼번호는 필수입니다"),
  category: z.string().min(1, "분류는 필수입니다"),
  inspectionItem: z.string().min(1, "점검항목은 필수입니다"),
  evaluationItems: z.array(
    z.object({
      evaluationItem: z.string().min(1, "평가항목은 필수입니다"),
      evaluationItemDescription: z.string().min(1, "평가항목 설명은 필수입니다"),
      answerOptions: z.array(
        z.object({
          answerText: z.string().min(1, "답변 내용은 필수입니다"),
          score: z.coerce.number().min(0, "점수는 0 이상이어야 합니다"),
        })
      ).min(1, "최소 1개의 답변 옵션이 필요합니다"),
    })
  ).min(1, "최소 1개의 평가항목이 필요합니다"),
})

type EvaluationFormData = z.infer<typeof evaluationFormSchema>

interface EsgEvaluationFormSheetProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  evaluation: EsgEvaluationsView | null
  onSuccess: () => void
}

export function EsgEvaluationFormSheet({
  open,
  onOpenChange,
  evaluation,
  onSuccess,
}: EsgEvaluationFormSheetProps) {
  const [isPending, startTransition] = useTransition()
  const isEdit = !!evaluation

  const form = useForm<EvaluationFormData>({
    resolver: zodResolver(evaluationFormSchema),
    defaultValues: {
      serialNumber: "",
      category: "",
      inspectionItem: "",
      evaluationItems: [
        {
          evaluationItem: "",
          evaluationItemDescription: "",
          answerOptions: [
            { answerText: "", score: 0 },
            { answerText: "", score: 0 },
          ],
        },
      ],
    },
  })


  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: "evaluationItems",
  })

  // 편집 모드일 때 기존 데이터 로드
  React.useEffect(() => {
    if (open && isEdit && evaluation) {
      // 기존 서비스 함수를 사용하여 상세 데이터 로드
      startTransition(async () => {
        try {
          const details = await getEsgEvaluationDetails(evaluation.id)
          console.log(details)
          
          if (details) {
            form.reset({
              serialNumber: details.serialNumber,
              category: details.category,
              inspectionItem: details.inspectionItem,
              evaluationItems: details.evaluationItems?.map((item) => ({
                evaluationItem: item.evaluationItem,
                evaluationItemDescription: item.evaluationItemDescription,
                answerOptions: item.answerOptions?.map((option) => ({
                  answerText: option.answerText,
                  score: parseFloat(option.score),
                })) || [],
              })) || [],
            })
          }
        } catch (error) {
          console.error('Error loading evaluation for edit:', error)
          toast.error(error instanceof Error ? error.message : '편집할 데이터를 불러오는데 실패했습니다.')
        }
      })
    } else if (open && !isEdit) {
      // 새 생성 모드
      form.reset({
        serialNumber: "",
        category: "",
        inspectionItem: "",
        evaluationItems: [
          {
            evaluationItem: "",
            evaluationItemDescription: "",
            answerOptions: [
              { answerText: "", score: 0 },
              { answerText: "", score: 0 },
            ],
          },
        ],
      })
    }
  }, [open, isEdit, evaluation, form])

  const onSubmit = async (data: EvaluationFormData) => {
    startTransition(async () => {
      try {
        // 폼 데이터를 서비스 함수에 맞는 형태로 변환
        const evaluationData = {
          serialNumber: data.serialNumber,
          category: data.category,
          inspectionItem: data.inspectionItem,
        }

        const items = data.evaluationItems.map(item => ({
          evaluationItem: item.evaluationItem,
          evaluationItemDescription: item.evaluationItemDescription,
          answerOptions: item.answerOptions.map(option => ({
            answerText: option.answerText,
            score: option.score,
          }))
        }))

        if (isEdit && evaluation) {
          // 수정 - 전체 평가표 수정
          await updateEsgEvaluationWithItems(evaluation.id, evaluationData, items)
          toast.success('평가표가 수정되었습니다.')
        } else {
          // 생성 - 평가표와 항목들 함께 생성
          await createEsgEvaluationWithItemsEnhanced(evaluationData, items)
          toast.success('평가표가 생성되었습니다.')
        }
        
        onSuccess()
        onOpenChange(false)
      } catch (error) {
        console.error('Error saving evaluation:', error)
        toast.error(
          error instanceof Error ? error.message : '저장 중 오류가 발생했습니다.'
        )
      }
    })
  }

  if (!open) return null

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="w-[900px] sm:max-w-[900px] flex flex-col" style={{width:900, maxWidth:900}}>

        {/* 고정 헤더 */}
        <SheetHeader className="flex-shrink-0 pb-6">
          <SheetTitle>
            {isEdit ? 'ESG 평가표 수정' : '새 ESG 평가표 생성'}
          </SheetTitle>
          <SheetDescription>
            {isEdit
              ? '평가표의 정보를 수정합니다.'
              : '새로운 ESG 평가표를 생성합니다.'}
          </SheetDescription>
        </SheetHeader>

        <Form {...form}>
          <form 
            onSubmit={form.handleSubmit(onSubmit)} 
            className="flex flex-col flex-1 min-h-0"
          >
            {/* 스크롤 가능한 콘텐츠 영역 */}
            <ScrollArea className="flex-1 pr-4">
              <div className="space-y-6 pb-6">
                {/* 기본 정보 */}
                <Card>
                  <CardHeader>
                    <CardTitle>기본 정보</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <FormField
                      control={form.control}
                      name="serialNumber"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>시리얼번호</FormLabel>
                          <FormControl>
                            <Input placeholder="P-1" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="category"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>분류</FormLabel>
                          <FormControl>
                            <Input placeholder="정보공시" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="inspectionItem"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>점검항목</FormLabel>
                          <FormControl>
                          <Input placeholder="ESG 정보공시 형식" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </CardContent>
                </Card>

                {/* 평가항목들 */}
                <Card>
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <div>
                        <CardTitle>평가항목들</CardTitle>
                        <CardDescription>
                          각 평가항목과 해당 답변 옵션들을 설정합니다.
                        </CardDescription>
                      </div>
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={() =>
                          append({
                            evaluationItem: "",
                            evaluationItemDescription: "",
                            answerOptions: [
                              { answerText: "", score: 0 },
                              { answerText: "", score: 0 },
                            ],
                          })
                        }
                        disabled={isPending}
                      >
                        <Plus className="w-4 h-4 mr-2" />
                        항목 추가
                      </Button>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      {fields.map((field, index) => (
                        <EvaluationItemForm
                          key={field.id}
                          index={index}
                          form={form}
                          onRemove={() => remove(index)}
                          canRemove={fields.length > 1}
                          disabled={isPending}
                        />
                      ))}
                    </div>
                  </CardContent>
                </Card>
              </div>
            </ScrollArea>

            {/* 고정 버튼 영역 */}
            <div className="flex-shrink-0 flex justify-end gap-2 pt-4 border-t bg-background">
              <Button
                type="button"
                variant="outline"
                onClick={() => onOpenChange(false)}
                disabled={isPending}
              >
                취소
              </Button>
              <Button type="submit" disabled={isPending}>
                {isPending
                  ? '저장 중...'
                  : isEdit
                  ? '수정하기'
                  : '생성하기'}
              </Button>
            </div>
          </form>
        </Form>
      </SheetContent>
    </Sheet>
  )
}

// 평가항목 개별 폼 컴포넌트
interface EvaluationItemFormProps {
  index: number
  form: any
  onRemove: () => void
  canRemove: boolean
  disabled?: boolean
}

function EvaluationItemForm({
  index,
  form,
  onRemove,
  canRemove,
  disabled = false,
}: EvaluationItemFormProps) {
  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: `evaluationItems.${index}.answerOptions`,
  })


  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <CardTitle className="text-lg">평가항목 {index + 1}</CardTitle>
          {canRemove && (
            <Button
              type="button"
              variant="ghost"
              size="sm"
              onClick={onRemove}
              className="text-destructive hover:text-destructive"
              disabled={disabled}
            >
              <Trash2 className="w-4 h-4" />
            </Button>
          )}
        </div>
      </CardHeader>
      <CardContent className="space-y-4">
        <FormField
          control={form.control}
          name={`evaluationItems.${index}.evaluationItem`}
          render={({ field }) => (
            <FormItem>
              <FormLabel>평가항목</FormLabel>
              <FormControl>
              <Input placeholder="평가항목을 입력해주세요..." {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name={`evaluationItems.${index}.evaluationItemDescription`}
          render={({ field }) => (
            <FormItem>
              <FormLabel>평가항목 설명</FormLabel>
              <FormControl>
                <Textarea
                  placeholder="평가할 항목에 대한 설명을 입력해주세요..."
                  {...field}
                  disabled={disabled}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <div>
          <div className="flex items-center justify-between mb-2">
            <label className="text-sm font-medium">답변 옵션들</label>
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={() => append({ answerText: "", score: 0 })}
              disabled={disabled}
            >
              <Plus className="w-4 h-4 mr-2" />
              옵션 추가
            </Button>
          </div>
          
          <div className="space-y-2">
            {fields.map((option, optionIndex) => (
              <div key={option.id} className="flex gap-2">
                <FormField
                  control={form.control}
                  name={`evaluationItems.${index}.answerOptions.${optionIndex}.answerText`}
                  render={({ field }) => (
                    <FormItem className="flex-1">
                      <FormControl>
                        <Input 
                          placeholder="답변 내용" 
                          {...field} 
                          disabled={disabled}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name={`evaluationItems.${index}.answerOptions.${optionIndex}.score`}
                  render={({ field }) => (
                    <FormItem className="w-24">
                      <FormControl>
                        <Input
                          type="number"
                          step="0.1"
                          placeholder="점수"
                          {...field}
                          disabled={disabled}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                {fields.length > 1 && (
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => remove(optionIndex)}
                    className="text-destructive hover:text-destructive"
                    disabled={disabled}
                  >
                    <X className="w-4 h-4" />
                  </Button>
                )}
              </div>
            ))}
          </div>
        </div>
      </CardContent>
    </Card>
  )
}