新增订单推荐人和邀请码功能,优化支付流程中的订单插入逻辑,确保订单记录准确。更新小程序支付请求,支持传递邀请码以便于分销归属和对账。同时,调整数据库结构以支持新字段,提升系统的稳定性和用户体验。

This commit is contained in:
乘风
2026-02-06 18:34:02 +08:00
parent f8fac00c85
commit 2e65d68e1e
34 changed files with 3288 additions and 1255 deletions

View File

@@ -7,6 +7,7 @@ import { NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'
import { requireAdminResponse } from '@/lib/admin-auth'
import { query } from '@/lib/db'
// 获取书籍目录
const BOOK_DIR = path.join(process.cwd(), 'book')
@@ -286,27 +287,38 @@ export async function POST(request: Request) {
console.log('[AdminChapters] 更新章节:', { action, chapterId })
switch (action) {
case 'updatePrice':
// 更新章节价格
// TODO: 保存到数据库
case 'updatePrice': {
if (data?.price != null && chapterId) {
await query('UPDATE chapters SET price = ?, updated_at = NOW() WHERE id = ?', [Number(data.price), chapterId])
}
return NextResponse.json({
success: true,
data: { message: '价格更新成功', chapterId, price: data.price }
data: { message: '价格更新成功', chapterId, price: data?.price }
})
}
case 'toggleFree':
// 切换免费状态
case 'toggleFree': {
if (data?.isFree != null && chapterId) {
await query('UPDATE chapters SET is_free = ?, updated_at = NOW() WHERE id = ?', [!!data.isFree, chapterId])
}
return NextResponse.json({
success: true,
data: { message: '免费状态更新成功', chapterId, isFree: data.isFree }
data: { message: '免费状态更新成功', chapterId, isFree: data?.isFree }
})
}
case 'updateStatus':
// 更新发布状态
case 'updateStatus': {
if (data?.status && chapterId) {
const s = String(data.status)
if (['draft', 'published', 'archived'].includes(s)) {
await query('UPDATE chapters SET status = ?, updated_at = NOW() WHERE id = ?', [s, chapterId])
}
}
return NextResponse.json({
success: true,
data: { message: '发布状态更新成功', chapterId, status: data.status }
data: { message: '发布状态更新成功', chapterId, status: data?.status }
})
}
default:
return NextResponse.json({

View File

@@ -88,8 +88,22 @@ export async function PUT(req: NextRequest) {
)
}
// TODO: 根据ID找到文件并更新
// id 格式: category/filename无 .md
const filePath = path.join(BOOK_DIR, `${id}.md`)
if (!fs.existsSync(filePath)) {
return NextResponse.json(
{ error: '章节文件不存在' },
{ status: 404 }
)
}
const markdownContent = matter.stringify(content ?? '', {
title: title ?? id.split('/').pop(),
date: new Date().toISOString(),
tags: tags || [],
draft: false
})
fs.writeFileSync(filePath, markdownContent, 'utf-8')
return NextResponse.json({
success: true,
message: '章节更新成功'
@@ -117,8 +131,15 @@ export async function DELETE(req: NextRequest) {
)
}
// TODO: 根据ID删除文件
const filePath = path.join(BOOK_DIR, `${id}.md`)
if (!fs.existsSync(filePath)) {
return NextResponse.json(
{ error: '章节文件不存在' },
{ status: 404 }
)
}
fs.unlinkSync(filePath)
return NextResponse.json({
success: true,
message: '章节删除成功'

View File

@@ -1,60 +1,61 @@
/**
* 后台提现 API
* GET: 查提现记录。PUT: 查库 + 更新提现状态 + 更新用户已提现金额(当前未接入微信打款
* 后台提现 API - 使用 Prisma ORM
* GET: 查提现记录(包含用户信息、收款账号=微信号
* PUT: 审批提现 = 调用微信打款 + 更新状态 + 更新用户已提现金额
*/
import { NextResponse } from 'next/server'
import { query } from '@/lib/db'
import { prisma } from '@/lib/prisma'
import { requireAdminResponse } from '@/lib/admin-auth'
import { createTransfer } from '@/lib/wechat-transfer'
/** 安全转数组,避免 undefined.length绝不返回 undefined */
function toArray<T = any>(x: unknown): T[] {
if (x == null) return []
if (Array.isArray(x)) return x as T[]
if (typeof x === 'object' && x !== null) return [x] as T[]
return []
}
/** 安全取数组长度,避免对 undefined 读 .length */
function safeLength(x: unknown): number {
if (x == null) return 0
if (Array.isArray(x)) return x.length
return 0
}
// ========== GET只查提现记录 ==========
// ========== GET查询提现记录带用户信息、收款账号=微信号)==========
export async function GET(request: Request) {
console.log('[Withdrawals] GET 开始')
try {
const authErr = requireAdminResponse(request)
if (authErr) return authErr
const sql = `
SELECT
w.id, w.user_id, w.amount, w.status, w.created_at,
u.nickname as user_nickname, u.avatar as user_avatar
FROM withdrawals w
LEFT JOIN users u ON w.user_id = u.id
ORDER BY w.created_at DESC
LIMIT 100
`
const result = await query(sql)
const rows = toArray(result)
const withdrawalsData = await prisma.withdrawals.findMany({
take: 100,
orderBy: { created_at: 'desc' },
select: {
id: true,
user_id: true,
amount: true,
status: true,
created_at: true,
wechat_id: true,
}
})
const withdrawals = rows.map((w: any) => ({
id: w.id,
user_id: w.user_id,
user_name: w.user_nickname || '未知用户',
userAvatar: w.user_avatar,
amount: parseFloat(w.amount) || 0,
status: w.status === 'success' ? 'completed' : (w.status === 'failed' ? 'rejected' : w.status),
created_at: w.created_at,
method: 'wechat',
}))
const userIds = [...new Set(withdrawalsData.map(w => w.user_id))]
const users = await prisma.users.findMany({
where: { id: { in: userIds } },
select: { id: true, nickname: true, avatar: true, wechat_id: true }
})
const userMap = new Map(users.map(u => [u.id, u]))
const withdrawals = withdrawalsData.map(w => {
const user = userMap.get(w.user_id)
return {
id: w.id,
user_id: w.user_id,
user_name: user?.nickname || '未知用户',
userAvatar: user?.avatar,
amount: Number(w.amount),
status: w.status === 'success' ? 'completed' :
w.status === 'failed' ? 'rejected' :
w.status,
created_at: w.created_at,
method: 'wechat',
account: w.wechat_id || user?.wechat_id || '未绑定微信号',
}
})
return NextResponse.json({
success: true,
withdrawals,
stats: { total: safeLength(withdrawals) },
stats: { total: withdrawals.length },
})
} catch (error: any) {
console.error('[Withdrawals] GET 失败:', error?.message)
@@ -65,69 +66,112 @@ export async function GET(request: Request) {
}
}
// ========== PUT查库 + 更新状态 + 更新用户已提现,暂不调用微信打款 ==========
// ========== PUT审批提现(使用 Prisma 事务)==========
export async function PUT(request: Request) {
const STEP = '[Withdrawals PUT]'
try {
console.log(STEP, '1. 开始')
const authErr = requireAdminResponse(request)
if (authErr) return authErr
console.log(STEP, '2. 鉴权通过')
const body = await request.json()
console.log(STEP, '3. body 已解析', typeof body, body ? 'ok' : 'null')
const id = body?.id
const action = body?.action
const rejectReason = body?.errorMessage || body?.reason || '管理员拒绝'
const { id, action, errorMessage, reason } = body
const rejectReason = errorMessage || reason || '管理员拒绝'
if (!id || !action) {
return NextResponse.json({ success: false, error: '缺少 id 或 action' }, { status: 400 })
}
console.log(STEP, '4. id/action 有效', id, action)
console.log(STEP, '2. id/action 有效', id, action)
console.log(STEP, '5. 即将 query SELECT')
const result = await query('SELECT * FROM withdrawals WHERE id = ?', [id])
console.log(STEP, '6. query 返回', typeof result, 'length=', safeLength(result))
const rows = toArray<any>(result)
console.log(STEP, '7. toArray 后 length=', safeLength(rows))
if (safeLength(rows) === 0) {
const withdrawal = await prisma.withdrawals.findUnique({
where: { id },
select: { id: true, user_id: true, amount: true, status: true, wechat_openid: true }
})
if (!withdrawal) {
return NextResponse.json({ success: false, error: '提现记录不存在' }, { status: 404 })
}
console.log(STEP, '8. 有记录')
const row = rows[0]
console.log(STEP, '9. row', row ? 'ok' : 'null')
if (row.status !== 'pending') {
if (withdrawal.status !== 'pending') {
return NextResponse.json({ success: false, error: '该记录已处理,不可重复审批' }, { status: 400 })
}
console.log(STEP, '10. 状态 pending')
const amount = parseFloat(String(row.amount ?? 0)) || 0
const userId = String(row.user_id ?? '')
console.log(STEP, '11. amount/userId', amount, userId)
const amount = Number(withdrawal.amount)
const userId = withdrawal.user_id
const openid = withdrawal.wechat_openid
if (action === 'approve') {
console.log(STEP, '12. 执行 approve UPDATE withdrawals')
await query(
`UPDATE withdrawals SET status = 'success', processed_at = NOW(), transaction_id = ? WHERE id = ?`,
[`manual_${Date.now()}`, id]
)
console.log(STEP, '13. 执行 approve UPDATE users')
await query(
`UPDATE users SET withdrawn_earnings = COALESCE(withdrawn_earnings, 0) + ? WHERE id = ?`,
[amount, userId]
)
console.log(STEP, '14. 批准完成')
return NextResponse.json({ success: true, message: '已批准,已更新提现状态与用户已提现金额(未发起微信打款)' })
console.log(STEP, '3. 发起微信打款')
if (!openid) {
return NextResponse.json({
success: false,
error: '该提现记录无微信 openid无法打款请线下处理'
}, { status: 400 })
}
const amountFen = Math.round(amount * 100)
const transferResult = await createTransfer({
openid,
amountFen,
outDetailNo: id,
transferRemark: '提现',
})
if (!transferResult.success) {
console.error(STEP, '微信打款失败:', transferResult.errorCode, transferResult.errorMessage)
await prisma.withdrawals.update({
where: { id },
data: {
status: 'failed',
processed_at: new Date(),
error_message: transferResult.errorMessage || transferResult.errorCode || '打款失败'
}
})
return NextResponse.json({
success: false,
error: '微信打款失败: ' + (transferResult.errorMessage || transferResult.errorCode || '未知错误')
}, { status: 500 })
}
const batchNo = transferResult.outBatchNo || `B${Date.now()}`
console.log(STEP, '4. 打款成功,更新数据库')
await prisma.$transaction(async (tx) => {
await tx.withdrawals.update({
where: { id },
data: {
status: 'success',
processed_at: new Date(),
transaction_id: transferResult.batchId || batchNo
}
})
const user = await tx.users.findUnique({
where: { id: userId },
select: { withdrawn_earnings: true }
})
await tx.users.update({
where: { id: userId },
data: {
withdrawn_earnings: Number(user?.withdrawn_earnings || 0) + amount
}
})
})
console.log(STEP, '5. 批准完成,钱已打到用户微信零钱')
return NextResponse.json({
success: true,
message: '已批准并打款成功,款项将到账用户微信零钱'
})
}
if (action === 'reject') {
console.log(STEP, '15. 执行 reject UPDATE')
await query(
`UPDATE withdrawals SET status = 'failed', processed_at = NOW(), error_message = ? WHERE id = ?`,
[rejectReason, id]
)
console.log(STEP, '16. 拒绝完成')
console.log(STEP, '5. 执行拒绝操作')
await prisma.withdrawals.update({
where: { id },
data: {
status: 'failed',
processed_at: new Date(),
error_message: rejectReason
}
})
console.log(STEP, '6. 拒绝完成')
return NextResponse.json({ success: true, message: '已拒绝该提现申请' })
}