feat(shop): 数据库店铺支持拉取商品与订单,一键拉单纳入数据库店铺并收紧货主范围
- 新增 shopDatabaseSync 服务:按商品表/订单表/明细表字段映射读取客户库,写入店铺商品与待审核订单(含明细重建、幂等更新、无明细跳过、已流转单只刷新平台侧数据) - shop_database 控制器新增 pull-products / pull-orders 接口与路由、contract - 一键拉单任务新增 database / all 范围,resolveShops 支持按货主收窄,runShop 走数据库店铺分支 - 店铺列表新增「拉取商品」「拉取订单」,订单页一键拉单可按范围选择店铺 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
eb8c94eacf
commit
c7a3a01faf
@ -1279,6 +1279,10 @@ module.exports = {
|
||||
name: { type: 'string', description: '表名' },
|
||||
comment: { type: 'string', description: '表注释' },
|
||||
},
|
||||
/** 数据库店铺拉取订单入参 */
|
||||
pullShopDatabaseOrderRequest: {
|
||||
days: { type: 'integer', description: '回看天数:大于 0 时按订单表的下单时间列过滤,0 或空表示不限时间(全量)' },
|
||||
},
|
||||
shopDatabaseColumnItem: {
|
||||
name: { type: 'string', description: '列名' },
|
||||
type: { type: 'string', description: '列类型' },
|
||||
|
||||
@ -488,6 +488,68 @@ class ShopDatabaseController extends Controller {
|
||||
await closeQuietly(conn);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @summary 拉取店铺商品(数据库店铺)
|
||||
* @description 按配置的商品表与字段映射读取客户库,写入/更新店铺商品(供绑定系统商品/组合商品)
|
||||
* @router post /api/shops/{id}/database-config/pull-products
|
||||
* @apikey
|
||||
* @request path integer *id 店铺主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async pullProducts() {
|
||||
const { ctx } = this;
|
||||
const shop = await this.loadShop(ctx.params.id);
|
||||
if (!shop) return;
|
||||
try {
|
||||
const result = await ctx.service.shopDatabaseSync.pullProducts(shop);
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
message: `拉取完成:共 ${result.total} 条(新增 ${result.created},更新 ${result.updated})`,
|
||||
data: result,
|
||||
};
|
||||
} catch (err) {
|
||||
ctx.status = err.status || 400;
|
||||
ctx.body = { code: ctx.status, message: err.message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 拉取店铺订单(数据库店铺)
|
||||
* @description 按配置的订单表/明细表与字段映射读取客户库明文订单,写入待审核订单
|
||||
* @router post /api/shops/{id}/database-config/pull-orders
|
||||
* @apikey
|
||||
* @request path integer *id 店铺主键ID
|
||||
* @request body pullShopDatabaseOrderRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async pullOrders() {
|
||||
const { ctx } = this;
|
||||
const shop = await this.loadShop(ctx.params.id);
|
||||
if (!shop) return;
|
||||
// 回看天数:0 表示不限下单时间(全量)
|
||||
const days = Number(ctx.request.body && ctx.request.body.days);
|
||||
const endTime = new Date();
|
||||
const startTime = Number.isInteger(days) && days > 0
|
||||
? new Date(endTime.getTime() - days * 24 * 3600 * 1000)
|
||||
: null;
|
||||
try {
|
||||
const result = await ctx.service.shopDatabaseSync.pullOrders(shop, {
|
||||
startTime,
|
||||
endTime: startTime ? endTime : null,
|
||||
});
|
||||
const scope = startTime ? `最近 ${days} 天` : '全部';
|
||||
const message = `拉取完成(${scope}):${result.orders} 单(新增 ${result.created},更新 ${result.updated}),明细 ${result.items} 条`
|
||||
+ (result.skipped ? `;跳过无明细 ${result.skipped} 单` : '');
|
||||
await ctx.service.shopDatabaseSync.markShopSynced(shop, new Date(), message);
|
||||
ctx.body = { code: 0, message, data: { ...result, start_time: startTime, end_time: endTime } };
|
||||
} catch (err) {
|
||||
await ctx.service.shopDatabaseSync
|
||||
.markShopSynced(shop, new Date(), `拉取失败:${err.message}`)
|
||||
.catch(() => {});
|
||||
ctx.status = err.status || 400;
|
||||
ctx.body = { code: ctx.status, message: err.message };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ShopDatabaseController;
|
||||
|
||||
@ -153,6 +153,9 @@ module.exports = app => {
|
||||
router.post('/api/shops/:id/database-config/connect', jwtAuth, principalCheck({ model: 'Shop' }), controller.shopDatabase.connect);
|
||||
router.get('/api/shops/:id/database-config/tables', jwtAuth, principalCheck({ model: 'Shop' }), controller.shopDatabase.tables);
|
||||
router.get('/api/shops/:id/database-config/columns', jwtAuth, principalCheck({ model: 'Shop' }), controller.shopDatabase.columns);
|
||||
// 数据库店铺拉取(服务端连客户库):店铺商品 / 订单
|
||||
router.post('/api/shops/:id/database-config/pull-products', jwtAuth, principalCheck({ model: 'Shop' }), controller.shopDatabase.pullProducts);
|
||||
router.post('/api/shops/:id/database-config/pull-orders', jwtAuth, principalCheck({ model: 'Shop' }), controller.shopDatabase.pullOrders);
|
||||
router.resources('shops', '/api/shops', jwtAuth, principalCheck({ model: 'Shop' }), controller.shop);
|
||||
// 店铺商品完全来自平台采集:不提供手工新增 / 编辑 / 删除,只保留查询与绑定;
|
||||
// 同步商品时平台已不存在的商品会自动移除
|
||||
|
||||
@ -14,9 +14,11 @@ const STATUS_LABELS = {
|
||||
[STATUS.FAILED]: '失败',
|
||||
};
|
||||
|
||||
/** 拉单范围:当前仅外部打单平台店铺,后续新增来源在此登记 */
|
||||
/** 拉单范围:外部打单平台店铺 / 数据库店铺 / 全部 */
|
||||
const SCOPES = {
|
||||
external_print: '外部打单平台店铺',
|
||||
database: '数据库店铺',
|
||||
all: '全部店铺(打单平台 + 数据库)',
|
||||
};
|
||||
|
||||
/** 回看天数的默认值与上限(0 表示「全部待处理」,不限下单时间) */
|
||||
@ -50,31 +52,68 @@ class OrderSyncTaskService extends Service {
|
||||
|
||||
/**
|
||||
* 按范围解析可拉取的店铺
|
||||
* @param {string} scope 拉单范围
|
||||
* @param {string} scope 拉单范围(external_print / database)
|
||||
* @param {number} principalId 主体ID
|
||||
* @param {Array<number>} [shopIds] 指定店铺ID
|
||||
* @param {Object} [access] 权限范围(所在公司权限只拉自己货主的店铺)
|
||||
* @return {Promise<Array>} 店铺列表
|
||||
*/
|
||||
async resolveShops(scope, principalId, shopIds) {
|
||||
async resolveShops(scope, principalId, shopIds, access) {
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const where = { principal_id: principalId, status: 1 };
|
||||
if (scope === 'external_print') {
|
||||
where.type = 2;
|
||||
where.external_print_account_id = { [Op.ne]: null };
|
||||
} else if (scope === 'database') {
|
||||
where.type = 3;
|
||||
} else if (scope === 'all') {
|
||||
// 打单平台店铺 + 数据库店铺:打单平台店铺需已关联账号
|
||||
where[Op.or] = [
|
||||
{ type: 2, external_print_account_id: { [Op.ne]: null } },
|
||||
{ type: 3 },
|
||||
];
|
||||
} else {
|
||||
return [];
|
||||
}
|
||||
const ids = (shopIds || []).map(Number).filter(id => Number.isInteger(id) && id > 0);
|
||||
if (ids.length) where.id = { [Op.in]: ids };
|
||||
|
||||
// 所在公司权限:只能拉取自己所属公司(货主)的店铺
|
||||
const ownIds = this.ownSubsidiaryIds(access);
|
||||
if (ownIds) {
|
||||
if (!ownIds.length) return [];
|
||||
where.subsidiary_id = { [Op.in]: ownIds };
|
||||
}
|
||||
|
||||
return await this.ctx.model.Shop.findAll({
|
||||
where,
|
||||
attributes: [ 'id', 'code', 'name', 'principal_id', 'type', 'external_print_account_id' ],
|
||||
attributes: [ 'id', 'code', 'name', 'principal_id', 'type', 'subsidiary_id', 'external_print_account_id' ],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
limit: MAX_SHOPS,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 权限范围内的货主ID(集团返回 null 表示不限制)
|
||||
* @param {Object} access 权限上下文
|
||||
* @return {Array<number>|null} 货主ID列表
|
||||
*/
|
||||
ownSubsidiaryIds(access) {
|
||||
if (!access || access.isGroup) return null;
|
||||
return (access.ownCompanyIds || []).map(Number);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析账号在主体下的权限范围(无登录态视为系统操作,按集团放行)
|
||||
* @param {number} userId 用户ID
|
||||
* @param {number} principalId 主体ID
|
||||
* @return {Promise<Object>} 权限上下文
|
||||
*/
|
||||
async resolveAccess(userId, principalId) {
|
||||
if (!userId) return { isGroup: true, ownCompanyIds: [] };
|
||||
return this.ctx.service.access.resolve(userId, principalId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交拉单任务:只落一条待处理记录,立即返回任务ID
|
||||
* @param {Object} payload 提交参数
|
||||
@ -106,9 +145,12 @@ class OrderSyncTaskService extends Service {
|
||||
throw err;
|
||||
}
|
||||
|
||||
const shops = await this.resolveShops(scope, principalId, payload.shop_ids);
|
||||
const access = await this.resolveAccess(userId, principalId);
|
||||
const shops = await this.resolveShops(scope, principalId, payload.shop_ids, access);
|
||||
if (!shops.length) {
|
||||
const err = new Error('没有可拉取的店铺:请先在「外部打单平台」同步商家并开启店铺状态');
|
||||
const err = new Error(scope === 'external_print'
|
||||
? '没有可拉取的店铺:请先在「外部打单平台」同步商家并开启店铺状态'
|
||||
: '没有可拉取的数据库店铺:请先新增数据库店铺并完成数据库配置');
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
@ -287,7 +329,8 @@ class OrderSyncTaskService extends Service {
|
||||
|
||||
let shops = [];
|
||||
try {
|
||||
shops = await this.resolveShops(task.scope, task.principal_id, task.shop_ids || []);
|
||||
const access = await this.resolveAccess(task.created_by, task.principal_id);
|
||||
shops = await this.resolveShops(task.scope, task.principal_id, task.shop_ids || [], access);
|
||||
} catch (err) {
|
||||
await Model.update(
|
||||
{ status: STATUS.FAILED, error_message: truncate(err.message, 500), finished_at: new Date(), progress: 100 },
|
||||
@ -411,6 +454,35 @@ class OrderSyncTaskService extends Service {
|
||||
end_time: task.end_time,
|
||||
};
|
||||
|
||||
// 数据库店铺:走数据库拉取服务,口径与单店「拉取订单」一致
|
||||
if (Number(shop.type) === 3) {
|
||||
try {
|
||||
const result = await ctx.service.shopDatabaseSync.pullOrders(shop, {
|
||||
startTime: task.start_time ? new Date(task.start_time) : null,
|
||||
endTime: task.end_time ? new Date(task.end_time) : null,
|
||||
});
|
||||
const message = `拉取成功:${result.orders} 单(新增 ${result.created},更新 ${result.updated}),明细 ${result.items} 条`
|
||||
+ (result.skipped ? `;跳过无明细 ${result.skipped} 单` : '');
|
||||
await ctx.service.shopDatabaseSync.markShopSynced(shop, new Date(), message);
|
||||
return {
|
||||
...base,
|
||||
success: true,
|
||||
message,
|
||||
orders: result.orders || 0,
|
||||
created: result.created || 0,
|
||||
updated: result.updated || 0,
|
||||
skipped: 0,
|
||||
voided: 0,
|
||||
items: result.items || 0,
|
||||
};
|
||||
} catch (err) {
|
||||
const message = `拉取失败:${err.message}`;
|
||||
await ctx.service.shopDatabaseSync.markShopSynced(shop, new Date(), message).catch(() => {});
|
||||
ctx.logger.warn(`[order-sync-worker] 数据库店铺 ${shop.id} 拉单失败:${err.message}`);
|
||||
return { ...base, success: false, message: err.message };
|
||||
}
|
||||
}
|
||||
|
||||
const account = accounts.get(Number(shop.external_print_account_id));
|
||||
if (!account) {
|
||||
const message = '店铺关联的打单账号不存在';
|
||||
|
||||
517
backend/app/service/shopDatabaseSync.js
Normal file
517
backend/app/service/shopDatabaseSync.js
Normal file
@ -0,0 +1,517 @@
|
||||
'use strict';
|
||||
|
||||
const { Service } = require('egg');
|
||||
const { ORDER_STATUS } = require('../lib/orderStatus');
|
||||
const { buildSnapshot } = require('../lib/orderItemExpand');
|
||||
const { DEFAULT_DB_TYPE, DEFAULT_PORT, DATASETS } = require('../lib/shopDatabaseFields');
|
||||
const {
|
||||
normalizeParams,
|
||||
validateParams,
|
||||
openConnection,
|
||||
closeQuietly,
|
||||
} = require('../lib/shopDatabaseClient');
|
||||
|
||||
/** 单次拉取的订单上限(避免客户库数据量过大拖垮进程) */
|
||||
const MAX_ORDERS_PER_PULL = 2000;
|
||||
|
||||
/**
|
||||
* 截断字符串,避免超出表字段长度
|
||||
* @param {*} value 原始值
|
||||
* @param {number} max 最大长度
|
||||
* @return {string} 截断后的字符串
|
||||
*/
|
||||
function truncateText(value, max) {
|
||||
return String(value == null ? '' : value).slice(0, max);
|
||||
}
|
||||
|
||||
/**
|
||||
* 明细行转列表摘要快照(与订单页 product_info 口径一致)
|
||||
* @param {Array} lines 明细
|
||||
* @return {Array|null} 快照
|
||||
*/
|
||||
function buildProductInfo(lines) {
|
||||
const list = Array.isArray(lines) ? lines : [];
|
||||
if (!list.length) return null;
|
||||
return list.map(line => ({
|
||||
item_code: line.sku_code || line.outer_item_id || null,
|
||||
item_name: line.name || null,
|
||||
quantity: line.quantity,
|
||||
price: line.price,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据库店铺(shops.type=3)拉取服务
|
||||
*
|
||||
* 直接用配置里的「商品表 / 订单表 / 订单明细表 + 字段映射」读取客户自有库的明文数据:
|
||||
* 1. 商品:按商品表映射读全量,按「店铺 + 商品编码 + 规格」写入店铺商品(shop_products);
|
||||
* 2. 订单:按订单表映射读订单、按订单明细表映射读明细(用映射的订单号列关联),
|
||||
* 写入 orders / order_index / order_status_pending / order_status_items,
|
||||
* 再交给 orderItemResolve 按店铺商品绑定关系展开,口径与打单平台拉单一致。
|
||||
*/
|
||||
class ShopDatabaseSyncService extends Service {
|
||||
/**
|
||||
* 取店铺的数据库配置,并校验连接与表映射是否完整
|
||||
* @param {Object} shop 店铺实例(需含 id / principal_id / subsidiary_id / name)
|
||||
* @return {Promise<Object>} 配置实例
|
||||
*/
|
||||
async requireConfig(shop) {
|
||||
const { ctx } = this;
|
||||
const config = await ctx.model.ShopDatabaseConfig.findOne({ where: { shop_id: shop.id } });
|
||||
if (!config) {
|
||||
const err = new Error('该数据库店铺尚未配置数据库连接,请先在「配置」中完成设置');
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
const params = this.paramsOf(config);
|
||||
const paramsError = validateParams(params);
|
||||
if (paramsError) {
|
||||
const err = new Error(`数据库配置不完整:${paramsError}`);
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
for (const dataset of Object.values(DATASETS)) {
|
||||
if (!config[dataset.tableColumn]) {
|
||||
const err = new Error(`数据库配置不完整:未选择${dataset.label}`);
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置转连接参数
|
||||
* @param {Object} config 配置实例
|
||||
* @return {Object} 连接参数
|
||||
*/
|
||||
paramsOf(config) {
|
||||
return normalizeParams({
|
||||
db_type: config.db_type || DEFAULT_DB_TYPE,
|
||||
host: config.host,
|
||||
port: config.port == null ? DEFAULT_PORT : config.port,
|
||||
database_name: config.database_name,
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 按字段映射拼 SELECT:OMS 字段 → 源列(缺映射的字段不查)
|
||||
* @param {Object} conn 连接
|
||||
* @param {Object} table 表名
|
||||
* @param {Object} mapping 字段映射
|
||||
* @param {Object} dataset DATASETS 中的定义
|
||||
* @param {string} [where] 附加 WHERE 语句(已参数化)
|
||||
* @param {Array} [values] WHERE 参数
|
||||
* @return {Promise<Array>} 行数据(键为 OMS 字段名)
|
||||
*/
|
||||
async selectMapped(conn, table, mapping, dataset, where, values) {
|
||||
const map = mapping || {};
|
||||
const cols = dataset.fields
|
||||
.map(field => field.key)
|
||||
.filter(key => map[key])
|
||||
.map(key => `${conn.escapeId(map[key])} AS ${conn.escapeId(key)}`);
|
||||
if (!cols.length) return [];
|
||||
const sql = `SELECT ${cols.join(', ')} FROM ${conn.escapeId(table)}${where ? ` WHERE ${where}` : ''}`;
|
||||
const [ rows ] = await conn.query(sql, values || []);
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取店铺商品:按商品表映射全量读取,写入 / 更新店铺商品
|
||||
* @param {Object} shop 店铺实例
|
||||
* @return {Promise<{total: number, created: number, updated: number}>} 拉取统计
|
||||
*/
|
||||
async pullProducts(shop) {
|
||||
const { ctx } = this;
|
||||
const config = await this.requireConfig(shop);
|
||||
const params = this.paramsOf(config);
|
||||
let conn = null;
|
||||
try {
|
||||
conn = await openConnection(params);
|
||||
const dataset = DATASETS.product;
|
||||
const rows = await this.selectMapped(conn, config.product_table, config.product_fields, dataset);
|
||||
|
||||
const existRows = await ctx.model.ShopProduct.findAll({
|
||||
where: { principal_id: shop.principal_id, shop_id: shop.id },
|
||||
attributes: [ 'id', 'outer_item_id', 'outer_sku_id' ],
|
||||
raw: true,
|
||||
});
|
||||
const existMap = new Map(existRows.map(row => [
|
||||
`${row.outer_item_id}||${row.outer_sku_id || ''}`,
|
||||
Number(row.id),
|
||||
]));
|
||||
|
||||
const now = new Date();
|
||||
let created = 0;
|
||||
let updated = 0;
|
||||
for (const row of rows) {
|
||||
const itemCode = truncateText(row.item_code, 100);
|
||||
if (!itemCode) continue;
|
||||
const spec = row.sku_property == null ? '' : truncateText(row.sku_property, 255);
|
||||
const key = `${itemCode}||${spec}`;
|
||||
const fields = {
|
||||
principal_id: shop.principal_id,
|
||||
subsidiary_id: shop.subsidiary_id == null ? null : Number(shop.subsidiary_id),
|
||||
shop_id: shop.id,
|
||||
outer_item_id: itemCode,
|
||||
outer_sku_id: spec || null,
|
||||
title: truncateText(row.item_name, 255) || null,
|
||||
outer_code: itemCode,
|
||||
spec: spec || null,
|
||||
price: row.price == null || row.price === '' ? null : Number(row.price),
|
||||
status: 1,
|
||||
raw: row,
|
||||
synced_at: now,
|
||||
};
|
||||
const existId = existMap.get(key);
|
||||
if (existId) {
|
||||
await ctx.model.ShopProduct.update(fields, { where: { id: existId } });
|
||||
updated++;
|
||||
} else {
|
||||
await ctx.model.ShopProduct.create(fields);
|
||||
created++;
|
||||
}
|
||||
}
|
||||
await ctx.service.cache.invalidateShop(shop.id);
|
||||
return { total: rows.length, created, updated };
|
||||
} finally {
|
||||
await closeQuietly(conn);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取店铺订单:读订单表 + 明细表,按订单号分组后写入订单与待审核状态表
|
||||
* @param {Object} shop 店铺实例
|
||||
* @param {Object} options 时间窗
|
||||
* @param {Date} [options.startTime] 下单时间起
|
||||
* @param {Date} [options.endTime] 下单时间止
|
||||
* @return {Promise<Object>} 拉取统计
|
||||
*/
|
||||
async pullOrders(shop, options = {}) {
|
||||
const config = await this.requireConfig(shop);
|
||||
const params = this.paramsOf(config);
|
||||
const orderDataset = DATASETS.order;
|
||||
const itemDataset = DATASETS.order_item;
|
||||
let conn = null;
|
||||
try {
|
||||
conn = await openConnection(params);
|
||||
|
||||
// 下单时间可映射时按时间窗过滤,减少读取量
|
||||
const timeColumn = (config.order_fields || {}).place_order_time;
|
||||
let where = '';
|
||||
const values = [];
|
||||
if (timeColumn && options.startTime && options.endTime) {
|
||||
where = `${conn.escapeId(timeColumn)} >= ? AND ${conn.escapeId(timeColumn)} <= ?`;
|
||||
values.push(options.startTime, options.endTime);
|
||||
}
|
||||
const orderRows = await this.selectMapped(
|
||||
conn,
|
||||
config.order_table,
|
||||
config.order_fields,
|
||||
orderDataset,
|
||||
where,
|
||||
values
|
||||
);
|
||||
|
||||
const itemRows = await this.selectMapped(
|
||||
conn,
|
||||
config.order_item_table,
|
||||
config.order_item_fields,
|
||||
itemDataset
|
||||
);
|
||||
|
||||
// 明细按订单号归组(映射的订单号列做关联键)
|
||||
const itemsByOrder = new Map();
|
||||
for (const row of itemRows) {
|
||||
const key = String(row.order_no == null ? '' : row.order_no).trim();
|
||||
if (!key) continue;
|
||||
if (!itemsByOrder.has(key)) itemsByOrder.set(key, []);
|
||||
itemsByOrder.get(key).push(row);
|
||||
}
|
||||
|
||||
const result = { orders: 0, created: 0, updated: 0, items: 0, skipped: 0 };
|
||||
const seen = new Set();
|
||||
for (const orderRow of orderRows) {
|
||||
const sourceOrderNo = String(orderRow.order_no == null ? '' : orderRow.order_no).trim();
|
||||
if (!sourceOrderNo || seen.has(sourceOrderNo)) continue;
|
||||
seen.add(sourceOrderNo);
|
||||
if (seen.size > MAX_ORDERS_PER_PULL) break;
|
||||
|
||||
// 只处理有明细的订单:无明细无法生成可发货的单据
|
||||
const lines = itemsByOrder.get(sourceOrderNo) || [];
|
||||
if (!lines.length) {
|
||||
result.skipped++;
|
||||
continue;
|
||||
}
|
||||
const written = await this.saveOrder(shop, orderRow, lines, sourceOrderNo);
|
||||
result.orders++;
|
||||
if (written.created) result.created++;
|
||||
else result.updated++;
|
||||
result.items += written.items;
|
||||
}
|
||||
return result;
|
||||
} finally {
|
||||
await closeQuietly(conn);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 命中店铺商品(按商品编码 + 规格,规格为空时按编码命中任意规格)
|
||||
* @param {Object} shop 店铺实例
|
||||
* @param {Object} line 明细行
|
||||
* @return {Promise<Object|null>} 店铺商品
|
||||
*/
|
||||
async matchShopProduct(shop, line) {
|
||||
const { ctx } = this;
|
||||
const itemCode = String(line.item_code || '').trim();
|
||||
if (!itemCode) return null;
|
||||
const spec = String(line.sku_property || '').trim();
|
||||
const rows = await ctx.model.ShopProduct.findAll({
|
||||
where: { principal_id: shop.principal_id, shop_id: shop.id, outer_item_id: itemCode },
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
});
|
||||
if (!rows.length) return null;
|
||||
if (spec) {
|
||||
const hit = rows.find(row => String(row.outer_sku_id || '') === spec);
|
||||
if (hit) return hit;
|
||||
}
|
||||
return rows.find(row => !row.outer_sku_id) || rows[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入单个订单(orders + order_index + order_status_pending + order_status_items)
|
||||
* @param {Object} shop 店铺实例
|
||||
* @param {Object} orderRow 订单表映射行
|
||||
* @param {Array} lines 明细行
|
||||
* @param {string} sourceOrderNo 源订单号
|
||||
* @return {Promise<{created: boolean, items: number}>} 写入结果
|
||||
*/
|
||||
async saveOrder(shop, orderRow, lines, sourceOrderNo) {
|
||||
const { ctx } = this;
|
||||
const now = new Date();
|
||||
const orderNo = truncateText(`DB${shop.id}-${sourceOrderNo}`, 50);
|
||||
const subsidiaryId = shop.subsidiary_id == null ? null : Number(shop.subsidiary_id);
|
||||
|
||||
// 明细先解析出店铺商品与绑定的系统商品/组合商品
|
||||
const resolved = [];
|
||||
let itemTotal = 0;
|
||||
let itemAmount = 0;
|
||||
for (const line of lines) {
|
||||
const quantity = Number(line.quantity) || 0;
|
||||
const price = line.price == null || line.price === '' ? 0 : Number(line.price);
|
||||
const matched = await this.matchShopProduct(shop, line);
|
||||
const bound = this.resolveBindings(matched);
|
||||
itemTotal += quantity;
|
||||
itemAmount += quantity * price;
|
||||
resolved.push({ line, quantity, price, matched, bound });
|
||||
}
|
||||
|
||||
const receiver = {
|
||||
name: truncateText(orderRow.receiver, 50),
|
||||
mobile: truncateText(orderRow.mobile, 50),
|
||||
tel: truncateText(orderRow.tel, 50),
|
||||
province: truncateText(orderRow.province, 100),
|
||||
city: truncateText(orderRow.city, 100),
|
||||
area: truncateText(orderRow.area, 100),
|
||||
town: truncateText(orderRow.town, 100),
|
||||
address: truncateText(orderRow.detail_address, 500),
|
||||
zipCode: truncateText(orderRow.zip_code, 20),
|
||||
};
|
||||
const placeOrderTime = orderRow.place_order_time ? new Date(orderRow.place_order_time) : now;
|
||||
const totalAmount = orderRow.total_amount == null || orderRow.total_amount === ''
|
||||
? Number(itemAmount.toFixed(2))
|
||||
: Number(orderRow.total_amount);
|
||||
|
||||
const transaction = await ctx.model.transaction();
|
||||
try {
|
||||
// 1) 订单主表(页面「订单」列表走状态表,这里保留一份与原打单平台拉单一致的结构)
|
||||
const orderFields = {
|
||||
principal_id: shop.principal_id,
|
||||
shop_id: shop.id,
|
||||
order_no: orderNo,
|
||||
order_type: 1,
|
||||
total_amount: totalAmount,
|
||||
receiver: receiver.name || null,
|
||||
remark: truncateText(orderRow.buyer_message, 255) || null,
|
||||
external_order_id: truncateText(sourceOrderNo, 100),
|
||||
platform_type: 'DATABASE',
|
||||
external_created_at: placeOrderTime,
|
||||
synced_at: now,
|
||||
external_data: orderRow,
|
||||
};
|
||||
let order = await ctx.model.Order.findOne({
|
||||
where: { principal_id: shop.principal_id, order_no: orderNo },
|
||||
transaction,
|
||||
});
|
||||
const created = !order;
|
||||
if (order) await order.update(orderFields, { transaction });
|
||||
else order = await ctx.model.Order.create(orderFields, { transaction });
|
||||
|
||||
// 2) 已审核流转出待审核的订单只刷新平台侧数据,不覆盖仓内流程
|
||||
const indexRow = await ctx.model.OrderIndex.findOne({
|
||||
where: { principal_id: shop.principal_id, parent_order_no: sourceOrderNo },
|
||||
attributes: [ 'id', 'current_status' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
|
||||
const headFields = {
|
||||
shop_id: shop.id,
|
||||
subsidiary_id: subsidiaryId,
|
||||
shop_nick: truncateText(shop.name, 200),
|
||||
product_info: buildProductInfo(resolved.map(row => ({
|
||||
sku_code: row.line.item_code,
|
||||
outer_item_id: row.line.item_code,
|
||||
name: row.line.item_name,
|
||||
quantity: row.quantity,
|
||||
price: row.price,
|
||||
}))),
|
||||
receiver: receiver.name,
|
||||
mobile: receiver.mobile,
|
||||
tel: receiver.tel || receiver.mobile,
|
||||
province: receiver.province,
|
||||
city: receiver.city,
|
||||
area: receiver.area,
|
||||
town: receiver.town,
|
||||
detail_address: receiver.address,
|
||||
address: truncateText([ receiver.province, receiver.city, receiver.area, receiver.town, receiver.address ]
|
||||
.filter(Boolean).join(''), 255),
|
||||
zip_code: receiver.zipCode || null,
|
||||
total_amount: totalAmount,
|
||||
freight: Number(orderRow.freight) || 0,
|
||||
item_amount: Number(itemAmount.toFixed(2)),
|
||||
item_total: Number(itemTotal.toFixed(3)),
|
||||
item_kind: resolved.length,
|
||||
buyer_message: truncateText(orderRow.buyer_message, 500),
|
||||
seller_message: truncateText(orderRow.seller_message, 500),
|
||||
place_order_time: placeOrderTime,
|
||||
order_type: 'JYCK',
|
||||
extend_props: { source: 'shop_database', source_order_no: sourceOrderNo },
|
||||
};
|
||||
|
||||
let orderId;
|
||||
if (indexRow && indexRow.current_status !== ORDER_STATUS.PENDING) {
|
||||
await transaction.commit();
|
||||
return { created, items: resolved.length };
|
||||
}
|
||||
if (indexRow) {
|
||||
orderId = indexRow.id;
|
||||
await ctx.model.OrderStatusPending.update(headFields, { where: { id: orderId }, transaction });
|
||||
} else {
|
||||
const index = await ctx.model.OrderIndex.create({
|
||||
order_no: orderNo,
|
||||
parent_order_no: sourceOrderNo,
|
||||
principal_id: shop.principal_id,
|
||||
subsidiary_id: subsidiaryId,
|
||||
current_table: ORDER_STATUS.PENDING,
|
||||
current_status: ORDER_STATUS.PENDING,
|
||||
}, { transaction });
|
||||
orderId = index.id;
|
||||
await ctx.model.OrderStatusPending.create({
|
||||
...headFields,
|
||||
id: orderId,
|
||||
order_no: orderNo,
|
||||
parent_order_no: sourceOrderNo,
|
||||
principal_id: shop.principal_id,
|
||||
subsidiary_id: subsidiaryId,
|
||||
status: ORDER_STATUS.PENDING,
|
||||
}, { transaction });
|
||||
}
|
||||
|
||||
// 3) 明细整体替换后按绑定关系重建(组合商品会展开为子商品行)
|
||||
await ctx.model.OrderStatusItem.destroy({ where: { order_id: orderId }, transaction });
|
||||
const rows = resolved.map(({ line, quantity, price, matched, bound }, idx) => {
|
||||
const outerItemId = truncateText(line.item_code, 100);
|
||||
const snapshotLine = {
|
||||
outer_item_id: outerItemId,
|
||||
outer_sku_id: line.sku_property || null,
|
||||
sku_code: outerItemId,
|
||||
name: line.item_name || null,
|
||||
spec: line.sku_property || null,
|
||||
quantity,
|
||||
price,
|
||||
total_amount: Number((quantity * price).toFixed(2)),
|
||||
raw: line,
|
||||
};
|
||||
return {
|
||||
principal_id: shop.principal_id,
|
||||
order_id: orderId,
|
||||
shop_id: shop.id,
|
||||
order_line_no: String(idx + 1),
|
||||
item_code: outerItemId,
|
||||
item_name: truncateText(line.item_name, 255),
|
||||
plan_qty: quantity,
|
||||
actual_price: price,
|
||||
retail_price: price,
|
||||
ext_code: outerItemId,
|
||||
inventory_type: 'ZP',
|
||||
source_order_code: truncateText(sourceOrderNo, 50),
|
||||
sub_source_order_code: truncateText(`${outerItemId}-${idx + 1}`, 50),
|
||||
shop_product_id: matched ? matched.id : null,
|
||||
product_id: bound.product_id,
|
||||
combo_product_id: bound.combo_product_id,
|
||||
item_type: bound.item_type,
|
||||
parse_status: bound.parse_status,
|
||||
parse_msg: bound.parse_msg,
|
||||
outer_item_id: outerItemId,
|
||||
outer_sku_id: line.sku_property || null,
|
||||
sku_code: outerItemId,
|
||||
spec: truncateText(line.sku_property, 255),
|
||||
quantity,
|
||||
price,
|
||||
total_amount: Number((quantity * price).toFixed(2)),
|
||||
raw: line,
|
||||
platform_snapshot: buildSnapshot(snapshotLine, idx + 1),
|
||||
};
|
||||
});
|
||||
if (rows.length) await ctx.model.OrderStatusItem.bulkCreate(rows, { transaction });
|
||||
await ctx.service.orderItemResolve.rebuildOrderItems([ orderId ], { transaction });
|
||||
|
||||
await transaction.commit();
|
||||
return { created, items: resolved.length };
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 店铺商品绑定结果:已绑定系统商品/组合商品时直接落到对应字段
|
||||
* @param {Object|null} matched 店铺商品
|
||||
* @return {Object} { product_id, combo_product_id, item_type, parse_status, parse_msg }
|
||||
*/
|
||||
resolveBindings(matched) {
|
||||
if (matched && Number(matched.bind_type) === 1 && matched.product_id) {
|
||||
return { product_id: Number(matched.product_id), combo_product_id: null, item_type: 1, parse_status: 1, parse_msg: null };
|
||||
}
|
||||
if (matched && Number(matched.bind_type) === 2 && matched.combo_product_id) {
|
||||
return { product_id: null, combo_product_id: Number(matched.combo_product_id), item_type: 2, parse_status: 1, parse_msg: null };
|
||||
}
|
||||
return {
|
||||
product_id: null,
|
||||
combo_product_id: null,
|
||||
item_type: 1,
|
||||
parse_status: 2,
|
||||
parse_msg: matched ? '店铺商品未绑定系统商品' : '未匹配到店铺商品',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 回写店铺最近拉单时间与结果
|
||||
* @param {Object} shop 店铺实例
|
||||
* @param {Date} syncedAt 拉取时间
|
||||
* @param {string} message 结果说明
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async markShopSynced(shop, syncedAt, message) {
|
||||
const { ctx } = this;
|
||||
await ctx.model.Shop.update(
|
||||
{ last_order_sync_at: syncedAt, last_order_sync_msg: truncateText(message, 255) },
|
||||
{ where: { id: shop.id } }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ShopDatabaseSyncService;
|
||||
@ -123,3 +123,22 @@ export function getShopDatabaseColumns(shopId: number, table: string) {
|
||||
table,
|
||||
})
|
||||
}
|
||||
|
||||
/** 拉取店铺商品(按配置的商品表与字段映射读取客户库) */
|
||||
export function pullShopDatabaseProducts(shopId: number) {
|
||||
return post<{ total: number; created: number; updated: number }>(
|
||||
`/shops/${shopId}/database-config/pull-products`,
|
||||
{},
|
||||
)
|
||||
}
|
||||
|
||||
/** 拉取店铺订单(按配置的订单/明细表与字段映射读取客户库明文订单) */
|
||||
export function pullShopDatabaseOrders(shopId: number, data: { days?: number }) {
|
||||
return post<{
|
||||
orders: number
|
||||
created: number
|
||||
updated: number
|
||||
items: number
|
||||
skipped: number
|
||||
}>(`/shops/${shopId}/database-config/pull-orders`, data)
|
||||
}
|
||||
|
||||
@ -37,12 +37,19 @@ const visible = computed({
|
||||
const POLL_INTERVAL = 3000
|
||||
|
||||
const form = reactive({
|
||||
scope: 'external_print',
|
||||
scope: 'all',
|
||||
/** 回看天数;-1 视为「全部待处理」 */
|
||||
lookback_days: 3,
|
||||
shop_ids: [] as number[],
|
||||
})
|
||||
|
||||
/** 拉单范围选项:打单平台店铺 / 数据库店铺 / 两者全部 */
|
||||
const SCOPE_OPTIONS = [
|
||||
{ label: '全部店铺(打单平台 + 数据库)', value: 'all' },
|
||||
{ label: '外部打单平台店铺', value: 'external_print' },
|
||||
{ label: '数据库店铺', value: 'database' },
|
||||
]
|
||||
|
||||
const LOOKBACK_OPTIONS = [
|
||||
{ label: '最近 1 天', value: 1 },
|
||||
{ label: '最近 3 天', value: 3 },
|
||||
@ -88,11 +95,14 @@ async function loadShops() {
|
||||
if (shopOptions.value.length) return
|
||||
shopsLoading.value = true
|
||||
try {
|
||||
const res = await getShops({ page: 1, pageSize: 500, type: 2 })
|
||||
shopOptions.value = (res.list as ShopItem[]).map(shop => ({
|
||||
label: `${shop.code} ${shop.name}`,
|
||||
value: shop.id,
|
||||
}))
|
||||
// 拉单范围含数据库店铺时,可指定店铺需同时列出打单平台店铺与数据库店铺
|
||||
const types = form.scope === 'database' ? [ 3 ] : (form.scope === 'external_print' ? [ 2 ] : [ 2, 3 ])
|
||||
const lists = await Promise.all(
|
||||
types.map(type => getShops({ page: 1, pageSize: 500, type }).catch(() => ({ list: [] as ShopItem[] }))),
|
||||
)
|
||||
shopOptions.value = lists
|
||||
.flatMap((res) => res.list as ShopItem[])
|
||||
.map(shop => ({ label: `${shop.code} ${shop.name}`, value: shop.id }))
|
||||
} catch {
|
||||
shopOptions.value = []
|
||||
} finally {
|
||||
@ -209,14 +219,14 @@ function rowClassName({ row }: { row: OrderSyncShopItem }) {
|
||||
type="info"
|
||||
:closable="false"
|
||||
show-icon
|
||||
title="会按当前设置从各外部打单平台店铺拉取订单并写入「待审核」;平台已发货/已终结的订单会被自动作废。"
|
||||
title="会按当前范围从打单平台店铺(及数据库店铺)拉取订单并写入「待审核」;平台已发货/已终结的订单会被自动作废。"
|
||||
class="tip"
|
||||
/>
|
||||
|
||||
<el-form :inline="true" size="small" label-width="90px" :disabled="isRunning || submitting">
|
||||
<el-form-item label="拉取范围">
|
||||
<el-select v-model="form.scope" style="width: 220px">
|
||||
<el-option label="外部打单平台店铺(全部)" value="external_print" />
|
||||
<el-select v-model="form.scope" style="width: 280px">
|
||||
<el-option v-for="opt in SCOPE_OPTIONS" :key="opt.value" :label="opt.label" :value="opt.value" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="时间范围">
|
||||
|
||||
@ -20,6 +20,8 @@ import {
|
||||
connectShopDatabase,
|
||||
getShopDatabaseTables,
|
||||
getShopDatabaseColumns,
|
||||
pullShopDatabaseProducts,
|
||||
pullShopDatabaseOrders,
|
||||
type ShopDatabaseDataset,
|
||||
type ShopDatabaseFieldMapping,
|
||||
type ShopDatabaseTable,
|
||||
@ -482,6 +484,59 @@ async function handleSaveDatabaseConfig() {
|
||||
|
||||
/** 正在拉取订单的店铺ID(防止重复点击) */
|
||||
const fetchingOrderId = ref<number | null>(null)
|
||||
|
||||
/* -------------------- 数据库店铺拉取(商品 / 订单) -------------------- */
|
||||
/** 正在拉取商品的店铺ID */
|
||||
const dbPullingProductsId = ref<number | null>(null)
|
||||
|
||||
/** 拉取店铺商品:按配置的商品表读取客户库并写入店铺商品 */
|
||||
async function handlePullDbProducts(row: ShopItem) {
|
||||
dbPullingProductsId.value = row.id
|
||||
try {
|
||||
const res = await pullShopDatabaseProducts(row.id)
|
||||
ElMessage.success(`拉取完成:共 ${res.total} 条(新增 ${res.created},更新 ${res.updated})`)
|
||||
if (currentShop.value && currentShop.value.id === row.id) await fetchDetail(row.id)
|
||||
} catch {
|
||||
// 拦截器已提示
|
||||
} finally {
|
||||
dbPullingProductsId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
/** 数据库店铺拉取订单弹窗(沿用「拉取订单」的天数选择) */
|
||||
const dbPullOrdersVisible = ref(false)
|
||||
const dbPullOrdersSubmitting = ref(false)
|
||||
const dbPullOrdersShop = ref<ShopItem | null>(null)
|
||||
const dbPullOrdersForm = reactive({ days: 7 })
|
||||
|
||||
function openDbPullOrders(row: ShopItem) {
|
||||
dbPullOrdersShop.value = row
|
||||
dbPullOrdersForm.days = 7
|
||||
dbPullOrdersVisible.value = true
|
||||
}
|
||||
|
||||
async function submitDbPullOrders() {
|
||||
const shop = dbPullOrdersShop.value
|
||||
if (!shop) return
|
||||
dbPullOrdersSubmitting.value = true
|
||||
fetchingOrderId.value = shop.id
|
||||
try {
|
||||
const res = await pullShopDatabaseOrders(shop.id, { days: dbPullOrdersForm.days })
|
||||
const scope = dbPullOrdersForm.days === 0 ? '全部' : `最近 ${dbPullOrdersForm.days} 天`
|
||||
ElMessage.success(
|
||||
`拉取完成(${scope}):${res.orders} 单(新增 ${res.created},更新 ${res.updated}),明细 ${res.items} 条` +
|
||||
`${res.skipped ? `;跳过无明细 ${res.skipped} 单` : ''}`,
|
||||
)
|
||||
dbPullOrdersVisible.value = false
|
||||
await fetchList()
|
||||
if (currentShop.value && currentShop.value.id === shop.id) await fetchDetail(shop.id)
|
||||
} catch {
|
||||
// 拦截器已提示
|
||||
} finally {
|
||||
dbPullOrdersSubmitting.value = false
|
||||
fetchingOrderId.value = null
|
||||
}
|
||||
}
|
||||
/** 拉取订单弹窗 */
|
||||
const fetchOrderVisible = ref(false)
|
||||
const fetchOrderSubmitting = ref(false)
|
||||
@ -700,6 +755,20 @@ onMounted(() => {
|
||||
type="primary"
|
||||
@click.stop="openDatabaseConfig(row)"
|
||||
>配置</el-button>
|
||||
<el-button
|
||||
v-if="row.type === 3"
|
||||
link
|
||||
type="primary"
|
||||
:loading="dbPullingProductsId === row.id"
|
||||
@click.stop="handlePullDbProducts(row)"
|
||||
>拉取商品</el-button>
|
||||
<el-button
|
||||
v-if="row.type === 3"
|
||||
link
|
||||
type="primary"
|
||||
:loading="fetchingOrderId === row.id"
|
||||
@click.stop="openDbPullOrders(row)"
|
||||
>拉取订单</el-button>
|
||||
<el-button
|
||||
v-if="row.type === 2"
|
||||
link
|
||||
@ -908,6 +977,30 @@ onMounted(() => {
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog v-model="dbPullOrdersVisible" title="拉取订单(数据库店铺)" width="480px">
|
||||
<el-alert
|
||||
type="info"
|
||||
:closable="false"
|
||||
show-icon
|
||||
class="fetch-order-tip"
|
||||
title="按「订单表 + 订单明细表」的字段映射读取客户库明文订单,写入「待审核」;无明细的订单会跳过,已流转出待审核的订单只刷新平台侧数据"
|
||||
/>
|
||||
<el-form :model="dbPullOrdersForm" label-width="96px">
|
||||
<el-form-item label="店铺">
|
||||
<span>{{ dbPullOrdersShop?.name || '-' }}</span>
|
||||
</el-form-item>
|
||||
<el-form-item label="拉取范围">
|
||||
<el-select v-model="dbPullOrdersForm.days" style="width: 100%">
|
||||
<el-option v-for="item in FETCH_ORDER_DAYS" :key="item.value" :label="item.label" :value="item.value" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="dbPullOrdersVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="dbPullOrdersSubmitting" @click="submitDbPullOrders">开始拉取</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 数据库店铺配置:连接信息 → 测试连通 / 连接拉表 → 选表与字段映射 -->
|
||||
<el-dialog
|
||||
v-model="dbConfigVisible"
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user