feat(express): 外部打单快递接口、自定义快递编码与回 OMS 取号
- 外部打单平台快递接口:按账号同步平台模板、绑定快递编码、查看模板明细;打开列表只读库,仅「从平台同步数据」时拉取 - 系统管理新增自定义快递编码字典,订单改快递 / 物流下拉合并系统与自定义编码,推送奇门沿用订单上的编码 - 新增 OpenAPI deliveryorder.getwaybill:WMS 批量回取号(单次≤100、并发4、逐单结果),快递编码只取 WMS 报文,取消/作废/归档返回失败,已取号直接复用 - 新增 openapi_request_idempotency 请求级幂等:request_id 回放、报文摘要校验、30 分钟 stale 接管、7 天定时清理 - 外部打单平台订单按平台 fetch_waybill_no 下发 need_oms_waybill,推送时实时判定并回写单据 - 店铺、打单账号平台配置与「平台+编码→模板」绑定走 Redis 缓存,绑定/账号变更主动失效,避免批量推送与取号逐单查库 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
b14de3193c
commit
eaf957ed14
@ -1119,6 +1119,15 @@ module.exports = {
|
||||
principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入' },
|
||||
merchants: { type: 'array', itemType: 'externalPrintMerchantItem', required: true, description: '要创建到店铺的商家列表(取自商家列表接口)' },
|
||||
},
|
||||
externalPrintExpressInterfaceSaveItem: {
|
||||
id: { type: 'integer', required: true, description: '快递接口记录ID' },
|
||||
custom_code: { type: 'string', description: '绑定的快递编码(系统或自定义,最长 50 字符,传空解除绑定)' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
},
|
||||
saveExternalPrintExpressInterfacesRequest: {
|
||||
principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入' },
|
||||
items: { type: 'array', itemType: 'externalPrintExpressInterfaceSaveItem', required: true, description: '待保存的快递接口设置' },
|
||||
},
|
||||
externalPrintShopCreatedItem: {
|
||||
id: { type: 'integer', description: '店铺主键' },
|
||||
code: { type: 'string', description: '店铺编码(平台标识-账号ID-商家ID)' },
|
||||
@ -1500,7 +1509,7 @@ module.exports = {
|
||||
oaid_order_source_code: { type: 'string', description: 'OAID 订单来源编码(手工单不填写)' },
|
||||
source_order_codes: { type: 'string', description: '来源订单号集合(手工单不填写)' },
|
||||
extend_props: { type: 'string', description: '请求级扩展属性 JSON(手工单固定写入 labels: 手工单)' },
|
||||
need_oms_waybill: { type: 'integer', description: '是否回 OMS 取号:1是 0否(手工创建恒为 0,该字段留给其他来源订单,暂不处理)' },
|
||||
need_oms_waybill: { type: 'integer', description: '是否回 OMS 取号:1是 0否(手工创建恒为 0;外部打单平台订单按平台的 fetch_waybill_no 配置推送)' },
|
||||
name: { type: 'string', description: '收件人姓名(receiverInfo.name)' },
|
||||
tel: { type: 'string', description: '收件人电话(receiverInfo.tel)' },
|
||||
mobile: { type: 'string', description: '收件人移动电话(receiverInfo.mobile)' },
|
||||
@ -1772,6 +1781,38 @@ module.exports = {
|
||||
remark: { type: 'string', description: '备注' },
|
||||
},
|
||||
|
||||
// ---------- 自定义快递编码 custom_express_codes ----------
|
||||
customExpressCodeItem: {
|
||||
id: { type: 'integer', description: '主键' },
|
||||
code: { type: 'string', description: '自定义快递编码(订单 logistics_code)' },
|
||||
name: { type: 'string', description: '自定义快递名称(订单 logistics_name)' },
|
||||
express_code: { type: 'string', description: '对应的系统快递编码(express_companies.code)' },
|
||||
express_name: { type: 'string', description: '对应的系统快递名称' },
|
||||
sort: { type: 'integer', description: '排序(越小越靠前)' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
created_at: { type: 'string', description: '创建时间' },
|
||||
updated_at: { type: 'string', description: '更新时间' },
|
||||
},
|
||||
customExpressCodePage: buildPage('customExpressCodeItem', '自定义快递编码列表'),
|
||||
customExpressCodeListResponse: buildListResponse('customExpressCodePage'),
|
||||
createCustomExpressCodeRequest: {
|
||||
code: { type: 'string', required: true, description: '自定义快递编码(必填,不能与系统快递编码重复)' },
|
||||
name: { type: 'string', required: true, description: '自定义快递名称(必填)' },
|
||||
express_code: { type: 'string', required: true, description: '对应的系统快递编码(必填,须存在于快递公司字典)' },
|
||||
sort: { type: 'integer', description: '排序,默认 0' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用,默认 1' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
},
|
||||
updateCustomExpressCodeRequest: {
|
||||
code: { type: 'string', description: '自定义快递编码' },
|
||||
name: { type: 'string', description: '自定义快递名称' },
|
||||
express_code: { type: 'string', description: '对应的系统快递编码' },
|
||||
sort: { type: 'integer', description: '排序' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
},
|
||||
|
||||
// ---------- 仓库快递映射 warehouse_express_mappings ----------
|
||||
warehouseExpressMappingItem: {
|
||||
id: { type: 'integer', description: '主键' },
|
||||
@ -2337,7 +2378,7 @@ module.exports = {
|
||||
/** 批量修改待审核订单快递公司 */
|
||||
changeOrderStatusLogisticsRequest: {
|
||||
ids: { type: 'array', itemType: 'integer', required: true, description: '待审核订单ID数组' },
|
||||
logistics_code: { type: 'string', required: true, description: '启用的快递公司编码' },
|
||||
logistics_code: { type: 'string', required: true, description: '启用的快递编码(系统快递 express_companies.code 或自定义快递 custom_express_codes.code)' },
|
||||
},
|
||||
orderStatusChangeLogisticsData: {
|
||||
updated: { type: 'integer', description: '更新条数' },
|
||||
|
||||
279
backend/app/controller/customExpressCode.js
Normal file
279
backend/app/controller/customExpressCode.js
Normal file
@ -0,0 +1,279 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* @controller CustomExpressCodeController 自定义快递编码
|
||||
* 全局字典(不区分主体):自定义编码 + 名称 + 对应的系统快递编码
|
||||
*/
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||||
|
||||
/**
|
||||
* 404 响应(资源不存在)
|
||||
* @param {string} message 提示信息
|
||||
* @return {Error} 带 status 的异常
|
||||
*/
|
||||
function notFound(message) {
|
||||
const err = new Error(message);
|
||||
err.status = 404;
|
||||
return err;
|
||||
}
|
||||
|
||||
/**
|
||||
* 400 响应(参数校验失败)
|
||||
* @param {string} message 提示信息
|
||||
* @return {Error} 带 status 的异常
|
||||
*/
|
||||
function badRequest(message) {
|
||||
const err = new Error(message);
|
||||
err.status = 400;
|
||||
return err;
|
||||
}
|
||||
|
||||
class CustomExpressCodeController extends Controller {
|
||||
/**
|
||||
* @summary 自定义快递编码列表
|
||||
* @description 分页查询自定义快递编码,支持按编码 / 名称 / 对应系统编码 / 状态过滤
|
||||
* @router get /api/custom-express-codes
|
||||
* @apikey
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 20
|
||||
* @request query string keyword 关键词,匹配自定义编码 / 名称
|
||||
* @request query string express_code 对应的系统快递编码
|
||||
* @request query integer status 状态:1启用 0禁用
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
|
||||
const { keyword, express_code: expressCode, status } = ctx.query;
|
||||
|
||||
const where = {};
|
||||
const text = String(keyword || '').trim();
|
||||
if (text) {
|
||||
where[Op.or] = [
|
||||
{ code: { [Op.like]: `%${text}%` } },
|
||||
{ name: { [Op.like]: `%${text}%` } },
|
||||
];
|
||||
}
|
||||
if (expressCode) where.express_code = String(expressCode).trim();
|
||||
if (status !== undefined && status !== '') where.status = Number(status) === 0 ? 0 : 1;
|
||||
|
||||
const { count, rows } = await ctx.model.CustomExpressCode.findAndCountAll({
|
||||
where,
|
||||
offset,
|
||||
limit,
|
||||
order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.ExpressCompany,
|
||||
as: 'expressCompany',
|
||||
attributes: [ 'id', 'code', 'name' ],
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 快递编码下拉(自定义 + 系统)
|
||||
* @description 返回启用的自定义快递编码与系统快递公司,供订单选择物流公司、快递接口绑定使用;
|
||||
* source=custom 表示自定义(express_code 为其对应的系统编码),source=system 表示系统快递
|
||||
* @router get /api/custom-express-codes/options
|
||||
* @apikey
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async options() {
|
||||
const { ctx } = this;
|
||||
const [ customs, systems ] = await Promise.all([
|
||||
ctx.model.CustomExpressCode.findAll({
|
||||
where: { status: 1 },
|
||||
attributes: [ 'code', 'name', 'express_code', 'sort' ],
|
||||
order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
}),
|
||||
ctx.model.ExpressCompany.findAll({
|
||||
where: { status: 1 },
|
||||
attributes: [ 'id', 'code', 'name', 'sort' ],
|
||||
order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
}),
|
||||
]);
|
||||
|
||||
const systemNameByCode = new Map(systems.map(row => [ row.code, row.name ]));
|
||||
const customRows = customs.map(row => ({
|
||||
code: row.code,
|
||||
name: row.name,
|
||||
source: 'custom',
|
||||
express_code: row.express_code,
|
||||
express_name: systemNameByCode.get(row.express_code) || row.express_code,
|
||||
sort: Number(row.sort) || 0,
|
||||
}));
|
||||
const systemRows = systems.map(row => ({
|
||||
code: row.code,
|
||||
name: row.name,
|
||||
source: 'system',
|
||||
express_code: row.code,
|
||||
express_name: row.name,
|
||||
sort: Number(row.sort) || 0,
|
||||
}));
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: [ ...customRows, ...systemRows ] };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 自定义快递编码详情
|
||||
* @router get /api/custom-express-codes/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const item = await ctx.model.CustomExpressCode.findByPk(ctx.params.id, {
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.ExpressCompany,
|
||||
as: 'expressCompany',
|
||||
attributes: [ 'id', 'code', 'name' ],
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
if (!item) {
|
||||
this._fail(ctx, notFound('自定义快递编码不存在'), '自定义快递编码不存在');
|
||||
return;
|
||||
}
|
||||
ctx.body = { code: 0, message: 'success', data: item };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 新增自定义快递编码
|
||||
* @description 自定义编码不能与系统快递编码重复;对应的系统快递编码必须存在
|
||||
* @router post /api/custom-express-codes
|
||||
* @apikey
|
||||
* @request body createCustomExpressCodeRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async create() {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
const payload = await this._validate(ctx.request.body || {});
|
||||
const item = await ctx.model.CustomExpressCode.create(payload);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: item.id } };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '新增自定义快递编码失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 修改自定义快递编码
|
||||
* @description 未传字段保持原值;编码变更同样校验唯一性与系统编码冲突
|
||||
* @router put /api/custom-express-codes/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 主键ID
|
||||
* @request body updateCustomExpressCodeRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async update() {
|
||||
const { ctx } = this;
|
||||
const item = await ctx.model.CustomExpressCode.findByPk(ctx.params.id);
|
||||
if (!item) {
|
||||
this._fail(ctx, notFound('自定义快递编码不存在'), '自定义快递编码不存在');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const merged = { ...item.get({ plain: true }), ...(ctx.request.body || {}) };
|
||||
const payload = await this._validate(merged, item.id);
|
||||
await item.update(payload);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: item.id } };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '修改自定义快递编码失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 删除自定义快递编码
|
||||
* @description 历史订单已保存编码与名称快照,删除字典不影响已创建的订单
|
||||
* @router delete /api/custom-express-codes/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async destroy() {
|
||||
const { ctx } = this;
|
||||
const item = await ctx.model.CustomExpressCode.findByPk(ctx.params.id);
|
||||
if (!item) {
|
||||
this._fail(ctx, notFound('自定义快递编码不存在'), '自定义快递编码不存在');
|
||||
return;
|
||||
}
|
||||
await item.destroy();
|
||||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并归一化入参
|
||||
* @param {Object} body 入参
|
||||
* @param {number|null} id 修改时的记录ID(用于唯一性排除自身)
|
||||
* @return {Promise<Object>} 归一化后的字段
|
||||
*/
|
||||
async _validate(body = {}, id = null) {
|
||||
const { ctx } = this;
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const code = String(body.code == null ? '' : body.code).trim();
|
||||
const name = String(body.name == null ? '' : body.name).trim();
|
||||
const expressCode = String(body.express_code == null ? '' : body.express_code).trim();
|
||||
|
||||
if (!code) throw badRequest('code(自定义快递编码)为必填项');
|
||||
if (code.length > 50) throw badRequest('自定义快递编码不能超过 50 个字符');
|
||||
if (!name) throw badRequest('name(自定义快递名称)为必填项');
|
||||
if (name.length > 100) throw badRequest('自定义快递名称不能超过 100 个字符');
|
||||
if (!expressCode) throw badRequest('express_code(对应的系统快递编码)为必填项');
|
||||
|
||||
const systemCompany = await ctx.model.ExpressCompany.findOne({
|
||||
where: { code: expressCode },
|
||||
attributes: [ 'id' ],
|
||||
});
|
||||
if (!systemCompany) throw badRequest(`系统快递编码 ${expressCode} 不存在,请先在快递公司字典中维护`);
|
||||
|
||||
const systemSameCode = await ctx.model.ExpressCompany.findOne({
|
||||
where: { code },
|
||||
attributes: [ 'id' ],
|
||||
});
|
||||
if (systemSameCode) throw badRequest(`自定义编码 ${code} 与系统快递编码重复,请换一个编码`);
|
||||
|
||||
const where = { code };
|
||||
if (id != null) where.id = { [Op.ne]: id };
|
||||
const exist = await ctx.model.CustomExpressCode.findOne({ where, attributes: [ 'id' ] });
|
||||
if (exist) throw badRequest(`自定义编码 ${code} 已存在`);
|
||||
|
||||
return {
|
||||
code,
|
||||
name,
|
||||
express_code: expressCode,
|
||||
sort: Number.isFinite(Number(body.sort)) ? Number(body.sort) : 0,
|
||||
status: body.status === 0 || body.status === '0' || body.status === false ? 0 : 1,
|
||||
remark: String(body.remark == null ? '' : body.remark).trim().slice(0, 255) || null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一错误响应
|
||||
* @param {Object} ctx 上下文
|
||||
* @param {Error} err 异常(可带 status)
|
||||
* @param {string} fallbackMessage 兜底提示
|
||||
* @return {void} 无
|
||||
*/
|
||||
_fail(ctx, err, fallbackMessage) {
|
||||
const status = Number(err && err.status) || 500;
|
||||
ctx.status = status;
|
||||
ctx.body = { code: status, message: (err && err.message) || fallbackMessage };
|
||||
if (status >= 500) ctx.logger.error('[customExpressCode] %s', (err && err.message) || fallbackMessage, err);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CustomExpressCodeController;
|
||||
@ -244,6 +244,7 @@ class ExternalPrintAccountController extends Controller {
|
||||
}
|
||||
|
||||
await item.update(patch);
|
||||
await ctx.service.cache.invalidateExternalPrintAccount(item.id);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: item.id } };
|
||||
}
|
||||
|
||||
@ -990,6 +991,7 @@ class ExternalPrintAccountController extends Controller {
|
||||
}
|
||||
|
||||
await item.destroy();
|
||||
await ctx.service.cache.invalidateExternalPrintAccount(item.id);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||||
}
|
||||
}
|
||||
|
||||
169
backend/app/controller/externalPrintExpressInterface.js
Normal file
169
backend/app/controller/externalPrintExpressInterface.js
Normal file
@ -0,0 +1,169 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* @controller ExternalPrintExpressInterfaceController 外部打单平台快递接口
|
||||
* 归属打单账号:在「外部打单平台」页按账号查看 / 设置,前端不直连平台
|
||||
*/
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { buildPageResult } = require('../lib/pagination');
|
||||
|
||||
class ExternalPrintExpressInterfaceController extends Controller {
|
||||
/**
|
||||
* 取当前主体下的账号(需带平台配置)
|
||||
* @param {number|string} id 账号ID
|
||||
* @return {Promise<Object|null>} 账号实例
|
||||
*/
|
||||
async findAccount(id) {
|
||||
const { ctx } = this;
|
||||
const principalId = ctx.state.principalId;
|
||||
if (principalId == null) return null;
|
||||
return ctx.model.ExternalPrintAccount.findOne({
|
||||
where: { id, principal_id: principalId },
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.ExternalPrintPlatform,
|
||||
as: 'platform',
|
||||
attributes: [ 'id', 'code', 'name', 'url', 'fetch_waybill_no' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 快递接口列表
|
||||
* @description 返回账号已落库的快递接口(含失效记录),支持按状态 / 平台 / 快递公司 / 关键词过滤
|
||||
* @router get /api/external-print-accounts/{id}/express-interfaces
|
||||
* @apikey
|
||||
* @request path integer *id 账号主键ID
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 20
|
||||
* @request query integer status 状态:1有效 0已失效,不传返回全部
|
||||
* @request query string platform_code OMS 平台编码(如 PDD)
|
||||
* @request query string express_company_code 平台快递公司编码(如 YUNDA)
|
||||
* @request query string keyword 关键词(模板名称 / 快递公司 / 店铺 / 自定义编码)
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const account = await this.findAccount(ctx.params.id);
|
||||
if (!account) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '打单账号不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await ctx.service.externalPrintExpressInterface.list(account, ctx.query, ctx.state.principalId);
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
message: 'success',
|
||||
data: buildPageResult(result.list, result.total, { page: result.page, pageSize: result.pageSize }),
|
||||
};
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '查询快递接口失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 从平台全量拉取快递接口
|
||||
* @description 按账号下全部外部店铺的平台分区拉取面单模板;平台侧已不存在的模板保留并标记为失效
|
||||
* @router post /api/external-print-accounts/{id}/sync-express-interfaces
|
||||
* @apikey
|
||||
* @request path integer *id 账号主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async sync() {
|
||||
const { ctx } = this;
|
||||
const account = await this.findAccount(ctx.params.id);
|
||||
if (!account) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '打单账号不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await ctx.service.externalPrintExpressInterface.sync(account, ctx.state.principalId);
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '拉取快递接口失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 保存快递接口设置
|
||||
* @description 设置自定义编码(OMS 快递公司编码)与默认类型(none / platform / express);
|
||||
* 默认类型为单选,同账号同平台或同快递只保留一个默认
|
||||
* @router put /api/external-print-accounts/{id}/express-interfaces
|
||||
* @apikey
|
||||
* @request path integer *id 账号主键ID
|
||||
* @request body saveExternalPrintExpressInterfacesRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async saveSettings() {
|
||||
const { ctx } = this;
|
||||
const account = await this.findAccount(ctx.params.id);
|
||||
if (!account) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '打单账号不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await ctx.service.externalPrintExpressInterface.saveSettings(
|
||||
account,
|
||||
(ctx.request.body || {}).items,
|
||||
ctx.state.principalId
|
||||
);
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '保存快递接口设置失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 快递接口明细
|
||||
* @description 实时请求平台的「面单账号明细」接口,返回网点 / 账号等信息(凭据字段已屏蔽)
|
||||
* @router get /api/external-print-accounts/{id}/express-interfaces/{interfaceId}/detail
|
||||
* @apikey
|
||||
* @request path integer *id 账号主键ID
|
||||
* @request path integer *interfaceId 快递接口记录ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async detail() {
|
||||
const { ctx } = this;
|
||||
const account = await this.findAccount(ctx.params.id);
|
||||
if (!account) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '打单账号不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await ctx.service.externalPrintExpressInterface.detail(
|
||||
account,
|
||||
ctx.params.interfaceId,
|
||||
ctx.state.principalId
|
||||
);
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '查看快递接口明细失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一错误响应
|
||||
* @param {Object} ctx 上下文
|
||||
* @param {Error} err 异常(可带 status)
|
||||
* @param {string} fallbackMessage 兜底提示
|
||||
* @return {void} 无
|
||||
*/
|
||||
_fail(ctx, err, fallbackMessage) {
|
||||
const status = Number(err && err.status) || 500;
|
||||
ctx.status = status;
|
||||
ctx.body = { code: status, message: (err && err.message) || fallbackMessage };
|
||||
if (status >= 500) ctx.logger.error('[externalPrintExpressInterface] %s', (err && err.message) || fallbackMessage, err);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ExternalPrintExpressInterfaceController;
|
||||
@ -6,6 +6,7 @@ const { toSuccess, toFailure, nowTimestamp } = require('../lib/apiResponse');
|
||||
const { normalizeTimestamp, isTimestampValid, parseBody } = require('../lib/openapiCallback');
|
||||
const { recordCallbackLog } = require('../lib/callbackLog');
|
||||
const openapiMethods = require('../lib/openapiMethods');
|
||||
const openapiIdempotency = require('../lib/openapiIdempotency');
|
||||
|
||||
/**
|
||||
* @controller OpenapiController 对外通用回调接口(公开)
|
||||
@ -19,8 +20,11 @@ const openapiMethods = require('../lib/openapiMethods');
|
||||
* 处理流程:校验系统参数与时间戳 → 按 app_key 定位仓库接口配置与仓库(数据隔离靠
|
||||
* warehouse_apis.principal_id / warehouse_id)→ 验签 → 按 method 分发到
|
||||
* app/lib/openapiMethods.js 中注册的方法(index.ping / entryorder.confirm / entryorder.match /
|
||||
* deliveryorder.confirm / stockout.confirm / order.cancel),单据处理统一走 app/lib/orderCallback.js。
|
||||
* deliveryorder.confirm / deliveryorder.getwaybill / stockout.confirm / order.cancel),
|
||||
* 单据处理统一走 app/lib/orderCallback.js。
|
||||
* 每次请求(含未通过校验的)都会写入 callback_logs,记录请求 query/报文与返回报文。
|
||||
* 带 request_id 的请求按 (app_key, method, request_id) 幂等:处理完成后保存完整响应,
|
||||
* 重复请求直接回放原响应(见 app/lib/openapiIdempotency.js)。
|
||||
*/
|
||||
class OpenapiController extends Controller {
|
||||
/**
|
||||
@ -38,6 +42,32 @@ class OpenapiController extends Controller {
|
||||
result = { ok: false, httpStatus: 500, code: 500, message: `接口错误: ${err.message}` };
|
||||
}
|
||||
|
||||
// 幂等重放:直接返回首次处理的完整响应(含批量逐单结果)
|
||||
if (result.replay) {
|
||||
const body = result.replay.body || toFailure({
|
||||
message: '幂等记录缺少响应报文,请更换 request_id 后重试',
|
||||
code: 500,
|
||||
});
|
||||
ctx.status = result.replay.httpStatus || 200;
|
||||
ctx.body = body;
|
||||
ctx.type = 'application/json';
|
||||
recordCallbackLog(this.app, {
|
||||
method: ctx.query.method,
|
||||
appKey: ctx.query.app_key || ctx.query.appkey,
|
||||
query: ctx.query,
|
||||
requestBody: ctx.request.body,
|
||||
responseBody: body,
|
||||
api: result.api,
|
||||
warehouse: result.warehouse,
|
||||
httpStatus: ctx.status,
|
||||
ok: !!body && body.flag === 'success',
|
||||
message: `幂等重放(request_id=${result.requestId || ''})`,
|
||||
duration: Date.now() - startedAt,
|
||||
ip: ctx.ip,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const ok = !!result.ok;
|
||||
const httpStatus = ok ? 200 : (result.httpStatus || 500);
|
||||
const body = ok
|
||||
@ -48,6 +78,11 @@ class OpenapiController extends Controller {
|
||||
ctx.body = body;
|
||||
ctx.type = 'application/json';
|
||||
|
||||
// 幂等结果落库:同 request_id 重试时直接回放该响应
|
||||
if (result.idempotency) {
|
||||
await openapiIdempotency.finish(ctx, result.idempotency, { httpStatus, body, ok });
|
||||
}
|
||||
|
||||
// 回调日志:请求(query/报文)+ 返回(业务码/报文),未通过 app_key 校验的请求同样记录
|
||||
recordCallbackLog(this.app, {
|
||||
method: ctx.query.method,
|
||||
@ -143,7 +178,54 @@ class OpenapiController extends Controller {
|
||||
};
|
||||
}
|
||||
|
||||
const handled = await handler(ctx, { api, warehouse, body, query, appKey, method, timestamp });
|
||||
// 幂等:验签与 method 校验通过后按 request_id 占用,避免重复执行
|
||||
const idempotency = await openapiIdempotency.begin(ctx, { appKey, method, body, api, warehouse });
|
||||
if (idempotency.replay) {
|
||||
if (idempotency.replay.invalid) {
|
||||
return {
|
||||
ok: false,
|
||||
httpStatus: 400,
|
||||
code: 400,
|
||||
message: 'request_id 已被使用且报文不一致,请更换 request_id 后重试',
|
||||
api,
|
||||
warehouse,
|
||||
};
|
||||
}
|
||||
if (idempotency.replay.processing) {
|
||||
return {
|
||||
ok: false,
|
||||
httpStatus: 409,
|
||||
code: 409,
|
||||
message: '相同 request_id 的请求正在处理中,请稍后重试',
|
||||
api,
|
||||
warehouse,
|
||||
};
|
||||
}
|
||||
return {
|
||||
replay: idempotency.replay,
|
||||
requestId: idempotency.requestId,
|
||||
api,
|
||||
warehouse,
|
||||
};
|
||||
}
|
||||
const idemContext = { idempotency, requestId: idempotency.requestId };
|
||||
|
||||
let handled;
|
||||
try {
|
||||
handled = await handler(ctx, { api, warehouse, body, query, appKey, method, timestamp });
|
||||
} catch (err) {
|
||||
ctx.logger.error('[openapi] 业务处理异常', err);
|
||||
return {
|
||||
ok: false,
|
||||
httpStatus: 500,
|
||||
code: 500,
|
||||
message: `接口错误: ${err.message}`,
|
||||
api,
|
||||
warehouse,
|
||||
...idemContext,
|
||||
};
|
||||
}
|
||||
|
||||
// 方法返回 { ok, message, data }:ok=false 视为业务处理失败(HTTP 400),便于调用方重试/告警
|
||||
if (handled && handled.ok === false) {
|
||||
return {
|
||||
@ -154,6 +236,7 @@ class OpenapiController extends Controller {
|
||||
data: handled.data,
|
||||
api,
|
||||
warehouse,
|
||||
...idemContext,
|
||||
};
|
||||
}
|
||||
return {
|
||||
@ -162,6 +245,7 @@ class OpenapiController extends Controller {
|
||||
data: handled ? handled.data : null,
|
||||
api,
|
||||
warehouse,
|
||||
...idemContext,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@ -429,7 +429,8 @@ class OrderStatusController extends Controller {
|
||||
|
||||
/**
|
||||
* @summary 批量修改待审核订单快递
|
||||
* @description 仅待审核订单可修改;快递公司须为启用的快递字典项,并同步更新编码与名称快照。
|
||||
* @description 仅待审核订单可修改;支持系统快递公司或自定义快递编码(启用项),
|
||||
* 并同步更新 logistics_code / logistics_name 快照(推送奇门时原样下发)。
|
||||
* @router post /api/order-status/change-logistics
|
||||
* @apikey
|
||||
* @request body changeOrderStatusLogisticsRequest
|
||||
|
||||
@ -298,6 +298,8 @@ class ShopController extends Controller {
|
||||
}
|
||||
|
||||
await shop.update(ctx.request.body);
|
||||
// 店铺资料变更:清掉推送/取号用的店铺基础缓存
|
||||
await ctx.service.cache.invalidateShop(shop.id);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: shop.id, code: shop.code } };
|
||||
}
|
||||
|
||||
@ -327,6 +329,7 @@ class ShopController extends Controller {
|
||||
}
|
||||
|
||||
await shop.destroy();
|
||||
await ctx.service.cache.invalidateShop(ctx.params.id);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||||
}
|
||||
}
|
||||
|
||||
70
backend/app/lib/externalPrintConfig.js
Normal file
70
backend/app/lib/externalPrintConfig.js
Normal file
@ -0,0 +1,70 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 外部打单(店铺 / 账号 / 平台)配置读取
|
||||
*
|
||||
* 推送与取号都是逐单处理,直接查库会放大成 N 倍数据库压力,这里统一走缓存服务:
|
||||
* 命中返回缓存,未命中查库并回写;缓存服务不可用(如单元测试直接 new Service)时降级直查。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 读取店铺基础资料(按主体隔离校验)
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Number} shopId 店铺ID
|
||||
* @param {Number} [principalId] 主体ID,传入时校验归属
|
||||
* @return {Promise<Object|null>} 店铺基础资料(plain),不存在或跨主体为 null
|
||||
*/
|
||||
async function getShopBasic(ctx, shopId, principalId) {
|
||||
if (!shopId) return null;
|
||||
|
||||
const cache = ctx.service && ctx.service.cache;
|
||||
let shop = null;
|
||||
if (cache && typeof cache.getShopBasic === 'function') {
|
||||
shop = await cache.getShopBasic(shopId);
|
||||
} else {
|
||||
const row = await ctx.model.Shop.findByPk(shopId, {
|
||||
attributes: [ 'id', 'principal_id', 'name', 'type', 'external_print_account_id' ],
|
||||
});
|
||||
shop = row ? row.toJSON() : null;
|
||||
}
|
||||
if (!shop) return null;
|
||||
if (principalId != null && Number(shop.principal_id) !== Number(principalId)) return null;
|
||||
return shop;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取外部打单账号及其平台配置(含 fetch_waybill_no)
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Number} accountId 外部打单账号ID
|
||||
* @param {Number} [principalId] 主体ID,传入时校验归属
|
||||
* @return {Promise<Object|null>} 账号与平台配置(plain),不存在或跨主体为 null
|
||||
*/
|
||||
async function getAccountWithPlatform(ctx, accountId, principalId) {
|
||||
if (!accountId) return null;
|
||||
|
||||
const cache = ctx.service && ctx.service.cache;
|
||||
let account = null;
|
||||
if (cache && typeof cache.getExternalPrintAccount === 'function') {
|
||||
account = await cache.getExternalPrintAccount(accountId);
|
||||
} else {
|
||||
const row = await ctx.model.ExternalPrintAccount.findByPk(accountId, {
|
||||
attributes: [ 'id', 'principal_id', 'platform_id' ],
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.ExternalPrintPlatform,
|
||||
as: 'platform',
|
||||
attributes: [ 'id', 'code', 'name', 'url', 'fetch_waybill_no' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
account = row ? row.toJSON() : null;
|
||||
}
|
||||
if (!account) return null;
|
||||
if (principalId != null && Number(account.principal_id) !== Number(principalId)) return null;
|
||||
return account;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getShopBasic,
|
||||
getAccountWithPlatform,
|
||||
};
|
||||
198
backend/app/lib/openapiIdempotency.js
Normal file
198
backend/app/lib/openapiIdempotency.js
Normal file
@ -0,0 +1,198 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
const { stableStringify } = require('./wms/sign');
|
||||
|
||||
/**
|
||||
* 对外 OpenAPI 请求幂等。
|
||||
*
|
||||
* 以 (app_key, method, request_id) 唯一:
|
||||
* - 已完成(成功/失败)→ 直接回放上次保存的完整响应;
|
||||
* - 处理中 → 返回 409,让调用方稍后重试(避免并发重复执行);
|
||||
* - 同一 request_id 但报文不同 → 返回 400;
|
||||
* - 超过 30 分钟仍处于处理中(进程异常退出等)→ 允许接管重跑。
|
||||
*
|
||||
* request_id 来源(按优先级):query.request_id / query.requestId / header X-Request-Id /
|
||||
* body.request_id / body.requestId / body.request.request_id。
|
||||
* 未传 request_id 时不启用幂等(保持原行为)。
|
||||
*/
|
||||
|
||||
/** 幂等记录状态 */
|
||||
const STATUS = {
|
||||
PROCESSING: 0,
|
||||
SUCCESS: 1,
|
||||
FAILURE: 2,
|
||||
};
|
||||
|
||||
/** 处理中的记录超过该时长视为异常中断,允许接管重跑 */
|
||||
const STALE_MS = 30 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* 从请求中取幂等请求ID
|
||||
* @param {Object} ctx egg context
|
||||
* @return {string} request_id(未传时为空串)
|
||||
*/
|
||||
function extractRequestId(ctx) {
|
||||
const query = ctx.query || {};
|
||||
const body = ctx.request.body && typeof ctx.request.body === 'object' ? ctx.request.body : {};
|
||||
const nested = body.request && typeof body.request === 'object' ? body.request : {};
|
||||
const raw = query.request_id ||
|
||||
query.requestId ||
|
||||
ctx.get('x-request-id') ||
|
||||
body.request_id ||
|
||||
body.requestId ||
|
||||
nested.request_id ||
|
||||
nested.requestId;
|
||||
return String(raw == null ? '' : raw).trim().slice(0, 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求报文摘要:app_key + method + 稳定序列化的 body
|
||||
* @param {Object} params 参数
|
||||
* @param {string} params.appKey app_key
|
||||
* @param {string} params.method 方法名
|
||||
* @param {*} params.body 请求报文
|
||||
* @return {string} md5 摘要
|
||||
*/
|
||||
function buildRequestHash({ appKey, method, body }) {
|
||||
return crypto
|
||||
.createHash('md5')
|
||||
.update(stableStringify({ app_key: appKey, method, body: body || {} }), 'utf8')
|
||||
.digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析已保存的响应报文
|
||||
* @param {string} text 响应 JSON 文本
|
||||
* @return {Object|null} 响应对象
|
||||
*/
|
||||
function parseResponse(text) {
|
||||
if (!text) return null;
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造回放结果
|
||||
* @param {Object} row 幂等记录
|
||||
* @return {{httpStatus: number, body: Object|null}} 回放响应
|
||||
*/
|
||||
function buildReplay(row) {
|
||||
return {
|
||||
httpStatus: Number(row.http_status) || 200,
|
||||
body: parseResponse(row.response_body),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理已存在的幂等记录
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} row 幂等记录
|
||||
* @param {Object} params 参数
|
||||
* @param {string} params.requestId 请求ID
|
||||
* @param {string} params.hash 报文摘要
|
||||
* @param {Object} [params.api] 接口配置
|
||||
* @param {Object} [params.warehouse] 仓库
|
||||
* @return {Promise<Object>} { requestId, entry, replay }
|
||||
*/
|
||||
async function handleExisting(ctx, row, { requestId, hash, api, warehouse }) {
|
||||
if (row.request_hash && row.request_hash !== hash) {
|
||||
return { requestId, entry: null, replay: { invalid: true }, hash };
|
||||
}
|
||||
|
||||
if (Number(row.status) === STATUS.SUCCESS || Number(row.status) === STATUS.FAILURE) {
|
||||
return { requestId, entry: row, replay: buildReplay(row), hash };
|
||||
}
|
||||
|
||||
const updatedAt = new Date(row.updated_at || row.created_at || Date.now()).getTime();
|
||||
if (Date.now() - updatedAt < STALE_MS) {
|
||||
return { requestId, entry: null, replay: { processing: true }, hash };
|
||||
}
|
||||
|
||||
// 异常中断(进程退出等):接管后重新处理
|
||||
await row.update({
|
||||
status: STATUS.PROCESSING,
|
||||
request_hash: hash,
|
||||
http_status: null,
|
||||
response_body: null,
|
||||
principal_id: api ? api.principal_id : row.principal_id,
|
||||
warehouse_id: warehouse ? warehouse.id : row.warehouse_id,
|
||||
});
|
||||
return { requestId, entry: row, replay: null, hash };
|
||||
}
|
||||
|
||||
/**
|
||||
* 开始处理:占用 request_id(或返回可回放的结果)
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} params 参数
|
||||
* @param {string} params.appKey app_key
|
||||
* @param {string} params.method 方法名
|
||||
* @param {*} params.body 请求报文
|
||||
* @param {Object} [params.api] 接口配置
|
||||
* @param {Object} [params.warehouse] 仓库
|
||||
* @return {Promise<{requestId: string, entry: Object|null, replay: Object|null, hash: string}>} 处理上下文
|
||||
*/
|
||||
async function begin(ctx, { appKey, method, body, api, warehouse }) {
|
||||
const requestId = extractRequestId(ctx);
|
||||
if (!requestId) return { requestId: '', entry: null, replay: null, hash: '' };
|
||||
|
||||
const Model = ctx.model.OpenapiRequestIdempotency;
|
||||
const hash = buildRequestHash({ appKey, method, body });
|
||||
const where = { app_key: appKey, method, request_id: requestId };
|
||||
|
||||
const existing = await Model.findOne({ where });
|
||||
if (existing) return handleExisting(ctx, existing, { requestId, hash, api, warehouse });
|
||||
|
||||
try {
|
||||
const entry = await Model.create({
|
||||
app_key: appKey,
|
||||
method,
|
||||
request_id: requestId,
|
||||
request_hash: hash,
|
||||
principal_id: api ? api.principal_id : null,
|
||||
warehouse_id: warehouse ? warehouse.id : null,
|
||||
status: STATUS.PROCESSING,
|
||||
});
|
||||
return { requestId, entry, replay: null, hash };
|
||||
} catch (err) {
|
||||
// 并发下唯一索引冲突:以先写入的为准
|
||||
const exist = await Model.findOne({ where });
|
||||
if (!exist) throw err;
|
||||
return handleExisting(ctx, exist, { requestId, hash, api, warehouse });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录处理结果(供重试回放)
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object|null} state begin 返回的上下文
|
||||
* @param {Object} result 结果
|
||||
* @param {number} result.httpStatus HTTP 状态码
|
||||
* @param {Object} result.body 完整响应报文
|
||||
* @param {boolean} result.ok 业务是否成功
|
||||
* @return {Promise<void>} 无
|
||||
*/
|
||||
async function finish(ctx, state, { httpStatus, body, ok }) {
|
||||
if (!state || !state.entry) return;
|
||||
try {
|
||||
await state.entry.update({
|
||||
status: ok ? STATUS.SUCCESS : STATUS.FAILURE,
|
||||
http_status: httpStatus,
|
||||
response_body: JSON.stringify(body),
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.logger.error('[openapi-idempotency] 写入结果失败:%s', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
begin,
|
||||
finish,
|
||||
extractRequestId,
|
||||
buildRequestHash,
|
||||
STATUS,
|
||||
STALE_MS,
|
||||
};
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
const { nowTimestamp } = require('./apiResponse');
|
||||
const orderCallback = require('./orderCallback');
|
||||
const waybillGet = require('./waybillGet');
|
||||
|
||||
/**
|
||||
* 对外通用回调接口的方法注册表。
|
||||
@ -20,6 +21,7 @@ const orderCallback = require('./orderCallback');
|
||||
* 单据处理统一走 app/lib/orderCallback.js:按 app_key 定位到的「主体 + 仓库」校验后
|
||||
* 用单据号(inbound_orders.bill_no / outbound_orders.bill_no / order_deliveries.delivery_order_code)
|
||||
* 定位 OMS 单据;新增方法时在 METHODS 中按 `模块.动作` 注册即可。
|
||||
* 取号(deliveryorder.getwaybill)走 app/lib/waybillGet.js:批量逐单返回结果,快递编码取 WMS 报文。
|
||||
*
|
||||
* ⚠️ 单号表不可混用(以 D:/wms/methods/openapi_callback.json 为准):
|
||||
* entryorder.confirm → 入库单;stockout.confirm → 出库单(CK_ 组);deliveryorder.confirm → 发货单(FH_ 组)
|
||||
@ -117,6 +119,29 @@ const METHODS = {
|
||||
data: body,
|
||||
}),
|
||||
|
||||
/**
|
||||
* 批量取号(method = deliveryorder.getwaybill)
|
||||
*
|
||||
* WMS 发起取号,报文携带快递编码(不读取订单上的 logistics_code),OMS 回读订单信息:
|
||||
* 订单平台(source_platform_code)→ 店铺 → 外部打单账号 → 按「账号 + 平台 + 编码」定位快递接口。
|
||||
* 逐单返回成功/失败,互不影响;订单已取消 / 已作废 / 已归档时该单返回取号失败。
|
||||
*
|
||||
* 报文示例:
|
||||
* { "orders": [ { "deliveryOrderCode": "FH_xxx", "expressCode": "ZTO" } ] }
|
||||
* 返回 data:{ total, success, failed, results: [ { delivery_order_code, success, message, waybill_code, ... } ] }
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} payload 调用上下文
|
||||
* @param {Object} payload.api 按 app_key 定位到的接口配置
|
||||
* @param {Object} payload.warehouse 接口配置关联的仓库
|
||||
* @param {Object} payload.body 批量取号报文
|
||||
* @return {Promise<Object>} { ok, message, data }
|
||||
*/
|
||||
'deliveryorder.getwaybill': (ctx, { api, warehouse, body }) => waybillGet.getWaybills(ctx, {
|
||||
principalId: api.principal_id,
|
||||
warehouseId: warehouse.id,
|
||||
data: body,
|
||||
}),
|
||||
|
||||
/**
|
||||
* 出库单确认(method = stockout.confirm):WMS 出库完成(非订单出库单,CK 组 / wms_order_stockout)
|
||||
* 写回明细「已出数量」,扣减系统库存并置「已完成(4)」(幂等,明细以仓库侧为准)
|
||||
|
||||
@ -219,10 +219,17 @@ class PrintPlatformService {
|
||||
|
||||
/**
|
||||
* 回打单平台取运单号(fetch_waybill_no=1 的平台必须实现),由各平台实现
|
||||
*
|
||||
* 调用方为 WMS 取号回调(deliveryorder.getwaybill):订单信息由 OMS 回读,
|
||||
* 快递编码来自 WMS 报文,所选快递接口按「账号 + 平台 + 编码」匹配后传入。
|
||||
* @param {Object} order 订单数据(字段口径由平台协议决定)
|
||||
* @return {Promise<string[]>} 运单号列表
|
||||
* @param {Object} [options] 取号上下文
|
||||
* @param {Object} [options.template] 命中的快递接口(external_print_express_interfaces 记录)
|
||||
* @param {string} [options.expressCode] WMS 传入的快递编码
|
||||
* @param {string} [options.platformCode] 订单平台编码(如 TB)
|
||||
* @return {Promise<string|string[]|Object>} 运单号(字符串 / 数组 / 平台原始结果,由上层归一化)
|
||||
*/
|
||||
async fetchWaybillNo(order) { // eslint-disable-line no-unused-vars
|
||||
async fetchWaybillNo(order, options = {}) { // eslint-disable-line no-unused-vars
|
||||
throw new Error(`外部打单平台 ${this.platformName} 未实现 fetchWaybillNo()`);
|
||||
}
|
||||
}
|
||||
|
||||
@ -29,6 +29,12 @@ const PRODUCT_LIST_PATH = '/Product/LoadList';
|
||||
/** 订单列表接口(按分区域名请求,路径固定) */
|
||||
const ORDER_LIST_PATH = '/NewOrder/List';
|
||||
|
||||
/** 面单模板(快递接口)列表接口:按平台域名请求,返回当前分区下可用的快递面单模板 */
|
||||
const TEMPLATE_LIST_PATH = '/TemplateSet/LoadTemplateListInOrderList';
|
||||
|
||||
/** 面单账号明细接口:查看单个模板对应的电子面单账号 / 网点明细 */
|
||||
const TEMPLATE_DETAIL_PATH = '/TemplateSet/LoadWaybillAccountDetailInfo';
|
||||
|
||||
/** 订单列表单页条数(平台允许 500) */
|
||||
const ORDER_PAGE_SIZE = 500;
|
||||
|
||||
@ -54,6 +60,32 @@ const FALLBACK_PRODUCT_HOSTS = [
|
||||
'fxtk.dgjapp.com',
|
||||
];
|
||||
|
||||
/**
|
||||
* 面单模板(快递接口)接口按平台域名部署:分区 DbName → 模板接口域名 + PlatformType 写法。
|
||||
* 平台新增分区时在此补充;未收录的分区按商品域名的同类映射兜底。
|
||||
*/
|
||||
const TEMPLATE_PLATFORMS = {
|
||||
pinduoduo: { host: 'fxpdd.dgjapp.com', type: 'Pinduoduo' },
|
||||
toutiao: { host: 'fxdd.dgjapp.com', type: 'TouTiao' },
|
||||
douyin: { host: 'fxdd.dgjapp.com', type: 'TouTiao' },
|
||||
doudian: { host: 'fxdd.dgjapp.com', type: 'TouTiao' },
|
||||
wxvideo: { host: 'fxdd.dgjapp.com', type: 'WxVideo' },
|
||||
alibaba: { host: 'fxali.dgjapp.com', type: 'Alibaba' },
|
||||
taobao: { host: 'fxali.dgjapp.com', type: 'Taobao' },
|
||||
tmall: { host: 'fxali.dgjapp.com', type: 'Tmall' },
|
||||
jingdong: { host: 'fxjd.dgjapp.com', type: 'JingDong' },
|
||||
kuaishou: { host: 'fxtk.dgjapp.com', type: 'KuaiShou' },
|
||||
};
|
||||
|
||||
/** 只能识别出域名时的兜底 PlatformType(每个域名取一个代表平台) */
|
||||
const TEMPLATE_HOST_TYPES = {
|
||||
'fxpdd.dgjapp.com': [ 'Pinduoduo' ],
|
||||
'fxdd.dgjapp.com': [ 'TouTiao' ],
|
||||
'fxali.dgjapp.com': [ 'Alibaba' ],
|
||||
'fxjd.dgjapp.com': [ 'JingDong' ],
|
||||
'fxtk.dgjapp.com': [ 'KuaiShou' ],
|
||||
};
|
||||
|
||||
/** 商品列表单页条数(平台允许 200) */
|
||||
const PRODUCT_PAGE_SIZE = 200;
|
||||
|
||||
@ -91,6 +123,19 @@ function resolveOrderPlatform(platformType) {
|
||||
return resolvePlatform(presetCode || platformType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 PlatformType 反查面单模板接口域名(未收录时返回空字符串)
|
||||
* @param {*} platformType 店管家 PlatformType(如 Pinduoduo)
|
||||
* @return {string} 模板接口域名
|
||||
*/
|
||||
function resolveTemplateHost(platformType) {
|
||||
const key = String(platformType == null ? '' : platformType).trim().toLowerCase();
|
||||
for (const preset of Object.values(TEMPLATE_PLATFORMS)) {
|
||||
if (preset.type.toLowerCase() === key) return preset.host;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 平台侧「已发货 / 已终结」的订单状态(ErpState):
|
||||
* sended=已发货、success=交易成功、close=交易关闭,其余为各平台交易状态的等价写法。
|
||||
@ -531,6 +576,232 @@ class DgjService extends PrintPlatformService {
|
||||
return hosts.length ? hosts : FALLBACK_PRODUCT_HOSTS.slice();
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析店铺需要拉取面单模板的目标(模板接口域名 + PlatformType + 分区库名)。
|
||||
* 优先级:商家分区 DbAreas/DbArea 里的 DbName(如 pinduoduo)→ 展开该分区的全部库;
|
||||
* 识别不出分区时按商品域名兜底,每个域名取一个代表 PlatformType。
|
||||
* @param {Object} shop OMS 店铺记录(type=2,external_data 为商家原始结构)
|
||||
* @return {Promise<Array<{host: string, platformType: string, dbname: string, areaName: string}>>} 目标列表
|
||||
*/
|
||||
async resolveTemplateTargets(shop) {
|
||||
const data = (shop && shop.external_data) || {};
|
||||
const areaRows = [
|
||||
...(Array.isArray(data.DbAreas) ? data.DbAreas : []),
|
||||
...(Array.isArray(data.DbArea) ? data.DbArea : []),
|
||||
];
|
||||
const presets = [];
|
||||
for (const row of areaRows) {
|
||||
const key = String((row && (row.DbName || row.Name)) || '').toLowerCase();
|
||||
const preset = TEMPLATE_PLATFORMS[key];
|
||||
if (!preset) continue;
|
||||
if (!presets.some(item => item.host === preset.host && item.type === preset.type)) presets.push(preset);
|
||||
}
|
||||
if (!presets.length) {
|
||||
for (const host of this.resolveProductHosts(data)) {
|
||||
for (const type of TEMPLATE_HOST_TYPES[host] || []) {
|
||||
if (!presets.some(item => item.host === host && item.type === type)) presets.push({ host, type });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const targets = [];
|
||||
for (const preset of presets) {
|
||||
const areas = await this.listProductAreas(preset.host);
|
||||
for (const area of areas) {
|
||||
targets.push({ host: preset.host, platformType: preset.type, dbname: area.dbname, areaName: area.name });
|
||||
}
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取一个平台域名 / 分区下的面单模板(快递接口)列表
|
||||
* @param {string} host 模板接口域名
|
||||
* @param {Object} options 查询参数
|
||||
* @param {string} options.traceId 登录上下文 traceId
|
||||
* @param {string} options.dbname 分区库名
|
||||
* @param {string} options.platformType 店管家 PlatformType(如 Pinduoduo)
|
||||
* @return {Promise<Array>} 平台原始模板列表
|
||||
*/
|
||||
async fetchTemplateList(host, { traceId, dbname, platformType }) {
|
||||
const query = new URLSearchParams({
|
||||
token: this.token,
|
||||
traceId: traceId || '',
|
||||
dbname: dbname || '',
|
||||
dataFlag: '',
|
||||
});
|
||||
const form = new URLSearchParams({
|
||||
platformType: platformType || '',
|
||||
isDefault: 'false',
|
||||
IsCustomerOrder: 'false',
|
||||
FxPageType: '2',
|
||||
});
|
||||
const headers = {
|
||||
accept: 'application/json, text/javascript, */*; q=0.01',
|
||||
'accept-language': 'zh-CN,zh;q=0.9',
|
||||
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
||||
referer: `https://${host}/NewOrder/WaitOrder`,
|
||||
'user-agent': BROWSER_HEADERS['user-agent'],
|
||||
'x-requested-with': 'XMLHttpRequest',
|
||||
};
|
||||
if (this.cookie) headers.cookie = this.cookie;
|
||||
|
||||
const res = await this.request(`https://${host}${TEMPLATE_LIST_PATH}?${query.toString()}`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: form.toString(),
|
||||
});
|
||||
if (res.status === 401) {
|
||||
throw new Error(`店管家登录已失效:${(res.json && res.json.Message) || 'token is invalid'}`);
|
||||
}
|
||||
if (!res.json || res.json.Success !== true) {
|
||||
const reason = (res.json && (res.json.Message || res.json.ErrorCode)) || `HTTP ${res.status}`;
|
||||
throw new Error(reason);
|
||||
}
|
||||
if (Array.isArray(res.json.Data)) return res.json.Data;
|
||||
return Array.isArray(res.json.Data && res.json.Data.List) ? res.json.Data.List : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 把平台模板结构转换为统一结构(上层不直接依赖店管家字段)
|
||||
* @param {Object} item 平台模板原始结构
|
||||
* @param {Object} target 拉取目标(host / platformType / dbname)
|
||||
* @return {Object} 统一模板结构
|
||||
*/
|
||||
normalizeExpressTemplate(item, target) {
|
||||
const data = item || {};
|
||||
// 平台归属优先取模板自身的 TemplateTypeShort(如小红书模板挂在抖店分区下,
|
||||
// CloudPlatform / 分区 PlatformType 仍是 TouTiao),其次才用云端平台与分区类型兜底
|
||||
const platformType = String(
|
||||
data.TemplateTypeShort || data.CloudPlatform || data.PlatformType || target.platformType || ''
|
||||
).trim();
|
||||
const platform = resolveOrderPlatform(platformType);
|
||||
return {
|
||||
template_id: String(data.Id == null ? '' : data.Id),
|
||||
template_name: truncate(data.TemplateName, 128),
|
||||
platform_type: truncate(platformType, 32),
|
||||
platform_code: platform.code,
|
||||
platform_name: platform.name,
|
||||
express_company_id: toNumber(data.ExpressCompanyId),
|
||||
express_company_code: truncate(data.ExpressCompanyCode, 50),
|
||||
express_company_name: truncate(data.ExpressCompanyName, 100),
|
||||
shop_id: toNumber(data.ShopId),
|
||||
shop_name: truncate(data.ShopName, 128),
|
||||
dbname: truncate(target.dbname, 128),
|
||||
platform_updated_at: parseOrderTime(data.UpdateDate),
|
||||
raw: data,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取店铺关联的全部面单模板(快递接口):逐平台域名 / 分区查询后按模板ID去重。
|
||||
* 单个分区失败不影响其它分区,错误随结果返回,供上层提示。
|
||||
* @param {Object} shop OMS 店铺记录(type=2)
|
||||
* @return {Promise<{list: Array, errors: Array<string>, targets: Array<string>}>} 模板列表与逐项错误
|
||||
*/
|
||||
async listExpressTemplates(shop) {
|
||||
if (!this.token || !this.cookie) {
|
||||
throw new Error('账号未登录:缺少 token 或 cookie,请先登录');
|
||||
}
|
||||
|
||||
let traceId = '';
|
||||
try {
|
||||
const info = await this.getUserInfo();
|
||||
traceId = (info.data && info.data.TraceId) || '';
|
||||
} catch {
|
||||
// 忽略:traceId 缺失不阻断模板查询
|
||||
}
|
||||
|
||||
const targets = await this.resolveTemplateTargets(shop);
|
||||
if (!targets.length) {
|
||||
throw new Error('店铺缺少可识别的平台分区(DbAreas),无法确定快递接口所属平台');
|
||||
}
|
||||
|
||||
const rows = new Map();
|
||||
const errors = [];
|
||||
const hitTargets = [];
|
||||
for (const target of targets) {
|
||||
const label = `${target.host} / ${target.platformType}${target.areaName ? `(${target.areaName})` : ''}`;
|
||||
try {
|
||||
const list = await this.fetchTemplateList(target.host, {
|
||||
traceId,
|
||||
dbname: target.dbname,
|
||||
platformType: target.platformType,
|
||||
});
|
||||
for (const item of list) {
|
||||
if (!item || !item.Id) continue;
|
||||
// 平台标记为已删除的模板不落库:历史记录会在全量扫描后被标记失效
|
||||
if (item.IsDeleted === true) continue;
|
||||
rows.set(String(item.Id), this.normalizeExpressTemplate(item, target));
|
||||
}
|
||||
hitTargets.push(label);
|
||||
} catch (err) {
|
||||
errors.push(`${label}:${err.message}`);
|
||||
}
|
||||
}
|
||||
return { list: [ ...rows.values() ], errors, targets: hitTargets };
|
||||
}
|
||||
|
||||
/**
|
||||
* 查看单个模板的电子面单账号 / 网点明细(平台单独接口)
|
||||
* @param {Object} template 已落库的模板(template_id / platform_type / shop_id / dbname 等)
|
||||
* @return {Promise<Object|null>} 平台返回的明细数据
|
||||
*/
|
||||
async fetchWaybillAccountDetail(template) {
|
||||
const item = template || {};
|
||||
const platformType = String(item.platform_type || '').trim();
|
||||
const host = resolveTemplateHost(platformType);
|
||||
if (!host) throw new Error(`暂不支持该平台类型的快递接口明细:${platformType || '-'}`);
|
||||
|
||||
let traceId = '';
|
||||
try {
|
||||
const info = await this.getUserInfo();
|
||||
traceId = (info.data && info.data.TraceId) || '';
|
||||
} catch {
|
||||
// 忽略:traceId 缺失不阻断明细查询
|
||||
}
|
||||
|
||||
const raw = item.raw && typeof item.raw === 'object' ? item.raw : {};
|
||||
const query = new URLSearchParams({
|
||||
token: this.token,
|
||||
traceId,
|
||||
dbname: item.dbname || '',
|
||||
dataFlag: '',
|
||||
});
|
||||
const form = new URLSearchParams({
|
||||
Id: String(item.template_id || ''),
|
||||
TemplateId: String(item.template_id || ''),
|
||||
ShopId: String(item.shop_id == null ? '' : item.shop_id),
|
||||
ExpressCompanyId: String(item.express_company_id == null ? '' : item.express_company_id),
|
||||
CaiNiaoAuthInfoId: String(raw.CaiNiaoAuthInfoId || ''),
|
||||
platformType,
|
||||
FxPageType: '2',
|
||||
});
|
||||
const headers = {
|
||||
accept: 'application/json, text/javascript, */*; q=0.01',
|
||||
'accept-language': 'zh-CN,zh;q=0.9',
|
||||
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
||||
referer: `https://${host}/NewOrder/WaitOrder`,
|
||||
'user-agent': BROWSER_HEADERS['user-agent'],
|
||||
'x-requested-with': 'XMLHttpRequest',
|
||||
};
|
||||
if (this.cookie) headers.cookie = this.cookie;
|
||||
|
||||
const res = await this.request(`https://${host}${TEMPLATE_DETAIL_PATH}?${query.toString()}`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: form.toString(),
|
||||
});
|
||||
if (res.status === 401) {
|
||||
throw new Error(`店管家登录已失效:${(res.json && res.json.Message) || 'token is invalid'}`);
|
||||
}
|
||||
if (!res.json || res.json.Success !== true) {
|
||||
const reason = (res.json && (res.json.Message || res.json.ErrorCode)) || `HTTP ${res.status}`;
|
||||
throw new Error(reason);
|
||||
}
|
||||
return res.json.Data || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装商品列表查询表单(字段口径与店管家工作台一致)
|
||||
* @param {string} agentId 商家 FxUserId(注意不是商家 Id);为空表示不限商家
|
||||
@ -1347,11 +1618,13 @@ class DgjService extends PrintPlatformService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 店管家不回平台取号(平台配置 fetch_waybill_no = 0),调用即视为错误
|
||||
* 店管家取号尚未接入:平台配置 fetch_waybill_no = 0,等待平台取号接口确认后实现
|
||||
* @param {Object} order 订单数据
|
||||
* @param {Object} [options] 取号上下文(template / expressCode / platformCode)
|
||||
* @return {Promise<never>} 固定抛错
|
||||
*/
|
||||
async fetchWaybillNo() {
|
||||
throw new Error('店管家不回平台取号(fetch_waybill_no=0),不应调用 fetchWaybillNo()');
|
||||
async fetchWaybillNo(order, options = {}) { // eslint-disable-line no-unused-vars
|
||||
throw new Error('店管家取号未接入(fetch_waybill_no=0),请先确认平台取号接口');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
371
backend/app/lib/waybillGet.js
Normal file
371
backend/app/lib/waybillGet.js
Normal file
@ -0,0 +1,371 @@
|
||||
'use strict';
|
||||
|
||||
const orderCallback = require('./orderCallback');
|
||||
const { ORDER_STATUS } = require('./orderStatus');
|
||||
const { getShopBasic } = require('./externalPrintConfig');
|
||||
|
||||
/** 单号候选字段(与 deliveryorder.confirm 同口径,支持嵌套) */
|
||||
const CODE_PATHS = [
|
||||
'deliveryOrderCode',
|
||||
'deliveryOrder.deliveryOrderCode',
|
||||
'outBizCode',
|
||||
'deliveryOrder.outBizCode',
|
||||
'orderCode',
|
||||
'order.orderCode',
|
||||
];
|
||||
|
||||
/** WMS 传入的快递编码候选字段(不回读订单上的 logistics_code) */
|
||||
const EXPRESS_CODE_PATHS = [
|
||||
'expressCode',
|
||||
'express_code',
|
||||
'logisticsCode',
|
||||
'logistics_code',
|
||||
'express.code',
|
||||
];
|
||||
|
||||
/** 平台返回的运单号候选字段 */
|
||||
const WAYBILL_KEYS = [
|
||||
'waybillCode',
|
||||
'waybill_code',
|
||||
'mailNo',
|
||||
'mail_no',
|
||||
'logisticCode',
|
||||
'logistic_code',
|
||||
'LogisticCode',
|
||||
'WaybillCode',
|
||||
'expressCode',
|
||||
'express_code',
|
||||
];
|
||||
|
||||
/** 单次批量上限(避免一次回调过大、平台侧限流) */
|
||||
const MAX_BATCH = 100;
|
||||
|
||||
/** 并发处理数(平台取号是网络请求,适度并发缩短总耗时) */
|
||||
const CONCURRENCY = 4;
|
||||
|
||||
/** 取消 / 作废 / 归档等不可取号的状态 */
|
||||
const BLOCKED_STATUS_LABELS = {
|
||||
[ORDER_STATUS.CANCELED]: '订单已取消,取号失败',
|
||||
[ORDER_STATUS.VOID]: '订单已作废,取号失败',
|
||||
[ORDER_STATUS.HISTORY]: '订单已归档,取号失败',
|
||||
};
|
||||
|
||||
/**
|
||||
* 兼容 `{ request: {...} }` / `{ data: {...} }` 包装(与 orderCallback.unwrapPayload 同口径)
|
||||
* @param {Object} body 原始报文
|
||||
* @return {Object} 归一化报文
|
||||
*/
|
||||
function unwrapBody(body) {
|
||||
const source = body && typeof body === 'object' && !Array.isArray(body) ? body : {};
|
||||
const inner = [ source.request, source.data ].find(v => v && typeof v === 'object' && !Array.isArray(v));
|
||||
return inner ? { ...source, ...inner } : source;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从报文中提取批量订单项
|
||||
*
|
||||
* 兼容:`orders: []`、`deliveryOrders: []`、`deliveryOrders.deliveryOrder: []`、
|
||||
* `list: []`,以及只传单个对象的场景。
|
||||
* @param {Object} body 归一化后的报文
|
||||
* @return {Array} 订单项数组
|
||||
*/
|
||||
function extractItems(body) {
|
||||
const source = body || {};
|
||||
const candidates = [ source.orders, source.deliveryOrders, source.list, source.items ];
|
||||
for (const candidate of candidates) {
|
||||
if (Array.isArray(candidate)) return candidate;
|
||||
if (candidate && typeof candidate === 'object') {
|
||||
for (const key of [ 'orders', 'deliveryOrder', 'list', 'items' ]) {
|
||||
if (Array.isArray(candidate[key])) return candidate[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 单对象写法:本身就是一个订单项
|
||||
if (source.deliveryOrderCode || source.outBizCode || source.orderCode) return [ source ];
|
||||
if (source.deliveryOrder && typeof source.deliveryOrder === 'object' && !Array.isArray(source.deliveryOrder)) {
|
||||
return [ source ];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 取 WMS 传入的快递编码(只从报文取,不读订单)
|
||||
* @param {Object} item 订单项
|
||||
* @return {string} 快递编码
|
||||
*/
|
||||
function pickExpressCode(item) {
|
||||
return orderCallback.pickFirst(item || {}, EXPRESS_CODE_PATHS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归提取平台返回的运单号(兼容字符串 / 数组 / 常见字段名)
|
||||
* @param {*} value 平台返回值
|
||||
* @param {Array<string>} out 收集结果
|
||||
* @return {void}
|
||||
*/
|
||||
function collectWaybills(value, out) {
|
||||
if (value === undefined || value === null) return;
|
||||
if (typeof value === 'string') {
|
||||
const text = value.trim();
|
||||
if (text) out.push(text);
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) collectWaybills(item, out);
|
||||
return;
|
||||
}
|
||||
if (typeof value !== 'object') return;
|
||||
|
||||
for (const key of WAYBILL_KEYS) {
|
||||
const hit = value[key];
|
||||
if (typeof hit === 'string' && hit.trim()) {
|
||||
out.push(hit.trim());
|
||||
return;
|
||||
}
|
||||
}
|
||||
for (const key of [ 'waybills', 'waybillCodes', 'expressCodes', 'packages', 'data' ]) {
|
||||
if (value[key] !== undefined) collectWaybills(value[key], out);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化平台取号结果
|
||||
* @param {*} result 平台返回
|
||||
* @return {{waybill_code: string, waybill_codes: Array<string>}} 运单号
|
||||
*/
|
||||
function normalizeWaybill(result) {
|
||||
const list = [];
|
||||
collectWaybills(result, list);
|
||||
const unique = [ ...new Set(list) ];
|
||||
return { waybill_code: unique[0] || '', waybill_codes: unique };
|
||||
}
|
||||
|
||||
/**
|
||||
* 有限并发执行,保持结果顺序
|
||||
* @param {Array} items 待处理项
|
||||
* @param {number} limit 并发数
|
||||
* @param {Function} worker 处理函数
|
||||
* @return {Promise<Array>} 结果数组
|
||||
*/
|
||||
async function mapLimit(items, limit, worker) {
|
||||
const results = new Array(items.length);
|
||||
let cursor = 0;
|
||||
const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
||||
while (cursor < items.length) {
|
||||
const index = cursor;
|
||||
cursor += 1;
|
||||
results[index] = await worker(items[index], index);
|
||||
}
|
||||
});
|
||||
await Promise.all(runners);
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* 失败结果
|
||||
* @param {string} code 单号
|
||||
* @param {string} message 失败原因
|
||||
* @return {Object} 结果项
|
||||
*/
|
||||
function fail(code, message) {
|
||||
return { delivery_order_code: code || '', success: false, message };
|
||||
}
|
||||
|
||||
/**
|
||||
* 订单已有运单号时的结果(重试 / 不同 request_id 重复取号都直接复用,避免重复请求平台)
|
||||
* @param {string} code 单号
|
||||
* @param {string} expressCode WMS 传入的快递编码
|
||||
* @param {Object} order 订单
|
||||
* @return {Object} 成功结果
|
||||
*/
|
||||
function existingWaybillResult(code, expressCode, order) {
|
||||
return {
|
||||
delivery_order_code: code,
|
||||
success: true,
|
||||
message: '已取号,返回已有运单号',
|
||||
express_code: expressCode,
|
||||
waybill_code: order.express_code,
|
||||
waybill_codes: Array.isArray(order.express_codes) ? order.express_codes : [ order.express_code ],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取完整打单账号实例(含 cookie/token,平台客户端直接使用)
|
||||
* 同一批内按账号去重,避免逐单查库;缓存 promise 以合并并发请求
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} memo 批内缓存
|
||||
* @param {Number} accountId 外部打单账号ID
|
||||
* @param {Number} principalId 主体ID
|
||||
* @return {Promise<Object|null>} 账号实例,不存在或跨主体为 null
|
||||
*/
|
||||
async function loadAccountModel(ctx, memo, accountId, principalId) {
|
||||
const key = `account:${principalId}:${accountId}`;
|
||||
if (memo.has(key)) return await memo.get(key);
|
||||
|
||||
const promise = ctx.model.ExternalPrintAccount.findOne({
|
||||
where: { id: accountId, principal_id: principalId },
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.ExternalPrintPlatform,
|
||||
as: 'platform',
|
||||
attributes: [ 'id', 'code', 'name', 'url', 'fetch_waybill_no' ],
|
||||
},
|
||||
],
|
||||
}).catch(err => {
|
||||
memo.delete(key);
|
||||
throw err;
|
||||
});
|
||||
memo.set(key, promise);
|
||||
return await promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理单个订单取号
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} params 参数
|
||||
* @param {number} params.principalId 主体ID
|
||||
* @param {number} params.warehouseId app_key 定位到的仓库ID
|
||||
* @param {Object} params.item 订单项(含单号与快递编码)
|
||||
* @param {Map} params.memo 批内缓存(账号实例等)
|
||||
* @return {Promise<Object>} 结果项
|
||||
*/
|
||||
async function processItem(ctx, { principalId, warehouseId, item, memo }) {
|
||||
const code = orderCallback.pickFirst(item || {}, CODE_PATHS);
|
||||
if (!code) return fail('', '缺少发货单号(deliveryOrderCode / outBizCode)');
|
||||
|
||||
// 快递编码必须由 WMS 传入;订单上的 logistics_code 不参与取号
|
||||
const expressCode = pickExpressCode(item);
|
||||
if (!expressCode) return fail(code, '缺少快递编码(expressCode)');
|
||||
|
||||
try {
|
||||
const resolved = await orderCallback.resolveDeliveryBill(ctx, { code, principalId });
|
||||
const order = resolved.order;
|
||||
if (!order) return fail(code, `未找到发货单:${code}`);
|
||||
|
||||
// 仓库隔离:历史单据可能没有 warehouse_id,仅在双方都有值时校验
|
||||
if (order.warehouse_id && warehouseId && Number(order.warehouse_id) !== Number(warehouseId)) {
|
||||
return fail(code, `单据 ${code} 不属于当前 app_key 对应的仓库`);
|
||||
}
|
||||
|
||||
if (resolved.isNewModel) {
|
||||
const status = resolved.index.current_status;
|
||||
if (BLOCKED_STATUS_LABELS[status]) return fail(code, BLOCKED_STATUS_LABELS[status]);
|
||||
// 已有运单号:直接复用(幂等),不再请求平台
|
||||
if (order.express_code) return existingWaybillResult(code, expressCode, order);
|
||||
if (status === ORDER_STATUS.DELIVERY) return fail(code, '订单已配送但没有运单号');
|
||||
} else {
|
||||
const status = Number(order.status);
|
||||
if (status === 9) return fail(code, BLOCKED_STATUS_LABELS[ORDER_STATUS.CANCELED]);
|
||||
if (status === 5) return fail(code, BLOCKED_STATUS_LABELS[ORDER_STATUS.VOID]);
|
||||
if (order.express_code) return existingWaybillResult(code, expressCode, order);
|
||||
if (status === 4) return fail(code, '订单已完成但没有运单号');
|
||||
}
|
||||
|
||||
// 平台信息必须回读订单(订单来自哪个平台)
|
||||
const platformCode = String(order.source_platform_code || '').trim();
|
||||
if (!platformCode) return fail(code, '订单缺少来源平台,无法匹配快递接口');
|
||||
|
||||
// 打单账号:订单店铺 → 外部打单账号(跨打单平台无法取号)
|
||||
// 店铺与账号平台配置走缓存,避免一批 100 单反复查同一份配置
|
||||
if (!order.shop_id) return fail(code, '订单未关联店铺,无法确定打单账号');
|
||||
const shop = await getShopBasic(ctx, order.shop_id, principalId);
|
||||
if (!shop || Number(shop.type) !== 2 || !shop.external_print_account_id) {
|
||||
return fail(code, '订单未关联外部打单账号,无法取号');
|
||||
}
|
||||
|
||||
const account = await loadAccountModel(ctx, memo, shop.external_print_account_id, principalId);
|
||||
if (!account || !account.platform) return fail(code, '外部打单账号或平台配置不存在');
|
||||
|
||||
// 按「账号 + 订单平台 + WMS 传入的快递编码」定位唯一模板
|
||||
const template = await ctx.service.externalPrintExpressInterface.resolveByCode(
|
||||
account.id,
|
||||
{ platformCode, expressCode },
|
||||
principalId
|
||||
);
|
||||
if (!template) {
|
||||
return fail(code, `未找到匹配的快递接口(平台 ${platformCode},编码 ${expressCode})`);
|
||||
}
|
||||
|
||||
const platformService = ctx.service.externalPrintOrder.createPlatformService(account);
|
||||
if (!platformService.needFetchWaybillNo) {
|
||||
return fail(code, `打单平台「${account.platform.name}」未开启取号`);
|
||||
}
|
||||
|
||||
const orderPlain = order.get ? order.get({ plain: true }) : { ...order };
|
||||
const fetched = await platformService.fetchWaybillNo(orderPlain, {
|
||||
template: template.get ? template.get({ plain: true }) : template,
|
||||
expressCode,
|
||||
platformCode,
|
||||
});
|
||||
const waybill = normalizeWaybill(fetched);
|
||||
if (!waybill.waybill_code) return fail(code, '平台未返回运单号');
|
||||
|
||||
// 回写运单号(不覆盖订单上的物流编码/名称)
|
||||
await order.update({
|
||||
express_code: waybill.waybill_code,
|
||||
express_codes: waybill.waybill_codes,
|
||||
});
|
||||
|
||||
ctx.logger.info('[waybill.get] 取号成功', { code, expressCode, platformCode, waybillCode: waybill.waybill_code });
|
||||
return {
|
||||
delivery_order_code: code,
|
||||
success: true,
|
||||
message: 'ok',
|
||||
express_code: expressCode,
|
||||
platform_code: platformCode,
|
||||
waybill_code: waybill.waybill_code,
|
||||
waybill_codes: waybill.waybill_codes,
|
||||
};
|
||||
} catch (err) {
|
||||
ctx.logger.warn('[waybill.get] 取号失败 %s:%s', code, err.message);
|
||||
return fail(code, err.message || '取号失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量取号(method = deliveryorder.getwaybill)
|
||||
*
|
||||
* WMS 发起取号时携带快递编码,OMS 回读订单信息(平台 / 店铺 / 打单账号)后按
|
||||
* 「账号 + 平台 + 编码」定位快递接口并调用平台取号;逐单返回成功/失败,不影响其它订单。
|
||||
* 订单已取消 / 已作废 / 已归档时返回该单取号失败。
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} payload 调用上下文
|
||||
* @param {number} payload.principalId 主体ID
|
||||
* @param {number} payload.warehouseId app_key 定位到的仓库ID
|
||||
* @param {Object} payload.data 回调报文
|
||||
* @return {Promise<{ok: boolean, message: string, data?: Object}>} 批量结果
|
||||
*/
|
||||
async function getWaybills(ctx, { principalId, warehouseId, data }) {
|
||||
const body = unwrapBody(data);
|
||||
const items = extractItems(body);
|
||||
if (!items.length) {
|
||||
return { ok: false, message: '缺少待取号订单(orders / deliveryOrders)' };
|
||||
}
|
||||
if (items.length > MAX_BATCH) {
|
||||
return { ok: false, message: `单次最多取号 ${MAX_BATCH} 单` };
|
||||
}
|
||||
|
||||
// 同一批内按账号缓存完整账号实例(含 cookie/token,供平台客户端直接使用),
|
||||
// 一次批量回调通常只涉及 1 个打单账号,避免逐单重复查库
|
||||
const memo = new Map();
|
||||
const results = await mapLimit(items, CONCURRENCY, item => processItem(ctx, { principalId, warehouseId, item, memo }));
|
||||
const success = results.filter(row => row.success).length;
|
||||
return {
|
||||
ok: true,
|
||||
message: 'ok',
|
||||
data: {
|
||||
total: results.length,
|
||||
success,
|
||||
failed: results.length - success,
|
||||
results,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getWaybills,
|
||||
extractItems,
|
||||
pickExpressCode,
|
||||
normalizeWaybill,
|
||||
};
|
||||
@ -543,7 +543,8 @@ class QimenWmsClient {
|
||||
* 字段口径来源:D:/wms/methods/openapi.json `deliveryorder.create`
|
||||
* - 必填:deliveryOrder.deliveryOrderCode、orderLines.orderLine(非空,每行 planQty > 0)
|
||||
* - 收件人:receiverInfo.name/mobile/province/city/area/detailAddress 必填(OMS 侧已按同名口径校验)
|
||||
* - need_oms_waybill 在请求根节点(不在 deliveryOrder 内):手工单恒为 0,即「不用 OMS 取号」
|
||||
* - need_oms_waybill 在请求根节点(不在 deliveryOrder 内):外部打单平台订单按平台配置
|
||||
* fetch_waybill_no 决定(1=回 OMS 取号),手工单恒为 0
|
||||
* - 明细:itemId 与 itemCode 二选一,优先传 itemId(warehouse_products.wms_item_id 回写值),缺失时用 itemCode
|
||||
* @param {Object} order OMS 发货单(model 实例或 plain,已 include warehouse)
|
||||
* @param {Array} items 发货单明细(order_delivery_items,已 include product 时优先取商品快照)
|
||||
@ -661,7 +662,7 @@ class QimenWmsClient {
|
||||
return {
|
||||
deliveryOrder,
|
||||
orderLines: { orderLine: orderLineList },
|
||||
// 手工创建的发货单恒为 0(不用 OMS 取号);该参数在请求根节点
|
||||
// 外部打单平台订单按平台配置回 OMS 取号,手工单默认 0;该参数在请求根节点
|
||||
need_oms_waybill: o.need_oms_waybill == null ? 0 : Number(o.need_oms_waybill),
|
||||
};
|
||||
}
|
||||
|
||||
39
backend/app/model/customExpressCode.js
Normal file
39
backend/app/model/customExpressCode.js
Normal file
@ -0,0 +1,39 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 自定义快递编码模型,对应 custom_express_codes 表。
|
||||
*
|
||||
* 全局字典(不区分主体):code/name 为下发给订单与奇门的自定义值,
|
||||
* express_code 为对应的系统快递编码(express_companies.code),用于展示与映射参考。
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} customExpressCode model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, INTEGER, DATE } = app.Sequelize;
|
||||
|
||||
const CustomExpressCode = app.model.define('custom_express_code', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
code: { type: STRING(50), allowNull: false, comment: '自定义快递编码(订单 logistics_code)' },
|
||||
name: { type: STRING(100), allowNull: false, comment: '自定义快递名称(订单 logistics_name)' },
|
||||
express_code: { type: STRING(50), allowNull: false, comment: '对应的系统快递编码' },
|
||||
sort: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '排序,越小越靠前' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' },
|
||||
remark: { type: STRING(255), comment: '备注' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
}, {
|
||||
tableName: 'custom_express_codes',
|
||||
comment: '自定义快递编码字典',
|
||||
});
|
||||
|
||||
CustomExpressCode.associate = () => {
|
||||
// 对应的系统快递编码 → 快递公司字典(code 全局唯一),用于展示系统快递名称
|
||||
app.model.CustomExpressCode.belongsTo(app.model.ExpressCompany, {
|
||||
foreignKey: 'express_code',
|
||||
targetKey: 'code',
|
||||
as: 'expressCompany',
|
||||
});
|
||||
};
|
||||
|
||||
return CustomExpressCode;
|
||||
};
|
||||
@ -26,6 +26,10 @@ module.exports = app => {
|
||||
ExternalPrintAccount.associate = () => {
|
||||
app.model.ExternalPrintAccount.belongsTo(app.model.ExternalPrintPlatform, { foreignKey: 'platform_id', as: 'platform' });
|
||||
app.model.ExternalPrintAccount.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
|
||||
app.model.ExternalPrintAccount.hasMany(app.model.ExternalPrintExpressInterface, {
|
||||
foreignKey: 'account_id',
|
||||
as: 'expressInterfaces',
|
||||
});
|
||||
};
|
||||
|
||||
return ExternalPrintAccount;
|
||||
|
||||
58
backend/app/model/externalPrintExpressInterface.js
Normal file
58
backend/app/model/externalPrintExpressInterface.js
Normal file
@ -0,0 +1,58 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 外部打单平台快递接口(面单模板)模型,对应 external_print_express_interfaces 表。
|
||||
*
|
||||
* 数据由「从平台同步数据」拉取写入;用户可为模板绑定一个快递编码(custom_code),
|
||||
* WMS 回读运单号时按「打单账号 + 平台 + 编码」定位唯一模板。
|
||||
*
|
||||
* status=0 表示平台侧已不再返回该模板,记录保留用于展示失效与保留绑定。
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} externalPrintExpressInterface model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, JSON, DATE } = app.Sequelize;
|
||||
|
||||
const ExternalPrintExpressInterface = app.model.define('external_print_express_interface', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
|
||||
account_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属外部打单账号ID' },
|
||||
platform_type: { type: STRING(32), allowNull: false, defaultValue: '', comment: '打单平台原始平台类型' },
|
||||
platform_code: { type: STRING(20), allowNull: false, defaultValue: '', comment: 'OMS 预设平台编码' },
|
||||
platform_name: { type: STRING(50), comment: 'OMS 预设平台名称' },
|
||||
template_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '平台面单模板ID' },
|
||||
template_name: { type: STRING(128), comment: '模板名称' },
|
||||
express_company_id: { type: BIGINT.UNSIGNED, comment: '平台快递公司ID' },
|
||||
express_company_code: { type: STRING(50), comment: '平台快递公司编码' },
|
||||
express_company_name: { type: STRING(100), comment: '平台快递公司名称' },
|
||||
shop_id: { type: BIGINT.UNSIGNED, comment: '平台店铺ID' },
|
||||
shop_name: { type: STRING(128), comment: '平台店铺名称' },
|
||||
dbname: { type: STRING(128), comment: '拉取时使用的分区库名' },
|
||||
custom_code: { type: STRING(50), comment: '绑定的快递编码(系统或自定义),回读时按账号+平台+编码定位' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1有效 0失效' },
|
||||
platform_updated_at: { type: DATE, comment: '平台侧更新时间' },
|
||||
synced_at: { type: DATE, comment: '最近一次拉取时间' },
|
||||
raw: { type: JSON, comment: '平台返回的原始结构' },
|
||||
remark: { type: STRING(255), comment: '备注' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
}, {
|
||||
tableName: 'external_print_express_interfaces',
|
||||
comment: '外部打单平台快递接口(面单模板)',
|
||||
});
|
||||
|
||||
ExternalPrintExpressInterface.associate = () => {
|
||||
app.model.ExternalPrintExpressInterface.belongsTo(app.model.ExternalPrintAccount, {
|
||||
foreignKey: 'account_id',
|
||||
as: 'account',
|
||||
});
|
||||
// 自定义编码若恰好等于字典编码,可带出快递名称(仅用于展示,不参与保存校验)
|
||||
app.model.ExternalPrintExpressInterface.belongsTo(app.model.ExpressCompany, {
|
||||
foreignKey: 'custom_code',
|
||||
targetKey: 'code',
|
||||
as: 'customExpressCompany',
|
||||
});
|
||||
};
|
||||
|
||||
return ExternalPrintExpressInterface;
|
||||
};
|
||||
31
backend/app/model/openapiRequestIdempotency.js
Normal file
31
backend/app/model/openapiRequestIdempotency.js
Normal file
@ -0,0 +1,31 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 对外 OpenAPI 请求幂等模型,对应 openapi_request_idempotency 表。
|
||||
* 以 (app_key, method, request_id) 唯一;处理完成后保存完整响应,重试时原样回放。
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} openapiRequestIdempotency model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, INTEGER, TEXT, DATE } = app.Sequelize;
|
||||
|
||||
const OpenapiRequestIdempotency = app.model.define('openapi_request_idempotency', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
app_key: { type: STRING(100), allowNull: false, comment: '请求携带的 app_key' },
|
||||
method: { type: STRING(100), allowNull: false, comment: 'OpenAPI 方法名(模块.动作)' },
|
||||
request_id: { type: STRING(100), allowNull: false, comment: '调用方请求ID' },
|
||||
request_hash: { type: STRING(64), allowNull: false, comment: 'method + app_key + 请求报文摘要' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, comment: '按 app_key 定位到的主体ID' },
|
||||
warehouse_id: { type: BIGINT.UNSIGNED, comment: '按 app_key 定位到的仓库ID' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 0, comment: '状态:0处理中 1成功 2失败' },
|
||||
http_status: { type: INTEGER, comment: '响应 HTTP 状态码' },
|
||||
response_body: { type: TEXT('medium'), comment: '完整响应报文(重试时原样回放)' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
}, {
|
||||
tableName: 'openapi_request_idempotency',
|
||||
comment: '对外 OpenAPI 请求幂等表',
|
||||
});
|
||||
|
||||
return OpenapiRequestIdempotency;
|
||||
};
|
||||
@ -148,6 +148,11 @@ module.exports = app => {
|
||||
router.post('/api/external-print-accounts/:id/shops/:shopId/pull-products', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount.pullShopProducts);
|
||||
// 拉取商家订单(含明细),明细按店铺商品绑定关系写入系统商品关联
|
||||
router.post('/api/external-print-accounts/:id/shops/:shopId/sync-orders', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount.syncShopOrders);
|
||||
// 快递接口(面单模板):查看读取已落库数据,手动同步全量拉取;保存绑定的快递编码,明细单独请求平台接口
|
||||
router.get('/api/external-print-accounts/:id/express-interfaces', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintExpressInterface.index);
|
||||
router.post('/api/external-print-accounts/:id/sync-express-interfaces', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintExpressInterface.sync);
|
||||
router.put('/api/external-print-accounts/:id/express-interfaces', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintExpressInterface.saveSettings);
|
||||
router.get('/api/external-print-accounts/:id/express-interfaces/:interfaceId/detail', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintExpressInterface.detail);
|
||||
router.resources('externalPrintAccounts', '/api/external-print-accounts', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount);
|
||||
// 出入库单与明细(明细共用 stock_items 表,以 bill_type 区分:1入库 2出库)
|
||||
// 单据状态由业务事务推动(审核/推送/完成/驳回/作废/取消/恢复),不提供直接修改状态的接口
|
||||
@ -180,6 +185,9 @@ module.exports = app => {
|
||||
// 快递公司字典(通用字典,不区分主体):下拉需在 resources 之前注册,避免 /select 被当作 :id
|
||||
router.get('/api/express-companies/select', jwtAuth, controller.expressCompany.select);
|
||||
router.resources('expressCompanies', '/api/express-companies', jwtAuth, controller.expressCompany);
|
||||
// 自定义快递编码(全局字典):订单选快递 / 快递接口绑定共用;options 需在 resources 之前注册
|
||||
router.get('/api/custom-express-codes/options', jwtAuth, controller.customExpressCode.options);
|
||||
router.resources('customExpressCodes', '/api/custom-express-codes', jwtAuth, controller.customExpressCode);
|
||||
|
||||
// 商品属性字典(分类/品牌/单位,按主体隔离):下拉需在 resources 之前注册,避免 /select 被当作 :id
|
||||
router.get('/api/product-categories/select', jwtAuth, principalCheck({ model: 'ProductCategory' }), controller.productCategory.select);
|
||||
|
||||
31
backend/app/schedule/clear_openapi_idempotency.js
Normal file
31
backend/app/schedule/clear_openapi_idempotency.js
Normal file
@ -0,0 +1,31 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 定时清理 OpenAPI 幂等记录:每日凌晨 2 点执行,删除超过保留天数(默认 7 天)的记录。
|
||||
*
|
||||
* 幂等只需要覆盖调用方的重试窗口,过期记录可安全清理,避免表无限增长。
|
||||
*/
|
||||
const KEEP_DAYS = Number(process.env.OPENAPI_IDEMPOTENCY_KEEP_DAYS) || 7;
|
||||
|
||||
module.exports = {
|
||||
schedule: {
|
||||
cron: '0 0 2 * * *',
|
||||
type: 'worker',
|
||||
disable: false,
|
||||
},
|
||||
|
||||
/**
|
||||
* 执行清理
|
||||
* @param {Egg.Context} ctx egg context(定时任务上下文)
|
||||
* @return {Promise<number>} 删除的记录数
|
||||
*/
|
||||
async task(ctx) {
|
||||
const Op = ctx.app.Sequelize.Op;
|
||||
const threshold = new Date(Date.now() - KEEP_DAYS * 24 * 60 * 60 * 1000);
|
||||
const count = await ctx.model.OpenapiRequestIdempotency.destroy({
|
||||
where: { created_at: { [Op.lt]: threshold } },
|
||||
});
|
||||
ctx.logger.info(`[openapi-idempotency] 已清理 ${KEEP_DAYS} 天前的幂等记录,共删除 ${count} 条`);
|
||||
return count;
|
||||
},
|
||||
};
|
||||
@ -11,6 +11,9 @@ const KEYS = {
|
||||
userPrincipals: userId => `${PREFIX}:user-principals:${userId}`,
|
||||
principalOptions: userId => `${PREFIX}:principal-options:${userId}`,
|
||||
principal: principalId => `${PREFIX}:principal:${principalId}`,
|
||||
shopBasic: shopId => `${PREFIX}:shop-basic:${shopId}`,
|
||||
externalPrintAccount: accountId => `${PREFIX}:external-print-account:${accountId}`,
|
||||
expressTemplate: (accountId, platformCode, expressCode) => `${PREFIX}:express-template:${accountId}:${platformCode}:${expressCode}`,
|
||||
};
|
||||
|
||||
/**
|
||||
@ -194,6 +197,62 @@ class CacheService extends Service {
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- 店铺 / 打单平台配置(推送、取号高频读取) ----------
|
||||
|
||||
/**
|
||||
* 店铺基础资料(推送需要名称,取号需要类型与外部打单账号)
|
||||
* @param {Number} shopId 店铺ID
|
||||
* @return {Promise<Object>} 店铺基础资料,不存在为 null
|
||||
*/
|
||||
async getShopBasic(shopId) {
|
||||
if (!shopId) return null;
|
||||
return await this.remember(KEYS.shopBasic(shopId), this.ttls.shop, async () => {
|
||||
const shop = await this.ctx.model.Shop.findByPk(shopId, {
|
||||
attributes: [ 'id', 'principal_id', 'name', 'type', 'external_print_account_id' ],
|
||||
});
|
||||
return shop ? shop.toJSON() : null;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 外部打单账号及其平台配置(含 fetch_waybill_no,决定是否回 OMS 取号)
|
||||
* @param {Number} accountId 外部打单账号ID
|
||||
* @return {Promise<Object>} 账号与平台配置,不存在为 null
|
||||
*/
|
||||
async getExternalPrintAccount(accountId) {
|
||||
if (!accountId) return null;
|
||||
return await this.remember(KEYS.externalPrintAccount(accountId), this.ttls.platform, async () => {
|
||||
const account = await this.ctx.model.ExternalPrintAccount.findByPk(accountId, {
|
||||
attributes: [ 'id', 'principal_id', 'platform_id' ],
|
||||
include: [
|
||||
{
|
||||
model: this.ctx.model.ExternalPrintPlatform,
|
||||
as: 'platform',
|
||||
attributes: [ 'id', 'code', 'name', 'url', 'fetch_waybill_no' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
return account ? account.toJSON() : null;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 快递编码 → 面单模板绑定关系(未绑定的结果也缓存,避免批量取号反复穿透查库)
|
||||
* @param {Number} accountId 外部打单账号ID
|
||||
* @param {String} platformCode OMS 预设平台编码
|
||||
* @param {String} expressCode 快递编码(系统或自定义)
|
||||
* @param {Function} loader 未命中时的查询函数
|
||||
* @return {Promise<Object|null>} 模板记录,未绑定为 null
|
||||
*/
|
||||
async getExpressTemplate(accountId, platformCode, expressCode, loader) {
|
||||
const cached = await this.remember(
|
||||
KEYS.expressTemplate(accountId, platformCode, expressCode),
|
||||
this.ttls.platform,
|
||||
async () => ({ template: (await loader()) || null })
|
||||
);
|
||||
return cached ? cached.template : null;
|
||||
}
|
||||
|
||||
// ---------- 失效 ----------
|
||||
|
||||
/**
|
||||
@ -229,6 +288,26 @@ class CacheService extends Service {
|
||||
await this.forgetByPrefix(`${PREFIX}:principal-options:`);
|
||||
await this.forgetByPrefix(`${PREFIX}:user-principals:`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 店铺资料变更后失效
|
||||
* @param {Number} shopId 店铺ID
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async invalidateShop(shopId) {
|
||||
await this.forget(KEYS.shopBasic(shopId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 外部打单账号(或其快递接口绑定)变更后失效:账号平台配置 + 该账号下所有编码绑定
|
||||
* @param {Number} accountId 外部打单账号ID
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async invalidateExternalPrintAccount(accountId) {
|
||||
await this.forget(KEYS.externalPrintAccount(accountId));
|
||||
// 绑定关系按(账号 + 平台 + 编码)建 key,只能按账号前缀批量清除
|
||||
await this.forgetByPrefix(`${PREFIX}:express-template:${accountId}:`);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CacheService;
|
||||
|
||||
411
backend/app/service/externalPrintExpressInterface.js
Normal file
411
backend/app/service/externalPrintExpressInterface.js
Normal file
@ -0,0 +1,411 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
const { parsePagination } = require('../lib/pagination');
|
||||
|
||||
/** 明细接口可能返回的敏感字段(不回显给前端) */
|
||||
const SENSITIVE_DETAIL_KEYS = [ 'CustomerPwd', 'Password', 'Secret', 'Token', 'AppSecret', 'PrivateKey' ];
|
||||
|
||||
/**
|
||||
* 递归屏蔽明细里的凭据字段,避免电子面单账号密码通过接口泄露
|
||||
* @param {*} value 原始值
|
||||
* @return {*} 屏蔽后的值
|
||||
*/
|
||||
function maskSensitive(value) {
|
||||
if (Array.isArray(value)) return value.map(maskSensitive);
|
||||
if (!value || typeof value !== 'object') return value;
|
||||
const result = {};
|
||||
for (const [ key, item ] of Object.entries(value)) {
|
||||
result[key] = SENSITIVE_DETAIL_KEYS.includes(key) ? '******' : maskSensitive(item);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 外部打单平台快递接口(面单模板)服务。
|
||||
*
|
||||
* 数据来源:打单账号登录后,按账号下每个外部店铺的平台分区拉取全部面单模板;
|
||||
* 自定义编码与默认设置属于人工配置,同步时只刷新平台字段,不覆盖这些配置。
|
||||
* 平台侧不再返回的模板不删除,标记 status=0(已失效),保证映射配置不丢失。
|
||||
*/
|
||||
class ExternalPrintExpressInterfaceService extends Service {
|
||||
/**
|
||||
* 从平台全量拉取账号下所有店铺的快递接口并落库
|
||||
* @param {Object} account 打单账号实例(需 include platform)
|
||||
* @param {number} principalId 主体ID
|
||||
* @return {Promise<Object>} 同步结果(总数 / 新增 / 更新 / 失效 / 店铺 / 错误)
|
||||
*/
|
||||
async sync(account, principalId) {
|
||||
const { ctx } = this;
|
||||
const platformService = ctx.service.externalPrintOrder.createPlatformService(account);
|
||||
if (typeof platformService.listExpressTemplates !== 'function') {
|
||||
const err = new Error(`外部打单平台 ${account.platform.name} 暂不支持拉取快递接口`);
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
|
||||
const shops = await ctx.model.Shop.findAll({
|
||||
where: { principal_id: principalId, external_print_account_id: account.id, type: 2 },
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
});
|
||||
if (!shops.length) {
|
||||
const err = new Error('该账号下还没有外部打单平台店铺,请先「查看店铺」并添加店铺后再拉取快递接口');
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
|
||||
const merged = new Map();
|
||||
const errors = [];
|
||||
const syncedShops = [];
|
||||
for (const shop of shops) {
|
||||
try {
|
||||
const result = await platformService.listExpressTemplates(shop.get({ plain: true }));
|
||||
for (const item of result.list) merged.set(item.template_id, item);
|
||||
for (const message of result.errors) errors.push(`${shop.name}:${message}`);
|
||||
if (result.list.length) syncedShops.push(shop.name);
|
||||
} catch (err) {
|
||||
errors.push(`${shop.name}:${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 只有全部店铺都拉取成功时才标记失效,避免部分分区失败导致映射被误判为失效
|
||||
const fullScan = errors.length === 0;
|
||||
if (!merged.size && !fullScan) {
|
||||
const err = new Error(`拉取快递接口失败:${errors[0]}`);
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
const now = new Date();
|
||||
const transaction = await ctx.model.transaction();
|
||||
let created = 0;
|
||||
let updated = 0;
|
||||
let invalidated = 0;
|
||||
try {
|
||||
const existing = await ctx.model.ExternalPrintExpressInterface.findAll({
|
||||
where: { principal_id: principalId, account_id: account.id },
|
||||
transaction,
|
||||
});
|
||||
const byTemplate = new Map(existing.map(row => [ String(row.template_id), row ]));
|
||||
|
||||
for (const item of merged.values()) {
|
||||
const patch = {
|
||||
platform_type: item.platform_type,
|
||||
platform_code: item.platform_code,
|
||||
platform_name: item.platform_name,
|
||||
template_name: item.template_name,
|
||||
express_company_id: item.express_company_id || null,
|
||||
express_company_code: item.express_company_code || null,
|
||||
express_company_name: item.express_company_name || null,
|
||||
shop_id: item.shop_id || null,
|
||||
shop_name: item.shop_name || null,
|
||||
dbname: item.dbname || null,
|
||||
platform_updated_at: item.platform_updated_at || null,
|
||||
synced_at: now,
|
||||
status: 1,
|
||||
raw: item.raw,
|
||||
};
|
||||
const row = byTemplate.get(item.template_id);
|
||||
if (row) {
|
||||
await row.update(patch, { transaction });
|
||||
updated += 1;
|
||||
byTemplate.delete(item.template_id);
|
||||
} else {
|
||||
await ctx.model.ExternalPrintExpressInterface.create({
|
||||
principal_id: principalId,
|
||||
account_id: account.id,
|
||||
template_id: item.template_id,
|
||||
...patch,
|
||||
}, { transaction });
|
||||
created += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (fullScan) {
|
||||
for (const row of byTemplate.values()) {
|
||||
if (Number(row.status) === 0) continue;
|
||||
// 失效后不再参与回读定位,但绑定的快递编码保留,便于平台恢复后继续使用
|
||||
await row.update({ status: 0, synced_at: now }, { transaction });
|
||||
invalidated += 1;
|
||||
}
|
||||
}
|
||||
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
|
||||
// 平台同步会新增/失效模板并改写绑定,清掉该账号的绑定缓存
|
||||
await this.invalidateTemplateCache(account.id);
|
||||
|
||||
return {
|
||||
total: merged.size,
|
||||
created,
|
||||
updated,
|
||||
invalidated,
|
||||
shops: syncedShops,
|
||||
errors,
|
||||
full_scan: fullScan,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询已落库的快递接口
|
||||
* @param {Object} account 打单账号实例
|
||||
* @param {Object} params 查询参数(page / pageSize / status / platform_code / express_company_code / keyword)
|
||||
* @param {number} principalId 主体ID
|
||||
* @return {Promise<{list: Array, total: number}>} 列表与总数
|
||||
*/
|
||||
async list(account, params, principalId) {
|
||||
const { ctx } = this;
|
||||
const Op = ctx.app.Sequelize.Op;
|
||||
const { page, pageSize, offset, limit } = parsePagination(params);
|
||||
const where = { principal_id: principalId, account_id: account.id };
|
||||
|
||||
if (params.status !== undefined && params.status !== '' && params.status !== null) {
|
||||
where.status = Number(params.status) === 0 ? 0 : 1;
|
||||
}
|
||||
if (params.platform_code) where.platform_code = String(params.platform_code).trim();
|
||||
if (params.express_company_code) where.express_company_code = String(params.express_company_code).trim();
|
||||
|
||||
const keyword = String(params.keyword || '').trim();
|
||||
if (keyword) {
|
||||
where[Op.or] = [
|
||||
{ template_name: { [Op.like]: `%${keyword}%` } },
|
||||
{ express_company_name: { [Op.like]: `%${keyword}%` } },
|
||||
{ express_company_code: { [Op.like]: `%${keyword}%` } },
|
||||
{ shop_name: { [Op.like]: `%${keyword}%` } },
|
||||
{ custom_code: { [Op.like]: `%${keyword}%` } },
|
||||
];
|
||||
}
|
||||
|
||||
const { count, rows } = await ctx.model.ExternalPrintExpressInterface.findAndCountAll({
|
||||
where,
|
||||
offset,
|
||||
limit,
|
||||
// 列表不返回平台原始结构,避免大数据量拖慢列表
|
||||
attributes: { exclude: [ 'raw' ] },
|
||||
order: [
|
||||
[ 'status', 'DESC' ],
|
||||
[ 'platform_code', 'ASC' ],
|
||||
[ 'express_company_name', 'ASC' ],
|
||||
[ 'template_name', 'ASC' ],
|
||||
[ 'id', 'ASC' ],
|
||||
],
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.ExpressCompany,
|
||||
as: 'customExpressCompany',
|
||||
attributes: [ 'id', 'code', 'name' ],
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return { list: rows, total: count, page, pageSize };
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存人工配置:绑定的快递编码 / 备注
|
||||
*
|
||||
* 同一账号同一平台下,一个快递编码只能绑定一个模板(重复会拒绝),
|
||||
* 保证回读时按「账号 + 平台 + 编码」能唯一定位。
|
||||
* @param {Object} account 打单账号实例
|
||||
* @param {Array} items 待保存项 [{ id, custom_code, remark }]
|
||||
* @param {number} principalId 主体ID
|
||||
* @return {Promise<{updated: number}>} 更新条数
|
||||
*/
|
||||
async saveSettings(account, items, principalId) {
|
||||
const { ctx } = this;
|
||||
const Op = ctx.app.Sequelize.Op;
|
||||
const list = Array.isArray(items) ? items : [];
|
||||
if (!list.length) {
|
||||
const err = new Error('items(待保存的快递接口)不能为空');
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
if (list.length > 500) {
|
||||
const err = new Error('单次最多保存 500 条快递接口设置');
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
|
||||
const ids = [ ...new Set(list.map(item => Number(item && item.id)).filter(id => Number.isInteger(id) && id > 0)) ];
|
||||
if (ids.length !== list.length) {
|
||||
const err = new Error('存在无效或重复的快递接口ID');
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
|
||||
const rows = await ctx.model.ExternalPrintExpressInterface.findAll({
|
||||
where: { id: { [Op.in]: ids }, principal_id: principalId, account_id: account.id },
|
||||
});
|
||||
if (rows.length !== ids.length) {
|
||||
const err = new Error(`存在 ${ids.length - rows.length} 条快递接口不存在或不属于当前账号`);
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
const byId = new Map(rows.map(row => [ Number(row.id), row ]));
|
||||
|
||||
const patches = [];
|
||||
for (const item of list) {
|
||||
const row = byId.get(Number(item.id));
|
||||
const patch = {};
|
||||
if (item.custom_code !== undefined) {
|
||||
// 绑定的快递编码(系统或自定义),仅限制长度;同一账号同平台下必须唯一
|
||||
patch.custom_code = String(item.custom_code || '').trim().slice(0, 50) || null;
|
||||
}
|
||||
if (item.remark !== undefined) {
|
||||
patch.remark = String(item.remark || '').trim().slice(0, 255) || null;
|
||||
}
|
||||
if (Object.keys(patch).length) patches.push({ row, patch });
|
||||
}
|
||||
|
||||
if (!patches.length) return { updated: 0 };
|
||||
|
||||
// 同一账号 + 同一平台内,一个快递编码只能绑定一个模板(不同平台互不影响,可绑定相同编码):
|
||||
// 回读运单号按「订单平台 + 外部携带的快递编码」定位,同平台重复绑定会查到多条而无法确定用哪个
|
||||
const proposals = patches
|
||||
.filter(({ patch }) => patch.custom_code !== undefined && patch.custom_code)
|
||||
.map(({ row, patch }) => ({ row, code: patch.custom_code }));
|
||||
|
||||
for (const { row, code } of proposals) {
|
||||
const label = `${row.platform_name || row.platform_code || '未知平台'}`;
|
||||
const sameBatch = proposals.find(other =>
|
||||
Number(other.row.id) !== Number(row.id) &&
|
||||
other.row.platform_code === row.platform_code &&
|
||||
other.code === code
|
||||
);
|
||||
if (sameBatch) {
|
||||
const err = new Error(
|
||||
`平台「${label}」内快递编码「${code}」重复绑定:本次同时绑定到「${row.template_name || row.template_id}」和「${sameBatch.row.template_name || sameBatch.row.template_id}」,同平台内一个编码只能绑定一个模板,请改用其它编码(不同平台不受影响)`
|
||||
);
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
|
||||
const occupied = await ctx.model.ExternalPrintExpressInterface.findOne({
|
||||
where: {
|
||||
principal_id: principalId,
|
||||
account_id: account.id,
|
||||
platform_code: row.platform_code,
|
||||
custom_code: code,
|
||||
status: 1,
|
||||
id: { [Op.ne]: row.id },
|
||||
},
|
||||
attributes: [ 'id', 'template_name', 'template_id' ],
|
||||
});
|
||||
if (occupied) {
|
||||
const err = new Error(
|
||||
`平台「${label}」内快递编码「${code}」已绑定模板「${occupied.template_name || occupied.template_id}」,同平台内一个编码只能绑定一个模板,请先解除或改用其它编码(不同平台不受影响)`
|
||||
);
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
const transaction = await ctx.model.transaction();
|
||||
try {
|
||||
for (const { row, patch } of patches) {
|
||||
await row.update(patch, { transaction });
|
||||
}
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
|
||||
// 绑定关系变更:清掉该账号的「平台+编码 → 模板」缓存,避免取号短时间仍命中旧模板
|
||||
await this.invalidateTemplateCache(account.id);
|
||||
|
||||
return { updated: patches.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除某打单账号的快递编码绑定缓存(绑定变更 / 平台同步后调用)
|
||||
* @param {number} accountId 打单账号ID
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async invalidateTemplateCache(accountId) {
|
||||
const cache = this.ctx.service && this.ctx.service.cache;
|
||||
if (cache && typeof cache.invalidateExternalPrintAccount === 'function') {
|
||||
await cache.invalidateExternalPrintAccount(accountId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 回读运单号时定位快递接口
|
||||
*
|
||||
* WMS 发起取号会携带快递编码,且必须使用该订单所属外部打单账号(跨打单平台无法打印);
|
||||
* 本方法按「打单账号 + 订单平台(平台编码)+ 绑定的快递编码」唯一定位模板。
|
||||
* 不再参考订单上设置的物流公司,也不按店铺区分(店管家店铺是商家,共用账号下的接口)。
|
||||
* @param {number} accountId 打单账号ID
|
||||
* @param {Object} params 查询条件
|
||||
* @param {string} params.platformCode OMS 平台编码(如 TB)
|
||||
* @param {string} params.expressCode 外部携带的快递编码(系统或自定义)
|
||||
* @param {number} principalId 主体ID
|
||||
* @return {Promise<Object|null>} 命中的接口;未绑定或重复绑定时返回 null
|
||||
*/
|
||||
async resolveByCode(accountId, { platformCode, expressCode } = {}, principalId) {
|
||||
const { ctx } = this;
|
||||
if (!platformCode || !expressCode) return null;
|
||||
|
||||
const loader = async () => {
|
||||
const rows = await ctx.model.ExternalPrintExpressInterface.findAll({
|
||||
where: {
|
||||
principal_id: principalId,
|
||||
account_id: accountId,
|
||||
platform_code: platformCode,
|
||||
custom_code: expressCode,
|
||||
status: 1,
|
||||
},
|
||||
limit: 2,
|
||||
});
|
||||
// 唯一命中才返回;出现重复绑定(历史数据 / 平台变更)时返回 null,避免随意挑一个
|
||||
return rows.length === 1 ? rows[0].toJSON() : null;
|
||||
};
|
||||
|
||||
// 绑定关系查询高频(取号逐单定位模板),走缓存;绑定变更时由 sync / saveSettings 主动失效
|
||||
const cache = ctx.service && ctx.service.cache;
|
||||
if (cache && typeof cache.getExpressTemplate === 'function') {
|
||||
return await cache.getExpressTemplate(accountId, platformCode, expressCode, loader);
|
||||
}
|
||||
return await loader();
|
||||
}
|
||||
|
||||
/**
|
||||
* 查看单个快递接口的平台明细(实时请求平台单独接口)
|
||||
* @param {Object} account 打单账号实例(需 include platform)
|
||||
* @param {number} interfaceId 快递接口记录ID
|
||||
* @param {number} principalId 主体ID
|
||||
* @return {Promise<{interface: Object, detail: Object|null}>} 接口记录与平台明细
|
||||
*/
|
||||
async detail(account, interfaceId, principalId) {
|
||||
const { ctx } = this;
|
||||
const row = await ctx.model.ExternalPrintExpressInterface.findOne({
|
||||
where: { id: interfaceId, principal_id: principalId, account_id: account.id },
|
||||
});
|
||||
if (!row) {
|
||||
const err = new Error('快递接口不存在');
|
||||
err.status = 404;
|
||||
throw err;
|
||||
}
|
||||
if (Number(row.status) === 0) {
|
||||
const err = new Error('该快递接口在平台已失效,无法查看明细;请先重新拉取');
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
|
||||
const platformService = ctx.service.externalPrintOrder.createPlatformService(account);
|
||||
if (typeof platformService.fetchWaybillAccountDetail !== 'function') {
|
||||
const err = new Error(`外部打单平台 ${account.platform.name} 暂不支持查看快递接口明细`);
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
|
||||
const detail = await platformService.fetchWaybillAccountDetail(row.get({ plain: true }));
|
||||
return { interface: row, detail: maskSensitive(detail) };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ExternalPrintExpressInterfaceService;
|
||||
@ -347,6 +347,8 @@ class ExternalPrintOrderService extends Service {
|
||||
|
||||
const fields = {
|
||||
shop_id: shop.id,
|
||||
// 外部打单平台订单:平台配置要求回打单平台取号时,推送 WMS 需在根节点下发 need_oms_waybill=1
|
||||
need_oms_waybill: Number(account.platform && account.platform.fetch_waybill_no) === 1 ? 1 : 0,
|
||||
// 订单页「店铺」列展示 OMS 店铺名(平台店铺名带手机号,写入 extend_props 备用)
|
||||
shop_nick: truncateText(shop.name, 200),
|
||||
product_info: buildProductInfo(lines.map(row => row.line)),
|
||||
|
||||
@ -1560,7 +1560,7 @@ class OrderStatusService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量修改待审核订单快递公司(同步刷新物流编码与名称快照)
|
||||
* 批量修改待审核订单快递(系统快递或自定义快递,同步刷新物流编码与名称快照)
|
||||
* @param {Object} p { ids, logistics_code }
|
||||
* @return {Promise<Object>} { updated, target }
|
||||
*/
|
||||
@ -1586,12 +1586,21 @@ class OrderStatusService extends Service {
|
||||
throw err;
|
||||
}
|
||||
|
||||
const company = await ctx.model.ExpressCompany.findOne({
|
||||
// 优先命中自定义快递编码(订单保存自定义 code/name,推送奇门时原样下发),
|
||||
// 未命中再按系统快递公司字典解析
|
||||
let target = await ctx.model.CustomExpressCode.findOne({
|
||||
where: { code, status: 1 },
|
||||
attributes: [ 'code', 'name' ],
|
||||
});
|
||||
if (!company) {
|
||||
const err = new Error('快递公司不存在或未启用');
|
||||
if (!target) {
|
||||
const company = await ctx.model.ExpressCompany.findOne({
|
||||
where: { code, status: 1 },
|
||||
attributes: [ 'code', 'name' ],
|
||||
});
|
||||
if (company) target = { code: company.code, name: company.name };
|
||||
}
|
||||
if (!target) {
|
||||
const err = new Error('快递编码不存在或未启用(系统快递 / 自定义快递)');
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
@ -1601,7 +1610,7 @@ class OrderStatusService extends Service {
|
||||
let updated = 0;
|
||||
try {
|
||||
const [ count ] = await this._model(ORDER_STATUS.PENDING).update(
|
||||
{ logistics_code: company.code, logistics_name: company.name },
|
||||
{ logistics_code: target.code, logistics_name: target.name },
|
||||
{ where: { principal_id: principalId, id: { [Op.in]: ids } }, transaction }
|
||||
);
|
||||
updated = Number(count) || 0;
|
||||
@ -1616,7 +1625,7 @@ class OrderStatusService extends Service {
|
||||
throw err;
|
||||
}
|
||||
|
||||
return { updated, target: { code: company.code, name: company.name } };
|
||||
return { updated, target: { code: target.code, name: target.name } };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -4,6 +4,7 @@ const { Service } = require('egg');
|
||||
const QimenWmsClient = require('../lib/wms/qimenClient');
|
||||
const { ORDER_STATUS } = require('../lib/orderStatus');
|
||||
const { releaseOrderStock } = require('../utils/orderStock');
|
||||
const { getShopBasic, getAccountWithPlatform } = require('../lib/externalPrintConfig');
|
||||
|
||||
/** 单条单据最多推送尝试次数(无响应/超时才算一次可重试的失败;对方明确响应失败不重试) */
|
||||
const PUSH_MAX_ATTEMPTS = 3;
|
||||
@ -143,6 +144,22 @@ class OrderWmsService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断外部打单平台订单是否需要回 OMS 取号
|
||||
*
|
||||
* 以订单店铺绑定的打单账号所属平台配置 `fetch_waybill_no` 为准(1=需要回取号);
|
||||
* 手工店铺 / 非外部打单平台订单恒为 0。
|
||||
* 店铺与账号平台配置均走缓存(CACHE_TTL_SHOP / CACHE_TTL_PLATFORM),避免批量推送时逐单查库。
|
||||
* @param {Object} order 订单
|
||||
* @param {Object|null} shop 店铺(含 type / external_print_account_id)
|
||||
* @return {Promise<number>} 1 需要回 OMS 取号,0 否
|
||||
*/
|
||||
async resolveNeedOmsWaybill(order, shop) {
|
||||
if (!shop || Number(shop.type) !== 2 || !shop.external_print_account_id) return 0;
|
||||
const account = await getAccountWithPlatform(this.ctx, shop.external_print_account_id, order.principal_id);
|
||||
return account && account.platform && Number(account.platform.fetch_waybill_no) === 1 ? 1 : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载待推送订单(含仓库),仅返回「待推送」的单据
|
||||
* @param {Number|String} id 订单ID
|
||||
@ -223,19 +240,28 @@ class OrderWmsService extends Service {
|
||||
attemptedAt: now.toISOString(),
|
||||
};
|
||||
|
||||
// 店铺名称兜底:shopNick 取所选店铺名称(WMS 侧靠它匹配快递策略)
|
||||
if (!order.shop_nick && order.shop_id) {
|
||||
const shop = await ctx.model.Shop.findByPk(order.shop_id, { attributes: [ 'id', 'name' ] });
|
||||
if (shop && shop.name) {
|
||||
order.shop_nick = shop.name;
|
||||
await order.update({ shop_nick: shop.name });
|
||||
ctx.logger.info(`[order-wms] ${order.order_no} 补齐店铺名称快照:${shop.name}`);
|
||||
}
|
||||
// 店铺信息:补齐店铺名称快照,并判断外部打单平台订单是否需要回 OMS 取号(店铺资料走缓存)
|
||||
const shop = order.shop_id ? await getShopBasic(ctx, order.shop_id, order.principal_id) : null;
|
||||
if (!order.shop_nick && shop && shop.name) {
|
||||
order.shop_nick = shop.name;
|
||||
await order.update({ shop_nick: shop.name });
|
||||
ctx.logger.info(`[order-wms] ${order.order_no} 补齐店铺名称快照:${shop.name}`);
|
||||
}
|
||||
if (!order.shop_nick) {
|
||||
ctx.logger.warn(`[order-wms] ${order.order_no} 未取到店铺名称(shop_nick 为空),推送报文中不会有 shopNick`);
|
||||
}
|
||||
|
||||
// 回 OMS 取号开关:外部打单平台订单按平台配置实时判定(配置变更后未推送的订单也能生效)
|
||||
const needOmsWaybill = await this.resolveNeedOmsWaybill(order, shop);
|
||||
if (Number(order.need_oms_waybill) !== needOmsWaybill) {
|
||||
// 平台配置可能在建单后调整,推送前把实际下发值回写,保证单据记录与报文一致
|
||||
order.need_oms_waybill = needOmsWaybill;
|
||||
await order.update({ need_oms_waybill: needOmsWaybill });
|
||||
}
|
||||
if (needOmsWaybill) {
|
||||
ctx.logger.info(`[order-wms] ${order.order_no} 外部打单平台要求回 OMS 取号,推送 need_oms_waybill=1`);
|
||||
}
|
||||
|
||||
const itemRows = await ctx.model.OrderStatusItem.findAll({
|
||||
where: { order_id: order.id, principal_id: order.principal_id },
|
||||
order: [[ 'order_line_no', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
@ -251,6 +277,8 @@ class OrderWmsService extends Service {
|
||||
const items = itemRows.map(item => item.get({ plain: true }));
|
||||
const wmsItemIds = await this.resolveWmsItemIds(order, items);
|
||||
const view = this.adaptOrder(order, warehouse);
|
||||
// 请求根节点参数:外部打单平台订单按平台配置决定是否回 OMS 取号
|
||||
view.need_oms_waybill = needOmsWaybill;
|
||||
|
||||
let resp;
|
||||
try {
|
||||
|
||||
@ -150,12 +150,15 @@ module.exports = appInfo => {
|
||||
},
|
||||
};
|
||||
|
||||
// 业务缓存有效期(秒):用户信息、主体信息、可选主体列表
|
||||
// 业务缓存有效期(秒):用户信息、主体信息、可选主体列表、快递/打单平台配置
|
||||
// 主体/用户发生新增或更新时,相关缓存会被主动失效,这里的 TTL 仅作为兜底
|
||||
// shop / platform 用于推送、取号高频读取的店铺、打单账号与平台配置,避免逐单查库
|
||||
config.cache = {
|
||||
user: Number(process.env.CACHE_TTL_USER || 600),
|
||||
principal: Number(process.env.CACHE_TTL_PRINCIPAL || 600),
|
||||
principalOptions: Number(process.env.CACHE_TTL_PRINCIPAL_OPTIONS || 600),
|
||||
shop: Number(process.env.CACHE_TTL_SHOP || 300),
|
||||
platform: Number(process.env.CACHE_TTL_PLATFORM || 300),
|
||||
};
|
||||
|
||||
// 邮箱验证码限流:同一邮箱发送间隔(秒)与每日发送上限
|
||||
|
||||
@ -0,0 +1,147 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 外部打单平台快递接口(面单模板)表。
|
||||
*
|
||||
* 每个打单账号从平台拉取到的面单模板落一行,用于:
|
||||
* - 查看平台支持的快递接口(平台 / 店铺 / 模板 / 快递公司);
|
||||
* - 绑定快递编码(custom_code,系统或自定义快递编码),
|
||||
* WMS 回读运单号时按「打单账号 + 平台 + 编码」定位唯一模板。
|
||||
*
|
||||
* status=0 表示平台侧已不再返回该模板:数据保留(绑定的快递编码不丢),
|
||||
* 前端标记为「已失效」,避免映射配置被自动清理。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable('external_print_express_interfaces', {
|
||||
id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键',
|
||||
},
|
||||
principal_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属主体ID',
|
||||
},
|
||||
account_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属外部打单账号ID(external_print_accounts)',
|
||||
},
|
||||
platform_type: {
|
||||
type: Sequelize.STRING(32),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '打单平台原始平台类型(如 Pinduoduo / TouTiao)',
|
||||
},
|
||||
platform_code: {
|
||||
type: Sequelize.STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: 'OMS 预设平台编码(如 PDD,见 app/lib/platformCode.js)',
|
||||
},
|
||||
platform_name: {
|
||||
type: Sequelize.STRING(50),
|
||||
allowNull: true,
|
||||
comment: 'OMS 预设平台名称(如 拼多多)',
|
||||
},
|
||||
template_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '平台面单模板ID(店管家 LoadTemplateListInOrderList 返回的 Id)',
|
||||
},
|
||||
template_name: {
|
||||
type: Sequelize.STRING(128),
|
||||
allowNull: true,
|
||||
comment: '模板名称(如 【拼多多】韵达一联3)',
|
||||
},
|
||||
express_company_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '平台快递公司ID',
|
||||
},
|
||||
express_company_code: {
|
||||
type: Sequelize.STRING(50),
|
||||
allowNull: true,
|
||||
comment: '平台快递公司编码(如 YUNDA / STO)',
|
||||
},
|
||||
express_company_name: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '平台快递公司名称(如 韵达)',
|
||||
},
|
||||
shop_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '平台店铺(商家)ID',
|
||||
},
|
||||
shop_name: {
|
||||
type: Sequelize.STRING(128),
|
||||
allowNull: true,
|
||||
comment: '平台店铺(商家)名称',
|
||||
},
|
||||
dbname: {
|
||||
type: Sequelize.STRING(128),
|
||||
allowNull: true,
|
||||
comment: '拉取时使用的分区库名(查看明细时复用)',
|
||||
},
|
||||
custom_code: {
|
||||
type: Sequelize.STRING(50),
|
||||
allowNull: true,
|
||||
comment: '绑定的快递编码(系统或自定义),回读运单号时按 账号 + 平台 + 编码 定位',
|
||||
},
|
||||
status: {
|
||||
type: Sequelize.TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '状态:1有效 0平台已不再返回(失效,保留自定义设置)',
|
||||
},
|
||||
platform_updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '平台侧更新时间(模板 UpdateDate)',
|
||||
},
|
||||
synced_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '最近一次从平台拉取到的时间',
|
||||
},
|
||||
raw: {
|
||||
type: Sequelize.JSON,
|
||||
allowNull: true,
|
||||
comment: '平台返回的模板原始结构',
|
||||
},
|
||||
remark: {
|
||||
type: Sequelize.STRING(255),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
created_at: { type: Sequelize.DATE, allowNull: true, comment: '创建时间' },
|
||||
updated_at: { type: Sequelize.DATE, allowNull: true, comment: '更新时间' },
|
||||
});
|
||||
|
||||
await queryInterface.addIndex('external_print_express_interfaces', [ 'account_id', 'template_id' ], {
|
||||
name: 'uk_external_print_express_template',
|
||||
unique: true,
|
||||
});
|
||||
await queryInterface.addIndex('external_print_express_interfaces', [ 'principal_id', 'account_id' ], {
|
||||
name: 'idx_external_print_express_account',
|
||||
});
|
||||
await queryInterface.addIndex('external_print_express_interfaces', [ 'principal_id', 'platform_code' ], {
|
||||
name: 'idx_external_print_express_platform',
|
||||
});
|
||||
await queryInterface.addIndex('external_print_express_interfaces', [ 'principal_id', 'express_company_code' ], {
|
||||
name: 'idx_external_print_express_company',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.removeIndex('external_print_express_interfaces', 'idx_external_print_express_company');
|
||||
await queryInterface.removeIndex('external_print_express_interfaces', 'idx_external_print_express_platform');
|
||||
await queryInterface.removeIndex('external_print_express_interfaces', 'idx_external_print_express_account');
|
||||
await queryInterface.removeIndex('external_print_express_interfaces', 'uk_external_print_express_template');
|
||||
await queryInterface.dropTable('external_print_express_interfaces');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,73 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 自定义快递编码字典。
|
||||
*
|
||||
* 由「系统管理 → 自定义快递编码」维护(全局字典,不区分主体):
|
||||
* - code:自定义编码(订单 logistics_code 直接写这个值,推送奇门时原样下发)
|
||||
* - name:自定义名称(订单 logistics_name 直接写这个值)
|
||||
* - express_code:对应的系统快递编码(express_companies.code,便于对账与映射)
|
||||
*
|
||||
* 订单选择自定义快递后,logistics_code / logistics_name 保存自定义值,
|
||||
* 推送 WMS(奇门 deliveryOrder.logisticsCode / logisticsName)时保持自定义值不变。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable('custom_express_codes', {
|
||||
id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键',
|
||||
},
|
||||
code: {
|
||||
type: Sequelize.STRING(50),
|
||||
allowNull: false,
|
||||
comment: '自定义快递编码(订单 logistics_code)',
|
||||
},
|
||||
name: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: false,
|
||||
comment: '自定义快递名称(订单 logistics_name)',
|
||||
},
|
||||
express_code: {
|
||||
type: Sequelize.STRING(50),
|
||||
allowNull: false,
|
||||
comment: '对应的系统快递编码(express_companies.code)',
|
||||
},
|
||||
sort: {
|
||||
type: Sequelize.INTEGER,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '排序(下拉展示顺序,越小越靠前)',
|
||||
},
|
||||
status: {
|
||||
type: Sequelize.TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '状态:1启用 0禁用',
|
||||
},
|
||||
remark: {
|
||||
type: Sequelize.STRING(255),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
created_at: { type: Sequelize.DATE, allowNull: true, comment: '创建时间' },
|
||||
updated_at: { type: Sequelize.DATE, allowNull: true, comment: '更新时间' },
|
||||
});
|
||||
|
||||
await queryInterface.addIndex('custom_express_codes', [ 'code' ], {
|
||||
name: 'uk_custom_express_codes_code',
|
||||
unique: true,
|
||||
});
|
||||
await queryInterface.addIndex('custom_express_codes', [ 'express_code' ], {
|
||||
name: 'idx_custom_express_codes_express_code',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.removeIndex('custom_express_codes', 'idx_custom_express_codes_express_code');
|
||||
await queryInterface.removeIndex('custom_express_codes', 'uk_custom_express_codes_code');
|
||||
await queryInterface.dropTable('custom_express_codes');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,60 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 新增「自定义快递编码」菜单:挂在「系统管理」目录下。
|
||||
* 按 name + parent_id 判重,可重复执行。
|
||||
*/
|
||||
const PARENT_NAME = '系统管理';
|
||||
const MENU = {
|
||||
name: '自定义快递编码',
|
||||
type: 2,
|
||||
path: '/system/custom-express',
|
||||
icon: 'Van',
|
||||
permission: null,
|
||||
component: 'views/CustomExpress/Index.vue',
|
||||
sort: 60,
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const sequelize = queryInterface.sequelize;
|
||||
|
||||
const [ parent ] = await sequelize.query(
|
||||
'SELECT id FROM menus WHERE name = ? AND parent_id = 0 LIMIT 1',
|
||||
{ replacements: [ PARENT_NAME ], type: sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
if (!parent) return;
|
||||
const parentId = Number(parent.id);
|
||||
|
||||
const [ exist ] = await sequelize.query(
|
||||
'SELECT id FROM menus WHERE name = ? AND parent_id = ? LIMIT 1',
|
||||
{ replacements: [ MENU.name, parentId ], type: sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
if (exist) return;
|
||||
|
||||
await sequelize.query(
|
||||
`INSERT INTO menus
|
||||
(parent_id, name, type, path, icon, permission, component, sort, status, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, NOW(), NOW())`,
|
||||
{
|
||||
replacements: [
|
||||
parentId,
|
||||
MENU.name,
|
||||
MENU.type,
|
||||
MENU.path,
|
||||
MENU.icon,
|
||||
MENU.permission,
|
||||
MENU.component,
|
||||
MENU.sort,
|
||||
],
|
||||
}
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const sequelize = queryInterface.sequelize;
|
||||
await sequelize.query('DELETE FROM menus WHERE name = ? AND path = ?', {
|
||||
replacements: [ MENU.name, MENU.path ],
|
||||
});
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,87 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 对外 OpenAPI 请求幂等表。
|
||||
*
|
||||
* 外部系统(WMS)回调可能因超时重试,同一请求不应重复执行:
|
||||
* - 以 (app_key, method, request_id) 唯一;
|
||||
* - request_hash 记录 method + app_key + 请求报文摘要,防止同一 request_id 搭配不同报文;
|
||||
* - status:0 处理中 / 1 成功 / 2 失败;处理完成后 response_body 保存完整响应,
|
||||
* 重试时直接回放原响应(含逐单成功/失败结果)。
|
||||
*
|
||||
* 与 callback_logs 的区别:callback_logs 是异步、截断的排查日志;本表是可回放的幂等凭据。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable('openapi_request_idempotency', {
|
||||
id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键',
|
||||
},
|
||||
app_key: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: false,
|
||||
comment: '请求携带的 app_key',
|
||||
},
|
||||
method: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: false,
|
||||
comment: 'OpenAPI 方法名(模块.动作)',
|
||||
},
|
||||
request_id: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: false,
|
||||
comment: '调用方请求ID(query request_id / header X-Request-Id / body requestId)',
|
||||
},
|
||||
request_hash: {
|
||||
type: Sequelize.STRING(64),
|
||||
allowNull: false,
|
||||
comment: 'method + app_key + 请求报文摘要,防止同一 request_id 复用不同报文',
|
||||
},
|
||||
principal_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '按 app_key 定位到的主体ID',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '按 app_key 定位到的仓库ID',
|
||||
},
|
||||
status: {
|
||||
type: Sequelize.TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '状态:0处理中 1成功 2失败',
|
||||
},
|
||||
http_status: {
|
||||
type: Sequelize.INTEGER,
|
||||
allowNull: true,
|
||||
comment: '响应 HTTP 状态码',
|
||||
},
|
||||
response_body: {
|
||||
type: Sequelize.TEXT('medium'),
|
||||
allowNull: true,
|
||||
comment: '完整响应报文(重试时原样回放)',
|
||||
},
|
||||
created_at: { type: Sequelize.DATE, allowNull: true, comment: '创建时间' },
|
||||
updated_at: { type: Sequelize.DATE, allowNull: true, comment: '更新时间' },
|
||||
});
|
||||
|
||||
await queryInterface.addIndex('openapi_request_idempotency', [ 'app_key', 'method', 'request_id' ], {
|
||||
name: 'uk_openapi_request_id',
|
||||
unique: true,
|
||||
});
|
||||
await queryInterface.addIndex('openapi_request_idempotency', [ 'created_at' ], {
|
||||
name: 'idx_openapi_request_created',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.removeIndex('openapi_request_idempotency', 'idx_openapi_request_created');
|
||||
await queryInterface.removeIndex('openapi_request_idempotency', 'uk_openapi_request_id');
|
||||
await queryInterface.dropTable('openapi_request_idempotency');
|
||||
},
|
||||
};
|
||||
65
frontend/src/api/customExpressCode.ts
Normal file
65
frontend/src/api/customExpressCode.ts
Normal file
@ -0,0 +1,65 @@
|
||||
import { get, post, put, del } from '@/utils/request'
|
||||
|
||||
/** 自定义快递编码(全局字典) */
|
||||
export interface CustomExpressCodeItem {
|
||||
id: number
|
||||
/** 自定义编码(订单 logistics_code) */
|
||||
code: string
|
||||
/** 自定义名称(订单 logistics_name) */
|
||||
name: string
|
||||
/** 对应的系统快递编码(express_companies.code) */
|
||||
express_code: string
|
||||
sort: number
|
||||
status: number
|
||||
remark: string | null
|
||||
/** 对应系统快递(列表接口附带) */
|
||||
expressCompany?: { id: number; code: string; name: string } | null
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
|
||||
export interface CustomExpressCodePayload {
|
||||
code: string
|
||||
name: string
|
||||
express_code: string
|
||||
sort?: number
|
||||
status?: number
|
||||
remark?: string | null
|
||||
}
|
||||
|
||||
/** 订单 / 快递接口共用的快递下拉项:自定义 + 系统 */
|
||||
export interface ExpressCodeOption {
|
||||
code: string
|
||||
name: string
|
||||
/** custom 自定义快递编码 / system 系统快递公司 */
|
||||
source: 'custom' | 'system'
|
||||
/** 对应的系统快递编码(system 项即自身) */
|
||||
express_code: string
|
||||
/** 对应的系统快递名称 */
|
||||
express_name: string
|
||||
sort?: number
|
||||
}
|
||||
|
||||
export function getCustomExpressCodes(params?: object) {
|
||||
return get<{ list: CustomExpressCodeItem[]; total: number; page: number; pageSize: number }>(
|
||||
'/custom-express-codes',
|
||||
params,
|
||||
)
|
||||
}
|
||||
|
||||
export function createCustomExpressCode(data: CustomExpressCodePayload) {
|
||||
return post<{ id: number }>('/custom-express-codes', data)
|
||||
}
|
||||
|
||||
export function updateCustomExpressCode(id: number, data: Partial<CustomExpressCodePayload>) {
|
||||
return put<{ id: number }>(`/custom-express-codes/${id}`, data)
|
||||
}
|
||||
|
||||
export function deleteCustomExpressCode(id: number) {
|
||||
return del<{ id: number }>(`/custom-express-codes/${id}`)
|
||||
}
|
||||
|
||||
/** 快递下拉:启用的自定义快递编码 + 系统快递公司 */
|
||||
export function getExpressCodeOptions() {
|
||||
return get<ExpressCodeOption[]>('/custom-express-codes/options')
|
||||
}
|
||||
100
frontend/src/api/externalPrintExpressInterface.ts
Normal file
100
frontend/src/api/externalPrintExpressInterface.ts
Normal file
@ -0,0 +1,100 @@
|
||||
import { get, post, put } from '@/utils/request'
|
||||
import type { ExpressCompanyOption } from '@/api/expressCompany'
|
||||
|
||||
/** 外部打单平台快递接口(面单模板) */
|
||||
export interface ExternalPrintExpressInterfaceItem {
|
||||
id: number
|
||||
principal_id: number
|
||||
account_id: number
|
||||
/** 打单平台原始平台类型(如 Pinduoduo) */
|
||||
platform_type: string
|
||||
/** OMS 预设平台编码(如 PDD) */
|
||||
platform_code: string
|
||||
platform_name: string | null
|
||||
/** 平台面单模板ID */
|
||||
template_id: string
|
||||
template_name: string | null
|
||||
express_company_id: number | null
|
||||
/** 平台快递公司编码(如 YUNDA) */
|
||||
express_company_code: string | null
|
||||
express_company_name: string | null
|
||||
shop_id: number | null
|
||||
shop_name: string | null
|
||||
/** 绑定的快递编码(系统或自定义),回读时按账号 + 平台 + 编码定位 */
|
||||
custom_code: string | null
|
||||
/** 1有效 0平台已不再返回(失效) */
|
||||
status: number
|
||||
platform_updated_at?: string | null
|
||||
synced_at?: string | null
|
||||
remark: string | null
|
||||
/** 自定义编码命中的快递公司字典项 */
|
||||
customExpressCompany?: Pick<ExpressCompanyOption, 'id' | 'code' | 'name'> | null
|
||||
}
|
||||
|
||||
export interface ExternalPrintExpressInterfaceQuery {
|
||||
page: number
|
||||
pageSize: number
|
||||
status: string | number
|
||||
platform_code: string
|
||||
express_company_code: string
|
||||
keyword: string
|
||||
}
|
||||
|
||||
/** 全量拉取结果 */
|
||||
export interface ExternalPrintExpressInterfaceSyncResult {
|
||||
total: number
|
||||
created: number
|
||||
updated: number
|
||||
/** 平台侧已不存在、本次标记为失效的条数 */
|
||||
invalidated: number
|
||||
/** 拉到数据的店铺名称 */
|
||||
shops: string[]
|
||||
/** 逐店铺 / 分区的失败原因(部分失败不影响其它分区) */
|
||||
errors: string[]
|
||||
/** 是否所有店铺都拉取成功(失败时不会标记失效) */
|
||||
full_scan: boolean
|
||||
}
|
||||
|
||||
/** 明细接口返回 */
|
||||
export interface ExternalPrintExpressInterfaceDetail {
|
||||
interface: ExternalPrintExpressInterfaceItem
|
||||
detail: Record<string, unknown> | null
|
||||
}
|
||||
|
||||
/** 快递接口列表(含失效记录) */
|
||||
export function getExternalPrintExpressInterfaces(accountId: number, params?: object) {
|
||||
return get<{ list: ExternalPrintExpressInterfaceItem[]; total: number; page: number; pageSize: number }>(
|
||||
`/external-print-accounts/${accountId}/express-interfaces`,
|
||||
params,
|
||||
)
|
||||
}
|
||||
|
||||
/** 从平台全量拉取快递接口(平台已删除的保留并标记失效) */
|
||||
export function syncExternalPrintExpressInterfaces(accountId: number) {
|
||||
return post<ExternalPrintExpressInterfaceSyncResult>(
|
||||
`/external-print-accounts/${accountId}/sync-express-interfaces`,
|
||||
undefined,
|
||||
{ timeout: 180000 },
|
||||
)
|
||||
}
|
||||
|
||||
export interface SaveExternalPrintExpressInterfaceItem {
|
||||
id: number
|
||||
custom_code?: string | null
|
||||
remark?: string | null
|
||||
}
|
||||
|
||||
/** 保存自定义编码与默认类型 */
|
||||
export function saveExternalPrintExpressInterfaces(
|
||||
accountId: number,
|
||||
items: SaveExternalPrintExpressInterfaceItem[],
|
||||
) {
|
||||
return put<{ updated: number }>(`/external-print-accounts/${accountId}/express-interfaces`, { items })
|
||||
}
|
||||
|
||||
/** 查看单个快递接口的平台明细(实时请求平台) */
|
||||
export function getExternalPrintExpressInterfaceDetail(accountId: number, interfaceId: number) {
|
||||
return get<ExternalPrintExpressInterfaceDetail>(
|
||||
`/external-print-accounts/${accountId}/express-interfaces/${interfaceId}/detail`,
|
||||
)
|
||||
}
|
||||
@ -61,6 +61,7 @@ const defaultMenus: MenuItem[] = [
|
||||
{ id: 21, parent_id: 2, name: '我的', type: 2, path: '/system/user', icon: 'User', permission: null, component: 'views/User/Profile.vue', sort: 90, status: 1 },
|
||||
{ id: 22, parent_id: 2, name: '主体管理', type: 2, path: '/system/principal', icon: 'OfficeBuilding', permission: 'principal:list', component: 'views/Principal/Index.vue', sort: 80, status: 1 },
|
||||
{ id: 23, parent_id: 2, name: '账号', type: 2, path: '/system/principal-user', icon: 'Connection', permission: 'principalUser:list', component: 'views/PrincipalUser/Index.vue', sort: 70, status: 1 },
|
||||
{ id: 24, parent_id: 2, name: '自定义快递编码', type: 2, path: '/system/custom-express', icon: 'Van', permission: null, component: 'views/CustomExpress/Index.vue', sort: 60, status: 1 },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
333
frontend/src/views/CustomExpress/Index.vue
Normal file
333
frontend/src/views/CustomExpress/Index.vue
Normal file
@ -0,0 +1,333 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
|
||||
import DataTable from '@/components/DataTable.vue'
|
||||
import ListPager from '@/components/ListPager.vue'
|
||||
import { DEFAULT_PAGE_SIZE, useListPage } from '@/composables/useListPage'
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
import { getExpressCompanyOptions, type ExpressCompanyOption } from '@/api/expressCompany'
|
||||
import {
|
||||
createCustomExpressCode,
|
||||
deleteCustomExpressCode,
|
||||
getCustomExpressCodes,
|
||||
updateCustomExpressCode,
|
||||
type CustomExpressCodeItem,
|
||||
} from '@/api/customExpressCode'
|
||||
|
||||
/**
|
||||
* 系统管理 → 自定义快递编码
|
||||
*
|
||||
* 自定义编码 / 名称会直接写入订单的 logistics_code / logistics_name,
|
||||
* 推送奇门(WMS)时原样下发;express_code 记录对应的系统快递编码,便于对账。
|
||||
*/
|
||||
const query = reactive({
|
||||
page: 1,
|
||||
pageSize: DEFAULT_PAGE_SIZE,
|
||||
keyword: '',
|
||||
express_code: '',
|
||||
status: '' as string | number,
|
||||
})
|
||||
|
||||
const { loading, list, total, elapsed, fetchList, search, handlePageChange, handleSizeChange } = useListPage({
|
||||
query,
|
||||
fetcher: () => {
|
||||
const params: Record<string, unknown> = { ...query }
|
||||
if (!params.keyword) delete params.keyword
|
||||
if (!params.express_code) delete params.express_code
|
||||
if (params.status === '') delete params.status
|
||||
return getCustomExpressCodes(params)
|
||||
},
|
||||
})
|
||||
|
||||
function reset() {
|
||||
query.keyword = ''
|
||||
query.express_code = ''
|
||||
query.status = ''
|
||||
search()
|
||||
}
|
||||
|
||||
/* -------------------- 系统快递(对应编码下拉) -------------------- */
|
||||
const expressCompanies = ref<ExpressCompanyOption[]>([])
|
||||
|
||||
async function fetchExpressCompanies() {
|
||||
try {
|
||||
expressCompanies.value = await getExpressCompanyOptions()
|
||||
} catch {
|
||||
expressCompanies.value = []
|
||||
}
|
||||
}
|
||||
|
||||
function systemExpressLabel(code: string, fallbackName?: string | null) {
|
||||
const hit = expressCompanies.value.find(item => item.code === code)
|
||||
return `${hit?.name || fallbackName || code}(${code})`
|
||||
}
|
||||
|
||||
function systemExpressName(row: CustomExpressCodeItem) {
|
||||
return row.expressCompany?.name || expressCompanies.value.find(item => item.code === row.express_code)?.name || ''
|
||||
}
|
||||
|
||||
/* -------------------- 新增 / 编辑 -------------------- */
|
||||
const drawerVisible = ref(false)
|
||||
const submitting = ref(false)
|
||||
const formRef = ref<FormInstance>()
|
||||
const editId = ref<number | null>(null)
|
||||
|
||||
const form = reactive({
|
||||
code: '',
|
||||
name: '',
|
||||
express_code: '',
|
||||
sort: 0,
|
||||
status: 1,
|
||||
remark: '',
|
||||
})
|
||||
|
||||
const rules: FormRules = {
|
||||
code: [{ required: true, message: '请输入自定义快递编码', trigger: 'blur' }],
|
||||
name: [{ required: true, message: '请输入自定义快递名称', trigger: 'blur' }],
|
||||
express_code: [{ required: true, message: '请选择对应的系统快递', trigger: 'change' }],
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
editId.value = null
|
||||
Object.assign(form, {
|
||||
code: '',
|
||||
name: '',
|
||||
express_code: expressCompanies.value[0]?.code || '',
|
||||
sort: 0,
|
||||
status: 1,
|
||||
remark: '',
|
||||
})
|
||||
drawerVisible.value = true
|
||||
}
|
||||
|
||||
function openEdit(row: CustomExpressCodeItem) {
|
||||
editId.value = row.id
|
||||
Object.assign(form, {
|
||||
code: row.code,
|
||||
name: row.name,
|
||||
express_code: row.express_code,
|
||||
sort: Number(row.sort) || 0,
|
||||
status: Number(row.status) === 0 ? 0 : 1,
|
||||
remark: row.remark || '',
|
||||
})
|
||||
drawerVisible.value = true
|
||||
}
|
||||
|
||||
async function submitForm() {
|
||||
if (!formRef.value) return
|
||||
await formRef.value.validate(async valid => {
|
||||
if (!valid) return
|
||||
submitting.value = true
|
||||
try {
|
||||
const payload = {
|
||||
code: form.code.trim(),
|
||||
name: form.name.trim(),
|
||||
express_code: form.express_code,
|
||||
sort: Number(form.sort) || 0,
|
||||
status: form.status,
|
||||
remark: form.remark.trim(),
|
||||
}
|
||||
if (editId.value == null) {
|
||||
await createCustomExpressCode(payload)
|
||||
ElMessage.success('新增成功')
|
||||
} else {
|
||||
await updateCustomExpressCode(editId.value, payload)
|
||||
ElMessage.success('保存成功')
|
||||
}
|
||||
drawerVisible.value = false
|
||||
await fetchList()
|
||||
} catch {
|
||||
// 拦截器已提示
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async function handleDelete(row: CustomExpressCodeItem) {
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`确认删除自定义快递「${row.name}(${row.code})」?历史订单已保存编码与名称快照,不受影响。`,
|
||||
'删除确认',
|
||||
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' },
|
||||
)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await deleteCustomExpressCode(row.id)
|
||||
ElMessage.success('已删除')
|
||||
await fetchList()
|
||||
} catch {
|
||||
// 拦截器已提示
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await fetchExpressCompanies()
|
||||
await fetchList()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<el-card class="custom-express-card">
|
||||
<template #header>
|
||||
<div class="page-header">自定义快递编码</div>
|
||||
</template>
|
||||
|
||||
<el-alert
|
||||
type="info"
|
||||
show-icon
|
||||
:closable="false"
|
||||
class="tip"
|
||||
title="自定义编码会出现在订单的「修改快递」列表;订单保存自定义编码/名称,推送奇门时原样下发。自定义编码不能与系统快递编码重复。"
|
||||
/>
|
||||
|
||||
<el-form :inline="true" class="search-bar" @submit.prevent>
|
||||
<el-form-item label="关键词">
|
||||
<el-input
|
||||
v-model="query.keyword"
|
||||
placeholder="匹配自定义编码 / 名称"
|
||||
clearable
|
||||
style="width: 200px"
|
||||
@keyup.enter="search"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="系统快递">
|
||||
<el-select v-model="query.express_code" placeholder="全部" clearable filterable style="width: 200px" @change="search">
|
||||
<el-option
|
||||
v-for="company in expressCompanies"
|
||||
:key="company.code"
|
||||
:label="`${company.name}(${company.code})`"
|
||||
:value="company.code"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="状态">
|
||||
<el-select v-model="query.status" placeholder="全部" clearable style="width: 110px" @change="search">
|
||||
<el-option label="启用" :value="1" />
|
||||
<el-option label="禁用" :value="0" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" @click="search">查询</el-button>
|
||||
<el-button @click="reset">重置</el-button>
|
||||
</el-form-item>
|
||||
<el-form-item class="add-btn">
|
||||
<el-button type="success" @click="openCreate">新增自定义快递</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
|
||||
<div class="table-wrap">
|
||||
<DataTable :loading="loading" :data="list" height="100%">
|
||||
<el-table-column prop="code" label="自定义编码" width="160" show-overflow-tooltip />
|
||||
<el-table-column prop="name" label="自定义名称" min-width="180" show-overflow-tooltip />
|
||||
<el-table-column label="对应系统快递" min-width="180" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
{{ systemExpressLabel(row.express_code, systemExpressName(row)) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="sort" label="排序" width="80" align="center" />
|
||||
<el-table-column label="状态" width="90">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="Number(row.status) === 1 ? 'success' : 'info'">
|
||||
{{ Number(row.status) === 1 ? '启用' : '禁用' }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="remark" label="备注" min-width="140" show-overflow-tooltip />
|
||||
<el-table-column label="更新时间" width="160">
|
||||
<template #default="{ row }">{{ formatDateTime(row.updated_at) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="130" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button link type="primary" @click="openEdit(row)">编辑</el-button>
|
||||
<el-button link type="danger" @click="handleDelete(row)">删除</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</DataTable>
|
||||
</div>
|
||||
|
||||
<ListPager
|
||||
:total="total"
|
||||
:elapsed="elapsed"
|
||||
:page="query.page"
|
||||
:page-size="query.pageSize"
|
||||
@page-change="handlePageChange"
|
||||
@size-change="handleSizeChange"
|
||||
/>
|
||||
|
||||
<el-drawer
|
||||
v-model="drawerVisible"
|
||||
:title="editId == null ? '新增自定义快递' : '编辑自定义快递'"
|
||||
size="480px"
|
||||
>
|
||||
<el-form ref="formRef" :model="form" :rules="rules" label-width="130px">
|
||||
<el-form-item label="自定义编码" prop="code">
|
||||
<el-input v-model="form.code" maxlength="50" placeholder="如 SF.KY(订单物流编码)" />
|
||||
</el-form-item>
|
||||
<el-form-item label="自定义名称" prop="name">
|
||||
<el-input v-model="form.name" maxlength="100" placeholder="如 顺丰快运(订单物流名称)" />
|
||||
</el-form-item>
|
||||
<el-form-item label="对应系统快递" prop="express_code">
|
||||
<el-select v-model="form.express_code" filterable placeholder="请选择" style="width: 100%">
|
||||
<el-option
|
||||
v-for="company in expressCompanies"
|
||||
:key="company.code"
|
||||
:label="`${company.name}(${company.code})`"
|
||||
:value="company.code"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="排序">
|
||||
<el-input-number v-model="form.sort" :min="0" :max="99999" controls-position="right" />
|
||||
</el-form-item>
|
||||
<el-form-item label="状态">
|
||||
<el-switch v-model="form.status" :active-value="1" :inactive-value="0" active-text="启用" inactive-text="禁用" />
|
||||
</el-form-item>
|
||||
<el-form-item label="备注">
|
||||
<el-input v-model="form.remark" type="textarea" :rows="2" maxlength="255" show-word-limit />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="drawerVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="submitting" @click="submitForm">确定</el-button>
|
||||
</template>
|
||||
</el-drawer>
|
||||
</el-card>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.custom-express-card {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.custom-express-card :deep(.el-card__body) {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
padding: 10px 12px;
|
||||
}
|
||||
.page-header {
|
||||
font-weight: 600;
|
||||
}
|
||||
.tip {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.search-bar {
|
||||
flex: 0 0 auto;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.add-btn {
|
||||
margin-left: auto;
|
||||
}
|
||||
.table-wrap {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
</style>
|
||||
@ -0,0 +1,596 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import DataTable from '@/components/DataTable.vue'
|
||||
import ListPager from '@/components/ListPager.vue'
|
||||
import { DEFAULT_PAGE_SIZE } from '@/composables/useListPage'
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
import { getExpressCodeOptions, type ExpressCodeOption } from '@/api/customExpressCode'
|
||||
import {
|
||||
getExternalPrintExpressInterfaces,
|
||||
getExternalPrintExpressInterfaceDetail,
|
||||
saveExternalPrintExpressInterfaces,
|
||||
syncExternalPrintExpressInterfaces,
|
||||
type ExternalPrintExpressInterfaceItem,
|
||||
type ExternalPrintExpressInterfaceSyncResult,
|
||||
} from '@/api/externalPrintExpressInterface'
|
||||
import type { ExternalPrintAccountItem } from '@/api/externalPrintAccount'
|
||||
|
||||
/**
|
||||
* 外部打单平台「快递接口」弹窗
|
||||
*
|
||||
* 打开即从平台全量拉取账号下所有外部店铺的快递接口(面单模板),落库后展示;
|
||||
* 平台侧已删除的接口保留并标记「已失效」,自定义编码与默认设置不会丢。
|
||||
* 自定义编码映射到 OMS 快递公司字典,默认类型同一模板只能选一个(平台默认 / 快递默认)。
|
||||
*/
|
||||
const props = defineProps<{
|
||||
modelValue: boolean
|
||||
account: ExternalPrintAccountItem | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [ value: boolean ]
|
||||
}>()
|
||||
|
||||
const visible = computed({
|
||||
get: () => props.modelValue,
|
||||
set: value => emit('update:modelValue', value),
|
||||
})
|
||||
|
||||
const dialogTitle = computed(() => {
|
||||
const account = props.account
|
||||
if (!account) return '快递接口'
|
||||
return `快递接口 · ${account.platform?.name || '-'} / ${account.account}`
|
||||
})
|
||||
|
||||
const query = reactive({
|
||||
page: 1,
|
||||
pageSize: DEFAULT_PAGE_SIZE,
|
||||
status: '' as '' | 0 | 1,
|
||||
platform_code: '',
|
||||
express_company_code: '',
|
||||
keyword: '',
|
||||
})
|
||||
|
||||
const loading = ref(false)
|
||||
const syncing = ref(false)
|
||||
const saving = ref(false)
|
||||
const list = ref<ExternalPrintExpressInterfaceItem[]>([])
|
||||
const total = ref(0)
|
||||
const elapsed = ref(0)
|
||||
const lastSync = ref<ExternalPrintExpressInterfaceSyncResult | null>(null)
|
||||
|
||||
/** 已落库数据里最近一次同步时间(打开弹窗不拉取平台,用它提示数据新鲜度) */
|
||||
const lastSyncedAt = computed(() => {
|
||||
let latest: string | null = null
|
||||
for (const row of list.value) {
|
||||
const value = row.synced_at
|
||||
if (!value) continue
|
||||
if (!latest || new Date(value).getTime() > new Date(latest).getTime()) latest = value
|
||||
}
|
||||
return latest
|
||||
})
|
||||
|
||||
/** 平台 / 平台快递筛选项:跨页累积,避免翻页后选项丢失 */
|
||||
const platformOptions = ref<Array<{ code: string; name: string }>>([])
|
||||
const expressOptions = ref<Array<{ code: string; name: string }>>([])
|
||||
|
||||
/** 快递下拉:系统快递 + 自定义快递编码 */
|
||||
const expressCompanies = ref<ExpressCodeOption[]>([])
|
||||
|
||||
/** 单行下拉选项:把当前值补进去,避免历史值不在列表中显示为空 */
|
||||
function customCodeOptions(row: ExternalPrintExpressInterfaceItem) {
|
||||
const code = draftOf(row).custom_code
|
||||
if (code && !expressCompanies.value.some(item => item.code === code)) {
|
||||
return [
|
||||
{ code, name: code, source: 'system' as const, express_code: code, express_name: '' },
|
||||
...expressCompanies.value,
|
||||
]
|
||||
}
|
||||
return expressCompanies.value
|
||||
}
|
||||
|
||||
/**
|
||||
* 同账号同平台内,其它有效模板已绑定的编码。
|
||||
* 回读按「账号 + 平台 + 编码」唯一定位,同平台重复绑定无法确定用哪个接口;
|
||||
* 不同平台互不影响,可以绑定相同编码。
|
||||
*/
|
||||
function boundCodesOnPlatform(row: ExternalPrintExpressInterfaceItem) {
|
||||
const used = new Set<string>()
|
||||
for (const item of list.value) {
|
||||
if (Number(item.id) === Number(row.id)) continue
|
||||
if (item.platform_code !== row.platform_code) continue
|
||||
if (Number(item.status) !== 1) continue
|
||||
if (item.custom_code) used.add(item.custom_code)
|
||||
}
|
||||
return used
|
||||
}
|
||||
|
||||
/** 下拉可选项:排除同平台已绑定的编码(保留当前值,便于查看与改绑) */
|
||||
function selectableExpressOptions(row: ExternalPrintExpressInterfaceItem) {
|
||||
const used = boundCodesOnPlatform(row)
|
||||
const current = draftOf(row).custom_code
|
||||
return customCodeOptions(row).filter(option => option.code === current || !used.has(option.code))
|
||||
}
|
||||
|
||||
/** 编辑草稿:只有改过的行才提交 */
|
||||
const drafts = reactive<Record<number, { custom_code: string }>>({})
|
||||
|
||||
function draftOf(row: ExternalPrintExpressInterfaceItem) {
|
||||
if (!drafts[row.id]) {
|
||||
drafts[row.id] = { custom_code: row.custom_code || '' }
|
||||
}
|
||||
return drafts[row.id]
|
||||
}
|
||||
|
||||
function isDirty(row: ExternalPrintExpressInterfaceItem) {
|
||||
const draft = drafts[row.id]
|
||||
if (!draft) return false
|
||||
return draft.custom_code !== (row.custom_code || '')
|
||||
}
|
||||
|
||||
const dirtyItems = computed(() => list.value.filter(row => isDirty(row)))
|
||||
|
||||
function resetDrafts() {
|
||||
for (const key of Object.keys(drafts)) delete drafts[Number(key)]
|
||||
for (const row of list.value) {
|
||||
drafts[row.id] = { custom_code: row.custom_code || '' }
|
||||
}
|
||||
}
|
||||
|
||||
function rememberOptions(rows: ExternalPrintExpressInterfaceItem[]) {
|
||||
for (const row of rows) {
|
||||
if (row.platform_code && !platformOptions.value.some(item => item.code === row.platform_code)) {
|
||||
platformOptions.value.push({ code: row.platform_code, name: row.platform_name || row.platform_code })
|
||||
}
|
||||
if (
|
||||
row.express_company_code &&
|
||||
!expressOptions.value.some(item => item.code === row.express_company_code)
|
||||
) {
|
||||
expressOptions.value.push({
|
||||
code: row.express_company_code,
|
||||
name: row.express_company_name || row.express_company_code,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchList() {
|
||||
const account = props.account
|
||||
if (!account) return
|
||||
const started = Date.now()
|
||||
loading.value = true
|
||||
try {
|
||||
const params: Record<string, unknown> = {
|
||||
page: query.page,
|
||||
pageSize: query.pageSize,
|
||||
}
|
||||
if (query.status !== '') params.status = query.status
|
||||
if (query.platform_code) params.platform_code = query.platform_code
|
||||
if (query.express_company_code) params.express_company_code = query.express_company_code
|
||||
if (query.keyword.trim()) params.keyword = query.keyword.trim()
|
||||
|
||||
const result = await getExternalPrintExpressInterfaces(account.id, params)
|
||||
list.value = result.list || []
|
||||
total.value = result.total || 0
|
||||
rememberOptions(list.value)
|
||||
resetDrafts()
|
||||
} catch {
|
||||
list.value = []
|
||||
total.value = 0
|
||||
} finally {
|
||||
loading.value = false
|
||||
elapsed.value = Date.now() - started
|
||||
}
|
||||
}
|
||||
|
||||
function search() {
|
||||
query.page = 1
|
||||
fetchList()
|
||||
}
|
||||
|
||||
function resetQuery() {
|
||||
query.status = ''
|
||||
query.platform_code = ''
|
||||
query.express_company_code = ''
|
||||
query.keyword = ''
|
||||
search()
|
||||
}
|
||||
|
||||
async function runSync(manual = false) {
|
||||
const account = props.account
|
||||
if (!account) return
|
||||
if (manual && dirtyItems.value.length) {
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`当前有 ${dirtyItems.value.length} 条未保存的设置,重新拉取会丢弃这些修改,是否继续?`,
|
||||
'重新拉取',
|
||||
{ type: 'warning', confirmButtonText: '继续', cancelButtonText: '取消' },
|
||||
)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
syncing.value = true
|
||||
try {
|
||||
const result = await syncExternalPrintExpressInterfaces(account.id)
|
||||
lastSync.value = result
|
||||
const summary = `拉取完成:有效 ${result.total} 条,新增 ${result.created},更新 ${result.updated},失效 ${result.invalidated}`
|
||||
if (result.errors.length) {
|
||||
ElMessage.warning(`${summary};部分店铺失败:${result.errors[0]}`)
|
||||
} else {
|
||||
ElMessage.success(summary)
|
||||
}
|
||||
query.page = 1
|
||||
await fetchList()
|
||||
} catch {
|
||||
// 拦截器已提示
|
||||
} finally {
|
||||
syncing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function save() {
|
||||
const account = props.account
|
||||
if (!account) return
|
||||
const items = dirtyItems.value.map(row => ({
|
||||
id: row.id,
|
||||
custom_code: draftOf(row).custom_code || null,
|
||||
}))
|
||||
if (!items.length) return
|
||||
saving.value = true
|
||||
try {
|
||||
const result = await saveExternalPrintExpressInterfaces(account.id, items)
|
||||
ElMessage.success(`已保存 ${result.updated} 条设置`)
|
||||
await fetchList()
|
||||
} catch {
|
||||
// 拦截器已提示
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------- 明细(单独请求平台接口) -------------------- */
|
||||
const detailVisible = ref(false)
|
||||
const detailLoading = ref(false)
|
||||
const detailRow = ref<ExternalPrintExpressInterfaceItem | null>(null)
|
||||
const detailData = ref<Record<string, unknown> | null>(null)
|
||||
|
||||
const DETAIL_FIELDS: Array<[ string, string ]> = [
|
||||
[ 'ExpressCompanyName', '快递公司' ],
|
||||
[ 'ShopName', '店铺' ],
|
||||
[ 'BranchName', '网点名称' ],
|
||||
[ 'BranchCode', '网点编码' ],
|
||||
[ 'BranchAddress', '网点地址' ],
|
||||
[ 'CustomerName', '客户名称' ],
|
||||
[ 'CustomerCode', '客户编码' ],
|
||||
[ 'AuthAccountName', '授权账号' ],
|
||||
[ 'AuthSourceType', '授权来源' ],
|
||||
[ 'CaiNiaoAuthInfoId', '菜鸟授权ID' ],
|
||||
[ 'SiteAccountId', '站点账号ID' ],
|
||||
[ 'IsEbillWaybill', '电子面单' ],
|
||||
[ 'IsDefault', '平台默认' ],
|
||||
[ 'IsShow', '平台显示' ],
|
||||
]
|
||||
|
||||
const detailFields = computed(() => {
|
||||
const data = detailData.value || {}
|
||||
return DETAIL_FIELDS
|
||||
.filter(([ key ]) => data[key] !== undefined && data[key] !== null && data[key] !== '')
|
||||
.map(([ key, label ]) => ({ label, value: String(data[key]) }))
|
||||
})
|
||||
|
||||
const detailRaw = computed(() => (detailData.value ? JSON.stringify(detailData.value, null, 2) : ''))
|
||||
|
||||
async function openDetail(row: ExternalPrintExpressInterfaceItem) {
|
||||
const account = props.account
|
||||
if (!account) return
|
||||
detailRow.value = row
|
||||
detailData.value = null
|
||||
detailVisible.value = true
|
||||
detailLoading.value = true
|
||||
try {
|
||||
const result = await getExternalPrintExpressInterfaceDetail(account.id, row.id)
|
||||
detailData.value = result.detail
|
||||
} catch {
|
||||
detailData.value = null
|
||||
} finally {
|
||||
detailLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handlePageChange(page: number) {
|
||||
query.page = page
|
||||
fetchList()
|
||||
}
|
||||
|
||||
function handleSizeChange(size: number) {
|
||||
query.pageSize = size
|
||||
query.page = 1
|
||||
fetchList()
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
async open => {
|
||||
if (!open) return
|
||||
query.page = 1
|
||||
query.status = ''
|
||||
query.platform_code = ''
|
||||
query.express_company_code = ''
|
||||
query.keyword = ''
|
||||
lastSync.value = null
|
||||
platformOptions.value = []
|
||||
expressOptions.value = []
|
||||
detailVisible.value = false
|
||||
|
||||
try {
|
||||
expressCompanies.value = await getExpressCodeOptions()
|
||||
} catch {
|
||||
expressCompanies.value = []
|
||||
}
|
||||
// 打开只看已落库数据;需要刷新平台数据时由用户点击「从平台同步数据」
|
||||
await fetchList()
|
||||
},
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<el-dialog v-model="visible" :title="dialogTitle" width="1180px" top="5vh" destroy-on-close>
|
||||
<el-alert
|
||||
type="info"
|
||||
show-icon
|
||||
:closable="false"
|
||||
class="tip"
|
||||
title="列表展示已落库的数据,点击「从平台同步数据」才会重新拉取。平台侧已删除的接口会保留并标记「已失效」;同一账号、同一平台内一个快递编码只能绑定一个模板,不同平台互不影响(可绑定相同编码)。回读时按账号 + 平台 + 编码定位。"
|
||||
/>
|
||||
|
||||
<div class="toolbar">
|
||||
<el-form :inline="true" size="small" class="filters" @submit.prevent>
|
||||
<el-form-item label="状态">
|
||||
<el-select v-model="query.status" placeholder="全部" clearable style="width: 110px" @change="search">
|
||||
<el-option label="有效" :value="1" />
|
||||
<el-option label="已失效" :value="0" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="平台">
|
||||
<el-select v-model="query.platform_code" placeholder="全部" clearable style="width: 130px" @change="search">
|
||||
<el-option
|
||||
v-for="item in platformOptions"
|
||||
:key="item.code"
|
||||
:label="item.name"
|
||||
:value="item.code"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="快递">
|
||||
<el-select v-model="query.express_company_code" placeholder="全部" clearable filterable style="width: 140px" @change="search">
|
||||
<el-option
|
||||
v-for="item in expressOptions"
|
||||
:key="item.code"
|
||||
:label="`${item.name}(${item.code})`"
|
||||
:value="item.code"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="关键词">
|
||||
<el-input
|
||||
v-model="query.keyword"
|
||||
placeholder="接口名称 / 快递 / 店铺 / 自定义编码"
|
||||
clearable
|
||||
style="width: 230px"
|
||||
@keyup.enter="search"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" @click="search">查询</el-button>
|
||||
<el-button @click="resetQuery">重置</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<div class="toolbar-right">
|
||||
<span class="sync-summary">
|
||||
{{ lastSync ? `本次同步:有效 ${lastSync.total} / 失效 ${lastSync.invalidated}` : `上次同步:${formatDateTime(lastSyncedAt, '尚未同步')}` }}
|
||||
</span>
|
||||
<el-button size="small" :loading="syncing" @click="runSync(true)">从平台同步数据</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DataTable :loading="loading || syncing" :data="list" height="430">
|
||||
<el-table-column label="平台" width="100">
|
||||
<template #default="{ row }">
|
||||
<el-tag size="small" effect="plain">{{ row.platform_name || row.platform_code || '-' }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="店铺" width="130" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ row.shop_name || '-' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="快递接口" min-width="230" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<div class="if-name" :class="{ 'is-invalid': Number(row.status) === 0 }">
|
||||
{{ row.template_name || '-' }}
|
||||
<el-tag v-if="isDirty(row)" size="small" type="warning" effect="plain" class="dirty-tag">未保存</el-tag>
|
||||
</div>
|
||||
<div class="if-sub">模板ID {{ row.template_id }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="平台快递" width="140" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<span>{{ row.express_company_name || '-' }}</span>
|
||||
<span v-if="row.express_company_code" class="if-sub">({{ row.express_company_code }})</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="自定义编码" width="200">
|
||||
<template #default="{ row }">
|
||||
<el-select
|
||||
v-model="draftOf(row).custom_code"
|
||||
size="small"
|
||||
filterable
|
||||
clearable
|
||||
placeholder="未绑定"
|
||||
style="width: 100%"
|
||||
>
|
||||
<el-option-group label="自定义快递编码">
|
||||
<el-option
|
||||
v-for="item in selectableExpressOptions(row).filter(option => option.source === 'custom')"
|
||||
:key="`custom-${item.code}`"
|
||||
:label="`${item.name}(${item.code})`"
|
||||
:value="item.code"
|
||||
/>
|
||||
</el-option-group>
|
||||
<el-option-group label="系统快递">
|
||||
<el-option
|
||||
v-for="item in selectableExpressOptions(row).filter(option => option.source === 'system')"
|
||||
:key="`system-${item.code}`"
|
||||
:label="`${item.name}(${item.code})`"
|
||||
:value="item.code"
|
||||
/>
|
||||
</el-option-group>
|
||||
</el-select>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" width="90">
|
||||
<template #default="{ row }">
|
||||
<el-tag size="small" :type="Number(row.status) === 1 ? 'success' : 'info'" effect="plain">
|
||||
{{ Number(row.status) === 1 ? '有效' : '已失效' }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="平台更新时间" width="150">
|
||||
<template #default="{ row }">{{ formatDateTime(row.platform_updated_at) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="80" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button
|
||||
link
|
||||
type="primary"
|
||||
size="small"
|
||||
:disabled="Number(row.status) === 0"
|
||||
@click="openDetail(row)"
|
||||
>
|
||||
明细
|
||||
</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</DataTable>
|
||||
|
||||
<ListPager
|
||||
:total="total"
|
||||
:elapsed="elapsed"
|
||||
:page="query.page"
|
||||
:page-size="query.pageSize"
|
||||
@page-change="handlePageChange"
|
||||
@size-change="handleSizeChange"
|
||||
/>
|
||||
|
||||
<template #footer>
|
||||
<div class="footer-bar">
|
||||
<span class="footer-hint">失效记录仅保留展示与绑定关系,不参与回读定位。</span>
|
||||
<div>
|
||||
<el-button @click="visible = false">关闭</el-button>
|
||||
<el-button type="primary" :disabled="!dirtyItems.length" :loading="saving" @click="save">
|
||||
保存设置{{ dirtyItems.length ? `(${dirtyItems.length})` : '' }}
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 明细:单独请求平台接口 -->
|
||||
<el-drawer v-model="detailVisible" title="快递接口明细" size="560px">
|
||||
<template v-if="detailRow">
|
||||
<el-descriptions v-loading="detailLoading" :column="1" border size="small">
|
||||
<el-descriptions-item label="平台">{{ detailRow.platform_name || detailRow.platform_code || '-' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="店铺">{{ detailRow.shop_name || '-' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="接口">{{ detailRow.template_name || '-' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="模板ID">{{ detailRow.template_id }}</el-descriptions-item>
|
||||
<el-descriptions-item label="平台快递">
|
||||
{{ detailRow.express_company_name || '-' }}
|
||||
<span v-if="detailRow.express_company_code">({{ detailRow.express_company_code }})</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="自定义编码">{{ detailRow.custom_code || '-' }}</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
|
||||
<el-divider content-position="left">平台明细</el-divider>
|
||||
<el-descriptions v-if="detailFields.length" :column="1" border size="small">
|
||||
<el-descriptions-item v-for="field in detailFields" :key="field.label" :label="field.label">
|
||||
{{ field.value }}
|
||||
</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
<el-empty v-else :image-size="60" description="平台未返回可用字段,可查看下方原始返回" />
|
||||
|
||||
<el-collapse class="raw-collapse">
|
||||
<el-collapse-item title="平台原始返回" name="raw">
|
||||
<pre class="raw-json">{{ detailRaw || '无' }}</pre>
|
||||
</el-collapse-item>
|
||||
</el-collapse>
|
||||
</template>
|
||||
</el-drawer>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.tip {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
.filters {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.filters :deep(.el-form-item) {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.toolbar-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding-top: 2px;
|
||||
}
|
||||
.sync-summary {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.if-name {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.if-name.is-invalid {
|
||||
color: var(--el-text-color-placeholder);
|
||||
text-decoration: line-through;
|
||||
}
|
||||
.if-sub {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
.dirty-tag {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
.footer-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
.footer-hint {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
.raw-collapse {
|
||||
margin-top: 8px;
|
||||
}
|
||||
.raw-json {
|
||||
margin: 0;
|
||||
max-height: 320px;
|
||||
overflow: auto;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
}
|
||||
</style>
|
||||
@ -20,6 +20,7 @@ import {
|
||||
} from '@/api/externalPrintAccount'
|
||||
import DataTable from '@/components/DataTable.vue'
|
||||
import ListPager from '@/components/ListPager.vue'
|
||||
import ExpressInterfaceDialog from './ExpressInterfaceDialog.vue'
|
||||
import { DEFAULT_PAGE_SIZE, useListPage } from '@/composables/useListPage'
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
|
||||
@ -208,6 +209,15 @@ async function handleLogin(row: ExternalPrintAccountItem) {
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------- 快递接口(面单模板) -------------------- */
|
||||
const expressVisible = ref(false)
|
||||
const expressAccount = ref<ExternalPrintAccountItem | null>(null)
|
||||
|
||||
function openExpressInterfaces(row: ExternalPrintAccountItem) {
|
||||
expressAccount.value = row
|
||||
expressVisible.value = true
|
||||
}
|
||||
|
||||
/* -------------------- 平台店铺(商家) -------------------- */
|
||||
const shopsDialogVisible = ref(false)
|
||||
const shopsAccount = ref<ExternalPrintAccountItem | null>(null)
|
||||
@ -370,9 +380,10 @@ onBeforeUnmount(() => {
|
||||
<el-table-column label="创建时间" width="180">
|
||||
<template #default="{ row }">{{ formatDateTime(row.created_at) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="340" fixed="right">
|
||||
<el-table-column label="操作" width="420" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button link type="primary" @click="openMerchants(row)">查看店铺</el-button>
|
||||
<el-button link type="primary" @click="openExpressInterfaces(row)">快递接口</el-button>
|
||||
<el-button
|
||||
link
|
||||
type="primary"
|
||||
@ -490,6 +501,9 @@ onBeforeUnmount(() => {
|
||||
</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 快递接口:打开读取已落库数据,可手动同步并绑定快递编码 -->
|
||||
<ExpressInterfaceDialog v-model="expressVisible" :account="expressAccount" />
|
||||
</el-card>
|
||||
</template>
|
||||
|
||||
|
||||
@ -3,7 +3,7 @@ import { computed, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
|
||||
import DataTable from '@/components/DataTable.vue'
|
||||
import ProductSelect from '@/components/ProductSelect.vue'
|
||||
import { getExpressCompanyOptions, type ExpressCompanyOption } from '@/api/expressCompany'
|
||||
import { getExpressCodeOptions, type ExpressCodeOption } from '@/api/customExpressCode'
|
||||
import type { ProductSearchItem } from '@/api/product'
|
||||
import type { DataItem } from 'element-china-area-data'
|
||||
import {
|
||||
@ -318,20 +318,26 @@ const areaPathMatched = computed(() => {
|
||||
return true
|
||||
})
|
||||
|
||||
/* -------------------- 物流公司(快递公司字典) -------------------- */
|
||||
const expressCompanies = ref<ExpressCompanyOption[]>([])
|
||||
/* -------------------- 物流公司(系统快递 + 自定义快递编码) -------------------- */
|
||||
const expressCompanies = ref<ExpressCodeOption[]>([])
|
||||
|
||||
/** 下拉选项:字典项 + 当前值(WMS 可能回传字典外的自定义编码,避免显示为空) */
|
||||
const expressOptions = computed<ExpressCompanyOption[]>(() => {
|
||||
/** 下拉选项:系统 + 自定义 + 当前值(WMS 可能回传字典外的编码,避免显示为空) */
|
||||
const expressOptions = computed<ExpressCodeOption[]>(() => {
|
||||
const list = [ ...expressCompanies.value ]
|
||||
const code = String(form.logistics_code || '').trim()
|
||||
if (code && !list.some(company => company.code === code)) {
|
||||
list.unshift({ id: 0, code, name: String(form.logistics_name || code) })
|
||||
list.unshift({
|
||||
code,
|
||||
name: String(form.logistics_name || code),
|
||||
source: 'system',
|
||||
express_code: code,
|
||||
express_name: String(form.logistics_name || code),
|
||||
})
|
||||
}
|
||||
return list
|
||||
})
|
||||
|
||||
/** 选中物流公司后自动带出名称(与老发货单口径一致) */
|
||||
/** 选中快递后自动带出名称(自定义编码带出的是自定义名称) */
|
||||
function handleExpressChange(code: string | null) {
|
||||
const company = expressCompanies.value.find(item => item.code === code)
|
||||
form.logistics_name = company ? company.name : ''
|
||||
@ -342,7 +348,7 @@ watch(
|
||||
async open => {
|
||||
if (!open) return
|
||||
try {
|
||||
expressCompanies.value = await getExpressCompanyOptions()
|
||||
expressCompanies.value = await getExpressCodeOptions()
|
||||
} catch {
|
||||
// 拦截器已提示
|
||||
}
|
||||
@ -738,18 +744,28 @@ async function submit() {
|
||||
<el-form-item label="物流公司" prop="logistics_code">
|
||||
<el-select
|
||||
v-model="form.logistics_code"
|
||||
placeholder="请选择快递公司"
|
||||
placeholder="请选择快递"
|
||||
clearable
|
||||
filterable
|
||||
style="width: 100%"
|
||||
@change="handleExpressChange"
|
||||
>
|
||||
<el-option
|
||||
v-for="company in expressOptions"
|
||||
:key="company.code"
|
||||
:label="`${company.name}(${company.code})`"
|
||||
:value="company.code"
|
||||
/>
|
||||
<el-option-group label="自定义快递编码">
|
||||
<el-option
|
||||
v-for="company in expressOptions.filter(item => item.source === 'custom')"
|
||||
:key="company.code"
|
||||
:label="`${company.name}(${company.code})`"
|
||||
:value="company.code"
|
||||
/>
|
||||
</el-option-group>
|
||||
<el-option-group label="系统快递">
|
||||
<el-option
|
||||
v-for="company in expressOptions.filter(item => item.source === 'system')"
|
||||
:key="company.code"
|
||||
:label="`${company.name}(${company.code})`"
|
||||
:value="company.code"
|
||||
/>
|
||||
</el-option-group>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
|
||||
@ -6,7 +6,7 @@ import ExportButton from '@/components/ExportButton.vue'
|
||||
import ListPager from '@/components/ListPager.vue'
|
||||
import RecordPickerDialog from '@/components/RecordPickerDialog.vue'
|
||||
import OrderFormDialog from './OrderFormDialog.vue'
|
||||
import { getExpressCompanyOptions, type ExpressCompanyOption } from '@/api/expressCompany'
|
||||
import { getExpressCodeOptions } from '@/api/customExpressCode'
|
||||
import { DEFAULT_PAGE_SIZE, useListPage } from '@/composables/useListPage'
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
import { platformNameOf } from '@/constants/platform'
|
||||
@ -282,19 +282,25 @@ async function pickWarehouse(): Promise<number | null> {
|
||||
/** 批量修改快递使用的目标选择弹窗 */
|
||||
const expressPicker = reactive({
|
||||
visible: false,
|
||||
options: [] as ExpressCompanyOption[],
|
||||
options: [] as Array<Record<string, unknown>>,
|
||||
})
|
||||
const expressPickerOptions = computed(() => expressPicker.options.map(item => ({ ...item })))
|
||||
const expressPickerColumns = [
|
||||
{ prop: 'code', label: '快递编码', width: 180 },
|
||||
{ prop: 'name', label: '快递名称', minWidth: 200 },
|
||||
{ prop: 'code', label: '快递编码', width: 150 },
|
||||
{ prop: 'name', label: '快递名称', minWidth: 180 },
|
||||
{ prop: 'source_label', label: '类型', width: 90 },
|
||||
{ prop: 'express_name', label: '对应系统快递', minWidth: 140 },
|
||||
]
|
||||
let expressPickerResolve: ((row: Record<string, unknown> | null) => void) | null = null
|
||||
|
||||
async function pickExpressCompany(): Promise<Record<string, unknown> | null> {
|
||||
expressPicker.options = await getExpressCompanyOptions()
|
||||
const options = await getExpressCodeOptions()
|
||||
expressPicker.options = options.map(item => ({
|
||||
...item,
|
||||
source_label: item.source === 'custom' ? '自定义' : '系统',
|
||||
}))
|
||||
if (!expressPicker.options.length) {
|
||||
ElMessage.warning('暂无启用的快递公司,请先到「快递公司」维护')
|
||||
ElMessage.warning('暂无可用快递编码,请先在「系统管理 → 自定义快递编码」或快递公司字典维护')
|
||||
return null
|
||||
}
|
||||
expressPicker.visible = true
|
||||
@ -957,13 +963,13 @@ onMounted(async () => {
|
||||
<!-- 批量修改快递:仅待审核订单可用 -->
|
||||
<RecordPickerDialog
|
||||
:model-value="expressPicker.visible"
|
||||
title="选择快递公司"
|
||||
title="选择快递(系统 / 自定义)"
|
||||
:options="expressPickerOptions"
|
||||
:columns="expressPickerColumns"
|
||||
value-key="code"
|
||||
:search-props="['code', 'name']"
|
||||
:search-props="['code', 'name', 'express_name']"
|
||||
confirm-text="修改所选订单"
|
||||
empty-text="暂无启用的快递公司"
|
||||
empty-text="暂无可用快递编码"
|
||||
@update:model-value="onExpressPickerClose"
|
||||
@confirm="onExpressPickerConfirm"
|
||||
/>
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user