summaryrefslogtreecommitdiff
path: root/lib/basic-contract/gtc-vendor/bulk-update-gtc-clauses-dialog.tsx
blob: a9ef0f0e8271756c520978c894cc15d5d7be64e5 (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
"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 { Switch } from "@/components/ui/switch"

import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  FormDescription,
} from "@/components/ui/form"
import { Loader, Edit, AlertCircle } from "lucide-react"
import { toast } from "sonner"

import { bulkUpdateGtcClausesSchema, type BulkUpdateGtcClausesSchema } from "@/lib/gtc-contract/gtc-clauses/validations"
import { bulkUpdateGtcClauses } from "@/lib/gtc-contract/gtc-clauses/service"
import { type GtcClauseTreeView } from "@/db/schema/gtc"
import { useSession } from "next-auth/react"

interface BulkUpdateGtcClausesDialogProps
  extends React.ComponentPropsWithRef<typeof Dialog> {
  selectedClauses: GtcClauseTreeView[]
}

export function BulkUpdateGtcClausesDialog({ 
  selectedClauses, 
  ...props 
}: BulkUpdateGtcClausesDialogProps) {
  const [isUpdatePending, startUpdateTransition] = React.useTransition()
  const { data: session } = useSession()

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

  const form = useForm<BulkUpdateGtcClausesSchema>({
    resolver: zodResolver(bulkUpdateGtcClausesSchema),
    defaultValues: {
      clauseIds: selectedClauses.map(clause => clause.id),
      updates: {
        category: "",
        isActive: true,
      },
      editReason: "",
    },
  })

  React.useEffect(() => {
    if (selectedClauses.length > 0) {
      form.setValue("clauseIds", selectedClauses.map(clause => clause.id))
    }
  }, [selectedClauses, form])

  async function onSubmit(data: BulkUpdateGtcClausesSchema) {
    startUpdateTransition(async () => {
      if (!currentUserId) {
        toast.error("로그인이 필요합니다")
        return
      }

      try {
        const result = await bulkUpdateGtcClauses({
          ...data,
          updatedById: currentUserId
        })
        
        if (result.error) {
          toast.error(`에러: ${result.error}`)
          return
        }

        form.reset()
        props.onOpenChange?.(false)
        toast.success(`${selectedClauses.length}개의 조항이 수정되었습니다.`)
      } catch (error) {
        toast.error("조항 일괄 수정 중 오류가 발생했습니다.")
      }
    })
  }

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

  // 선택된 조항들의 통계
  const categoryCounts = React.useMemo(() => {
    const counts: Record<string, number> = {}
    selectedClauses.forEach(clause => {
      const category = clause.category || "미분류"
      counts[category] = (counts[category] || 0) + 1
    })
    return counts
  }, [selectedClauses])

  const activeCount = selectedClauses.filter(clause => clause.isActive).length
  const inactiveCount = selectedClauses.length - activeCount

  if (selectedClauses.length === 0) {
    return null
  }

  return (
    <Dialog {...props} onOpenChange={handleDialogOpenChange}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Edit className="h-5 w-5" />
            조항 일괄 수정
          </DialogTitle>
          <DialogDescription>
            선택한 {selectedClauses.length}개 조항의 공통 속성을 일괄 수정합니다.
          </DialogDescription>
        </DialogHeader>

        {/* 선택된 조항 요약 */}
        <div className="space-y-4 p-4 bg-muted/50 rounded-lg">
          <div className="flex items-center gap-2">
            <AlertCircle className="h-4 w-4 text-muted-foreground" />
            <span className="text-sm font-medium">선택된 조항 정보</span>
          </div>
          
          <div className="grid grid-cols-2 gap-4 text-sm">
            <div>
              <div className="font-medium text-muted-foreground mb-1">총 조항 수</div>
              <div>{selectedClauses.length}개</div>
            </div>
            
            <div>
              <div className="font-medium text-muted-foreground mb-1">상태</div>
              <div className="flex gap-2">
                <Badge variant="default">{activeCount}개 활성</Badge>
                {inactiveCount > 0 && (
                  <Badge variant="secondary">{inactiveCount}개 비활성</Badge>
                )}
              </div>
            </div>
          </div>

          {/* 분류별 통계 */}
          <div>
            <div className="font-medium text-muted-foreground mb-2">현재 분류 현황</div>
            <div className="flex flex-wrap gap-1">
              {Object.entries(categoryCounts).map(([category, count]) => (
                <Badge key={category} variant="outline" className="text-xs">
                  {category}: {count}개
                </Badge>
              ))}
            </div>
          </div>

          {/* 조항 미리보기 (최대 5개) */}
          <div>
            <div className="font-medium text-muted-foreground mb-2">포함된 조항 (일부)</div>
            <div className="space-y-1 max-h-24 overflow-y-auto">
              {selectedClauses.slice(0, 5).map(clause => (
                <div key={clause.id} className="flex items-center gap-2 text-xs">
                  <Badge variant="outline">{clause.itemNumber}</Badge>
                  <span className="truncate">{clause.subtitle}</span>
                </div>
              ))}
              {selectedClauses.length > 5 && (
                <div className="text-xs text-muted-foreground">
                  ... 외 {selectedClauses.length - 5}개 조항
                </div>
              )}
            </div>
          </div>
        </div>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)}>
            <div className="space-y-4">
              {/* 분류 수정 */}
              <FormField
                control={form.control}
                name="updates.category"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>분류 변경 (선택사항)</FormLabel>
                    <FormControl>
                      <Input 
                        placeholder="새로운 분류명을 입력하세요 (빈칸으로 두면 변경하지 않음)"
                        {...field} 
                      />
                    </FormControl>
                    <FormDescription>
                      모든 선택된 조항의 분류가 동일한 값으로 변경됩니다.
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 활성 상태 변경 */}
              <FormField
                control={form.control}
                name="updates.isActive"
                render={({ field }) => (
                  <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                    <div className="space-y-0.5">
                      <FormLabel className="text-base">활성 상태</FormLabel>
                      <FormDescription>
                        선택된 모든 조항의 활성 상태를 설정합니다.
                      </FormDescription>
                    </div>
                    <FormControl>
                      <Switch
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </FormControl>
                  </FormItem>
                )}
              />

              {/* 편집 사유 */}
              <FormField
                control={form.control}
                name="editReason"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>편집 사유 *</FormLabel>
                    <FormControl>
                      <Textarea
                        placeholder="일괄 수정 사유를 입력하세요..."
                        {...field}
                        rows={3}
                      />
                    </FormControl>
                    <FormDescription>
                      일괄 수정의 이유를 명확히 기록해주세요.
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <DialogFooter className="mt-6">
              <Button
                type="button"
                variant="outline"
                onClick={() => props.onOpenChange?.(false)}
                disabled={isUpdatePending}
              >
                Cancel
              </Button>
              <Button type="submit" disabled={isUpdatePending}>
                {isUpdatePending && (
                  <Loader
                    className="mr-2 size-4 animate-spin"
                    aria-hidden="true"
                  />
                )}
                Update {selectedClauses.length} Clauses
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}