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
|
"use client"
import * as React 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 { Button } from "@/components/ui/button"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import {
Sheet,
SheetContent,
SheetDescription,
SheetFooter,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Switch } from "@/components/ui/switch"
import { updateNoticeSchema, type UpdateNoticeSchema } from "@/lib/notice/validations"
import type { Notice } from "@/db/schema/notice"
import { updateNoticeData } from "@/lib/notice/service"
import TiptapEditor from "@/components/qna/tiptap-editor"
import { Calendar } from "@/components/ui/calendar"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { CalendarIcon } from "lucide-react"
import { format } from "date-fns"
import { ko } from "date-fns/locale"
import { cn } from "@/lib/utils"
type NoticeWithAuthor = Notice & {
authorName: string | null
authorEmail: string | null
}
interface UpdateNoticeSheetProps {
open: boolean
onOpenChange: (open: boolean) => void
notice: NoticeWithAuthor | null
pagePathOptions: Array<{ value: string; label: string }>
onSuccess?: () => void
}
export function UpdateNoticeSheet({
open,
onOpenChange,
notice,
pagePathOptions,
onSuccess
}: UpdateNoticeSheetProps) {
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 [isUpdatePending, startUpdateTransition] = React.useTransition()
const form = useForm<UpdateNoticeSchema>({
resolver: zodResolver(updateNoticeSchema),
defaultValues: {
id: 0,
pagePath: "",
title: "",
content: "",
isActive: true,
isPopup: false,
startAt: undefined,
endAt: undefined,
dontShowDuration: "never", // 기본값을 영구로 설정
},
})
// notice 데이터가 변경될 때 폼 초기화
React.useEffect(() => {
if (notice) {
form.reset({
id: notice.id,
pagePath: notice.pagePath,
title: notice.title,
content: notice.content,
isActive: notice.isActive,
isPopup: notice.isPopup || false,
startAt: notice.startAt || undefined,
endAt: notice.endAt || undefined,
dontShowDuration: notice.dontShowDuration as 'day' | 'never' || "never", // 기본값을 영구로 설정
})
}
}, [notice, form])
function onSubmit(input: UpdateNoticeSchema) {
if (!notice) return
startUpdateTransition(async () => {
try {
const result = await updateNoticeData(input)
if (result.success) {
toast.success(result.message || "공지사항이 성공적으로 수정되었습니다.")
if (onSuccess) onSuccess()
onOpenChange(false)
} else {
toast.error(result.message || "공지사항 수정에 실패했습니다.")
}
} catch (error) {
toast.error("예기치 못한 오류가 발생했습니다.")
console.error("공지사항 수정 오류:", error)
}
})
}
return (
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent className="flex h-full w-full flex-col gap-6 sm:max-w-4xl">
<SheetHeader className="text-left">
<SheetTitle>공지사항 수정</SheetTitle>
<SheetDescription>
공지사항의 제목과 내용을 수정할 수 있습니다. 수정된 내용은 즉시 반영됩니다.
</SheetDescription>
</SheetHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col flex-1 min-h-0 space-y-6">
{/* 공지사항 정보 표시 */}
{notice && (
<div className="rounded-md border border-muted bg-muted/50 p-3 text-sm">
<div className="font-medium text-muted-foreground mb-1">공지사항 정보</div>
<div className="space-y-1">
<div>작성자: {notice.authorName} ({notice.authorEmail})</div>
<div>작성일: {new Date(notice.createdAt).toLocaleDateString("ko-KR")}</div>
<div>수정일: {new Date(notice.updatedAt).toLocaleDateString("ko-KR")}</div>
<div>상태: {notice.isActive ? "활성" : "비활성"}</div>
</div>
</div>
)}
{/* 페이지 경로 선택 */}
<FormField
control={form.control}
name="pagePath"
render={({ field }) => (
<FormItem>
<FormLabel>페이지 경로 *</FormLabel>
<Select
onValueChange={field.onChange}
defaultValue={field.value}
disabled={isUpdatePending}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="페이지를 선택해주세요" />
</SelectTrigger>
</FormControl>
<SelectContent>
{pagePathOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
{safeTranslate(option.label)} - {option.value}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
{/* 제목 입력 */}
<FormField
control={form.control}
name="title"
render={({ field }) => (
<FormItem>
<FormLabel>제목 *</FormLabel>
<FormControl>
<Input
placeholder="공지사항의 제목을 입력해주세요"
disabled={isUpdatePending}
className="text-base"
{...field}
/>
</FormControl>
<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}
disabled={isUpdatePending}
/>
</FormControl>
</FormItem>
)}
/>
{/* 팝업 여부 */}
<FormField
control={form.control}
name="isPopup"
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}
disabled={isUpdatePending}
/>
</FormControl>
</FormItem>
)}
/>
{/* 유효기간 설정 (팝업인 경우에만 표시) */}
{form.watch('isPopup') && (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="startAt"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>게시 시작 일시</FormLabel>
<Popover>
<PopoverTrigger asChild>
<FormControl>
<Button
variant="outline"
className={cn(
"w-full pl-3 text-left font-normal",
!field.value && "text-muted-foreground"
)}
disabled={isUpdatePending}
>
{field.value ? (
format(field.value, "PPP HH:mm", { locale: ko })
) : (
<span>시작 일시 선택</span>
)}
<CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
</Button>
</FormControl>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="single"
selected={field.value}
onSelect={(date) => {
if (date) {
const dateTime = new Date(date)
if (field.value) {
dateTime.setHours(field.value.getHours())
dateTime.setMinutes(field.value.getMinutes())
} else {
dateTime.setHours(0, 0, 0, 0)
}
field.onChange(dateTime)
}
}}
disabled={(date) =>
date < new Date("1900-01-01")
}
initialFocus
/>
<div className="p-3 border-t">
<Input
type="time"
value={field.value ? format(field.value, "HH:mm") : ""}
onChange={(e) => {
if (field.value && e.target.value) {
const [hours, minutes] = e.target.value.split(':')
const newDate = new Date(field.value)
newDate.setHours(parseInt(hours), parseInt(minutes))
field.onChange(newDate)
}
}}
disabled={isUpdatePending}
/>
</div>
</PopoverContent>
</Popover>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="endAt"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>게시 종료 일시</FormLabel>
<Popover>
<PopoverTrigger asChild>
<FormControl>
<Button
variant="outline"
className={cn(
"w-full pl-3 text-left font-normal",
!field.value && "text-muted-foreground"
)}
disabled={isUpdatePending}
>
{field.value ? (
format(field.value, "PPP HH:mm", { locale: ko })
) : (
<span>종료 일시 선택</span>
)}
<CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
</Button>
</FormControl>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="single"
selected={field.value}
onSelect={(date) => {
if (date) {
const dateTime = new Date(date)
if (field.value) {
dateTime.setHours(field.value.getHours())
dateTime.setMinutes(field.value.getMinutes())
} else {
dateTime.setHours(23, 59, 59, 999)
}
field.onChange(dateTime)
}
}}
disabled={(date) =>
date < new Date("1900-01-01")
}
initialFocus
/>
<div className="p-3 border-t">
<Input
type="time"
value={field.value ? format(field.value, "HH:mm") : ""}
onChange={(e) => {
if (field.value && e.target.value) {
const [hours, minutes] = e.target.value.split(':')
const newDate = new Date(field.value)
newDate.setHours(parseInt(hours), parseInt(minutes))
field.onChange(newDate)
}
}}
disabled={isUpdatePending}
/>
</div>
</PopoverContent>
</Popover>
<FormMessage />
</FormItem>
)}
/>
</div>
)}
{/* 다시 보지 않기 설정 (팝업인 경우에만 표시) */}
{/* {form.watch('isPopup') && (
<FormField
control={form.control}
name="dontShowDuration"
render={({ field }) => (
<FormItem>
<FormLabel>'다시 보지 않기' 기간 설정</FormLabel>
<Select
onValueChange={field.onChange}
defaultValue={field.value}
disabled={isUpdatePending}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="기간을 선택하세요" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="day">하루 동안 표시하지 않음</SelectItem>
<SelectItem value="never">영구적으로 표시하지 않음</SelectItem>
</SelectContent>
</Select>
<div className="text-sm text-muted-foreground">
사용자가 '다시 보지 않기'를 체크하면 설정한 기간 동안 해당 공지사항이 표시되지 않습니다.
</div>
<FormMessage />
</FormItem>
)}
/>
)} */}
{/* 내용 입력 (리치텍스트 에디터) */}
<FormField
control={form.control}
name="content"
render={({ field }) => (
<FormItem className="flex flex-col flex-1 min-h-0">
<FormLabel>내용 *</FormLabel>
<FormControl className="flex flex-col flex-1 min-h-0">
<TiptapEditor
content={field.value}
setContent={field.onChange}
disabled={isUpdatePending}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
<SheetFooter className="gap-2 pt-4 border-t">
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isUpdatePending}
>
취소
</Button>
<Button
type="submit"
onClick={form.handleSubmit(onSubmit)}
disabled={isUpdatePending}
>
{isUpdatePending ? "수정 중..." : "수정 완료"}
</Button>
</SheetFooter>
</SheetContent>
</Sheet>
)
}
|