feat: 로또 추천 API, 텔레그램 봇 연동, 관리자 페이지 추가
- 로또 번호 추천 구독자 전용 페이지 (/services/lotto/recommend) - NAS 몬테카를로 API 연동 + 클라이언트 사이드 폴백 - 무료 미리보기 1개 + 구독자용 프리미엄 번호 추천 - 구독 플랜 변경: 골드(900원)/플래티넘(2,900원)/다이아(9,900원) - 텔레그램 봇 연동: 연결/해제, 웹훅, /start 명령 처리 - 마이페이지 텔레그램 연결 UI + 가이드 모달 - 관리자 페이지 (/admin): 대시보드, 회원, 서비스, 문의 관리 - Supabase 마이그레이션: profiles 텔레그램 컬럼, 신규 상품 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
91
app/api/lotto/dashboard/route.ts
Normal file
91
app/api/lotto/dashboard/route.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
|
||||
const LOTTO_PRODUCT_IDS = ['lotto_gold', 'lotto_platinum', 'lotto_diamond'];
|
||||
|
||||
async function nasGet(path: string): Promise<unknown> {
|
||||
const base = process.env.NAS_LOTTO_API_URL;
|
||||
if (!base) throw new Error('NAS_URL_NOT_CONFIGURED');
|
||||
|
||||
const headers: Record<string, string> = {};
|
||||
if (process.env.NAS_LOTTO_API_KEY) {
|
||||
headers['Authorization'] = `Bearer ${process.env.NAS_LOTTO_API_KEY}`;
|
||||
}
|
||||
|
||||
const res = await fetch(`${base}${path}`, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
signal: AbortSignal.timeout(10000),
|
||||
});
|
||||
|
||||
if (!res.ok) throw new Error(`NAS_${res.status}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/lotto/dashboard
|
||||
* 페이지 초기 로드용: latest + analysis + simulation 이력 병렬 조회
|
||||
*
|
||||
* Response:
|
||||
* {
|
||||
* plan: string,
|
||||
* latest: { drawNo, date, numbers, bonus, metrics },
|
||||
* analysis: { total_draws, mean_sum, std_sum, number_stats[] },
|
||||
* simulation: { runs[] }
|
||||
* }
|
||||
*/
|
||||
export async function GET() {
|
||||
try {
|
||||
// 1. 인증
|
||||
const supabase = await createClient();
|
||||
const { data: { user }, error: authError } = await supabase.auth.getUser();
|
||||
if (authError || !user) {
|
||||
return NextResponse.json({ error: 'UNAUTHORIZED' }, { status: 401 });
|
||||
}
|
||||
|
||||
// 2. 구독 확인
|
||||
const { data: orders } = await supabase
|
||||
.from('orders')
|
||||
.select('id, product_id, status, created_at')
|
||||
.eq('user_id', user.id)
|
||||
.eq('status', 'paid')
|
||||
.in('product_id', LOTTO_PRODUCT_IDS)
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(1);
|
||||
|
||||
if (!orders || orders.length === 0) {
|
||||
return NextResponse.json({ error: 'NOT_SUBSCRIBED' }, { status: 403 });
|
||||
}
|
||||
|
||||
const order = orders[0];
|
||||
const diffDays =
|
||||
(Date.now() - new Date(order.created_at).getTime()) / (1000 * 60 * 60 * 24);
|
||||
const maxDays = order.product_id === 'lotto_annual' ? 366 : 31;
|
||||
|
||||
if (diffDays > maxDays) {
|
||||
return NextResponse.json({ error: 'NOT_SUBSCRIBED' }, { status: 403 });
|
||||
}
|
||||
|
||||
// 3. NAS 병렬 조회
|
||||
const [latest, analysis, simulation] = await Promise.allSettled([
|
||||
nasGet('/api/lotto/latest'),
|
||||
nasGet('/api/lotto/analysis'),
|
||||
nasGet('/api/lotto/simulation'),
|
||||
]);
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
plan: order.product_id,
|
||||
latest: latest.status === 'fulfilled' ? latest.value : null,
|
||||
analysis: analysis.status === 'fulfilled' ? analysis.value : null,
|
||||
simulation: simulation.status === 'fulfilled' ? simulation.value : null,
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
const e = err as { name?: string; message?: string };
|
||||
if (e?.name === 'TimeoutError') {
|
||||
return NextResponse.json({ error: 'NAS_TIMEOUT' }, { status: 504 });
|
||||
}
|
||||
console.error('Lotto dashboard error:', err);
|
||||
return NextResponse.json({ error: 'INTERNAL_ERROR' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
47
app/api/lotto/preview/route.ts
Normal file
47
app/api/lotto/preview/route.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
/**
|
||||
* GET /api/lotto/preview
|
||||
* 인증 없이 NAS /api/lotto/recommend 단일 호출 (맛보기용 무료 추천)
|
||||
* NAS 미연결 시 → { error: 'NAS_UNAVAILABLE' } 503 반환
|
||||
* 클라이언트에서 이 경우 자체 Monte Carlo 폴백 처리
|
||||
*/
|
||||
export async function GET() {
|
||||
const base = process.env.NAS_LOTTO_API_URL;
|
||||
|
||||
if (!base) {
|
||||
return NextResponse.json({ error: 'NAS_UNAVAILABLE' }, { status: 503 });
|
||||
}
|
||||
|
||||
try {
|
||||
const headers: Record<string, string> = {};
|
||||
if (process.env.NAS_LOTTO_API_KEY) {
|
||||
headers['Authorization'] = `Bearer ${process.env.NAS_LOTTO_API_KEY}`;
|
||||
}
|
||||
|
||||
const res = await fetch(`${base}/api/lotto/recommend`, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
signal: AbortSignal.timeout(8000),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
console.warn(`[lotto/preview] NAS returned ${res.status}`);
|
||||
return NextResponse.json({ error: 'NAS_UNAVAILABLE' }, { status: 503 });
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
source: 'nas',
|
||||
numbers: data.numbers ?? [],
|
||||
metrics: data.metrics ?? null,
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
// ECONNREFUSED, 타임아웃 등 — 클라이언트 폴백 신호
|
||||
const e = err as { name?: string; code?: string; message?: string };
|
||||
console.warn('[lotto/preview] NAS unreachable:', e?.code ?? e?.message ?? e?.name);
|
||||
return NextResponse.json({ error: 'NAS_UNAVAILABLE' }, { status: 503 });
|
||||
}
|
||||
}
|
||||
106
app/api/lotto/recommend/route.ts
Normal file
106
app/api/lotto/recommend/route.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
|
||||
const LOTTO_PRODUCT_IDS = ['lotto_gold', 'lotto_platinum', 'lotto_diamond'];
|
||||
|
||||
/** 구독 유효 여부 확인 */
|
||||
async function checkSubscription(supabase: Awaited<ReturnType<typeof createClient>>, userId: string) {
|
||||
const { data: orders } = await supabase
|
||||
.from('orders')
|
||||
.select('id, product_id, status, created_at')
|
||||
.eq('user_id', userId)
|
||||
.eq('status', 'paid')
|
||||
.in('product_id', LOTTO_PRODUCT_IDS)
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(1);
|
||||
|
||||
if (!orders || orders.length === 0) return null;
|
||||
|
||||
const order = orders[0];
|
||||
const diffDays =
|
||||
(Date.now() - new Date(order.created_at).getTime()) / (1000 * 60 * 60 * 24);
|
||||
const maxDays = order.product_id === 'lotto_annual' ? 366 : 31;
|
||||
|
||||
return diffDays <= maxDays ? order : null;
|
||||
}
|
||||
|
||||
/** NAS API 호출 헬퍼 */
|
||||
async function nasGet(path: string): Promise<Response> {
|
||||
const base = process.env.NAS_LOTTO_API_URL;
|
||||
if (!base) throw new Error('NAS_URL_NOT_CONFIGURED');
|
||||
|
||||
const headers: Record<string, string> = {};
|
||||
if (process.env.NAS_LOTTO_API_KEY) {
|
||||
headers['Authorization'] = `Bearer ${process.env.NAS_LOTTO_API_KEY}`;
|
||||
}
|
||||
|
||||
return fetch(`${base}${path}`, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/lotto/recommend
|
||||
* Query params:
|
||||
* mode = "single" (기본) | "batch" | "best"
|
||||
*
|
||||
* single → NAS GET /api/lotto/recommend
|
||||
* batch → NAS GET /api/lotto/recommend/batch (5개 조합)
|
||||
* best → NAS GET /api/lotto/best (Monte Carlo 상위 20쌍)
|
||||
*/
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
// 1. 세션 확인
|
||||
const supabase = await createClient();
|
||||
const { data: { user }, error: authError } = await supabase.auth.getUser();
|
||||
|
||||
if (authError || !user) {
|
||||
return NextResponse.json({ error: 'UNAUTHORIZED' }, { status: 401 });
|
||||
}
|
||||
|
||||
// 2. 구독 확인
|
||||
const order = await checkSubscription(supabase, user.id);
|
||||
if (!order) {
|
||||
return NextResponse.json({ error: 'NOT_SUBSCRIBED' }, { status: 403 });
|
||||
}
|
||||
|
||||
const mode = req.nextUrl.searchParams.get('mode') ?? 'single';
|
||||
|
||||
// 3. NAS API 호출
|
||||
const nasPath =
|
||||
mode === 'batch'
|
||||
? '/api/lotto/recommend/batch'
|
||||
: mode === 'best'
|
||||
? '/api/lotto/best'
|
||||
: '/api/lotto/recommend';
|
||||
|
||||
const nasRes = await nasGet(nasPath);
|
||||
|
||||
if (!nasRes.ok) {
|
||||
const errText = await nasRes.text();
|
||||
console.error('NAS API error:', nasRes.status, errText);
|
||||
return NextResponse.json({ error: 'NAS_API_ERROR' }, { status: 502 });
|
||||
}
|
||||
|
||||
const nasData = await nasRes.json();
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
plan: order.product_id,
|
||||
mode,
|
||||
...nasData,
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
const e = err as { name?: string; message?: string };
|
||||
if (e?.name === 'TimeoutError') {
|
||||
return NextResponse.json({ error: 'NAS_TIMEOUT' }, { status: 504 });
|
||||
}
|
||||
if (e?.message === 'NAS_URL_NOT_CONFIGURED') {
|
||||
return NextResponse.json({ error: 'NAS_URL_NOT_CONFIGURED' }, { status: 500 });
|
||||
}
|
||||
console.error('Lotto recommend error:', err);
|
||||
return NextResponse.json({ error: 'INTERNAL_ERROR' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user