Spaces:
Sleeping
Sleeping
| import { Router, type Request, type Response } from 'express'; | |
| import { verifyToken } from './auth.js'; | |
| import { OrderService } from '../services/order.service.js'; | |
| import db from '../lib/db.js'; | |
| const router = Router(); | |
| /** | |
| * 获取可用产品列表 | |
| */ | |
| router.get('/products', async (req, res) => { | |
| const products = db.prepare('SELECT * FROM products').all(); | |
| res.json({ success: true, products }); | |
| }); | |
| /** | |
| * 创建订单 | |
| */ | |
| router.post('/create', verifyToken, async (req: any, res) => { | |
| const { productId, idempotencyKey } = req.body; | |
| const userId = req.user.userId; | |
| const result = await OrderService.createOrder({ userId, productId, idempotencyKey }); | |
| if (result.success) { | |
| res.json(result); | |
| } else { | |
| res.status(400).json(result); | |
| } | |
| }); | |
| /** | |
| * 模拟支付成功 (仅用于演示闭环,不涉及真实网关) | |
| */ | |
| router.post('/simulate-pay', verifyToken, async (req: any, res) => { | |
| const { orderId } = req.body; | |
| const userId = req.user.userId; | |
| // 1. 验证订单归属 | |
| const order = db.prepare('SELECT * FROM orders WHERE id = ? AND user_id = ?').get(orderId, userId) as any; | |
| if (!order) return res.status(404).json({ success: false, error: '订单不存在或无权操作' }); | |
| // 2. 完成支付逻辑 | |
| const result = await OrderService.completePayment(orderId, 'simulated', `SIM_${Date.now()}`); | |
| if (result.success) { | |
| res.json(result); | |
| } else { | |
| res.status(500).json(result); | |
| } | |
| }); | |
| /** | |
| * 获取我的订单 | |
| */ | |
| router.get('/my-orders', verifyToken, async (req: any, res) => { | |
| const userId = req.user.userId; | |
| const orders = db.prepare(` | |
| SELECT o.*, p.name as product_name | |
| FROM orders o | |
| JOIN products p ON o.product_id = p.id | |
| WHERE o.user_id = ? | |
| ORDER BY o.created_at DESC | |
| `).all(userId); | |
| res.json({ success: true, orders }); | |
| }); | |
| /** | |
| * 获取当前用户的配额和计划状态 | |
| */ | |
| router.get('/status', verifyToken, async (req: any, res) => { | |
| const userId = req.user.userId; | |
| const user = db.prepare('SELECT plan, quota_remaining FROM users WHERE id = ?').get(userId); | |
| res.json({ success: true, status: user }); | |
| }); | |
| export default router; | |