liufumingren eb8c94eacf feat(shop): 新增数据库店铺类型与连接/选表/字段映射配置
- 迁移 shop_database_configs:一店一条,存数据库类型/IP/端口/库名/账号/密码、
  商品表/订单表/订单明细表名、三份字段映射与最近校验结果
- 新增 shopDatabase 控制器与 lib:服务端用 mysql2 连接客户库(8s 超时、utf8mb4),
  提供配置读取/保存、测试连通、连接拉表、拉表列表与表字段;表名走白名单校验
- 保存时连得上则校验表与列真实存在(不存在拒绝保存),连不上则保存并提示未校验
- 店铺新增支持 type=3 数据库店铺;删除店铺时一并清理数据库配置
- 前端:新增店铺可选「数据库店铺」,创建后自动打开配置弹窗;列表对数据库店铺
  显示「配置」,弹窗内填写连接信息、测试连通、连接拉表、选三张表并逐个字段映射
- 契约与路由:补数据库店铺配置相关接口定义

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-05 15:44:06 +08:00

524 lines
19 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const { Controller } = require('egg');
const { parsePagination, buildPageResult } = require('../lib/pagination');
/** OMS 内创建的店铺编码前缀:用于区分「OMS 自动生成」与「平台店铺ID」 */
const CODE_PREFIX = 'OMS';
/** 店铺类型:1 平台店铺(手工/平台)2 外部打单平台商家 */
const SHOP_TYPE_PLATFORM = 1;
/** 店铺类型:外部打单平台导入的商家店铺(货主权限只读) */
const SHOP_TYPE_EXTERNAL = 2;
/** 店铺类型:数据库店铺(自建 MySQL 库拉取明文订单,需单独配置连接与字段映射) */
const SHOP_TYPE_DATABASE = 3;
/** 手工新增时允许选择的店铺类型:平台店铺 / 数据库店铺 */
const CREATABLE_TYPES = [ SHOP_TYPE_PLATFORM, SHOP_TYPE_DATABASE ];
/** 自动拉取订单的最小间隔(分钟) */
const MIN_AUTO_FETCH_INTERVAL = 3;
/**
* 解析自动拉取订单配置
* @param {Object} body 请求体
* @return {{auto_fetch_order?: number, auto_fetch_interval?: number, error?: string}} 解析结果
*/
function parseAutoFetchConfig(body) {
const result = {};
if (body.auto_fetch_order !== undefined) {
const flag = body.auto_fetch_order;
result.auto_fetch_order = flag === true || Number(flag) === 1 ? 1 : 0;
}
const rawInterval = body.auto_fetch_interval;
if (rawInterval !== undefined && rawInterval !== null && rawInterval !== '') {
const interval = Number(rawInterval);
if (!Number.isInteger(interval) || interval < MIN_AUTO_FETCH_INTERVAL) {
return { error: `自动拉取间隔必须是不小于 ${MIN_AUTO_FETCH_INTERVAL} 的整数(分钟)` };
}
result.auto_fetch_interval = interval;
}
return result;
}
/** 生成店铺编码: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禁用,不传则不过滤
* @request query integer type 店铺类型:1平台店铺 2外部打单平台商家,不传则不过滤
* @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, type, subsidiary_id: subsidiaryId } = ctx.query;
const principalId = ctx.state.principalId;
const where = {};
where.principal_id = 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);
if (type !== undefined && type !== '') where.type = Number(type);
if (subsidiaryId !== undefined && subsidiaryId !== '') where.subsidiary_id = Number(subsidiaryId);
// 所在公司权限:店铺列表仅展示自己所属公司(货主)的店铺
const access = await ctx.service.access.resolve(ctx.userId, principalId);
if (!access.isGroup) {
const ownIds = access.ownCompanyIds.map(Number);
if (where.subsidiary_id !== undefined) {
if (!ownIds.includes(Number(where.subsidiary_id))) {
ctx.body = { code: 0, message: 'success', data: buildPageResult([], 0, { page, pageSize }) };
return;
}
} else {
where.subsidiary_id = { [Op.in]: ownIds };
}
}
const { count, rows } = await ctx.model.Shop.findAndCountAll({
where,
offset,
limit,
order: [[ 'id', 'DESC' ]],
include: [
{ model: ctx.model.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false },
],
});
// 数据库模式(预留)的密码不回显;附带扁平货主名称
const list = rows.map(row => {
const plain = row.get({ plain: true });
plain.has_db_password = !!plain.db_password;
plain.subsidiary_name = plain.subsidiary ? plain.subsidiary.name : '';
delete plain.db_password;
return plain;
});
ctx.body = { code: 0, message: 'success', data: buildPageResult(list, 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, {
include: [
{ model: ctx.model.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false },
],
});
if (!shop) {
ctx.status = 404;
ctx.body = { code: 404, message: '店铺不存在' };
return;
}
// 所在公司权限:仅可查看自己所属公司(货主)的店铺
if (!(await this.canAccess(ctx, shop))) {
ctx.status = 403;
ctx.body = { code: 403, 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,
}),
]);
const data = shop.get({ plain: true });
data.has_db_password = !!data.db_password;
data.subsidiary_name = data.subsidiary ? data.subsidiary.name : '';
delete data.db_password;
ctx.body = {
code: 0,
message: 'success',
data: {
...data,
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 时校验同一主体下唯一;type 可选 1 平台店铺(默认)/ 3 数据库店铺
* @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;
}
const autoFetch = parseAutoFetchConfig(ctx.request.body);
if (autoFetch.error) {
ctx.status = 400;
ctx.body = { code: 400, message: autoFetch.error };
return;
}
// 所属货主必填;所在公司权限只能选自己所属公司
const subsidiary = await this.resolveSubsidiaryId(ctx.request.body.subsidiary_id, principalId);
if (!subsidiary.ok) {
ctx.status = 400;
ctx.body = { code: 400, message: subsidiary.message };
return;
}
const access = await ctx.service.access.resolve(ctx.userId, principalId);
if (!access.isGroup && !access.ownCompanyIds.map(Number).includes(Number(subsidiary.value))) {
ctx.status = 403;
ctx.body = { code: 403, message: '只能选择自己所属公司(货主)' };
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 body = { ...ctx.request.body };
delete body.external_print_account_id;
delete body.external_data;
delete body.db_host;
delete body.db_port;
delete body.db_name;
delete body.db_username;
delete body.db_password;
// 店铺类型:不传默认平台店铺;数据库店铺的连接信息在「配置」弹窗单独维护
let shopType = SHOP_TYPE_PLATFORM;
if (body.type !== undefined && body.type !== null && body.type !== '') {
const incoming = Number(body.type);
if (!CREATABLE_TYPES.includes(incoming)) {
ctx.status = 400;
ctx.body = { code: 400, message: '店铺类型仅支持:1 平台店铺 / 3 数据库店铺' };
return;
}
shopType = incoming;
}
delete body.type;
const shop = await ctx.model.Shop.create({
...body,
type: shopType,
code: shopCode,
subsidiary_id: subsidiary.value,
auto_fetch_order: autoFetch.auto_fetch_order == null ? 0 : autoFetch.auto_fetch_order,
auto_fetch_interval: autoFetch.auto_fetch_interval == null
? MIN_AUTO_FETCH_INTERVAL
: autoFetch.auto_fetch_interval,
});
ctx.body = { code: 0, message: 'success', data: { id: shop.id, code: shop.code } };
}
/**
* 校验「所属货主」:必须是当前主体下的下属公司(必填)
* @param {number|string|null|undefined} value 前端传入的 subsidiary_id
* @param {number|string} principalId 当前主体ID
* @return {Promise<{ok: boolean, value?: number, message?: string}>} 校验结果
*/
async resolveSubsidiaryId(value, principalId) {
if (value === undefined || value === null || value === '') {
return { ok: false, message: '请选择所属货主(下属公司)' };
}
const id = Number(value);
if (!Number.isInteger(id) || id <= 0) return { ok: false, message: '所属货主不合法' };
const subsidiary = await this.ctx.model.PrincipalSubsidiary.findOne({
where: { id, principal_id: principalId },
attributes: [ 'id' ],
});
if (!subsidiary) return { ok: false, message: '所属货主不存在或不属于当前集团' };
return { ok: true, value: Number(subsidiary.id) };
}
/**
* 判断货主ID是否属于当前账号自己的公司
* @param {Object} access 权限上下文
* @param {number|null} subsidiaryId 货主ID
* @return {boolean} 是否属于自己公司
*/
isOwnSubsidiary(access, subsidiaryId) {
if (subsidiaryId === null || subsidiaryId === undefined) return false;
return (access.ownCompanyIds || []).map(Number).includes(Number(subsidiaryId));
}
/**
* 判断店铺是否为外部打单平台导入的店铺
* @param {Object} shop 店铺 model 实例
* @return {boolean} 是否外部打单平台店铺
*/
isExternalShop(shop) {
return Number(shop.type) === SHOP_TYPE_EXTERNAL || !!shop.external_print_account_id;
}
/**
* 判断当前账号是否有权访问该店铺(集团权限均可;所在公司权限限自己所属公司)
* @param {Object} ctx egg context
* @param {Object} shop 店铺 model 实例
* @return {Promise<boolean>} 是否有权限
*/
async canAccess(ctx, shop) {
const access = await ctx.service.access.resolve(ctx.userId, shop.principal_id);
if (access.isGroup) return true;
return this.isOwnSubsidiary(access, shop.subsidiary_id);
}
/**
* 生成同主体下唯一的店铺编码
* @param {number} principalId 主体ID
* @return {Promise<string|null>} 编码,重试多次仍冲突时返回 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;
// 所在公司权限:仅可维护自己所属公司(货主)的店铺
if (!(await this.canAccess(ctx, shop))) {
ctx.status = 403;
ctx.body = { code: 403, message: '仅可修改自己所属公司(货主)的店铺' };
return;
}
// 外部打单平台导入的店铺:货主权限只读(仅可拉取订单/同步商品)
const access = await ctx.service.access.resolve(ctx.userId, shop.principal_id);
if (!access.isGroup && this.isExternalShop(shop)) {
ctx.status = 403;
ctx.body = { code: 403, message: '外部打单平台店铺不可编辑,仅可拉取订单和同步商品' };
return;
}
// 店铺创建后不可更改所属货主(历史无货主店铺允许补齐一次)
let subsidiaryChanged = false;
const incomingSubsidiary = ctx.request.body.subsidiary_id;
if (incomingSubsidiary !== undefined && incomingSubsidiary !== null && incomingSubsidiary !== '') {
const subsidiary = await this.resolveSubsidiaryId(incomingSubsidiary, shop.principal_id);
if (!subsidiary.ok) {
ctx.status = 400;
ctx.body = { code: 400, message: subsidiary.message };
return;
}
if (shop.subsidiary_id != null && Number(subsidiary.value) !== Number(shop.subsidiary_id)) {
ctx.status = 400;
ctx.body = { code: 400, message: '店铺创建后不可更改所属货主' };
return;
}
if (!access.isGroup && !this.isOwnSubsidiary(access, subsidiary.value)) {
ctx.status = 403;
ctx.body = { code: 403, message: '只能维护自己所属公司(货主)的店铺' };
return;
}
subsidiaryChanged = shop.subsidiary_id == null;
ctx.request.body.subsidiary_id = subsidiary.value;
} else {
// 未传或传空:保持原货主,不允许清空
delete ctx.request.body.subsidiary_id;
}
// 外部平台导入 / 数据库模式相关字段由对应接入逻辑维护,普通编辑不允许修改
delete ctx.request.body.type;
delete ctx.request.body.external_print_account_id;
delete ctx.request.body.external_data;
delete ctx.request.body.db_host;
delete ctx.request.body.db_port;
delete ctx.request.body.db_name;
delete ctx.request.body.db_username;
delete ctx.request.body.db_password;
// 拉单状态由系统写入(手动/定时拉取),不允许编辑接口修改
delete ctx.request.body.last_order_sync_at;
delete ctx.request.body.last_order_sync_msg;
const autoFetch = parseAutoFetchConfig(ctx.request.body);
if (autoFetch.error) {
ctx.status = 400;
ctx.body = { code: 400, message: autoFetch.error };
return;
}
Object.assign(ctx.request.body, autoFetch);
// 编码留空视为不修改;改动时校验同主体唯一,避免撞唯一索引报 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);
// 货主变更时,店铺商品的货主跟随店铺一起调整
if (subsidiaryChanged) {
await ctx.model.ShopProduct.update(
{ subsidiary_id: shop.subsidiary_id },
{ where: { principal_id: shop.principal_id, shop_id: shop.id } }
);
}
// 店铺资料变更:清掉推送/取号用的店铺基础缓存
await ctx.service.cache.invalidateShop(shop.id);
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 access = await ctx.service.access.resolve(ctx.userId, shop.principal_id);
if (!access.isGroup) {
if (!this.isOwnSubsidiary(access, shop.subsidiary_id)) {
ctx.status = 403;
ctx.body = { code: 403, message: '仅可删除自己所属公司(货主)的店铺' };
return;
}
if (this.isExternalShop(shop)) {
ctx.status = 403;
ctx.body = { code: 403, 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 ctx.model.ShopDatabaseConfig.destroy({ where: { shop_id: shop.id } });
await shop.destroy();
await ctx.service.cache.invalidateShop(ctx.params.id);
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
}
}
module.exports = ShopController;