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:
2026-03-16 02:12:17 +09:00
parent 2469063979
commit a95715ec6b
32 changed files with 3060 additions and 35 deletions

View File

@@ -0,0 +1,52 @@
import { NextResponse } from 'next/server';
import { createAdminClient } from '@/lib/supabase/admin';
import { verifyAdminTokenNode } from '@/lib/admin-auth';
import { cookies } from 'next/headers';
export const runtime = 'nodejs';
async function checkAuth() {
const cookieStore = await cookies();
const token = cookieStore.get('admin_token')?.value;
return token && verifyAdminTokenNode(token);
}
export async function GET() {
if (!(await checkAuth())) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const supabase = createAdminClient();
const { data, error } = await supabase
.from('contact_requests')
.select('*')
.order('created_at', { ascending: false })
.limit(100);
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
return NextResponse.json({ contacts: data ?? [] });
}
export async function PATCH(request: Request) {
if (!(await checkAuth())) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { id, status } = await request.json();
const supabase = createAdminClient();
const { error } = await supabase
.from('contact_requests')
.update({ status })
.eq('id', id);
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
return NextResponse.json({ success: true });
}

View File

@@ -0,0 +1,29 @@
import { NextResponse } from 'next/server';
import { createAdminToken, checkAdminCredentials } from '@/lib/admin-auth';
export const runtime = 'nodejs';
export async function POST(request: Request) {
try {
const { id, password } = await request.json();
if (!checkAdminCredentials(id, password)) {
return NextResponse.json({ error: '아이디 또는 비밀번호가 올바르지 않습니다.' }, { status: 401 });
}
const token = createAdminToken();
const response = NextResponse.json({ success: true });
response.cookies.set('admin_token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 60 * 60 * 24, // 24시간
path: '/',
});
return response;
} catch {
return NextResponse.json({ error: '서버 오류가 발생했습니다.' }, { status: 500 });
}
}

View File

@@ -0,0 +1,11 @@
import { NextResponse } from 'next/server';
export async function POST() {
const response = NextResponse.json({ success: true });
response.cookies.set('admin_token', '', {
httpOnly: true,
maxAge: 0,
path: '/',
});
return response;
}

View File

@@ -0,0 +1,40 @@
import { NextResponse } from 'next/server';
import { createAdminClient } from '@/lib/supabase/admin';
import { verifyAdminTokenNode } from '@/lib/admin-auth';
import { cookies } from 'next/headers';
export const runtime = 'nodejs';
export async function GET() {
const cookieStore = await cookies();
const token = cookieStore.get('admin_token')?.value;
if (!token || !verifyAdminTokenNode(token)) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const supabase = createAdminClient();
const { data: profiles, error } = await supabase
.from('profiles')
.select('id, email, full_name, created_at')
.order('created_at', { ascending: false })
.limit(100);
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
// 각 회원의 주문 수 + 결제 금액 집계
const enriched = await Promise.all(
(profiles ?? []).map(async (p: { id: string; email: string; full_name: string; created_at: string }) => {
const [ordersRes, paymentsRes] = await Promise.all([
supabase.from('orders').select('id', { count: 'exact', head: true }).eq('user_id', p.id).eq('status', 'paid'),
supabase.from('payments').select('amount').eq('user_id', p.id).eq('status', 'paid'),
]);
const totalPaid = (paymentsRes.data ?? []).reduce((s: number, x: { amount: number }) => s + x.amount, 0);
return { ...p, orderCount: ordersRes.count ?? 0, totalPaid };
})
);
return NextResponse.json({ members: enriched });
}

View File

@@ -0,0 +1,60 @@
import { NextResponse } from 'next/server';
import { createAdminClient } from '@/lib/supabase/admin';
import { verifyAdminTokenNode } from '@/lib/admin-auth';
import { cookies } from 'next/headers';
export const runtime = 'nodejs';
async function checkAuth() {
const cookieStore = await cookies();
const token = cookieStore.get('admin_token')?.value;
return token && verifyAdminTokenNode(token);
}
export async function GET() {
if (!(await checkAuth())) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const supabase = createAdminClient();
const { data, error } = await supabase
.from('service_settings')
.select('*')
.order('order_index');
if (error) {
// 테이블이 없으면 기본값 반환
return NextResponse.json({ services: DEFAULT_SERVICES });
}
return NextResponse.json({ services: data?.length ? data : DEFAULT_SERVICES });
}
export async function PATCH(request: Request) {
if (!(await checkAuth())) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { id, is_active } = await request.json();
const supabase = createAdminClient();
const { error } = await supabase
.from('service_settings')
.upsert({ id, is_active, updated_at: new Date().toISOString() });
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
return NextResponse.json({ success: true });
}
const DEFAULT_SERVICES = [
{ id: 'saju', name: 'AI 사주 분석', description: '사주 입력 및 AI 해석 서비스', is_active: true, order_index: 1 },
{ id: 'lotto', name: '로또 번호 추천', description: '빅데이터 기반 로또 번호 분석', is_active: true, order_index: 2 },
{ id: 'stock', name: '주식 자동매매', description: '텔레그램 연동 자동매매 프로그램', is_active: true, order_index: 3 },
{ id: 'automation', name: '업무 자동화 RPA', description: '반복 업무 자동화 개발', is_active: true, order_index: 4 },
{ id: 'prompt', name: '프롬프트 엔지니어링', description: 'AI 프롬프트 설계 서비스', is_active: true, order_index: 5 },
{ id: 'freelance', name: '외주 개발', description: '맞춤형 소프트웨어 개발', is_active: true, order_index: 6 },
];

View File

@@ -0,0 +1,51 @@
import { NextResponse } from 'next/server';
import { createAdminClient } from '@/lib/supabase/admin';
import { verifyAdminTokenNode } from '@/lib/admin-auth';
import { cookies } from 'next/headers';
export const runtime = 'nodejs';
export async function GET() {
const cookieStore = await cookies();
const token = cookieStore.get('admin_token')?.value;
if (!token || !verifyAdminTokenNode(token)) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const supabase = createAdminClient();
// 병렬 쿼리
const [profilesRes, ordersRes, paymentsRes, contactsRes, monthlyRes] = await Promise.all([
supabase.from('profiles').select('id', { count: 'exact', head: true }),
supabase.from('orders').select('id', { count: 'exact', head: true }).eq('status', 'paid'),
supabase.from('payments').select('amount').eq('status', 'paid'),
supabase.from('contact_requests').select('id', { count: 'exact', head: true }).eq('status', 'pending'),
supabase.from('payments').select('amount, created_at').eq('status', 'paid').order('created_at', { ascending: true }),
]);
const totalMembers = profilesRes.count ?? 0;
const totalOrders = ordersRes.count ?? 0;
const totalRevenue = (paymentsRes.data ?? []).reduce((sum: number, p: { amount: number }) => sum + p.amount, 0);
const pendingContacts = contactsRes.count ?? 0;
// 최근 6개월 월별 수익 집계
const monthly: Record<string, number> = {};
const now = new Date();
for (let i = 5; i >= 0; i--) {
const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
monthly[key] = 0;
}
for (const p of (monthlyRes.data ?? []) as Array<{ amount: number; created_at: string }>) {
const d = new Date(p.created_at);
const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
if (key in monthly) {
monthly[key] += p.amount;
}
}
const monthlyChart = Object.entries(monthly).map(([month, revenue]) => ({ month, revenue }));
return NextResponse.json({ totalMembers, totalOrders, totalRevenue, pendingContacts, monthlyChart });
}

View 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 });
}
}

View 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 });
}
}

View 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 });
}
}

View File

@@ -0,0 +1,76 @@
import { NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
/**
* POST /api/telegram/connect
* 인증된 유저에게 15분 유효 연결 토큰을 발급하고
* 텔레그램 봇 딥링크를 반환합니다.
*
* Response: { deepLink: string, expiresAt: string }
*/
export async function POST() {
const supabase = await createClient();
const { data: { user }, error: authError } = await supabase.auth.getUser();
if (authError || !user) {
return NextResponse.json({ error: 'UNAUTHORIZED' }, { status: 401 });
}
const botUsername = process.env.TELEGRAM_BOT_USERNAME;
if (!botUsername) {
return NextResponse.json({ error: 'TELEGRAM_BOT_USERNAME이 설정되지 않았습니다.' }, { status: 500 });
}
// 15분 유효 토큰 생성
const token = crypto.randomUUID().replace(/-/g, '');
const expiresAt = new Date(Date.now() + 15 * 60 * 1000).toISOString();
// 프로필 upsert (없는 경우 대비)
await supabase
.from('profiles')
.upsert({ id: user.id, email: user.email }, { onConflict: 'id' });
const { error: updateError } = await supabase
.from('profiles')
.update({
telegram_connect_token: token,
telegram_token_expires: expiresAt,
})
.eq('id', user.id);
if (updateError) {
console.error('telegram connect token update error:', updateError);
return NextResponse.json({ error: 'DB_ERROR' }, { status: 500 });
}
const deepLink = `https://t.me/${botUsername}?start=${token}`;
return NextResponse.json({ deepLink, expiresAt });
}
/**
* DELETE /api/telegram/connect
* 텔레그램 연결 해제 (chat_id 및 토큰 초기화)
*/
export async function DELETE() {
const supabase = await createClient();
const { data: { user }, error: authError } = await supabase.auth.getUser();
if (authError || !user) {
return NextResponse.json({ error: 'UNAUTHORIZED' }, { status: 401 });
}
const { error } = await supabase
.from('profiles')
.update({
telegram_chat_id: null,
telegram_connect_token: null,
telegram_token_expires: null,
})
.eq('id', user.id);
if (error) {
return NextResponse.json({ error: 'DB_ERROR' }, { status: 500 });
}
return NextResponse.json({ ok: true });
}

View File

@@ -0,0 +1,45 @@
import { NextRequest, NextResponse } from 'next/server';
import { setWebhook, getWebhookInfo } from '@/lib/telegram';
/**
* GET /api/telegram/setup — 현재 웹훅 등록 상태 확인
* POST /api/telegram/setup — 텔레그램 웹훅 등록 (최초 1회 or 도메인 변경 시)
*
* 보안: TELEGRAM_SETUP_SECRET 헤더로 보호 (환경변수와 일치해야 접근 가능)
* 사용: curl -X POST https://your-domain/api/telegram/setup \
* -H "x-setup-secret: YOUR_SECRET"
*/
function checkSecret(req: NextRequest): boolean {
const secret = process.env.TELEGRAM_SETUP_SECRET;
if (!secret) return false; // 시크릿 미설정이면 항상 거부
return req.headers.get('x-setup-secret') === secret;
}
export async function GET(req: NextRequest) {
if (!checkSecret(req)) {
return NextResponse.json({ error: 'FORBIDDEN' }, { status: 403 });
}
const info = await getWebhookInfo();
return NextResponse.json(info);
}
export async function POST(req: NextRequest) {
if (!checkSecret(req)) {
return NextResponse.json({ error: 'FORBIDDEN' }, { status: 403 });
}
const appUrl = process.env.NEXT_PUBLIC_APP_URL ?? process.env.VERCEL_URL;
if (!appUrl) {
return NextResponse.json(
{ error: 'NEXT_PUBLIC_APP_URL 또는 VERCEL_URL 환경변수가 필요합니다.' },
{ status: 500 }
);
}
const webhookUrl = `${appUrl.startsWith('http') ? appUrl : `https://${appUrl}`}/api/telegram/webhook`;
const secretToken = process.env.TELEGRAM_WEBHOOK_SECRET;
const result = await setWebhook(webhookUrl, secretToken);
return NextResponse.json({ webhookUrl, result });
}

View File

@@ -0,0 +1,124 @@
import { NextRequest, NextResponse } from 'next/server';
import { createAdminClient } from '@/lib/supabase/admin';
import { sendMessage, type TelegramUpdate } from '@/lib/telegram';
/**
* POST /api/telegram/webhook
* Telegram이 호출하는 웹훅 엔드포인트
* - X-Telegram-Bot-Api-Secret-Token 헤더로 요청 검증
* - /start <TOKEN> 명령으로 유저 텔레그램 계정 연결
*/
export async function POST(req: NextRequest) {
// 1. 웹훅 시크릿 토큰 검증
const secretToken = process.env.TELEGRAM_WEBHOOK_SECRET;
if (secretToken) {
const incoming = req.headers.get('x-telegram-bot-api-secret-token');
if (incoming !== secretToken) {
return NextResponse.json({ error: 'UNAUTHORIZED' }, { status: 401 });
}
}
let update: TelegramUpdate;
try {
update = await req.json();
} catch {
return NextResponse.json({ error: 'INVALID_JSON' }, { status: 400 });
}
const message = update.message;
if (!message?.text || !message.from) {
// 지원하지 않는 업데이트 타입 — 200으로 응답해야 재전송 방지
return NextResponse.json({ ok: true });
}
const chatId = message.chat.id;
const text = message.text.trim();
const firstName = message.from.first_name ?? '고객';
// 2. /start 명령 처리
if (text.startsWith('/start')) {
const parts = text.split(' ');
const token = parts[1]; // /start <TOKEN>
if (!token) {
await sendMessage(
chatId,
`안녕하세요, ${firstName}님! 👋\n\n쟁승메이드 로또 알림 봇입니다.\n\n[마이페이지](https://jaengseung.com/mypage)에서 텔레그램 연결 버튼을 클릭하여 계정을 연결해주세요.`
);
return NextResponse.json({ ok: true });
}
// 3. 토큰으로 유저 조회
const supabase = createAdminClient();
const now = new Date().toISOString();
const { data: profile, error } = await supabase
.from('profiles')
.select('id, email, telegram_chat_id, telegram_connect_token, telegram_token_expires')
.eq('telegram_connect_token', token)
.gt('telegram_token_expires', now)
.maybeSingle();
if (error || !profile) {
await sendMessage(
chatId,
`❌ 연결 코드가 유효하지 않거나 만료되었습니다.\n\n마이페이지에서 다시 연결을 시도해주세요.`
);
return NextResponse.json({ ok: true });
}
if (profile.telegram_chat_id) {
await sendMessage(
chatId,
`✅ 이미 연결된 계정입니다.\n\n📧 ${profile.email}`
);
return NextResponse.json({ ok: true });
}
// 4. chat_id 저장 + 토큰 초기화
await supabase
.from('profiles')
.update({
telegram_chat_id: String(chatId),
telegram_connect_token: null,
telegram_token_expires: null,
})
.eq('id', profile.id);
await sendMessage(
chatId,
`🎉 텔레그램 연결 완료!\n\n📧 ${profile.email} 계정과 연결되었습니다.\n\n이제 매주 로또 번호를 이 채팅으로 받아보실 수 있습니다. 🎰`
);
return NextResponse.json({ ok: true });
}
// 5. 그 외 명령어
if (text === '/status') {
const supabase = createAdminClient();
const { data: profile } = await supabase
.from('profiles')
.select('email')
.eq('telegram_chat_id', String(chatId))
.maybeSingle();
if (profile) {
await sendMessage(chatId, `✅ 연결 상태: 정상\n📧 ${profile.email}`);
} else {
await sendMessage(chatId, `❌ 연결된 계정이 없습니다.\n마이페이지에서 연결해주세요.`);
}
return NextResponse.json({ ok: true });
}
if (text === '/help') {
await sendMessage(
chatId,
`*쟁승메이드 로또 봇 명령어*\n\n/status — 연결 상태 확인\n/help — 도움말`
);
return NextResponse.json({ ok: true });
}
// 기본 응답
await sendMessage(chatId, `/help 를 입력하면 사용 가능한 명령어를 확인할 수 있습니다.`);
return NextResponse.json({ ok: true });
}