'use strict'; const { Service } = require('egg'); /** 续期天数上限(10 年):防止手滑把 365 写成 3650 以外的离谱值 */ const MAX_DAYS = 3650; /** DECIMAL(10,2) 能放下的最大值 */ const MAX_MONEY = 99999999.99; const CODE_PATTERN = /^[A-Za-z0-9_-]{2,32}$/; /** * 平台管理员:续期套餐维护(`/api/web/admin/plans`) * * 续期下单**只认库里的套餐价**(见 `service/subject_order.js`),所以这里改价 / 改天数不用发版。 * - 列表带**已下架**套餐:页面要能把下架的重新上架; * - `code` 是稳定标识(历史订单会快照 `plan_code`),**创建后不能改**; * - 删除是软删;只想让用户端不再展示,用「下架」就够了(历史订单不受影响)。 */ class AdminPlanService extends Service { get Plan() { return this.app.model.SubjectPlan; } /** 全部套餐(含已下架),按 sort 升序 */ async list() { const rows = await this.Plan.findAll({ order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]], }); return rows.map(row => this.present(row)); } /** * 新建套餐 * @param {object} body { code?, name, days, price, originalPrice?, tag?, description?, sort?, status? } */ async create(body = {}) { const payload = this.normalize(body); if (payload.code) { await this.assertCodeFree(payload.code, null); } else { payload.code = await this.uniqueCode(payload.days); } const row = await this.Plan.create(payload); this.ctx.logger.info('[admin] 新增套餐:id=%s code=%s price=%s', row.id, payload.code, payload.price); return this.present(row); } /** * 修改套餐(只改传了的字段;`code` 不可改) * @param {number|string} id * @param {object} body */ async update(id, body = {}) { const row = await this.findPlan(id); const payload = this.normalize(body, row); await row.update(payload); this.ctx.logger.info('[admin] 修改套餐:id=%s(%s)', row.id, JSON.stringify(payload)); return this.present(row); } /** 删除套餐(软删;历史订单已快照套餐信息,不受影响) */ async remove(id) { const row = await this.findPlan(id); await row.destroy(); this.ctx.logger.info('[admin] 删除套餐:id=%s code=%s', row.id, row.code); return { id: Number(row.id) }; } /** 按 id 取套餐,不存在 404 */ async findPlan(id) { const planId = Number(id); if (!Number.isInteger(planId) || planId <= 0) this.ctx.throw(400, 'id 必须是正整数'); const row = await this.Plan.findByPk(planId); if (!row) this.ctx.throw(404, '套餐不存在'); return row; } /** * 校验并整理字段 * * `base` 为空 = 新建(必填项必须传齐);传了原行 = 更新(只校验 / 整理传了的字段)。 */ normalize(rawBody = {}, base = null) { const body = Object.assign({}, rawBody); const has = key => Object.prototype.hasOwnProperty.call(body, key); const data = {}; // 新建时补齐可选项的默认值(更新时空缺 = 不改) if (!base) { if (body.status === undefined || body.status === null) body.status = 1; if (body.sort === undefined || body.sort === null) body.sort = 0; if (body.tag === undefined) body.tag = null; if (body.description === undefined) body.description = null; if (body.originalPrice === undefined) body.originalPrice = null; } if (!base || has('code')) { const code = body.code === undefined || body.code === null ? '' : String(body.code).trim(); if (base) { if (code && code !== String(base.code)) this.ctx.throw(409, '套餐编码创建后不能修改'); } else if (code) { if (!CODE_PATTERN.test(code)) this.ctx.throw(422, '套餐编码只能包含字母、数字、下划线、短横线(2~32 位)'); data.code = code; } } if (!base || has('name')) { const name = body.name === undefined || body.name === null ? '' : String(body.name).trim(); if (!name) this.ctx.throw(422, '请填写套餐名称'); if (name.length > 64) this.ctx.throw(422, '套餐名称不能超过 64 个字符'); data.name = name; } if (!base || has('days')) { const days = Number(body.days); if (!Number.isInteger(days) || days <= 0) this.ctx.throw(422, '续期天数必须是正整数'); if (days > MAX_DAYS) this.ctx.throw(422, `续期天数不能超过 ${MAX_DAYS} 天`); data.days = days; } if (!base || has('price')) { data.price = this.money(body.price, '售价'); } if (!base || has('originalPrice')) { const raw = body.originalPrice; data.originalPrice = raw === undefined || raw === null || raw === '' ? null : this.money(raw, '划线原价'); } if (!base || has('tag')) { const tag = body.tag === undefined || body.tag === null ? '' : String(body.tag).trim(); if (tag.length > 16) this.ctx.throw(422, '角标文案不能超过 16 个字符'); data.tag = tag || null; } if (!base || has('description')) { const description = body.description === undefined || body.description === null ? '' : String(body.description).trim(); if (description.length > 255) this.ctx.throw(422, '副标题说明不能超过 255 个字符'); data.description = description || null; } if (!base || has('sort')) { const sort = Number(body.sort); if (!Number.isInteger(sort) || sort < 0) this.ctx.throw(422, '排序必须是非负整数'); if (sort > 9999) this.ctx.throw(422, '排序不能超过 9999'); data.sort = sort; } if (!base || has('status')) { const status = Number(body.status); if (status !== 0 && status !== 1) this.ctx.throw(422, '状态只能是 1(上架)或 0(下架)'); data.status = status; } return data; } /** 金额:非负数字,保留两位小数 */ money(value, label) { const num = Number(value); if (!Number.isFinite(num)) this.ctx.throw(422, `${label}必须是数字`); if (num < 0) this.ctx.throw(422, `${label}不能小于 0`); if (num > MAX_MONEY) this.ctx.throw(422, `${label}过大`); return Math.round(num * 100) / 100; } /** 编码不能重复(含软删的行,避免撞唯一索引) */ async assertCodeFree(code, id) { const existing = await this.Plan.findOne({ where: { code }, paranoid: false }); if (existing && Number(existing.id) !== Number(id)) this.ctx.throw(409, `套餐编码「${code}」已存在`); } /** 没填 code 时按天数生成:p30、p180…重复了就加后缀 */ async uniqueCode(days) { const base = `p${days}`; let code = base; for (let i = 2; i <= 99; i++) { const existing = await this.Plan.findOne({ where: { code }, paranoid: false }); if (!existing) return code; code = `${base}-${i}`; } this.ctx.throw(409, '同名套餐过多,请手动填写套餐编码'); } /** 展示字段(固定 camelCase) */ present(row) { const price = Number(row.price); const original = row.originalPrice === null || row.originalPrice === undefined ? null : Number(row.originalPrice); const status = Number(row.status) === 1 ? 1 : 0; const days = Number(row.days); return { id: Number(row.id), code: row.code, name: row.name, days, price, originalPrice: original, tag: row.tag || null, description: row.description || null, sort: Number(row.sort), status, statusText: status === 1 ? '上架' : '下架', pricePerDay: days > 0 ? Math.round((price / days) * 100) / 100 : null, createdAt: row.createdAt || null, updatedAt: row.updatedAt || null, }; } } module.exports = AdminPlanService;