feat: 渠道展示、订阅套餐、系统配置全功能

- 新增 Channel / SubscriptionPlan / SystemConfig 三个数据模型
- Order 模型扩展支持订阅订单(order_type, plan_id, subscription_group_id)
- Sub2API client 新增分组查询、订阅分配/续期、用户订阅查询
- 订单服务支持订阅履约流程(CAS 锁 + 分组消失安全处理)
- 管理后台:渠道管理、订阅套餐管理、系统配置、Sub2API 分组同步
- 用户页面:双 Tab UI(按量付费/包月订阅)、渠道卡片、充值弹窗、订阅确认
- PaymentForm 支持 fixedAmount 固定金额模式
- 订单状态 API 返回 failedReason 用于订阅异常展示
- 数据库迁移脚本
This commit is contained in:
erio
2026-03-13 19:06:25 +08:00
parent 9f621713c3
commit eafb7e49fa
38 changed files with 5376 additions and 289 deletions

View File

@@ -0,0 +1,74 @@
import { NextRequest, NextResponse } from 'next/server';
import { verifyAdminToken, unauthorizedResponse } from '@/lib/admin-auth';
import { prisma } from '@/lib/db';
export async function PUT(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
if (!(await verifyAdminToken(request))) return unauthorizedResponse(request);
try {
const { id } = await params;
const body = await request.json();
const existing = await prisma.channel.findUnique({ where: { id } });
if (!existing) {
return NextResponse.json({ error: '渠道不存在' }, { status: 404 });
}
// 如果更新了 group_id检查唯一性
if (body.group_id !== undefined && Number(body.group_id) !== existing.groupId) {
const conflict = await prisma.channel.findUnique({
where: { groupId: Number(body.group_id) },
});
if (conflict) {
return NextResponse.json(
{ error: `分组 ID ${body.group_id} 已被渠道「${conflict.name}」使用` },
{ status: 409 },
);
}
}
const data: Record<string, unknown> = {};
if (body.group_id !== undefined) data.groupId = Number(body.group_id);
if (body.name !== undefined) data.name = body.name;
if (body.platform !== undefined) data.platform = body.platform;
if (body.rate_multiplier !== undefined) data.rateMultiplier = body.rate_multiplier;
if (body.description !== undefined) data.description = body.description;
if (body.models !== undefined) data.models = body.models;
if (body.features !== undefined) data.features = body.features;
if (body.sort_order !== undefined) data.sortOrder = body.sort_order;
if (body.enabled !== undefined) data.enabled = body.enabled;
const channel = await prisma.channel.update({
where: { id },
data,
});
return NextResponse.json({
...channel,
rateMultiplier: Number(channel.rateMultiplier),
});
} catch (error) {
console.error('Failed to update channel:', error);
return NextResponse.json({ error: '更新渠道失败' }, { status: 500 });
}
}
export async function DELETE(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
if (!(await verifyAdminToken(request))) return unauthorizedResponse(request);
try {
const { id } = await params;
const existing = await prisma.channel.findUnique({ where: { id } });
if (!existing) {
return NextResponse.json({ error: '渠道不存在' }, { status: 404 });
}
await prisma.channel.delete({ where: { id } });
return NextResponse.json({ success: true });
} catch (error) {
console.error('Failed to delete channel:', error);
return NextResponse.json({ error: '删除渠道失败' }, { status: 500 });
}
}

View File

@@ -0,0 +1,84 @@
import { NextRequest, NextResponse } from 'next/server';
import { verifyAdminToken, unauthorizedResponse } from '@/lib/admin-auth';
import { prisma } from '@/lib/db';
import { getGroup } from '@/lib/sub2api/client';
export async function GET(request: NextRequest) {
if (!(await verifyAdminToken(request))) return unauthorizedResponse(request);
try {
const channels = await prisma.channel.findMany({
orderBy: { sortOrder: 'asc' },
});
// 并发检查每个渠道对应的 Sub2API 分组是否仍然存在
const results = await Promise.all(
channels.map(async (channel) => {
let groupExists = false;
try {
const group = await getGroup(channel.groupId);
groupExists = group !== null;
} catch {
groupExists = false;
}
return {
...channel,
rateMultiplier: Number(channel.rateMultiplier),
groupExists,
};
}),
);
return NextResponse.json({ channels: results });
} catch (error) {
console.error('Failed to list channels:', error);
return NextResponse.json({ error: '获取渠道列表失败' }, { status: 500 });
}
}
export async function POST(request: NextRequest) {
if (!(await verifyAdminToken(request))) return unauthorizedResponse(request);
try {
const body = await request.json();
const { group_id, name, platform, rate_multiplier, description, models, features, sort_order, enabled } = body;
if (!group_id || !name || !platform || rate_multiplier === undefined) {
return NextResponse.json({ error: '缺少必填字段: group_id, name, platform, rate_multiplier' }, { status: 400 });
}
// 验证 group_id 唯一性
const existing = await prisma.channel.findUnique({
where: { groupId: Number(group_id) },
});
if (existing) {
return NextResponse.json({ error: `分组 ID ${group_id} 已被渠道「${existing.name}」使用` }, { status: 409 });
}
const channel = await prisma.channel.create({
data: {
groupId: Number(group_id),
name,
platform,
rateMultiplier: rate_multiplier,
description: description ?? null,
models: models ?? null,
features: features ?? null,
sortOrder: sort_order ?? 0,
enabled: enabled ?? true,
},
});
return NextResponse.json(
{
...channel,
rateMultiplier: Number(channel.rateMultiplier),
},
{ status: 201 },
);
} catch (error) {
console.error('Failed to create channel:', error);
return NextResponse.json({ error: '创建渠道失败' }, { status: 500 });
}
}

View File

@@ -0,0 +1,63 @@
import { NextRequest, NextResponse } from 'next/server';
import { verifyAdminToken, unauthorizedResponse } from '@/lib/admin-auth';
import { getAllSystemConfigs, setSystemConfigs } from '@/lib/system-config';
const SENSITIVE_PATTERNS = ['KEY', 'SECRET', 'PASSWORD', 'PRIVATE'];
function maskSensitiveValue(key: string, value: string): string {
const isSensitive = SENSITIVE_PATTERNS.some((pattern) => key.toUpperCase().includes(pattern));
if (!isSensitive || value.length <= 4) return value;
return '*'.repeat(value.length - 4) + value.slice(-4);
}
export async function GET(request: NextRequest) {
if (!(await verifyAdminToken(request))) return unauthorizedResponse(request);
try {
const configs = await getAllSystemConfigs();
const masked = configs.map((config) => ({
...config,
value: maskSensitiveValue(config.key, config.value),
}));
return NextResponse.json({ configs: masked });
} catch (error) {
console.error('Failed to get system configs:', error);
return NextResponse.json({ error: '获取系统配置失败' }, { status: 500 });
}
}
export async function PUT(request: NextRequest) {
if (!(await verifyAdminToken(request))) return unauthorizedResponse(request);
try {
const body = await request.json();
const { configs } = body;
if (!Array.isArray(configs) || configs.length === 0) {
return NextResponse.json({ error: '缺少必填字段: configs 数组' }, { status: 400 });
}
// 校验每条配置
for (const config of configs) {
if (!config.key || config.value === undefined) {
return NextResponse.json({ error: '每条配置必须包含 key 和 value' }, { status: 400 });
}
}
await setSystemConfigs(
configs.map((c: { key: string; value: string; group?: string; label?: string }) => ({
key: c.key,
value: c.value,
group: c.group,
label: c.label,
})),
);
return NextResponse.json({ success: true, updated: configs.length });
} catch (error) {
console.error('Failed to update system configs:', error);
return NextResponse.json({ error: '更新系统配置失败' }, { status: 500 });
}
}

View File

@@ -0,0 +1,15 @@
import { NextRequest, NextResponse } from 'next/server';
import { verifyAdminToken, unauthorizedResponse } from '@/lib/admin-auth';
import { getAllGroups } from '@/lib/sub2api/client';
export async function GET(request: NextRequest) {
if (!(await verifyAdminToken(request))) return unauthorizedResponse(request);
try {
const groups = await getAllGroups();
return NextResponse.json({ groups });
} catch (error) {
console.error('Failed to fetch Sub2API groups:', error);
return NextResponse.json({ error: '获取 Sub2API 分组列表失败' }, { status: 500 });
}
}

View File

@@ -0,0 +1,90 @@
import { NextRequest, NextResponse } from 'next/server';
import { verifyAdminToken, unauthorizedResponse } from '@/lib/admin-auth';
import { prisma } from '@/lib/db';
export async function PUT(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
if (!(await verifyAdminToken(request))) return unauthorizedResponse(request);
try {
const { id } = await params;
const body = await request.json();
const existing = await prisma.subscriptionPlan.findUnique({ where: { id } });
if (!existing) {
return NextResponse.json({ error: '订阅套餐不存在' }, { status: 404 });
}
// 如果更新了 group_id检查唯一性
if (body.group_id !== undefined && Number(body.group_id) !== existing.groupId) {
const conflict = await prisma.subscriptionPlan.findUnique({
where: { groupId: Number(body.group_id) },
});
if (conflict) {
return NextResponse.json(
{ error: `分组 ID ${body.group_id} 已被套餐「${conflict.name}」使用` },
{ status: 409 },
);
}
}
const data: Record<string, unknown> = {};
if (body.group_id !== undefined) data.groupId = Number(body.group_id);
if (body.name !== undefined) data.name = body.name;
if (body.description !== undefined) data.description = body.description;
if (body.price !== undefined) data.price = body.price;
if (body.original_price !== undefined) data.originalPrice = body.original_price;
if (body.validity_days !== undefined) data.validityDays = body.validity_days;
if (body.features !== undefined) data.features = body.features;
if (body.for_sale !== undefined) data.forSale = body.for_sale;
if (body.sort_order !== undefined) data.sortOrder = body.sort_order;
const plan = await prisma.subscriptionPlan.update({
where: { id },
data,
});
return NextResponse.json({
...plan,
price: Number(plan.price),
originalPrice: plan.originalPrice ? Number(plan.originalPrice) : null,
});
} catch (error) {
console.error('Failed to update subscription plan:', error);
return NextResponse.json({ error: '更新订阅套餐失败' }, { status: 500 });
}
}
export async function DELETE(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
if (!(await verifyAdminToken(request))) return unauthorizedResponse(request);
try {
const { id } = await params;
const existing = await prisma.subscriptionPlan.findUnique({ where: { id } });
if (!existing) {
return NextResponse.json({ error: '订阅套餐不存在' }, { status: 404 });
}
// 检查是否有活跃订单引用此套餐
const activeOrderCount = await prisma.order.count({
where: {
planId: id,
status: { in: ['PENDING', 'PAID', 'RECHARGING'] },
},
});
if (activeOrderCount > 0) {
return NextResponse.json(
{ error: `该套餐仍有 ${activeOrderCount} 个活跃订单,无法删除` },
{ status: 409 },
);
}
await prisma.subscriptionPlan.delete({ where: { id } });
return NextResponse.json({ success: true });
} catch (error) {
console.error('Failed to delete subscription plan:', error);
return NextResponse.json({ error: '删除订阅套餐失败' }, { status: 500 });
}
}

View File

@@ -0,0 +1,89 @@
import { NextRequest, NextResponse } from 'next/server';
import { verifyAdminToken, unauthorizedResponse } from '@/lib/admin-auth';
import { prisma } from '@/lib/db';
import { getGroup } from '@/lib/sub2api/client';
export async function GET(request: NextRequest) {
if (!(await verifyAdminToken(request))) return unauthorizedResponse(request);
try {
const plans = await prisma.subscriptionPlan.findMany({
orderBy: { sortOrder: 'asc' },
});
// 并发检查每个套餐对应的 Sub2API 分组是否仍然存在
const results = await Promise.all(
plans.map(async (plan) => {
let groupExists = false;
try {
const group = await getGroup(plan.groupId);
groupExists = group !== null;
} catch {
groupExists = false;
}
return {
...plan,
price: Number(plan.price),
originalPrice: plan.originalPrice ? Number(plan.originalPrice) : null,
groupExists,
};
}),
);
return NextResponse.json({ plans: results });
} catch (error) {
console.error('Failed to list subscription plans:', error);
return NextResponse.json({ error: '获取订阅套餐列表失败' }, { status: 500 });
}
}
export async function POST(request: NextRequest) {
if (!(await verifyAdminToken(request))) return unauthorizedResponse(request);
try {
const body = await request.json();
const { group_id, name, description, price, original_price, validity_days, features, for_sale, sort_order } = body;
if (!group_id || !name || price === undefined) {
return NextResponse.json({ error: '缺少必填字段: group_id, name, price' }, { status: 400 });
}
// 验证 group_id 唯一性
const existing = await prisma.subscriptionPlan.findUnique({
where: { groupId: Number(group_id) },
});
if (existing) {
return NextResponse.json(
{ error: `分组 ID ${group_id} 已被套餐「${existing.name}」使用` },
{ status: 409 },
);
}
const plan = await prisma.subscriptionPlan.create({
data: {
groupId: Number(group_id),
name,
description: description ?? null,
price,
originalPrice: original_price ?? null,
validityDays: validity_days ?? 30,
features: features ?? null,
forSale: for_sale ?? false,
sortOrder: sort_order ?? 0,
},
});
return NextResponse.json(
{
...plan,
price: Number(plan.price),
originalPrice: plan.originalPrice ? Number(plan.originalPrice) : null,
},
{ status: 201 },
);
} catch (error) {
console.error('Failed to create subscription plan:', error);
return NextResponse.json({ error: '创建订阅套餐失败' }, { status: 500 });
}
}

View File

@@ -0,0 +1,34 @@
import { NextRequest, NextResponse } from 'next/server';
import { verifyAdminToken, unauthorizedResponse } from '@/lib/admin-auth';
import { getUserSubscriptions } from '@/lib/sub2api/client';
export async function GET(request: NextRequest) {
if (!(await verifyAdminToken(request))) return unauthorizedResponse(request);
try {
const searchParams = request.nextUrl.searchParams;
const userId = searchParams.get('user_id');
if (!userId) {
return NextResponse.json({ error: '缺少必填参数: user_id' }, { status: 400 });
}
const parsedUserId = Number(userId);
if (!Number.isFinite(parsedUserId) || parsedUserId <= 0) {
return NextResponse.json({ error: '无效的 user_id' }, { status: 400 });
}
const subscriptions = await getUserSubscriptions(parsedUserId);
// 如果提供了 group_id 筛选,过滤结果
const groupId = searchParams.get('group_id');
const filtered = groupId
? subscriptions.filter((s) => s.group_id === Number(groupId))
: subscriptions;
return NextResponse.json({ subscriptions: filtered });
} catch (error) {
console.error('Failed to query subscriptions:', error);
return NextResponse.json({ error: '查询订阅信息失败' }, { status: 500 });
}
}