From 3030f50cd3ff4dc955742188a42108efc53acace Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 21 Oct 2026 17:43:18 +0800 Subject: [PATCH] =?UTF-8?q?=E7=BB=AD=E6=9C=9F=E6=94=B9=E4=B8=BA=E9=80=89?= =?UTF-8?q?=E5=A5=97=E9=A4=90=E4=B8=8B=E5=8D=95=EF=BC=8C=E6=94=AF=E4=BB=98?= =?UTF-8?q?=E5=9B=9E=E8=B0=83=E7=A1=AE=E8=AE=A4=E5=90=8E=E6=89=8D=E7=BB=AD?= =?UTF-8?q?=E6=9C=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 数据库 - 新增 subject_plans(天数 + 定价):迁移内置三档 30 天 ¥99 / 180 天 ¥499(推荐,划线 594)/ 365 天 ¥899(最划算,划线 1204) - subject_orders 增加 plan_id / plan_code / plan_name 快照 后端 - GET /api/web/subject-plans:上架套餐(含 pricePerDay) - POST /api/web/subjects/:id/orders 改为 { planId }:金额只认套餐价, 前端传的 amount/days 一律忽略;套餐不存在/下架/未配价格 → 422 - 新增 GET /api/web/subjects/:id/orders/:orderNo(轮询支付状态)、 POST .../orders/:orderNo/close(关闭待支付订单) - 下单仍然只建单不动期限;续期只发生在 POST /api/pay/notify(渠道回调)成功之后 前端 - 续期不再 prompt 输入天数:弹窗展示套餐卡片(天数/价格/划线价/角标/折合每天), 点「生成订单(¥xxx)」→ 显示订单号、金额、状态(待支付) - 每 2s 轮询订单状态,回调确认后自动刷新主体列表并提示新到期时间; 待支付时可「关闭订单」,避免留下悬挂单 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- backend/README.md | 23 +- backend/app/controller/web/subject_order.js | 38 +- backend/app/controller/web/subject_plan.js | 19 + backend/app/model/subject_order.js | 3 + backend/app/model/subject_plan.js | 34 ++ backend/app/router.js | 5 +- backend/app/service/subject_order.js | 80 ++++- backend/app/service/subject_plan.js | 58 +++ .../20261021180000-create-subject-plans.js | 83 +++++ ...261021180100-add-plan-to-subject-orders.js | 37 ++ .../test/app/controller/subject-order.test.js | 80 ++++- frontend/src/api/subjectApi.ts | 61 ++++ frontend/src/views/SubjectsView.vue | 331 ++++++++++++++++-- 13 files changed, 788 insertions(+), 64 deletions(-) create mode 100644 backend/app/controller/web/subject_plan.js create mode 100644 backend/app/model/subject_plan.js create mode 100644 backend/app/service/subject_plan.js create mode 100644 backend/database/migrations/20261021180000-create-subject-plans.js create mode 100644 backend/database/migrations/20261021180100-add-plan-to-subject-orders.js diff --git a/backend/README.md b/backend/README.md index 4dfece2..2f467a5 100644 --- a/backend/README.md +++ b/backend/README.md @@ -1013,17 +1013,30 @@ await this.ctx.service.cache.remember('user:1', 60, () => loadFromMysql()); - 创建者不能降级、不能移除;不能改自己的角色、不能删自己(避免管理员把自己锁死); - 管理员不能直接移除,需先「取消管理员」;给**未绑定账号**的成员设为管理员,绑定后即为管理员。 -### 续期订单与支付回调 +### 续期套餐与订单(支付回调驱动) -**下单不会立刻续期**,只有支付渠道回调成功后才把主体期限顺延(幂等,重复回调不重复续期)。 +**续期不再是「自己输入天数」**:前端先选套餐(天数 + 定价都在库里),点「生成订单」只落一笔**待支付**订单, +**不会立刻续期**;只有支付渠道回调确认后才把主体期限顺延(幂等,重复回调不重复续期)。 | 方法 | 路径 | 说明 | |---|---|---| +| GET | `/api/web/subject-plans` | 上架套餐 `{ list: [{ id, code, name, days, price, originalPrice, tag, description, pricePerDay }] }`(任何登录用户可读) | | GET | `/api/web/subjects/:id/orders` | 订单列表(成员可见,`{ total, page, pageSize, list }`) | -| POST | `/api/web/subjects/:id/orders` | 下单 `{ days, amount?, remark? }`(仅管理员)→ `{ orderNo, days, amount, status:0待支付, ... }`;`amount` 不传时按 `PAY_AMOUNT_PER_DAY` 自动算,都没配则金额为空(不校验) | +| POST | `/api/web/subjects/:id/orders` | **选套餐下单** `{ planId, remark? }`(仅管理员)→ `{ orderNo, planId, planName, days, amount, status:0待支付, pending:true, … }`;**金额只认套餐价**,前端传的 `amount/days` 一律忽略 | +| GET | `/api/web/subjects/:id/orders/:orderNo` | 单笔订单(续期弹窗每 2s 轮询支付状态,`pending=false` 即停止) | +| POST | `/api/web/subjects/:id/orders/:orderNo/close` | 关闭待支付订单(仅管理员;已支付 → 409) | | POST | `/api/pay/notify` | **公开的渠道回调** `{ orderNo, transactionId?, amount?, channel?, paidAt? }` → `{ duplicated, order }`;订单不存在 404、金额不符 422、签名错 400 | | POST | `/api/internal/subject-orders/:orderNo/pay` | **内部令牌**:模拟支付成功(不需要签名),方便联调/补单 | +订单会快照 `plan_id / plan_code / plan_name`,套餐后续改价或下架都不影响历史订单对账。 +套餐表 `subject_plans`(迁移 `20261021180000-create-subject-plans` 内置三档,改价直接改库、不用发版): + +| code | 天数 | 价格 | 备注 | +|---|---|---|---| +| `p30` | 30 | ¥99 | 短期试用 / 临时项目 | +| `p180` | 180 | ¥499 | 角标「推荐」,划线价 ¥594(≈¥2.77/天) | +| `p365` | 365 | ¥899 | 角标「最划算」,划线价 ¥1204(≈¥2.46/天) | + 签名:配置了 `PAY_CALLBACK_SECRET` 时,回调必须带 `X-Pay-Sign = hex(HMAC-SHA256(secret, "orderNo\ntransactionId\namount"))`; 未配置密钥且 `PAY_MOCK=true` 时允许不带签名直接回调(开发/测试默认开启;**生产默认关闭**, @@ -1035,10 +1048,10 @@ await this.ctx.service.cache.remember('user:1', 60, () => loadFromMysql()); **模拟一次付费续期**(本地/测试): ```bash -# 1) 下单(需要主体管理员用户令牌) +# 1) 选套餐下单(需要主体管理员用户令牌) curl -X POST http://127.0.0.1:7300/api/web/subjects/1/orders \ -H "Authorization: Bearer " -H "Content-Type: application/json" \ - -d '{"days":30,"amount":99}' + -d '{"planId":1}' # 2a) 模拟渠道回调(PAY_MOCK=true 时不需要签名) curl -X POST http://127.0.0.1:7300/api/pay/notify \ diff --git a/backend/app/controller/web/subject_order.js b/backend/app/controller/web/subject_order.js index f0edc4f..29a929b 100644 --- a/backend/app/controller/web/subject_order.js +++ b/backend/app/controller/web/subject_order.js @@ -16,8 +16,7 @@ function toId(value) { * * 下单不会立刻续期;等支付渠道回调 `POST /api/pay/notify` 后才顺延期限。 */ -class WebSubjectOrderController extends Controller { - /** GET /api/web/subjects/:id/orders —— 订单列表 */ +class WebSubjectOrderController extends Controller { /** GET /api/web/subjects/:id/orders —— 订单列表 */ async index() { const { ctx } = this; const id = toId(ctx.params.id); @@ -33,24 +32,51 @@ class WebSubjectOrderController extends Controller { ctx.body = { ok: true, data }; } - /** POST /api/web/subjects/:id/orders —— { days, amount?, remark? } */ + /** POST /api/web/subjects/:id/orders —— { planId, remark? } 选套餐下单(只建单,支付回调后才续期) */ async create() { const { ctx } = this; const id = toId(ctx.params.id); if (!id) ctx.throw(400, 'id 必须是正整数'); - const { days, amount, remark } = ctx.request.body || {}; + const { planId, remark } = ctx.request.body || {}; const data = await ctx.service.subjectOrder.create({ subjectId: id, userId: ctx.state.user.id, - days, - amount, + planId, remark, }); ctx.status = 201; ctx.body = { ok: true, data }; } + + /** GET /api/web/subjects/:id/orders/:orderNo —— 单笔订单(续期弹窗轮询支付状态) */ + async show() { + const { ctx } = this; + const id = toId(ctx.params.id); + if (!id) ctx.throw(400, 'id 必须是正整数'); + + const data = await ctx.service.subjectOrder.detail({ + subjectId: id, + userId: ctx.state.user.id, + orderNo: ctx.params.orderNo, + }); + ctx.body = { ok: true, data }; + } + + /** POST /api/web/subjects/:id/orders/:orderNo/close —— 关闭待支付订单 */ + async close() { + const { ctx } = this; + const id = toId(ctx.params.id); + if (!id) ctx.throw(400, 'id 必须是正整数'); + + const data = await ctx.service.subjectOrder.close({ + subjectId: id, + userId: ctx.state.user.id, + orderNo: ctx.params.orderNo, + }); + ctx.body = { ok: true, data }; + } } module.exports = WebSubjectOrderController; diff --git a/backend/app/controller/web/subject_plan.js b/backend/app/controller/web/subject_plan.js new file mode 100644 index 0000000..484ec45 --- /dev/null +++ b/backend/app/controller/web/subject_plan.js @@ -0,0 +1,19 @@ +'use strict'; + +const { Controller } = require('egg'); + +/** + * 续期套餐(`GET /api/web/subject-plans`) + * + * 只读、任何登录用户都能看(续期弹窗要展示天数与定价)。 + * 鉴权:`middleware.apiAuth()`;不需要主体 id(换主体/新主体都要能看价格)。 + */ +class WebSubjectPlanController extends Controller { + async index() { + const { ctx } = this; + const list = await ctx.service.subjectPlan.list(); + ctx.body = { ok: true, data: { list } }; + } +} + +module.exports = WebSubjectPlanController; diff --git a/backend/app/model/subject_order.js b/backend/app/model/subject_order.js index 5fdb449..c0edf4c 100644 --- a/backend/app/model/subject_order.js +++ b/backend/app/model/subject_order.js @@ -17,6 +17,9 @@ module.exports = (app) => { orderNo: { type: STRING(32), allowNull: false, unique: true, comment: '订单号(对外唯一)' }, subjectId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '主体 subjects.id' }, userId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '下单用户 users.id' }, + planId: { type: BIGINT.UNSIGNED, allowNull: true, comment: '续期套餐 subject_plans.id(内部单可为空)' }, + planCode: { type: STRING(32), allowNull: true, comment: '套餐编码快照' }, + planName: { type: STRING(64), allowNull: true, comment: '套餐名称快照' }, days: { type: INTEGER.UNSIGNED, allowNull: false, comment: '续期天数' }, amount: { type: DECIMAL(10, 2), allowNull: true, comment: '应付金额(为空表示不校验)' }, status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: '状态:0待支付 1已支付 2已关闭' }, diff --git a/backend/app/model/subject_plan.js b/backend/app/model/subject_plan.js new file mode 100644 index 0000000..abff359 --- /dev/null +++ b/backend/app/model/subject_plan.js @@ -0,0 +1,34 @@ +'use strict'; + +/** + * 续期套餐(subject_plans) + * + * 一行 = 一个可选的续期套餐(天数 + 售价)。续期时前端只传套餐 id, + * 金额由服务端按 `price` 计算,避免被前端篡改。 + * + * - `code`:稳定编码(p30 / p180 / p365 …),接口与日志里用 + * - `status`:1 上架 0 下架(下架后历史订单不受影响) + * - `sort`:展示顺序(小的在前) + */ +module.exports = (app) => { + const { BIGINT, STRING, TINYINT, INTEGER, DECIMAL, DATE } = app.Sequelize; + + const SubjectPlan = app.model.define('subject_plan', { + id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, + code: { type: STRING(32), allowNull: false, unique: true, comment: '套餐编码(稳定标识)' }, + name: { type: STRING(64), allowNull: false, comment: '套餐名称(展示用)' }, + days: { type: INTEGER.UNSIGNED, allowNull: false, comment: '续期天数' }, + price: { type: DECIMAL(10, 2), allowNull: false, defaultValue: 0, comment: '售价(元)' }, + originalPrice: { type: DECIMAL(10, 2), allowNull: true, comment: '划线原价(可选)' }, + tag: { type: STRING(16), allowNull: true, comment: '角标文案(推荐 / 最划算)' }, + description: { type: STRING(255), allowNull: true, comment: '副标题说明' }, + sort: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '排序(小的在前)' }, + status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1上架 0下架' }, + }, { + tableName: 'subject_plans', + paranoid: true, + comment: '主体续期套餐表', + }); + + return SubjectPlan; +}; diff --git a/backend/app/router.js b/backend/app/router.js index 3ba264e..6a7a7e8 100644 --- a/backend/app/router.js +++ b/backend/app/router.js @@ -68,10 +68,13 @@ module.exports = (app) => { // 给未绑定账号/微信的成员生成绑定码(手机扫码后绑定) router.post('/api/web/subjects/:id/members/:memberId/bind-code', apiAuth, controller.web.subject.memberBindCode); - // 续期订单:下单不改变期限,支付结果由渠道回调 `POST /api/pay/notify` 驱动 + // 续期订单:选套餐下单不改变期限,支付结果由渠道回调 `POST /api/pay/notify` 驱动 // ⚠️ 不挂 subjectAuth:主体已过期也要能下单续期 + router.get('/api/web/subject-plans', apiAuth, controller.web.subjectPlan.index); router.get('/api/web/subjects/:id/orders', apiAuth, controller.web.subjectOrder.index); router.post('/api/web/subjects/:id/orders', apiAuth, controller.web.subjectOrder.create); + router.get('/api/web/subjects/:id/orders/:orderNo', apiAuth, controller.web.subjectOrder.show); + router.post('/api/web/subjects/:id/orders/:orderNo/close', apiAuth, controller.web.subjectOrder.close); // 成员绑定:手机扫码页(公开查状态)+ 登录后确认绑定 router.get('/api/subject/member-bind', controller.auth.memberBind.status); diff --git a/backend/app/service/subject_order.js b/backend/app/service/subject_order.js index 285fafd..fe84326 100644 --- a/backend/app/service/subject_order.js +++ b/backend/app/service/subject_order.js @@ -9,10 +9,11 @@ const STATUS_TEXT = { 0: '待支付', 1: '已支付', 2: '已关闭' }; /** * 主体续期订单 service * - * 流程:`create()` 下单(待支付)→ 支付渠道回调 `payNotify()` → 标记已支付 + 主体顺延 + 清状态缓存。 + * 流程:`create()` 选套餐下单(待支付)→ 支付渠道回调 `payNotify()` → 标记已支付 + 主体顺延 + 清状态缓存。 * * 关键约定: * - **支付靠回调驱动**:下单不改变期限,只有 `payNotify()` 成功才续期; + * - **价格只认套餐**:下单只收 `planId`,金额取库里的 `subject_plans.price`,不信前端传的金额; * - **幂等**:同一订单重复回调只续期一次(第二次返回 `duplicated: true`); * - 续期基数与 `service.subject.update` 一致:未过期在原到期时间上顺延,已过期从当前时间起算。 */ @@ -25,43 +26,79 @@ class SubjectOrderService extends Service { return this.app.model.Subject; } - /** 创建订单(管理员):只建单,不动期限 */ - async create({ subjectId, userId, days, amount, remark, channel = 'mock' } = {}) { + /** + * 创建订单(管理员):选套餐 → 只建单,不动期限 + * + * @param {object} params { subjectId, userId, planId, remark } + */ + async create({ subjectId, userId, planId, remark } = {}) { const { subject } = await this.ctx.service.subject.ensureAdmin(subjectId, userId); - const grantDays = Number(days); - if (!Number.isInteger(grantDays) || grantDays <= 0 || grantDays > 3650) { - this.ctx.throw(422, '续期天数必须是 1~3650 的整数'); - } + const plan = await this.ctx.service.subjectPlan.findActive(planId); + const grantDays = Number(plan.days); + const price = Number(plan.price); - const payCfg = this.config.pay || {}; - const perDay = Number(payCfg.amountPerDay || 0); - let price = null; - if (amount !== undefined && amount !== null && amount !== '') { - price = Number(amount); - if (!Number.isFinite(price) || price < 0) this.ctx.throw(422, '金额不合法'); - } else if (perDay > 0) { - price = Math.round(perDay * grantDays * 100) / 100; + if (!Number.isFinite(grantDays) || grantDays <= 0 || grantDays > 3650) { + this.ctx.throw(422, '套餐天数不合法,请联系管理员'); + } + if (!Number.isFinite(price) || price <= 0) { + this.ctx.throw(422, '该套餐未设置价格,请联系管理员'); } const order = await this.Order.create({ orderNo: generateOrderNo(), subjectId: Number(subject.id), userId: Number(userId), + planId: Number(plan.id), + planCode: plan.code, + planName: plan.name, days: grantDays, - amount: price, + amount: Math.round(price * 100) / 100, status: 0, - channel: channel || 'mock', + channel: 'mock', expireBefore: subject.expireAt, remark: remark || null, }); - this.ctx.logger.info('[order] 用户 %s 为主体 %s 创建续期订单 %s(%s 天,金额 %s)', - userId, subject.id, order.orderNo, grantDays, price); + this.ctx.logger.info('[order] 用户 %s 为主体 %s 创建续期订单 %s(套餐 %s,%s 天,金额 %s)', + userId, subject.id, order.orderNo, plan.code, grantDays, price); return this.present(order); } + /** 单个订单(续期弹窗轮询支付状态用;必须是该主体成员) */ + async detail({ subjectId, userId, orderNo } = {}) { + await this.ctx.service.subject.findForUser(subjectId, userId); + + const no = String(orderNo || '').trim(); + if (!no) this.ctx.throw(400, 'orderNo 不能为空'); + + const order = await this.Order.findOne({ + where: { orderNo: no, subjectId: Number(subjectId) }, + }); + if (!order) this.ctx.throw(404, '订单不存在'); + return this.present(order); + } + + /** 关闭待支付订单(用户取消 / 重新下单前清理) */ + async close({ subjectId, userId, orderNo } = {}) { + await this.ctx.service.subject.ensureAdmin(subjectId, userId); + + const no = String(orderNo || '').trim(); + if (!no) this.ctx.throw(400, 'orderNo 不能为空'); + + const order = await this.Order.findOne({ + where: { orderNo: no, subjectId: Number(subjectId) }, + }); + if (!order) this.ctx.throw(404, '订单不存在'); + if (Number(order.status) === 1) this.ctx.throw(409, '订单已支付,不能关闭'); + if (Number(order.status) === 2) return this.present(order); + + await order.update({ status: 2 }); + this.ctx.logger.info('[order] 用户 %s 关闭订单 %s', userId, no); + return this.present(order); + } + /** 某主体的订单列表(成员可见) */ async list({ subjectId, userId, page = 1, pageSize = 20 } = {}) { await this.ctx.service.subject.findForUser(subjectId, userId); @@ -164,10 +201,15 @@ class SubjectOrderService extends Service { orderNo: order.orderNo, subjectId: Number(order.subjectId), userId: Number(order.userId), + planId: order.planId === null || order.planId === undefined ? null : Number(order.planId), + planCode: order.planCode || null, + planName: order.planName || null, days: Number(order.days), amount: order.amount === null || order.amount === undefined ? null : Number(order.amount), status: Number(order.status), statusText: STATUS_TEXT[Number(order.status)] || '未知', + /** 前端据此判断要不要继续轮询 */ + pending: Number(order.status) === 0, channel: order.channel || null, transactionId: order.transactionId || null, paidAt: order.paidAt || null, diff --git a/backend/app/service/subject_plan.js b/backend/app/service/subject_plan.js new file mode 100644 index 0000000..f5c49a6 --- /dev/null +++ b/backend/app/service/subject_plan.js @@ -0,0 +1,58 @@ +'use strict'; + +const { Service } = require('egg'); + +/** + * 续期套餐 service + * + * 套餐(天数 + 定价)放在库里,改价不用发版: + * - `list()` 只返回上架套餐(`status=1`),按 `sort` 升序; + * - `findActive()` 下单时按 id 取套餐,**价格只认库里的值**(前端传的金额一律忽略)。 + */ +class SubjectPlanService extends Service { + get Plan() { + return this.app.model.SubjectPlan; + } + + /** 上架套餐列表(任何登录用户可读,续期弹窗用) */ + async list() { + const rows = await this.Plan.findAll({ + where: { status: 1 }, + order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]], + }); + return rows.map(row => this.present(row)); + } + + /** 取一个上架套餐(不存在 / 已下架 → 422) */ + async findActive(planId) { + const id = Number(planId); + if (!Number.isInteger(id) || id <= 0) this.ctx.throw(422, '请选择续期套餐'); + + const plan = await this.Plan.findOne({ where: { id, status: 1 } }); + if (!plan) this.ctx.throw(422, '套餐不存在或已下架,请刷新后重选'); + return plan; + } + + present(plan) { + const price = Number(plan.price); + const original = plan.originalPrice === null || plan.originalPrice === undefined + ? null + : Number(plan.originalPrice); + + return { + id: Number(plan.id), + code: plan.code, + name: plan.name, + days: Number(plan.days), + price, + originalPrice: original, + tag: plan.tag || null, + description: plan.description || null, + sort: Number(plan.sort), + // 折合每天多少钱(展示用,保留两位) + pricePerDay: Number(plan.days) > 0 ? Math.round((price / Number(plan.days)) * 100) / 100 : null, + }; + } +} + +module.exports = SubjectPlanService; diff --git a/backend/database/migrations/20261021180000-create-subject-plans.js b/backend/database/migrations/20261021180000-create-subject-plans.js new file mode 100644 index 0000000..637bb73 --- /dev/null +++ b/backend/database/migrations/20261021180000-create-subject-plans.js @@ -0,0 +1,83 @@ +'use strict'; + +/** + * 续期套餐(subject_plans)+ 默认三档套餐 + * + * 之前续期是「自己输入天数」,改成**选择套餐**:套餐把天数与定价绑在一起,价格由服务端算, + * 前端只传 `planId`(不信任前端传来的金额)。 + * + * 默认三档(价格可在库/接口里改,不用发版): + * 30 天 ¥ 99 + * 180 天 ¥ 499 + * 365 天 ¥ 899 + */ +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, TINYINT, INTEGER, DECIMAL, DATE } = Sequelize; + + await queryInterface.createTable('subject_plans', { + id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false }, + code: { type: STRING(32), allowNull: false, unique: true, comment: '套餐编码(month/半年/年 等,稳定标识)' }, + name: { type: STRING(64), allowNull: false, comment: '套餐名称(展示用)' }, + days: { type: INTEGER.UNSIGNED, allowNull: false, comment: '续期天数' }, + price: { type: DECIMAL(10, 2), allowNull: false, defaultValue: 0, comment: '售价(元)' }, + original_price: { type: DECIMAL(10, 2), allowNull: true, comment: '划线原价(可选)' }, + tag: { type: STRING(16), allowNull: true, comment: '角标文案(如「推荐」「最划算」)' }, + description: { type: STRING(255), allowNull: true, comment: '副标题说明' }, + sort: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '排序(小的在前)' }, + status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1 上架 0 下架' }, + created_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') }, + updated_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') }, + deleted_at: { type: DATE, allowNull: true }, + }, { comment: '主体续期套餐表' }); + + await queryInterface.addIndex('subject_plans', [ 'status', 'sort' ], { name: 'idx_subject_plans_status_sort' }); + + const now = new Date(); + await queryInterface.bulkInsert('subject_plans', [ + { + code: 'p30', + name: '30 天', + days: 30, + price: 99, + original_price: null, + tag: null, + description: '短期试用 / 临时项目', + sort: 10, + status: 1, + created_at: now, + updated_at: now, + }, + { + code: 'p180', + name: '180 天', + days: 180, + price: 499, + original_price: 594, + tag: '推荐', + description: '半年,折合 ¥2.77 / 天', + sort: 20, + status: 1, + created_at: now, + updated_at: now, + }, + { + code: 'p365', + name: '365 天', + days: 365, + price: 899, + original_price: 1204, + tag: '最划算', + description: '一年,折合 ¥2.46 / 天', + sort: 30, + status: 1, + created_at: now, + updated_at: now, + }, + ]); + }, + + async down(queryInterface) { + await queryInterface.dropTable('subject_plans'); + }, +}; diff --git a/backend/database/migrations/20261021180100-add-plan-to-subject-orders.js b/backend/database/migrations/20261021180100-add-plan-to-subject-orders.js new file mode 100644 index 0000000..362f830 --- /dev/null +++ b/backend/database/migrations/20261021180100-add-plan-to-subject-orders.js @@ -0,0 +1,37 @@ +'use strict'; + +/** + * 续期订单补「套餐」快照 + * + * 订单要记下当时买的哪个套餐(id / code / name),套餐后续改价或下架都不影响历史订单对账。 + */ +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT, STRING } = Sequelize; + + await queryInterface.addColumn('subject_orders', 'plan_id', { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '续期套餐 subject_plans.id(内部/手工单可能为空)', + after: 'user_id', + }); + await queryInterface.addColumn('subject_orders', 'plan_code', { + type: STRING(32), + allowNull: true, + comment: '套餐编码快照', + after: 'plan_id', + }); + await queryInterface.addColumn('subject_orders', 'plan_name', { + type: STRING(64), + allowNull: true, + comment: '套餐名称快照', + after: 'plan_code', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn('subject_orders', 'plan_id'); + await queryInterface.removeColumn('subject_orders', 'plan_code'); + await queryInterface.removeColumn('subject_orders', 'plan_name'); + }, +}; diff --git a/backend/test/app/controller/subject-order.test.js b/backend/test/app/controller/subject-order.test.js index 7e39b78..82db048 100644 --- a/backend/test/app/controller/subject-order.test.js +++ b/backend/test/app/controller/subject-order.test.js @@ -64,7 +64,21 @@ describe('test/app/controller/subject-order.test.js', () => { }; } - function mockModels({ memberRole = 1, subject, order, log } = {}) { + /** 套餐行(subject_plans):天数与定价都在库里,下单只认 planId */ + const planRow = (overrides = {}) => instance(Object.assign({ + id: 7, + code: 'p30', + name: '30 天', + days: 30, + price: 99, + originalPrice: null, + tag: null, + description: null, + sort: 10, + status: 1, + }, overrides)); + + function mockModels({ memberRole = 1, subject, order, plan, log } = {}) { mock(app, 'model', { User: { async findByPk() { return instance(Object.assign({}, USER)); } }, SubjectMember: { @@ -75,6 +89,13 @@ describe('test/app/controller/subject-order.test.js', () => { Subject: { async findByPk() { return typeof subject === 'function' ? subject() : subject; }, }, + SubjectPlan: { + async findOne() { + if (plan === undefined) return planRow(); + return typeof plan === 'function' ? plan() : plan; + }, + async findAll() { return [ planRow() ]; }, + }, SubjectOrder: { async create(fields) { return orderRow(Object.assign({ id: 101 }, fields)); }, async findOne() { return typeof order === 'function' ? order() : order; }, @@ -88,15 +109,44 @@ describe('test/app/controller/subject-order.test.js', () => { app.createAnonymousContext().service.subjectState.clearLocalCache(); }); - it('POST /api/web/subjects/:id/orders:管理员下单 → 201(待支付,不动期限)', async () => { - mockModels({ subject: subjectRow(new Date(Date.now() - 86400000)) }); + it('GET /api/web/subject-plans:返回上架套餐(含计算好的每天单价)', async () => { + mockModels(); + + const res = await app.httpRequest().get('/api/web/subject-plans').set(auth()).expect(200); + const list = res.body.data.list; + assert(list.length === 1, JSON.stringify(res.body)); + assert(list[0].days === 30 && list[0].price === 99); + assert(list[0].pricePerDay === 3.3, `pricePerDay 应为 3.3,实际 ${list[0].pricePerDay}`); + }); + + it('POST /api/web/subjects/:id/orders:选套餐下单 → 201(待支付,不动期限,金额取套餐价)', async () => { + const subject = subjectRow(new Date(Date.now() - 86400000)); + let subjectUpdated = 0; + const rawUpdate = subject.update; + subject.update = async (...args) => { + subjectUpdated++; + return rawUpdate(...args); + }; + mockModels({ subject }); const res = await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`) - .set(auth()).send({ days: 30, amount: 99 }).expect(201); + .set(auth()).send({ planId: 7 }).expect(201); assert(res.body.data.orderNo, JSON.stringify(res.body)); assert(res.body.data.status === 0 && res.body.data.days === 30); - assert(res.body.data.amount === 99); + assert(res.body.data.amount === 99, `金额应取套餐价 99,实际 ${res.body.data.amount}`); + assert(res.body.data.planId === 7 && res.body.data.planName === '30 天'); + assert(subjectUpdated === 0, '下单不能改主体期限'); + }); + + it('POST /api/web/subjects/:id/orders:前端传的金额被忽略(只认套餐价)', async () => { + mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)) }); + + const res = await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`) + .set(auth()).send({ planId: 7, amount: 0.01, days: 9999 }).expect(201); + + assert(res.body.data.amount === 99, JSON.stringify(res.body)); + assert(res.body.data.days === 30); }); it('POST /api/web/subjects/:id/orders:普通成员不能下单(403)', async () => { @@ -106,16 +156,28 @@ describe('test/app/controller/subject-order.test.js', () => { }); await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`) - .set(auth()).send({ days: 30 }).expect(403); + .set(auth()).send({ planId: 7 }).expect(403); }); - it('POST /api/web/subjects/:id/orders:天数非法 → 422', async () => { + it('POST /api/web/subjects/:id/orders:没选套餐 / 套餐不存在 → 422', async () => { mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)) }); await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`) - .set(auth()).send({ days: 0 }).expect(422); + .set(auth()).send({}).expect(422); + + mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)), plan: null }); await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`) - .set(auth()).send({ days: 3651 }).expect(422); + .set(auth()).send({ planId: 999 }).expect(422); + }); + + it('POST /api/web/subjects/:id/orders:套餐没配价格 → 422', async () => { + mockModels({ + subject: subjectRow(new Date(Date.now() + 86400000)), + plan: planRow({ price: 0 }), + }); + + await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`) + .set(auth()).send({ planId: 7 }).expect(422); }); it('POST /api/pay/notify:支付成功后主体续期,且缓存失效(设备立刻看到新期限)', async () => { diff --git a/frontend/src/api/subjectApi.ts b/frontend/src/api/subjectApi.ts index 3d8bbcb..f906824 100644 --- a/frontend/src/api/subjectApi.ts +++ b/frontend/src/api/subjectApi.ts @@ -84,3 +84,64 @@ export function confirmMemberBind(code: string): Promise<{ }> { return api.post('/api/subject/member-bind/confirm', { code }); } + +// ---------------- 续期:套餐 + 订单 ---------------- + +/** 续期套餐(库里的天数 + 定价) */ +export interface SubjectPlan { + id: number; + code: string; + name: string; + days: number; + price: number; + originalPrice?: number | null; + tag?: string | null; + description?: string | null; + sort: number; + pricePerDay?: number | null; +} + +/** 续期订单(下单只建单,支付回调确认后才续期) */ +export interface SubjectOrder { + id: number; + orderNo: string; + subjectId: number; + userId: number; + planId?: number | null; + planCode?: string | null; + planName?: string | null; + days: number; + amount?: number | null; + /** 0 待支付 / 1 已支付 / 2 已关闭 */ + status: number; + statusText: string; + /** 是否还在等支付(前端据此决定要不要继续轮询) */ + pending: boolean; + channel?: string | null; + transactionId?: string | null; + paidAt?: string | null; + expireBefore?: string | null; + expireAfter?: string | null; + remark?: string | null; + createdAt?: string | null; +} + +/** 上架套餐列表 */ +export function fetchSubjectPlans(): Promise<{ list: SubjectPlan[] }> { + return api.get<{ list: SubjectPlan[] }>('/api/web/subject-plans'); +} + +/** 选套餐下单(金额由服务端按套餐算,前端不传金额) */ +export function createSubjectOrder(id: number, planId: number): Promise { + return api.post(`/api/web/subjects/${id}/orders`, { planId }); +} + +/** 单笔订单(轮询支付状态) */ +export function fetchSubjectOrder(id: number, orderNo: string): Promise { + return api.get(`/api/web/subjects/${id}/orders/${encodeURIComponent(orderNo)}`); +} + +/** 关闭待支付订单 */ +export function closeSubjectOrder(id: number, orderNo: string): Promise { + return api.post(`/api/web/subjects/${id}/orders/${encodeURIComponent(orderNo)}/close`, {}); +} diff --git a/frontend/src/views/SubjectsView.vue b/frontend/src/views/SubjectsView.vue index 9fb7687..f38778f 100644 --- a/frontend/src/views/SubjectsView.vue +++ b/frontend/src/views/SubjectsView.vue @@ -12,14 +12,19 @@ import ModalBox from '@/components/ModalBox.vue'; import { ApiError } from '@/api/client'; import { addSubjectMember, + closeSubjectOrder, createMemberBindCode, createSubject, + createSubjectOrder, fetchMemberBindStatus, fetchSubjectMembers, + fetchSubjectOrder, + fetchSubjectPlans, removeSubjectMember, - updateSubject, updateSubjectMemberRole, type MemberBindCode, + type SubjectOrder, + type SubjectPlan, } from '@/api/subjectApi'; import { applySubjects, @@ -91,29 +96,121 @@ function useThis(item: SubjectItem) { window.location.reload(); } -const renewing = ref(0); -async function renew(item: SubjectItem) { - const input = window.prompt(`给「${item.name}」续期多少天?(1~3650)`, '30'); - if (!input) return; - const days = Number(input); - if (!Number.isFinite(days) || days <= 0) { - error.value = '续期天数必须是正整数'; +// 续期:选套餐 → 生成订单(待支付)→ 支付回调确认后才真正续期 +const renewOpen = ref(false); +const renewSubject = ref(null); +const plans = ref([]); +const plansLoading = ref(false); +const planId = ref(null); +const creating = ref(false); +const order = ref(null); +const paid = ref(false); +let orderTimer: number | null = null; + +const currentPlan = computed(() => plans.value.find(item => item.id === planId.value) || null); + +async function openRenew(item: SubjectItem) { + renewSubject.value = item; + renewOpen.value = true; + order.value = null; + paid.value = false; + error.value = ''; + ok.value = ''; + stopOrderPolling(); + + if (!plans.value.length) { + plansLoading.value = true; + try { + const data = await fetchSubjectPlans(); + plans.value = data.list; + } catch (err) { + error.value = err instanceof ApiError ? err.message : '套餐加载失败'; + } finally { + plansLoading.value = false; + } + } + + // 默认选中「推荐」那档,没有就选第一档 + const preferred = plans.value.find(p => p.tag) || plans.value[0]; + planId.value = preferred ? preferred.id : null; +} + +/** 生成订单:只建单,不改期限 */ +async function createOrder() { + const subject = renewSubject.value; + if (!subject || !planId.value) { + error.value = '请选择续期套餐'; return; } - renewing.value = item.id; + + creating.value = true; error.value = ''; ok.value = ''; try { - const updated = await updateSubject(item.id, { extendDays: Math.round(days) }); - ok.value = `「${item.name}」已续期,新到期时间:${formatTime(updated.expireAt)}`; - await load(); + order.value = await createSubjectOrder(subject.id, planId.value); + paid.value = false; + startOrderPolling(); } catch (err) { - error.value = err instanceof ApiError ? err.message : '续期失败'; + error.value = err instanceof ApiError ? err.message : '下单失败'; } finally { - renewing.value = 0; + creating.value = false; } } +/** 轮询订单状态:只有支付回调确认后(status=1)才算续期成功 */ +function startOrderPolling() { + stopOrderPolling(); + orderTimer = window.setInterval(async () => { + const subject = renewSubject.value; + const current = order.value; + if (!subject || !current || !current.pending) { + stopOrderPolling(); + return; + } + try { + const latest = await fetchSubjectOrder(subject.id, current.orderNo); + order.value = latest; + if (Number(latest.status) === 1) { + stopOrderPolling(); + paid.value = true; + ok.value = `订单已支付,「${subject.name}」续期 ${latest.days} 天,到期时间:${formatTime(latest.expireAfter)}`; + await load(); + } else if (Number(latest.status) === 2) { + stopOrderPolling(); + } + } catch { + // 网络抖动忽略,下一轮继续 + } + }, 2000); +} + +function stopOrderPolling() { + if (orderTimer !== null) { + window.clearInterval(orderTimer); + orderTimer = null; + } +} + +async function closeOrder() { + const subject = renewSubject.value; + const current = order.value; + if (subject && current && current.pending) { + try { + await closeSubjectOrder(subject.id, current.orderNo); + } catch { + // 关不掉也无所谓:订单会自然过期,不阻塞用户 + } + } + stopOrderPolling(); + order.value = null; +} + +function finishRenew() { + stopOrderPolling(); + renewOpen.value = false; + order.value = null; +} + // ---------------- 成员管理 ---------------- const memberOpen = ref(false); const memberSubject = ref(null); @@ -277,7 +374,10 @@ function copyBindUrl() { } onMounted(load); -onBeforeUnmount(stopBindPolling); +onBeforeUnmount(() => { + stopBindPolling(); + stopOrderPolling(); +}); /** 列表里标出「当前主体」 */ const currentId = computed(() => currentSubjectId.value); @@ -349,14 +449,7 @@ function isSelf(member: SubjectMemberItem) { 进入 - + @@ -486,6 +579,88 @@ function isSelf(member: SubjectMemberItem) { + + + +
+
+ 当前到期时间 + {{ formatTime(renewSubject.expireAt) }} + 已到期 +
+

续期从「当前到期时间」往后顺延;已到期则从今天开始算。

+
+ + +
+

套餐加载中…

+ +
+ + +
+
订单号{{ order.orderNo }}
+
套餐{{ order.planName || `${order.days} 天` }}
+
应付金额¥{{ order.amount ?? '—' }}
+
+ 状态 + + {{ order.statusText }} + +
+ +

+ 订单已生成,尚未续期:支付确认(渠道回调)到账后才会计入期限,本窗口会自动刷新状态。 +

+

+ 支付已确认,主体已续期 {{ order.days }} 天,新到期时间:{{ formatTime(order.expireAfter) }} +

+

订单已关闭,如需续期请重新下单。

+
+ + +
@@ -521,7 +696,6 @@ function isSelf(member: SubjectMemberItem) { .bind-box { text-align: center; } - .bind-qr { width: 200px; height: 200px; @@ -564,4 +738,113 @@ function isSelf(member: SubjectMemberItem) { color: #94a3b8; padding: 24px 0; } + +/* ---------------- 续期弹窗 ---------------- */ +.renew-head { + margin-bottom: 12px; +} + +.renew-head .hint { + margin: 0 0 4px; +} + +.plan-list { + display: flex; + flex-direction: column; + gap: 10px; +} + +.plan-item { + display: flex; + align-items: center; + gap: 12px; + padding: 12px 14px; + border: 1px solid #e5e7eb; + border-radius: 10px; + cursor: pointer; + transition: border-color 0.15s, background 0.15s; +} + +.plan-item:hover { + border-color: #cbd5e1; + background: #f8fafc; +} + +.plan-item.active { + border-color: #2563eb; + background: #eff6ff; + box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.12); +} + +.plan-main { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: 4px; +} + +.plan-title { + display: flex; + align-items: center; + gap: 8px; + font-size: 15px; +} + +.plan-tag { + font-size: 11px; + line-height: 16px; + padding: 0 6px; + border-radius: 999px; + color: #b45309; + background: #fef3c7; +} + +.plan-desc { + font-size: 12px; + color: #64748b; +} + +.plan-price { + display: flex; + flex-direction: column; + align-items: flex-end; + gap: 2px; + white-space: nowrap; +} + +.plan-price b { + font-size: 18px; + color: #dc2626; +} + +.plan-price s { + font-size: 12px; + color: #94a3b8; +} + +.order-box { + display: flex; + flex-direction: column; + gap: 8px; +} + +.order-row { + display: flex; + align-items: center; + gap: 12px; + font-size: 13px; + color: #475569; +} + +.order-row > span:first-child { + width: 84px; + color: #94a3b8; + flex: 0 0 84px; +} + +.order-amount { + color: #dc2626; + font-size: 16px; +}