'use strict'; const { Controller } = require('egg'); const { parsePagination, buildPageResult } = require('../lib/pagination'); /** OMS 内创建的店铺编码前缀:用于区分「OMS 自动生成」与「平台店铺ID」 */ const CODE_PREFIX = 'OMS'; /** 生成店铺编码:OMS + yyMMddHHmmss + 4 位随机数(如 OMS2609111530123456) */ function genShopCode() { const pad = num => String(num).padStart(2, '0'); const d = new Date(); const ts = `${pad(d.getFullYear() % 100)}${pad(d.getMonth() + 1)}${pad(d.getDate())}` + `${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`; const rand = Math.floor(1000 + Math.random() * 9000); return `${CODE_PREFIX}${ts}${rand}`; } /** * @controller ShopController 店铺管理 */ class ShopController extends Controller { /** * @summary 店铺列表 * @description 分页查询店铺,支持名称/编码模糊搜索、平台与状态过滤 * @router get /api/shops * @apikey * @request query integer page 页码,默认 1 * @request query integer pageSize 每页条数,默认 20 * @request query integer principal_id 所属主体ID(必填,需当前账号已绑定该主体) * @request query string keyword 关键词,匹配店铺名称或编码 * @request query string platform 平台标识,如 taobao/pdd/douyin/jd * @request query integer status 状态:1启用 0禁用,不传则不过滤 * @response 200 shopListResponse success */ async index() { const { ctx } = this; const Op = this.app.Sequelize.Op; const { page, pageSize, offset, limit } = parsePagination(ctx.query); const { keyword, platform, status } = ctx.query; const where = {}; where.principal_id = ctx.state.principalId; if (keyword) { where[Op.or] = [ { name: { [Op.like]: `%${keyword}%` } }, { code: { [Op.like]: `%${keyword}%` } }, ]; } if (platform) where.platform = platform; if (status !== undefined && status !== '') where.status = Number(status); const { count, rows } = await ctx.model.Shop.findAndCountAll({ where, offset, limit, order: [[ 'id', 'DESC' ]], }); ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) }; } /** * @summary 店铺详情 * @description 按主键查询店铺基本信息,并附带店铺商品、订单的关联统计,供详情面板展示 * @router get /api/shops/{id} * @apikey * @request path integer *id 店铺主键ID * @response 200 shopDetailResponse success */ async show() { const { ctx } = this; const Op = ctx.app.Sequelize.Op; const shop = await ctx.model.Shop.findByPk(ctx.params.id); if (!shop) { ctx.status = 404; ctx.body = { code: 404, message: '店铺不存在' }; return; } const shopId = shop.id; const [ shopProductCount, boundCount, orderCount, orderAmount, latestOrder ] = await Promise.all([ ctx.model.ShopProduct.count({ where: { shop_id: shopId } }), ctx.model.ShopProduct.count({ where: { shop_id: shopId, bind_type: { [Op.ne]: 0 } } }), ctx.model.Order.count({ where: { shop_id: shopId } }), ctx.model.Order.sum('total_amount', { where: { shop_id: shopId } }), ctx.model.Order.findOne({ where: { shop_id: shopId }, attributes: [ 'created_at' ], order: [[ 'id', 'DESC' ]], raw: true, }), ]); ctx.body = { code: 0, message: 'success', data: { ...shop.get({ plain: true }), stats: { shop_product_count: shopProductCount, shop_product_bound_count: boundCount, order_count: orderCount, order_amount: Number(orderAmount || 0), latest_order_at: latestOrder ? latestOrder.created_at : null, }, }, }; } /** * @summary 新增店铺 * @description name 必填;code 留空时自动生成 OMS 前缀编码(表示该店铺由 OMS 创建), * 传入 code 时校验同一主体下唯一 * @router post /api/shops * @apikey * @request body createShopRequest *body * @response 200 baseResponse success */ async create() { const { ctx } = this; const { name, principal_id: principalId } = ctx.request.body; if (!name) { ctx.status = 400; ctx.body = { code: 400, message: 'name 为必填项' }; return; } // 已有编码(如平台店铺ID)直接用;未填则生成 OMS 前缀编码 const code = String(ctx.request.body.code || '').trim(); let shopCode = code; if (code) { const exist = await ctx.model.Shop.findOne({ where: { principal_id: principalId, code } }); if (exist) { ctx.status = 400; ctx.body = { code: 400, message: '该主体下店铺编码已存在' }; return; } } else { shopCode = await this.nextShopCode(principalId); if (!shopCode) { ctx.status = 500; ctx.body = { code: 500, message: '店铺编码生成失败,请重试' }; return; } } const shop = await ctx.model.Shop.create({ ...ctx.request.body, code: shopCode }); ctx.body = { code: 0, message: 'success', data: { id: shop.id, code: shop.code } }; } /** * 生成同主体下唯一的店铺编码 * @param {number} principalId 主体ID * @return {Promise} 编码,重试多次仍冲突时返回 null */ async nextShopCode(principalId) { const { ctx } = this; for (let i = 0; i < 5; i++) { const code = genShopCode(); const exist = await ctx.model.Shop.findOne({ where: { principal_id: principalId, code } }); if (!exist) return code; } return null; } /** * @summary 更新店铺 * @description 未传入的字段保持原值;code 留空表示不修改 * @router put /api/shops/{id} * @apikey * @request path integer *id 店铺主键ID * @request body updateShopRequest *body * @response 200 baseResponse success */ async update() { const { ctx } = this; const Op = ctx.app.Sequelize.Op; const shop = await ctx.model.Shop.findByPk(ctx.params.id); if (!shop) { ctx.status = 404; ctx.body = { code: 404, message: '店铺不存在' }; return; } delete ctx.request.body.principal_id; // 编码留空视为不修改;改动时校验同主体唯一,避免撞唯一索引报 500 const code = String(ctx.request.body.code || '').trim(); if (code) { const exist = await ctx.model.Shop.findOne({ where: { principal_id: shop.principal_id, code, id: { [Op.ne]: shop.id } }, }); if (exist) { ctx.status = 400; ctx.body = { code: 400, message: '该主体下店铺编码已存在' }; return; } ctx.request.body.code = code; } else { delete ctx.request.body.code; } await shop.update(ctx.request.body); ctx.body = { code: 0, message: 'success', data: { id: shop.id, code: shop.code } }; } /** * @summary 删除店铺 * @description 物理删除店铺,其下店铺商品会一并删除;存在订单引用时请先处理 * @router delete /api/shops/{id} * @apikey * @request path integer *id 店铺主键ID * @response 200 baseResponse success */ async destroy() { const { ctx } = this; const shop = await ctx.model.Shop.findByPk(ctx.params.id); if (!shop) { ctx.status = 404; ctx.body = { code: 404, message: '店铺不存在' }; return; } const orderCount = await ctx.model.Order.count({ where: { shop_id: shop.id } }); if (orderCount) { ctx.status = 400; ctx.body = { code: 400, message: `该店铺下仍有 ${orderCount} 个订单,不能删除` }; return; } await shop.destroy(); ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } }; } } module.exports = ShopController;