summaryrefslogtreecommitdiff
path: root/lib/basic-contract/gtc-vendor/clause-variable-settings-dialog.tsx
blob: 36d47403623f5fbb2359e73b3b85e7af6a662a18 (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
"use client"

import * as React from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { Dialog, 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 { Badge } from "@/components/ui/badge"

import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  FormDescription,
} from "@/components/ui/form"
import { Loader, Settings2, Wand2, Copy, Eye } from "lucide-react"
import { toast } from "sonner"
import { cn } from "@/lib/utils"

import { updateGtcClauseSchema, type UpdateGtcClauseSchema } from "@/lib/gtc-contract/gtc-clauses/validations"
import { updateGtcClause } from "@/lib/gtc-contract/gtc-clauses/service"
import { type GtcClauseTreeView } from "@/db/schema/gtc"
import { useSession } from "next-auth/react"

interface ClauseVariableSettingsDialogProps
  extends React.ComponentPropsWithRef<typeof Dialog> {
  clause: GtcClauseTreeView | null
  onSuccess?: () => void
}

export function ClauseVariableSettingsDialog({ 
  clause, 
  onSuccess,
  ...props 
}: ClauseVariableSettingsDialogProps) {
  const [isUpdatePending, startUpdateTransition] = React.useTransition()
  const [showPreview, setShowPreview] = React.useState(false)
  const { data: session } = useSession()

  const currentUserId = React.useMemo(() => {
    return session?.user?.id ? Number(session.user.id) : null
  }, [session])

  const form = useForm<UpdateGtcClauseSchema>({
    resolver: zodResolver(updateGtcClauseSchema),
    defaultValues: {
      numberVariableName: "",
      subtitleVariableName: "",
      contentVariableName: "",
      editReason: "",
    },
  })

  // clause가 변경될 때 폼 데이터 설정
  React.useEffect(() => {
    if (clause) {
      form.reset({
        numberVariableName: clause.numberVariableName || "",
        subtitleVariableName: clause.subtitleVariableName || "",
        contentVariableName: clause.contentVariableName || "",
        editReason: "",
      })
    }
  }, [clause, form])

  const generateAutoVariableNames = () => {
    if (!clause) return

    const fullPath = clause.fullPath || clause.itemNumber

    console.log(clause.fullPath,fullPath,"fullPath")
    console.log(clause, "clause")

    const prefix = "CLAUSE_" + fullPath.replace(/\./g, "_")
    
    form.setValue("numberVariableName", `${prefix}_NUMBER`)
    form.setValue("subtitleVariableName", `${prefix}_SUBTITLE`)
    form.setValue("contentVariableName", `${prefix}_CONTENT`)
    
    toast.success("변수명이 자동 생성되었습니다.")
  }

  const copyCurrentVariableNames = () => {
    if (!clause) return
    
    const currentVars = {
      number: clause.autoNumberVariable,
      subtitle: clause.autoSubtitleVariable,
      content: clause.autoContentVariable,
    }
    
    form.setValue("numberVariableName", currentVars.number)
    form.setValue("subtitleVariableName", currentVars.subtitle)
    form.setValue("contentVariableName", currentVars.content)
    
    toast.success("현재 변수명이 복사되었습니다.")
  }

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

      try {
        const result = await updateGtcClause(clause.id, {
          numberVariableName: data.numberVariableName,
          subtitleVariableName: data.subtitleVariableName,
          contentVariableName: data.contentVariableName,
          editReason: data.editReason || "PDFTron 변수명 설정",
          updatedById: currentUserId,
        })

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

        form.reset()
        props.onOpenChange?.(false)
        toast.success("변수명이 설정되었습니다!")
        onSuccess?.()
      } catch (error) {
        toast.error("변수명 설정 중 오류가 발생했습니다.")
      }
    })
  }

  function handleDialogOpenChange(nextOpen: boolean) {
    if (!nextOpen) {
      form.reset()
      setShowPreview(false)
    }
    props.onOpenChange?.(nextOpen)
  }

  const currentNumberVar = form.watch("numberVariableName")
  const currentSubtitleVar = form.watch("subtitleVariableName")
  const currentContentVar = form.watch("contentVariableName")
  
  const hasAllVariables = currentNumberVar && currentSubtitleVar && currentContentVar

  if (!clause) {
    return null
  }

  return (
    <Dialog {...props} onOpenChange={handleDialogOpenChange}>
      <DialogContent className="max-w-2xl max-h-[90vh] flex flex-col">
        <DialogHeader className="flex-shrink-0">
          <DialogTitle className="flex items-center gap-2">
            <Settings2 className="h-5 w-5" />
            PDFTron 변수명 설정
          </DialogTitle>
          <DialogDescription>
            조항의 PDFTron 변수명을 설정하여 문서 생성에 사용합니다.
          </DialogDescription>
        </DialogHeader>

        {/* 조항 정보 */}
        <div className="p-3 bg-muted/50 rounded-lg text-sm flex-shrink-0">
          <div className="font-medium mb-2">대상 조항</div>
          <div className="space-y-1 text-muted-foreground">
            <div className="flex items-center gap-2">
              <Badge variant="outline">{clause.itemNumber}</Badge>
              <span>{clause.subtitle}</span>
              <Badge variant={clause.hasAllVariableNames ? "default" : "destructive"}>
                {clause.hasAllVariableNames ? "설정됨" : "미설정"}
              </Badge>
            </div>
            {clause.fullPath && (
              <div className="text-xs">경로: {clause.fullPath}</div>
            )}
            {clause.category && (
              <div className="text-xs">분류: {clause.category}</div>
            )}
          </div>
        </div>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col flex-1 min-h-0">
            <div className="flex-1 overflow-y-auto px-1">
              <div className="space-y-4 py-4">
                {/* 자동 생성 버튼들 */}
                <div className="flex gap-2">
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={generateAutoVariableNames}
                    className="flex items-center gap-2"
                  >
                    <Wand2 className="h-4 w-4" />
                    자동 생성
                  </Button>
                  
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={copyCurrentVariableNames}
                    className="flex items-center gap-2"
                  >
                    <Copy className="h-4 w-4" />
                    현재값 복사
                  </Button>
                  
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => setShowPreview(!showPreview)}
                    className="flex items-center gap-2"
                  >
                    <Eye className="h-4 w-4" />
                    {showPreview ? "미리보기 숨기기" : "미리보기"}
                  </Button>
                </div>

                {/* 현재 설정된 변수명 표시 */}
                {clause.hasAllVariableNames && (
                  <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg">
                    <div className="text-sm font-medium text-blue-900 mb-2">현재 설정된 변수명</div>
                    <div className="space-y-1 text-xs">
                      <div><code className="bg-blue-100 px-1 rounded">{clause.numberVariableName}</code></div>
                      <div><code className="bg-blue-100 px-1 rounded">{clause.subtitleVariableName}</code></div>
                      <div><code className="bg-blue-100 px-1 rounded">{clause.contentVariableName}</code></div>
                    </div>
                  </div>
                )}

                {/* 변수명 입력 필드들 */}
                <div className="space-y-4">
                  <FormField
                    control={form.control}
                    name="numberVariableName"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>채번 변수명 *</FormLabel>
                        <FormControl>
                          <Input 
                            placeholder="예: CLAUSE_1_NUMBER, HEADER_1_NUM 등"
                            {...field} 
                          />
                        </FormControl>
                        <FormDescription>
                          문서에서 조항 번호를 표시할 변수명입니다.
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="subtitleVariableName"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>소제목 변수명 *</FormLabel>
                        <FormControl>
                          <Input 
                            placeholder="예: CLAUSE_1_SUBTITLE, HEADER_1_TITLE 등"
                            {...field} 
                          />
                        </FormControl>
                        <FormDescription>
                          문서에서 조항 제목을 표시할 변수명입니다.
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="contentVariableName"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>상세항목 변수명 *</FormLabel>
                        <FormControl>
                          <Input 
                            placeholder="예: CLAUSE_1_CONTENT, BODY_1_TEXT 등"
                            {...field} 
                          />
                        </FormControl>
                        <FormDescription>
                          문서에서 조항 내용을 표시할 변수명입니다.
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                {/* 미리보기 */}
                {showPreview && hasAllVariables && (
                  <div className="p-3 bg-gray-50 border rounded-lg">
                    <div className="text-sm font-medium mb-2">PDFTron 템플릿 미리보기</div>
                    <div className="space-y-2 text-xs font-mono bg-white p-2 rounded border">
                      <div className="text-blue-600">{"{{" + currentNumberVar + "}}"}. {"{{" + currentSubtitleVar + "}}"}</div>
                      <div className="text-gray-600 ml-4">{"{{" + currentContentVar + "}}"}</div>
                    </div>
                    <div className="text-xs text-muted-foreground mt-2">
                      실제 문서에서 위와 같은 형태로 표시됩니다.
                    </div>
                  </div>
                )}

                {/* 편집 사유 */}
                <FormField
                  control={form.control}
                  name="editReason"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>편집 사유 (선택사항)</FormLabel>
                      <FormControl>
                        <Textarea
                          placeholder="변수명 설정 사유를 입력하세요..."
                          {...field}
                          rows={2}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </div>

            <DialogFooter className="flex-shrink-0 border-t pt-4">
              <Button
                type="button"
                variant="outline"
                onClick={() => props.onOpenChange?.(false)}
                disabled={isUpdatePending}
              >
                Cancel
              </Button>
              <Button 
                type="submit" 
                disabled={isUpdatePending || !hasAllVariables}
              >
                {isUpdatePending && (
                  <Loader
                    className="mr-2 size-4 animate-spin"
                    aria-hidden="true"
                  />
                )}
                <Settings2 className="mr-2 h-4 w-4" />
                Save Variables
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}