'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;