summaryrefslogtreecommitdiff
path: root/components/notice/notice-create-dialog.tsx
blob: 98c66c99821f07e672a8d167e855fa8196f04523 (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
"use client"

import * as React from "react"
import { useState } from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { useParams } from "next/navigation"
import { useTranslation } from "@/i18n/client"
import { toast } from "sonner"
import { Loader, Check, ChevronsUpDown } from "lucide-react"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Switch } from "@/components/ui/switch"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Command, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem } from "@/components/ui/command"
import { cn } from "@/lib/utils"
import TiptapEditor from "@/components/qna/tiptap-editor"
import { createNotice } from "@/lib/notice/service"
import { createNoticeSchema, type CreateNoticeSchema } from "@/lib/notice/validations"

interface NoticeCreateDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  pagePathOptions: Array<{ value: string; label: string }>
  currentUserId?: number
  onSuccess?: () => void
}

export function NoticeCreateDialog({
  open,
  onOpenChange,
  pagePathOptions,
  currentUserId,
  onSuccess,
}: NoticeCreateDialogProps) {
  const params = useParams()
  const lng = (params?.lng as string) || 'ko'
  const { t } = useTranslation(lng, 'menu')
  
  // 안전한 번역 함수 (키가 없을 때 원본 키 반환)
  const safeTranslate = (key: string): string => {
    try {
      const translated = t(key)
      // 번역 키가 그대로 반환되는 경우 원본 키 사용
      if (translated === key) {
        return key
      }
      return translated || key
    } catch (error) {
      console.warn(`Translation failed for key: ${key}`, error)
      return key
    }
  }
  const [isLoading, setIsLoading] = useState(false)

  const form = useForm<CreateNoticeSchema>({
    resolver: zodResolver(createNoticeSchema),
    defaultValues: {
      pagePath: "",
      title: "",
      content: "",
      authorId: currentUserId,
      isActive: true,
    },
  })

  React.useEffect(() => {
    if (open) {
      // 다이얼로그가 열릴 때마다 폼 초기화
      form.reset({
        pagePath: "",
        title: "",
        content: "",
        authorId: currentUserId,
        isActive: true,
      })
    }
  }, [open, currentUserId, form])

  const onSubmit = async (values: CreateNoticeSchema) => {
    setIsLoading(true)
    console.log("Form values:", values) // 디버깅용
    try {
      const result = await createNotice(values)
      console.log("Create result:", result) // 디버깅용

      if (result.success) {
        toast.success(result.message || "공지사항이 성공적으로 생성되었습니다.")
        if (onSuccess) onSuccess()
        onOpenChange(false)
      } else {
        toast.error(result.message || "공지사항 생성에 실패했습니다.")
        console.error("Create failed:", result.message)
      }
    } catch (error) {
      toast.error("공지사항 생성에 실패했습니다.")
      console.error("Create error:", error)
    } finally {
      setIsLoading(false)
    }
  }



  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="text-xl font-bold">
            새 공지사항 작성
          </DialogTitle>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="pagePath"
                render={({ field }) => {
                  const [open, setOpen] = useState(false)
                  const [searchTerm, setSearchTerm] = useState("")

                  const filteredOptions = React.useMemo(() => {
                    if (!searchTerm.trim()) return pagePathOptions

                    const lowerSearch = searchTerm.toLowerCase()
                    return pagePathOptions.filter(
                      (option) =>
                        safeTranslate(option.label).toLowerCase().includes(lowerSearch) ||
                        option.value.toLowerCase().includes(lowerSearch)
                    )
                  }, [pagePathOptions, searchTerm])

                  const selectedOption = pagePathOptions.find(option => option.value === field.value)

                  return (
                    <FormItem>
                      <FormLabel>페이지 경로 *</FormLabel>
                      <Popover open={open} onOpenChange={setOpen}>
                        <PopoverTrigger asChild>
                          <FormControl>
                            <Button
                              variant="outline"
                              role="combobox"
                              aria-expanded={open}
                              className="w-full justify-between"
                            >
                              {selectedOption
                                ? `${safeTranslate(selectedOption.label)} - ${selectedOption.value}`
                                : "페이지를 선택하세요"}
                              <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                            </Button>
                          </FormControl>
                        </PopoverTrigger>
                        <PopoverContent className="w-full p-0" align="start">
                          <Command>
                            <CommandInput
                              placeholder="페이지명 또는 경로 검색..."
                              onValueChange={setSearchTerm}
                            />
                            <CommandList className="max-h-[300px]">
                              <CommandEmpty>검색 결과가 없습니다</CommandEmpty>
                              <CommandGroup>
                                {filteredOptions.map((option) => (
                                  <CommandItem
                                    key={option.value}
                                    value={`${safeTranslate(option.label)} ${option.value}`}
                                    onSelect={() => {
                                      field.onChange(option.value)
                                      setOpen(false)
                                    }}
                                  >
                                    <Check
                                      className={cn(
                                        "mr-2 h-4 w-4",
                                        field.value === option.value
                                          ? "opacity-100"
                                          : "opacity-0"
                                      )}
                                    />
                                    <span className="font-medium">{safeTranslate(option.label)}</span>
                                    <span className="ml-2 text-gray-500 truncate">- {option.value}</span>
                                  </CommandItem>
                                ))}
                              </CommandGroup>
                            </CommandList>
                          </Command>
                        </PopoverContent>
                      </Popover>
                      <FormMessage />
                    </FormItem>
                  )
                }}
              />

              <FormField
                control={form.control}
                name="isActive"
                render={({ field }) => (
                  <FormItem className="flex flex-row items-center justify-between rounded-lg border p-3">
                    <div className="space-y-0.5">
                      <FormLabel className="text-base">활성 상태</FormLabel>
                      <div className="text-sm text-muted-foreground">
                        활성화하면 해당 페이지에서 공지사항이 표시됩니다.
                      </div>
                    </div>
                    <FormControl>
                      <Switch
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </FormControl>
                  </FormItem>
                )}
              />
            </div>

            <FormField
              control={form.control}
              name="title"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>제목 *</FormLabel>
                  <FormControl>
                    <Input placeholder="공지사항 제목을 입력하세요" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="content"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>내용 *</FormLabel>
                  <FormControl>
                    <div className="min-h-[400px]">
                      <TiptapEditor
                        content={field.value}
                        setContent={field.onChange}
                        disabled={isLoading}
                        height="300px"
                      />
                    </div>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <div className="flex justify-end gap-2 pt-4">
              <Button
                type="button"
                variant="outline"
                onClick={() => onOpenChange(false)}
                disabled={isLoading}
              >
                취소
              </Button>
              <Button type="submit" disabled={isLoading}>
                {isLoading && <Loader className="mr-2 h-4 w-4 animate-spin" />}
                생성
              </Button>
            </div>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}