Compare commits

...

81 commits

Author SHA1 Message Date
a3960489d4 fix: Meilisearch 검색 유사도 필터링 추가
- 유사도 0.5 미만인 검색 결과 필터링
- showRankingScore 활성화하여 점수 기반 필터링 적용
2026-01-10 19:06:49 +09:00
622839b0e8 feat: Meilisearch 동기화 봇 추가 및 시간대 관련 수정
봇 시스템:
- Meilisearch 동기화 봇 추가 (meilisearch-bot.js)
- bots 테이블 type enum에 meilisearch 추가
- youtube-scheduler.js에 meilisearch 봇 분기 추가
- admin.js API에서 meilisearch 봇 지원

봇 관리 페이지 개선 (AdminScheduleBots.jsx):
- Meilisearch 공식 로고 아이콘 추가
- Meilisearch 봇 통계: 동기화 수/소요 시간 표시
- 봇 타입별 배경색 (X: 검정, Meilisearch: #ddf1fd, YouTube: 빨강)

시간대 정리:
- MariaDB KST 설정으로 DATE_ADD(NOW(), INTERVAL 9 HOUR) → NOW() 변경
- youtube-bot.js, x-bot.js에서 10곳 수정
2026-01-10 18:59:39 +09:00
8780384164 fix(x-bot): 유튜브 일정에 채널명(source_name) 추가
- createScheduleFromYoutube에서 video.channelTitle을 source_name에 저장
- Meilisearch 동기화 시에도 source_name 포함
2026-01-10 18:26:43 +09:00
0ee587ad08 chore: 불필요한 스크립트 파일 삭제
- scrape_all.cjs, scrape_all.js, scrape_search.cjs 삭제 (미사용)
- scrape_log.txt, scrape_search_log.txt 삭제 (로그 파일)
- extract_youtube_from_x.js 삭제 (일회성 스크립트)
2026-01-10 17:22:45 +09:00
59e5a1d47b feat: X 봇 구현 및 봇 관리 기능 개선
- X 봇 서비스 추가 (x-bot.js)
  - Nitter를 통한 @realfromis_9 트윗 수집
  - 트윗을 일정으로 자동 저장 (카테고리 12)
  - 관리 채널 외 유튜브 링크 감지 시 별도 일정 추가
  - 1분 간격 동기화 지원

- DB 스키마 변경
  - bots.type enum 수정 (vlive, weverse 제거, x 추가)
  - bot_x_config 테이블 추가

- 봇 스케줄러 수정 (youtube-scheduler.js)
  - 봇 타입별 동기화 함수 분기 (syncBot)
  - X 봇 지원 추가

- 관리자 페이지 개선 (AdminScheduleBots.jsx)
  - 봇 타입별 아이콘 표시 (YouTube/X)
  - X 아이콘 SVG 컴포넌트 추가

- last_added_count 로직 수정
  - 추가 항목 없으면 이전 값 유지 (0으로 초기화 방지)

- 기존 X 일정에서 유튜브 영상 추출 스크립트 추가
2026-01-10 17:06:23 +09:00
0376c0ac73 feat: 검색 카드 제목 2줄 ellipsis 적용
- line-clamp-2 추가하여 긴 제목 잘림 처리
2026-01-10 10:37:11 +09:00
3b79aa13c2 feat: 검색 카드 날짜 레이아웃 개선
- 왼쪽에 날짜 세로 배치 (년도/월.일/요일)
- 일요일 빨간색, 토요일 파란색 요일 색상 적용
- 오른쪽 콘텐츠 영역으로 분리
2026-01-10 10:35:00 +09:00
54fe3074dc feat: 검색 결과 카드 디자인 개선
- TimelineScheduleCard 스타일로 리디자인
- 날짜 뱃지 추가 (M.D (요일) 형식)
- 시간/카테고리 뱃지 스타일 통일
- 멤버 태그 그라데이션 적용
- 스프링 애니메이션 추가
2026-01-10 10:31:22 +09:00
83e3689f02 feat: 모바일 검색 뒤로가기 버튼 처리
- enterSearchMode()에서 history.pushState로 히스토리 상태 추가
- popstate 이벤트로 뒤로가기 시 검색 모드 종료
- 이전 페이지로 이동하지 않고 일정 화면으로 복귀
2026-01-10 10:28:21 +09:00
0521e3d0ec fix: 모바일 일정 HTML 엔티티 디코딩 적용
- decodeHtmlEntities 함수 추가
- ScheduleCard, TimelineScheduleCard title에 적용
- & → & 등으로 올바르게 표시
2026-01-10 10:26:21 +09:00
d84ab36a83 fix: 검색 스크롤 초기화 개선
- virtualizer.scrollToOffset(0) 사용
- DOM 스크롤도 함께 초기화 (fallback)
2026-01-10 10:23:03 +09:00
ff2c596865 fix: 검색 시 스크롤 위치 초기화
- searchTerm 변경 시 scrollContainerRef.scrollTop = 0 적용
- 검색 취소 후 재검색 시 맨 위부터 표시
2026-01-10 10:16:19 +09:00
54bbe75ecc fix: 검색 모드 진입 시 기존 일정 숨김
- isSearchMode일 때 searchTerm 없으면 '검색어를 입력하세요' 표시
- 기존 날짜별 일정이 보이지 않도록 조건 수정
2026-01-10 10:14:59 +09:00
c8ec8de946 fix: 모바일 검색 X버튼 중복 및 하단 여백 수정
- type='search' → type='text'로 변경하여 브라우저 기본 X버튼 제거
- 무한 스크롤 트리거 여백 py-4 → py-2로 축소
2026-01-10 10:12:32 +09:00
660acd0007 feat: 모바일 일정 검색에 가상 스크롤 적용
- @tanstack/react-virtual useVirtualizer 적용
- 동적 높이 지원 (measureElement, data-index)
- SEARCH_LIMIT 10 → 20으로 증가
- 검색 결과가 많아도 DOM에는 화면에 보이는 요소만 렌더링
2026-01-10 10:10:36 +09:00
b35dab5eea feat: 모바일 일정 검색 UX 개선
- 입력 시마다 검색 → 키패드 검색 버튼 눌러야 검색으로 변경
- searchInput과 searchTerm 분리
- type='search', enterKeyHint='search' 추가로 모바일 키보드 최적화
- 취소 버튼 잘림 현상 수정 (flex-shrink-0, min-w-0)
2026-01-10 10:05:56 +09:00
0efa0a8e5c feat: AdminSchedule.jsx에 동적 높이 가상 스크롤 적용
- measureElement와 data-index 추가
- 고정 높이 제거하여 내용에 맞게 자동 조절
2026-01-10 09:52:34 +09:00
4ecc16347c fix: 일정 페이지 최소 높이 및 관리 페이지 글씨 크기 수정
- Schedule.jsx: 검색 결과 아이템에 min-h-[100px] 추가
- AdminSchedule.jsx: 글씨 크기 및 아이콘 크기 원복
2026-01-10 09:50:56 +09:00
d22466ec23 feat: 가상 스크롤 동적 높이 지원
- measureElement와 data-index 사용으로 각 아이템 실제 높이 측정
- 고정 높이(h-[120px]) 제거하여 내용에 맞게 자동 조절
2026-01-10 09:46:38 +09:00
0cab67dfbe fix: 가상 스크롤 컨테이너 높이에서 마지막 여백 제거 2026-01-10 09:43:58 +09:00
92782e9022 fix: 마지막 검색 결과 항목 여백 제거 2026-01-10 09:42:34 +09:00
043f8b465d fix: 가상 스크롤 버그 수정
- searchSchedules 미정의 오류 수정 (setSearchTerm만 사용)
- Schedule.jsx 항목 간 여백 추가 (ITEM_HEIGHT 136px)
2026-01-10 09:40:40 +09:00
ad2d501c39 feat: 일정 검색에 가상 스크롤 최적화 적용
- @tanstack/react-virtual 라이브러리 추가
- Schedule.jsx, AdminSchedule.jsx에 useVirtualizer 적용
- 검색 결과가 많아도 DOM에는 화면에 보이는 요소만 렌더링
- 스크롤 성능 대폭 향상
2026-01-10 09:34:18 +09:00
7192379eb0 chore: 일정 검색 페이징 limit을 20개로 변경
- Schedule.jsx, AdminSchedule.jsx SEARCH_LIMIT 5 -> 20
2026-01-10 09:20:27 +09:00
9986b918d8 fix: 검색 모드에서 카테고리 필터링 적용
- 검색 결과에도 selectedCategories로 필터링 추가
- Schedule.jsx, AdminSchedule.jsx 수정
2026-01-10 09:16:15 +09:00
bedda590eb fix: 검색 모드에서 카테고리 카운트 수정
- 검색 모드일 때 selectedDate 조건 제거하여 모든 검색 결과의 카테고리 표시
- Schedule.jsx, AdminSchedule.jsx 수정
2026-01-10 09:13:49 +09:00
cdca23e317 refactor: PC public 페이지 공통 컴포넌트 및 유틸 적용
- LightboxIndicator 공통 컴포넌트 생성 및 AlbumDetail, AlbumGallery에 적용
- formatDate를 utils/date에서 import하도록 변경 (Album, Members, AlbumDetail)
- 중복 코드 약 100줄 제거
2026-01-10 09:06:26 +09:00
22db79e960 fix: PC 공개 일정 페이지 HTML 엔티티 디코딩 수정
- decodeHtmlEntities 함수 추가하여 < > 등 올바르게 표시
- 레이아웃 변경 없음 (원래 상태 유지)
2026-01-10 00:45:30 +09:00
97767bc5ca fix: 일정 목록 높이 자동 계산으로 잘림 문제 해결
- main을 flex flex-col로 변경
- 브레드크럼, 타이틀에 flex-shrink-0 추가
- 그리드에 flex-1 min-h-0 추가
- 일정 목록 컬럼에 flex flex-col min-h-0 추가
- 스크롤 컨테이너에서 max-h 고정값 제거하고 flex-1로 변경
2026-01-10 00:31:34 +09:00
04ce4beba4 fix: 일정 관리 페이지 UI 수정
1. 외부 스크롤 제거 (h-screen overflow-hidden flex flex-col)
2. HTML 엔티티 디코딩 함수 추가 (< > 등 올바르게 표시)
3. decodeHtmlEntities 함수를 컴포넌트 외부로 이동하여 ScheduleItem에서 접근 가능
2026-01-10 00:27:32 +09:00
0f7d3d6f39 Revert "fix: 관리 페이지 날짜 상태 조건부 초기화"
This reverts commit 2dd5219265.
2026-01-10 00:20:04 +09:00
2dd5219265 fix: 관리 페이지 날짜 상태 조건부 초기화
문제: 일정 관리 페이지에서 날짜 선택 후 홈으로 갔다왔을 때
오늘 날짜로 초기화가 안됨

해결:
- useScheduleStore에 preserveState 플래그 추가
- AdminSchedule에서 preserveState가 false면 오늘 날짜로 초기화
- AdminScheduleForm, AdminScheduleBots에서 일정 관리로 돌아갈 때
  preserveState를 true로 설정하여 상태 유지
2026-01-10 00:19:06 +09:00
d6eb8d410c feat: 모바일 홈 화면 섹션별 애니메이션 추가
- 히어로 섹션: 페이드인 + 텍스트 슬라이드업
- 멤버 섹션: 프로필 팝 애니메이션
- 앨범 섹션: 카드 슬라이드업
- 일정 섹션: 카드 슬라이드인
- 순차적 딜레이로 자연스러운 로딩 효과
2026-01-10 00:11:04 +09:00
dc879fc60d feat: 모바일 멤버 페이지 카드 애니메이션 추가
- 페이드인 + 슬라이드업 애니메이션 적용
- 순차적 딜레이로 자연스러운 등장 효과
2026-01-10 00:09:13 +09:00
24fc1f2b87 fix: 누락된 getAlbumTracks API 함수 추가
- api/public/albums.js에 getAlbumTracks 함수 누락으로 모바일 페이지 오류 발생
- AlbumDetail.jsx에서 사용하는 함수 추가
2026-01-10 00:05:57 +09:00
1f9cf34e31 refactor: 모바일 public 페이지 API 모듈 적용
수정된 파일 (5개):
- pages/mobile/public/Album.jsx
  - fetch('/api/albums') → getAlbums()

- pages/mobile/public/Members.jsx
  - fetch('/api/members') → getMembers()

- pages/mobile/public/AlbumDetail.jsx
  - fetch('/api/albums') → getAlbums()
  - fetch('/api/albums/{id}/tracks') → getAlbumTracks()

- pages/mobile/public/AlbumGallery.jsx
  - fetch('/api/albums') → getAlbums()
  - fetch('/api/albums/{id}/photos') → getAlbumPhotos()

- pages/mobile/public/Schedule.jsx
  - fetch('/api/schedules?year=...') → getSchedules()
  - fetch('/api/schedules/categories') → getCategories()
  - fetch('/api/schedules?search=...') → searchSchedules()

Home.jsx는 이미 API 모듈 사용 중이므로 제외
2026-01-10 00:02:42 +09:00
8e01692d6e refactor: ConfirmDialog 추가 적용 및 일정 제목 truncate 제거
수정된 파일:
- AdminScheduleCategory.jsx (50줄 → 15줄, 35줄 제거)
- AdminAlbumPhotos.jsx (60줄 → 15줄, 45줄 제거)
- AdminScheduleForm.jsx (55줄 → 12줄, 43줄 제거)
- AdminSchedule.jsx 일정 제목 truncate 2곳 제거

총 약 220줄의 중복 코드 제거
2026-01-09 23:44:37 +09:00
d52b43397c refactor: ConfirmDialog 공통 컴포넌트 생성 및 적용
새로 생성된 파일:
- components/admin/ConfirmDialog.jsx (109줄)
  - 삭제 확인 등 위험한 작업을 위한 공통 다이얼로그
  - Props: isOpen, onClose, onConfirm, title, message, loading, variant 등

수정된 파일:
- pages/pc/admin/AdminAlbums.jsx (60줄 → 15줄)
- pages/pc/admin/AdminSchedule.jsx (70줄 → 17줄)

총 약 100줄의 중복 코드 제거
2026-01-09 23:36:34 +09:00
5c812b7ac5 fix: AdminAlbumPhotos 로딩 시 헤더 유지
- 로딩 상태에서도 AdminHeader 표시
- 콘텐츠 영역만 스피너로 대체
- 페이지 전환 시 헤더 깜빡임 해결
2026-01-09 23:28:58 +09:00
b37ca360a5 fix: AdminAlbumForm 페이지 전환 애니메이션 제거
- motion.div를 일반 div로 변경
- pageVariants 변수 제거
- 다른 Admin 페이지와 일관성 유지
- 페이지 전환 시 헤더 깜빡임 해결
2026-01-09 23:25:48 +09:00
97fb4b7964 refactor: AdminHeader 공통 컴포넌트를 모든 Admin 페이지에 적용
새로 생성된 파일:
- components/admin/AdminHeader.jsx (47줄)

수정된 파일 (10개):
- pages/pc/admin/AdminMembers.jsx
- pages/pc/admin/AdminMemberEdit.jsx
- pages/pc/admin/AdminAlbums.jsx
- pages/pc/admin/AdminAlbumForm.jsx
- pages/pc/admin/AdminAlbumPhotos.jsx
- pages/pc/admin/AdminSchedule.jsx
- pages/pc/admin/AdminScheduleForm.jsx
- pages/pc/admin/AdminScheduleBots.jsx
- pages/pc/admin/AdminScheduleCategory.jsx
- pages/pc/admin/AdminDashboard.jsx

각 파일에서:
- 중복 헤더 JSX 제거 (24줄 → 1줄)
- handleLogout 함수 제거 (4~6줄)
- LogOut import 제거

총 약 300줄의 중복 코드 제거
2026-01-09 23:18:48 +09:00
7f9c53b53a refactor: AdminHeader 공통 컴포넌트 생성 및 AdminMembers 적용
새로 생성된 파일:
- components/admin/AdminHeader.jsx (47줄)
  - 로고, Admin 배지, 사용자 정보, 로그아웃 버튼 포함

수정된 파일:
- pages/pc/admin/AdminMembers.jsx
  - AdminHeader import 추가
  - 중복 헤더 JSX 제거 (24줄 -> 1줄)
  - handleLogout 함수 제거 (5줄)

나머지 9개 Admin 페이지도 동일한 패턴으로 적용 가능
2026-01-09 23:09:11 +09:00
07a0c30f0f refactor: NumberPicker, CustomTimePicker 공통 컴포넌트로 분리
새로 생성된 파일:
- components/admin/NumberPicker.jsx (185줄)
- components/admin/CustomTimePicker.jsx (176줄)

수정된 파일:
- pages/pc/admin/AdminScheduleForm.jsx (362줄 제거)

AdminScheduleForm에서 중복 정의된 NumberPicker, CustomTimePicker를
별도 파일로 분리하고 import로 대체.

총 코드 변화: 361줄 → 0줄 (361줄 제거)
2026-01-09 23:05:38 +09:00
0b00055773 refactor: useToast 커스텀 훅으로 Toast 로직 통합
- hooks/useToast.js 생성 (44줄)
- 적용 파일 (9개):
  - AdminMembers.jsx
  - AdminMemberEdit.jsx
  - AdminAlbums.jsx
  - AdminAlbumForm.jsx
  - AdminAlbumPhotos.jsx
  - AdminSchedule.jsx
  - AdminScheduleForm.jsx
  - AdminScheduleBots.jsx
  - AdminScheduleCategory.jsx
- 각 파일에서 중복된 toast useState/useEffect 제거
- showSuccess/showError 편의 메서드 활용

총 약 70줄의 중복 코드 제거
2026-01-09 22:57:34 +09:00
3367f4806d chore: scrape 파일 gitignore에 추가 2026-01-09 22:49:26 +09:00
8424c3422d fix: Schedule 페이지 오류 수정 및 년월 선택 스타일 통일
- Schedule.jsx: yearRange, monthNames 변수 누락 수정
- Schedule.jsx, AdminSchedule.jsx: 현재 년도/월 테두리 제거, 글씨색만 유지
- CustomDatePicker.jsx: 동일 스타일 적용
2026-01-09 22:47:32 +09:00
7867eb8928 refactor: CustomDatePicker 공통 컴포넌트로 분리
- components/admin/CustomDatePicker.jsx 생성 (269줄)
- AdminMemberEdit에서 중복 제거 (-237줄)
- AdminAlbumForm에서 중복 제거 (-273줄)
- AdminScheduleForm에서 중복 제거 (-349줄)
- 현재 년도/월 표시: 테두리 제거, 글씨색만 유지
- 오늘 날짜: 배경색 제거, 글씨색만 유지
- 요일/일요일/토요일 색상 구분 추가

총 코드 감소: 약 860줄
2026-01-09 22:42:33 +09:00
8124a1abe1 refactor: 모든 Admin 페이지 API 모듈화 완료
- AdminMemberEdit API 모듈 적용
- AdminScheduleForm API 모듈 적용
- AdminAlbumPhotos API 모듈 적용 (업로드는 SSE 유지)
- api/admin/albums.js에 getAlbumTeasers, deleteAlbumTeaser 추가

총 적용 완료:
- Public 페이지: 7개
- Admin 페이지: 10개 전체 완료
2026-01-09 22:26:37 +09:00
f006309ef4 refactor: 남은 Admin 페이지 API 모듈 적용 완료
- AdminAlbums API 모듈 적용

총 적용 완료:
- Public 페이지: 7개 (PC 6 + 모바일 1)
- Admin 페이지: 7개 (Schedule, ScheduleBots, ScheduleCategory, Login, Dashboard, Albums, Schedule)
2026-01-09 22:16:25 +09:00
fbb68e66ee refactor: 인증 API 모듈화 및 Admin 페이지 적용 완료
- api/admin/auth.js 인증 모듈 생성 (verifyToken, login, logout, hasToken 등)
- categories.js reorderCategories 경로 수정
- AdminScheduleCategory 전체 API 모듈 적용
- AdminLogin API 모듈 적용
- AdminDashboard API 모듈 적용

남은 작업: AdminAlbums, AdminAlbumPhotos, AdminMemberEdit, AdminScheduleForm
2026-01-09 22:15:10 +09:00
0722ca10f3 refactor: API 중앙화 최종 (5/5)
- Schedule.jsx import 경로 오류 수정
- AdminSchedule.jsx API 모듈 적용 (schedulesApi, categoriesApi)
- 전체: PC public 6개, 모바일 Home 1개, Admin 2개 적용 완료
2026-01-09 22:09:42 +09:00
0ff9f196f1 refactor: PC/모바일 public 페이지 API 모듈 적용 (4/5)
- PC: Schedule, Home, Album, AlbumDetail, AlbumGallery, Members
- 모바일: Home
- albums.js에 getAlbumByName 추가
- schedules.js에 getUpcomingSchedules 추가
2026-01-09 22:06:56 +09:00
20f496ca24 refactor: API 중앙화 마무리 (3/3)
- api/public/ import 경로 ../index로 수정
- schedules.js에 getUpcomingSchedules 함수 추가
- Home.jsx API 모듈 적용
2026-01-09 22:02:04 +09:00
e994aa08ca refactor: API 및 페이지 폴더 구조 정리 (2/3)
- api/schedules, albums, members → api/public/로 이동
- pages/pc/*.jsx → pages/pc/public/로 이동
- pages/mobile/*.jsx → pages/mobile/public/로 이동
- App.jsx 라우터 경로 수정
- 모든 public 페이지의 import 경로 수정
2026-01-09 22:00:14 +09:00
9886048a4c refactor: API 중앙화 시작 (1/3)
- api/ 디렉토리 구조 생성
  - index.js: 공통 fetch 래퍼
  - schedules.js, albums.js, members.js: 공개 API
  - admin/: 어드민 API (bots, albums, categories, members, schedules)
- Schedule.jsx: API 모듈 적용
- AdminScheduleBots.jsx: API 모듈 적용
2026-01-09 21:56:32 +09:00
12e95003ae fix: Schedule 카테고리 '전체' 카운트를 선택된 날짜 기준으로 수정
- categoryCounts.get('total')로 변경하여 선택된 날짜 기준으로 표시
2026-01-09 21:43:45 +09:00
71a206da36 feat: Schedule 페이지 카테고리 카운트 선택된 날짜 기준으로 변경
- categoryCounts useMemo 맵 추가
- 선택된 날짜가 있으면 해당 날짜의 일정만 카테고리 카운트
- O(1) 조회로 성능 최적화
2026-01-09 21:42:29 +09:00
80fad4d055 perf: 일정 페이지 월별 데이터 로딩으로 변경
- 프론트엔드: currentDate 변경 시 해당 월 일정만 로드
- 백엔드: /api/schedules에 year/month 파라미터 지원 추가
- 초기 로딩 속도 개선 (전체 로드 → 월별 로드)
2026-01-09 21:38:29 +09:00
2b6fa74eb8 perf: Schedule 페이지 성능 최적화
- useDeferredValue로 달력 점 표시 지연 처리
- scheduleDateMap으로 O(1) 조회 최적화
- selectedDate 변경 시 스크롤 맨 위로 초기화
2026-01-09 20:34:26 +09:00
8db0a574ab fix: 봇 관리 페이지 애니메이션 최적화
- 시작/중지 시 로컬 상태만 업데이트하여 전체 목록 새로고침 방지
- isInitialLoad 상태로 첫 로드 시에만 애니메이션 실행
- 새로고침 버튼 클릭 시에도 애니메이션 실행
2026-01-09 20:31:47 +09:00
330eb46ff4 fix: 봇 상태 동기화 로직 개선
- syncBotStatuses에서 bot.id를 parseInt로 변환
- 메모리에 없는 running 봇을 stopped로 변경하는 대신 재등록
- 서버 재시작 시에도 봇이 자동으로 유지되도록 개선
2026-01-09 19:37:29 +09:00
b161f1a9f7 fix: 봇 스케줄러 botId 타입 불일치 수정
- registerBot, unregisterBot, isBotRunning에서 botId를 parseInt()로 정수 변환
- URL 파라미터(문자열)와 DB 조회 결과(숫자) 간 타입 일치 문제 해결
- 10초 상태 동기화에서 메모리 스케줄러를 찾지 못해 stopped로 변경되던 버그 수정
2026-01-09 19:31:11 +09:00
fc35a35987 perf: AdminSchedule 성능 최적화
- filteredSchedules useMemo로 불필요한 재계산 방지
- ScheduleItem React.memo 컴포넌트로 분리하여 리렌더링 방지
- categoryCounts useMemo 맵으로 O(1) 카테고리 카운트 조회
- 카테고리 카운트를 선택된 날짜 기준으로 계산
- useDeferredValue로 달력 점 표시 지연 처리하여 UI 응답성 향상
- selectedDate 변경 시 스크롤 맨 위로 초기화
2026-01-09 19:26:52 +09:00
a2f89644a6 fix: body.is-pc 클래스 기반 PC CSS 분리
- App.jsx에 PCWrapper 추가하여 PC에서만 body.is-pc 클래스 추가
- pc.css를 body.is-pc 기반으로 변경하여 모바일 영향 없앰
- useEffect import 추가
2026-01-09 18:14:44 +09:00
2aff770134 fix: pc.css에 미디어 쿼리 추가하여 모바일 영향 방지 2026-01-09 18:08:48 +09:00
4cbfeb5168 refactor: CSS를 공통/PC/모바일로 분리
- index.css: 공통 스타일 (tailwind, 스크롤바, 트랜지션)
- pc.css: PC 전용 (min-width, 스크롤바 공간)
- mobile.css: 모바일 전용 (레이아웃, 달력 스타일)
- 각 Layout 컴포넌트에서 해당 CSS import
2026-01-09 18:05:07 +09:00
494c2a9d6d perf: AdminSchedule 달력 렌더링 성능 최적화
- scheduleDateMap useMemo로 O(1) 조회 구현
- hasSchedule, getScheduleColor 함수 배열 순회 제거
2026-01-09 17:53:58 +09:00
4619d101f0 refactor: 전체보기 기능 제거 및 날짜 선택 기본값 개선
- 전체보기 버튼 제거
- 월 이동 시 이번달이면 오늘, 다른 달이면 1일 자동 선택
- 같은 날짜 클릭 시 토글 제거 (항상 선택 유지)
- 필터링 대상 줄여서 성능 개선
2026-01-09 17:35:15 +09:00
578ab25568 feat: 모바일 일정 날짜 변경 시 스크롤 맨 위로 초기화
- contentRef 추가하여 mobile-content 요소 참조
- selectedDate 변경 시 useEffect로 scrollTop = 0 설정
2026-01-09 15:04:27 +09:00
d0b78f0b5d refactor: AdminSchedule, AdminScheduleForm 날짜 파싱에 formatDate 유틸리티 적용
- AdminSchedule.jsx: hasSchedule, getScheduleColor, filteredSchedules에서 formatDate 사용
- AdminScheduleForm.jsx: 수정 모드 날짜 로드 시 formatDate 사용
- toISOString 대신 dayjs 기반 formatDate 사용
2026-01-09 09:57:51 +09:00
0d72dfe456 feat: dayjs 라이브러리로 날짜 계산 로직 통합
- dayjs 패키지 설치 (타임존 지원)
- utils/date.js 유틸리티 생성 (getTodayKST, formatDate, parseDateKST 등)
- PC/모바일 Home.jsx의 날짜 계산을 유틸리티로 교체
- PC Schedule.jsx, AdminSchedule.jsx의 getTodayKST 함수를 유틸리티로 교체
- KST 타임존 기준으로 정확한 날짜 계산 보장
2026-01-09 09:46:54 +09:00
cca25b456c feat(mobile): 모바일 레이아웃 시스템 구축 - 컨텐츠 영역만 스크롤되도록 개선
- index.css: 모바일 레이아웃 CSS 시스템 추가 (mobile-layout-container, mobile-content, mobile-toolbar)
- Layout.jsx: MobileLayout에서 레이아웃 및 body 스크롤 제어 통합
- 하단 네비게이션을 fixed에서 flex-shrink-0으로 변경
- 모바일 스크롤바 숨김 처리
- Home, Members, Album, Schedule 페이지 여백 정리
2026-01-09 09:26:51 +09:00
20546599cc feat: YouTube API 할당량 경고 시스템 구현
- RSS 방식에서 YouTube API 방식으로 변경 (최근 10개 영상 조회)
- rss_url 컬럼 삭제
- Google Cloud Webhook으로 할당량 경고 수신
- 95% 도달 시 봇 자동 중지
- LA 시간 자정(할당량 리셋)에 봇 자동 재시작
- 봇 관리 페이지에 경고 배너 표시
2026-01-07 23:54:35 +09:00
030c495c01 모바일 일정: 달력 점 표시 PC 버전과 통일, 멤버 배지 초록색, 월 변경 시 날짜 선택 로직 개선 2026-01-07 16:00:42 +09:00
f2b0170cf8 모바일 일정: 달력 헤더 툴바 통합, 년월 드롭다운 개선 2026-01-07 15:20:30 +09:00
767cbcaf5f refactor(mobile): Swiper 제거하고 터치 제스처 방식 CalendarPicker로 변경 2026-01-07 14:23:02 +09:00
0750dded97 refactor(pc): 홈/멤버 페이지 UI 개선
- 홈: 퀵 링크 제거, 통계 섹션(데뷔일/D+Day/멤버수/팬덤명) 추가
- 홈: 모든 섹션 배경색 회색(bg-gray-50)으로 통일
- 멤버: 전 멤버 카드 UI를 현재 멤버와 동일하게 변경 (5열 그리드)
- 멤버: 불필요한 stats API 호출 제거
2026-01-07 10:30:09 +09:00
f958e2b5e2 feat(mobile): 모바일 페이지 기본 구현
- 모바일 레이아웃 및 하단 네비게이션 추가
- 홈 페이지: 히어로, 멤버, 앨범(2개), 일정 섹션
- 멤버 페이지: 현재/전 멤버 분리, 상세 모달
- 앨범 페이지: 목록, 상세, 갤러리
- 일정 페이지: 캘린더 피커, 세로 스크롤 목록
- ScrollToTop 컴포넌트로 페이지 이동 시 스크롤 초기화
- PC 홈 일정 API startDate+limit 방식으로 변경
2026-01-07 10:10:12 +09:00
c54de2ba82 feat: useInfiniteQuery 기반 무한 스크롤 구현 및 UI 개선
- react-infinite-scroll-component를 useInfiniteQuery + useInView로 대체
- Schedule.jsx, AdminSchedule.jsx에 안정적인 무한 스크롤 적용
- source_name에 Link2 아이콘 추가 (카테고리 오른쪽 인라인 표시)
- 멤버 5명 이상일 경우 '프로미스나인'으로 표시 (탈퇴 멤버 고려)
- AdminSchedule 일반 모드에서 members 배열도 확인하여 멤버 표시
- QueryClientProvider 설정 추가 (main.jsx)
2026-01-06 19:48:43 +09:00
2278d42026 chore: 환경 변수 파일 업데이트 2026-01-06 14:17:31 +09:00
bb027df914 feat: 일정 관련 UI/UX 개선
- 카테고리 정렬: 일정 개수 기준 내림차순, 0개 숨김, 기타는 맨 아래 고정
- useMemo로 카테고리 정렬 메모이제이션 (깜빡임 방지)
- 일정 수정 시 이미지 삭제 버그 수정 (existingImageIds 업데이트)
- 이미지 파일명에서 Date.now() 제거 (01.webp 형식 유지)
- 이미지 삭제 후 sort_order 재정렬 로직 추가
- 날짜 선택 시 요일 표시 추가 (2026년 1월 7일 (수) 형식)
2026-01-06 14:16:29 +09:00
63 changed files with 7472 additions and 3756 deletions

2
.env
View file

@ -18,7 +18,7 @@ RUSTFS_SECRET_KEY=tDTwLkcHN5UVuWnea2s8OECrmiv013qoSQIpYbBd
RUSTFS_BUCKET=fromis-9
# Kakao API
KAKAO_REST_KEY=cf21156ae6cc8f6e95b3a3150926cdf8
KAKAO_REST_KEY=e7a5516bf6cb1b398857789ee2ea6eea
# YouTube API
YOUTUBE_API_KEY=AIzaSyC6l3nFlcHgLc0d1Q9WPyYQjVKTv21ZqFs

5
.gitignore vendored
View file

@ -19,3 +19,8 @@ Thumbs.db
dist/
build/
meilisearch_data/
# Scrape files
backend/scrape_*.cjs
backend/scrape_*.js
backend/scrape_*.txt

View file

@ -10,6 +10,8 @@ import {
} from "@aws-sdk/client-s3";
import pool from "../lib/db.js";
import { syncNewVideos, syncAllVideos } from "../services/youtube-bot.js";
import { syncAllTweets } from "../services/x-bot.js";
import { syncAllSchedules } from "../services/meilisearch-bot.js";
import { startBot, stopBot } from "../services/youtube-scheduler.js";
import {
addOrUpdateSchedule,
@ -1607,7 +1609,8 @@ router.put(
const file = req.files[i];
currentOrder++;
const orderNum = String(currentOrder).padStart(2, "0");
const filename = `${orderNum}_${Date.now()}.webp`;
// 파일명: 01.webp, 02.webp 형식 (Date.now() 제거)
const filename = `${orderNum}.webp`;
const imageBuffer = await sharp(file.buffer)
.webp({ quality: 90 })
@ -1631,6 +1634,18 @@ router.put(
}
}
// sort_order 재정렬 (삭제로 인한 간격 제거)
const [remainingImages] = await connection.query(
"SELECT id FROM schedule_images WHERE schedule_id = ? ORDER BY sort_order ASC",
[id]
);
for (let i = 0; i < remainingImages.length; i++) {
await connection.query(
"UPDATE schedule_images SET sort_order = ? WHERE id = ?",
[i + 1, remainingImages[i].id]
);
}
await connection.commit();
// Meilisearch 동기화
@ -1735,9 +1750,12 @@ router.delete("/schedules/:id", authenticateToken, async (req, res) => {
router.get("/bots", authenticateToken, async (req, res) => {
try {
const [bots] = await pool.query(`
SELECT b.*, c.channel_id, c.rss_url, c.channel_name
SELECT b.*,
yc.channel_id, yc.channel_name,
xc.username, xc.nitter_url
FROM bots b
LEFT JOIN bot_youtube_config c ON b.id = c.bot_id
LEFT JOIN bot_youtube_config yc ON b.id = yc.bot_id
LEFT JOIN bot_x_config xc ON b.id = xc.bot_id
ORDER BY b.id ASC
`);
res.json(bots);
@ -1779,7 +1797,28 @@ router.post("/bots/:id/stop", authenticateToken, async (req, res) => {
router.post("/bots/:id/sync-all", authenticateToken, async (req, res) => {
try {
const { id } = req.params;
const result = await syncAllVideos(id);
// 봇 타입 조회
const [bots] = await pool.query("SELECT type FROM bots WHERE id = ?", [id]);
if (bots.length === 0) {
return res.status(404).json({ error: "봇을 찾을 수 없습니다." });
}
const botType = bots[0].type;
let result;
if (botType === "youtube") {
result = await syncAllVideos(id);
} else if (botType === "x") {
result = await syncAllTweets(id);
} else if (botType === "meilisearch") {
result = await syncAllSchedules(id);
} else {
return res
.status(400)
.json({ error: `지원하지 않는 봇 타입: ${botType}` });
}
res.json({
message: `${result.addedCount}개 일정이 추가되었습니다.`,
addedCount: result.addedCount,
@ -1793,4 +1832,154 @@ router.post("/bots/:id/sync-all", authenticateToken, async (req, res) => {
}
});
// =====================================================
// YouTube API 할당량 경고 Webhook
// =====================================================
// 메모리에 경고 상태 저장 (서버 재시작 시 초기화)
let quotaWarning = {
active: false,
timestamp: null,
message: null,
stoppedBots: [], // 할당량 초과로 중지된 봇 ID 목록
};
// 자정 재시작 타이머
let quotaResetTimer = null;
/**
* 자정(LA 시간) 재시작 예약
* YouTube 할당량은 LA 태평양 시간 자정에 리셋됨
*/
async function scheduleQuotaReset() {
// 기존 타이머 취소
if (quotaResetTimer) {
clearTimeout(quotaResetTimer);
}
// LA 시간으로 다음 자정 계산
const now = new Date();
const laTime = new Date(
now.toLocaleString("en-US", { timeZone: "America/Los_Angeles" })
);
const tomorrow = new Date(laTime);
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(0, 1, 0, 0); // 자정 1분 후 (안전 마진)
// 현재 LA 시간과 다음 자정까지의 밀리초 계산
const nowLA = new Date(
now.toLocaleString("en-US", { timeZone: "America/Los_Angeles" })
);
const msUntilReset = tomorrow.getTime() - nowLA.getTime();
console.log(
`[Quota Reset] ${Math.round(
msUntilReset / 1000 / 60
)} 재시작 예약됨`
);
quotaResetTimer = setTimeout(async () => {
console.log("[Quota Reset] 할당량 리셋 시간 도달, 봇 재시작 중...");
try {
// 할당량 초과로 중지된 봇들만 재시작
for (const botId of quotaWarning.stoppedBots) {
await startBot(botId);
console.log(`[Quota Reset] Bot ${botId} 재시작됨`);
}
// 경고 상태 초기화
quotaWarning = {
active: false,
timestamp: null,
message: null,
stoppedBots: [],
};
console.log("[Quota Reset] 모든 봇 재시작 완료, 경고 상태 초기화");
} catch (error) {
console.error("[Quota Reset] 봇 재시작 오류:", error.message);
}
}, msUntilReset);
}
// Webhook 인증 정보
const WEBHOOK_USERNAME = "fromis9_quota_webhook";
const WEBHOOK_PASSWORD = "Qw8$kLm3nP2xVr7tYz!9";
// Basic Auth 검증 미들웨어
const verifyWebhookAuth = (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith("Basic ")) {
return res.status(401).json({ error: "인증이 필요합니다." });
}
const base64Credentials = authHeader.split(" ")[1];
const credentials = Buffer.from(base64Credentials, "base64").toString(
"utf-8"
);
const [username, password] = credentials.split(":");
if (username !== WEBHOOK_USERNAME || password !== WEBHOOK_PASSWORD) {
return res.status(401).json({ error: "인증 실패" });
}
next();
};
// Google Cloud 할당량 경고 Webhook 수신
router.post("/quota-alert", verifyWebhookAuth, async (req, res) => {
console.log("[Quota Alert] Google Cloud에서 할당량 경고 수신:", req.body);
quotaWarning = {
active: true,
timestamp: new Date().toISOString(),
message:
"일일 할당량의 95%를 사용했습니다. (9,500 / 10,000 units) - 봇이 자동 중지되었습니다.",
};
// 모든 실행 중인 봇 중지
try {
const [runningBots] = await pool.query(
"SELECT id, name FROM bots WHERE status = 'running'"
);
// 중지된 봇 ID 저장 (자정에 재시작용)
quotaWarning.stoppedBots = runningBots.map((bot) => bot.id);
for (const bot of runningBots) {
await stopBot(bot.id);
console.log(`[Quota Alert] Bot ${bot.name} 중지됨`);
}
console.log(
`[Quota Alert] ${runningBots.length}개 봇이 할당량 초과로 중지됨`
);
// 자정에 봇 재시작 예약 (LA 시간 기준 = YouTube 할당량 리셋 시간)
scheduleQuotaReset();
} catch (error) {
console.error("[Quota Alert] 봇 중지 오류:", error.message);
}
res
.status(200)
.json({ success: true, message: "경고가 등록되고 봇이 중지되었습니다." });
});
// 할당량 경고 상태 조회 (프론트엔드용)
router.get("/quota-warning", authenticateToken, (req, res) => {
res.json(quotaWarning);
});
// 할당량 경고 해제 (수동)
router.delete("/quota-warning", authenticateToken, (req, res) => {
quotaWarning = {
active: false,
timestamp: null,
message: null,
};
res.json({ success: true, message: "경고가 해제되었습니다." });
});
export default router;

View file

@ -7,18 +7,38 @@ const router = express.Router();
// 공개 일정 목록 조회 (검색 포함)
router.get("/", async (req, res) => {
try {
const { search, startDate, endDate, limit } = req.query;
const { search, startDate, endDate, limit, year, month } = req.query;
// 검색어가 있으면 Meilisearch 사용
if (search && search.trim()) {
const results = await searchSchedules(search.trim());
return res.json(results);
const offset = parseInt(req.query.offset) || 0;
const pageLimit = parseInt(req.query.limit) || 20;
const results = await searchSchedules(search.trim(), {
offset,
limit: pageLimit,
});
return res.json({
schedules: results.hits,
total: results.total,
offset: results.offset,
limit: results.limit,
hasMore: results.offset + results.hits.length < results.total,
});
}
// 날짜 필터 및 제한 조건 구성
let whereClause = "WHERE 1=1";
const params = [];
// 년/월 필터링 (월별 데이터 로딩용)
if (year && month) {
whereClause += " AND YEAR(s.date) = ? AND MONTH(s.date) = ?";
params.push(parseInt(year), parseInt(month));
} else if (year) {
whereClause += " AND YEAR(s.date) = ?";
params.push(parseInt(year));
}
if (startDate) {
whereClause += " AND s.date >= ?";
params.push(startDate);

View file

@ -0,0 +1,84 @@
/**
* Meilisearch 동기화 서비스
* 모든 일정을 Meilisearch에 동기화
*/
import pool from "../lib/db.js";
import { addOrUpdateSchedule } from "./meilisearch.js";
/**
* 전체 일정 Meilisearch 동기화
*/
export async function syncAllSchedules(botId) {
try {
const startTime = Date.now();
// 모든 일정 조회
const [schedules] = await pool.query(`
SELECT s.id, s.title, s.description, s.date, s.time,
s.category_id, s.source_url, s.source_name,
c.name as category_name, c.color as category_color
FROM schedules s
LEFT JOIN schedule_categories c ON s.category_id = c.id
`);
let synced = 0;
for (const s of schedules) {
// 멤버 조회
const [members] = await pool.query(
"SELECT m.id, m.name FROM schedule_members sm JOIN members m ON sm.member_id = m.id WHERE sm.schedule_id = ?",
[s.id]
);
// Meilisearch 동기화
await addOrUpdateSchedule({
id: s.id,
title: s.title,
description: s.description || "",
date: s.date,
time: s.time,
category_id: s.category_id,
category_name: s.category_name || "",
category_color: s.category_color || "",
source_name: s.source_name,
source_url: s.source_url,
members: members,
});
synced++;
}
const elapsedMs = Date.now() - startTime;
const elapsedSec = (elapsedMs / 1000).toFixed(2);
// 봇 상태 업데이트 (schedules_added = 동기화 수, last_added_count = 소요시간 ms)
await pool.query(
`UPDATE bots SET
last_check_at = NOW(),
schedules_added = ?,
last_added_count = ?,
error_message = NULL
WHERE id = ?`,
[synced, elapsedMs, botId]
);
console.log(`[Meilisearch Bot] ${synced}개 동기화 완료 (${elapsedSec}초)`);
return { synced, elapsed: elapsedSec };
} catch (error) {
// 오류 상태 업데이트
await pool.query(
`UPDATE bots SET
last_check_at = NOW(),
status = 'error',
error_message = ?
WHERE id = ?`,
[error.message, botId]
);
throw error;
}
}
export default {
syncAllSchedules,
};

View file

@ -53,6 +53,11 @@ export async function initMeilisearch() {
},
});
// 페이징 설정 (기본 1000개 제한 해제)
await index.updatePagination({
maxTotalHits: 10000, // 최대 10000개까지 조회 가능
});
console.log("[Meilisearch] 인덱스 초기화 완료");
} catch (error) {
console.error("[Meilisearch] 초기화 오류:", error.message);
@ -106,15 +111,17 @@ export async function deleteSchedule(scheduleId) {
}
/**
* 일정 검색
* 일정 검색 (페이징 지원)
*/
export async function searchSchedules(query, options = {}) {
try {
const index = client.index(SCHEDULE_INDEX);
const searchOptions = {
limit: options.limit || 50,
limit: options.limit || 1000, // 기본 1000개 (Meilisearch 최대)
offset: options.offset || 0, // 페이징용 offset
attributesToRetrieve: ["*"],
showRankingScore: true, // 유사도 점수 포함
};
// 카테고리 필터
@ -129,10 +136,19 @@ export async function searchSchedules(query, options = {}) {
const results = await index.search(query, searchOptions);
return results.hits;
// 유사도 0.5 미만인 결과 필터링
const filteredHits = results.hits.filter((hit) => hit._rankingScore >= 0.5);
// 페이징 정보 포함 반환
return {
hits: filteredHits,
total: filteredHits.length, // 필터링 후 결과 수
offset: searchOptions.offset,
limit: searchOptions.limit,
};
} catch (error) {
console.error("[Meilisearch] 검색 오류:", error.message);
return [];
return { hits: [], total: 0, offset: 0, limit: 0 };
}
}

629
backend/services/x-bot.js Normal file
View file

@ -0,0 +1,629 @@
/**
* X 서비스
*
* - Nitter를 통해 @realfromis_9 트윗 수집
* - 트윗을 schedules 테이블에 저장
* - 유튜브 링크 감지 별도 일정 추가
*/
import pool from "../lib/db.js";
import { addOrUpdateSchedule } from "./meilisearch.js";
// YouTube API 키
const YOUTUBE_API_KEY =
process.env.YOUTUBE_API_KEY || "AIzaSyBmn79egY0M_z5iUkqq9Ny0zVFP6PoYCzM";
// X 카테고리 ID
const X_CATEGORY_ID = 12;
// 유튜브 카테고리 ID
const YOUTUBE_CATEGORY_ID = 7;
/**
* UTC KST 변환
*/
export function toKST(utcDate) {
const date = new Date(utcDate);
return new Date(date.getTime() + 9 * 60 * 60 * 1000);
}
/**
* 날짜를 YYYY-MM-DD 형식으로 변환
*/
export function formatDate(date) {
return date.toISOString().split("T")[0];
}
/**
* 시간을 HH:MM:SS 형식으로 변환
*/
export function formatTime(date) {
return date.toTimeString().split(" ")[0];
}
/**
* Nitter 날짜 파싱 ("Jan 7, 2026 · 12:00 PM UTC" Date)
*/
function parseNitterDateTime(timeStr) {
if (!timeStr) return null;
try {
const cleaned = timeStr.replace(" · ", " ").replace(" UTC", "");
const date = new Date(cleaned + " UTC");
if (isNaN(date.getTime())) return null;
return date;
} catch (e) {
return null;
}
}
/**
* 트윗 텍스트에서 문단 추출 (title용)
*/
export function extractTitle(text) {
if (!text) return "";
// 빈 줄(\n\n)로 분리하여 첫 문단 추출
const paragraphs = text.split(/\n\n+/);
const firstParagraph = paragraphs[0]?.trim() || "";
return firstParagraph;
}
/**
* 텍스트에서 유튜브 videoId 추출
*/
export function extractYoutubeVideoIds(text) {
if (!text) return [];
const videoIds = [];
// youtu.be/{videoId} 형식
const shortMatches = text.match(/youtu\.be\/([a-zA-Z0-9_-]{11})/g);
if (shortMatches) {
shortMatches.forEach((m) => {
const id = m.replace("youtu.be/", "");
if (id && id.length === 11) videoIds.push(id);
});
}
// youtube.com/watch?v={videoId} 형식
const watchMatches = text.match(
/youtube\.com\/watch\?v=([a-zA-Z0-9_-]{11})/g
);
if (watchMatches) {
watchMatches.forEach((m) => {
const id = m.match(/v=([a-zA-Z0-9_-]{11})/)?.[1];
if (id) videoIds.push(id);
});
}
// youtube.com/shorts/{videoId} 형식
const shortsMatches = text.match(
/youtube\.com\/shorts\/([a-zA-Z0-9_-]{11})/g
);
if (shortsMatches) {
shortsMatches.forEach((m) => {
const id = m.match(/shorts\/([a-zA-Z0-9_-]{11})/)?.[1];
if (id) videoIds.push(id);
});
}
return [...new Set(videoIds)];
}
/**
* 관리 중인 채널 ID 목록 조회
*/
export async function getManagedChannelIds() {
const [configs] = await pool.query(
"SELECT channel_id FROM bot_youtube_config"
);
return configs.map((c) => c.channel_id);
}
/**
* YouTube API로 영상 정보 조회
*/
async function fetchVideoInfo(videoId) {
try {
const url = `https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=${videoId}&key=${YOUTUBE_API_KEY}`;
const response = await fetch(url);
const data = await response.json();
if (!data.items || data.items.length === 0) {
return null;
}
const video = data.items[0];
const snippet = video.snippet;
const duration = video.contentDetails?.duration || "";
// duration 파싱
const durationMatch = duration.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);
let seconds = 0;
if (durationMatch) {
seconds =
parseInt(durationMatch[1] || 0) * 3600 +
parseInt(durationMatch[2] || 0) * 60 +
parseInt(durationMatch[3] || 0);
}
const isShorts = seconds > 0 && seconds <= 60;
return {
videoId,
title: snippet.title,
description: snippet.description || "",
channelId: snippet.channelId,
channelTitle: snippet.channelTitle,
publishedAt: new Date(snippet.publishedAt),
isShorts,
videoUrl: isShorts
? `https://www.youtube.com/shorts/${videoId}`
: `https://www.youtube.com/watch?v=${videoId}`,
};
} catch (error) {
console.error(`영상 정보 조회 오류 (${videoId}):`, error.message);
return null;
}
}
/**
* Nitter에서 트윗 수집 ( 페이지만)
*/
async function fetchTweetsFromNitter(nitterUrl, username) {
const url = `${nitterUrl}/${username}`;
const response = await fetch(url);
const html = await response.text();
const tweets = [];
const tweetContainers = html.split('class="timeline-item ');
for (let i = 1; i < tweetContainers.length; i++) {
const container = tweetContainers[i];
const tweet = {};
// 고정 트윗 체크
tweet.isPinned =
tweetContainers[i - 1].includes("pinned") || container.includes("Pinned");
// 리트윗 체크
tweet.isRetweet = container.includes('class="retweet-header"');
// 트윗 ID 추출
const linkMatch = container.match(/href="\/[^\/]+\/status\/(\d+)/);
tweet.id = linkMatch ? linkMatch[1] : null;
// 시간 추출
const timeMatch = container.match(
/<span class="tweet-date"[^>]*><a[^>]*title="([^"]+)"/
);
tweet.time = timeMatch ? parseNitterDateTime(timeMatch[1]) : null;
// 텍스트 내용 추출
const contentMatch = container.match(
/<div class="tweet-content[^"]*"[^>]*>([\s\S]*?)<\/div>/
);
if (contentMatch) {
tweet.text = contentMatch[1]
.replace(/<br\s*\/?>/g, "\n")
.replace(/<a[^>]*>([^<]*)<\/a>/g, "$1")
.replace(/<[^>]+>/g, "")
.trim();
}
// URL 생성
tweet.url = tweet.id
? `https://x.com/${username}/status/${tweet.id}`
: null;
if (tweet.id && !tweet.isRetweet && !tweet.isPinned) {
tweets.push(tweet);
}
}
return tweets;
}
/**
* Nitter에서 전체 트윗 수집 (페이지네이션)
*/
async function fetchAllTweetsFromNitter(nitterUrl, username) {
const allTweets = [];
let cursor = null;
let pageNum = 1;
let consecutiveEmpty = 0;
const DELAY_MS = 1000;
while (true) {
const url = cursor
? `${nitterUrl}/${username}?cursor=${cursor}`
: `${nitterUrl}/${username}`;
console.log(`[페이지 ${pageNum}] 스크래핑 중...`);
try {
const response = await fetch(url);
const html = await response.text();
const tweets = [];
const tweetContainers = html.split('class="timeline-item ');
for (let i = 1; i < tweetContainers.length; i++) {
const container = tweetContainers[i];
const tweet = {};
tweet.isPinned =
tweetContainers[i - 1].includes("pinned") ||
container.includes("Pinned");
tweet.isRetweet = container.includes('class="retweet-header"');
const linkMatch = container.match(/href="\/[^\/]+\/status\/(\d+)/);
tweet.id = linkMatch ? linkMatch[1] : null;
const timeMatch = container.match(
/<span class="tweet-date"[^>]*><a[^>]*title="([^"]+)"/
);
tweet.time = timeMatch ? parseNitterDateTime(timeMatch[1]) : null;
const contentMatch = container.match(
/<div class="tweet-content[^"]*"[^>]*>([\s\S]*?)<\/div>/
);
if (contentMatch) {
tweet.text = contentMatch[1]
.replace(/<br\s*\/?>/g, "\n")
.replace(/<a[^>]*>([^<]*)<\/a>/g, "$1")
.replace(/<[^>]+>/g, "")
.trim();
}
tweet.url = tweet.id
? `https://x.com/${username}/status/${tweet.id}`
: null;
if (tweet.id && !tweet.isRetweet && !tweet.isPinned) {
tweets.push(tweet);
}
}
if (tweets.length === 0) {
consecutiveEmpty++;
console.log(` -> 트윗 없음 (연속 ${consecutiveEmpty}회)`);
if (consecutiveEmpty >= 3) break;
} else {
consecutiveEmpty = 0;
allTweets.push(...tweets);
console.log(` -> ${tweets.length}개 추출 (누적: ${allTweets.length})`);
}
// 다음 페이지 cursor 추출
const cursorMatch = html.match(
/class="show-more"[^>]*>\s*<a href="\?cursor=([^"]+)"/
);
if (!cursorMatch) {
console.log("\n다음 페이지 없음. 스크래핑 완료.");
break;
}
cursor = cursorMatch[1];
pageNum++;
await new Promise((r) => setTimeout(r, DELAY_MS));
} catch (error) {
console.error(` -> 오류: ${error.message}`);
consecutiveEmpty++;
if (consecutiveEmpty >= 5) break;
await new Promise((r) => setTimeout(r, DELAY_MS * 3));
}
}
return allTweets;
}
/**
* 트윗을 일정으로 저장
*/
async function createScheduleFromTweet(tweet) {
// source_url로 중복 체크
const [existing] = await pool.query(
"SELECT id FROM schedules WHERE source_url = ?",
[tweet.url]
);
if (existing.length > 0) {
return null; // 이미 존재
}
const kstDate = toKST(tweet.time);
const date = formatDate(kstDate);
const time = formatTime(kstDate);
const title = extractTitle(tweet.text);
const description = tweet.text;
// 일정 생성
const [result] = await pool.query(
`INSERT INTO schedules (title, description, date, time, category_id, source_url, source_name)
VALUES (?, ?, ?, ?, ?, ?, NULL)`,
[title, description, date, time, X_CATEGORY_ID, tweet.url]
);
const scheduleId = result.insertId;
// Meilisearch 동기화
try {
const [categoryInfo] = await pool.query(
"SELECT name, color FROM schedule_categories WHERE id = ?",
[X_CATEGORY_ID]
);
await addOrUpdateSchedule({
id: scheduleId,
title,
description,
date,
time,
category_id: X_CATEGORY_ID,
category_name: categoryInfo[0]?.name || "",
category_color: categoryInfo[0]?.color || "",
source_name: null,
source_url: tweet.url,
members: [],
});
} catch (searchError) {
console.error("Meilisearch 동기화 오류:", searchError.message);
}
return scheduleId;
}
/**
* 유튜브 영상을 일정으로 저장
*/
async function createScheduleFromYoutube(video) {
// source_url로 중복 체크
const [existing] = await pool.query(
"SELECT id FROM schedules WHERE source_url = ?",
[video.videoUrl]
);
if (existing.length > 0) {
return null; // 이미 존재
}
const kstDate = toKST(video.publishedAt);
const date = formatDate(kstDate);
const time = formatTime(kstDate);
// 일정 생성 (source_name에 채널명 저장)
const [result] = await pool.query(
`INSERT INTO schedules (title, date, time, category_id, source_url, source_name)
VALUES (?, ?, ?, ?, ?, ?)`,
[
video.title,
date,
time,
YOUTUBE_CATEGORY_ID,
video.videoUrl,
video.channelTitle || null,
]
);
const scheduleId = result.insertId;
// Meilisearch 동기화
try {
const [categoryInfo] = await pool.query(
"SELECT name, color FROM schedule_categories WHERE id = ?",
[YOUTUBE_CATEGORY_ID]
);
await addOrUpdateSchedule({
id: scheduleId,
title: video.title,
description: "",
date,
time,
category_id: YOUTUBE_CATEGORY_ID,
category_name: categoryInfo[0]?.name || "",
category_color: categoryInfo[0]?.color || "",
source_name: video.channelTitle || null,
source_url: video.videoUrl,
members: [],
});
} catch (searchError) {
console.error("Meilisearch 동기화 오류:", searchError.message);
}
return scheduleId;
}
/**
* 트윗 동기화 ( 페이지만 - 1 간격 실행용)
*/
export async function syncNewTweets(botId) {
try {
// 봇 정보 조회
const [bots] = await pool.query(
`SELECT b.*, c.username, c.nitter_url
FROM bots b
LEFT JOIN bot_x_config c ON b.id = c.bot_id
WHERE b.id = ?`,
[botId]
);
if (bots.length === 0) {
throw new Error("봇을 찾을 수 없습니다.");
}
const bot = bots[0];
if (!bot.username) {
throw new Error("Username이 설정되지 않았습니다.");
}
const nitterUrl = bot.nitter_url || "http://nitter:8080";
// 관리 중인 채널 목록 조회
const managedChannelIds = await getManagedChannelIds();
// Nitter에서 트윗 수집 (첫 페이지만)
const tweets = await fetchTweetsFromNitter(nitterUrl, bot.username);
let addedCount = 0;
let ytAddedCount = 0;
for (const tweet of tweets) {
// 트윗 저장
const scheduleId = await createScheduleFromTweet(tweet);
if (scheduleId) addedCount++;
// 유튜브 링크 처리
const videoIds = extractYoutubeVideoIds(tweet.text);
for (const videoId of videoIds) {
const video = await fetchVideoInfo(videoId);
if (!video) continue;
// 관리 중인 채널이면 스킵
if (managedChannelIds.includes(video.channelId)) continue;
// 유튜브 일정 저장
const ytScheduleId = await createScheduleFromYoutube(video);
if (ytScheduleId) ytAddedCount++;
}
}
// 봇 상태 업데이트
// 추가된 항목이 있을 때만 last_added_count 업데이트 (0이면 이전 값 유지)
const totalAdded = addedCount + ytAddedCount;
if (totalAdded > 0) {
await pool.query(
`UPDATE bots SET
last_check_at = NOW(),
schedules_added = schedules_added + ?,
last_added_count = ?,
error_message = NULL
WHERE id = ?`,
[totalAdded, totalAdded, botId]
);
} else {
await pool.query(
`UPDATE bots SET
last_check_at = NOW(),
error_message = NULL
WHERE id = ?`,
[botId]
);
}
return { addedCount, ytAddedCount, total: tweets.length };
} catch (error) {
// 오류 상태 업데이트
await pool.query(
`UPDATE bots SET
last_check_at = NOW(),
status = 'error',
error_message = ?
WHERE id = ?`,
[error.message, botId]
);
throw error;
}
}
/**
* 전체 트윗 동기화 (전체 페이지 - 초기화용)
*/
export async function syncAllTweets(botId) {
try {
// 봇 정보 조회
const [bots] = await pool.query(
`SELECT b.*, c.username, c.nitter_url
FROM bots b
LEFT JOIN bot_x_config c ON b.id = c.bot_id
WHERE b.id = ?`,
[botId]
);
if (bots.length === 0) {
throw new Error("봇을 찾을 수 없습니다.");
}
const bot = bots[0];
if (!bot.username) {
throw new Error("Username이 설정되지 않았습니다.");
}
const nitterUrl = bot.nitter_url || "http://nitter:8080";
// 관리 중인 채널 목록 조회
const managedChannelIds = await getManagedChannelIds();
// Nitter에서 전체 트윗 수집
const tweets = await fetchAllTweetsFromNitter(nitterUrl, bot.username);
let addedCount = 0;
let ytAddedCount = 0;
for (const tweet of tweets) {
// 트윗 저장
const scheduleId = await createScheduleFromTweet(tweet);
if (scheduleId) addedCount++;
// 유튜브 링크 처리
const videoIds = extractYoutubeVideoIds(tweet.text);
for (const videoId of videoIds) {
const video = await fetchVideoInfo(videoId);
if (!video) continue;
// 관리 중인 채널이면 스킵
if (managedChannelIds.includes(video.channelId)) continue;
// 유튜브 일정 저장
const ytScheduleId = await createScheduleFromYoutube(video);
if (ytScheduleId) ytAddedCount++;
}
}
// 봇 상태 업데이트
// 추가된 항목이 있을 때만 last_added_count 업데이트 (0이면 이전 값 유지)
const totalAdded = addedCount + ytAddedCount;
if (totalAdded > 0) {
await pool.query(
`UPDATE bots SET
last_check_at = NOW(),
schedules_added = schedules_added + ?,
last_added_count = ?,
error_message = NULL
WHERE id = ?`,
[totalAdded, totalAdded, botId]
);
} else {
await pool.query(
`UPDATE bots SET
last_check_at = NOW(),
error_message = NULL
WHERE id = ?`,
[botId]
);
}
return { addedCount, ytAddedCount, total: tweets.length };
} catch (error) {
await pool.query(
`UPDATE bots SET
status = 'error',
error_message = ?
WHERE id = ?`,
[error.message, botId]
);
throw error;
}
}
export default {
syncNewTweets,
syncAllTweets,
extractTitle,
extractYoutubeVideoIds,
toKST,
};

View file

@ -152,6 +152,83 @@ function parseDuration(duration) {
return hours * 3600 + minutes * 60 + seconds;
}
/**
* YouTube API로 최근 N개 영상 수집 (정기 동기화용)
* @param {string} channelId - 채널 ID
* @param {number} maxResults - 조회할 영상 (기본 10)
*/
export async function fetchRecentVideosFromAPI(channelId, maxResults = 10) {
const videos = [];
try {
// 채널의 업로드 플레이리스트 ID 조회
const channelResponse = await fetch(
`https://www.googleapis.com/youtube/v3/channels?part=contentDetails&id=${channelId}&key=${YOUTUBE_API_KEY}`
);
const channelData = await channelResponse.json();
if (!channelData.items || channelData.items.length === 0) {
throw new Error("채널을 찾을 수 없습니다.");
}
const uploadsPlaylistId =
channelData.items[0].contentDetails.relatedPlaylists.uploads;
// 플레이리스트 아이템 조회 (최근 N개만)
const url = `https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=${uploadsPlaylistId}&maxResults=${maxResults}&key=${YOUTUBE_API_KEY}`;
const response = await fetch(url);
const data = await response.json();
if (data.error) {
throw new Error(data.error.message);
}
// 영상 ID 목록 추출
const videoIds = data.items.map((item) => item.snippet.resourceId.videoId);
// videos API로 duration 조회 (Shorts 판별용)
const videosResponse = await fetch(
`https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=${videoIds.join(
","
)}&key=${YOUTUBE_API_KEY}`
);
const videosData = await videosResponse.json();
// duration으로 Shorts 판별 맵 생성
const durationMap = {};
if (videosData.items) {
for (const v of videosData.items) {
const duration = v.contentDetails.duration;
const seconds = parseDuration(duration);
durationMap[v.id] = seconds <= 60 ? "shorts" : "video";
}
}
for (const item of data.items) {
const snippet = item.snippet;
const videoId = snippet.resourceId.videoId;
const publishedAt = toKST(new Date(snippet.publishedAt));
const videoType = durationMap[videoId] || "video";
videos.push({
videoId,
title: snippet.title,
description: snippet.description || "",
publishedAt,
date: formatDate(publishedAt),
time: formatTime(publishedAt),
videoUrl: getVideoUrl(videoId, videoType),
videoType,
});
}
return videos;
} catch (error) {
console.error("YouTube API 오류:", error);
throw error;
}
}
/**
* YouTube API로 전체 영상 수집 (초기 동기화용)
* Shorts 판별: duration이 60 이하이면 Shorts
@ -356,14 +433,14 @@ function extractMemberIdsFromDescription(description, memberNameMap) {
}
/**
* 봇의 영상 동기화 (RSS 기반)
* 봇의 영상 동기화 (YouTube API 기반)
*/
export async function syncNewVideos(botId) {
try {
// 봇 정보 조회 (bot_youtube_config 조인)
const [bots] = await pool.query(
`
SELECT b.*, c.channel_id, c.rss_url
SELECT b.*, c.channel_id
FROM bots b
LEFT JOIN bot_youtube_config c ON b.id = c.bot_id
WHERE b.id = ?
@ -377,8 +454,8 @@ export async function syncNewVideos(botId) {
const bot = bots[0];
if (!bot.rss_url) {
throw new Error("RSS URL이 설정되지 않았습니다.");
if (!bot.channel_id) {
throw new Error("Channel ID가 설정되지 않았습니다.");
}
// 봇별 커스텀 설정 조회
@ -386,8 +463,8 @@ export async function syncNewVideos(botId) {
const categoryId = await getYoutubeCategory();
// RSS 피드 파싱
const videos = await parseRSSFeed(bot.rss_url);
// YouTube API로 최근 10개 영상 조회
const videos = await fetchRecentVideosFromAPI(bot.channel_id, 10);
let addedCount = 0;
// 멤버 추출을 위한 이름 맵 조회 (필요 시)
@ -434,22 +511,33 @@ export async function syncNewVideos(botId) {
}
// 봇 상태 업데이트 (전체 추가 수 + 마지막 추가 수)
await pool.query(
`UPDATE bots SET
last_check_at = DATE_ADD(NOW(), INTERVAL 9 HOUR),
schedules_added = schedules_added + ?,
last_added_count = ?,
error_message = NULL
WHERE id = ?`,
[addedCount, addedCount, botId]
);
// addedCount > 0일 때만 last_added_count 업데이트 (0이면 이전 값 유지)
if (addedCount > 0) {
await pool.query(
`UPDATE bots SET
last_check_at = NOW(),
schedules_added = schedules_added + ?,
last_added_count = ?,
error_message = NULL
WHERE id = ?`,
[addedCount, addedCount, botId]
);
} else {
await pool.query(
`UPDATE bots SET
last_check_at = NOW(),
error_message = NULL
WHERE id = ?`,
[botId]
);
}
return { addedCount, total: videos.length };
} catch (error) {
// 오류 상태 업데이트
await pool.query(
`UPDATE bots SET
last_check_at = DATE_ADD(NOW(), INTERVAL 9 HOUR),
last_check_at = NOW(),
status = 'error',
error_message = ?
WHERE id = ?`,
@ -467,7 +555,7 @@ export async function syncAllVideos(botId) {
// 봇 정보 조회 (bot_youtube_config 조인)
const [bots] = await pool.query(
`
SELECT b.*, c.channel_id, c.rss_url
SELECT b.*, c.channel_id
FROM bots b
LEFT JOIN bot_youtube_config c ON b.id = c.bot_id
WHERE b.id = ?
@ -538,15 +626,26 @@ export async function syncAllVideos(botId) {
}
// 봇 상태 업데이트 (전체 추가 수 + 마지막 추가 수)
await pool.query(
`UPDATE bots SET
last_check_at = DATE_ADD(NOW(), INTERVAL 9 HOUR),
schedules_added = schedules_added + ?,
last_added_count = ?,
error_message = NULL
WHERE id = ?`,
[addedCount, addedCount, botId]
);
// addedCount > 0일 때만 last_added_count 업데이트 (0이면 이전 값 유지)
if (addedCount > 0) {
await pool.query(
`UPDATE bots SET
last_check_at = NOW(),
schedules_added = schedules_added + ?,
last_added_count = ?,
error_message = NULL
WHERE id = ?`,
[addedCount, addedCount, botId]
);
} else {
await pool.query(
`UPDATE bots SET
last_check_at = NOW(),
error_message = NULL
WHERE id = ?`,
[botId]
);
}
return { addedCount, total: videos.length };
} catch (error) {

View file

@ -1,49 +1,76 @@
import cron from "node-cron";
import pool from "../lib/db.js";
import { syncNewVideos } from "./youtube-bot.js";
import { syncNewTweets } from "./x-bot.js";
import { syncAllSchedules } from "./meilisearch-bot.js";
// 봇별 스케줄러 인스턴스 저장
const schedulers = new Map();
/**
* 타입에 따라 적절한 동기화 함수 호출
*/
async function syncBot(botId) {
const [bots] = await pool.query("SELECT type FROM bots WHERE id = ?", [
botId,
]);
if (bots.length === 0) throw new Error("봇을 찾을 수 없습니다.");
const botType = bots[0].type;
if (botType === "youtube") {
return await syncNewVideos(botId);
} else if (botType === "x") {
return await syncNewTweets(botId);
} else if (botType === "meilisearch") {
return await syncAllSchedules(botId);
} else {
throw new Error(`지원하지 않는 봇 타입: ${botType}`);
}
}
/**
* 봇이 메모리에서 실행 중인지 확인
*/
export function isBotRunning(botId) {
return schedulers.has(botId);
const id = parseInt(botId);
return schedulers.has(id);
}
/**
* 개별 스케줄 등록
*/
export function registerBot(botId, intervalMinutes = 2, cronExpression = null) {
const id = parseInt(botId);
// 기존 스케줄이 있으면 제거
unregisterBot(botId);
unregisterBot(id);
// cron 표현식: 지정된 표현식 사용, 없으면 기본값 생성
const expression = cronExpression || `1-59/${intervalMinutes} * * * *`;
const task = cron.schedule(expression, async () => {
console.log(`[Bot ${botId}] 동기화 시작...`);
console.log(`[Bot ${id}] 동기화 시작...`);
try {
const result = await syncNewVideos(botId);
console.log(`[Bot ${botId}] 동기화 완료: ${result.addedCount}개 추가`);
const result = await syncBot(id);
console.log(`[Bot ${id}] 동기화 완료: ${result.addedCount}개 추가`);
} catch (error) {
console.error(`[Bot ${botId}] 동기화 오류:`, error.message);
console.error(`[Bot ${id}] 동기화 오류:`, error.message);
}
});
schedulers.set(botId, task);
console.log(`[Bot ${botId}] 스케줄 등록됨 (cron: ${expression})`);
schedulers.set(id, task);
console.log(`[Bot ${id}] 스케줄 등록됨 (cron: ${expression})`);
}
/**
* 개별 스케줄 해제
*/
export function unregisterBot(botId) {
if (schedulers.has(botId)) {
schedulers.get(botId).stop();
schedulers.delete(botId);
console.log(`[Bot ${botId}] 스케줄 해제됨`);
const id = parseInt(botId);
if (schedulers.has(id)) {
schedulers.get(id).stop();
schedulers.delete(id);
console.log(`[Bot ${id}] 스케줄 해제됨`);
}
}
@ -55,15 +82,48 @@ async function syncBotStatuses() {
const [bots] = await pool.query("SELECT id, status FROM bots");
for (const bot of bots) {
const isRunningInMemory = schedulers.has(bot.id);
const botId = parseInt(bot.id);
const isRunningInMemory = schedulers.has(botId);
const isRunningInDB = bot.status === "running";
// 메모리에 없는데 DB가 running이면 → 서버 크래시 등으로 불일치, DB를 stopped로 업데이트
// 메모리에 없는데 DB가 running이면 → 서버 크래시 등으로 불일치
// 이 경우 DB를 stopped로 변경하는 대신, 메모리에 봇을 다시 등록
if (!isRunningInMemory && isRunningInDB) {
await pool.query("UPDATE bots SET status = 'stopped' WHERE id = ?", [
bot.id,
]);
console.log(`[Scheduler] Bot ${bot.id} 상태 동기화: stopped`);
console.log(`[Scheduler] Bot ${botId} 메모리에 없음, 재등록 시도...`);
try {
const [botInfo] = await pool.query(
"SELECT check_interval, cron_expression FROM bots WHERE id = ?",
[botId]
);
if (botInfo.length > 0) {
const { check_interval, cron_expression } = botInfo[0];
// 직접 registerBot 함수 호출 (import 순환 방지를 위해 내부 로직 사용)
const expression =
cron_expression || `1-59/${check_interval} * * * *`;
const task = cron.schedule(expression, async () => {
console.log(`[Bot ${botId}] 동기화 시작...`);
try {
const result = await syncBot(botId);
console.log(
`[Bot ${botId}] 동기화 완료: ${result.addedCount}개 추가`
);
} catch (error) {
console.error(`[Bot ${botId}] 동기화 오류:`, error.message);
}
});
schedulers.set(botId, task);
console.log(
`[Scheduler] Bot ${botId} 재등록 완료 (cron: ${expression})`
);
}
} catch (error) {
console.error(`[Scheduler] Bot ${botId} 재등록 오류:`, error.message);
// 재등록 실패 시에만 stopped로 변경
await pool.query("UPDATE bots SET status = 'stopped' WHERE id = ?", [
botId,
]);
console.log(`[Scheduler] Bot ${botId} 상태 동기화: stopped`);
}
}
}
} catch (error) {
@ -116,7 +176,7 @@ export async function startBot(botId) {
// 즉시 1회 실행
try {
await syncNewVideos(botId);
await syncBot(botId);
} catch (error) {
console.error(`[Bot ${botId}] 초기 동기화 오류:`, error.message);
}

View file

@ -1,2 +1,2 @@
VITE_KAKAO_JS_KEY=5a626e19fbafb33b1eea26f162038ccb
VITE_KAKAO_REST_KEY=cf21156ae6cc8f6e95b3a3150926cdf8
VITE_KAKAO_REST_KEY=e7a5516bf6cb1b398857789ee2ea6eea

View file

@ -2,7 +2,10 @@
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, viewport-fit=cover"
/>
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<title>fromis_9 - 프로미스나인</title>
<link

View file

@ -8,16 +8,23 @@
"name": "fromis9-frontend",
"version": "1.0.0",
"dependencies": {
"@tanstack/react-query": "^5.90.16",
"@tanstack/react-virtual": "^3.13.18",
"dayjs": "^1.11.19",
"framer-motion": "^11.0.8",
"lucide-react": "^0.344.0",
"react": "^18.2.0",
"react-calendar": "^6.0.0",
"react-colorful": "^5.6.1",
"react-device-detect": "^2.2.3",
"react-dom": "^18.2.0",
"react-infinite-scroll-component": "^6.1.1",
"react-intersection-observer": "^10.0.0",
"react-ios-time-picker": "^0.2.2",
"react-photo-album": "^3.4.0",
"react-router-dom": "^6.22.3",
"react-window": "^2.2.3",
"swiper": "^12.0.3",
"zustand": "^5.0.9"
},
"devDependencies": {
@ -1128,6 +1135,59 @@
"win32"
]
},
"node_modules/@tanstack/query-core": {
"version": "5.90.16",
"resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.90.16.tgz",
"integrity": "sha512-MvtWckSVufs/ja463/K4PyJeqT+HMlJWtw6PrCpywznd2NSgO3m4KwO9RqbFqGg6iDE8vVMFWMeQI4Io3eEYww==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
}
},
"node_modules/@tanstack/react-query": {
"version": "5.90.16",
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.90.16.tgz",
"integrity": "sha512-bpMGOmV4OPmif7TNMteU/Ehf/hoC0Kf98PDc0F4BZkFrEapRMEqI/V6YS0lyzwSV6PQpY1y4xxArUIfBW5LVxQ==",
"license": "MIT",
"dependencies": {
"@tanstack/query-core": "5.90.16"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"peerDependencies": {
"react": "^18 || ^19"
}
},
"node_modules/@tanstack/react-virtual": {
"version": "3.13.18",
"resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.13.18.tgz",
"integrity": "sha512-dZkhyfahpvlaV0rIKnvQiVoWPyURppl6w4m9IwMDpuIjcJ1sD9YGWrt0wISvgU7ewACXx2Ct46WPgI6qAD4v6A==",
"license": "MIT",
"dependencies": {
"@tanstack/virtual-core": "3.13.18"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/@tanstack/virtual-core": {
"version": "3.13.18",
"resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.13.18.tgz",
"integrity": "sha512-Mx86Hqu1k39icq2Zusq+Ey2J6dDWTjDvEv43PJtRCoEYTLyfaPnxIQ6iy7YAOK0NV/qOEmZQ/uCufrppZxTgcg==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
}
},
"node_modules/@types/babel__core": {
"version": "7.20.5",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
@ -1229,6 +1289,15 @@
"vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"
}
},
"node_modules/@wojtekmaj/date-utils": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/@wojtekmaj/date-utils/-/date-utils-2.0.2.tgz",
"integrity": "sha512-Do66mSlSNifFFuo3l9gNKfRMSFi26CRuQMsDJuuKO/ekrDWuTTtE4ZQxoFCUOG+NgxnpSeBq/k5TY8ZseEzLpA==",
"license": "MIT",
"funding": {
"url": "https://github.com/wojtekmaj/date-utils?sponsor=1"
}
},
"node_modules/any-promise": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz",
@ -1433,6 +1502,15 @@
"node": ">= 6"
}
},
"node_modules/clsx": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",
"integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/commander": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz",
@ -1470,6 +1548,12 @@
"devOptional": true,
"license": "MIT"
},
"node_modules/dayjs": {
"version": "1.11.19",
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.19.tgz",
"integrity": "sha512-t5EcLVS6QPBNqM2z8fakk/NKel+Xzshgt8FFKAn+qwlD1pzZWxh0nVCrvFK7ZDb6XucZeF9z8C7CBWTRIVApAw==",
"license": "MIT"
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
@ -1687,6 +1771,18 @@
"node": ">=6.9.0"
}
},
"node_modules/get-user-locale": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/get-user-locale/-/get-user-locale-3.0.0.tgz",
"integrity": "sha512-iJfHSmdYV39UUBw7Jq6GJzeJxUr4U+S03qdhVuDsR9gCEnfbqLy9gYDJFBJQL1riqolFUKQvx36mEkp2iGgJ3g==",
"license": "MIT",
"dependencies": {
"memoize": "^10.0.0"
},
"funding": {
"url": "https://github.com/wojtekmaj/get-user-locale?sponsor=1"
}
},
"node_modules/glob-parent": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz",
@ -1868,6 +1964,21 @@
"react": "^16.5.1 || ^17.0.0 || ^18.0.0"
}
},
"node_modules/memoize": {
"version": "10.2.0",
"resolved": "https://registry.npmjs.org/memoize/-/memoize-10.2.0.tgz",
"integrity": "sha512-DeC6b7QBrZsRs3Y02A6A7lQyzFbsQbqgjI6UW0GigGWV+u1s25TycMr0XHZE4cJce7rY/vyw2ctMQqfDkIhUEA==",
"license": "MIT",
"dependencies": {
"mimic-function": "^5.0.1"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sindresorhus/memoize?sponsor=1"
}
},
"node_modules/merge2": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",
@ -1892,6 +2003,18 @@
"node": ">=8.6"
}
},
"node_modules/mimic-function": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz",
"integrity": "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==",
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/motion-dom": {
"version": "11.18.1",
"resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-11.18.1.tgz",
@ -2235,6 +2358,31 @@
"node": ">=0.10.0"
}
},
"node_modules/react-calendar": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/react-calendar/-/react-calendar-6.0.0.tgz",
"integrity": "sha512-6wqaki3Us0DNDjZDr0DYIzhSFprNoy4FdPT9Pjy5aD2hJJVjtJwmdMT9VmrTUo949nlk35BOxehThxX62RkuRQ==",
"license": "MIT",
"dependencies": {
"@wojtekmaj/date-utils": "^2.0.2",
"clsx": "^2.0.0",
"get-user-locale": "^3.0.0",
"warning": "^4.0.0"
},
"funding": {
"url": "https://github.com/wojtekmaj/react-calendar?sponsor=1"
},
"peerDependencies": {
"@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/react-colorful": {
"version": "5.6.1",
"resolved": "https://registry.npmjs.org/react-colorful/-/react-colorful-5.6.1.tgz",
@ -2271,6 +2419,33 @@
"react": "^18.3.1"
}
},
"node_modules/react-infinite-scroll-component": {
"version": "6.1.1",
"resolved": "https://registry.npmjs.org/react-infinite-scroll-component/-/react-infinite-scroll-component-6.1.1.tgz",
"integrity": "sha512-R8YoOyiNDynSWmfVme5LHslsKrP+/xcRUWR2ies8UgUab9dtyw5ECnMCVPPmnmjjF4MWQmfVdRwRWcWaDgeyMA==",
"license": "MIT",
"dependencies": {
"throttle-debounce": "^2.1.0"
},
"peerDependencies": {
"react": ">=16.0.0"
}
},
"node_modules/react-intersection-observer": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/react-intersection-observer/-/react-intersection-observer-10.0.0.tgz",
"integrity": "sha512-JJRgcnFQoVXmbE5+GXr1OS1NDD1gHk0HyfpLcRf0575IbJz+io8yzs4mWVlfaqOQq1FiVjLvuYAdEEcrrCfveg==",
"license": "MIT",
"peerDependencies": {
"react": "^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0"
},
"peerDependenciesMeta": {
"react-dom": {
"optional": true
}
}
},
"node_modules/react-ios-time-picker": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/react-ios-time-picker/-/react-ios-time-picker-0.2.2.tgz",
@ -2562,6 +2737,25 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/swiper": {
"version": "12.0.3",
"resolved": "https://registry.npmjs.org/swiper/-/swiper-12.0.3.tgz",
"integrity": "sha512-BHd6U1VPEIksrXlyXjMmRWO0onmdNPaTAFduzqR3pgjvi7KfmUCAm/0cj49u2D7B0zNjMw02TSeXfinC1hDCXg==",
"funding": [
{
"type": "patreon",
"url": "https://www.patreon.com/swiperjs"
},
{
"type": "open_collective",
"url": "http://opencollective.com/swiper"
}
],
"license": "MIT",
"engines": {
"node": ">= 4.7.0"
}
},
"node_modules/tailwindcss": {
"version": "3.4.19",
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.19.tgz",
@ -2623,6 +2817,15 @@
"node": ">=0.8"
}
},
"node_modules/throttle-debounce": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/throttle-debounce/-/throttle-debounce-2.3.0.tgz",
"integrity": "sha512-H7oLPV0P7+jgvrk+6mwwwBDmxTaxnu9HMXmloNLXwnNO0ZxZ31Orah2n8lU1eMPvsaowP2CX+USCgyovXfdOFQ==",
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/tinyglobby": {
"version": "0.2.15",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
@ -2821,6 +3024,15 @@
}
}
},
"node_modules/warning": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/warning/-/warning-4.0.3.tgz",
"integrity": "sha512-rpJyN222KWIvHJ/F53XSZv0Zl/accqHR8et1kpaMTD/fLCRxtV8iX8czMzY7sVZupTI3zcUTg8eycS2kNF9l6w==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.0.0"
}
},
"node_modules/yallist": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",

View file

@ -9,16 +9,23 @@
"preview": "vite preview"
},
"dependencies": {
"@tanstack/react-query": "^5.90.16",
"@tanstack/react-virtual": "^3.13.18",
"dayjs": "^1.11.19",
"framer-motion": "^11.0.8",
"lucide-react": "^0.344.0",
"react": "^18.2.0",
"react-calendar": "^6.0.0",
"react-colorful": "^5.6.1",
"react-device-detect": "^2.2.3",
"react-dom": "^18.2.0",
"react-infinite-scroll-component": "^6.1.1",
"react-intersection-observer": "^10.0.0",
"react-ios-time-picker": "^0.2.2",
"react-photo-album": "^3.4.0",
"react-router-dom": "^6.22.3",
"react-window": "^2.2.3",
"swiper": "^12.0.3",
"zustand": "^5.0.9"
},
"devDependencies": {

View file

@ -1,13 +1,25 @@
import { useEffect } from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { BrowserView, MobileView } from 'react-device-detect';
//
import ScrollToTop from './components/ScrollToTop';
// PC
import PCHome from './pages/pc/Home';
import PCMembers from './pages/pc/Members';
import PCAlbum from './pages/pc/Album';
import PCAlbumDetail from './pages/pc/AlbumDetail';
import PCAlbumGallery from './pages/pc/AlbumGallery';
import PCSchedule from './pages/pc/Schedule';
import PCHome from './pages/pc/public/Home';
import PCMembers from './pages/pc/public/Members';
import PCAlbum from './pages/pc/public/Album';
import PCAlbumDetail from './pages/pc/public/AlbumDetail';
import PCAlbumGallery from './pages/pc/public/AlbumGallery';
import PCSchedule from './pages/pc/public/Schedule';
//
import MobileHome from './pages/mobile/public/Home';
import MobileMembers from './pages/mobile/public/Members';
import MobileAlbum from './pages/mobile/public/Album';
import MobileAlbumDetail from './pages/mobile/public/AlbumDetail';
import MobileAlbumGallery from './pages/mobile/public/AlbumGallery';
import MobileSchedule from './pages/mobile/public/Schedule';
//
import AdminLogin from './pages/pc/admin/AdminLogin';
@ -22,13 +34,25 @@ import AdminScheduleForm from './pages/pc/admin/AdminScheduleForm';
import AdminScheduleCategory from './pages/pc/admin/AdminScheduleCategory';
import AdminScheduleBots from './pages/pc/admin/AdminScheduleBots';
// PC
//
import PCLayout from './components/pc/Layout';
import MobileLayout from './components/mobile/Layout';
// PC body
function PCWrapper({ children }) {
useEffect(() => {
document.body.classList.add('is-pc');
return () => document.body.classList.remove('is-pc');
}, []);
return children;
}
function App() {
return (
<BrowserRouter future={{ v7_startTransition: true, v7_relativeSplatPath: true }}>
<ScrollToTop />
<BrowserView>
<PCWrapper>
<Routes>
{/* 관리자 페이지 (레이아웃 없음) */}
<Route path="/admin" element={<AdminLogin />} />
@ -59,18 +83,21 @@ function App() {
</PCLayout>
} />
</Routes>
</PCWrapper>
</BrowserView>
<MobileView>
{/* 모바일 버전은 추후 구현 */}
<div className="flex items-center justify-center h-screen bg-gray-100 p-4">
<div className="text-center">
<p className="text-xl font-bold text-primary mb-2">fromis_9</p>
<p className="text-gray-500">모바일 버전은 준비 중입니다.</p>
</div>
</div>
<Routes>
<Route path="/" element={<MobileLayout><MobileHome /></MobileLayout>} />
<Route path="/members" element={<MobileLayout pageTitle="멤버"><MobileMembers /></MobileLayout>} />
<Route path="/album" element={<MobileLayout pageTitle="앨범"><MobileAlbum /></MobileLayout>} />
<Route path="/album/:name" element={<MobileLayout pageTitle="앨범"><MobileAlbumDetail /></MobileLayout>} />
<Route path="/album/:name/gallery" element={<MobileLayout pageTitle="앨범"><MobileAlbumGallery /></MobileLayout>} />
<Route path="/schedule" element={<MobileLayout useCustomLayout><MobileSchedule /></MobileLayout>} />
</Routes>
</MobileView>
</BrowserRouter>
);
}
export default App;

View file

@ -0,0 +1,62 @@
/**
* 어드민 앨범 관리 API
*/
import { fetchAdminApi, fetchAdminFormData } from "../index";
// 앨범 목록 조회
export async function getAlbums() {
return fetchAdminApi("/api/admin/albums");
}
// 앨범 상세 조회
export async function getAlbum(id) {
return fetchAdminApi(`/api/admin/albums/${id}`);
}
// 앨범 생성
export async function createAlbum(formData) {
return fetchAdminFormData("/api/admin/albums", formData, "POST");
}
// 앨범 수정
export async function updateAlbum(id, formData) {
return fetchAdminFormData(`/api/admin/albums/${id}`, formData, "PUT");
}
// 앨범 삭제
export async function deleteAlbum(id) {
return fetchAdminApi(`/api/admin/albums/${id}`, { method: "DELETE" });
}
// 앨범 사진 목록 조회
export async function getAlbumPhotos(albumId) {
return fetchAdminApi(`/api/admin/albums/${albumId}/photos`);
}
// 앨범 사진 업로드
export async function uploadAlbumPhotos(albumId, formData) {
return fetchAdminFormData(
`/api/admin/albums/${albumId}/photos`,
formData,
"POST"
);
}
// 앨범 사진 삭제
export async function deleteAlbumPhoto(albumId, photoId) {
return fetchAdminApi(`/api/admin/albums/${albumId}/photos/${photoId}`, {
method: "DELETE",
});
}
// 앨범 티저 목록 조회
export async function getAlbumTeasers(albumId) {
return fetchAdminApi(`/api/admin/albums/${albumId}/teasers`);
}
// 앨범 티저 삭제
export async function deleteAlbumTeaser(albumId, teaserId) {
return fetchAdminApi(`/api/admin/albums/${albumId}/teasers/${teaserId}`, {
method: "DELETE",
});
}

View file

@ -0,0 +1,42 @@
/**
* 어드민 인증 API
*/
import { fetchAdminApi } from "../index";
// 토큰 검증
export async function verifyToken() {
return fetchAdminApi("/api/admin/verify");
}
// 로그인
export async function login(username, password) {
const response = await fetch("/api/admin/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || "로그인 실패");
}
return response.json();
}
// 로그아웃 (로컬 스토리지 정리)
export function logout() {
localStorage.removeItem("adminToken");
localStorage.removeItem("adminUser");
}
// 현재 사용자 정보 가져오기
export function getCurrentUser() {
const userData = localStorage.getItem("adminUser");
return userData ? JSON.parse(userData) : null;
}
// 토큰 존재 여부 확인
export function hasToken() {
return !!localStorage.getItem("adminToken");
}

View file

@ -0,0 +1,34 @@
/**
* 어드민 관리 API
*/
import { fetchAdminApi } from "../index";
// 봇 목록 조회
export async function getBots() {
return fetchAdminApi("/api/admin/bots");
}
// 봇 시작
export async function startBot(id) {
return fetchAdminApi(`/api/admin/bots/${id}/start`, { method: "POST" });
}
// 봇 정지
export async function stopBot(id) {
return fetchAdminApi(`/api/admin/bots/${id}/stop`, { method: "POST" });
}
// 봇 전체 동기화
export async function syncAllVideos(id) {
return fetchAdminApi(`/api/admin/bots/${id}/sync-all`, { method: "POST" });
}
// 할당량 경고 조회
export async function getQuotaWarning() {
return fetchAdminApi("/api/admin/quota-warning");
}
// 할당량 경고 해제
export async function dismissQuotaWarning() {
return fetchAdminApi("/api/admin/quota-warning", { method: "DELETE" });
}

View file

@ -0,0 +1,40 @@
/**
* 어드민 카테고리 관리 API
*/
import { fetchAdminApi } from "../index";
// 카테고리 목록 조회
export async function getCategories() {
return fetchAdminApi("/api/admin/schedule-categories");
}
// 카테고리 생성
export async function createCategory(data) {
return fetchAdminApi("/api/admin/schedule-categories", {
method: "POST",
body: JSON.stringify(data),
});
}
// 카테고리 수정
export async function updateCategory(id, data) {
return fetchAdminApi(`/api/admin/schedule-categories/${id}`, {
method: "PUT",
body: JSON.stringify(data),
});
}
// 카테고리 삭제
export async function deleteCategory(id) {
return fetchAdminApi(`/api/admin/schedule-categories/${id}`, {
method: "DELETE",
});
}
// 카테고리 순서 변경
export async function reorderCategories(orders) {
return fetchAdminApi("/api/admin/schedule-categories-order", {
method: "PUT",
body: JSON.stringify({ orders }),
});
}

View file

@ -0,0 +1,19 @@
/**
* 어드민 멤버 관리 API
*/
import { fetchAdminApi, fetchAdminFormData } from "../index";
// 멤버 목록 조회
export async function getMembers() {
return fetchAdminApi("/api/admin/members");
}
// 멤버 상세 조회
export async function getMember(id) {
return fetchAdminApi(`/api/admin/members/${id}`);
}
// 멤버 수정
export async function updateMember(id, formData) {
return fetchAdminFormData(`/api/admin/members/${id}`, formData, "PUT");
}

View file

@ -0,0 +1,36 @@
/**
* 어드민 일정 관리 API
*/
import { fetchAdminApi, fetchAdminFormData } from "../index";
// 일정 목록 조회 (월별)
export async function getSchedules(year, month) {
return fetchAdminApi(`/api/admin/schedules?year=${year}&month=${month}`);
}
// 일정 검색 (Meilisearch)
export async function searchSchedules(query) {
return fetchAdminApi(
`/api/admin/schedules/search?q=${encodeURIComponent(query)}`
);
}
// 일정 상세 조회
export async function getSchedule(id) {
return fetchAdminApi(`/api/admin/schedules/${id}`);
}
// 일정 생성
export async function createSchedule(formData) {
return fetchAdminFormData("/api/admin/schedules", formData, "POST");
}
// 일정 수정
export async function updateSchedule(id, formData) {
return fetchAdminFormData(`/api/admin/schedules/${id}`, formData, "PUT");
}
// 일정 삭제
export async function deleteSchedule(id) {
return fetchAdminApi(`/api/admin/schedules/${id}`, { method: "DELETE" });
}

60
frontend/src/api/index.js Normal file
View file

@ -0,0 +1,60 @@
/**
* 공통 API 유틸리티
* 모든 API 호출에서 사용되는 기본 fetch 래퍼
*/
// 기본 fetch 래퍼
export async function fetchApi(url, options = {}) {
const response = await fetch(url, {
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
});
if (!response.ok) {
const error = await response.json().catch(() => ({ error: "요청 실패" }));
throw new Error(error.error || `HTTP ${response.status}`);
}
return response.json();
}
// 어드민 토큰 가져오기
export function getAdminToken() {
return localStorage.getItem("adminToken");
}
// 어드민 API용 fetch 래퍼 (토큰 자동 추가)
export async function fetchAdminApi(url, options = {}) {
const token = getAdminToken();
return fetchApi(url, {
...options,
headers: {
...options.headers,
Authorization: `Bearer ${token}`,
},
});
}
// FormData 전송용 (이미지 업로드 등)
export async function fetchAdminFormData(url, formData, method = "POST") {
const token = getAdminToken();
const response = await fetch(url, {
method,
headers: {
Authorization: `Bearer ${token}`,
},
body: formData,
});
if (!response.ok) {
const error = await response.json().catch(() => ({ error: "요청 실패" }));
throw new Error(error.error || `HTTP ${response.status}`);
}
return response.json();
}

View file

@ -0,0 +1,29 @@
/**
* 앨범 관련 공개 API
*/
import { fetchApi } from "../index";
// 앨범 목록 조회
export async function getAlbums() {
return fetchApi("/api/albums");
}
// 앨범 상세 조회 (ID)
export async function getAlbum(id) {
return fetchApi(`/api/albums/${id}`);
}
// 앨범 상세 조회 (이름)
export async function getAlbumByName(name) {
return fetchApi(`/api/albums/by-name/${name}`);
}
// 앨범 사진 조회
export async function getAlbumPhotos(albumId) {
return fetchApi(`/api/albums/${albumId}/photos`);
}
// 앨범 트랙 조회
export async function getAlbumTracks(albumId) {
return fetchApi(`/api/albums/${albumId}/tracks`);
}

View file

@ -0,0 +1,14 @@
/**
* 멤버 관련 공개 API
*/
import { fetchApi } from "../index";
// 멤버 목록 조회
export async function getMembers() {
return fetchApi("/api/members");
}
// 멤버 상세 조회
export async function getMember(id) {
return fetchApi(`/api/members/${id}`);
}

View file

@ -0,0 +1,35 @@
/**
* 일정 관련 공개 API
*/
import { fetchApi } from "../index";
import { getTodayKST } from "../../utils/date";
// 일정 목록 조회 (월별)
export async function getSchedules(year, month) {
return fetchApi(`/api/schedules?year=${year}&month=${month}`);
}
// 다가오는 일정 조회 (오늘 이후)
export async function getUpcomingSchedules(limit = 3) {
const todayStr = getTodayKST();
return fetchApi(`/api/schedules?startDate=${todayStr}&limit=${limit}`);
}
// 일정 검색 (Meilisearch)
export async function searchSchedules(query, { offset = 0, limit = 20 } = {}) {
return fetchApi(
`/api/schedules?search=${encodeURIComponent(
query
)}&offset=${offset}&limit=${limit}`
);
}
// 일정 상세 조회
export async function getSchedule(id) {
return fetchApi(`/api/schedules/${id}`);
}
// 카테고리 목록 조회
export async function getCategories() {
return fetchApi("/api/schedule-categories");
}

View file

@ -0,0 +1,15 @@
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
//
function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return null;
}
export default ScrollToTop;

View file

@ -0,0 +1,46 @@
/**
* AdminHeader 컴포넌트
* 모든 Admin 페이지에서 공통으로 사용하는 헤더
* 로고, Admin 배지, 사용자 정보, 로그아웃 버튼 포함
*/
import { useNavigate, Link } from 'react-router-dom';
import { LogOut } from 'lucide-react';
function AdminHeader({ user }) {
const navigate = useNavigate();
const handleLogout = () => {
localStorage.removeItem('adminToken');
localStorage.removeItem('adminUser');
navigate('/admin');
};
return (
<header className="bg-white shadow-sm border-b border-gray-100">
<div className="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
<div className="flex items-center gap-4">
<Link to="/admin/dashboard" className="text-2xl font-bold text-primary hover:opacity-80 transition-opacity">
fromis_9
</Link>
<span className="px-3 py-1 bg-primary/10 text-primary text-sm font-medium rounded-full">
Admin
</span>
</div>
<div className="flex items-center gap-4">
<span className="text-gray-500 text-sm">
안녕하세요, <span className="text-gray-900 font-medium">{user?.username}</span>
</span>
<button
onClick={handleLogout}
className="flex items-center gap-2 px-4 py-2 text-gray-500 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors"
>
<LogOut size={18} />
<span>로그아웃</span>
</button>
</div>
</div>
</header>
);
}
export default AdminHeader;

View file

@ -0,0 +1,115 @@
/**
* ConfirmDialog 컴포넌트
* 삭제 위험한 작업의 확인을 위한 공통 다이얼로그
*
* Props:
* - isOpen: 다이얼로그 표시 여부
* - onClose: 닫기 콜백
* - onConfirm: 확인 콜백
* - title: 제목 (: "앨범 삭제")
* - message: 메시지 내용 (ReactNode 가능)
* - confirmText: 확인 버튼 텍스트 (기본: "삭제")
* - cancelText: 취소 버튼 텍스트 (기본: "취소")
* - loading: 로딩 상태
* - loadingText: 로딩 텍스트 (기본: "삭제 중...")
* - variant: 버튼 색상 (기본: "danger", "primary" 가능)
*/
import { motion, AnimatePresence } from 'framer-motion';
import { AlertTriangle, Trash2 } from 'lucide-react';
function ConfirmDialog({
isOpen,
onClose,
onConfirm,
title,
message,
confirmText = '삭제',
cancelText = '취소',
loading = false,
loadingText = '삭제 중...',
variant = 'danger',
icon: Icon = AlertTriangle
}) {
//
const buttonColors = {
danger: 'bg-red-500 hover:bg-red-600',
primary: 'bg-primary hover:bg-primary-dark'
};
const iconBgColors = {
danger: 'bg-red-100',
primary: 'bg-primary/10'
};
const iconColors = {
danger: 'text-red-500',
primary: 'text-primary'
};
return (
<AnimatePresence>
{isOpen && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
onClick={() => !loading && onClose()}
>
<motion.div
initial={{ scale: 0.9, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.9, opacity: 0 }}
className="bg-white rounded-2xl p-6 max-w-md w-full mx-4 shadow-xl"
onClick={(e) => e.stopPropagation()}
>
{/* 헤더 */}
<div className="flex items-center gap-3 mb-4">
<div className={`w-10 h-10 rounded-full ${iconBgColors[variant]} flex items-center justify-center`}>
<Icon className={iconColors[variant]} size={20} />
</div>
<h3 className="text-lg font-bold text-gray-900">{title}</h3>
</div>
{/* 메시지 */}
<div className="text-gray-600 mb-6">
{message}
</div>
{/* 버튼 */}
<div className="flex justify-end gap-3">
<button
type="button"
onClick={onClose}
disabled={loading}
className="px-4 py-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors disabled:opacity-50"
>
{cancelText}
</button>
<button
type="button"
onClick={onConfirm}
disabled={loading}
className={`px-4 py-2 ${buttonColors[variant]} text-white rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50`}
>
{loading ? (
<>
<span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
{loadingText}
</>
) : (
<>
<Trash2 size={16} />
{confirmText}
</>
)}
</button>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
);
}
export default ConfirmDialog;

View file

@ -0,0 +1,261 @@
/**
* 커스텀 데이트픽커 컴포넌트
* // 선택이 가능한 드롭다운 형태의 날짜 선택기
*/
import { useState, useEffect, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Calendar, ChevronLeft, ChevronRight, ChevronDown } from 'lucide-react';
function CustomDatePicker({ value, onChange, placeholder = '날짜 선택', showDayOfWeek = false }) {
const [isOpen, setIsOpen] = useState(false);
const [viewMode, setViewMode] = useState('days');
const [viewDate, setViewDate] = useState(() => {
if (value) return new Date(value);
return new Date();
});
const ref = useRef(null);
useEffect(() => {
const handleClickOutside = (e) => {
if (ref.current && !ref.current.contains(e.target)) {
setIsOpen(false);
setViewMode('days');
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
const year = viewDate.getFullYear();
const month = viewDate.getMonth();
const firstDay = new Date(year, month, 1).getDay();
const daysInMonth = new Date(year, month + 1, 0).getDate();
const days = [];
for (let i = 0; i < firstDay; i++) {
days.push(null);
}
for (let i = 1; i <= daysInMonth; i++) {
days.push(i);
}
const startYear = Math.floor(year / 10) * 10 - 1;
const years = Array.from({ length: 12 }, (_, i) => startYear + i);
const prevMonth = () => setViewDate(new Date(year, month - 1, 1));
const nextMonth = () => setViewDate(new Date(year, month + 1, 1));
const prevYearRange = () => setViewDate(new Date(year - 10, month, 1));
const nextYearRange = () => setViewDate(new Date(year + 10, month, 1));
const selectDate = (day) => {
const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
onChange(dateStr);
setIsOpen(false);
setViewMode('days');
};
const selectYear = (y) => {
setViewDate(new Date(y, month, 1));
setViewMode('months');
};
const selectMonth = (m) => {
setViewDate(new Date(year, m, 1));
setViewMode('days');
};
// ( )
const formatDisplayDate = (dateStr) => {
if (!dateStr) return '';
const [y, m, d] = dateStr.split('-');
if (showDayOfWeek) {
const dayNames = ['일', '월', '화', '수', '목', '금', '토'];
const date = new Date(parseInt(y), parseInt(m) - 1, parseInt(d));
const dayOfWeek = dayNames[date.getDay()];
return `${y}${parseInt(m)}${parseInt(d)}일 (${dayOfWeek})`;
}
return `${y}${parseInt(m)}${parseInt(d)}`;
};
const isSelected = (day) => {
if (!value || !day) return false;
const [y, m, d] = value.split('-');
return parseInt(y) === year && parseInt(m) === month + 1 && parseInt(d) === day;
};
const isToday = (day) => {
if (!day) return false;
const today = new Date();
return today.getFullYear() === year && today.getMonth() === month && today.getDate() === day;
};
const isCurrentYear = (y) => new Date().getFullYear() === y;
const isCurrentMonth = (m) => {
const today = new Date();
return today.getFullYear() === year && today.getMonth() === m;
};
const monthNames = ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'];
return (
<div ref={ref} className="relative">
<button
type="button"
onClick={() => setIsOpen(!isOpen)}
className="w-full px-4 py-3 border border-gray-200 rounded-xl bg-white flex items-center justify-between hover:border-gray-300 transition-colors focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
>
<span className={value ? 'text-gray-900' : 'text-gray-400'}>
{value ? formatDisplayDate(value) : placeholder}
</span>
<Calendar size={18} className="text-gray-400" />
</button>
<AnimatePresence>
{isOpen && (
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -10 }}
transition={{ duration: 0.15 }}
className="absolute z-50 mt-2 bg-white border border-gray-200 rounded-xl shadow-lg p-4 w-80"
>
<div className="flex items-center justify-between mb-4">
<button
type="button"
onClick={viewMode === 'years' ? prevYearRange : prevMonth}
className="p-1.5 hover:bg-gray-100 rounded-lg transition-colors"
>
<ChevronLeft size={20} className="text-gray-600" />
</button>
<button
type="button"
onClick={() => setViewMode(viewMode === 'days' ? 'years' : 'days')}
className="font-medium text-gray-900 hover:text-primary transition-colors flex items-center gap-1"
>
{viewMode === 'years' ? `${years[0]} - ${years[years.length - 1]}` : `${year}${month + 1}`}
<ChevronDown size={16} className={`transition-transform ${viewMode !== 'days' ? 'rotate-180' : ''}`} />
</button>
<button
type="button"
onClick={viewMode === 'years' ? nextYearRange : nextMonth}
className="p-1.5 hover:bg-gray-100 rounded-lg transition-colors"
>
<ChevronRight size={20} className="text-gray-600" />
</button>
</div>
<AnimatePresence mode="wait">
{viewMode === 'years' && (
<motion.div
key="years"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.15 }}
>
<div className="text-center text-sm text-gray-500 mb-3">년도</div>
<div className="grid grid-cols-4 gap-2 mb-4">
{years.map((y) => (
<button
key={y}
type="button"
onClick={() => selectYear(y)}
className={`py-2 rounded-lg text-sm transition-colors ${year === y ? 'bg-primary text-white' : 'hover:bg-gray-100 text-gray-700'} ${isCurrentYear(y) && year !== y ? 'text-primary font-medium' : ''}`}
>
{y}
</button>
))}
</div>
<div className="text-center text-sm text-gray-500 mb-3"></div>
<div className="grid grid-cols-4 gap-2">
{monthNames.map((m, i) => (
<button
key={m}
type="button"
onClick={() => selectMonth(i)}
className={`py-2 rounded-lg text-sm transition-colors ${month === i ? 'bg-primary text-white' : 'hover:bg-gray-100 text-gray-700'} ${isCurrentMonth(i) && month !== i ? 'text-primary font-medium' : ''}`}
>
{m}
</button>
))}
</div>
</motion.div>
)}
{viewMode === 'months' && (
<motion.div
key="months"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.15 }}
>
<div className="text-center text-sm text-gray-500 mb-3"> 선택</div>
<div className="grid grid-cols-4 gap-2">
{monthNames.map((m, i) => (
<button
key={m}
type="button"
onClick={() => selectMonth(i)}
className={`py-2.5 rounded-lg text-sm transition-colors ${month === i ? 'bg-primary text-white' : 'hover:bg-gray-100 text-gray-700'} ${isCurrentMonth(i) && month !== i ? 'text-primary font-medium' : ''}`}
>
{m}
</button>
))}
</div>
</motion.div>
)}
{viewMode === 'days' && (
<motion.div
key="days"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.15 }}
>
<div className="grid grid-cols-7 gap-1 mb-2">
{['일', '월', '화', '수', '목', '금', '토'].map((d, i) => (
<div
key={d}
className={`text-center text-xs font-medium py-1 ${i === 0 ? 'text-red-400' : i === 6 ? 'text-blue-400' : 'text-gray-400'}`}
>
{d}
</div>
))}
</div>
<div className="grid grid-cols-7 gap-1">
{days.map((day, i) => {
const dayOfWeek = i % 7;
return (
<button
key={i}
type="button"
disabled={!day}
onClick={() => day && selectDate(day)}
className={`aspect-square rounded-full text-sm font-medium flex items-center justify-center transition-all
${!day ? '' : 'hover:bg-gray-100'}
${isSelected(day) ? 'bg-primary text-white hover:bg-primary' : ''}
${isToday(day) && !isSelected(day) ? 'text-primary font-bold' : ''}
${day && !isSelected(day) && !isToday(day) && dayOfWeek === 0 ? 'text-red-500' : ''}
${day && !isSelected(day) && !isToday(day) && dayOfWeek === 6 ? 'text-blue-500' : ''}
${day && !isSelected(day) && !isToday(day) && dayOfWeek > 0 && dayOfWeek < 6 ? 'text-gray-700' : ''}
`}
>
{day}
</button>
);
})}
</div>
</motion.div>
)}
</AnimatePresence>
</motion.div>
)}
</AnimatePresence>
</div>
);
}
export default CustomDatePicker;

View file

@ -0,0 +1,178 @@
/**
* CustomTimePicker 컴포넌트
* 오전/오후, 시간, 분을 선택할 있는 시간 피커
* NumberPicker를 사용하여 스크롤 방식 선택 제공
*/
import { useState, useEffect, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Clock } from 'lucide-react';
import NumberPicker from './NumberPicker';
function CustomTimePicker({ value, onChange, placeholder = "시간 선택" }) {
const [isOpen, setIsOpen] = useState(false);
const ref = useRef(null);
//
const parseValue = () => {
if (!value) return { hour: "12", minute: "00", period: "오후" };
const [h, m] = value.split(":");
const hour = parseInt(h);
const isPM = hour >= 12;
const hour12 = hour === 0 ? 12 : hour > 12 ? hour - 12 : hour;
return {
hour: String(hour12).padStart(2, "0"),
minute: m,
period: isPM ? "오후" : "오전",
};
};
const parsed = parseValue();
const [selectedHour, setSelectedHour] = useState(parsed.hour);
const [selectedMinute, setSelectedMinute] = useState(parsed.minute);
const [selectedPeriod, setSelectedPeriod] = useState(parsed.period);
//
useEffect(() => {
const handleClickOutside = (e) => {
if (ref.current && !ref.current.contains(e.target)) {
setIsOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
//
useEffect(() => {
if (isOpen) {
const parsed = parseValue();
setSelectedHour(parsed.hour);
setSelectedMinute(parsed.minute);
setSelectedPeriod(parsed.period);
}
}, [isOpen, value]);
//
const handleSave = () => {
let hour = parseInt(selectedHour);
if (selectedPeriod === "오후" && hour !== 12) hour += 12;
if (selectedPeriod === "오전" && hour === 12) hour = 0;
const timeStr = `${String(hour).padStart(2, "0")}:${selectedMinute}`;
onChange(timeStr);
setIsOpen(false);
};
//
const handleCancel = () => {
setIsOpen(false);
};
//
const handleClear = () => {
onChange("");
setIsOpen(false);
};
//
const displayValue = () => {
if (!value) return placeholder;
const [h, m] = value.split(":");
const hour = parseInt(h);
const isPM = hour >= 12;
const hour12 = hour === 0 ? 12 : hour > 12 ? hour - 12 : hour;
return `${isPM ? "오후" : "오전"} ${hour12}:${m}`;
};
//
const periods = ["오전", "오후"];
const hours = [
"01", "02", "03", "04", "05", "06",
"07", "08", "09", "10", "11", "12",
];
const minutes = Array.from({ length: 60 }, (_, i) =>
String(i).padStart(2, "0")
);
return (
<div ref={ref} className="relative">
<button
type="button"
onClick={() => setIsOpen(!isOpen)}
className="w-full px-4 py-3 border border-gray-200 rounded-xl bg-white flex items-center justify-between hover:border-gray-300 transition-colors focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
>
<span className={value ? "text-gray-900" : "text-gray-400"}>
{displayValue()}
</span>
<Clock size={18} className="text-gray-400" />
</button>
<AnimatePresence>
{isOpen && (
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -10 }}
className="absolute top-full left-0 mt-2 bg-white rounded-2xl shadow-xl border border-gray-200 z-50 overflow-hidden"
>
{/* 피커 영역 */}
<div className="flex items-center justify-center px-4 py-4">
{/* 오전/오후 (맨 앞) */}
<NumberPicker
items={periods}
value={selectedPeriod}
onChange={setSelectedPeriod}
/>
{/* 시간 */}
<NumberPicker
items={hours}
value={selectedHour}
onChange={setSelectedHour}
/>
<span className="text-xl text-gray-300 font-medium mx-0.5">
:
</span>
{/* 분 */}
<NumberPicker
items={minutes}
value={selectedMinute}
onChange={setSelectedMinute}
/>
</div>
{/* 푸터 버튼 */}
<div className="flex items-center justify-between px-4 py-3 bg-gray-50">
<button
type="button"
onClick={handleClear}
className="px-3 py-1.5 text-sm text-gray-400 hover:text-gray-600 transition-colors"
>
초기화
</button>
<div className="flex items-center gap-2">
<button
type="button"
onClick={handleCancel}
className="px-4 py-1.5 text-sm text-gray-600 hover:bg-gray-200 rounded-lg transition-colors"
>
취소
</button>
<button
type="button"
onClick={handleSave}
className="px-4 py-1.5 text-sm bg-primary text-white font-medium rounded-lg hover:bg-primary-dark transition-colors"
>
저장
</button>
</div>
</div>
</motion.div>
)}
</AnimatePresence>
</div>
);
}
export default CustomTimePicker;

View file

@ -0,0 +1,192 @@
/**
* NumberPicker 컴포넌트
* 스크롤 가능한 숫자/ 선택 피커
* AdminScheduleForm의 시간 선택에서 사용
*/
import { useState, useEffect, useRef } from 'react';
function NumberPicker({ items, value, onChange }) {
const ITEM_HEIGHT = 40;
const containerRef = useRef(null);
const [offset, setOffset] = useState(0);
const offsetRef = useRef(0); // ref
const touchStartY = useRef(0);
const startOffset = useRef(0);
const isScrolling = useRef(false);
// offset ref
useEffect(() => {
offsetRef.current = offset;
}, [offset]);
//
useEffect(() => {
if (value !== null && value !== undefined) {
const index = items.indexOf(value);
if (index !== -1) {
const newOffset = -index * ITEM_HEIGHT;
setOffset(newOffset);
offsetRef.current = newOffset;
}
}
}, []);
//
useEffect(() => {
const index = items.indexOf(value);
if (index !== -1) {
const targetOffset = -index * ITEM_HEIGHT;
if (Math.abs(offset - targetOffset) > 1) {
setOffset(targetOffset);
offsetRef.current = targetOffset;
}
}
}, [value, items]);
const centerOffset = ITEM_HEIGHT; //
//
const isItemInCenter = (item) => {
const itemIndex = items.indexOf(item);
const itemPosition = -itemIndex * ITEM_HEIGHT;
const tolerance = ITEM_HEIGHT / 2;
return Math.abs(offset - itemPosition) < tolerance;
};
// ( )
const updateOffset = (newOffset) => {
const maxOffset = 0;
const minOffset = -(items.length - 1) * ITEM_HEIGHT;
return Math.min(maxOffset, Math.max(minOffset, newOffset));
};
//
const updateCenterItem = (currentOffset) => {
const centerIndex = Math.round(-currentOffset / ITEM_HEIGHT);
if (centerIndex >= 0 && centerIndex < items.length) {
const centerItem = items[centerIndex];
if (value !== centerItem) {
onChange(centerItem);
}
}
};
//
const snapToClosestItem = (currentOffset) => {
const targetOffset = Math.round(currentOffset / ITEM_HEIGHT) * ITEM_HEIGHT;
setOffset(targetOffset);
offsetRef.current = targetOffset;
updateCenterItem(targetOffset);
};
//
const handleTouchStart = (e) => {
e.stopPropagation();
touchStartY.current = e.touches[0].clientY;
startOffset.current = offsetRef.current;
};
//
const handleTouchMove = (e) => {
e.stopPropagation();
const touchY = e.touches[0].clientY;
const deltaY = touchY - touchStartY.current;
const newOffset = updateOffset(startOffset.current + deltaY);
setOffset(newOffset);
offsetRef.current = newOffset;
};
//
const handleTouchEnd = (e) => {
e.stopPropagation();
snapToClosestItem(offsetRef.current);
};
// -
const handleWheel = (e) => {
e.preventDefault();
e.stopPropagation();
if (isScrolling.current) return;
isScrolling.current = true;
const newOffset = updateOffset(
offsetRef.current - Math.sign(e.deltaY) * ITEM_HEIGHT
);
setOffset(newOffset);
offsetRef.current = newOffset;
snapToClosestItem(newOffset);
setTimeout(() => {
isScrolling.current = false;
}, 50);
};
//
const handleMouseDown = (e) => {
e.preventDefault();
e.stopPropagation();
touchStartY.current = e.clientY;
startOffset.current = offsetRef.current;
const handleMouseMove = (moveEvent) => {
moveEvent.preventDefault();
const deltaY = moveEvent.clientY - touchStartY.current;
const newOffset = updateOffset(startOffset.current + deltaY);
setOffset(newOffset);
offsetRef.current = newOffset;
};
const handleMouseUp = () => {
snapToClosestItem(offsetRef.current);
document.removeEventListener("mousemove", handleMouseMove);
document.removeEventListener("mouseup", handleMouseUp);
};
document.addEventListener("mousemove", handleMouseMove);
document.addEventListener("mouseup", handleMouseUp);
};
// wheel passive false
useEffect(() => {
const container = containerRef.current;
if (container) {
container.addEventListener("wheel", handleWheel, { passive: false });
return () => container.removeEventListener("wheel", handleWheel);
}
}, []);
return (
<div
ref={containerRef}
className="relative w-16 h-[120px] overflow-hidden touch-none select-none cursor-grab active:cursor-grabbing"
onTouchStart={handleTouchStart}
onTouchMove={handleTouchMove}
onTouchEnd={handleTouchEnd}
onMouseDown={handleMouseDown}
>
{/* 중앙 선택 영역 */}
<div className="absolute top-1/2 left-1 right-1 h-10 -translate-y-1/2 bg-primary/10 rounded-lg z-0" />
{/* 피커 내부 */}
<div
className="relative transition-transform duration-150 ease-out"
style={{ transform: `translateY(${offset + centerOffset}px)` }}
>
{items.map((item) => (
<div
key={item}
className={`h-10 leading-10 text-center select-none transition-all duration-150 ${
isItemInCenter(item)
? "text-primary text-lg font-bold"
: "text-gray-300 text-base"
}`}
>
{item}
</div>
))}
</div>
</div>
);
}
export default NumberPicker;

View file

@ -0,0 +1,42 @@
import { memo } from 'react';
/**
* 라이트박스 인디케이터 컴포넌트
* 이미지 갤러리에서 현재 위치를 표시하는 슬라이딩 인디케이터
* CSS transition 사용으로 GPU 가속
*/
const LightboxIndicator = memo(function LightboxIndicator({ count, currentIndex, goToIndex }) {
const translateX = -(currentIndex * 18) + 100 - 6;
return (
<div className="absolute bottom-6 left-1/2 -translate-x-1/2 overflow-hidden" style={{ width: '200px' }}>
{/* 양옆 페이드 그라데이션 */}
<div className="absolute inset-0 pointer-events-none z-10" style={{
background: 'linear-gradient(to right, rgba(0,0,0,1) 0%, transparent 20%, transparent 80%, rgba(0,0,0,1) 100%)'
}} />
{/* 슬라이딩 컨테이너 - CSS transition으로 GPU 가속 */}
<div
className="flex items-center gap-2 justify-center"
style={{
width: `${count * 18}px`,
transform: `translateX(${translateX}px)`,
transition: 'transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94)'
}}
>
{Array.from({ length: count }).map((_, i) => (
<button
key={i}
className={`rounded-full flex-shrink-0 transition-all duration-300 ${
i === currentIndex
? 'w-3 h-3 bg-white'
: 'w-2.5 h-2.5 bg-white/40 hover:bg-white/60'
}`}
onClick={() => goToIndex(i)}
/>
))}
</div>
</div>
);
});
export default LightboxIndicator;

View file

@ -0,0 +1,93 @@
import { NavLink, useLocation } from 'react-router-dom';
import { Home, Users, Disc3, Calendar } from 'lucide-react';
import { useEffect } from 'react';
import '../../mobile.css';
//
function MobileHeader({ title }) {
return (
<header className="bg-white shadow-sm sticky top-0 z-50">
<div className="flex items-center justify-center h-14 px-4">
{title ? (
<span className="text-xl font-bold text-primary">{title}</span>
) : (
<NavLink to="/" className="text-xl font-bold text-primary">
fromis_9
</NavLink>
)}
</div>
</header>
);
}
//
function MobileBottomNav() {
const location = useLocation();
const navItems = [
{ path: '/', label: '홈', icon: Home },
{ path: '/members', label: '멤버', icon: Users },
{ path: '/album', label: '앨범', icon: Disc3 },
{ path: '/schedule', label: '일정', icon: Calendar },
];
return (
<nav className="flex-shrink-0 bg-white border-t border-gray-200 z-50 safe-area-bottom">
<div className="flex items-center justify-around h-16">
{navItems.map((item) => {
const Icon = item.icon;
const isActive = location.pathname === item.path ||
(item.path !== '/' && location.pathname.startsWith(item.path));
return (
<NavLink
key={item.path}
to={item.path}
className={`flex flex-col items-center justify-center gap-1 w-full h-full transition-colors ${
isActive ? 'text-primary' : 'text-gray-400'
}`}
>
<Icon size={22} strokeWidth={isActive ? 2.5 : 2} />
<span className="text-xs font-medium">{item.label}</span>
</NavLink>
);
})}
</div>
</nav>
);
}
//
// pageTitle: ( fromis_9)
// hideHeader: true ( )
// useCustomLayout: true (mobile-layout-container )
function MobileLayout({ children, pageTitle, hideHeader = false, useCustomLayout = false }) {
// (body )
useEffect(() => {
document.documentElement.classList.add('mobile-layout');
return () => {
document.documentElement.classList.remove('mobile-layout');
};
}, []);
// (Schedule )
if (useCustomLayout) {
return (
<div className="mobile-layout-container bg-gray-50">
{children}
<MobileBottomNav />
</div>
);
}
return (
<div className="mobile-layout-container bg-gray-50">
{!hideHeader && <MobileHeader title={pageTitle} />}
<main className="mobile-content">{children}</main>
<MobileBottomNav />
</div>
);
}
export default MobileLayout;

View file

@ -1,5 +1,6 @@
import Header from './Header';
import Footer from './Footer';
import '../../pc.css';
function Layout({ children }) {
return (

View file

@ -0,0 +1,56 @@
/**
* Toast 상태 관리 커스텀
* 자동 숨김 타이머 상태 관리를 제공
*/
import { useState, useEffect, useCallback } from "react";
function useToast(duration = 3000) {
const [toast, setToast] = useState(null);
// Toast 자동 숨김
useEffect(() => {
if (toast) {
const timer = setTimeout(() => setToast(null), duration);
return () => clearTimeout(timer);
}
}, [toast, duration]);
// Toast 표시 함수
const showToast = useCallback((message, type = "info") => {
setToast({ message, type });
}, []);
// 편의 메서드
const showSuccess = useCallback(
(message) => showToast(message, "success"),
[showToast]
);
const showError = useCallback(
(message) => showToast(message, "error"),
[showToast]
);
const showWarning = useCallback(
(message) => showToast(message, "warning"),
[showToast]
);
const showInfo = useCallback(
(message) => showToast(message, "info"),
[showToast]
);
// Toast 숨김 함수
const hideToast = useCallback(() => setToast(null), []);
return {
toast,
setToast,
showToast,
showSuccess,
showError,
showWarning,
showInfo,
hideToast,
};
}
export default useToast;

View file

@ -3,20 +3,11 @@
@tailwind utilities;
/* 기본 스타일 */
html {
overflow-y: scroll; /* 항상 스크롤바 공간 확보 - 화면 밀림 방지 */
}
body {
background-color: #fafafa;
color: #1a1a1a;
}
/* 최소 너비 설정 - 화면 축소시 깨짐 방지 */
#root {
min-width: 1440px;
}
/* 스크롤바 스타일 */
::-webkit-scrollbar {
width: 8px;
@ -87,3 +78,8 @@ body {
-ms-overflow-style: none;
scrollbar-width: none;
}
/* Swiper autoHeight 지원 */
.swiper-slide {
height: auto !important;
}

View file

@ -1,10 +1,23 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import App from './App';
import './index.css';
// React Query
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 60 * 5, // 5
refetchOnWindowFocus: false,
},
},
});
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</React.StrictMode>
);

156
frontend/src/mobile.css Normal file
View file

@ -0,0 +1,156 @@
/* 모바일 전용 스타일 */
/* 모바일 html,body 스크롤 방지 */
html.mobile-layout,
html.mobile-layout body {
margin: 0;
padding: 0;
height: 100%;
overflow: hidden;
}
/* 모바일 레이아웃 컨테이너 */
.mobile-layout-container {
display: flex;
flex-direction: column;
height: 100dvh;
overflow: hidden;
}
/* 모바일 툴바 (기본 56px) */
.mobile-toolbar {
flex-shrink: 0;
background-color: #ffffff;
}
/* 일정 페이지 툴바 (헤더 + 날짜 선택기) */
.mobile-toolbar-schedule {
flex-shrink: 0;
background-color: #ffffff;
}
/* 하단 네비게이션 */
.mobile-bottom-nav {
flex-shrink: 0;
}
/* 컨텐츠 영역 - 스크롤 가능, 스크롤바 숨김 */
.mobile-content {
flex: 1;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
overscroll-behavior: contain;
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* IE/Edge */
}
.mobile-content::-webkit-scrollbar {
display: none; /* Chrome, Safari, Opera */
}
/* 모바일 safe-area 지원 (노치, 홈 인디케이터) */
.safe-area-bottom {
padding-bottom: env(safe-area-inset-bottom, 0);
}
.safe-area-top {
padding-top: env(safe-area-inset-top, 0);
}
/* 모바일 달력 스타일 */
.mobile-calendar-wrapper .react-calendar__navigation button:hover {
background-color: #f3f4f6;
border-radius: 0.5rem;
}
.mobile-calendar-wrapper .react-calendar__navigation__label {
font-weight: 600;
font-size: 0.875rem;
color: #374151;
}
.mobile-calendar-wrapper .react-calendar__month-view__weekdays {
text-align: center;
font-size: 0.75rem;
font-weight: 500;
color: #6b7280;
}
.mobile-calendar-wrapper .react-calendar__month-view__weekdays__weekday {
padding: 0.5rem 0;
}
.mobile-calendar-wrapper .react-calendar__month-view__weekdays__weekday abbr {
text-decoration: none;
}
/* 일요일 (빨간색) */
.mobile-calendar-wrapper
.react-calendar__month-view__weekdays__weekday:first-child {
color: #f87171;
}
/* 토요일 (파란색) */
.mobile-calendar-wrapper
.react-calendar__month-view__weekdays__weekday:last-child {
color: #60a5fa;
}
.mobile-calendar-wrapper .react-calendar__tile {
display: flex;
flex-direction: column;
align-items: center;
padding: 0.25rem;
background: none;
border: none;
font-size: 0.75rem;
color: #374151;
}
.mobile-calendar-wrapper .react-calendar__tile:hover {
background-color: #f3f4f6;
border-radius: 9999px;
}
.mobile-calendar-wrapper .react-calendar__tile abbr {
display: flex;
align-items: center;
justify-content: center;
width: 1.75rem;
height: 1.75rem;
border-radius: 9999px;
}
/* 이웃 달 날짜 (흐리게) */
.mobile-calendar-wrapper
.react-calendar__month-view__days__day--neighboringMonth {
color: #d1d5db;
}
/* 일요일 */
.mobile-calendar-wrapper .react-calendar__tile.sunday abbr {
color: #ef4444;
}
/* 토요일 */
.mobile-calendar-wrapper .react-calendar__tile.saturday abbr {
color: #3b82f6;
}
/* 오늘 */
.mobile-calendar-wrapper .react-calendar__tile--now abbr {
background-color: #548360;
color: white;
font-weight: 700;
}
/* 선택된 날짜 */
.mobile-calendar-wrapper .react-calendar__tile--active abbr {
background-color: #548360;
color: white;
}
.mobile-calendar-wrapper .react-calendar__tile--active:enabled:hover abbr,
.mobile-calendar-wrapper .react-calendar__tile--active:enabled:focus abbr {
background-color: #456e50;
}

View file

@ -0,0 +1,63 @@
import { motion } from 'framer-motion';
import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { getAlbums } from '../../../api/public/albums';
//
function MobileAlbum() {
const navigate = useNavigate();
const [albums, setAlbums] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
getAlbums()
.then(data => {
setAlbums(data);
setLoading(false);
})
.catch(console.error);
}, []);
if (loading) {
return (
<div className="flex items-center justify-center h-64">
<div className="w-8 h-8 border-2 border-primary border-t-transparent rounded-full animate-spin" />
</div>
);
}
return (
<div className="px-4 py-4">
<div className="grid grid-cols-2 gap-4">
{albums.map((album, index) => (
<motion.div
key={album.id}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.05 }}
onClick={() => navigate(`/album/${album.folder_name}`)}
className="bg-white rounded-2xl overflow-hidden shadow-sm"
>
<div className="aspect-square bg-gray-200">
{album.cover_thumb_url && (
<img
src={album.cover_thumb_url}
alt={album.title}
className="w-full h-full object-cover"
/>
)}
</div>
<div className="p-3">
<p className="font-semibold text-sm truncate">{album.title}</p>
<p className="text-xs text-gray-400 mt-0.5">
{album.album_type} · {album.release_date?.slice(0, 4)}
</p>
</div>
</motion.div>
))}
</div>
</div>
);
}
export default MobileAlbum;

View file

@ -0,0 +1,141 @@
import { motion } from 'framer-motion';
import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { ArrowLeft, Play } from 'lucide-react';
import { getAlbums, getAlbumTracks } from '../../../api/public/albums';
//
function MobileAlbumDetail() {
const { name } = useParams();
const navigate = useNavigate();
const [album, setAlbum] = useState(null);
const [tracks, setTracks] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
//
getAlbums()
.then(data => {
const found = data.find(a => a.folder_name === name);
if (found) {
setAlbum(found);
//
getAlbumTracks(found.id)
.then(setTracks)
.catch(console.error);
}
setLoading(false);
})
.catch(console.error);
}, [name]);
if (loading) {
return (
<div className="flex items-center justify-center h-64">
<div className="w-8 h-8 border-2 border-primary border-t-transparent rounded-full animate-spin" />
</div>
);
}
if (!album) {
return (
<div className="text-center py-12">
<p className="text-gray-500">앨범을 찾을 없습니다</p>
</div>
);
}
return (
<div className="pb-6">
{/* 헤더 */}
<div className="sticky top-14 z-40 bg-white/80 backdrop-blur-sm px-4 py-3 flex items-center gap-3 border-b">
<button onClick={() => navigate(-1)} className="p-1">
<ArrowLeft size={24} />
</button>
<span className="font-semibold truncate">{album.title}</span>
</div>
{/* 앨범 정보 */}
<div className="px-4 py-6">
<div className="flex gap-4">
<div className="w-32 h-32 rounded-2xl overflow-hidden bg-gray-200 shadow-lg flex-shrink-0">
{album.cover_medium_url && (
<img
src={album.cover_medium_url}
alt={album.title}
className="w-full h-full object-cover"
/>
)}
</div>
<div className="flex-1">
<h1 className="text-xl font-bold">{album.title}</h1>
<p className="text-gray-500 text-sm mt-1">{album.album_type}</p>
<p className="text-gray-400 text-sm">{album.release_date}</p>
<button
onClick={() => navigate(`/album/${name}/gallery`)}
className="mt-4 px-4 py-2 bg-primary text-white rounded-full text-sm font-medium"
>
갤러리 보기
</button>
</div>
</div>
</div>
{/* 트랙 리스트 */}
{tracks.length > 0 && (
<div className="px-4">
<h2 className="text-lg font-bold mb-3">수록곡</h2>
<div className="bg-white rounded-2xl overflow-hidden shadow-sm">
{tracks.map((track, index) => (
<motion.div
key={track.id}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: index * 0.05 }}
className="flex items-center gap-3 p-4 border-b border-gray-100 last:border-none"
>
<span className="w-6 text-center text-gray-400 text-sm">
{track.track_number}
</span>
<div className="flex-1 min-w-0">
<p className={`font-medium text-sm truncate ${track.is_title_track ? 'text-primary' : ''}`}>
{track.title}
{track.is_title_track && (
<span className="ml-2 text-xs bg-primary/10 text-primary px-2 py-0.5 rounded-full">
타이틀
</span>
)}
</p>
<p className="text-xs text-gray-400 truncate">{track.duration}</p>
</div>
{track.music_video_url && (
<a
href={track.music_video_url}
target="_blank"
rel="noopener noreferrer"
className="p-2 text-red-500"
>
<Play size={18} fill="currentColor" />
</a>
)}
</motion.div>
))}
</div>
</div>
)}
{/* 설명 */}
{album.description && (
<div className="px-4 mt-6">
<h2 className="text-lg font-bold mb-3">소개</h2>
<p className="text-gray-600 text-sm leading-relaxed bg-white p-4 rounded-2xl">
{album.description}
</p>
</div>
)}
</div>
);
}
export default MobileAlbumDetail;

View file

@ -0,0 +1,131 @@
import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { ArrowLeft, X, ChevronLeft, ChevronRight } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { getAlbums, getAlbumPhotos } from '../../../api/public/albums';
//
function MobileAlbumGallery() {
const { name } = useParams();
const navigate = useNavigate();
const [album, setAlbum] = useState(null);
const [photos, setPhotos] = useState([]);
const [loading, setLoading] = useState(true);
const [selectedIndex, setSelectedIndex] = useState(null);
useEffect(() => {
getAlbums()
.then(data => {
const found = data.find(a => a.folder_name === name);
if (found) {
setAlbum(found);
getAlbumPhotos(found.id)
.then(setPhotos)
.catch(console.error);
}
setLoading(false);
})
.catch(console.error);
}, [name]);
//
const goToImage = (delta) => {
const newIndex = selectedIndex + delta;
if (newIndex >= 0 && newIndex < photos.length) {
setSelectedIndex(newIndex);
}
};
if (loading) {
return (
<div className="flex items-center justify-center h-64">
<div className="w-8 h-8 border-2 border-primary border-t-transparent rounded-full animate-spin" />
</div>
);
}
return (
<div className="pb-4">
{/* 헤더 */}
<div className="sticky top-14 z-40 bg-white/80 backdrop-blur-sm px-4 py-3 flex items-center gap-3 border-b">
<button onClick={() => navigate(-1)} className="p-1">
<ArrowLeft size={24} />
</button>
<span className="font-semibold truncate">{album?.title} 갤러리</span>
</div>
{/* 갤러리 그리드 */}
<div className="grid grid-cols-3 gap-0.5 p-0.5">
{photos.map((photo, index) => (
<motion.div
key={photo.id}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: index * 0.02 }}
onClick={() => setSelectedIndex(index)}
className="aspect-square bg-gray-200 cursor-pointer"
>
<img
src={photo.thumb_url}
alt=""
className="w-full h-full object-cover"
loading="lazy"
/>
</motion.div>
))}
</div>
{/* 풀스크린 뷰어 */}
<AnimatePresence>
{selectedIndex !== null && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 bg-black z-50 flex flex-col"
>
{/* 뷰어 헤더 */}
<div className="flex items-center justify-between p-4 text-white">
<button onClick={() => setSelectedIndex(null)}>
<X size={24} />
</button>
<span className="text-sm">
{selectedIndex + 1} / {photos.length}
</span>
<div className="w-6" />
</div>
{/* 이미지 */}
<div className="flex-1 flex items-center justify-center relative">
<img
src={photos[selectedIndex]?.medium_url || photos[selectedIndex]?.original_url}
alt=""
className="max-w-full max-h-full object-contain"
/>
{/* 좌우 네비게이션 */}
{selectedIndex > 0 && (
<button
onClick={() => goToImage(-1)}
className="absolute left-2 p-2 text-white/80"
>
<ChevronLeft size={32} />
</button>
)}
{selectedIndex < photos.length - 1 && (
<button
onClick={() => goToImage(1)}
className="absolute right-2 p-2 text-white/80"
>
<ChevronRight size={32} />
</button>
)}
</div>
</motion.div>
)}
</AnimatePresence>
</div>
);
}
export default MobileAlbumGallery;

View file

@ -0,0 +1,265 @@
import { motion } from 'framer-motion';
import { ChevronRight, Clock, Tag } from 'lucide-react';
import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { getTodayKST } from '../../../utils/date';
import { getMembers } from '../../../api/public/members';
import { getAlbums } from '../../../api/public/albums';
import { getUpcomingSchedules } from '../../../api/public/schedules';
//
function MobileHome() {
const navigate = useNavigate();
const [members, setMembers] = useState([]);
const [albums, setAlbums] = useState([]);
const [schedules, setSchedules] = useState([]);
//
useEffect(() => {
//
getMembers()
.then(data => setMembers(data.filter(m => !m.is_former)))
.catch(console.error);
// ( 2)
getAlbums()
.then(data => setAlbums(data.slice(0, 2)))
.catch(console.error);
//
getUpcomingSchedules(3)
.then(data => setSchedules(data))
.catch(console.error);
}, []);
return (
<div>
{/* 히어로 섹션 */}
<motion.section
className="relative bg-gradient-to-br from-primary to-primary-dark py-12 px-4 overflow-hidden"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
>
<div className="absolute inset-0 bg-black/10" />
<motion.div
className="relative text-center text-white"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2, duration: 0.5 }}
>
<h1 className="text-3xl font-bold mb-1">fromis_9</h1>
<p className="text-lg font-light mb-3">프로미스나인</p>
<p className="text-sm opacity-80 leading-relaxed">
인사드리겠습니다. , !<br />
이제는 약속해 소중히 간직해,<br />
당신의 아이돌로 성장하겠습니다!
</p>
</motion.div>
{/* 장식 */}
<div className="absolute right-0 top-0 w-32 h-32 rounded-full bg-white/10 -translate-y-1/2 translate-x-1/2" />
<div className="absolute left-0 bottom-0 w-24 h-24 rounded-full bg-white/5 translate-y-1/2 -translate-x-1/2" />
</motion.section>
{/* 멤버 섹션 */}
<motion.section
className="px-4 py-6"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.3, duration: 0.5 }}
>
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-bold">멤버</h2>
<button
onClick={() => navigate('/members')}
className="text-primary text-sm flex items-center gap-1"
>
전체보기 <ChevronRight size={16} />
</button>
</div>
<div className="grid grid-cols-5 gap-2">
{members.map((member, index) => (
<motion.div
key={member.id}
className="text-center"
initial={{ opacity: 0, scale: 0.8 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ delay: 0.4 + index * 0.05, duration: 0.3 }}
whileTap={{ scale: 0.95 }}
>
<div className="aspect-square rounded-full overflow-hidden bg-gray-200 mb-1">
{member.image_url && (
<img
src={member.image_url}
alt={member.name}
className="w-full h-full object-cover"
/>
)}
</div>
<p className="text-xs font-medium truncate">{member.name}</p>
</motion.div>
))}
</div>
</motion.section>
{/* 앨범 섹션 */}
<motion.section
className="px-4 py-6 bg-gray-50"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.5, duration: 0.5 }}
>
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-bold">앨범</h2>
<button
onClick={() => navigate('/album')}
className="text-primary text-sm flex items-center gap-1"
>
전체보기 <ChevronRight size={16} />
</button>
</div>
<div className="grid grid-cols-2 gap-3">
{albums.map((album, index) => (
<motion.div
key={album.id}
onClick={() => navigate(`/album/${album.folder_name}`)}
className="bg-white rounded-xl overflow-hidden shadow-sm"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.6 + index * 0.1, duration: 0.3 }}
whileTap={{ scale: 0.98 }}
>
<div className="aspect-square bg-gray-200">
{album.cover_thumb_url && (
<img
src={album.cover_thumb_url}
alt={album.title}
className="w-full h-full object-cover"
/>
)}
</div>
<div className="p-3">
<p className="font-medium text-sm truncate">{album.title}</p>
<p className="text-xs text-gray-400">{album.release_date?.slice(0, 4)}</p>
</div>
</motion.div>
))}
</div>
</motion.section>
{/* 일정 섹션 */}
<motion.section
className="px-4 py-4"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.7, duration: 0.5 }}
>
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-bold">다가오는 일정</h2>
<button
onClick={() => navigate('/schedule')}
className="text-primary text-sm flex items-center gap-1"
>
전체보기 <ChevronRight size={16} />
</button>
</div>
{schedules.length > 0 ? (
<div className="space-y-3">
{schedules.map((schedule, index) => {
const scheduleDate = new Date(schedule.date);
const today = new Date();
const currentYear = today.getFullYear();
const currentMonth = today.getMonth();
const scheduleYear = scheduleDate.getFullYear();
const scheduleMonth = scheduleDate.getMonth();
const isCurrentYear = scheduleYear === currentYear;
const isCurrentMonth = isCurrentYear && scheduleMonth === currentMonth;
// (5 )
const memberList = schedule.member_names ? schedule.member_names.split(',').map(n => n.trim()).filter(Boolean) : [];
return (
<motion.div
key={schedule.id}
className="flex gap-4 bg-white p-4 rounded-xl shadow-sm border border-gray-100 overflow-hidden"
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: 0.8 + index * 0.1, duration: 0.3 }}
whileTap={{ scale: 0.98 }}
onClick={() => navigate('/schedule')}
>
{/* 날짜 영역 */}
<div className="flex flex-col items-center justify-center min-w-[50px]">
{/* 현재 년도가 아니면 년.월 표시 */}
{!isCurrentYear && (
<span className="text-[10px] text-gray-400 font-medium">
{scheduleYear}.{scheduleMonth + 1}
</span>
)}
{/* 현재 달이 아니면 월 표시 (현재 년도일 때) */}
{isCurrentYear && !isCurrentMonth && (
<span className="text-[10px] text-gray-400 font-medium">
{scheduleMonth + 1}
</span>
)}
<span className="text-2xl font-bold text-primary">
{scheduleDate.getDate()}
</span>
<span className="text-xs text-gray-400 font-medium">
{['일', '월', '화', '수', '목', '금', '토'][scheduleDate.getDay()]}
</span>
</div>
{/* 세로 구분선 */}
<div className="w-px bg-gray-100" />
{/* 내용 영역 */}
<div className="flex-1 min-w-0">
<p className="font-semibold text-sm text-gray-800 line-clamp-2 leading-snug">
{schedule.title}
</p>
{/* 시간 + 카테고리 (PC버전 스타일) */}
<div className="flex items-center gap-3 mt-2 text-xs text-gray-400">
{schedule.time && (
<span className="flex items-center gap-1">
<Clock size={12} />
{schedule.time.slice(0, 5)}
</span>
)}
{schedule.category_name && (
<span className="flex items-center gap-1">
<Tag size={12} />
{schedule.category_name}
</span>
)}
</div>
{/* 멤버 */}
{memberList.length > 0 && (
<div className="flex flex-wrap gap-1 mt-2">
{(memberList.length >= 5 ? ['프로미스나인'] : memberList).map((name, i) => (
<span
key={i}
className="px-2 py-0.5 bg-primary/10 text-primary text-[10px] rounded-full font-medium"
>
{name.trim()}
</span>
))}
</div>
)}
</div>
</motion.div>
);
})}
</div>
) : (
<div className="text-center py-8 text-gray-400">
<p>다가오는 일정이 없습니다</p>
</div>
)}
</motion.section>
</div>
);
}
export default MobileHome;

View file

@ -0,0 +1,127 @@
import { motion, AnimatePresence } from 'framer-motion';
import { useState, useEffect } from 'react';
import { Instagram } from 'lucide-react';
import { getMembers } from '../../../api/public/members';
//
function MobileMembers() {
const [members, setMembers] = useState([]);
const [formerMembers, setFormerMembers] = useState([]);
const [selectedMember, setSelectedMember] = useState(null);
useEffect(() => {
getMembers()
.then(data => {
setMembers(data.filter(m => !m.is_former));
setFormerMembers(data.filter(m => m.is_former));
})
.catch(console.error);
}, []);
//
const renderMemberCard = (member, index, isFormer = false) => (
<motion.div
key={member.id}
onClick={() => setSelectedMember(member)}
className="text-center cursor-pointer"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.05, duration: 0.3 }}
whileTap={{ scale: 0.95 }}
>
<div className={`aspect-square rounded-2xl overflow-hidden bg-gray-200 mb-2 shadow-sm ${isFormer ? 'grayscale' : ''}`}>
{member.image_url && (
<img
src={member.image_url}
alt={member.name}
className="w-full h-full object-cover"
/>
)}
</div>
<p className={`font-medium text-sm ${isFormer ? 'text-gray-400' : ''}`}>{member.name}</p>
<p className="text-xs text-gray-400">{member.position || ''}</p>
</motion.div>
);
return (
<div className="px-4 py-4">
{/* 현재 멤버 */}
<div className="grid grid-cols-3 gap-3">
{members.map((member, index) => renderMemberCard(member, index))}
</div>
{/* 전 멤버 */}
{formerMembers.length > 0 && (
<>
<div className="mt-8 mb-4">
<h2 className="text-lg font-bold text-gray-400"> 멤버</h2>
</div>
<div className="grid grid-cols-3 gap-3">
{formerMembers.map((member, index) => renderMemberCard(member, index, true))}
</div>
</>
)}
{/* 멤버 상세 모달 */}
<AnimatePresence>
{selectedMember && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 bg-black/50 z-50 flex items-end"
onClick={() => setSelectedMember(null)}
>
<motion.div
initial={{ y: '100%' }}
animate={{ y: 0 }}
exit={{ y: '100%' }}
transition={{ type: 'spring', damping: 25, stiffness: 300 }}
className="bg-white w-full rounded-t-3xl p-6 pb-24"
onClick={e => e.stopPropagation()}
>
<div className="flex gap-4">
<div className={`w-24 h-24 rounded-2xl overflow-hidden bg-gray-200 flex-shrink-0 ${selectedMember.is_former ? 'grayscale' : ''}`}>
{selectedMember.image_url && (
<img
src={selectedMember.image_url}
alt={selectedMember.name}
className="w-full h-full object-cover"
/>
)}
</div>
<div>
<h2 className="text-xl font-bold">{selectedMember.name}</h2>
<p className="text-gray-500 text-sm">{selectedMember.position}</p>
<p className="text-gray-400 text-sm mt-1">
{selectedMember.birth_date?.slice(0, 10).replaceAll('-', '.')}
</p>
{/* 전 멤버가 아닌 경우에만 인스타그램 표시 */}
{!selectedMember.is_former && selectedMember.instagram && (
<a
href={selectedMember.instagram}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 mt-2 text-pink-500"
>
<Instagram size={16} />
<span className="text-sm">Instagram</span>
</a>
)}
</div>
</div>
<button
onClick={() => setSelectedMember(null)}
className="w-full mt-6 py-3 bg-gray-100 rounded-xl font-medium"
>
닫기
</button>
</motion.div>
</motion.div>
)}
</AnimatePresence>
</div>
);
}
export default MobileMembers;

File diff suppressed because it is too large Load diff

View file

@ -2,10 +2,13 @@ import { useState, useEffect, useRef } from 'react';
import { useNavigate, useParams, Link } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import {
Save, Home, ChevronRight, LogOut, Music, Trash2, Plus, Image, Star,
ChevronDown, ChevronLeft, Calendar
Save, Home, ChevronRight, Music, Trash2, Plus, Image, Star,
ChevronDown
} from 'lucide-react';
import Toast from '../../../components/Toast';
import CustomDatePicker from '../../../components/admin/CustomDatePicker';
import AdminHeader from '../../../components/admin/AdminHeader';
import useToast from '../../../hooks/useToast';
//
function CustomSelect({ value, onChange, options, placeholder }) {
@ -71,280 +74,6 @@ function CustomSelect({ value, onChange, options, placeholder }) {
);
}
//
function CustomDatePicker({ value, onChange }) {
const [isOpen, setIsOpen] = useState(false);
const [viewMode, setViewMode] = useState('days'); // 'days' | 'months' | 'years'
const [viewDate, setViewDate] = useState(() => {
if (value) return new Date(value);
return new Date();
});
const ref = useRef(null);
useEffect(() => {
const handleClickOutside = (e) => {
if (ref.current && !ref.current.contains(e.target)) {
setIsOpen(false);
setViewMode('days');
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
const year = viewDate.getFullYear();
const month = viewDate.getMonth();
const firstDay = new Date(year, month, 1).getDay();
const daysInMonth = new Date(year, month + 1, 0).getDate();
const days = [];
for (let i = 0; i < firstDay; i++) {
days.push(null);
}
for (let i = 1; i <= daysInMonth; i++) {
days.push(i);
}
// ( -10 ~ +10)
const startYear = Math.floor(year / 10) * 10 - 1;
const years = Array.from({ length: 12 }, (_, i) => startYear + i);
const prevMonth = () => setViewDate(new Date(year, month - 1, 1));
const nextMonth = () => setViewDate(new Date(year, month + 1, 1));
const prevYearRange = () => setViewDate(new Date(year - 10, month, 1));
const nextYearRange = () => setViewDate(new Date(year + 10, month, 1));
const selectDate = (day) => {
const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
onChange(dateStr);
setIsOpen(false);
setViewMode('days');
};
const selectYear = (y) => {
setViewDate(new Date(y, month, 1));
setViewMode('months');
};
const selectMonth = (m) => {
setViewDate(new Date(year, m, 1));
setViewMode('days');
};
const formatDisplayDate = (dateStr) => {
if (!dateStr) return '';
const [y, m, d] = dateStr.split('-');
return `${y}${parseInt(m)}${parseInt(d)}`;
};
const isSelected = (day) => {
if (!value || !day) return false;
const [y, m, d] = value.split('-');
return parseInt(y) === year && parseInt(m) === month + 1 && parseInt(d) === day;
};
const isToday = (day) => {
if (!day) return false;
const today = new Date();
return today.getFullYear() === year && today.getMonth() === month && today.getDate() === day;
};
const isCurrentYear = (y) => {
return new Date().getFullYear() === y;
};
const isCurrentMonth = (m) => {
const today = new Date();
return today.getFullYear() === year && today.getMonth() === m;
};
const months = ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'];
return (
<div ref={ref} className="relative">
<button
type="button"
onClick={() => setIsOpen(!isOpen)}
className="w-full px-4 py-2.5 border border-gray-200 rounded-lg bg-white flex items-center justify-between hover:border-gray-300 transition-colors focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
>
<span className={value ? 'text-gray-900' : 'text-gray-400'}>
{value ? formatDisplayDate(value) : '날짜 선택'}
</span>
<Calendar size={18} className="text-gray-400" />
</button>
<AnimatePresence>
{isOpen && (
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -10 }}
transition={{ duration: 0.15 }}
className="absolute z-50 mt-2 bg-white border border-gray-200 rounded-xl shadow-lg p-4 w-80"
>
{/* 헤더 */}
<div className="flex items-center justify-between mb-4">
<button
type="button"
onClick={viewMode === 'years' ? prevYearRange : prevMonth}
className="p-1.5 hover:bg-gray-100 rounded-lg transition-colors"
>
<ChevronLeft size={20} className="text-gray-600" />
</button>
<button
type="button"
onClick={() => setViewMode(viewMode === 'days' ? 'years' : 'days')}
className="font-medium text-gray-900 hover:text-primary transition-colors flex items-center gap-1"
>
{viewMode === 'years' ? `${years[0]} - ${years[years.length - 1]}` : `${year}${month + 1}`}
<ChevronDown size={16} className={`transition-transform ${viewMode !== 'days' ? 'rotate-180' : ''}`} />
</button>
<button
type="button"
onClick={viewMode === 'years' ? nextYearRange : nextMonth}
className="p-1.5 hover:bg-gray-100 rounded-lg transition-colors"
>
<ChevronRight size={20} className="text-gray-600" />
</button>
</div>
<AnimatePresence mode="wait">
{viewMode === 'years' && (
<motion.div
key="years"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.15 }}
>
{/* 년도 라벨 */}
<div className="text-center text-sm text-gray-500 mb-3">년도</div>
{/* 년도 그리드 */}
<div className="grid grid-cols-4 gap-2 mb-4">
{years.map((y) => (
<button
key={y}
type="button"
onClick={() => selectYear(y)}
className={`
py-2 rounded-lg text-sm transition-colors
${year === y ? 'bg-primary text-white' : 'hover:bg-gray-100 text-gray-700'}
${isCurrentYear(y) && year !== y ? 'border border-primary text-primary' : ''}
`}
>
{y}
</button>
))}
</div>
{/* 월 라벨 */}
<div className="text-center text-sm text-gray-500 mb-3"></div>
{/* 월 그리드 */}
<div className="grid grid-cols-4 gap-2">
{months.map((m, i) => (
<button
key={m}
type="button"
onClick={() => selectMonth(i)}
className={`
py-2 rounded-lg text-sm transition-colors
${month === i ? 'bg-primary text-white' : 'hover:bg-gray-100 text-gray-700'}
${isCurrentMonth(i) && month !== i ? 'border border-primary text-primary' : ''}
`}
>
{m}
</button>
))}
</div>
</motion.div>
)}
{viewMode === 'months' && (
<motion.div
key="months"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.15 }}
>
{/* 월 라벨 */}
<div className="text-center text-sm text-gray-500 mb-3"> 선택</div>
{/* 월 그리드 */}
<div className="grid grid-cols-4 gap-2">
{months.map((m, i) => (
<button
key={m}
type="button"
onClick={() => selectMonth(i)}
className={`
py-2.5 rounded-lg text-sm transition-colors
${month === i ? 'bg-primary text-white' : 'hover:bg-gray-100 text-gray-700'}
${isCurrentMonth(i) && month !== i ? 'border border-primary text-primary' : ''}
`}
>
{m}
</button>
))}
</div>
</motion.div>
)}
{viewMode === 'days' && (
<motion.div
key="days"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.15 }}
>
{/* 요일 */}
<div className="grid grid-cols-7 gap-1 mb-2">
{['일', '월', '화', '수', '목', '금', '토'].map((d, i) => (
<div
key={d}
className={`text-center text-xs font-medium py-1 ${
i === 0 ? 'text-red-400' : i === 6 ? 'text-blue-400' : 'text-gray-400'
}`}
>
{d}
</div>
))}
</div>
{/* 날짜 */}
<div className="grid grid-cols-7 gap-1">
{days.map((day, i) => (
<button
key={i}
type="button"
disabled={!day}
onClick={() => day && selectDate(day)}
className={`
aspect-square rounded-lg text-sm flex items-center justify-center transition-colors
${!day ? '' : 'hover:bg-gray-100'}
${isSelected(day) ? 'bg-primary text-white hover:bg-primary-dark' : ''}
${isToday(day) && !isSelected(day) ? 'border border-primary text-primary' : ''}
${day && !isSelected(day) && !isToday(day) ? 'text-gray-700' : ''}
`}
>
{day}
</button>
))}
</div>
</motion.div>
)}
</AnimatePresence>
</motion.div>
)}
</AnimatePresence>
</div>
);
}
function AdminAlbumForm() {
const navigate = useNavigate();
const { id } = useParams();
@ -356,15 +85,7 @@ function AdminAlbumForm() {
const [saving, setSaving] = useState(false);
const [coverPreview, setCoverPreview] = useState(null);
const [coverFile, setCoverFile] = useState(null);
const [toast, setToast] = useState(null);
// Toast
useEffect(() => {
if (toast) {
const timer = setTimeout(() => setToast(null), 3000);
return () => clearTimeout(timer);
}
}, [toast]);
const { toast, setToast } = useToast();
const [formData, setFormData] = useState({
title: '',
@ -420,12 +141,6 @@ function AdminAlbumForm() {
}
}, [id, isEditMode, navigate]);
const handleLogout = () => {
localStorage.removeItem('adminToken');
localStorage.removeItem('adminUser');
navigate('/admin');
};
const handleInputChange = (e) => {
const { name, value } = e.target;
@ -544,49 +259,13 @@ function AdminAlbumForm() {
const albumTypes = ['정규', '미니', '싱글'];
const pageVariants = {
initial: { opacity: 0, y: 20 },
animate: { opacity: 1, y: 0 },
exit: { opacity: 0, y: -20 }
};
return (
<motion.div
className="min-h-screen bg-gray-50"
initial="initial"
animate="animate"
exit="exit"
variants={pageVariants}
transition={{ duration: 0.3 }}
>
<div className="min-h-screen bg-gray-50">
{/* Toast */}
<Toast toast={toast} onClose={() => setToast(null)} />
{/* 헤더 */}
<header className="bg-white shadow-sm border-b border-gray-100">
<div className="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
<div className="flex items-center gap-4">
<Link to="/admin/dashboard" className="text-2xl font-bold text-primary hover:opacity-80 transition-opacity">
fromis_9
</Link>
<span className="px-3 py-1 bg-primary/10 text-primary text-sm font-medium rounded-full">
Admin
</span>
</div>
<div className="flex items-center gap-4">
<span className="text-gray-500 text-sm">
안녕하세요, <span className="text-gray-900 font-medium">{user?.username}</span>
</span>
<button
onClick={handleLogout}
className="flex items-center gap-2 px-4 py-2 text-gray-500 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors"
>
<LogOut size={18} />
<span>로그아웃</span>
</button>
</div>
</div>
</header>
<AdminHeader user={user} />
{/* 메인 콘텐츠 */}
<main className="max-w-4xl mx-auto px-6 py-8">
@ -981,7 +660,7 @@ function AdminAlbumForm() {
</form>
)}
</main>
</motion.div>
</div>
);
}

View file

@ -3,11 +3,18 @@ import { useNavigate, Link, useParams } from 'react-router-dom';
import { motion, AnimatePresence, Reorder } from 'framer-motion';
import {
Upload, Trash2, Image, X, Check, Plus,
Home, ChevronRight, LogOut, ArrowLeft, Grid, List,
ZoomIn, AlertTriangle, GripVertical, Users, User, Users2,
Home, ChevronRight, ArrowLeft, Grid, List,
ZoomIn, GripVertical, Users, User, Users2,
Tag, FolderOpen, Save
} from 'lucide-react';
import Toast from '../../../components/Toast';
import AdminHeader from '../../../components/admin/AdminHeader';
import ConfirmDialog from '../../../components/admin/ConfirmDialog';
import useToast from '../../../hooks/useToast';
import * as authApi from '../../../api/admin/auth';
import { getAlbum } from '../../../api/public/albums';
import { getMembers } from '../../../api/public/members';
import * as albumsApi from '../../../api/admin/albums';
function AdminAlbumPhotos() {
const { albumId } = useParams();
@ -20,7 +27,7 @@ function AdminAlbumPhotos() {
const [teasers, setTeasers] = useState([]); //
const [loading, setLoading] = useState(true);
const [user, setUser] = useState(null);
const [toast, setToast] = useState(null);
const { toast, setToast } = useToast();
const [selectedPhotos, setSelectedPhotos] = useState([]);
const [uploading, setUploading] = useState(false);
const [uploadProgress, setUploadProgress] = useState(0);
@ -135,77 +142,49 @@ function AdminAlbumPhotos() {
}));
};
// Toast
useEffect(() => {
if (toast) {
const timer = setTimeout(() => setToast(null), 3000);
return () => clearTimeout(timer);
}
}, [toast]);
useEffect(() => {
//
const token = localStorage.getItem('adminToken');
const userData = localStorage.getItem('adminUser');
if (!token || !userData) {
if (!authApi.hasToken()) {
navigate('/admin');
return;
}
setUser(JSON.parse(userData));
setUser(authApi.getCurrentUser());
fetchAlbumData();
}, [navigate, albumId]);
const fetchAlbumData = async () => {
try {
const token = localStorage.getItem('adminToken');
//
const albumRes = await fetch(`/api/albums/${albumId}`);
if (!albumRes.ok) throw new Error('앨범을 찾을 수 없습니다');
const albumData = await albumRes.json();
const albumData = await getAlbum(albumId);
setAlbum(albumData);
//
const membersRes = await fetch('/api/members');
if (membersRes.ok) {
const membersData = await membersRes.json();
try {
const membersData = await getMembers();
setMembers(membersData);
}
} catch (e) { /* 무시 */ }
//
const photosRes = await fetch(`/api/admin/albums/${albumId}/photos`, {
headers: { 'Authorization': `Bearer ${token}` }
});
let photosData = [];
if (photosRes.ok) {
photosData = await photosRes.json();
try {
photosData = await albumsApi.getAlbumPhotos(albumId);
setPhotos(photosData);
}
} catch (e) { /* 무시 */ }
//
const teasersRes = await fetch(`/api/admin/albums/${albumId}/teasers`, {
headers: { 'Authorization': `Bearer ${token}` }
});
let teasersData = [];
if (teasersRes.ok) {
teasersData = await teasersRes.json();
try {
teasersData = await albumsApi.getAlbumTeasers(albumId);
setTeasers(teasersData);
}
} catch (e) { /* 무시 */ }
// ( + 1)
// ,
//
const maxPhotoOrder = photosData.length > 0
? Math.max(...photosData.map(p => p.sort_order || 0))
: 0;
const maxTeaserOrder = teasersData.length > 0
? Math.max(...teasersData.map(t => t.sort_order || 0))
: 0;
//
setStartNumber(maxPhotoOrder + 1);
setLoading(false);
} catch (error) {
console.error('앨범 로드 오류:', error);
@ -229,12 +208,6 @@ function AdminAlbumPhotos() {
}
}, [photoType, photos, teasers]);
const handleLogout = () => {
localStorage.removeItem('adminToken');
localStorage.removeItem('adminUser');
navigate('/admin');
};
//
const handleFileSelect = (e) => {
const files = Array.from(e.target.files);
@ -504,7 +477,6 @@ function AdminAlbumPhotos() {
// ( /)
const handleDelete = async () => {
setDeleting(true);
const token = localStorage.getItem('adminToken');
try {
// ID ID
@ -515,24 +487,12 @@ function AdminAlbumPhotos() {
//
for (const photoId of photoIds) {
const res = await fetch(`/api/admin/albums/${albumId}/photos/${photoId}`, {
method: 'DELETE',
headers: { 'Authorization': `Bearer ${token}` }
});
if (!res.ok) {
throw new Error('사진 삭제 실패');
}
await albumsApi.deleteAlbumPhoto(albumId, photoId);
}
//
for (const teaserId of teaserIds) {
const res = await fetch(`/api/admin/albums/${albumId}/teasers/${teaserId}`, {
method: 'DELETE',
headers: { 'Authorization': `Bearer ${token}` }
});
if (!res.ok) {
throw new Error('티저 삭제 실패');
}
await albumsApi.deleteAlbumTeaser(albumId, teaserId);
}
// UI
@ -553,8 +513,14 @@ function AdminAlbumPhotos() {
if (loading) {
return (
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
<div className="animate-spin rounded-full h-12 w-12 border-4 border-primary border-t-transparent"></div>
<div className="min-h-screen bg-gray-50">
{/* 헤더 */}
<AdminHeader user={user} />
{/* 로딩 스피너 */}
<main className="max-w-7xl mx-auto px-6 py-8 flex items-center justify-center" style={{ minHeight: 'calc(100vh - 80px)' }}>
<div className="animate-spin rounded-full h-12 w-12 border-4 border-primary border-t-transparent"></div>
</main>
</div>
);
}
@ -565,65 +531,20 @@ function AdminAlbumPhotos() {
<Toast toast={toast} onClose={() => setToast(null)} />
{/* 삭제 확인 다이얼로그 */}
<AnimatePresence>
{deleteDialog.show && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
onClick={() => !deleting && setDeleteDialog({ show: false, photos: [] })}
>
<motion.div
initial={{ scale: 0.9, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.9, opacity: 0 }}
className="bg-white rounded-2xl p-6 max-w-md w-full mx-4 shadow-xl"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center gap-3 mb-4">
<div className="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center">
<AlertTriangle className="text-red-500" size={20} />
</div>
<h3 className="text-lg font-bold text-gray-900">사진 삭제</h3>
</div>
<p className="text-gray-600 mb-6">
<span className="font-medium text-gray-900">{deleteDialog.photos.length}</span> 사진을 삭제하시겠습니까?
<br />
<span className="text-sm text-red-500"> 작업은 되돌릴 없습니다.</span>
</p>
<div className="flex justify-end gap-3">
<button
onClick={() => setDeleteDialog({ show: false, photos: [] })}
disabled={deleting}
className="px-4 py-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors disabled:opacity-50"
>
취소
</button>
<button
onClick={handleDelete}
disabled={deleting}
className="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors disabled:opacity-50 flex items-center gap-2"
>
{deleting ? (
<>
<span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
삭제 ...
</>
) : (
<>
<Trash2 size={16} />
삭제
</>
)}
</button>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
<ConfirmDialog
isOpen={deleteDialog.show}
onClose={() => setDeleteDialog({ show: false, photos: [] })}
onConfirm={handleDelete}
title="사진 삭제"
message={
<>
<span className="font-medium text-gray-900">{deleteDialog.photos.length}</span> 사진을 삭제하시겠습니까?
<br />
<span className="text-sm text-red-500"> 작업은 되돌릴 없습니다.</span>
</>
}
loading={deleting}
/>
{/* 이미지 미리보기 */}
<AnimatePresence>
@ -668,30 +589,7 @@ function AdminAlbumPhotos() {
</AnimatePresence>
{/* 헤더 */}
<header className="bg-white shadow-sm border-b border-gray-100">
<div className="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
<div className="flex items-center gap-4">
<Link to="/admin/dashboard" className="text-2xl font-bold text-primary hover:opacity-80 transition-opacity">
fromis_9
</Link>
<span className="px-3 py-1 bg-primary/10 text-primary text-sm font-medium rounded-full">
Admin
</span>
</div>
<div className="flex items-center gap-4">
<span className="text-gray-500 text-sm">
안녕하세요, <span className="text-gray-900 font-medium">{user?.username}</span>
</span>
<button
onClick={handleLogout}
className="flex items-center gap-2 px-4 py-2 text-gray-500 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors"
>
<LogOut size={18} />
<span>로그아웃</span>
</button>
</div>
</div>
</header>
<AdminHeader user={user} />
{/* 메인 콘텐츠 */}
<main className="max-w-7xl mx-auto px-6 py-8">

View file

@ -3,10 +3,16 @@ import { useNavigate, Link } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import {
Plus, Search, Edit2, Trash2, Image, Music,
Home, ChevronRight, LogOut, Calendar, AlertTriangle, X
Home, ChevronRight, Calendar, X
} from 'lucide-react';
import Toast from '../../../components/Toast';
import Tooltip from '../../../components/Tooltip';
import AdminHeader from '../../../components/admin/AdminHeader';
import ConfirmDialog from '../../../components/admin/ConfirmDialog';
import useToast from '../../../hooks/useToast';
import * as authApi from '../../../api/admin/auth';
import { getAlbums } from '../../../api/public/albums';
import * as albumsApi from '../../../api/admin/albums';
function AdminAlbums() {
const navigate = useNavigate();
@ -14,49 +20,30 @@ function AdminAlbums() {
const [loading, setLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState('');
const [user, setUser] = useState(null);
const [toast, setToast] = useState(null);
const { toast, setToast } = useToast();
const [deleteDialog, setDeleteDialog] = useState({ show: false, album: null });
const [deleting, setDeleting] = useState(false);
// Toast
useEffect(() => {
if (toast) {
const timer = setTimeout(() => setToast(null), 3000);
return () => clearTimeout(timer);
}
}, [toast]);
useEffect(() => {
//
const token = localStorage.getItem('adminToken');
const userData = localStorage.getItem('adminUser');
if (!token || !userData) {
if (!authApi.hasToken()) {
navigate('/admin');
return;
}
setUser(JSON.parse(userData));
setUser(authApi.getCurrentUser());
fetchAlbums();
}, [navigate]);
const fetchAlbums = () => {
fetch('/api/albums')
.then(res => res.json())
.then(data => {
setAlbums(data);
setLoading(false);
})
.catch(error => {
console.error('앨범 로드 오류:', error);
setLoading(false);
});
};
const handleLogout = () => {
localStorage.removeItem('adminToken');
localStorage.removeItem('adminUser');
navigate('/admin');
const fetchAlbums = async () => {
try {
const data = await getAlbums();
setAlbums(data);
} catch (error) {
console.error('앨범 로드 오류:', error);
} finally {
setLoading(false);
}
};
const handleDelete = async () => {
@ -64,21 +51,10 @@ function AdminAlbums() {
setDeleting(true);
try {
const token = localStorage.getItem('adminToken');
const response = await fetch(`/api/admin/albums/${deleteDialog.album.id}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`,
},
});
if (!response.ok) {
throw new Error('삭제 실패');
}
await albumsApi.deleteAlbum(deleteDialog.album.id);
setToast({ message: `"${deleteDialog.album.title}" 앨범이 삭제되었습니다.`, type: 'success' });
setDeleteDialog({ show: false, album: null });
fetchAlbums(); //
fetchAlbums();
} catch (error) {
console.error('삭제 오류:', error);
setToast({ message: '앨범 삭제 중 오류가 발생했습니다.', type: 'error' });
@ -105,91 +81,23 @@ function AdminAlbums() {
<Toast toast={toast} onClose={() => setToast(null)} />
{/* 삭제 확인 다이얼로그 */}
<AnimatePresence>
{deleteDialog.show && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
onClick={() => !deleting && setDeleteDialog({ show: false, album: null })}
>
<motion.div
initial={{ scale: 0.9, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.9, opacity: 0 }}
className="bg-white rounded-2xl p-6 max-w-md w-full mx-4 shadow-xl"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center gap-3 mb-4">
<div className="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center">
<AlertTriangle className="text-red-500" size={20} />
</div>
<h3 className="text-lg font-bold text-gray-900">앨범 삭제</h3>
</div>
<p className="text-gray-600 mb-6">
<span className="font-medium text-gray-900">"{deleteDialog.album?.title}"</span> 앨범을 삭제하시겠습니까?
<br />
<span className="text-sm text-red-500"> 작업은 되돌릴 없으며, 모든 트랙과 커버 이미지가 함께 삭제됩니다.</span>
</p>
<div className="flex justify-end gap-3">
<button
onClick={() => setDeleteDialog({ show: false, album: null })}
disabled={deleting}
className="px-4 py-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors disabled:opacity-50"
>
취소
</button>
<button
onClick={handleDelete}
disabled={deleting}
className="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors disabled:opacity-50 flex items-center gap-2"
>
{deleting ? (
<>
<span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
삭제 ...
</>
) : (
<>
<Trash2 size={16} />
삭제
</>
)}
</button>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
<ConfirmDialog
isOpen={deleteDialog.show}
onClose={() => setDeleteDialog({ show: false, album: null })}
onConfirm={handleDelete}
title="앨범 삭제"
message={
<>
<span className="font-medium text-gray-900">"{deleteDialog.album?.title}"</span> 앨범을 삭제하시겠습니까?
<br />
<span className="text-sm text-red-500"> 작업은 되돌릴 없으며, 모든 트랙과 커버 이미지가 함께 삭제됩니다.</span>
</>
}
loading={deleting}
/>
{/* 헤더 */}
<header className="bg-white shadow-sm border-b border-gray-100">
<div className="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
<div className="flex items-center gap-4">
<Link to="/admin/dashboard" className="text-2xl font-bold text-primary hover:opacity-80 transition-opacity">
fromis_9
</Link>
<span className="px-3 py-1 bg-primary/10 text-primary text-sm font-medium rounded-full">
Admin
</span>
</div>
<div className="flex items-center gap-4">
<span className="text-gray-500 text-sm">
안녕하세요, <span className="text-gray-900 font-medium">{user?.username}</span>
</span>
<button
onClick={handleLogout}
className="flex items-center gap-2 px-4 py-2 text-gray-500 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors"
>
<LogOut size={18} />
<span>로그아웃</span>
</button>
</div>
</div>
</header>
<AdminHeader user={user} />
{/* 메인 콘텐츠 */}
<main className="max-w-7xl mx-auto px-6 py-8">

View file

@ -2,9 +2,14 @@ import { useState, useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { motion } from 'framer-motion';
import {
Disc3, Calendar, Users, LogOut,
Disc3, Calendar, Users,
Home, ChevronRight
} from 'lucide-react';
import AdminHeader from '../../../components/admin/AdminHeader';
import * as authApi from '../../../api/admin/auth';
import { getMembers } from '../../../api/public/members';
import { getAlbums, getAlbum } from '../../../api/public/albums';
import { getSchedules } from '../../../api/public/schedules';
// ( )
function AnimatedNumber({ value }) {
@ -49,27 +54,17 @@ function AdminDashboard() {
useEffect(() => {
//
const token = localStorage.getItem('adminToken');
const userData = localStorage.getItem('adminUser');
if (!token || !userData) {
if (!authApi.hasToken()) {
navigate('/admin');
return;
}
setUser(JSON.parse(userData));
setUser(authApi.getCurrentUser());
//
fetch('/api/admin/verify', {
headers: { Authorization: `Bearer ${token}` }
})
.then(res => {
if (!res.ok) throw new Error('Invalid token');
return res.json();
})
authApi.verifyToken()
.catch(() => {
localStorage.removeItem('adminToken');
localStorage.removeItem('adminUser');
authApi.logout();
navigate('/admin');
});
@ -80,56 +75,39 @@ function AdminDashboard() {
const fetchStats = async () => {
//
try {
const membersRes = await fetch('/api/members');
if (membersRes.ok) {
const members = await membersRes.json();
setStats(prev => ({ ...prev, members: members.filter(m => !m.is_former).length }));
}
const members = await getMembers();
setStats(prev => ({ ...prev, members: members.filter(m => !m.is_former).length }));
} catch (e) { console.error('멤버 통계 오류:', e); }
try {
const albumsRes = await fetch('/api/albums');
if (albumsRes.ok) {
const albums = await albumsRes.json();
setStats(prev => ({ ...prev, albums: albums.length }));
//
let totalPhotos = 0;
for (const album of albums) {
try {
const detailRes = await fetch(`/api/albums/${album.id}`);
if (detailRes.ok) {
const detail = await detailRes.json();
if (detail.conceptPhotos) {
Object.values(detail.conceptPhotos).forEach(photos => {
totalPhotos += photos.length;
});
}
if (detail.teasers) {
totalPhotos += detail.teasers.length;
}
}
} catch (e) { /* 개별 앨범 오류 무시 */ }
}
setStats(prev => ({ ...prev, photos: totalPhotos }));
const albums = await getAlbums();
setStats(prev => ({ ...prev, albums: albums.length }));
//
let totalPhotos = 0;
for (const album of albums) {
try {
const detail = await getAlbum(album.id);
if (detail.conceptPhotos) {
Object.values(detail.conceptPhotos).forEach(photos => {
totalPhotos += photos.length;
});
}
if (detail.teasers) {
totalPhotos += detail.teasers.length;
}
} catch (e) { /* 개별 앨범 오류 무시 */ }
}
setStats(prev => ({ ...prev, photos: totalPhotos }));
} catch (e) { console.error('앨범 통계 오류:', e); }
try {
const schedulesRes = await fetch('/api/schedules');
if (schedulesRes.ok) {
const schedules = await schedulesRes.json();
setStats(prev => ({ ...prev, schedules: Array.isArray(schedules) ? schedules.length : 0 }));
}
const today = new Date();
const schedules = await getSchedules(today.getFullYear(), today.getMonth() + 1);
setStats(prev => ({ ...prev, schedules: Array.isArray(schedules) ? schedules.length : 0 }));
} catch (e) { console.error('일정 통계 오류:', e); }
};
const handleLogout = () => {
localStorage.removeItem('adminToken');
localStorage.removeItem('adminUser');
navigate('/admin');
};
//
const menuItems = [
{
@ -158,30 +136,7 @@ function AdminDashboard() {
return (
<div className="min-h-screen bg-gray-50">
{/* 헤더 */}
<header className="bg-white shadow-sm border-b border-gray-100">
<div className="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
<div className="flex items-center gap-4">
<Link to="/admin/dashboard" className="text-2xl font-bold text-primary hover:opacity-80 transition-opacity">
fromis_9
</Link>
<span className="px-3 py-1 bg-primary/10 text-primary text-sm font-medium rounded-full">
Admin
</span>
</div>
<div className="flex items-center gap-4">
<span className="text-gray-500 text-sm">
안녕하세요, <span className="text-gray-900 font-medium">{user?.username}</span>
</span>
<button
onClick={handleLogout}
className="flex items-center gap-2 px-4 py-2 text-gray-500 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors"
>
<LogOut size={18} />
<span>로그아웃</span>
</button>
</div>
</div>
</header>
<AdminHeader user={user} />
{/* 메인 콘텐츠 */}
<main className="max-w-7xl mx-auto px-6 py-8">

View file

@ -2,6 +2,7 @@ import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { motion } from 'framer-motion';
import { Lock, User, AlertCircle, Eye, EyeOff } from 'lucide-react';
import * as authApi from '../../../api/admin/auth';
function AdminLogin() {
const navigate = useNavigate();
@ -14,13 +15,13 @@ function AdminLogin() {
//
useEffect(() => {
const token = localStorage.getItem('adminToken');
if (token) {
//
fetch('/api/admin/verify', {
headers: { 'Authorization': `Bearer ${token}` }
})
.then(res => res.json())
if (!authApi.hasToken()) {
setCheckingAuth(false);
return;
}
//
authApi.verifyToken()
.then(data => {
if (data.valid) {
navigate('/admin/dashboard');
@ -29,9 +30,6 @@ function AdminLogin() {
}
})
.catch(() => setCheckingAuth(false));
} else {
setCheckingAuth(false);
}
}, [navigate]);
const handleSubmit = async (e) => {
@ -40,17 +38,7 @@ function AdminLogin() {
setLoading(true);
try {
const response = await fetch('/api/admin/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || '로그인에 실패했습니다.');
}
const data = await authApi.login(username, password);
// JWT
localStorage.setItem('adminToken', data.token);

View file

@ -2,247 +2,15 @@ import { useState, useEffect, useRef } from 'react';
import { useNavigate, useParams, Link } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import {
Save, Upload, LogOut,
Home, ChevronRight, ChevronLeft, ChevronDown, User, Instagram, Calendar, Briefcase
Save, Upload,
Home, ChevronRight, User, Instagram, Calendar, Briefcase
} from 'lucide-react';
import Toast from '../../../components/Toast';
//
function CustomDatePicker({ value, onChange }) {
const [isOpen, setIsOpen] = useState(false);
const [viewMode, setViewMode] = useState('days');
const [viewDate, setViewDate] = useState(() => {
if (value) return new Date(value);
return new Date();
});
const ref = useRef(null);
useEffect(() => {
const handleClickOutside = (e) => {
if (ref.current && !ref.current.contains(e.target)) {
setIsOpen(false);
setViewMode('days');
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
const year = viewDate.getFullYear();
const month = viewDate.getMonth();
const firstDay = new Date(year, month, 1).getDay();
const daysInMonth = new Date(year, month + 1, 0).getDate();
const days = [];
for (let i = 0; i < firstDay; i++) {
days.push(null);
}
for (let i = 1; i <= daysInMonth; i++) {
days.push(i);
}
const startYear = Math.floor(year / 10) * 10 - 1;
const years = Array.from({ length: 12 }, (_, i) => startYear + i);
const prevMonth = () => setViewDate(new Date(year, month - 1, 1));
const nextMonth = () => setViewDate(new Date(year, month + 1, 1));
const prevYearRange = () => setViewDate(new Date(year - 10, month, 1));
const nextYearRange = () => setViewDate(new Date(year + 10, month, 1));
const selectDate = (day) => {
const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
onChange(dateStr);
setIsOpen(false);
setViewMode('days');
};
const selectYear = (y) => {
setViewDate(new Date(y, month, 1));
setViewMode('months');
};
const selectMonth = (m) => {
setViewDate(new Date(year, m, 1));
setViewMode('days');
};
const formatDisplayDate = (dateStr) => {
if (!dateStr) return '';
const [y, m, d] = dateStr.split('-');
return `${y}${parseInt(m)}${parseInt(d)}`;
};
const isSelected = (day) => {
if (!value || !day) return false;
const [y, m, d] = value.split('-');
return parseInt(y) === year && parseInt(m) === month + 1 && parseInt(d) === day;
};
const isToday = (day) => {
if (!day) return false;
const today = new Date();
return today.getFullYear() === year && today.getMonth() === month && today.getDate() === day;
};
const isCurrentYear = (y) => new Date().getFullYear() === y;
const isCurrentMonth = (m) => {
const today = new Date();
return today.getFullYear() === year && today.getMonth() === m;
};
const months = ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'];
return (
<div ref={ref} className="relative">
<button
type="button"
onClick={() => setIsOpen(!isOpen)}
className="w-full px-4 py-3 border border-gray-200 rounded-xl bg-white flex items-center justify-between hover:border-gray-300 transition-colors focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
>
<span className={value ? 'text-gray-900' : 'text-gray-400'}>
{value ? formatDisplayDate(value) : '날짜 선택'}
</span>
<Calendar size={18} className="text-gray-400" />
</button>
<AnimatePresence>
{isOpen && (
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -10 }}
transition={{ duration: 0.15 }}
className="absolute z-50 mt-2 bg-white border border-gray-200 rounded-xl shadow-lg p-4 w-80"
>
<div className="flex items-center justify-between mb-4">
<button
type="button"
onClick={viewMode === 'years' ? prevYearRange : prevMonth}
className="p-1.5 hover:bg-gray-100 rounded-lg transition-colors"
>
<ChevronLeft size={20} className="text-gray-600" />
</button>
<button
type="button"
onClick={() => setViewMode(viewMode === 'days' ? 'years' : 'days')}
className="font-medium text-gray-900 hover:text-primary transition-colors flex items-center gap-1"
>
{viewMode === 'years' ? `${years[0]} - ${years[years.length - 1]}` : `${year}${month + 1}`}
<ChevronDown size={16} className={`transition-transform ${viewMode !== 'days' ? 'rotate-180' : ''}`} />
</button>
<button
type="button"
onClick={viewMode === 'years' ? nextYearRange : nextMonth}
className="p-1.5 hover:bg-gray-100 rounded-lg transition-colors"
>
<ChevronRight size={20} className="text-gray-600" />
</button>
</div>
<AnimatePresence mode="wait">
{viewMode === 'years' && (
<motion.div
key="years"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.15 }}
>
<div className="text-center text-sm text-gray-500 mb-3">년도</div>
<div className="grid grid-cols-4 gap-2 mb-4">
{years.map((y) => (
<button
key={y}
type="button"
onClick={() => selectYear(y)}
className={`py-2 rounded-lg text-sm transition-colors ${year === y ? 'bg-primary text-white' : 'hover:bg-gray-100 text-gray-700'} ${isCurrentYear(y) && year !== y ? 'border border-primary text-primary' : ''}`}
>
{y}
</button>
))}
</div>
<div className="text-center text-sm text-gray-500 mb-3"></div>
<div className="grid grid-cols-4 gap-2">
{months.map((m, i) => (
<button
key={m}
type="button"
onClick={() => selectMonth(i)}
className={`py-2 rounded-lg text-sm transition-colors ${month === i ? 'bg-primary text-white' : 'hover:bg-gray-100 text-gray-700'} ${isCurrentMonth(i) && month !== i ? 'border border-primary text-primary' : ''}`}
>
{m}
</button>
))}
</div>
</motion.div>
)}
{viewMode === 'months' && (
<motion.div
key="months"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.15 }}
>
<div className="text-center text-sm text-gray-500 mb-3"> 선택</div>
<div className="grid grid-cols-4 gap-2">
{months.map((m, i) => (
<button
key={m}
type="button"
onClick={() => selectMonth(i)}
className={`py-2.5 rounded-lg text-sm transition-colors ${month === i ? 'bg-primary text-white' : 'hover:bg-gray-100 text-gray-700'} ${isCurrentMonth(i) && month !== i ? 'border border-primary text-primary' : ''}`}
>
{m}
</button>
))}
</div>
</motion.div>
)}
{viewMode === 'days' && (
<motion.div
key="days"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.15 }}
>
<div className="grid grid-cols-7 gap-1 mb-2">
{['일', '월', '화', '수', '목', '금', '토'].map((d, i) => (
<div
key={d}
className={`text-center text-xs font-medium py-1 ${i === 0 ? 'text-red-400' : i === 6 ? 'text-blue-400' : 'text-gray-400'}`}
>
{d}
</div>
))}
</div>
<div className="grid grid-cols-7 gap-1">
{days.map((day, i) => (
<button
key={i}
type="button"
disabled={!day}
onClick={() => day && selectDate(day)}
className={`aspect-square rounded-lg text-sm flex items-center justify-center transition-colors ${!day ? '' : 'hover:bg-gray-100'} ${isSelected(day) ? 'bg-primary text-white hover:bg-primary-dark' : ''} ${isToday(day) && !isSelected(day) ? 'border border-primary text-primary' : ''} ${day && !isSelected(day) && !isToday(day) ? 'text-gray-700' : ''}`}
>
{day}
</button>
))}
</div>
</motion.div>
)}
</AnimatePresence>
</motion.div>
)}
</AnimatePresence>
</div>
);
}
import CustomDatePicker from '../../../components/admin/CustomDatePicker';
import AdminHeader from '../../../components/admin/AdminHeader';
import useToast from '../../../hooks/useToast';
import * as authApi from '../../../api/admin/auth';
import * as membersApi from '../../../api/admin/members';
function AdminMemberEdit() {
const navigate = useNavigate();
@ -250,7 +18,7 @@ function AdminMemberEdit() {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [toast, setToast] = useState(null);
const { toast, setToast } = useToast();
const [imagePreview, setImagePreview] = useState(null);
const [imageFile, setImageFile] = useState(null);
@ -262,38 +30,20 @@ function AdminMemberEdit() {
is_former: false
});
// Toast
useEffect(() => {
if (toast) {
const timer = setTimeout(() => setToast(null), 3000);
return () => clearTimeout(timer);
}
}, [toast]);
useEffect(() => {
//
const token = localStorage.getItem('adminToken');
const userData = localStorage.getItem('adminUser');
if (!token || !userData) {
if (!authApi.hasToken()) {
navigate('/admin');
return;
}
setUser(JSON.parse(userData));
setUser(authApi.getCurrentUser());
fetchMember();
}, [navigate, name]);
const fetchMember = async () => {
try {
const token = localStorage.getItem('adminToken');
const res = await fetch(`/api/admin/members/${encodeURIComponent(name)}`, {
headers: { Authorization: `Bearer ${token}` }
});
if (!res.ok) throw new Error('멤버 조회 실패');
const data = await res.json();
const data = await membersApi.getMember(encodeURIComponent(name));
setFormData({
name: data.name || '',
birth_date: data.birth_date ? data.birth_date.split('T')[0] : '',
@ -310,12 +60,6 @@ function AdminMemberEdit() {
}
};
const handleLogout = () => {
localStorage.removeItem('adminToken');
localStorage.removeItem('adminUser');
navigate('/admin');
};
const handleImageChange = (e) => {
const file = e.target.files[0];
if (file) {
@ -331,7 +75,6 @@ function AdminMemberEdit() {
setSaving(true);
try {
const token = localStorage.getItem('adminToken');
const formDataToSend = new FormData();
formDataToSend.append('name', formData.name);
@ -344,14 +87,7 @@ function AdminMemberEdit() {
formDataToSend.append('image', imageFile);
}
const res = await fetch(`/api/admin/members/${encodeURIComponent(name)}`, {
method: 'PUT',
headers: { Authorization: `Bearer ${token}` },
body: formDataToSend
});
if (!res.ok) throw new Error('수정 실패');
await membersApi.updateMember(encodeURIComponent(name), formDataToSend);
setToast({ message: '멤버 정보가 수정되었습니다.', type: 'success' });
setTimeout(() => navigate('/admin/members'), 1000);
} catch (error) {
@ -368,30 +104,7 @@ function AdminMemberEdit() {
<Toast toast={toast} onClose={() => setToast(null)} />
{/* 헤더 */}
<header className="bg-white shadow-sm border-b border-gray-100">
<div className="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
<div className="flex items-center gap-4">
<Link to="/admin/dashboard" className="text-2xl font-bold text-primary hover:opacity-80 transition-opacity">
fromis_9
</Link>
<span className="px-3 py-1 bg-primary/10 text-primary text-sm font-medium rounded-full">
Admin
</span>
</div>
<div className="flex items-center gap-4">
<span className="text-gray-500 text-sm">
안녕하세요, <span className="text-gray-900 font-medium">{user?.username}</span>
</span>
<button
onClick={handleLogout}
className="flex items-center gap-2 px-4 py-2 text-gray-500 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors"
>
<LogOut size={18} />
<span>로그아웃</span>
</button>
</div>
</div>
</header>
<AdminHeader user={user} />
{/* 메인 콘텐츠 */}
<main className="max-w-4xl mx-auto px-6 py-8">

View file

@ -2,25 +2,19 @@ import { useState, useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { motion } from 'framer-motion';
import {
Edit2, LogOut,
Edit2,
Home, ChevronRight, Users, User
} from 'lucide-react';
import Toast from '../../../components/Toast';
import AdminHeader from '../../../components/admin/AdminHeader';
import useToast from '../../../hooks/useToast';
function AdminMembers() {
const navigate = useNavigate();
const [members, setMembers] = useState([]);
const [loading, setLoading] = useState(true);
const [user, setUser] = useState(null);
const [toast, setToast] = useState(null);
// Toast
useEffect(() => {
if (toast) {
const timer = setTimeout(() => setToast(null), 3000);
return () => clearTimeout(timer);
}
}, [toast]);
const { toast, setToast } = useToast();
useEffect(() => {
//
@ -49,12 +43,6 @@ function AdminMembers() {
});
};
const handleLogout = () => {
localStorage.removeItem('adminToken');
localStorage.removeItem('adminUser');
navigate('/admin');
};
// / (is_former: 0=, 1=)
const activeMembers = members.filter(m => !m.is_former);
const formerMembers = members.filter(m => m.is_former);
@ -110,30 +98,7 @@ function AdminMembers() {
<Toast toast={toast} onClose={() => setToast(null)} />
{/* 헤더 */}
<header className="bg-white shadow-sm border-b border-gray-100">
<div className="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
<div className="flex items-center gap-4">
<Link to="/admin/dashboard" className="text-2xl font-bold text-primary hover:opacity-80 transition-opacity">
fromis_9
</Link>
<span className="px-3 py-1 bg-primary/10 text-primary text-sm font-medium rounded-full">
Admin
</span>
</div>
<div className="flex items-center gap-4">
<span className="text-gray-500 text-sm">
안녕하세요, <span className="text-gray-900 font-medium">{user?.username}</span>
</span>
<button
onClick={handleLogout}
className="flex items-center gap-2 px-4 py-2 text-gray-500 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors"
>
<LogOut size={18} />
<span>로그아웃</span>
</button>
</div>
</div>
</header>
<AdminHeader user={user} />
{/* 메인 콘텐츠 */}
<main className="max-w-7xl mx-auto px-6 py-8">

File diff suppressed because it is too large Load diff

View file

@ -2,27 +2,54 @@ import { useState, useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import {
LogOut, Home, ChevronRight, Bot, Play, Square,
Home, ChevronRight, Bot, Play, Square,
Youtube, Calendar, Clock, CheckCircle, XCircle, RefreshCw, Download
} from 'lucide-react';
import Toast from '../../../components/Toast';
import Tooltip from '../../../components/Tooltip';
import AdminHeader from '../../../components/admin/AdminHeader';
import useToast from '../../../hooks/useToast';
import * as botsApi from '../../../api/admin/bots';
// X
const XIcon = ({ size = 20, fill = "currentColor" }) => (
<svg width={size} height={size} viewBox="0 0 24 24" fill={fill}>
<path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
</svg>
);
// Meilisearch
const MeilisearchIcon = ({ size = 20 }) => (
<svg width={size} height={size} viewBox="0 108.4 512 295.2">
<defs>
<linearGradient id="meili-a" x1="488.157" x2="-21.055" y1="469.917" y2="179.001" gradientTransform="matrix(1 0 0 -1 0 514)" gradientUnits="userSpaceOnUse">
<stop offset="0" stopColor="#ff5caa"/>
<stop offset="1" stopColor="#ff4e62"/>
</linearGradient>
<linearGradient id="meili-b" x1="522.305" x2="13.094" y1="410.144" y2="119.228" gradientTransform="matrix(1 0 0 -1 0 514)" gradientUnits="userSpaceOnUse">
<stop offset="0" stopColor="#ff5caa"/>
<stop offset="1" stopColor="#ff4e62"/>
</linearGradient>
<linearGradient id="meili-c" x1="556.456" x2="47.244" y1="350.368" y2="59.452" gradientTransform="matrix(1 0 0 -1 0 514)" gradientUnits="userSpaceOnUse">
<stop offset="0" stopColor="#ff5caa"/>
<stop offset="1" stopColor="#ff4e62"/>
</linearGradient>
</defs>
<path d="m0 403.6 94.6-239.3c13.3-33.7 46.2-55.9 82.8-55.9h57l-94.6 239.3c-13.3 33.7-46.2 55.9-82.8 55.9z" fill="url(#meili-a)"/>
<path d="m138.8 403.6 94.6-239.3c13.3-33.7 46.2-55.9 82.8-55.9h57l-94.6 239.3c-13.3 33.7-46.2 55.9-82.8 55.9z" fill="url(#meili-b)"/>
<path d="m277.6 403.6 94.6-239.3c13.3-33.7 46.2-55.9 82.8-55.9h57l-94.6 239.3c-13.3 33.7-46.2 55.9-82.8 55.9z" fill="url(#meili-c)"/>
</svg>
);
function AdminScheduleBots() {
const navigate = useNavigate();
const [user, setUser] = useState(null);
const [toast, setToast] = useState(null);
const { toast, setToast } = useToast();
const [bots, setBots] = useState([]);
const [loading, setLoading] = useState(true);
const [isInitialLoad, setIsInitialLoad] = useState(true); // ()
const [syncing, setSyncing] = useState(null); // ID
// Toast
useEffect(() => {
if (toast) {
const timer = setTimeout(() => setToast(null), 3000);
return () => clearTimeout(timer);
}
}, [toast]);
const [quotaWarning, setQuotaWarning] = useState(null); //
useEffect(() => {
const token = localStorage.getItem('adminToken');
@ -35,21 +62,15 @@ function AdminScheduleBots() {
setUser(JSON.parse(userData));
fetchBots();
fetchQuotaWarning();
}, [navigate]);
//
const fetchBots = async () => {
setLoading(true);
try {
const token = localStorage.getItem('adminToken');
const response = await fetch('/api/admin/bots', {
headers: { Authorization: `Bearer ${token}` }
});
if (response.ok) {
const data = await response.json();
setBots(data);
}
const data = await botsApi.getBots();
setBots(data);
} catch (error) {
console.error('봇 목록 조회 오류:', error);
setToast({ type: 'error', message: '봇 목록을 불러올 수 없습니다.' });
@ -58,65 +79,69 @@ function AdminScheduleBots() {
}
};
const handleLogout = () => {
localStorage.removeItem('adminToken');
localStorage.removeItem('adminUser');
navigate('/admin');
//
const fetchQuotaWarning = async () => {
try {
const data = await botsApi.getQuotaWarning();
if (data.active) {
setQuotaWarning(data);
}
} catch (error) {
console.error('할당량 경고 조회 오류:', error);
}
};
//
const handleDismissQuotaWarning = async () => {
try {
await botsApi.dismissQuotaWarning();
setQuotaWarning(null);
} catch (error) {
console.error('할당량 경고 해제 오류:', error);
}
};
// /
const toggleBot = async (botId, currentStatus, botName) => {
try {
const token = localStorage.getItem('adminToken');
const action = currentStatus === 'running' ? 'stop' : 'start';
const response = await fetch(`/api/admin/bots/${botId}/${action}`, {
method: 'POST',
headers: { Authorization: `Bearer ${token}` }
});
if (response.ok) {
setToast({
type: 'success',
message: action === 'start' ? `${botName} 봇이 시작되었습니다.` : `${botName} 봇이 정지되었습니다.`
});
fetchBots(); //
if (action === 'start') {
await botsApi.startBot(botId);
} else {
const data = await response.json();
setToast({ type: 'error', message: data.error || '작업 실패' });
await botsApi.stopBot(botId);
}
// ( )
setBots(prev => prev.map(bot =>
bot.id === botId
? { ...bot, status: action === 'start' ? 'running' : 'stopped' }
: bot
));
setToast({
type: 'success',
message: action === 'start' ? `${botName} 봇이 시작되었습니다.` : `${botName} 봇이 정지되었습니다.`
});
} catch (error) {
console.error('봇 토글 오류:', error);
setToast({ type: 'error', message: '작업 중 오류가 발생했습니다.' });
setToast({ type: 'error', message: error.message || '작업 중 오류가 발생했습니다.' });
}
};
//
const syncAllVideos = async (botId) => {
const handleSyncAllVideos = async (botId) => {
setSyncing(botId);
try {
const token = localStorage.getItem('adminToken');
const response = await fetch(`/api/admin/bots/${botId}/sync-all`, {
method: 'POST',
headers: { Authorization: `Bearer ${token}` }
const data = await botsApi.syncAllVideos(botId);
setToast({
type: 'success',
message: `${data.addedCount}개 일정이 추가되었습니다. (전체 ${data.total}개)`
});
if (response.ok) {
const data = await response.json();
setToast({
type: 'success',
message: `${data.addedCount}개 일정이 추가되었습니다. (전체 ${data.total}개)`
});
} else {
const data = await response.json();
setToast({ type: 'error', message: data.error || '동기화 실패' });
}
// /
fetchBots();
} catch (error) {
console.error('전체 동기화 오류:', error);
setToast({ type: 'error', message: '동기화 중 오류가 발생했습니다.' });
fetchBots(); //
setToast({ type: 'error', message: error.message || '동기화 중 오류가 발생했습니다.' });
fetchBots();
} finally {
setSyncing(null);
}
@ -193,30 +218,7 @@ function AdminScheduleBots() {
<Toast toast={toast} onClose={() => setToast(null)} />
{/* 헤더 */}
<header className="bg-white shadow-sm border-b border-gray-100">
<div className="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
<div className="flex items-center gap-4">
<Link to="/admin/dashboard" className="text-2xl font-bold text-primary hover:opacity-80 transition-opacity">
fromis_9
</Link>
<span className="px-3 py-1 bg-primary/10 text-primary text-sm font-medium rounded-full">
Admin
</span>
</div>
<div className="flex items-center gap-4">
<span className="text-gray-500 text-sm">
안녕하세요, <span className="text-gray-900 font-medium">{user?.username}</span>
</span>
<button
onClick={handleLogout}
className="flex items-center gap-2 px-4 py-2 text-gray-500 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors"
>
<LogOut size={18} />
<span>로그아웃</span>
</button>
</div>
</div>
</header>
<AdminHeader user={user} />
{/* 메인 콘텐츠 */}
<main className="max-w-7xl mx-auto px-6 py-8">
@ -265,13 +267,36 @@ function AdminScheduleBots() {
</div>
</div>
{/* API 할당량 경고 배너 */}
{quotaWarning && (
<div className="bg-red-50 border border-red-200 rounded-xl p-4 mb-8 flex items-start justify-between">
<div className="flex items-start gap-3">
<div className="w-8 h-8 rounded-full bg-red-100 flex items-center justify-center flex-shrink-0">
<XCircle size={18} className="text-red-500" />
</div>
<div>
<h3 className="font-bold text-red-700">YouTube API 할당량 경고</h3>
<p className="text-sm text-red-600 mt-0.5">
{quotaWarning.message}
</p>
</div>
</div>
<button
onClick={handleDismissQuotaWarning}
className="text-red-400 hover:text-red-600 transition-colors text-sm px-2 py-1"
>
닫기
</button>
</div>
)}
{/* 봇 목록 */}
<div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
<div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between">
<h2 className="font-bold text-gray-900"> 목록</h2>
<Tooltip text="새로고침">
<button
onClick={fetchBots}
onClick={() => { setIsInitialLoad(true); fetchBots(); }}
disabled={loading}
className="p-2 hover:bg-gray-100 rounded-lg transition-colors text-gray-500 hover:text-gray-700 disabled:opacity-50"
>
@ -299,16 +324,25 @@ function AdminScheduleBots() {
return (
<motion.div
key={bot.id}
initial={{ opacity: 0, scale: 0.95 }}
initial={isInitialLoad ? { opacity: 0, scale: 0.95 } : false}
animate={{ opacity: 1, scale: 1 }}
transition={{ delay: index * 0.05 }}
transition={isInitialLoad ? { delay: index * 0.05 } : { duration: 0.15 }}
onAnimationComplete={() => isInitialLoad && index === bots.length - 1 && setIsInitialLoad(false)}
className="relative bg-gradient-to-br from-gray-50 to-white rounded-xl border border-gray-200 overflow-hidden hover:shadow-md transition-all"
>
{/* 상단 헤더 */}
<div className="flex items-center justify-between p-4 border-b border-gray-100">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-lg bg-red-50 flex items-center justify-center">
<Youtube size={20} className="text-red-500" />
<div className={`w-10 h-10 rounded-lg flex items-center justify-center ${
bot.type === 'x' ? 'bg-black' : bot.type === 'meilisearch' ? 'bg-[#ddf1fd]' : 'bg-red-50'
}`}>
{bot.type === 'x' ? (
<XIcon size={20} fill="white" />
) : bot.type === 'meilisearch' ? (
<MeilisearchIcon size={20} />
) : (
<Youtube size={20} className="text-red-500" />
)}
</div>
<div>
<h3 className="font-bold text-gray-900">{bot.name}</h3>
@ -325,16 +359,33 @@ function AdminScheduleBots() {
{/* 통계 정보 */}
<div className="grid grid-cols-3 divide-x divide-gray-100 bg-gray-50/50">
<div className="p-3 text-center">
<div className="text-lg font-bold text-gray-900">{bot.schedules_added}</div>
<div className="text-xs text-gray-400"> 추가</div>
</div>
<div className="p-3 text-center">
<div className={`text-lg font-bold ${bot.last_added_count > 0 ? 'text-green-500' : 'text-gray-400'}`}>
+{bot.last_added_count || 0}
</div>
<div className="text-xs text-gray-400">마지막</div>
</div>
{bot.type === 'meilisearch' ? (
<>
<div className="p-3 text-center">
<div className="text-lg font-bold text-gray-900">{bot.schedules_added || 0}</div>
<div className="text-xs text-gray-400">동기화 </div>
</div>
<div className="p-3 text-center">
<div className="text-lg font-bold text-gray-900">
{bot.last_added_count ? `${((bot.last_added_count / 1000) || 0).toFixed(1)}` : '-'}
</div>
<div className="text-xs text-gray-400">소요 시간</div>
</div>
</>
) : (
<>
<div className="p-3 text-center">
<div className="text-lg font-bold text-gray-900">{bot.schedules_added}</div>
<div className="text-xs text-gray-400"> 추가</div>
</div>
<div className="p-3 text-center">
<div className={`text-lg font-bold ${bot.last_added_count > 0 ? 'text-green-500' : 'text-gray-400'}`}>
+{bot.last_added_count || 0}
</div>
<div className="text-xs text-gray-400">마지막</div>
</div>
</>
)}
<div className="p-3 text-center">
<div className="text-lg font-bold text-gray-900">{formatInterval(bot.check_interval)}</div>
<div className="text-xs text-gray-400">업데이트 간격</div>
@ -354,7 +405,7 @@ function AdminScheduleBots() {
<div className="p-4 border-t border-gray-100">
<div className="flex gap-2">
<button
onClick={() => syncAllVideos(bot.id)}
onClick={() => handleSyncAllVideos(bot.id)}
disabled={syncing === bot.id}
className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-blue-500 text-white rounded-lg font-medium transition-colors hover:bg-blue-600 disabled:opacity-50"
>

View file

@ -1,9 +1,14 @@
import { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { motion, AnimatePresence, Reorder } from 'framer-motion';
import { LogOut, Home, ChevronRight, Plus, Edit3, Trash2, GripVertical, X, AlertTriangle } from 'lucide-react';
import { Home, ChevronRight, Plus, Edit3, Trash2, GripVertical, X } from 'lucide-react';
import { HexColorPicker } from 'react-colorful';
import Toast from '../../../components/Toast';
import AdminHeader from '../../../components/admin/AdminHeader';
import ConfirmDialog from '../../../components/admin/ConfirmDialog';
import useToast from '../../../hooks/useToast';
import * as authApi from '../../../api/admin/auth';
import * as categoriesApi from '../../../api/admin/categories';
// (8)
const colorOptions = [
@ -36,13 +41,7 @@ function AdminScheduleCategory() {
const [user, setUser] = useState(null);
const [categories, setCategories] = useState([]);
const [loading, setLoading] = useState(true);
const [toast, setToast] = useState(null);
// (3 )
const showToast = (type, message) => {
setToast({ type, message });
setTimeout(() => setToast(null), 3000);
};
const { toast, setToast, showSuccess, showError } = useToast();
//
const [modalOpen, setModalOpen] = useState(false);
@ -58,48 +57,36 @@ function AdminScheduleCategory() {
//
useEffect(() => {
const token = localStorage.getItem('adminToken');
if (!token) {
if (!authApi.hasToken()) {
navigate('/admin');
return;
}
fetch('/api/admin/verify', {
headers: { 'Authorization': `Bearer ${token}` }
})
.then(res => res.json())
.then(data => {
if (data.valid) {
setUser(data.user);
fetchCategories();
} else {
navigate('/admin');
}
})
.catch(() => navigate('/admin'));
authApi.verifyToken()
.then(data => {
if (data.valid) {
setUser(data.user);
fetchCategories();
} else {
navigate('/admin');
}
})
.catch(() => navigate('/admin'));
}, [navigate]);
//
const fetchCategories = async () => {
try {
const res = await fetch('/api/admin/schedule-categories');
const data = await res.json();
const data = await categoriesApi.getCategories();
setCategories(data);
} catch (error) {
console.error('카테고리 조회 오류:', error);
showToast('error', '카테고리를 불러오는데 실패했습니다.');
showError('카테고리를 불러오는데 실패했습니다.');
} finally {
setLoading(false);
}
};
//
const handleLogout = () => {
localStorage.removeItem('adminToken');
localStorage.removeItem('adminUser');
navigate('/admin');
};
// (/)
const openModal = (category = null) => {
if (category) {
@ -116,7 +103,7 @@ function AdminScheduleCategory() {
//
const handleSave = async () => {
if (!formData.name.trim()) {
showToast('error', '카테고리 이름을 입력해주세요.');
showError('카테고리 이름을 입력해주세요.');
return;
}
@ -126,37 +113,22 @@ function AdminScheduleCategory() {
&& cat.id !== editingCategory?.id
);
if (isDuplicate) {
showToast('error', '이미 존재하는 카테고리입니다.');
showError('이미 존재하는 카테고리입니다.');
return;
}
const token = localStorage.getItem('adminToken');
try {
const url = editingCategory
? `/api/admin/schedule-categories/${editingCategory.id}`
: '/api/admin/schedule-categories';
const res = await fetch(url, {
method: editingCategory ? 'PUT' : 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(formData)
});
if (res.ok) {
showToast('success', editingCategory ? '카테고리가 수정되었습니다.' : '카테고리가 추가되었습니다.');
setModalOpen(false);
fetchCategories();
if (editingCategory) {
await categoriesApi.updateCategory(editingCategory.id, formData);
} else {
const error = await res.json();
showToast('error', error.error || '저장에 실패했습니다.');
await categoriesApi.createCategory(formData);
}
showSuccess(editingCategory ? '카테고리가 수정되었습니다.' : '카테고리가 추가되었습니다.');
setModalOpen(false);
fetchCategories();
} catch (error) {
console.error('저장 오류:', error);
showToast('error', '저장 중 오류가 발생했습니다.');
showError(error.message || '저장에 실패했습니다.');
}
};
@ -170,26 +142,15 @@ function AdminScheduleCategory() {
const handleDelete = async () => {
if (!deleteTarget) return;
const token = localStorage.getItem('adminToken');
try {
const res = await fetch(`/api/admin/schedule-categories/${deleteTarget.id}`, {
method: 'DELETE',
headers: { 'Authorization': `Bearer ${token}` }
});
if (res.ok) {
showToast('success', '카테고리가 삭제되었습니다.');
setDeleteDialogOpen(false);
setDeleteTarget(null);
fetchCategories();
} else {
const error = await res.json();
showToast('error', error.error || '삭제에 실패했습니다.');
}
await categoriesApi.deleteCategory(deleteTarget.id);
showSuccess('카테고리가 삭제되었습니다.');
setDeleteDialogOpen(false);
setDeleteTarget(null);
fetchCategories();
} catch (error) {
console.error('삭제 오류:', error);
showToast('error', '삭제 중 오류가 발생했습니다.');
showError(error.message || '삭제에 실패했습니다.');
}
};
@ -203,16 +164,8 @@ function AdminScheduleCategory() {
sort_order: idx + 1
}));
const token = localStorage.getItem('adminToken');
try {
await fetch('/api/admin/schedule-categories-order', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({ orders })
});
await categoriesApi.reorderCategories(orders);
} catch (error) {
console.error('순서 업데이트 오류:', error);
fetchCategories(); //
@ -232,30 +185,7 @@ function AdminScheduleCategory() {
<Toast toast={toast} onClose={() => setToast(null)} />
{/* 헤더 */}
<header className="bg-white shadow-sm border-b border-gray-100">
<div className="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
<div className="flex items-center gap-4">
<Link to="/admin/dashboard" className="text-2xl font-bold text-primary hover:opacity-80 transition-opacity">
fromis_9
</Link>
<span className="px-3 py-1 bg-primary/10 text-primary text-sm font-medium rounded-full">
Admin
</span>
</div>
<div className="flex items-center gap-4">
<span className="text-gray-500 text-sm">
안녕하세요, <span className="text-gray-900 font-medium">{user?.username}</span>
</span>
<button
onClick={handleLogout}
className="flex items-center gap-2 px-4 py-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors"
>
<LogOut size={18} />
로그아웃
</button>
</div>
</div>
</header>
<AdminHeader user={user} />
{/* 메인 콘텐츠 */}
<main className="max-w-4xl mx-auto px-6 py-8">
@ -517,54 +447,19 @@ function AdminScheduleCategory() {
</AnimatePresence>
{/* 삭제 확인 다이얼로그 */}
<AnimatePresence>
{deleteDialogOpen && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
onClick={() => setDeleteDialogOpen(false)}
>
<motion.div
initial={{ scale: 0.9, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.9, opacity: 0 }}
className="bg-white rounded-2xl p-6 max-w-md w-full mx-4 shadow-xl"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center gap-3 mb-4">
<div className="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center">
<AlertTriangle className="text-red-500" size={20} />
</div>
<h3 className="text-lg font-bold text-gray-900">카테고리 삭제</h3>
</div>
<p className="text-gray-600 mb-6">
<span className="font-medium text-gray-900">"{deleteTarget?.name}"</span> 카테고리를 삭제하시겠습니까?
<br />
<span className="text-sm text-red-500"> 작업은 되돌릴 없습니다.</span>
</p>
<div className="flex justify-end gap-3">
<button
onClick={() => setDeleteDialogOpen(false)}
className="px-4 py-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors"
>
취소
</button>
<button
onClick={handleDelete}
className="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors flex items-center gap-2"
>
<Trash2 size={16} />
삭제
</button>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
<ConfirmDialog
isOpen={deleteDialogOpen}
onClose={() => setDeleteDialogOpen(false)}
onConfirm={handleDelete}
title="카테고리 삭제"
message={
<>
<span className="font-medium text-gray-900">"{deleteTarget?.name}"</span> 카테고리를 삭제하시겠습니까?
<br />
<span className="text-sm text-red-500"> 작업은 되돌릴 없습니다.</span>
</>
}
/>
</div>
);
}

File diff suppressed because it is too large Load diff

View file

@ -2,6 +2,8 @@ import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { motion } from 'framer-motion';
import { Calendar, Music } from 'lucide-react';
import { getAlbums } from '../../../api/public/albums';
import { formatDate } from '../../../utils/date';
function Album() {
const navigate = useNavigate();
@ -9,8 +11,7 @@ function Album() {
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('/api/albums')
.then(res => res.json())
getAlbums()
.then(data => {
setAlbums(data);
setLoading(false);
@ -21,13 +22,6 @@ function Album() {
});
}, []);
//
const formatDate = (dateStr) => {
if (!dateStr) return '';
const date = new Date(dateStr);
return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}.${String(date.getDate()).padStart(2, '0')}`;
};
//
const getTitleTrack = (tracks) => {
if (!tracks || tracks.length === 0) return '';
@ -149,7 +143,7 @@ function Album() {
</p>
<div className="flex items-center gap-2 text-sm text-gray-500">
<Calendar size={14} />
<span>{formatDate(album.release_date)}</span>
<span>{formatDate(album.release_date, 'YYYY.MM.DD')}</span>
</div>
</div>
</motion.div>

View file

@ -2,41 +2,10 @@ import { useState, useEffect, useCallback, memo } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { Calendar, Music2, Clock, X, ChevronLeft, ChevronRight, Download, MoreVertical, FileText } from 'lucide-react';
import { getAlbumByName } from '../../../api/public/albums';
import { formatDate } from '../../../utils/date';
import LightboxIndicator from '../../../components/common/LightboxIndicator';
// - CSS transition JS
const LightboxIndicator = memo(function LightboxIndicator({ count, currentIndex, setLightbox }) {
const translateX = -(currentIndex * 18) + 100 - 6;
return (
<div className="absolute bottom-6 left-1/2 -translate-x-1/2 overflow-hidden" style={{ width: '200px' }}>
{/* 양옆 페이드 그라데이션 */}
<div className="absolute inset-0 pointer-events-none z-10" style={{
background: 'linear-gradient(to right, rgba(0,0,0,1) 0%, transparent 20%, transparent 80%, rgba(0,0,0,1) 100%)'
}} />
{/* 슬라이딩 컨테이너 - CSS transition으로 GPU 가속 */}
<div
className="flex items-center gap-2 justify-center"
style={{
width: `${count * 18}px`,
transform: `translateX(${translateX}px)`,
transition: 'transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94)'
}}
>
{Array.from({ length: count }).map((_, i) => (
<button
key={i}
className={`rounded-full flex-shrink-0 transition-all duration-300 ${
i === currentIndex
? 'w-3 h-3 bg-white'
: 'w-2.5 h-2.5 bg-white/40 hover:bg-white/60'
}`}
onClick={() => setLightbox(prev => ({ ...prev, index: i }))}
/>
))}
</div>
</div>
);
});
function AlbumDetail() {
const { name } = useParams();
const navigate = useNavigate();
@ -157,8 +126,7 @@ function AlbumDetail() {
}, [lightbox.open, lightbox.index, lightbox.images, preloadedImages]);
useEffect(() => {
fetch(`/api/albums/by-name/${name}`)
.then(res => res.json())
getAlbumByName(name)
.then(data => {
setAlbum(data);
setLoading(false);
@ -171,13 +139,6 @@ function AlbumDetail() {
// URL - API
//
const formatDate = (dateStr) => {
if (!dateStr) return '';
const date = new Date(dateStr);
return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}.${String(date.getDate()).padStart(2, '0')}`;
};
//
const getTotalDuration = () => {
if (!album?.tracks) return '';
@ -317,7 +278,7 @@ function AlbumDetail() {
<div className="flex items-center gap-6 text-gray-500 mb-3">
<div className="flex items-center gap-2">
<Calendar size={18} />
<span>{formatDate(album.release_date)}</span>
<span>{formatDate(album.release_date, 'YYYY.MM.DD')}</span>
</div>
<div className="flex items-center gap-2">
<Music2 size={18} />
@ -568,12 +529,12 @@ function AlbumDetail() {
</button>
)}
{/* 인디케이터 - memo 컴포넌트로 분리 */}
{/* 인디케이터 - 공통 컴포넌트 사용 */}
{lightbox.images.length > 1 && (
<LightboxIndicator
count={lightbox.images.length}
currentIndex={lightbox.index}
setLightbox={setLightbox}
goToIndex={(i) => setLightbox(prev => ({ ...prev, index: i }))}
/>
)}
</div>

View file

@ -4,41 +4,8 @@ import { motion, AnimatePresence } from 'framer-motion';
import { X, ChevronLeft, ChevronRight, Download } from 'lucide-react';
import { RowsPhotoAlbum } from 'react-photo-album';
import 'react-photo-album/rows.css';
// - CSS transition JS
const LightboxIndicator = memo(function LightboxIndicator({ count, currentIndex, setLightbox }) {
const translateX = -(currentIndex * 18) + 100 - 6;
return (
<div className="absolute bottom-6 left-1/2 -translate-x-1/2 overflow-hidden" style={{ width: '200px' }}>
{/* 양옆 페이드 그라데이션 */}
<div className="absolute inset-0 pointer-events-none z-10" style={{
background: 'linear-gradient(to right, rgba(0,0,0,1) 0%, transparent 20%, transparent 80%, rgba(0,0,0,1) 100%)'
}} />
{/* 슬라이딩 컨테이너 - CSS transition으로 GPU 가속 */}
<div
className="flex items-center gap-2 justify-center"
style={{
width: `${count * 18}px`,
transform: `translateX(${translateX}px)`,
transition: 'transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94)'
}}
>
{Array.from({ length: count }).map((_, i) => (
<button
key={i}
className={`rounded-full flex-shrink-0 transition-all duration-300 ${
i === currentIndex
? 'w-3 h-3 bg-white'
: 'w-2.5 h-2.5 bg-white/40 hover:bg-white/60'
}`}
onClick={() => setLightbox(prev => ({ ...prev, index: i }))}
/>
))}
</div>
</div>
);
});
import { getAlbumByName } from '../../../api/public/albums';
import LightboxIndicator from '../../../components/common/LightboxIndicator';
// CSS + overflow +
const galleryStyles = `
@ -82,8 +49,7 @@ function AlbumGallery() {
const [preloadedImages] = useState(() => new Set()); // URL
useEffect(() => {
fetch(`/api/albums/by-name/${name}`)
.then(res => res.json())
getAlbumByName(name)
.then(data => {
setAlbum(data);
const allPhotos = [];
@ -392,11 +358,11 @@ function AlbumGallery() {
</button>
)}
{/* 하단 점 인디케이터 - memo 컴포넌트로 분리 */}
{/* 하단 점 인디케이터 - 공통 컴포넌트 사용 */}
<LightboxIndicator
count={photos.length}
currentIndex={lightbox.index}
setLightbox={setLightbox}
goToIndex={(i) => setLightbox(prev => ({ ...prev, index: i }))}
/>
</div>
</motion.div>

View file

@ -1,7 +1,10 @@
import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Link } from 'react-router-dom';
import { Calendar, Users, Disc3, ArrowRight, Clock } from 'lucide-react';
import { Calendar, ArrowRight, Clock, Link2, Tag } from 'lucide-react';
import { getTodayKST } from '../../../utils/date';
import { getMembers } from '../../../api/public/members';
import { getUpcomingSchedules } from '../../../api/public/schedules';
function Home() {
const [members, setMembers] = useState([]);
@ -9,21 +12,12 @@ function Home() {
useEffect(() => {
//
fetch('/api/members')
.then(res => res.json())
getMembers()
.then(data => setMembers(data))
.catch(error => console.error('멤버 데이터 로드 오류:', error));
// ( 3)
// KST
const now = new Date();
const kstOffset = 9 * 60; // KST UTC+9
const kstTime = new Date(now.getTime() + (kstOffset + now.getTimezoneOffset()) * 60000);
const todayStr = kstTime.toISOString().split('T')[0];
fetch(`/api/schedules?startDate=${todayStr}&limit=3`)
.then(res => res.json())
getUpcomingSchedules(3)
.then(data => setUpcomingSchedules(data))
.catch(error => console.error('일정 데이터 로드 오류:', error));
}, []);
@ -64,34 +58,46 @@ function Home() {
</div>
</section>
{/* 퀵 링크 섹션 */}
<section className="py-16 bg-white">
{/* 그룹 통계 섹션 */}
<section className="py-16 bg-gray-50">
<div className="max-w-7xl mx-auto px-6">
<div className="grid grid-cols-3 gap-8">
<Link
to="/members"
className="group p-8 bg-gray-50 rounded-2xl hover:bg-primary hover:text-white transition-all duration-300"
<div className="grid grid-cols-4 gap-6">
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1 }}
className="bg-gradient-to-br from-primary to-primary-dark rounded-2xl p-6 text-white text-center"
>
<Users size={40} className="mb-4 text-primary group-hover:text-white" />
<h3 className="text-xl font-bold mb-2">멤버</h3>
<p className="text-gray-500 group-hover:text-white/80">5명의 멤버를 만나보세요</p>
</Link>
<Link
to="/album"
className="group p-8 bg-gray-50 rounded-2xl hover:bg-primary hover:text-white transition-all duration-300"
<p className="text-3xl font-bold mb-1">2018.01.24</p>
<p className="text-white/70 text-sm">데뷔일</p>
</motion.div>
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2 }}
className="bg-gradient-to-br from-primary to-primary-dark rounded-2xl p-6 text-white text-center"
>
<Disc3 size={40} className="mb-4 text-primary group-hover:text-white" />
<h3 className="text-xl font-bold mb-2">앨범</h3>
<p className="text-gray-500 group-hover:text-white/80">앨범과 음악을 확인하세요</p>
</Link>
<Link
to="/schedule"
className="group p-8 bg-gray-50 rounded-2xl hover:bg-primary hover:text-white transition-all duration-300"
<p className="text-3xl font-bold mb-1">D+{(Math.floor((new Date() - new Date('2018-01-24')) / (1000 * 60 * 60 * 24)) + 1).toLocaleString()}</p>
<p className="text-white/70 text-sm">D+Day</p>
</motion.div>
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.3 }}
className="bg-gradient-to-br from-primary to-primary-dark rounded-2xl p-6 text-white text-center"
>
<Calendar size={40} className="mb-4 text-primary group-hover:text-white" />
<h3 className="text-xl font-bold mb-2">일정</h3>
<p className="text-gray-500 group-hover:text-white/80">다가오는 일정을 확인하세요</p>
</Link>
<p className="text-3xl font-bold mb-1">5</p>
<p className="text-white/70 text-sm">멤버 </p>
</motion.div>
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.4 }}
className="bg-gradient-to-br from-primary to-primary-dark rounded-2xl p-6 text-white text-center"
>
<p className="text-3xl font-bold mb-1">flover</p>
<p className="text-white/70 text-sm">팬덤명</p>
</motion.div>
</div>
</div>
</section>
@ -132,7 +138,7 @@ function Home() {
</section>
{/* 일정 미리보기 */}
<section className="py-16 bg-white">
<section className="py-16 bg-gray-50">
<div className="max-w-7xl mx-auto px-6">
<div className="flex justify-between items-center mb-8">
<h2 className="text-3xl font-bold">다가오는 일정</h2>
@ -157,9 +163,6 @@ function Home() {
const memberList = schedule.member_names ? schedule.member_names.split(',') : [];
const displayMembers = memberList.length >= 5 ? ['프로미스나인'] : memberList;
// ()
const categoryColor = schedule.category_color || '#6B8E6B';
return (
<motion.div
key={schedule.id}
@ -168,13 +171,12 @@ function Home() {
transition={{ delay: index * 0.05 }}
className="flex items-stretch bg-white rounded-2xl shadow-sm hover:shadow-md transition-shadow overflow-hidden"
>
{/* 날짜 영역 */}
{/* 날짜 영역 - primary 색상 고정 */}
<div className="w-20 flex flex-col items-center justify-center text-white py-5 bg-primary">
<span className="text-3xl font-bold">{day}</span>
<span className="text-sm font-medium opacity-80">{weekday}</span>
</div>
{/* 내용 영역 */}
<div className="flex-1 p-5 flex flex-col justify-center">
<h3 className="font-bold text-lg text-gray-900 mb-2">{schedule.title}</h3>
@ -182,20 +184,20 @@ function Home() {
<div className="flex flex-wrap items-center gap-3 text-sm text-gray-500">
{schedule.time && (
<div className="flex items-center gap-1">
<Clock size={14} className="text-primary" />
<Clock size={14} className="text-primary opacity-60" />
<span>{schedule.time.slice(0, 5)}</span>
</div>
)}
{schedule.category_name && (
<div className="flex items-center gap-1.5">
<span
className="w-2 h-2 rounded-full"
style={{ backgroundColor: categoryColor }}
/>
<span>
{schedule.category_name}
{schedule.source_name && ` · ${schedule.source_name}`}
</span>
<div className="flex items-center gap-1">
<Tag size={14} className="text-primary opacity-60" />
<span>{schedule.category_name}</span>
</div>
)}
{schedule.source_name && (
<div className="flex items-center gap-1">
<Link2 size={14} className="text-primary opacity-60" />
<span>{schedule.source_name}</span>
</div>
)}
</div>

View file

@ -1,20 +1,17 @@
import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Instagram, Calendar } from 'lucide-react';
import { getMembers } from '../../../api/public/members';
import { formatDate } from '../../../utils/date';
function Members() {
const [members, setMembers] = useState([]);
const [stats, setStats] = useState({ memberCount: 0, albumCount: 0, debutYear: 2018, fandomName: 'flover' });
const [loading, setLoading] = useState(true);
useEffect(() => {
Promise.all([
fetch('/api/members').then(res => res.json()),
fetch('/api/stats').then(res => res.json())
])
.then(([membersData, statsData]) => {
setMembers(membersData);
setStats(statsData);
getMembers()
.then(data => {
setMembers(data);
setLoading(false);
})
.catch(error => {
@ -23,13 +20,6 @@ function Members() {
});
}, []);
//
const formatDate = (dateStr) => {
if (!dateStr) return '';
const date = new Date(dateStr);
return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}.${String(date.getDate()).padStart(2, '0')}`;
};
if (loading) {
return (
<div className="py-16 flex justify-center items-center min-h-[60vh]">
@ -87,7 +77,7 @@ function Members() {
<div className="flex items-center gap-2 text-sm text-gray-500 mb-4">
<Calendar size={14} />
<span>{formatDate(member.birth_date)}</span>
<span>{formatDate(member.birth_date, 'YYYY.MM.DD')}</span>
</div>
{/* 인스타그램 링크 */}
@ -111,66 +101,55 @@ function Members() {
))}
</div>
{/* 탈퇴 멤버 섹션 - 콤팩트한 가로 리스트 */}
{/* 전 멤버 섹션 - 현재 멤버와 동일한 카드 UI */}
{members.filter(m => m.is_former).length > 0 && (
<motion.div
initial={{ opacity: 0, y: 30 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.5 }}
className="mt-12"
className="mt-16"
>
<h2 className="text-lg font-bold mb-4 text-gray-400"> 멤버</h2>
<div className="flex gap-4">
<h2 className="text-2xl font-bold mb-8 text-gray-400"> 멤버</h2>
<div className="grid grid-cols-5 gap-8">
{members.filter(m => m.is_former).map((member, index) => (
<motion.div
key={member.id}
initial={{ opacity: 0, x: -10 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: 0.6 + index * 0.05 }}
className="group flex items-center gap-3 bg-gray-100 rounded-full pr-4 hover:bg-gray-200 transition-colors"
initial={{ opacity: 0, y: 30 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.6 + index * 0.1 }}
className="group h-full"
>
{/* 작은 원형 이미지 */}
<div className="w-12 h-12 rounded-full bg-gray-200 overflow-hidden flex-shrink-0">
<img
src={member.image_url || '/placeholder-member.jpg'}
alt={member.name}
className="w-full h-full object-cover grayscale group-hover:grayscale-0 transition-all duration-300"
/>
<div className="relative bg-white rounded-3xl overflow-hidden shadow-lg hover:shadow-2xl transition-all duration-300 h-full flex flex-col">
{/* 이미지 - grayscale */}
<div className="aspect-[3/4] bg-gray-100 overflow-hidden flex-shrink-0">
<img
src={member.image_url}
alt={member.name}
className="w-full h-full object-cover grayscale group-hover:grayscale-0 transition-all duration-500"
/>
</div>
{/* 정보 */}
<div className="p-6 flex-1 flex flex-col">
<h3 className="text-xl font-bold mb-1 text-gray-500">{member.name}</h3>
<p className="text-gray-400 text-sm font-medium mb-3 min-h-[20px]">{member.position || '\u00A0'}</p>
<div className="flex items-center gap-2 text-sm text-gray-400">
<Calendar size={14} />
<span>{formatDate(member.birth_date, 'YYYY.MM.DD')}</span>
</div>
</div>
{/* 호버 효과 - 컬러 바 */}
<div className="absolute bottom-0 left-0 right-0 h-1 bg-gray-400 transform scale-x-0 group-hover:scale-x-100 transition-transform duration-300" />
</div>
{/* 이름 */}
<p className="font-medium text-gray-600 text-sm">{member.name}</p>
</motion.div>
))}
</div>
</motion.div>
)}
{/* 그룹 정보 */}
<motion.div
initial={{ opacity: 0, y: 30 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.6 }}
className="mt-16 bg-gradient-to-r from-primary to-primary-dark rounded-3xl p-10 text-white"
>
<div className="grid grid-cols-4 gap-8 text-center">
<div>
<p className="text-4xl font-bold mb-2">2018.01.24</p>
<p className="text-white/70">데뷔일</p>
</div>
<div>
<p className="text-4xl font-bold mb-2">D+{(Math.floor((new Date() - new Date('2018-01-24')) / (1000 * 60 * 60 * 24)) + 1).toLocaleString()}</p>
<p className="text-white/70">D+Day</p>
</div>
<div>
<p className="text-4xl font-bold mb-2">{members.filter(m => !m.is_former).length}</p>
<p className="text-white/70">멤버 </p>
</div>
<div>
<p className="text-4xl font-bold mb-2">{stats.fandomName}</p>
<p className="text-white/70">팬덤명</p>
</div>
</div>
</motion.div>
</div>
</div>
);

View file

@ -1,19 +1,24 @@
import { useState, useEffect, useRef, useMemo } from 'react';
import { useState, useEffect, useRef, useMemo, useDeferredValue, memo } from 'react';
import { useNavigate } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { Clock, ChevronLeft, ChevronRight, ChevronDown, Tag, Search, ArrowLeft } from 'lucide-react';
import { Clock, ChevronLeft, ChevronRight, ChevronDown, Tag, Search, ArrowLeft, Link2 } from 'lucide-react';
import { useInfiniteQuery } from '@tanstack/react-query';
import { useVirtualizer } from '@tanstack/react-virtual';
import { useInView } from 'react-intersection-observer';
import { getTodayKST } from '../../../utils/date';
import { getSchedules, getCategories, searchSchedules as searchSchedulesApi } from '../../../api/public/schedules';
// HTML
const decodeHtmlEntities = (text) => {
if (!text) return '';
const textarea = document.createElement('textarea');
textarea.innerHTML = text;
return textarea.value;
};
function Schedule() {
const navigate = useNavigate();
// KST (YYYY-MM-DD)
const getTodayKST = () => {
const now = new Date();
const kstOffset = 9 * 60 * 60 * 1000; // 9
const kstDate = new Date(now.getTime() + kstOffset);
return kstDate.toISOString().split('T')[0];
};
const [currentDate, setCurrentDate] = useState(new Date());
const [selectedDate, setSelectedDate] = useState(getTodayKST()); // KST
const [showYearMonthPicker, setShowYearMonthPicker] = useState(false);
@ -31,27 +36,82 @@ function Schedule() {
//
const [showCategoryTooltip, setShowCategoryTooltip] = useState(false);
const categoryRef = useRef(null);
const scrollContainerRef = useRef(null); //
//
const [isSearchMode, setIsSearchMode] = useState(false);
const [searchInput, setSearchInput] = useState('');
const [searchTerm, setSearchTerm] = useState('');
const [searchResults, setSearchResults] = useState([]);
const [searchLoading, setSearchLoading] = useState(false);
const SEARCH_LIMIT = 20; // 20
const ESTIMATED_ITEM_HEIGHT = 120; // ( )
// Intersection Observer for infinite scroll
const { ref: loadMoreRef, inView } = useInView({
threshold: 0,
rootMargin: '100px',
});
// useInfiniteQuery for search
const {
data: searchData,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
isLoading: searchLoading,
refetch: refetchSearch,
} = useInfiniteQuery({
queryKey: ['scheduleSearch', searchTerm],
queryFn: async ({ pageParam = 0 }) => {
const response = await fetch(
`/api/schedules?search=${encodeURIComponent(searchTerm)}&offset=${pageParam}&limit=${SEARCH_LIMIT}`
);
if (!response.ok) throw new Error('Search failed');
return response.json();
},
getNextPageParam: (lastPage) => {
if (lastPage.hasMore) {
return lastPage.offset + lastPage.schedules.length;
}
return undefined;
},
enabled: !!searchTerm && isSearchMode,
});
// Flatten search results
const searchResults = useMemo(() => {
if (!searchData?.pages) return [];
return searchData.pages.flatMap(page => page.schedules);
}, [searchData]);
const searchTotal = searchData?.pages?.[0]?.total || 0;
// Auto fetch next page when scrolled to bottom
useEffect(() => {
if (inView && hasNextPage && !isFetchingNextPage && isSearchMode && searchTerm) {
fetchNextPage();
}
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage, isSearchMode, searchTerm]);
//
// ()
useEffect(() => {
fetchSchedules();
fetchCategories();
loadCategories();
}, []);
//
useEffect(() => {
const year = currentDate.getFullYear();
const month = currentDate.getMonth();
loadSchedules(year, month + 1);
}, [currentDate]);
const fetchSchedules = async () => {
const loadSchedules = async (year, month) => {
setLoading(true);
try {
const response = await fetch('/api/schedules');
if (response.ok) {
const data = await response.json();
setSchedules(data);
}
const data = await getSchedules(year, month);
setSchedules(data);
} catch (error) {
console.error('일정 로드 오류:', error);
} finally {
@ -59,37 +119,14 @@ function Schedule() {
}
};
const fetchCategories = async () => {
const loadCategories = async () => {
try {
const response = await fetch('/api/schedule-categories');
if (response.ok) {
const data = await response.json();
setCategories(data);
}
const data = await getCategories();
setCategories(data);
} catch (error) {
console.error('카테고리 로드 오류:', error);
}
};
// (Meilisearch API )
const searchSchedules = async (term) => {
if (!term.trim()) {
setSearchResults([]);
return;
}
setSearchLoading(true);
try {
const response = await fetch(`/api/schedules?search=${encodeURIComponent(term)}`);
if (response.ok) {
const data = await response.json();
setSearchResults(data);
}
} catch (error) {
console.error('검색 오류:', error);
} finally {
setSearchLoading(false);
}
};
//
useEffect(() => {
@ -107,6 +144,13 @@ function Schedule() {
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
//
useEffect(() => {
if (scrollContainerRef.current) {
scrollContainerRef.current.scrollTop = 0;
}
}, [selectedDate]);
//
const getDaysInMonth = (year, month) => new Date(year, month + 1, 0).getDate();
const getFirstDayOfMonth = (year, month) => new Date(year, month, 1).getDay();
@ -118,38 +162,68 @@ function Schedule() {
const days = ['일', '월', '화', '수', '목', '금', '토'];
// (ISO YYYY-MM-DD )
const scheduleDates = schedules.map(s => s.date ? s.date.split('T')[0] : '');
// UI
const deferredSchedules = useDeferredValue(schedules);
//
// (O(1) ) -
const scheduleDateMap = useMemo(() => {
const map = new Map();
deferredSchedules.forEach(s => {
const dateStr = s.date ? s.date.split('T')[0] : '';
if (!map.has(dateStr)) {
map.set(dateStr, s);
}
});
return map;
}, [deferredSchedules]);
// (O(1))
const getScheduleColor = (day) => {
const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
const schedule = schedules.find(s => (s.date ? s.date.split('T')[0] : '') === dateStr);
const schedule = scheduleDateMap.get(dateStr);
if (!schedule) return null;
const cat = categories.find(c => c.id === schedule.category_id);
return cat?.color || '#4A7C59';
};
// (O(1))
const hasSchedule = (day) => {
const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
return scheduleDates.includes(dateStr);
return scheduleDateMap.has(dateStr);
};
const prevMonth = () => {
setSlideDirection(-1);
setCurrentDate(new Date(year, month - 1, 1));
setSelectedDate(null); //
const newDate = new Date(year, month - 1, 1);
setCurrentDate(newDate);
// , 1
const today = new Date();
if (newDate.getFullYear() === today.getFullYear() && newDate.getMonth() === today.getMonth()) {
setSelectedDate(getTodayKST());
} else {
const firstDay = `${newDate.getFullYear()}-${String(newDate.getMonth() + 1).padStart(2, '0')}-01`;
setSelectedDate(firstDay);
}
};
const nextMonth = () => {
setSlideDirection(1);
setCurrentDate(new Date(year, month + 1, 1));
setSelectedDate(null); //
const newDate = new Date(year, month + 1, 1);
setCurrentDate(newDate);
// , 1
const today = new Date();
if (newDate.getFullYear() === today.getFullYear() && newDate.getMonth() === today.getMonth()) {
setSelectedDate(getTodayKST());
} else {
const firstDay = `${newDate.getFullYear()}-${String(newDate.getMonth() + 1).padStart(2, '0')}-01`;
setSelectedDate(firstDay);
}
};
// ( )
const selectDate = (day) => {
const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
setSelectedDate(selectedDate === dateStr ? null : dateStr);
setSelectedDate(dateStr);
};
const selectYear = (newYear) => {
@ -158,7 +232,16 @@ function Schedule() {
};
const selectMonth = (newMonth) => {
setCurrentDate(new Date(year, newMonth, 1));
const newDate = new Date(year, newMonth, 1);
setCurrentDate(newDate);
// , 1
const today = new Date();
if (newDate.getFullYear() === today.getFullYear() && newDate.getMonth() === today.getMonth()) {
setSelectedDate(getTodayKST());
} else {
const firstDay = `${year}-${String(newMonth + 1).padStart(2, '0')}-01`;
setSelectedDate(firstDay);
}
setShowYearMonthPicker(false);
setViewMode('yearMonth');
};
@ -180,7 +263,9 @@ function Schedule() {
if (isSearchMode) {
// , API (Meilisearch )
if (!searchTerm) return [];
return searchResults;
//
if (selectedCategories.length === 0) return searchResults;
return searchResults.filter(s => selectedCategories.includes(s.category_id));
}
@ -204,6 +289,36 @@ function Schedule() {
});
}, [schedules, selectedDate, currentYearMonth, selectedCategories, isSearchMode, searchTerm, searchResults]);
// ( , )
const virtualizer = useVirtualizer({
count: isSearchMode && searchTerm ? filteredSchedules.length : 0,
getScrollElement: () => scrollContainerRef.current,
estimateSize: () => ESTIMATED_ITEM_HEIGHT,
overscan: 5, //
});
// (useMemo ) -
const categoryCounts = useMemo(() => {
const source = (isSearchMode && searchTerm) ? searchResults : schedules;
const counts = new Map();
let total = 0;
source.forEach(s => {
const scheduleDate = s.date ? s.date.split('T')[0] : '';
//
if (!isSearchMode && selectedDate) {
if (scheduleDate !== selectedDate) return;
}
const catId = s.category_id;
counts.set(catId, (counts.get(catId) || 0) + 1);
total++;
});
counts.set('total', total);
return counts;
}, [schedules, searchResults, isSearchMode, searchTerm, selectedDate]);
const formatDate = (dateStr) => {
const date = new Date(dateStr);
const dayNames = ['일', '월', '화', '수', '목', '금', '토'];
@ -220,25 +335,24 @@ function Schedule() {
if (!schedule.description && schedule.source_url) {
window.open(schedule.source_url, '_blank');
} else {
// ( )
//
navigate(`/schedule/${schedule.id}`);
}
};
//
const startYear = Math.floor(year / 10) * 10 - 1;
const yearRange = Array.from({ length: 12 }, (_, i) => startYear + i);
const isCurrentYear = (y) => new Date().getFullYear() === y;
const currentYear = new Date().getFullYear();
const isCurrentYear = (y) => y === currentYear;
const isCurrentMonth = (m) => {
const today = new Date();
return today.getFullYear() === year && today.getMonth() === m;
const now = new Date();
return year === now.getFullYear() && m === now.getMonth();
};
//
const [yearRangeStart, setYearRangeStart] = useState(currentYear - 1);
const yearRange = Array.from({ length: 12 }, (_, i) => yearRangeStart + i);
const monthNames = ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'];
const prevYearRange = () => setCurrentDate(new Date(year - 10, month, 1));
const nextYearRange = () => setCurrentDate(new Date(year + 10, month, 1));
const prevYearRange = () => setYearRangeStart(prev => prev - 3);
const nextYearRange = () => setYearRangeStart(prev => prev + 3);
//
const getSelectedCategoryNames = () => {
@ -262,6 +376,21 @@ function Schedule() {
return cat?.name || '';
};
// ( )
const sortedCategories = useMemo(() => {
return categories
.map(category => ({
...category,
count: categoryCounts.get(category.id) || 0
}))
.filter(category => category.count > 0)
.sort((a, b) => {
if (a.name === '기타') return 1;
if (b.name === '기타') return -1;
return b.count - a.count;
});
}, [categories, categoryCounts]);
return (
<div className="py-16">
<div className="max-w-7xl mx-auto px-6">
@ -350,7 +479,7 @@ function Schedule() {
onClick={() => selectYear(y)}
className={`py-2 text-sm rounded-lg transition-colors ${
year === y ? 'bg-primary text-white' :
isCurrentYear(y) && year !== y ? 'border border-primary text-primary hover:bg-primary/10' :
isCurrentYear(y) && year !== y ? 'text-primary font-medium hover:bg-primary/10' :
'hover:bg-gray-100 text-gray-700'
}`}
>
@ -366,7 +495,7 @@ function Schedule() {
onClick={() => selectMonth(i)}
className={`py-2 text-sm rounded-lg transition-colors ${
month === i ? 'bg-primary text-white' :
isCurrentMonth(i) && month !== i ? 'border border-primary text-primary hover:bg-primary/10' :
isCurrentMonth(i) && month !== i ? 'text-primary font-medium hover:bg-primary/10' :
'hover:bg-gray-100 text-gray-700'
}`}
>
@ -386,7 +515,7 @@ function Schedule() {
onClick={() => selectMonth(i)}
className={`py-2.5 text-sm rounded-lg transition-colors ${
month === i ? 'bg-primary text-white' :
isCurrentMonth(i) && month !== i ? 'border border-primary text-primary hover:bg-primary/10' :
isCurrentMonth(i) && month !== i ? 'text-primary font-medium hover:bg-primary/10' :
'hover:bg-gray-100 text-gray-700'
}`}
>
@ -445,6 +574,13 @@ function Schedule() {
const eventColor = getScheduleColor(day);
const dayOfWeek = (firstDay + i) % 7;
const isToday = new Date().toDateString() === new Date(year, month, day).toDateString();
// ( , 3)
const daySchedules = schedules.filter(s => {
const scheduleDate = s.date ? s.date.split('T')[0] : '';
const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
return scheduleDate === dateStr;
}).slice(0, 3);
return (
<button
@ -452,17 +588,24 @@ function Schedule() {
onClick={() => selectDate(day)}
className={`aspect-square flex flex-col items-center justify-center rounded-full text-base font-medium transition-all relative hover:bg-gray-100
${isSelected ? 'bg-primary text-white shadow-lg hover:bg-primary' : ''}
${isToday && !isSelected ? 'bg-primary/10 text-primary font-bold hover:bg-primary/20' : ''}
${isToday && !isSelected ? 'text-primary font-bold' : ''}
${dayOfWeek === 0 && !isSelected && !isToday ? 'text-red-500' : ''}
${dayOfWeek === 6 && !isSelected && !isToday ? 'text-blue-500' : ''}
`}
>
<span>{day}</span>
{/* 점: absolute로 위치 고정하여 글씨 위치에 영향 없음 */}
<span
className={`absolute bottom-1 w-1.5 h-1.5 rounded-full ${hasEvent ? '' : 'opacity-0'}`}
style={{ backgroundColor: isSelected ? 'white' : (eventColor || 'transparent') }}
/>
{/* 점: 선택되지 않은 날짜에만 표시, 최대 3개 */}
{!isSelected && daySchedules.length > 0 && (
<span className="absolute bottom-1 flex gap-0.5">
{daySchedules.map((schedule, idx) => (
<span
key={idx}
className="w-1 h-1 rounded-full"
style={{ backgroundColor: getCategoryColor(schedule.category_id) }}
/>
))}
</span>
)}
</button>
);
})}
@ -482,23 +625,12 @@ function Schedule() {
</motion.div>
</AnimatePresence>
{/* 범례 및 전체보기 */}
<div className="mt-6 pt-4 border-t border-gray-100 flex items-center justify-between text-sm">
{/* 범례 */}
<div className="mt-6 pt-4 border-t border-gray-100 flex items-center text-sm">
<div className="flex items-center gap-1.5 text-gray-500">
<span className="w-2 h-2 rounded-full bg-primary flex-shrink-0" />
<span className="leading-none">일정 있음</span>
</div>
<button
onClick={() => setSelectedDate(null)}
className={`px-4 py-2 rounded-lg transition-colors ${
selectedDate
? 'bg-primary text-white hover:bg-primary-dark'
: 'bg-gray-100 text-gray-400 cursor-default'
}`}
disabled={!selectedDate}
>
전체 보기
</button>
</div>
</div>
</motion.div>
@ -523,25 +655,12 @@ function Schedule() {
<span>전체</span>
</div>
<span className="text-sm text-gray-400">
{isSearchMode && searchTerm
? searchResults.length
: schedules.filter(s => {
const scheduleDate = s.date ? s.date.split('T')[0] : '';
return scheduleDate.startsWith(currentYearMonth);
}).length
}
{categoryCounts.get('total') || 0}
</span>
</button>
{/* 개별 카테고리 */}
{categories.map(category => {
// ,
const count = isSearchMode && searchTerm
? searchResults.filter(s => s.category_id === category.id).length
: schedules.filter(s => {
const scheduleDate = s.date ? s.date.split('T')[0] : '';
return scheduleDate.startsWith(currentYearMonth) && s.category_id === category.id;
}).length;
{/* 개별 카테고리 - useMemo로 정렬됨 */}
{sortedCategories.map(category => {
const isSelected = selectedCategories.includes(category.id);
return (
<button
@ -558,7 +677,7 @@ function Schedule() {
/>
<span>{category.name}</span>
</div>
<span className="text-sm text-gray-400">{count}</span>
<span className="text-sm text-gray-400">{category.count}</span>
</button>
);
})}
@ -602,7 +721,6 @@ function Schedule() {
onKeyDown={(e) => {
if (e.key === 'Enter') {
setSearchTerm(searchInput);
searchSchedules(searchInput);
} else if (e.key === 'Escape') {
setIsSearchMode(false);
setSearchInput('');
@ -616,7 +734,6 @@ function Schedule() {
<button
onClick={() => {
setSearchTerm(searchInput);
searchSchedules(searchInput);
}}
disabled={searchLoading}
className="px-4 py-1.5 bg-primary text-white text-sm font-medium rounded-lg hover:bg-primary/90 transition-colors disabled:opacity-50"
@ -704,110 +821,207 @@ function Schedule() {
</div>
<motion.div
key={isSearchMode ? 'search' : 'normal'}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.15 }}
<div
ref={scrollContainerRef}
id="scheduleScrollContainer"
className="max-h-[calc(100vh-200px)] overflow-y-auto space-y-4 py-2 pr-2"
>
{loading ? (
<div className="text-center py-20 text-gray-500">로딩 ...</div>
) : filteredSchedules.length > 0 ? (
filteredSchedules.map((schedule, index) => {
const formatted = formatDate(schedule.date);
const categoryColor = getCategoryColor(schedule.category_id);
const categoryName = getCategoryName(schedule.category_id);
return (
<motion.div
key={`${schedule.id}-${selectedDate || 'all'}`}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: Math.min(index, 10) * 0.03 }}
onClick={() => handleScheduleClick(schedule)}
className="flex items-stretch bg-white rounded-2xl shadow-sm hover:shadow-md transition-shadow overflow-hidden cursor-pointer"
isSearchMode && searchTerm ? (
/* 검색 모드: 가상 스크롤 */
<>
<div
style={{
height: `${virtualizer.getTotalSize()}px`,
width: '100%',
position: 'relative',
}}
>
{/* 날짜 영역 */}
<div
className="w-24 flex flex-col items-center justify-center text-white py-6"
style={{ backgroundColor: categoryColor }}
>
{/* 검색 모드일 때 년.월 표시, 일반 모드에서는 월 표시 안함 */}
{isSearchMode && searchTerm && (
<span className="text-xs font-medium opacity-60">
{new Date(schedule.date).getFullYear()}.{new Date(schedule.date).getMonth() + 1}
</span>
)}
<span className="text-3xl font-bold">{formatted.day}</span>
<span className="text-sm font-medium opacity-80">{formatted.weekday}</span>
</div>
{/* 스케줄 내용 */}
<div className="flex-1 p-6 flex flex-col justify-center">
<h3 className="font-bold text-lg mb-2">{schedule.title}</h3>
{virtualizer.getVirtualItems().map((virtualItem) => {
const schedule = filteredSchedules[virtualItem.index];
if (!schedule) return null;
<div className="flex flex-wrap gap-3 text-base text-gray-500">
{schedule.time && (
<div className="flex items-center gap-1">
<Clock size={16} style={{ color: categoryColor }} />
<span>{schedule.time.slice(0, 5)}</span>
</div>
)}
{categoryName && (
<div className="flex items-center gap-1">
<span
className="w-2 h-2 rounded-full flex-shrink-0"
const formatted = formatDate(schedule.date);
const categoryColor = getCategoryColor(schedule.category_id);
const categoryName = getCategoryName(schedule.category_id);
return (
<div
key={virtualItem.key}
ref={virtualizer.measureElement}
data-index={virtualItem.index}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
transform: `translateY(${virtualItem.start}px)`,
}}
>
<div className={virtualItem.index < filteredSchedules.length - 1 ? "pb-4" : ""}>
<div
onClick={() => handleScheduleClick(schedule)}
className="flex items-stretch bg-white rounded-2xl shadow-sm hover:shadow-md transition-shadow overflow-hidden cursor-pointer min-h-[100px]"
>
{/* 날짜 영역 */}
<div
className="w-24 flex flex-col items-center justify-center text-white"
style={{ backgroundColor: categoryColor }}
/>
<span>
{categoryName}
{schedule.source_name && ` · ${schedule.source_name}`}
</span>
>
<span className="text-xs font-medium opacity-60">
{new Date(schedule.date).getFullYear()}.{new Date(schedule.date).getMonth() + 1}
</span>
<span className="text-3xl font-bold">{formatted.day}</span>
<span className="text-sm font-medium opacity-80">{formatted.weekday}</span>
</div>
{/* 스케줄 내용 */}
<div className="flex-1 p-4 flex flex-col justify-center">
<h3 className="font-bold text-lg mb-1">{decodeHtmlEntities(schedule.title)}</h3>
<div className="flex flex-wrap gap-3 text-base text-gray-500">
{schedule.time && (
<span className="flex items-center gap-1">
<Clock size={16} className="opacity-60" />
{schedule.time.slice(0, 5)}
</span>
)}
<span className="flex items-center gap-1">
<Tag size={16} className="opacity-60" />
{categoryName}
</span>
{schedule.source_name && (
<span className="flex items-center gap-1">
<Link2 size={16} className="opacity-60" />
{schedule.source_name}
</span>
)}
</div>
{(() => {
const memberNames = schedule.member_names || schedule.members?.map(m => m.name).join(',') || '';
const memberList = memberNames.split(',').filter(name => name.trim());
if (memberList.length === 0) return null;
if (memberList.length === 5) {
return (
<div className="flex flex-wrap gap-1.5 mt-1">
<span className="px-2 py-0.5 bg-primary/10 text-primary text-sm font-medium rounded-full">
프로미스나인
</span>
</div>
);
}
return (
<div className="flex flex-wrap gap-1.5 mt-1">
{memberList.map((name, i) => (
<span key={i} className="px-2 py-0.5 bg-primary/10 text-primary text-sm font-medium rounded-full">
{name}
</span>
))}
</div>
);
})()}
</div>
</div>
</div>
)}
</div>
);
})}
</div>
{/* 무한 스크롤 트리거 & 로딩 인디케이터 */}
<div ref={loadMoreRef} className="py-4">
{isFetchingNextPage && (
<div className="flex justify-center">
<div className="w-6 h-6 border-2 border-primary border-t-transparent rounded-full animate-spin" />
</div>
{/* 멤버 태그 (별도 줄) */}
{(() => {
const memberList = schedule.members
? schedule.members.map(m => m.name)
: (schedule.member_names ? schedule.member_names.split(',') : []);
if (memberList.length === 0) return null;
// 5 ''
if (memberList.length >= 5) {
)}
{!hasNextPage && filteredSchedules.length > 0 && (
<div className="text-center text-sm text-gray-400">
{filteredSchedules.length} 표시 (모두 로드됨)
</div>
)}
</div>
</>
) : (
/* 일반 모드: 기존 렌더링 */
filteredSchedules.map((schedule, index) => {
const formatted = formatDate(schedule.date);
const categoryColor = getCategoryColor(schedule.category_id);
const categoryName = getCategoryName(schedule.category_id);
return (
<motion.div
key={`${schedule.id}-${selectedDate || 'all'}`}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: Math.min(index, 10) * 0.03 }}
onClick={() => handleScheduleClick(schedule)}
className="flex items-stretch bg-white rounded-2xl shadow-sm hover:shadow-md transition-shadow overflow-hidden cursor-pointer"
>
<div
className="w-24 flex flex-col items-center justify-center text-white py-6"
style={{ backgroundColor: categoryColor }}
>
<span className="text-3xl font-bold">{formatted.day}</span>
<span className="text-sm font-medium opacity-80">{formatted.weekday}</span>
</div>
<div className="flex-1 p-6 flex flex-col justify-center">
<h3 className="font-bold text-lg mb-2">{decodeHtmlEntities(schedule.title)}</h3>
<div className="flex flex-wrap gap-3 text-base text-gray-500">
{schedule.time && (
<span className="flex items-center gap-1">
<Clock size={16} className="opacity-60" />
{schedule.time.slice(0, 5)}
</span>
)}
<span className="flex items-center gap-1">
<Tag size={16} className="opacity-60" />
{categoryName}
</span>
{schedule.source_name && (
<span className="flex items-center gap-1">
<Link2 size={16} className="opacity-60" />
{schedule.source_name}
</span>
)}
</div>
{(() => {
const memberNames = schedule.member_names || schedule.members?.map(m => m.name).join(',') || '';
const memberList = memberNames.split(',').filter(name => name.trim());
if (memberList.length === 0) return null;
if (memberList.length === 5) {
return (
<div className="flex flex-wrap gap-1.5 mt-2">
<span className="px-2 py-0.5 bg-primary/10 text-primary text-sm font-medium rounded-full">
프로미스나인
</span>
</div>
);
}
return (
<div className="flex flex-wrap gap-1.5 mt-2">
<span className="px-2 py-0.5 bg-primary/10 text-primary text-sm font-medium rounded-full">
프로미스나인
</span>
{memberList.map((name, i) => (
<span key={i} className="px-2 py-0.5 bg-primary/10 text-primary text-sm font-medium rounded-full">
{name}
</span>
))}
</div>
);
}
//
return (
<div className="flex flex-wrap gap-1.5 mt-2">
{memberList.map((name, i) => (
<span key={i} className="px-2 py-0.5 bg-primary/10 text-primary text-sm font-medium rounded-full">
{name}
</span>
))}
</div>
);
})()}
</div>
</motion.div>
);
})
})()}
</div>
</motion.div>
);
})
)
) : (
<div className="text-center py-20 text-gray-500">
{selectedDate ? '선택한 날짜에 일정이 없습니다.' : '예정된 일정이 없습니다.'}
</div>
)}
</motion.div>
</div>
</div>
</div>

11
frontend/src/pc.css Normal file
View file

@ -0,0 +1,11 @@
/* PC 전용 스타일 - body.is-pc 클래스가 있을 때만 적용 */
/* PC 항상 스크롤바 공간 확보 - 화면 밀림 방지 */
body.is-pc {
overflow-y: scroll;
}
/* PC 최소 너비 설정 */
body.is-pc #root {
min-width: 1440px;
}

View file

@ -10,9 +10,12 @@ const useScheduleStore = create((set) => ({
// 필터 및 선택
selectedCategories: [],
selectedDate: null, // null이면 getTodayKST() 사용
selectedDate: null, // null이면 전체보기, undefined이면 getTodayKST() 사용
currentDate: new Date(),
// 스크롤 위치
scrollPosition: 0,
// 상태 업데이트 함수
setSearchInput: (value) => set({ searchInput: value }),
setSearchTerm: (value) => set({ searchTerm: value }),
@ -20,6 +23,7 @@ const useScheduleStore = create((set) => ({
setSelectedCategories: (value) => set({ selectedCategories: value }),
setSelectedDate: (value) => set({ selectedDate: value }),
setCurrentDate: (value) => set({ currentDate: value }),
setScrollPosition: (value) => set({ scrollPosition: value }),
// 상태 초기화
reset: () =>
@ -30,6 +34,7 @@ const useScheduleStore = create((set) => ({
selectedCategories: [],
selectedDate: null,
currentDate: new Date(),
scrollPosition: 0,
}),
}));

View file

@ -0,0 +1,81 @@
/**
* 날짜 관련 유틸리티 함수
* dayjs를 사용하여 KST(한국 표준시) 기준으로 날짜 처리
*/
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
// 플러그인 확장
dayjs.extend(utc);
dayjs.extend(timezone);
// 기본 타임존 설정
const KST = "Asia/Seoul";
/**
* KST 기준 오늘 날짜 (YYYY-MM-DD)
* @returns {string} 오늘 날짜 문자열
*/
export const getTodayKST = () => {
return dayjs().tz(KST).format("YYYY-MM-DD");
};
/**
* KST 기준 현재 시각
* @returns {dayjs.Dayjs} dayjs 객체
*/
export const nowKST = () => {
return dayjs().tz(KST);
};
/**
* 날짜 문자열 포맷팅
* @param {string|Date} date - 날짜
* @param {string} format - 포맷 (기본: 'YYYY-MM-DD')
* @returns {string} 포맷된 날짜 문자열
*/
export const formatDate = (date, format = "YYYY-MM-DD") => {
return dayjs(date).tz(KST).format(format);
};
/**
* 날짜에서 , , , 요일 추출
* @param {string|Date} date - 날짜
* @returns {object} { year, month, day, weekday }
*/
export const parseDateKST = (date) => {
const d = dayjs(date).tz(KST);
const weekdays = ["일", "월", "화", "수", "목", "금", "토"];
return {
year: d.year(),
month: d.month() + 1,
day: d.date(),
weekday: weekdays[d.day()],
};
};
/**
* 날짜 비교 (같은 날인지)
* @param {string|Date} date1
* @param {string|Date} date2
* @returns {boolean}
*/
export const isSameDay = (date1, date2) => {
return (
dayjs(date1).tz(KST).format("YYYY-MM-DD") ===
dayjs(date2).tz(KST).format("YYYY-MM-DD")
);
};
/**
* 날짜가 오늘인지 확인
* @param {string|Date} date
* @returns {boolean}
*/
export const isToday = (date) => {
return isSameDay(date, dayjs());
};
// dayjs 인스턴스도 export (고급 사용용)
export { dayjs };