Compare commits
No commits in common. "a3960489d4f27af698facd501a295419bb792fb2" and "dac2234a0b58846a1085471999bcbfdb7d35fcab" have entirely different histories.
a3960489d4
...
dac2234a0b
63 changed files with 3754 additions and 7470 deletions
2
.env
2
.env
|
|
@ -18,7 +18,7 @@ RUSTFS_SECRET_KEY=tDTwLkcHN5UVuWnea2s8OECrmiv013qoSQIpYbBd
|
|||
RUSTFS_BUCKET=fromis-9
|
||||
|
||||
# Kakao API
|
||||
KAKAO_REST_KEY=e7a5516bf6cb1b398857789ee2ea6eea
|
||||
KAKAO_REST_KEY=cf21156ae6cc8f6e95b3a3150926cdf8
|
||||
|
||||
# YouTube API
|
||||
YOUTUBE_API_KEY=AIzaSyC6l3nFlcHgLc0d1Q9WPyYQjVKTv21ZqFs
|
||||
|
|
|
|||
5
.gitignore
vendored
5
.gitignore
vendored
|
|
@ -19,8 +19,3 @@ Thumbs.db
|
|||
dist/
|
||||
build/
|
||||
meilisearch_data/
|
||||
|
||||
# Scrape files
|
||||
backend/scrape_*.cjs
|
||||
backend/scrape_*.js
|
||||
backend/scrape_*.txt
|
||||
|
|
|
|||
|
|
@ -10,8 +10,6 @@ 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,
|
||||
|
|
@ -1609,8 +1607,7 @@ router.put(
|
|||
const file = req.files[i];
|
||||
currentOrder++;
|
||||
const orderNum = String(currentOrder).padStart(2, "0");
|
||||
// 파일명: 01.webp, 02.webp 형식 (Date.now() 제거)
|
||||
const filename = `${orderNum}.webp`;
|
||||
const filename = `${orderNum}_${Date.now()}.webp`;
|
||||
|
||||
const imageBuffer = await sharp(file.buffer)
|
||||
.webp({ quality: 90 })
|
||||
|
|
@ -1634,18 +1631,6 @@ 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 동기화
|
||||
|
|
@ -1750,12 +1735,9 @@ router.delete("/schedules/:id", authenticateToken, async (req, res) => {
|
|||
router.get("/bots", authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const [bots] = await pool.query(`
|
||||
SELECT b.*,
|
||||
yc.channel_id, yc.channel_name,
|
||||
xc.username, xc.nitter_url
|
||||
SELECT b.*, c.channel_id, c.rss_url, c.channel_name
|
||||
FROM bots b
|
||||
LEFT JOIN bot_youtube_config yc ON b.id = yc.bot_id
|
||||
LEFT JOIN bot_x_config xc ON b.id = xc.bot_id
|
||||
LEFT JOIN bot_youtube_config c ON b.id = c.bot_id
|
||||
ORDER BY b.id ASC
|
||||
`);
|
||||
res.json(bots);
|
||||
|
|
@ -1797,28 +1779,7 @@ 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 [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}` });
|
||||
}
|
||||
|
||||
const result = await syncAllVideos(id);
|
||||
res.json({
|
||||
message: `${result.addedCount}개 일정이 추가되었습니다.`,
|
||||
addedCount: result.addedCount,
|
||||
|
|
@ -1832,154 +1793,4 @@ 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;
|
||||
|
|
|
|||
|
|
@ -7,38 +7,18 @@ const router = express.Router();
|
|||
// 공개 일정 목록 조회 (검색 포함)
|
||||
router.get("/", async (req, res) => {
|
||||
try {
|
||||
const { search, startDate, endDate, limit, year, month } = req.query;
|
||||
const { search, startDate, endDate, limit } = req.query;
|
||||
|
||||
// 검색어가 있으면 Meilisearch 사용
|
||||
if (search && search.trim()) {
|
||||
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,
|
||||
});
|
||||
const results = await searchSchedules(search.trim());
|
||||
return res.json(results);
|
||||
}
|
||||
|
||||
// 날짜 필터 및 제한 조건 구성
|
||||
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);
|
||||
|
|
|
|||
|
|
@ -1,84 +0,0 @@
|
|||
/**
|
||||
* 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,
|
||||
};
|
||||
|
|
@ -53,11 +53,6 @@ export async function initMeilisearch() {
|
|||
},
|
||||
});
|
||||
|
||||
// 페이징 설정 (기본 1000개 제한 해제)
|
||||
await index.updatePagination({
|
||||
maxTotalHits: 10000, // 최대 10000개까지 조회 가능
|
||||
});
|
||||
|
||||
console.log("[Meilisearch] 인덱스 초기화 완료");
|
||||
} catch (error) {
|
||||
console.error("[Meilisearch] 초기화 오류:", error.message);
|
||||
|
|
@ -111,17 +106,15 @@ export async function deleteSchedule(scheduleId) {
|
|||
}
|
||||
|
||||
/**
|
||||
* 일정 검색 (페이징 지원)
|
||||
* 일정 검색
|
||||
*/
|
||||
export async function searchSchedules(query, options = {}) {
|
||||
try {
|
||||
const index = client.index(SCHEDULE_INDEX);
|
||||
|
||||
const searchOptions = {
|
||||
limit: options.limit || 1000, // 기본 1000개 (Meilisearch 최대)
|
||||
offset: options.offset || 0, // 페이징용 offset
|
||||
limit: options.limit || 50,
|
||||
attributesToRetrieve: ["*"],
|
||||
showRankingScore: true, // 유사도 점수 포함
|
||||
};
|
||||
|
||||
// 카테고리 필터
|
||||
|
|
@ -136,19 +129,10 @@ export async function searchSchedules(query, options = {}) {
|
|||
|
||||
const results = await index.search(query, searchOptions);
|
||||
|
||||
// 유사도 0.5 미만인 결과 필터링
|
||||
const filteredHits = results.hits.filter((hit) => hit._rankingScore >= 0.5);
|
||||
|
||||
// 페이징 정보 포함 반환
|
||||
return {
|
||||
hits: filteredHits,
|
||||
total: filteredHits.length, // 필터링 후 결과 수
|
||||
offset: searchOptions.offset,
|
||||
limit: searchOptions.limit,
|
||||
};
|
||||
return results.hits;
|
||||
} catch (error) {
|
||||
console.error("[Meilisearch] 검색 오류:", error.message);
|
||||
return { hits: [], total: 0, offset: 0, limit: 0 };
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,629 +0,0 @@
|
|||
/**
|
||||
* 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,
|
||||
};
|
||||
|
|
@ -152,83 +152,6 @@ 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
|
||||
|
|
@ -433,14 +356,14 @@ function extractMemberIdsFromDescription(description, memberNameMap) {
|
|||
}
|
||||
|
||||
/**
|
||||
* 봇의 새 영상 동기화 (YouTube API 기반)
|
||||
* 봇의 새 영상 동기화 (RSS 기반)
|
||||
*/
|
||||
export async function syncNewVideos(botId) {
|
||||
try {
|
||||
// 봇 정보 조회 (bot_youtube_config 조인)
|
||||
const [bots] = await pool.query(
|
||||
`
|
||||
SELECT b.*, c.channel_id
|
||||
SELECT b.*, c.channel_id, c.rss_url
|
||||
FROM bots b
|
||||
LEFT JOIN bot_youtube_config c ON b.id = c.bot_id
|
||||
WHERE b.id = ?
|
||||
|
|
@ -454,8 +377,8 @@ export async function syncNewVideos(botId) {
|
|||
|
||||
const bot = bots[0];
|
||||
|
||||
if (!bot.channel_id) {
|
||||
throw new Error("Channel ID가 설정되지 않았습니다.");
|
||||
if (!bot.rss_url) {
|
||||
throw new Error("RSS URL이 설정되지 않았습니다.");
|
||||
}
|
||||
|
||||
// 봇별 커스텀 설정 조회
|
||||
|
|
@ -463,8 +386,8 @@ export async function syncNewVideos(botId) {
|
|||
|
||||
const categoryId = await getYoutubeCategory();
|
||||
|
||||
// YouTube API로 최근 10개 영상 조회
|
||||
const videos = await fetchRecentVideosFromAPI(bot.channel_id, 10);
|
||||
// RSS 피드 파싱
|
||||
const videos = await parseRSSFeed(bot.rss_url);
|
||||
let addedCount = 0;
|
||||
|
||||
// 멤버 추출을 위한 이름 맵 조회 (필요 시)
|
||||
|
|
@ -511,33 +434,22 @@ export async function syncNewVideos(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]
|
||||
);
|
||||
}
|
||||
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]
|
||||
);
|
||||
|
||||
return { addedCount, total: videos.length };
|
||||
} catch (error) {
|
||||
// 오류 상태 업데이트
|
||||
await pool.query(
|
||||
`UPDATE bots SET
|
||||
last_check_at = NOW(),
|
||||
last_check_at = DATE_ADD(NOW(), INTERVAL 9 HOUR),
|
||||
status = 'error',
|
||||
error_message = ?
|
||||
WHERE id = ?`,
|
||||
|
|
@ -555,7 +467,7 @@ export async function syncAllVideos(botId) {
|
|||
// 봇 정보 조회 (bot_youtube_config 조인)
|
||||
const [bots] = await pool.query(
|
||||
`
|
||||
SELECT b.*, c.channel_id
|
||||
SELECT b.*, c.channel_id, c.rss_url
|
||||
FROM bots b
|
||||
LEFT JOIN bot_youtube_config c ON b.id = c.bot_id
|
||||
WHERE b.id = ?
|
||||
|
|
@ -626,26 +538,15 @@ export async function syncAllVideos(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]
|
||||
);
|
||||
}
|
||||
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]
|
||||
);
|
||||
|
||||
return { addedCount, total: videos.length };
|
||||
} catch (error) {
|
||||
|
|
|
|||
|
|
@ -1,76 +1,49 @@
|
|||
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) {
|
||||
const id = parseInt(botId);
|
||||
return schedulers.has(id);
|
||||
return schedulers.has(botId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 개별 봇 스케줄 등록
|
||||
*/
|
||||
export function registerBot(botId, intervalMinutes = 2, cronExpression = null) {
|
||||
const id = parseInt(botId);
|
||||
// 기존 스케줄이 있으면 제거
|
||||
unregisterBot(id);
|
||||
unregisterBot(botId);
|
||||
|
||||
// cron 표현식: 지정된 표현식 사용, 없으면 기본값 생성
|
||||
const expression = cronExpression || `1-59/${intervalMinutes} * * * *`;
|
||||
|
||||
const task = cron.schedule(expression, async () => {
|
||||
console.log(`[Bot ${id}] 동기화 시작...`);
|
||||
console.log(`[Bot ${botId}] 동기화 시작...`);
|
||||
try {
|
||||
const result = await syncBot(id);
|
||||
console.log(`[Bot ${id}] 동기화 완료: ${result.addedCount}개 추가`);
|
||||
const result = await syncNewVideos(botId);
|
||||
console.log(`[Bot ${botId}] 동기화 완료: ${result.addedCount}개 추가`);
|
||||
} catch (error) {
|
||||
console.error(`[Bot ${id}] 동기화 오류:`, error.message);
|
||||
console.error(`[Bot ${botId}] 동기화 오류:`, error.message);
|
||||
}
|
||||
});
|
||||
|
||||
schedulers.set(id, task);
|
||||
console.log(`[Bot ${id}] 스케줄 등록됨 (cron: ${expression})`);
|
||||
schedulers.set(botId, task);
|
||||
console.log(`[Bot ${botId}] 스케줄 등록됨 (cron: ${expression})`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 개별 봇 스케줄 해제
|
||||
*/
|
||||
export function unregisterBot(botId) {
|
||||
const id = parseInt(botId);
|
||||
if (schedulers.has(id)) {
|
||||
schedulers.get(id).stop();
|
||||
schedulers.delete(id);
|
||||
console.log(`[Bot ${id}] 스케줄 해제됨`);
|
||||
if (schedulers.has(botId)) {
|
||||
schedulers.get(botId).stop();
|
||||
schedulers.delete(botId);
|
||||
console.log(`[Bot ${botId}] 스케줄 해제됨`);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -82,48 +55,15 @@ async function syncBotStatuses() {
|
|||
const [bots] = await pool.query("SELECT id, status FROM bots");
|
||||
|
||||
for (const bot of bots) {
|
||||
const botId = parseInt(bot.id);
|
||||
const isRunningInMemory = schedulers.has(botId);
|
||||
const isRunningInMemory = schedulers.has(bot.id);
|
||||
const isRunningInDB = bot.status === "running";
|
||||
|
||||
// 메모리에 없는데 DB가 running이면 → 서버 크래시 등으로 불일치
|
||||
// 이 경우 DB를 stopped로 변경하는 대신, 메모리에 봇을 다시 등록
|
||||
// 메모리에 없는데 DB가 running이면 → 서버 크래시 등으로 불일치, DB를 stopped로 업데이트
|
||||
if (!isRunningInMemory && isRunningInDB) {
|
||||
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`);
|
||||
}
|
||||
await pool.query("UPDATE bots SET status = 'stopped' WHERE id = ?", [
|
||||
bot.id,
|
||||
]);
|
||||
console.log(`[Scheduler] Bot ${bot.id} 상태 동기화: stopped`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
|
|
@ -176,7 +116,7 @@ export async function startBot(botId) {
|
|||
|
||||
// 즉시 1회 실행
|
||||
try {
|
||||
await syncBot(botId);
|
||||
await syncNewVideos(botId);
|
||||
} catch (error) {
|
||||
console.error(`[Bot ${botId}] 초기 동기화 오류:`, error.message);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,2 +1,2 @@
|
|||
VITE_KAKAO_JS_KEY=5a626e19fbafb33b1eea26f162038ccb
|
||||
VITE_KAKAO_REST_KEY=e7a5516bf6cb1b398857789ee2ea6eea
|
||||
VITE_KAKAO_REST_KEY=cf21156ae6cc8f6e95b3a3150926cdf8
|
||||
|
|
|
|||
|
|
@ -2,10 +2,7 @@
|
|||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta
|
||||
name="viewport"
|
||||
content="width=device-width, initial-scale=1.0, viewport-fit=cover"
|
||||
/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
|
||||
<title>fromis_9 - 프로미스나인</title>
|
||||
<link
|
||||
|
|
|
|||
212
frontend/package-lock.json
generated
212
frontend/package-lock.json
generated
|
|
@ -8,23 +8,16 @@
|
|||
"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": {
|
||||
|
|
@ -1135,59 +1128,6 @@
|
|||
"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",
|
||||
|
|
@ -1289,15 +1229,6 @@
|
|||
"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",
|
||||
|
|
@ -1502,15 +1433,6 @@
|
|||
"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",
|
||||
|
|
@ -1548,12 +1470,6 @@
|
|||
"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",
|
||||
|
|
@ -1771,18 +1687,6 @@
|
|||
"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",
|
||||
|
|
@ -1964,21 +1868,6 @@
|
|||
"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",
|
||||
|
|
@ -2003,18 +1892,6 @@
|
|||
"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",
|
||||
|
|
@ -2358,31 +2235,6 @@
|
|||
"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",
|
||||
|
|
@ -2419,33 +2271,6 @@
|
|||
"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",
|
||||
|
|
@ -2737,25 +2562,6 @@
|
|||
"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",
|
||||
|
|
@ -2817,15 +2623,6 @@
|
|||
"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",
|
||||
|
|
@ -3024,15 +2821,6 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"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",
|
||||
|
|
|
|||
|
|
@ -9,23 +9,16 @@
|
|||
"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": {
|
||||
|
|
|
|||
|
|
@ -1,25 +1,13 @@
|
|||
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/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 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 AdminLogin from './pages/pc/admin/AdminLogin';
|
||||
|
|
@ -34,25 +22,13 @@ 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 />} />
|
||||
|
|
@ -83,21 +59,18 @@ function App() {
|
|||
</PCLayout>
|
||||
} />
|
||||
</Routes>
|
||||
</PCWrapper>
|
||||
</BrowserView>
|
||||
<MobileView>
|
||||
<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>
|
||||
{/* 모바일 버전은 추후 구현 */}
|
||||
<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>
|
||||
</MobileView>
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
|
||||
|
|
|
|||
|
|
@ -1,62 +0,0 @@
|
|||
/**
|
||||
* 어드민 앨범 관리 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",
|
||||
});
|
||||
}
|
||||
|
|
@ -1,42 +0,0 @@
|
|||
/**
|
||||
* 어드민 인증 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");
|
||||
}
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
/**
|
||||
* 어드민 봇 관리 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" });
|
||||
}
|
||||
|
|
@ -1,40 +0,0 @@
|
|||
/**
|
||||
* 어드민 카테고리 관리 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 }),
|
||||
});
|
||||
}
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
/**
|
||||
* 어드민 멤버 관리 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");
|
||||
}
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
/**
|
||||
* 어드민 일정 관리 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" });
|
||||
}
|
||||
|
|
@ -1,60 +0,0 @@
|
|||
/**
|
||||
* 공통 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();
|
||||
}
|
||||
|
|
@ -1,29 +0,0 @@
|
|||
/**
|
||||
* 앨범 관련 공개 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`);
|
||||
}
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
/**
|
||||
* 멤버 관련 공개 API
|
||||
*/
|
||||
import { fetchApi } from "../index";
|
||||
|
||||
// 멤버 목록 조회
|
||||
export async function getMembers() {
|
||||
return fetchApi("/api/members");
|
||||
}
|
||||
|
||||
// 멤버 상세 조회
|
||||
export async function getMember(id) {
|
||||
return fetchApi(`/api/members/${id}`);
|
||||
}
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
/**
|
||||
* 일정 관련 공개 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");
|
||||
}
|
||||
|
|
@ -1,15 +0,0 @@
|
|||
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;
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
/**
|
||||
* 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;
|
||||
|
|
@ -1,115 +0,0 @@
|
|||
/**
|
||||
* 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;
|
||||
|
|
@ -1,261 +0,0 @@
|
|||
/**
|
||||
* 커스텀 데이트픽커 컴포넌트
|
||||
* 연/월/일 선택이 가능한 드롭다운 형태의 날짜 선택기
|
||||
*/
|
||||
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;
|
||||
|
|
@ -1,178 +0,0 @@
|
|||
/**
|
||||
* 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;
|
||||
|
|
@ -1,192 +0,0 @@
|
|||
/**
|
||||
* 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;
|
||||
|
|
@ -1,42 +0,0 @@
|
|||
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;
|
||||
|
|
@ -1,93 +0,0 @@
|
|||
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;
|
||||
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
import Header from './Header';
|
||||
import Footer from './Footer';
|
||||
import '../../pc.css';
|
||||
|
||||
function Layout({ children }) {
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -1,56 +0,0 @@
|
|||
/**
|
||||
* 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;
|
||||
|
|
@ -3,11 +3,20 @@
|
|||
@tailwind utilities;
|
||||
|
||||
/* 기본 스타일 */
|
||||
html {
|
||||
overflow-y: scroll; /* 항상 스크롤바 공간 확보 - 화면 밀림 방지 */
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: #fafafa;
|
||||
color: #1a1a1a;
|
||||
}
|
||||
|
||||
/* 최소 너비 설정 - 화면 축소시 깨짐 방지 */
|
||||
#root {
|
||||
min-width: 1440px;
|
||||
}
|
||||
|
||||
/* 스크롤바 스타일 */
|
||||
::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
|
|
@ -78,8 +87,3 @@ body {
|
|||
-ms-overflow-style: none;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
/* Swiper autoHeight 지원 */
|
||||
.swiper-slide {
|
||||
height: auto !important;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,23 +1,10 @@
|
|||
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>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<App />
|
||||
</QueryClientProvider>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,156 +0,0 @@
|
|||
/* 모바일 전용 스타일 */
|
||||
|
||||
/* 모바일 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;
|
||||
}
|
||||
|
|
@ -1,63 +0,0 @@
|
|||
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;
|
||||
|
|
@ -1,141 +0,0 @@
|
|||
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;
|
||||
|
|
@ -1,131 +0,0 @@
|
|||
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;
|
||||
|
|
@ -1,265 +0,0 @@
|
|||
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;
|
||||
|
|
@ -1,127 +0,0 @@
|
|||
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
|
|
@ -2,8 +2,6 @@ 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();
|
||||
|
|
@ -11,7 +9,8 @@ function Album() {
|
|||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
getAlbums()
|
||||
fetch('/api/albums')
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
setAlbums(data);
|
||||
setLoading(false);
|
||||
|
|
@ -22,6 +21,13 @@ 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 '';
|
||||
|
|
@ -143,7 +149,7 @@ function Album() {
|
|||
</p>
|
||||
<div className="flex items-center gap-2 text-sm text-gray-500">
|
||||
<Calendar size={14} />
|
||||
<span>{formatDate(album.release_date, 'YYYY.MM.DD')}</span>
|
||||
<span>{formatDate(album.release_date)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
|
|
@ -2,10 +2,41 @@ 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();
|
||||
|
|
@ -126,7 +157,8 @@ function AlbumDetail() {
|
|||
}, [lightbox.open, lightbox.index, lightbox.images, preloadedImages]);
|
||||
|
||||
useEffect(() => {
|
||||
getAlbumByName(name)
|
||||
fetch(`/api/albums/by-name/${name}`)
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
setAlbum(data);
|
||||
setLoading(false);
|
||||
|
|
@ -139,6 +171,13 @@ 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 '';
|
||||
|
|
@ -278,7 +317,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, 'YYYY.MM.DD')}</span>
|
||||
<span>{formatDate(album.release_date)}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Music2 size={18} />
|
||||
|
|
@ -529,12 +568,12 @@ function AlbumDetail() {
|
|||
</button>
|
||||
)}
|
||||
|
||||
{/* 인디케이터 - 공통 컴포넌트 사용 */}
|
||||
{/* 인디케이터 - memo 컴포넌트로 분리 */}
|
||||
{lightbox.images.length > 1 && (
|
||||
<LightboxIndicator
|
||||
count={lightbox.images.length}
|
||||
currentIndex={lightbox.index}
|
||||
goToIndex={(i) => setLightbox(prev => ({ ...prev, index: i }))}
|
||||
setLightbox={setLightbox}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
|
@ -4,8 +4,41 @@ 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';
|
||||
import { getAlbumByName } from '../../../api/public/albums';
|
||||
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>
|
||||
);
|
||||
});
|
||||
|
||||
// CSS로 호버 효과 추가 + overflow 문제 수정 + 로드 애니메이션
|
||||
const galleryStyles = `
|
||||
|
|
@ -49,7 +82,8 @@ function AlbumGallery() {
|
|||
const [preloadedImages] = useState(() => new Set()); // 프리로드된 이미지 URL 추적
|
||||
|
||||
useEffect(() => {
|
||||
getAlbumByName(name)
|
||||
fetch(`/api/albums/by-name/${name}`)
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
setAlbum(data);
|
||||
const allPhotos = [];
|
||||
|
|
@ -358,11 +392,11 @@ function AlbumGallery() {
|
|||
</button>
|
||||
)}
|
||||
|
||||
{/* 하단 점 인디케이터 - 공통 컴포넌트 사용 */}
|
||||
{/* 하단 점 인디케이터 - memo 컴포넌트로 분리 */}
|
||||
<LightboxIndicator
|
||||
count={photos.length}
|
||||
currentIndex={lightbox.index}
|
||||
goToIndex={(i) => setLightbox(prev => ({ ...prev, index: i }))}
|
||||
setLightbox={setLightbox}
|
||||
/>
|
||||
</div>
|
||||
</motion.div>
|
||||
|
|
@ -1,10 +1,7 @@
|
|||
import { useState, useEffect } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { Link } from 'react-router-dom';
|
||||
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';
|
||||
import { Calendar, Users, Disc3, ArrowRight, Clock } from 'lucide-react';
|
||||
|
||||
function Home() {
|
||||
const [members, setMembers] = useState([]);
|
||||
|
|
@ -12,12 +9,21 @@ function Home() {
|
|||
|
||||
useEffect(() => {
|
||||
// 멤버 데이터 로드
|
||||
getMembers()
|
||||
fetch('/api/members')
|
||||
.then(res => res.json())
|
||||
.then(data => setMembers(data))
|
||||
.catch(error => console.error('멤버 데이터 로드 오류:', error));
|
||||
|
||||
// 다가오는 일정 로드 (오늘 이후 3개)
|
||||
getUpcomingSchedules(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())
|
||||
.then(data => setUpcomingSchedules(data))
|
||||
.catch(error => console.error('일정 데이터 로드 오류:', error));
|
||||
}, []);
|
||||
|
|
@ -58,46 +64,34 @@ function Home() {
|
|||
</div>
|
||||
</section>
|
||||
|
||||
{/* 그룹 통계 섹션 */}
|
||||
<section className="py-16 bg-gray-50">
|
||||
{/* 퀵 링크 섹션 */}
|
||||
<section className="py-16 bg-white">
|
||||
<div className="max-w-7xl mx-auto px-6">
|
||||
<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"
|
||||
<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"
|
||||
>
|
||||
<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"
|
||||
<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">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"
|
||||
<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">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>
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
|
@ -138,7 +132,7 @@ function Home() {
|
|||
</section>
|
||||
|
||||
{/* 일정 미리보기 */}
|
||||
<section className="py-16 bg-gray-50">
|
||||
<section className="py-16 bg-white">
|
||||
<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>
|
||||
|
|
@ -163,6 +157,9 @@ 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}
|
||||
|
|
@ -171,12 +168,13 @@ 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>
|
||||
|
|
@ -184,20 +182,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 opacity-60" />
|
||||
<Clock size={14} className="text-primary" />
|
||||
<span>{schedule.time.slice(0, 5)}</span>
|
||||
</div>
|
||||
)}
|
||||
{schedule.category_name && (
|
||||
<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 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>
|
||||
)}
|
||||
</div>
|
||||
|
|
@ -1,17 +1,20 @@
|
|||
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(() => {
|
||||
getMembers()
|
||||
.then(data => {
|
||||
setMembers(data);
|
||||
Promise.all([
|
||||
fetch('/api/members').then(res => res.json()),
|
||||
fetch('/api/stats').then(res => res.json())
|
||||
])
|
||||
.then(([membersData, statsData]) => {
|
||||
setMembers(membersData);
|
||||
setStats(statsData);
|
||||
setLoading(false);
|
||||
})
|
||||
.catch(error => {
|
||||
|
|
@ -20,6 +23,13 @@ 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]">
|
||||
|
|
@ -77,7 +87,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, 'YYYY.MM.DD')}</span>
|
||||
<span>{formatDate(member.birth_date)}</span>
|
||||
</div>
|
||||
|
||||
{/* 인스타그램 링크 */}
|
||||
|
|
@ -101,55 +111,66 @@ 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-16"
|
||||
className="mt-12"
|
||||
>
|
||||
<h2 className="text-2xl font-bold mb-8 text-gray-400">전 멤버</h2>
|
||||
<div className="grid grid-cols-5 gap-8">
|
||||
<h2 className="text-lg font-bold mb-4 text-gray-400">전 멤버</h2>
|
||||
<div className="flex gap-4">
|
||||
{members.filter(m => m.is_former).map((member, index) => (
|
||||
<motion.div
|
||||
key={member.id}
|
||||
initial={{ opacity: 0, y: 30 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.6 + index * 0.1 }}
|
||||
className="group h-full"
|
||||
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"
|
||||
>
|
||||
<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 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>
|
||||
{/* 이름 */}
|
||||
<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>
|
||||
);
|
||||
|
|
@ -1,24 +1,19 @@
|
|||
import { useState, useEffect, useRef, useMemo, useDeferredValue, memo } from 'react';
|
||||
import { useState, useEffect, useRef, useMemo } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
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;
|
||||
};
|
||||
import { Clock, ChevronLeft, ChevronRight, ChevronDown, Tag, Search, ArrowLeft } from 'lucide-react';
|
||||
|
||||
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);
|
||||
|
|
@ -36,82 +31,27 @@ 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 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]);
|
||||
const [searchResults, setSearchResults] = useState([]);
|
||||
const [searchLoading, setSearchLoading] = useState(false);
|
||||
|
||||
// 데이터 로드
|
||||
// 초기 데이터 로드 (카테고리만)
|
||||
useEffect(() => {
|
||||
loadCategories();
|
||||
fetchSchedules();
|
||||
fetchCategories();
|
||||
}, []);
|
||||
|
||||
// 월 변경 시 일정 로드
|
||||
useEffect(() => {
|
||||
const year = currentDate.getFullYear();
|
||||
const month = currentDate.getMonth();
|
||||
loadSchedules(year, month + 1);
|
||||
}, [currentDate]);
|
||||
|
||||
const loadSchedules = async (year, month) => {
|
||||
setLoading(true);
|
||||
const fetchSchedules = async () => {
|
||||
try {
|
||||
const data = await getSchedules(year, month);
|
||||
setSchedules(data);
|
||||
const response = await fetch('/api/schedules');
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setSchedules(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('일정 로드 오류:', error);
|
||||
} finally {
|
||||
|
|
@ -119,14 +59,37 @@ function Schedule() {
|
|||
}
|
||||
};
|
||||
|
||||
const loadCategories = async () => {
|
||||
const fetchCategories = async () => {
|
||||
try {
|
||||
const data = await getCategories();
|
||||
setCategories(data);
|
||||
const response = await fetch('/api/schedule-categories');
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
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(() => {
|
||||
|
|
@ -144,13 +107,6 @@ 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();
|
||||
|
|
@ -162,68 +118,38 @@ function Schedule() {
|
|||
|
||||
const days = ['일', '월', '화', '수', '목', '금', '토'];
|
||||
|
||||
// 스케줄 데이터를 지연 처리하여 달력 UI 응답성 향상
|
||||
const deferredSchedules = useDeferredValue(schedules);
|
||||
// 스케줄이 있는 날짜 목록 (ISO 형식에서 YYYY-MM-DD 추출)
|
||||
const scheduleDates = schedules.map(s => s.date ? s.date.split('T')[0] : '');
|
||||
|
||||
// 일정 날짜별 맵 (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 = scheduleDateMap.get(dateStr);
|
||||
const schedule = schedules.find(s => (s.date ? s.date.split('T')[0] : '') === 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 scheduleDateMap.has(dateStr);
|
||||
return scheduleDates.includes(dateStr);
|
||||
};
|
||||
|
||||
const prevMonth = () => {
|
||||
setSlideDirection(-1);
|
||||
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);
|
||||
}
|
||||
setCurrentDate(new Date(year, month - 1, 1));
|
||||
setSelectedDate(null); // 월 변경 시 초기화
|
||||
};
|
||||
|
||||
const nextMonth = () => {
|
||||
setSlideDirection(1);
|
||||
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);
|
||||
}
|
||||
setCurrentDate(new Date(year, month + 1, 1));
|
||||
setSelectedDate(null); // 월 변경 시 초기화
|
||||
};
|
||||
|
||||
// 날짜 선택 (토글 없이 항상 선택)
|
||||
const selectDate = (day) => {
|
||||
const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
|
||||
setSelectedDate(dateStr);
|
||||
setSelectedDate(selectedDate === dateStr ? null : dateStr);
|
||||
};
|
||||
|
||||
const selectYear = (newYear) => {
|
||||
|
|
@ -232,16 +158,7 @@ function Schedule() {
|
|||
};
|
||||
|
||||
const selectMonth = (newMonth) => {
|
||||
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);
|
||||
}
|
||||
setCurrentDate(new Date(year, newMonth, 1));
|
||||
setShowYearMonthPicker(false);
|
||||
setViewMode('yearMonth');
|
||||
};
|
||||
|
|
@ -263,9 +180,7 @@ function Schedule() {
|
|||
if (isSearchMode) {
|
||||
// 검색 전엔 빈 목록, 검색 후엔 API 결과 (Meilisearch 유사도순 유지)
|
||||
if (!searchTerm) return [];
|
||||
// 카테고리 필터링 적용
|
||||
if (selectedCategories.length === 0) return searchResults;
|
||||
return searchResults.filter(s => selectedCategories.includes(s.category_id));
|
||||
return searchResults;
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -289,36 +204,6 @@ 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 = ['일', '월', '화', '수', '목', '금', '토'];
|
||||
|
|
@ -335,24 +220,25 @@ function Schedule() {
|
|||
if (!schedule.description && schedule.source_url) {
|
||||
window.open(schedule.source_url, '_blank');
|
||||
} else {
|
||||
// 상세 페이지로 이동
|
||||
// 상세 페이지로 이동 (추후 구현)
|
||||
navigate(`/schedule/${schedule.id}`);
|
||||
}
|
||||
};
|
||||
|
||||
const currentYear = new Date().getFullYear();
|
||||
const isCurrentYear = (y) => y === currentYear;
|
||||
// 년도 범위
|
||||
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 isCurrentMonth = (m) => {
|
||||
const now = new Date();
|
||||
return year === now.getFullYear() && m === now.getMonth();
|
||||
const today = new Date();
|
||||
return today.getFullYear() === year && today.getMonth() === m;
|
||||
};
|
||||
|
||||
// 연도 선택 범위
|
||||
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 = () => setYearRangeStart(prev => prev - 3);
|
||||
const nextYearRange = () => setYearRangeStart(prev => prev + 3);
|
||||
|
||||
const prevYearRange = () => setCurrentDate(new Date(year - 10, month, 1));
|
||||
const nextYearRange = () => setCurrentDate(new Date(year + 10, month, 1));
|
||||
|
||||
// 선택된 카테고리 이름
|
||||
const getSelectedCategoryNames = () => {
|
||||
|
|
@ -376,21 +262,6 @@ 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">
|
||||
|
|
@ -479,7 +350,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 ? 'text-primary font-medium hover:bg-primary/10' :
|
||||
isCurrentYear(y) && year !== y ? 'border border-primary text-primary hover:bg-primary/10' :
|
||||
'hover:bg-gray-100 text-gray-700'
|
||||
}`}
|
||||
>
|
||||
|
|
@ -495,7 +366,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 ? 'text-primary font-medium hover:bg-primary/10' :
|
||||
isCurrentMonth(i) && month !== i ? 'border border-primary text-primary hover:bg-primary/10' :
|
||||
'hover:bg-gray-100 text-gray-700'
|
||||
}`}
|
||||
>
|
||||
|
|
@ -515,7 +386,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 ? 'text-primary font-medium hover:bg-primary/10' :
|
||||
isCurrentMonth(i) && month !== i ? 'border border-primary text-primary hover:bg-primary/10' :
|
||||
'hover:bg-gray-100 text-gray-700'
|
||||
}`}
|
||||
>
|
||||
|
|
@ -574,13 +445,6 @@ 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
|
||||
|
|
@ -588,24 +452,17 @@ 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 ? 'text-primary font-bold' : ''}
|
||||
${isToday && !isSelected ? 'bg-primary/10 text-primary font-bold hover:bg-primary/20' : ''}
|
||||
${dayOfWeek === 0 && !isSelected && !isToday ? 'text-red-500' : ''}
|
||||
${dayOfWeek === 6 && !isSelected && !isToday ? 'text-blue-500' : ''}
|
||||
`}
|
||||
>
|
||||
<span>{day}</span>
|
||||
{/* 점: 선택되지 않은 날짜에만 표시, 최대 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>
|
||||
)}
|
||||
{/* 점: absolute로 위치 고정하여 글씨 위치에 영향 없음 */}
|
||||
<span
|
||||
className={`absolute bottom-1 w-1.5 h-1.5 rounded-full ${hasEvent ? '' : 'opacity-0'}`}
|
||||
style={{ backgroundColor: isSelected ? 'white' : (eventColor || 'transparent') }}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
|
|
@ -625,12 +482,23 @@ function Schedule() {
|
|||
</motion.div>
|
||||
</AnimatePresence>
|
||||
|
||||
{/* 범례 */}
|
||||
<div className="mt-6 pt-4 border-t border-gray-100 flex items-center text-sm">
|
||||
{/* 범례 및 전체보기 */}
|
||||
<div className="mt-6 pt-4 border-t border-gray-100 flex items-center justify-between 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>
|
||||
|
|
@ -655,12 +523,25 @@ function Schedule() {
|
|||
<span>전체</span>
|
||||
</div>
|
||||
<span className="text-sm text-gray-400">
|
||||
{categoryCounts.get('total') || 0}
|
||||
{isSearchMode && searchTerm
|
||||
? searchResults.length
|
||||
: schedules.filter(s => {
|
||||
const scheduleDate = s.date ? s.date.split('T')[0] : '';
|
||||
return scheduleDate.startsWith(currentYearMonth);
|
||||
}).length
|
||||
}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{/* 개별 카테고리 - useMemo로 정렬됨 */}
|
||||
{sortedCategories.map(category => {
|
||||
{/* 개별 카테고리 */}
|
||||
{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;
|
||||
const isSelected = selectedCategories.includes(category.id);
|
||||
return (
|
||||
<button
|
||||
|
|
@ -677,7 +558,7 @@ function Schedule() {
|
|||
/>
|
||||
<span>{category.name}</span>
|
||||
</div>
|
||||
<span className="text-sm text-gray-400">{category.count}</span>
|
||||
<span className="text-sm text-gray-400">{count}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
|
|
@ -721,6 +602,7 @@ function Schedule() {
|
|||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
setSearchTerm(searchInput);
|
||||
searchSchedules(searchInput);
|
||||
} else if (e.key === 'Escape') {
|
||||
setIsSearchMode(false);
|
||||
setSearchInput('');
|
||||
|
|
@ -734,6 +616,7 @@ 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"
|
||||
|
|
@ -821,207 +704,110 @@ function Schedule() {
|
|||
|
||||
</div>
|
||||
|
||||
<div
|
||||
ref={scrollContainerRef}
|
||||
id="scheduleScrollContainer"
|
||||
<motion.div
|
||||
key={isSearchMode ? 'search' : 'normal'}
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
transition={{ duration: 0.15 }}
|
||||
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 ? (
|
||||
isSearchMode && searchTerm ? (
|
||||
/* 검색 모드: 가상 스크롤 */
|
||||
<>
|
||||
<div
|
||||
style={{
|
||||
height: `${virtualizer.getTotalSize()}px`,
|
||||
width: '100%',
|
||||
position: 'relative',
|
||||
}}
|
||||
|
||||
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"
|
||||
>
|
||||
{virtualizer.getVirtualItems().map((virtualItem) => {
|
||||
const schedule = filteredSchedules[virtualItem.index];
|
||||
if (!schedule) return null;
|
||||
|
||||
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 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>
|
||||
)}
|
||||
{!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 }}
|
||||
>
|
||||
<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>
|
||||
{/* 검색 모드일 때 년.월 표시, 일반 모드에서는 월 표시 안함 */}
|
||||
{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>
|
||||
|
||||
<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"
|
||||
style={{ backgroundColor: categoryColor }}
|
||||
/>
|
||||
<span>
|
||||
{categoryName}
|
||||
{schedule.source_name && ` · ${schedule.source_name}`}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</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>
|
||||
);
|
||||
}
|
||||
{/* 멤버 태그 (별도 줄) */}
|
||||
{(() => {
|
||||
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) {
|
||||
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>
|
||||
))}
|
||||
<span className="px-2 py-0.5 bg-primary/10 text-primary text-sm font-medium rounded-full">
|
||||
프로미스나인
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
</motion.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 className="text-center py-20 text-gray-500">
|
||||
{selectedDate ? '선택한 날짜에 일정이 없습니다.' : '예정된 일정이 없습니다.'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
|
@ -2,13 +2,10 @@ import { useState, useEffect, useRef } from 'react';
|
|||
import { useNavigate, useParams, Link } from 'react-router-dom';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import {
|
||||
Save, Home, ChevronRight, Music, Trash2, Plus, Image, Star,
|
||||
ChevronDown
|
||||
Save, Home, ChevronRight, LogOut, Music, Trash2, Plus, Image, Star,
|
||||
ChevronDown, ChevronLeft, Calendar
|
||||
} 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 }) {
|
||||
|
|
@ -74,6 +71,280 @@ 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();
|
||||
|
|
@ -85,7 +356,15 @@ function AdminAlbumForm() {
|
|||
const [saving, setSaving] = useState(false);
|
||||
const [coverPreview, setCoverPreview] = useState(null);
|
||||
const [coverFile, setCoverFile] = useState(null);
|
||||
const { toast, setToast } = useToast();
|
||||
const [toast, setToast] = useState(null);
|
||||
|
||||
// Toast 자동 숨김
|
||||
useEffect(() => {
|
||||
if (toast) {
|
||||
const timer = setTimeout(() => setToast(null), 3000);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [toast]);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
title: '',
|
||||
|
|
@ -141,6 +420,12 @@ function AdminAlbumForm() {
|
|||
}
|
||||
}, [id, isEditMode, navigate]);
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem('adminToken');
|
||||
localStorage.removeItem('adminUser');
|
||||
navigate('/admin');
|
||||
};
|
||||
|
||||
const handleInputChange = (e) => {
|
||||
const { name, value } = e.target;
|
||||
|
||||
|
|
@ -259,13 +544,49 @@ function AdminAlbumForm() {
|
|||
|
||||
const albumTypes = ['정규', '미니', '싱글'];
|
||||
|
||||
const pageVariants = {
|
||||
initial: { opacity: 0, y: 20 },
|
||||
animate: { opacity: 1, y: 0 },
|
||||
exit: { opacity: 0, y: -20 }
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<motion.div
|
||||
className="min-h-screen bg-gray-50"
|
||||
initial="initial"
|
||||
animate="animate"
|
||||
exit="exit"
|
||||
variants={pageVariants}
|
||||
transition={{ duration: 0.3 }}
|
||||
>
|
||||
{/* Toast */}
|
||||
<Toast toast={toast} onClose={() => setToast(null)} />
|
||||
|
||||
{/* 헤더 */}
|
||||
<AdminHeader user={user} />
|
||||
<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>
|
||||
|
||||
{/* 메인 콘텐츠 */}
|
||||
<main className="max-w-4xl mx-auto px-6 py-8">
|
||||
|
|
@ -660,7 +981,7 @@ function AdminAlbumForm() {
|
|||
</form>
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -3,18 +3,11 @@ import { useNavigate, Link, useParams } from 'react-router-dom';
|
|||
import { motion, AnimatePresence, Reorder } from 'framer-motion';
|
||||
import {
|
||||
Upload, Trash2, Image, X, Check, Plus,
|
||||
Home, ChevronRight, ArrowLeft, Grid, List,
|
||||
ZoomIn, GripVertical, Users, User, Users2,
|
||||
Home, ChevronRight, LogOut, ArrowLeft, Grid, List,
|
||||
ZoomIn, AlertTriangle, 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();
|
||||
|
|
@ -27,7 +20,7 @@ function AdminAlbumPhotos() {
|
|||
const [teasers, setTeasers] = useState([]); // 티저 이미지
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [user, setUser] = useState(null);
|
||||
const { toast, setToast } = useToast();
|
||||
const [toast, setToast] = useState(null);
|
||||
const [selectedPhotos, setSelectedPhotos] = useState([]);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [uploadProgress, setUploadProgress] = useState(0);
|
||||
|
|
@ -142,49 +135,77 @@ function AdminAlbumPhotos() {
|
|||
}));
|
||||
};
|
||||
|
||||
// Toast 자동 숨김
|
||||
useEffect(() => {
|
||||
if (toast) {
|
||||
const timer = setTimeout(() => setToast(null), 3000);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [toast]);
|
||||
|
||||
useEffect(() => {
|
||||
// 로그인 확인
|
||||
if (!authApi.hasToken()) {
|
||||
const token = localStorage.getItem('adminToken');
|
||||
const userData = localStorage.getItem('adminUser');
|
||||
|
||||
if (!token || !userData) {
|
||||
navigate('/admin');
|
||||
return;
|
||||
}
|
||||
|
||||
setUser(authApi.getCurrentUser());
|
||||
setUser(JSON.parse(userData));
|
||||
fetchAlbumData();
|
||||
}, [navigate, albumId]);
|
||||
|
||||
const fetchAlbumData = async () => {
|
||||
try {
|
||||
const token = localStorage.getItem('adminToken');
|
||||
|
||||
// 앨범 정보 로드
|
||||
const albumData = await getAlbum(albumId);
|
||||
const albumRes = await fetch(`/api/albums/${albumId}`);
|
||||
if (!albumRes.ok) throw new Error('앨범을 찾을 수 없습니다');
|
||||
const albumData = await albumRes.json();
|
||||
setAlbum(albumData);
|
||||
|
||||
// 멤버 목록 로드
|
||||
try {
|
||||
const membersData = await getMembers();
|
||||
const membersRes = await fetch('/api/members');
|
||||
if (membersRes.ok) {
|
||||
const membersData = await membersRes.json();
|
||||
setMembers(membersData);
|
||||
} catch (e) { /* 무시 */ }
|
||||
}
|
||||
|
||||
// 기존 컨셉 포토 목록 로드
|
||||
const photosRes = await fetch(`/api/admin/albums/${albumId}/photos`, {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
let photosData = [];
|
||||
try {
|
||||
photosData = await albumsApi.getAlbumPhotos(albumId);
|
||||
if (photosRes.ok) {
|
||||
photosData = await photosRes.json();
|
||||
setPhotos(photosData);
|
||||
} catch (e) { /* 무시 */ }
|
||||
}
|
||||
|
||||
// 티저 이미지 목록 로드
|
||||
const teasersRes = await fetch(`/api/admin/albums/${albumId}/teasers`, {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
let teasersData = [];
|
||||
try {
|
||||
teasersData = await albumsApi.getAlbumTeasers(albumId);
|
||||
if (teasersRes.ok) {
|
||||
teasersData = await teasersRes.json();
|
||||
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);
|
||||
|
|
@ -208,6 +229,12 @@ 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);
|
||||
|
|
@ -477,6 +504,7 @@ function AdminAlbumPhotos() {
|
|||
// 삭제 처리 (기존 사진/티저)
|
||||
const handleDelete = async () => {
|
||||
setDeleting(true);
|
||||
const token = localStorage.getItem('adminToken');
|
||||
|
||||
try {
|
||||
// 사진 ID와 티저 ID 분리
|
||||
|
|
@ -487,12 +515,24 @@ function AdminAlbumPhotos() {
|
|||
|
||||
// 사진 삭제
|
||||
for (const photoId of photoIds) {
|
||||
await albumsApi.deleteAlbumPhoto(albumId, photoId);
|
||||
const res = await fetch(`/api/admin/albums/${albumId}/photos/${photoId}`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error('사진 삭제 실패');
|
||||
}
|
||||
}
|
||||
|
||||
// 티저 삭제
|
||||
for (const teaserId of teaserIds) {
|
||||
await albumsApi.deleteAlbumTeaser(albumId, teaserId);
|
||||
const res = await fetch(`/api/admin/albums/${albumId}/teasers/${teaserId}`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error('티저 삭제 실패');
|
||||
}
|
||||
}
|
||||
|
||||
// UI 상태 업데이트
|
||||
|
|
@ -513,14 +553,8 @@ function AdminAlbumPhotos() {
|
|||
|
||||
if (loading) {
|
||||
return (
|
||||
<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 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>
|
||||
);
|
||||
}
|
||||
|
|
@ -531,20 +565,65 @@ function AdminAlbumPhotos() {
|
|||
<Toast toast={toast} onClose={() => setToast(null)} />
|
||||
|
||||
{/* 삭제 확인 다이얼로그 */}
|
||||
<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>
|
||||
{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>
|
||||
|
||||
{/* 이미지 미리보기 */}
|
||||
<AnimatePresence>
|
||||
|
|
@ -589,7 +668,30 @@ function AdminAlbumPhotos() {
|
|||
</AnimatePresence>
|
||||
|
||||
{/* 헤더 */}
|
||||
<AdminHeader user={user} />
|
||||
<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>
|
||||
|
||||
{/* 메인 콘텐츠 */}
|
||||
<main className="max-w-7xl mx-auto px-6 py-8">
|
||||
|
|
|
|||
|
|
@ -3,16 +3,10 @@ import { useNavigate, Link } from 'react-router-dom';
|
|||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import {
|
||||
Plus, Search, Edit2, Trash2, Image, Music,
|
||||
Home, ChevronRight, Calendar, X
|
||||
Home, ChevronRight, LogOut, Calendar, AlertTriangle, 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();
|
||||
|
|
@ -20,30 +14,49 @@ function AdminAlbums() {
|
|||
const [loading, setLoading] = useState(true);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [user, setUser] = useState(null);
|
||||
const { toast, setToast } = useToast();
|
||||
const [toast, setToast] = useState(null);
|
||||
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(() => {
|
||||
// 로그인 확인
|
||||
if (!authApi.hasToken()) {
|
||||
const token = localStorage.getItem('adminToken');
|
||||
const userData = localStorage.getItem('adminUser');
|
||||
|
||||
if (!token || !userData) {
|
||||
navigate('/admin');
|
||||
return;
|
||||
}
|
||||
|
||||
setUser(authApi.getCurrentUser());
|
||||
setUser(JSON.parse(userData));
|
||||
fetchAlbums();
|
||||
}, [navigate]);
|
||||
|
||||
const fetchAlbums = async () => {
|
||||
try {
|
||||
const data = await getAlbums();
|
||||
setAlbums(data);
|
||||
} catch (error) {
|
||||
console.error('앨범 로드 오류:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
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 handleDelete = async () => {
|
||||
|
|
@ -51,10 +64,21 @@ function AdminAlbums() {
|
|||
|
||||
setDeleting(true);
|
||||
try {
|
||||
await albumsApi.deleteAlbum(deleteDialog.album.id);
|
||||
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('삭제 실패');
|
||||
}
|
||||
|
||||
setToast({ message: `"${deleteDialog.album.title}" 앨범이 삭제되었습니다.`, type: 'success' });
|
||||
setDeleteDialog({ show: false, album: null });
|
||||
fetchAlbums();
|
||||
fetchAlbums(); // 목록 새로고침
|
||||
} catch (error) {
|
||||
console.error('삭제 오류:', error);
|
||||
setToast({ message: '앨범 삭제 중 오류가 발생했습니다.', type: 'error' });
|
||||
|
|
@ -81,23 +105,91 @@ function AdminAlbums() {
|
|||
<Toast toast={toast} onClose={() => setToast(null)} />
|
||||
|
||||
{/* 삭제 확인 다이얼로그 */}
|
||||
<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}
|
||||
/>
|
||||
<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>
|
||||
|
||||
{/* 헤더 */}
|
||||
<AdminHeader user={user} />
|
||||
<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>
|
||||
|
||||
{/* 메인 콘텐츠 */}
|
||||
<main className="max-w-7xl mx-auto px-6 py-8">
|
||||
|
|
|
|||
|
|
@ -2,14 +2,9 @@ import { useState, useEffect } from 'react';
|
|||
import { useNavigate, Link } from 'react-router-dom';
|
||||
import { motion } from 'framer-motion';
|
||||
import {
|
||||
Disc3, Calendar, Users,
|
||||
Disc3, Calendar, Users, LogOut,
|
||||
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 }) {
|
||||
|
|
@ -54,17 +49,27 @@ function AdminDashboard() {
|
|||
|
||||
useEffect(() => {
|
||||
// 로그인 상태 확인
|
||||
if (!authApi.hasToken()) {
|
||||
const token = localStorage.getItem('adminToken');
|
||||
const userData = localStorage.getItem('adminUser');
|
||||
|
||||
if (!token || !userData) {
|
||||
navigate('/admin');
|
||||
return;
|
||||
}
|
||||
|
||||
setUser(authApi.getCurrentUser());
|
||||
setUser(JSON.parse(userData));
|
||||
|
||||
// 토큰 유효성 검증
|
||||
authApi.verifyToken()
|
||||
fetch('/api/admin/verify', {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
})
|
||||
.then(res => {
|
||||
if (!res.ok) throw new Error('Invalid token');
|
||||
return res.json();
|
||||
})
|
||||
.catch(() => {
|
||||
authApi.logout();
|
||||
localStorage.removeItem('adminToken');
|
||||
localStorage.removeItem('adminUser');
|
||||
navigate('/admin');
|
||||
});
|
||||
|
||||
|
|
@ -75,39 +80,56 @@ function AdminDashboard() {
|
|||
const fetchStats = async () => {
|
||||
// 각 통계를 개별적으로 가져와서 하나가 실패해도 다른 것은 표시
|
||||
try {
|
||||
const members = await getMembers();
|
||||
setStats(prev => ({ ...prev, members: members.filter(m => !m.is_former).length }));
|
||||
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 }));
|
||||
}
|
||||
} catch (e) { console.error('멤버 통계 오류:', e); }
|
||||
|
||||
try {
|
||||
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) { /* 개별 앨범 오류 무시 */ }
|
||||
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 }));
|
||||
}
|
||||
setStats(prev => ({ ...prev, photos: totalPhotos }));
|
||||
} catch (e) { console.error('앨범 통계 오류:', e); }
|
||||
|
||||
try {
|
||||
const today = new Date();
|
||||
const schedules = await getSchedules(today.getFullYear(), today.getMonth() + 1);
|
||||
setStats(prev => ({ ...prev, schedules: Array.isArray(schedules) ? schedules.length : 0 }));
|
||||
const schedulesRes = await fetch('/api/schedules');
|
||||
if (schedulesRes.ok) {
|
||||
const schedules = await schedulesRes.json();
|
||||
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 = [
|
||||
{
|
||||
|
|
@ -136,7 +158,30 @@ function AdminDashboard() {
|
|||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
{/* 헤더 */}
|
||||
<AdminHeader user={user} />
|
||||
<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>
|
||||
|
||||
{/* 메인 콘텐츠 */}
|
||||
<main className="max-w-7xl mx-auto px-6 py-8">
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ 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();
|
||||
|
|
@ -15,13 +14,13 @@ function AdminLogin() {
|
|||
|
||||
// 이미 로그인되어 있으면 대시보드로 리다이렉트
|
||||
useEffect(() => {
|
||||
if (!authApi.hasToken()) {
|
||||
setCheckingAuth(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// 토큰 유효성 검증
|
||||
authApi.verifyToken()
|
||||
const token = localStorage.getItem('adminToken');
|
||||
if (token) {
|
||||
// 토큰 유효성 검증
|
||||
fetch('/api/admin/verify', {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
})
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
if (data.valid) {
|
||||
navigate('/admin/dashboard');
|
||||
|
|
@ -30,6 +29,9 @@ function AdminLogin() {
|
|||
}
|
||||
})
|
||||
.catch(() => setCheckingAuth(false));
|
||||
} else {
|
||||
setCheckingAuth(false);
|
||||
}
|
||||
}, [navigate]);
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
|
|
@ -38,7 +40,17 @@ function AdminLogin() {
|
|||
setLoading(true);
|
||||
|
||||
try {
|
||||
const data = await authApi.login(username, password);
|
||||
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 || '로그인에 실패했습니다.');
|
||||
}
|
||||
|
||||
// JWT 토큰 저장
|
||||
localStorage.setItem('adminToken', data.token);
|
||||
|
|
|
|||
|
|
@ -2,15 +2,247 @@ import { useState, useEffect, useRef } from 'react';
|
|||
import { useNavigate, useParams, Link } from 'react-router-dom';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import {
|
||||
Save, Upload,
|
||||
Home, ChevronRight, User, Instagram, Calendar, Briefcase
|
||||
Save, Upload, LogOut,
|
||||
Home, ChevronRight, ChevronLeft, ChevronDown, User, Instagram, Calendar, Briefcase
|
||||
} 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';
|
||||
import * as authApi from '../../../api/admin/auth';
|
||||
import * as membersApi from '../../../api/admin/members';
|
||||
|
||||
// 커스텀 데이트픽커 컴포넌트
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
function AdminMemberEdit() {
|
||||
const navigate = useNavigate();
|
||||
|
|
@ -18,7 +250,7 @@ function AdminMemberEdit() {
|
|||
const [user, setUser] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const { toast, setToast } = useToast();
|
||||
const [toast, setToast] = useState(null);
|
||||
const [imagePreview, setImagePreview] = useState(null);
|
||||
const [imageFile, setImageFile] = useState(null);
|
||||
|
||||
|
|
@ -30,20 +262,38 @@ function AdminMemberEdit() {
|
|||
is_former: false
|
||||
});
|
||||
|
||||
// Toast 자동 숨김
|
||||
useEffect(() => {
|
||||
if (toast) {
|
||||
const timer = setTimeout(() => setToast(null), 3000);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [toast]);
|
||||
|
||||
useEffect(() => {
|
||||
// 로그인 확인
|
||||
if (!authApi.hasToken()) {
|
||||
const token = localStorage.getItem('adminToken');
|
||||
const userData = localStorage.getItem('adminUser');
|
||||
|
||||
if (!token || !userData) {
|
||||
navigate('/admin');
|
||||
return;
|
||||
}
|
||||
|
||||
setUser(authApi.getCurrentUser());
|
||||
setUser(JSON.parse(userData));
|
||||
fetchMember();
|
||||
}, [navigate, name]);
|
||||
|
||||
const fetchMember = async () => {
|
||||
try {
|
||||
const data = await membersApi.getMember(encodeURIComponent(name));
|
||||
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();
|
||||
setFormData({
|
||||
name: data.name || '',
|
||||
birth_date: data.birth_date ? data.birth_date.split('T')[0] : '',
|
||||
|
|
@ -60,6 +310,12 @@ function AdminMemberEdit() {
|
|||
}
|
||||
};
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem('adminToken');
|
||||
localStorage.removeItem('adminUser');
|
||||
navigate('/admin');
|
||||
};
|
||||
|
||||
const handleImageChange = (e) => {
|
||||
const file = e.target.files[0];
|
||||
if (file) {
|
||||
|
|
@ -75,6 +331,7 @@ function AdminMemberEdit() {
|
|||
setSaving(true);
|
||||
|
||||
try {
|
||||
const token = localStorage.getItem('adminToken');
|
||||
const formDataToSend = new FormData();
|
||||
|
||||
formDataToSend.append('name', formData.name);
|
||||
|
|
@ -87,7 +344,14 @@ function AdminMemberEdit() {
|
|||
formDataToSend.append('image', imageFile);
|
||||
}
|
||||
|
||||
await membersApi.updateMember(encodeURIComponent(name), formDataToSend);
|
||||
const res = await fetch(`/api/admin/members/${encodeURIComponent(name)}`, {
|
||||
method: 'PUT',
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
body: formDataToSend
|
||||
});
|
||||
|
||||
if (!res.ok) throw new Error('수정 실패');
|
||||
|
||||
setToast({ message: '멤버 정보가 수정되었습니다.', type: 'success' });
|
||||
setTimeout(() => navigate('/admin/members'), 1000);
|
||||
} catch (error) {
|
||||
|
|
@ -104,7 +368,30 @@ function AdminMemberEdit() {
|
|||
<Toast toast={toast} onClose={() => setToast(null)} />
|
||||
|
||||
{/* 헤더 */}
|
||||
<AdminHeader user={user} />
|
||||
<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>
|
||||
|
||||
{/* 메인 콘텐츠 */}
|
||||
<main className="max-w-4xl mx-auto px-6 py-8">
|
||||
|
|
|
|||
|
|
@ -2,19 +2,25 @@ import { useState, useEffect } from 'react';
|
|||
import { useNavigate, Link } from 'react-router-dom';
|
||||
import { motion } from 'framer-motion';
|
||||
import {
|
||||
Edit2,
|
||||
Edit2, LogOut,
|
||||
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 } = useToast();
|
||||
const [toast, setToast] = useState(null);
|
||||
|
||||
// Toast 자동 숨김
|
||||
useEffect(() => {
|
||||
if (toast) {
|
||||
const timer = setTimeout(() => setToast(null), 3000);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [toast]);
|
||||
|
||||
useEffect(() => {
|
||||
// 로그인 확인
|
||||
|
|
@ -43,6 +49,12 @@ 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);
|
||||
|
|
@ -98,7 +110,30 @@ function AdminMembers() {
|
|||
<Toast toast={toast} onClose={() => setToast(null)} />
|
||||
|
||||
{/* 헤더 */}
|
||||
<AdminHeader user={user} />
|
||||
<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>
|
||||
|
||||
{/* 메인 콘텐츠 */}
|
||||
<main className="max-w-7xl mx-auto px-6 py-8">
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -2,54 +2,27 @@ import { useState, useEffect } from 'react';
|
|||
import { useNavigate, Link } from 'react-router-dom';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import {
|
||||
Home, ChevronRight, Bot, Play, Square,
|
||||
LogOut, 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 } = useToast();
|
||||
const [toast, setToast] = useState(null);
|
||||
const [bots, setBots] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [isInitialLoad, setIsInitialLoad] = useState(true); // 첫 로드 여부 (애니메이션용)
|
||||
const [syncing, setSyncing] = useState(null); // 동기화 중인 봇 ID
|
||||
const [quotaWarning, setQuotaWarning] = useState(null); // 할당량 경고 상태
|
||||
|
||||
// Toast 자동 숨김
|
||||
useEffect(() => {
|
||||
if (toast) {
|
||||
const timer = setTimeout(() => setToast(null), 3000);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [toast]);
|
||||
|
||||
useEffect(() => {
|
||||
const token = localStorage.getItem('adminToken');
|
||||
|
|
@ -62,15 +35,21 @@ function AdminScheduleBots() {
|
|||
|
||||
setUser(JSON.parse(userData));
|
||||
fetchBots();
|
||||
fetchQuotaWarning();
|
||||
}, [navigate]);
|
||||
|
||||
// 봇 목록 조회
|
||||
const fetchBots = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await botsApi.getBots();
|
||||
setBots(data);
|
||||
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);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('봇 목록 조회 오류:', error);
|
||||
setToast({ type: 'error', message: '봇 목록을 불러올 수 없습니다.' });
|
||||
|
|
@ -79,69 +58,65 @@ function AdminScheduleBots() {
|
|||
}
|
||||
};
|
||||
|
||||
// 할당량 경고 상태 조회
|
||||
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 handleLogout = () => {
|
||||
localStorage.removeItem('adminToken');
|
||||
localStorage.removeItem('adminUser');
|
||||
navigate('/admin');
|
||||
};
|
||||
|
||||
// 봇 시작/정지 토글
|
||||
const toggleBot = async (botId, currentStatus, botName) => {
|
||||
try {
|
||||
const token = localStorage.getItem('adminToken');
|
||||
const action = currentStatus === 'running' ? 'stop' : 'start';
|
||||
|
||||
if (action === 'start') {
|
||||
await botsApi.startBot(botId);
|
||||
} else {
|
||||
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} 봇이 정지되었습니다.`
|
||||
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(); // 목록 새로고침
|
||||
} else {
|
||||
const data = await response.json();
|
||||
setToast({ type: 'error', message: data.error || '작업 실패' });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('봇 토글 오류:', error);
|
||||
setToast({ type: 'error', message: error.message || '작업 중 오류가 발생했습니다.' });
|
||||
setToast({ type: 'error', message: '작업 중 오류가 발생했습니다.' });
|
||||
}
|
||||
};
|
||||
|
||||
// 전체 동기화
|
||||
const handleSyncAllVideos = async (botId) => {
|
||||
const syncAllVideos = async (botId) => {
|
||||
setSyncing(botId);
|
||||
try {
|
||||
const data = await botsApi.syncAllVideos(botId);
|
||||
setToast({
|
||||
type: 'success',
|
||||
message: `${data.addedCount}개 일정이 추가되었습니다. (전체 ${data.total}개)`
|
||||
const token = localStorage.getItem('adminToken');
|
||||
const response = await fetch(`/api/admin/bots/${botId}/sync-all`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
|
||||
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: error.message || '동기화 중 오류가 발생했습니다.' });
|
||||
fetchBots();
|
||||
setToast({ type: 'error', message: '동기화 중 오류가 발생했습니다.' });
|
||||
fetchBots(); // 오류에도 목록 갱신
|
||||
} finally {
|
||||
setSyncing(null);
|
||||
}
|
||||
|
|
@ -218,7 +193,30 @@ function AdminScheduleBots() {
|
|||
<Toast toast={toast} onClose={() => setToast(null)} />
|
||||
|
||||
{/* 헤더 */}
|
||||
<AdminHeader user={user} />
|
||||
<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>
|
||||
|
||||
{/* 메인 콘텐츠 */}
|
||||
<main className="max-w-7xl mx-auto px-6 py-8">
|
||||
|
|
@ -267,36 +265,13 @@ 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={() => { setIsInitialLoad(true); fetchBots(); }}
|
||||
onClick={fetchBots}
|
||||
disabled={loading}
|
||||
className="p-2 hover:bg-gray-100 rounded-lg transition-colors text-gray-500 hover:text-gray-700 disabled:opacity-50"
|
||||
>
|
||||
|
|
@ -324,25 +299,16 @@ function AdminScheduleBots() {
|
|||
return (
|
||||
<motion.div
|
||||
key={bot.id}
|
||||
initial={isInitialLoad ? { opacity: 0, scale: 0.95 } : false}
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
transition={isInitialLoad ? { delay: index * 0.05 } : { duration: 0.15 }}
|
||||
onAnimationComplete={() => isInitialLoad && index === bots.length - 1 && setIsInitialLoad(false)}
|
||||
transition={{ delay: index * 0.05 }}
|
||||
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 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 className="w-10 h-10 rounded-lg bg-red-50 flex items-center justify-center">
|
||||
<Youtube size={20} className="text-red-500" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-bold text-gray-900">{bot.name}</h3>
|
||||
|
|
@ -359,33 +325,16 @@ function AdminScheduleBots() {
|
|||
|
||||
{/* 통계 정보 */}
|
||||
<div className="grid grid-cols-3 divide-x divide-gray-100 bg-gray-50/50">
|
||||
{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">{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>
|
||||
|
|
@ -405,7 +354,7 @@ function AdminScheduleBots() {
|
|||
<div className="p-4 border-t border-gray-100">
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => handleSyncAllVideos(bot.id)}
|
||||
onClick={() => syncAllVideos(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"
|
||||
>
|
||||
|
|
|
|||
|
|
@ -1,14 +1,9 @@
|
|||
import { useState, useEffect } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { motion, AnimatePresence, Reorder } from 'framer-motion';
|
||||
import { Home, ChevronRight, Plus, Edit3, Trash2, GripVertical, X } from 'lucide-react';
|
||||
import { LogOut, Home, ChevronRight, Plus, Edit3, Trash2, GripVertical, X, AlertTriangle } 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 = [
|
||||
|
|
@ -41,7 +36,13 @@ function AdminScheduleCategory() {
|
|||
const [user, setUser] = useState(null);
|
||||
const [categories, setCategories] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const { toast, setToast, showSuccess, showError } = useToast();
|
||||
const [toast, setToast] = useState(null);
|
||||
|
||||
// 토스트 표시 (3초 후 자동 닫힘)
|
||||
const showToast = (type, message) => {
|
||||
setToast({ type, message });
|
||||
setTimeout(() => setToast(null), 3000);
|
||||
};
|
||||
|
||||
// 모달 상태
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
|
|
@ -57,36 +58,48 @@ function AdminScheduleCategory() {
|
|||
|
||||
// 사용자 인증 확인
|
||||
useEffect(() => {
|
||||
if (!authApi.hasToken()) {
|
||||
const token = localStorage.getItem('adminToken');
|
||||
if (!token) {
|
||||
navigate('/admin');
|
||||
return;
|
||||
}
|
||||
|
||||
authApi.verifyToken()
|
||||
.then(data => {
|
||||
if (data.valid) {
|
||||
setUser(data.user);
|
||||
fetchCategories();
|
||||
} else {
|
||||
navigate('/admin');
|
||||
}
|
||||
})
|
||||
.catch(() => navigate('/admin'));
|
||||
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'));
|
||||
}, [navigate]);
|
||||
|
||||
// 카테고리 목록 조회
|
||||
const fetchCategories = async () => {
|
||||
try {
|
||||
const data = await categoriesApi.getCategories();
|
||||
const res = await fetch('/api/admin/schedule-categories');
|
||||
const data = await res.json();
|
||||
setCategories(data);
|
||||
} catch (error) {
|
||||
console.error('카테고리 조회 오류:', error);
|
||||
showError('카테고리를 불러오는데 실패했습니다.');
|
||||
showToast('error', '카테고리를 불러오는데 실패했습니다.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 로그아웃
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem('adminToken');
|
||||
localStorage.removeItem('adminUser');
|
||||
navigate('/admin');
|
||||
};
|
||||
|
||||
// 모달 열기 (추가/수정)
|
||||
const openModal = (category = null) => {
|
||||
if (category) {
|
||||
|
|
@ -103,7 +116,7 @@ function AdminScheduleCategory() {
|
|||
// 카테고리 저장
|
||||
const handleSave = async () => {
|
||||
if (!formData.name.trim()) {
|
||||
showError('카테고리 이름을 입력해주세요.');
|
||||
showToast('error', '카테고리 이름을 입력해주세요.');
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -113,22 +126,37 @@ function AdminScheduleCategory() {
|
|||
&& cat.id !== editingCategory?.id
|
||||
);
|
||||
if (isDuplicate) {
|
||||
showError('이미 존재하는 카테고리입니다.');
|
||||
showToast('error', '이미 존재하는 카테고리입니다.');
|
||||
return;
|
||||
}
|
||||
|
||||
const token = localStorage.getItem('adminToken');
|
||||
|
||||
try {
|
||||
if (editingCategory) {
|
||||
await categoriesApi.updateCategory(editingCategory.id, formData);
|
||||
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();
|
||||
} else {
|
||||
await categoriesApi.createCategory(formData);
|
||||
const error = await res.json();
|
||||
showToast('error', error.error || '저장에 실패했습니다.');
|
||||
}
|
||||
showSuccess(editingCategory ? '카테고리가 수정되었습니다.' : '카테고리가 추가되었습니다.');
|
||||
setModalOpen(false);
|
||||
fetchCategories();
|
||||
} catch (error) {
|
||||
console.error('저장 오류:', error);
|
||||
showError(error.message || '저장에 실패했습니다.');
|
||||
showToast('error', '저장 중 오류가 발생했습니다.');
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -142,15 +170,26 @@ function AdminScheduleCategory() {
|
|||
const handleDelete = async () => {
|
||||
if (!deleteTarget) return;
|
||||
|
||||
const token = localStorage.getItem('adminToken');
|
||||
|
||||
try {
|
||||
await categoriesApi.deleteCategory(deleteTarget.id);
|
||||
showSuccess('카테고리가 삭제되었습니다.');
|
||||
setDeleteDialogOpen(false);
|
||||
setDeleteTarget(null);
|
||||
fetchCategories();
|
||||
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 || '삭제에 실패했습니다.');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('삭제 오류:', error);
|
||||
showError(error.message || '삭제에 실패했습니다.');
|
||||
showToast('error', '삭제 중 오류가 발생했습니다.');
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -164,8 +203,16 @@ function AdminScheduleCategory() {
|
|||
sort_order: idx + 1
|
||||
}));
|
||||
|
||||
const token = localStorage.getItem('adminToken');
|
||||
try {
|
||||
await categoriesApi.reorderCategories(orders);
|
||||
await fetch('/api/admin/schedule-categories-order', {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({ orders })
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('순서 업데이트 오류:', error);
|
||||
fetchCategories(); // 실패시 원래 데이터 다시 불러오기
|
||||
|
|
@ -185,7 +232,30 @@ function AdminScheduleCategory() {
|
|||
<Toast toast={toast} onClose={() => setToast(null)} />
|
||||
|
||||
{/* 헤더 */}
|
||||
<AdminHeader user={user} />
|
||||
<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>
|
||||
|
||||
{/* 메인 콘텐츠 */}
|
||||
<main className="max-w-4xl mx-auto px-6 py-8">
|
||||
|
|
@ -447,19 +517,54 @@ function AdminScheduleCategory() {
|
|||
</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>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<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>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,11 +0,0 @@
|
|||
/* PC 전용 스타일 - body.is-pc 클래스가 있을 때만 적용 */
|
||||
|
||||
/* PC 항상 스크롤바 공간 확보 - 화면 밀림 방지 */
|
||||
body.is-pc {
|
||||
overflow-y: scroll;
|
||||
}
|
||||
|
||||
/* PC 최소 너비 설정 */
|
||||
body.is-pc #root {
|
||||
min-width: 1440px;
|
||||
}
|
||||
|
|
@ -10,12 +10,9 @@ const useScheduleStore = create((set) => ({
|
|||
|
||||
// 필터 및 선택
|
||||
selectedCategories: [],
|
||||
selectedDate: null, // null이면 전체보기, undefined이면 getTodayKST() 사용
|
||||
selectedDate: null, // null이면 getTodayKST() 사용
|
||||
currentDate: new Date(),
|
||||
|
||||
// 스크롤 위치
|
||||
scrollPosition: 0,
|
||||
|
||||
// 상태 업데이트 함수
|
||||
setSearchInput: (value) => set({ searchInput: value }),
|
||||
setSearchTerm: (value) => set({ searchTerm: value }),
|
||||
|
|
@ -23,7 +20,6 @@ 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: () =>
|
||||
|
|
@ -34,7 +30,6 @@ const useScheduleStore = create((set) => ({
|
|||
selectedCategories: [],
|
||||
selectedDate: null,
|
||||
currentDate: new Date(),
|
||||
scrollPosition: 0,
|
||||
}),
|
||||
}));
|
||||
|
||||
|
|
|
|||
|
|
@ -1,81 +0,0 @@
|
|||
/**
|
||||
* 날짜 관련 유틸리티 함수
|
||||
* 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 };
|
||||
Loading…
Add table
Reference in a new issue