AlertListPanel.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. 'use client';
  2. import { useEffect, useRef, useState } from 'react';
  3. import Image from 'next/image';
  4. import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
  5. import { faPlus, faImage, faPlay, faStop } from '@fortawesome/free-solid-svg-icons';
  6. import { Checkbox } from '@/components/ui/checkbox';
  7. import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog';
  8. import { fetchApi } from '@/lib/utils/client';
  9. import { useStudioContext } from '@/app/studio/context';
  10. import { useAlertConfigContext } from '../context';
  11. import type { AlertConfigItem } from '@/types/response/donation/alertConfig';
  12. import { PER_PAGE_OPTIONS } from '@/constants/donation';
  13. type Props = {
  14. items: AlertConfigItem[];
  15. loading: boolean;
  16. saving: boolean;
  17. checkedIDs: Set<number>;
  18. setCheckedIDs: React.Dispatch<React.SetStateAction<Set<number>>>;
  19. page: number;
  20. setPage: React.Dispatch<React.SetStateAction<number>>;
  21. perPage: number;
  22. setPerPage: React.Dispatch<React.SetStateAction<number>>;
  23. onNew: () => void;
  24. onEdit: (item: AlertConfigItem) => void;
  25. onBatchDelete: () => void;
  26. };
  27. export default function AlertListPanel({
  28. items,
  29. loading,
  30. saving,
  31. checkedIDs,
  32. setCheckedIDs,
  33. page,
  34. setPage,
  35. perPage,
  36. setPerPage,
  37. onNew,
  38. onEdit,
  39. onBatchDelete
  40. }: Props) {
  41. const { channelID } = useStudioContext();
  42. const { setItems } = useAlertConfigContext();
  43. const [playingAudio, setPlayingAudio] = useState<number|null>(null);
  44. const [previewImageUrl, setPreviewImageUrl] = useState<string|null>(null);
  45. const [thumbErrors, setThumbErrors] = useState<Set<number>>(new Set());
  46. const [togglingIDs, setTogglingIDs] = useState<Set<number>>(new Set());
  47. const audioRef = useRef<HTMLAudioElement|null>(null);
  48. // ── 활성/비활성 토글 ─────────────────────────────
  49. const handleToggleActive = async (item: AlertConfigItem) => {
  50. if (!channelID || togglingIDs.has(item.id)) {
  51. return;
  52. }
  53. const next = !item.isActive;
  54. // 1) in-flight guard (race 방지)
  55. setTogglingIDs(prev => {
  56. const s = new Set(prev);
  57. s.add(item.id);
  58. return s;
  59. });
  60. // 2) optimistic update
  61. setItems(prev => prev.map(x => x.id === item.id ? { ...x, isActive: next } : x));
  62. try {
  63. const res = await fetchApi<{ id: number; isActive: boolean }>(
  64. `/api/studio/donation/alert/config/${item.id}/active`,
  65. {
  66. method: 'PATCH',
  67. body: { channelID, isActive: next },
  68. silent: true
  69. }
  70. );
  71. if (!res.success) {
  72. // 롤백
  73. setItems(prev => prev.map(x => x.id === item.id ? { ...x, isActive: item.isActive } : x));
  74. alert(res.message || '활성 상태 변경에 실패했습니다.');
  75. } else if (res.data && res.data.isActive !== next) {
  76. // 서버가 다른 값 반환 시 ground truth 반영
  77. setItems(prev => prev.map(x => x.id === item.id ? { ...x, isActive: res.data!.isActive } : x));
  78. }
  79. } catch (err) {
  80. // 네트워크/예외 → 롤백
  81. setItems(prev => prev.map(x => x.id === item.id ? { ...x, isActive: item.isActive } : x));
  82. alert(err instanceof Error ? err.message : '활성 상태 변경에 실패했습니다.');
  83. } finally {
  84. setTogglingIDs(prev => {
  85. const s = new Set(prev);
  86. s.delete(item.id);
  87. return s;
  88. });
  89. }
  90. };
  91. // ── 페이징 ───────────────────────────────────────
  92. const totalPages = Math.max(1, Math.ceil(items.length / perPage));
  93. const pagedItems = items.slice((page - 1) * perPage, page * perPage);
  94. const handlePerPageChange = (value: number) => {
  95. setPerPage(value);
  96. setPage(1);
  97. };
  98. // ── 전체선택 ─────────────────────────────────────
  99. const visibleIDs = pagedItems.map(i => i.id);
  100. const checkedCount = visibleIDs.filter(id => checkedIDs.has(id)).length;
  101. const allChecked = pagedItems.length > 0 && checkedCount === visibleIDs.length;
  102. const isIndeterminate = checkedCount > 0 && checkedCount < visibleIDs.length;
  103. const handleSelectAll = () => {
  104. setCheckedIDs(prev => {
  105. const next = new Set(prev);
  106. if (allChecked) {
  107. visibleIDs.forEach(id => next.delete(id));
  108. } else {
  109. visibleIDs.forEach(id => next.add(id));
  110. }
  111. return next;
  112. });
  113. };
  114. const handleToggleCheck = (id: number) => {
  115. setCheckedIDs(prev => {
  116. const next = new Set(prev);
  117. if (next.has(id)) {
  118. next.delete(id);
  119. } else {
  120. next.add(id);
  121. }
  122. return next;
  123. });
  124. };
  125. // ── 사운드 재생/정지 ─────────────────────────────
  126. const handlePlaySound = (itemId: number, soundUrl: string) => {
  127. // 이미 재생 중이면 정지
  128. if (playingAudio === itemId && audioRef.current) {
  129. audioRef.current.pause();
  130. audioRef.current = null;
  131. setPlayingAudio(null);
  132. return;
  133. }
  134. // 기존 재생 정지
  135. if (audioRef.current) {
  136. audioRef.current.pause();
  137. audioRef.current = null;
  138. }
  139. const audio = new Audio(soundUrl);
  140. audioRef.current = audio;
  141. setPlayingAudio(itemId);
  142. audio.play().catch(() => {});
  143. audio.addEventListener('ended', () => {
  144. setPlayingAudio(null);
  145. audioRef.current = null;
  146. });
  147. };
  148. // unmount 시 오디오 정리
  149. useEffect(() => {
  150. return () => {
  151. if (audioRef.current) {
  152. audioRef.current.pause();
  153. audioRef.current = null;
  154. }
  155. };
  156. }, []);
  157. return (
  158. <div className="alert-config__list-panel">
  159. <div className="alert-config__toolbar">
  160. <div className="alert-config__toolbar-left">
  161. <span className="alert-config__count">총 {items.length}개</span>
  162. {checkedIDs.size > 0 && (
  163. <span className="alert-config__count">({checkedIDs.size}개 선택)</span>
  164. )}
  165. </div>
  166. <div className="alert-config__toolbar-right">
  167. <select
  168. value={perPage}
  169. onChange={e => handlePerPageChange(Number(e.target.value))}
  170. className="alert-config__per-page"
  171. title="보여질 개수"
  172. >
  173. {PER_PAGE_OPTIONS.map(n => (
  174. <option key={n} value={n}>{n}개씩</option>
  175. ))}
  176. </select>
  177. <button type="button" className="alert-config__btn" onClick={onNew}>
  178. <FontAwesomeIcon icon={faPlus} />
  179. 추가
  180. </button>
  181. <button
  182. type="button"
  183. className="alert-config__btn alert-config__btn--danger"
  184. onClick={onBatchDelete}
  185. disabled={checkedIDs.size === 0 || saving}
  186. >
  187. 삭제
  188. </button>
  189. </div>
  190. </div>
  191. <div className="alert-config__table-wrap">
  192. {loading ? (
  193. <div className="alert-config__empty">준비 중...</div>
  194. ) : items.length === 0 ? (
  195. <div className="alert-config__empty">등록된 알림 설정이 없습니다.</div>
  196. ) : (
  197. <table className="alert-config__table">
  198. <thead>
  199. <tr>
  200. <th className="alert-config__th--check">
  201. <Checkbox
  202. checked={allChecked} indeterminate={isIndeterminate}
  203. onCheckedChange={handleSelectAll}
  204. aria-label="전체선택"
  205. />
  206. </th>
  207. <th>조건</th>
  208. <th>금액</th>
  209. <th>제목</th>
  210. <th>보낼 내용</th>
  211. <th>노출(초)</th>
  212. <th>활성</th>
  213. <th>미디어</th>
  214. <th>비고</th>
  215. </tr>
  216. </thead>
  217. <tbody>
  218. {pagedItems.map(item => {
  219. const isChecked = checkedIDs.has(item.id);
  220. const hasImage = item.enableImage && item.imageUrl;
  221. const hasSound = item.enableSound && item.soundUrl;
  222. return (
  223. <tr
  224. key={item.id}
  225. className={isChecked ? 'alert-config__row--checked' : ''}
  226. >
  227. <td className="alert-config__td--check">
  228. <Checkbox
  229. checked={isChecked}
  230. onCheckedChange={() => handleToggleCheck(item.id)}
  231. aria-label={`${item.id} 선택`}
  232. />
  233. </td>
  234. <td>
  235. <span className={`alert-config__match-badge alert-config__match-badge--${item.matchType === 1 ? 'exact' : 'min'}`}>
  236. {item.matchType === 1 ? '정확히' : '이상'}
  237. </span>
  238. </td>
  239. <td>{item.amount.toLocaleString()}원</td>
  240. <td>{item.title || <span className="text-muted-foreground">미입력</span>}</td>
  241. <td className="alert-config__td--message">{item.message}</td>
  242. <td>{item.displayDurationSec}초</td>
  243. <td>
  244. <button
  245. type="button"
  246. role="switch"
  247. aria-checked={item.isActive}
  248. aria-busy={togglingIDs.has(item.id)}
  249. aria-label={`${item.title || `#${item.id}`} 활성 상태 ${item.isActive ? '끄기' : '켜기'}`}
  250. className={`alert-config__active-toggle${item.isActive ? ' alert-config__active-toggle--on' : ''}${togglingIDs.has(item.id) ? ' alert-config__active-toggle--busy' : ''}`}
  251. onClick={() => handleToggleActive(item)}
  252. disabled={togglingIDs.has(item.id) || saving}
  253. title={item.isActive ? '비활성화' : '활성화'}
  254. >
  255. <span className="alert-config__active-toggle-knob" aria-hidden="true" />
  256. </button>
  257. </td>
  258. <td className="alert-config__td--media">
  259. <div>
  260. {hasImage && (
  261. thumbErrors.has(item.id) ? (
  262. <button
  263. type="button"
  264. className="alert-config__media-btn alert-config__media-btn--image"
  265. title="이미지 보기"
  266. onClick={() => setPreviewImageUrl(item.imageUrl!)}
  267. >
  268. <FontAwesomeIcon icon={faImage} />
  269. </button>
  270. ) : (
  271. <button
  272. type="button"
  273. className="alert-config__media-thumb"
  274. title="이미지 크게 보기"
  275. onClick={() => setPreviewImageUrl(item.imageUrl!)}
  276. >
  277. <Image
  278. src={item.imageUrl!}
  279. alt="알림 이미지"
  280. width={96}
  281. height={96}
  282. sizes="96px"
  283. quality={90}
  284. className="alert-config__media-thumb-img"
  285. loading="lazy"
  286. onError={() => setThumbErrors(prev => new Set(prev).add(item.id))}
  287. />
  288. </button>
  289. )
  290. )}
  291. {hasSound && (
  292. <button
  293. type="button"
  294. className={`alert-config__media-btn alert-config__media-btn--sound${playingAudio === item.id ? ' alert-config__media-btn--playing' : ''}`}
  295. title={playingAudio === item.id ? '사운드 정지' : '사운드 재생'}
  296. onClick={() => handlePlaySound(item.id, item.soundUrl!)}
  297. >
  298. <FontAwesomeIcon icon={playingAudio === item.id ? faStop : faPlay} />
  299. </button>
  300. )}
  301. {!hasImage && !hasSound && (
  302. <span className="text-muted-foreground">-</span>
  303. )}
  304. </div>
  305. </td>
  306. <td>
  307. <button
  308. type="button"
  309. className="alert-config__btn alert-config__btn--sm"
  310. onClick={() => onEdit(item)}
  311. disabled={isChecked}
  312. >
  313. 수정
  314. </button>
  315. </td>
  316. </tr>
  317. );
  318. })}
  319. </tbody>
  320. </table>
  321. )}
  322. </div>
  323. {totalPages > 1 && (
  324. <div className="alert-config__pagination">
  325. <button
  326. type="button"
  327. className="alert-config__page-btn"
  328. disabled={page <= 1}
  329. onClick={() => setPage(p => p - 1)}
  330. >
  331. </button>
  332. {Array.from({ length: totalPages }, (_, i) => i + 1).map(p => (
  333. <button
  334. key={p}
  335. type="button"
  336. className={`alert-config__page-btn${p === page ? ' alert-config__page-btn--active' : ''}`}
  337. onClick={() => setPage(p)}
  338. >
  339. {p}
  340. </button>
  341. ))}
  342. <button
  343. type="button"
  344. className="alert-config__page-btn"
  345. disabled={page >= totalPages}
  346. onClick={() => setPage(p => p + 1)}
  347. >
  348. </button>
  349. </div>
  350. )}
  351. {/* 이미지 확대 모달 */}
  352. <Dialog open={!!previewImageUrl} onOpenChange={open => { if (!open) { setPreviewImageUrl(null); } }}>
  353. <DialogContent className="alert-config__media-dialog">
  354. <DialogTitle className="sr-only">이미지 미리보기</DialogTitle>
  355. {previewImageUrl && (
  356. <img
  357. src={previewImageUrl}
  358. alt="알림 이미지"
  359. className="alert-config__media-dialog-img"
  360. />
  361. )}
  362. </DialogContent>
  363. </Dialog>
  364. </div>
  365. );
  366. }