- 新增 app/lib/intercept_guard 共享守卫:除 none 外所有拦截状态一律视为已拦截 - 分配波次(singleFetchByIds)/抓取波次(createWavePickTask) 排除拦截订单并回传清单 - 分配储位(allocatePicking)/分配快递(createWaybillCodePipeline、batchAllocateExpress) 跳过拦截订单并回报 - 打印组装(getWavePlatformPrintData/getOrderPrintData/getPrintDataByWaybillCodes) 剔除拦截订单,打印回写/波次反查/标记均排除 - 拣货完成(wavePickTaskComplete) 拦截报错;复核(assertOrderCanRecheck/批量快捷复核) 补全拦截状态 - 打包/称重(workbench、order.updateExpressWeighingWeight) 拦截阻断,波次批量操作排除拦截单 - 绑定包材(order_express) 拦截阻断,波次批量绑定排除拦截单
7136 lines
272 KiB
JavaScript
7136 lines
272 KiB
JavaScript
'use strict';
|
||
|
||
const OrderBaseService = require('./base');
|
||
|
||
const PENDING_OUTBOUND_STATUS = 'padding';
|
||
const PENDING_CANCEL_STATUS = 'cancel';
|
||
const PENDING_CANCEL_STEP = 9;
|
||
const PENDING_OUTBOUND_STEP = 4;
|
||
const PENDING_CANCEL_ALLOWED_STEPS = new Set([ 0, 1, 2, 3 ]);
|
||
const PENDING_CANCEL_PENDING_STEPS = new Set([ 1, 2 ]);
|
||
const ALLOCATE_STORAGE_TASK_CACHE_KEY_PREFIX = 'order:pending:allocate_storage:request:';
|
||
const ALLOCATE_STORAGE_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2;
|
||
const ALLOCATE_STORAGE_PROGRESS_MAP = Object.freeze({
|
||
submitted: 5,
|
||
running: 50,
|
||
success: 100,
|
||
failed: 100,
|
||
not_found: 0,
|
||
unknown: 0,
|
||
});
|
||
|
||
const BATCH_INTERCEPT_TASK_CACHE_KEY_PREFIX = 'order:batch-intercept:';
|
||
const BATCH_INTERCEPT_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24;
|
||
|
||
const BATCH_LOCK_TASK_CACHE_KEY_PREFIX = 'order:batch-lock:';
|
||
const BATCH_LOCK_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24;
|
||
|
||
const BATCH_UNLOCK_TASK_CACHE_KEY_PREFIX = 'order:batch-unlock:';
|
||
const BATCH_UNLOCK_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24;
|
||
|
||
const ALLOCATE_EXPRESS_TASK_CACHE_KEY_PREFIX = 'order:pending:allocate_express:request:';
|
||
const ALLOCATE_EXPRESS_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2;
|
||
const ALLOCATE_EXPRESS_PROGRESS_MAP = Object.freeze({
|
||
submitted: 5,
|
||
running: 50,
|
||
success: 100,
|
||
failed: 100,
|
||
not_found: 0,
|
||
unknown: 0,
|
||
});
|
||
|
||
const BATCH_UNINTERCEPT_TASK_CACHE_KEY_PREFIX = 'order:batch-unintercept:';
|
||
const BATCH_UNINTERCEPT_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24;
|
||
|
||
const SYNC_ORDER_IDS_TASK_CACHE_KEY_PREFIX = 'order:pending:sync_order_ids:request:';
|
||
const SYNC_ORDER_IDS_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2;
|
||
const SYNC_ORDER_IDS_PROGRESS_MAP = Object.freeze({
|
||
submitted: 5,
|
||
running: 50,
|
||
success: 100,
|
||
failed: 100,
|
||
not_found: 0,
|
||
unknown: 0,
|
||
});
|
||
|
||
const ALLOCATE_SUB_ORDER_TASK_CACHE_KEY_PREFIX = 'order:pending:allocate_sub_order:request:';
|
||
const ALLOCATE_SUB_ORDER_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2;
|
||
const ALLOCATE_SUB_ORDER_PROGRESS_MAP = Object.freeze({
|
||
submitted: 5,
|
||
running: 50,
|
||
success: 100,
|
||
partial: 80,
|
||
failed: 100,
|
||
not_found: 0,
|
||
unknown: 0,
|
||
});
|
||
|
||
/**
|
||
* 中国行政区划反向查询表。
|
||
*
|
||
* 用于在 AI 解析结果缺少 province/city/area 时进行兜底反向推断。
|
||
* 覆盖三类特殊行政区:
|
||
* - direct:省直辖县级市(如湖北仙桃、潜江、天门)
|
||
* - no_district:不设区的地级市(如东莞、中山、嘉峪关、儋州、三沙)
|
||
* - delegated:地级市代管县级市(如苏州代管昆山)
|
||
*
|
||
* 键为 area(区/县)标准名称,值为 { province, city, type }。
|
||
* 同时提供 city -> province 的映射表用于根据城市名反查省份。
|
||
*/
|
||
const CHINA_ADMIN_DIVISION_MAP = Object.freeze({
|
||
// ========== 省直辖县级市 / 省直管县 ==========
|
||
仙桃市: { province: '湖北省', city: '湖北省', type: 'direct' },
|
||
潜江市: { province: '湖北省', city: '湖北省', type: 'direct' },
|
||
天门市: { province: '湖北省', city: '湖北省', type: 'direct' },
|
||
神农架林区: { province: '湖北省', city: '湖北省', type: 'direct' },
|
||
济源市: { province: '河南省', city: '河南省', type: 'direct' },
|
||
五指山市: { province: '海南省', city: '海南省', type: 'direct' },
|
||
琼海市: { province: '海南省', city: '海南省', type: 'direct' },
|
||
文昌市: { province: '海南省', city: '海南省', type: 'direct' },
|
||
万宁市: { province: '海南省', city: '海南省', type: 'direct' },
|
||
东方市: { province: '海南省', city: '海南省', type: 'direct' },
|
||
定安县: { province: '海南省', city: '海南省', type: 'direct' },
|
||
屯昌县: { province: '海南省', city: '海南省', type: 'direct' },
|
||
澄迈县: { province: '海南省', city: '海南省', type: 'direct' },
|
||
临高县: { province: '海南省', city: '海南省', type: 'direct' },
|
||
白沙黎族自治县: { province: '海南省', city: '海南省', type: 'direct' },
|
||
昌江黎族自治县: { province: '海南省', city: '海南省', type: 'direct' },
|
||
乐东黎族自治县: { province: '海南省', city: '海南省', type: 'direct' },
|
||
陵水黎族自治县: { province: '海南省', city: '海南省', type: 'direct' },
|
||
保亭黎族苗族自治县: { province: '海南省', city: '海南省', type: 'direct' },
|
||
琼中黎族苗族自治县: { province: '海南省', city: '海南省', type: 'direct' },
|
||
石河子市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' },
|
||
阿拉尔市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' },
|
||
图木舒克市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' },
|
||
五家渠市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' },
|
||
北屯市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' },
|
||
铁门关市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' },
|
||
双河市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' },
|
||
可克达拉市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' },
|
||
昆玉市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' },
|
||
胡杨河市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' },
|
||
新星市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' },
|
||
白杨市: { province: '新疆维吾尔自治区', city: '新疆维吾尔自治区', type: 'direct' },
|
||
|
||
// ========== 不设区的地级市(city 和 area 可为同一值) ==========
|
||
东莞市: { province: '广东省', city: '东莞市', type: 'no_district' },
|
||
中山市: { province: '广东省', city: '中山市', type: 'no_district' },
|
||
嘉峪关市: { province: '甘肃省', city: '嘉峪关市', type: 'no_district' },
|
||
儋州市: { province: '海南省', city: '儋州市', type: 'no_district' },
|
||
三沙市: { province: '海南省', city: '三沙市', type: 'no_district' },
|
||
|
||
// ========== 常见地级市代管县级市 ==========
|
||
昆山市: { province: '江苏省', city: '苏州市', type: 'delegated' },
|
||
常熟市: { province: '江苏省', city: '苏州市', type: 'delegated' },
|
||
张家港市: { province: '江苏省', city: '苏州市', type: 'delegated' },
|
||
太仓市: { province: '江苏省', city: '苏州市', type: 'delegated' },
|
||
江阴市: { province: '江苏省', city: '无锡市', type: 'delegated' },
|
||
宜兴市: { province: '江苏省', city: '无锡市', type: 'delegated' },
|
||
丹阳市: { province: '江苏省', city: '镇江市', type: 'delegated' },
|
||
扬中市: { province: '江苏省', city: '镇江市', type: 'delegated' },
|
||
句容市: { province: '江苏省', city: '镇江市', type: 'delegated' },
|
||
溧阳市: { province: '江苏省', city: '常州市', type: 'delegated' },
|
||
海安市: { province: '江苏省', city: '南通市', type: 'delegated' },
|
||
启东市: { province: '江苏省', city: '南通市', type: 'delegated' },
|
||
如皋市: { province: '江苏省', city: '南通市', type: 'delegated' },
|
||
仪征市: { province: '江苏省', city: '扬州市', type: 'delegated' },
|
||
高邮市: { province: '江苏省', city: '扬州市', type: 'delegated' },
|
||
兴化市: { province: '江苏省', city: '泰州市', type: 'delegated' },
|
||
靖江市: { province: '江苏省', city: '泰州市', type: 'delegated' },
|
||
泰兴市: { province: '江苏省', city: '泰州市', type: 'delegated' },
|
||
邳州市: { province: '江苏省', city: '徐州市', type: 'delegated' },
|
||
新沂市: { province: '江苏省', city: '徐州市', type: 'delegated' },
|
||
东台市: { province: '江苏省', city: '盐城市', type: 'delegated' },
|
||
建德市: { province: '浙江省', city: '杭州市', type: 'delegated' },
|
||
慈溪市: { province: '浙江省', city: '宁波市', type: 'delegated' },
|
||
余姚市: { province: '浙江省', city: '宁波市', type: 'delegated' },
|
||
瑞安市: { province: '浙江省', city: '温州市', type: 'delegated' },
|
||
乐清市: { province: '浙江省', city: '温州市', type: 'delegated' },
|
||
海宁市: { province: '浙江省', city: '嘉兴市', type: 'delegated' },
|
||
平湖市: { province: '浙江省', city: '嘉兴市', type: 'delegated' },
|
||
桐乡市: { province: '浙江省', city: '嘉兴市', type: 'delegated' },
|
||
诸暨市: { province: '浙江省', city: '绍兴市', type: 'delegated' },
|
||
嵊州市: { province: '浙江省', city: '绍兴市', type: 'delegated' },
|
||
兰溪市: { province: '浙江省', city: '金华市', type: 'delegated' },
|
||
义乌市: { province: '浙江省', city: '金华市', type: 'delegated' },
|
||
东阳市: { province: '浙江省', city: '金华市', type: 'delegated' },
|
||
永康市: { province: '浙江省', city: '金华市', type: 'delegated' },
|
||
江山市: { province: '浙江省', city: '衢州市', type: 'delegated' },
|
||
温岭市: { province: '浙江省', city: '台州市', type: 'delegated' },
|
||
临海市: { province: '浙江省', city: '台州市', type: 'delegated' },
|
||
龙泉市: { province: '浙江省', city: '丽水市', type: 'delegated' },
|
||
巢湖市: { province: '安徽省', city: '合肥市', type: 'delegated' },
|
||
无为市: { province: '安徽省', city: '芜湖市', type: 'delegated' },
|
||
桐城市: { province: '安徽省', city: '安庆市', type: 'delegated' },
|
||
天长市: { province: '安徽省', city: '滁州市', type: 'delegated' },
|
||
明光市: { province: '安徽省', city: '滁州市', type: 'delegated' },
|
||
界首市: { province: '安徽省', city: '阜阳市', type: 'delegated' },
|
||
宁国市: { province: '安徽省', city: '宣城市', type: 'delegated' },
|
||
广德市: { province: '安徽省', city: '宣城市', type: 'delegated' },
|
||
福清市: { province: '福建省', city: '福州市', type: 'delegated' },
|
||
晋江市: { province: '福建省', city: '泉州市', type: 'delegated' },
|
||
南安市: { province: '福建省', city: '泉州市', type: 'delegated' },
|
||
石狮市: { province: '福建省', city: '泉州市', type: 'delegated' },
|
||
龙海市: { province: '福建省', city: '漳州市', type: 'delegated' },
|
||
邵武市: { province: '福建省', city: '南平市', type: 'delegated' },
|
||
武夷山市: { province: '福建省', city: '南平市', type: 'delegated' },
|
||
漳平市: { province: '福建省', city: '龙岩市', type: 'delegated' },
|
||
福安市: { province: '福建省', city: '宁德市', type: 'delegated' },
|
||
福鼎市: { province: '福建省', city: '宁德市', type: 'delegated' },
|
||
乐平市: { province: '江西省', city: '景德镇市', type: 'delegated' },
|
||
瑞昌市: { province: '江西省', city: '九江市', type: 'delegated' },
|
||
共青城市: { province: '江西省', city: '九江市', type: 'delegated' },
|
||
庐山市: { province: '江西省', city: '九江市', type: 'delegated' },
|
||
贵溪市: { province: '江西省', city: '鹰潭市', type: 'delegated' },
|
||
瑞金市: { province: '江西省', city: '赣州市', type: 'delegated' },
|
||
井冈山市: { province: '江西省', city: '吉安市', type: 'delegated' },
|
||
丰城市: { province: '江西省', city: '宜春市', type: 'delegated' },
|
||
樟树市: { province: '江西省', city: '宜春市', type: 'delegated' },
|
||
高安市: { province: '江西省', city: '宜春市', type: 'delegated' },
|
||
德兴市: { province: '江西省', city: '上饶市', type: 'delegated' },
|
||
章丘区: { province: '山东省', city: '济南市', type: 'delegated' },
|
||
胶州市: { province: '山东省', city: '青岛市', type: 'delegated' },
|
||
平度市: { province: '山东省', city: '青岛市', type: 'delegated' },
|
||
莱西市: { province: '山东省', city: '青岛市', type: 'delegated' },
|
||
滕州市: { province: '山东省', city: '枣庄市', type: 'delegated' },
|
||
龙口市: { province: '山东省', city: '烟台市', type: 'delegated' },
|
||
莱阳市: { province: '山东省', city: '烟台市', type: 'delegated' },
|
||
莱州市: { province: '山东省', city: '烟台市', type: 'delegated' },
|
||
招远市: { province: '山东省', city: '烟台市', type: 'delegated' },
|
||
栖霞市: { province: '山东省', city: '烟台市', type: 'delegated' },
|
||
海阳市: { province: '山东省', city: '烟台市', type: 'delegated' },
|
||
青州市: { province: '山东省', city: '潍坊市', type: 'delegated' },
|
||
诸城市: { province: '山东省', city: '潍坊市', type: 'delegated' },
|
||
寿光市: { province: '山东省', city: '潍坊市', type: 'delegated' },
|
||
安丘市: { province: '山东省', city: '潍坊市', type: 'delegated' },
|
||
高密市: { province: '山东省', city: '潍坊市', type: 'delegated' },
|
||
昌邑市: { province: '山东省', city: '潍坊市', type: 'delegated' },
|
||
曲阜市: { province: '山东省', city: '济宁市', type: 'delegated' },
|
||
邹城市: { province: '山东省', city: '济宁市', type: 'delegated' },
|
||
新泰市: { province: '山东省', city: '泰安市', type: 'delegated' },
|
||
肥城市: { province: '山东省', city: '泰安市', type: 'delegated' },
|
||
荣成市: { province: '山东省', city: '威海市', type: 'delegated' },
|
||
乳山市: { province: '山东省', city: '威海市', type: 'delegated' },
|
||
乐陵市: { province: '山东省', city: '德州市', type: 'delegated' },
|
||
禹城市: { province: '山东省', city: '德州市', type: 'delegated' },
|
||
临清市: { province: '山东省', city: '聊城市', type: 'delegated' },
|
||
巩义市: { province: '河南省', city: '郑州市', type: 'delegated' },
|
||
新密市: { province: '河南省', city: '郑州市', type: 'delegated' },
|
||
荥阳市: { province: '河南省', city: '郑州市', type: 'delegated' },
|
||
新郑市: { province: '河南省', city: '郑州市', type: 'delegated' },
|
||
登封市: { province: '河南省', city: '郑州市', type: 'delegated' },
|
||
偃师区: { province: '河南省', city: '洛阳市', type: 'delegated' },
|
||
舞钢市: { province: '河南省', city: '平顶山市', type: 'delegated' },
|
||
汝州市: { province: '河南省', city: '平顶山市', type: 'delegated' },
|
||
林州市: { province: '河南省', city: '安阳市', type: 'delegated' },
|
||
卫辉市: { province: '河南省', city: '新乡市', type: 'delegated' },
|
||
辉县市: { province: '河南省', city: '新乡市', type: 'delegated' },
|
||
长垣市: { province: '河南省', city: '新乡市', type: 'delegated' },
|
||
沁阳市: { province: '河南省', city: '焦作市', type: 'delegated' },
|
||
孟州市: { province: '河南省', city: '焦作市', type: 'delegated' },
|
||
禹州市: { province: '河南省', city: '许昌市', type: 'delegated' },
|
||
长葛市: { province: '河南省', city: '许昌市', type: 'delegated' },
|
||
义马市: { province: '河南省', city: '三门峡市', type: 'delegated' },
|
||
灵宝市: { province: '河南省', city: '三门峡市', type: 'delegated' },
|
||
邓州市: { province: '河南省', city: '南阳市', type: 'delegated' },
|
||
永城市: { province: '河南省', city: '商丘市', type: 'delegated' },
|
||
项城市: { province: '河南省', city: '周口市', type: 'delegated' },
|
||
大冶市: { province: '湖北省', city: '黄石市', type: 'delegated' },
|
||
丹江口市: { province: '湖北省', city: '十堰市', type: 'delegated' },
|
||
宜都市: { province: '湖北省', city: '宜昌市', type: 'delegated' },
|
||
当阳市: { province: '湖北省', city: '宜昌市', type: 'delegated' },
|
||
枝江市: { province: '湖北省', city: '宜昌市', type: 'delegated' },
|
||
老河口市: { province: '湖北省', city: '襄阳市', type: 'delegated' },
|
||
枣阳市: { province: '湖北省', city: '襄阳市', type: 'delegated' },
|
||
宜城市: { province: '湖北省', city: '襄阳市', type: 'delegated' },
|
||
钟祥市: { province: '湖北省', city: '荆门市', type: 'delegated' },
|
||
京山市: { province: '湖北省', city: '荆门市', type: 'delegated' },
|
||
应城市: { province: '湖北省', city: '孝感市', type: 'delegated' },
|
||
安陆市: { province: '湖北省', city: '孝感市', type: 'delegated' },
|
||
汉川市: { province: '湖北省', city: '孝感市', type: 'delegated' },
|
||
石首市: { province: '湖北省', city: '荆州市', type: 'delegated' },
|
||
洪湖市: { province: '湖北省', city: '荆州市', type: 'delegated' },
|
||
松滋市: { province: '湖北省', city: '荆州市', type: 'delegated' },
|
||
监利市: { province: '湖北省', city: '荆州市', type: 'delegated' },
|
||
麻城市: { province: '湖北省', city: '黄冈市', type: 'delegated' },
|
||
武穴市: { province: '湖北省', city: '黄冈市', type: 'delegated' },
|
||
赤壁市: { province: '湖北省', city: '咸宁市', type: 'delegated' },
|
||
广水市: { province: '湖北省', city: '随州市', type: 'delegated' },
|
||
恩施市: { province: '湖北省', city: '恩施土家族苗族自治州', type: 'delegated' },
|
||
利川市: { province: '湖北省', city: '恩施土家族苗族自治州', type: 'delegated' },
|
||
浏阳市: { province: '湖南省', city: '长沙市', type: 'delegated' },
|
||
宁乡市: { province: '湖南省', city: '长沙市', type: 'delegated' },
|
||
醴陵市: { province: '湖南省', city: '株洲市', type: 'delegated' },
|
||
湘乡市: { province: '湖南省', city: '湘潭市', type: 'delegated' },
|
||
韶山市: { province: '湖南省', city: '湘潭市', type: 'delegated' },
|
||
耒阳市: { province: '湖南省', city: '衡阳市', type: 'delegated' },
|
||
常宁市: { province: '湖南省', city: '衡阳市', type: 'delegated' },
|
||
武冈市: { province: '湖南省', city: '邵阳市', type: 'delegated' },
|
||
邵东市: { province: '湖南省', city: '邵阳市', type: 'delegated' },
|
||
汨罗市: { province: '湖南省', city: '岳阳市', type: 'delegated' },
|
||
临湘市: { province: '湖南省', city: '岳阳市', type: 'delegated' },
|
||
津市市: { province: '湖南省', city: '常德市', type: 'delegated' },
|
||
沅江市: { province: '湖南省', city: '益阳市', type: 'delegated' },
|
||
资兴市: { province: '湖南省', city: '郴州市', type: 'delegated' },
|
||
洪江市: { province: '湖南省', city: '怀化市', type: 'delegated' },
|
||
冷水江市: { province: '湖南省', city: '娄底市', type: 'delegated' },
|
||
涟源市: { province: '湖南省', city: '娄底市', type: 'delegated' },
|
||
吉首市: { province: '湖南省', city: '湘西土家族苗族自治州', type: 'delegated' },
|
||
增城区: { province: '广东省', city: '广州市', type: 'delegated' },
|
||
从化区: { province: '广东省', city: '广州市', type: 'delegated' },
|
||
乐昌市: { province: '广东省', city: '韶关市', type: 'delegated' },
|
||
南雄市: { province: '广东省', city: '韶关市', type: 'delegated' },
|
||
廉江市: { province: '广东省', city: '湛江市', type: 'delegated' },
|
||
雷州市: { province: '广东省', city: '湛江市', type: 'delegated' },
|
||
吴川市: { province: '广东省', city: '湛江市', type: 'delegated' },
|
||
高州市: { province: '广东省', city: '茂名市', type: 'delegated' },
|
||
化州市: { province: '广东省', city: '茂名市', type: 'delegated' },
|
||
信宜市: { province: '广东省', city: '茂名市', type: 'delegated' },
|
||
高要区: { province: '广东省', city: '肇庆市', type: 'delegated' },
|
||
四会市: { province: '广东省', city: '肇庆市', type: 'delegated' },
|
||
惠东县: { province: '广东省', city: '惠州市', type: 'delegated' },
|
||
博罗县: { province: '广东省', city: '惠州市', type: 'delegated' },
|
||
龙门县: { province: '广东省', city: '惠州市', type: 'delegated' },
|
||
兴宁市: { province: '广东省', city: '梅州市', type: 'delegated' },
|
||
陆丰市: { province: '广东省', city: '汕尾市', type: 'delegated' },
|
||
阳春市: { province: '广东省', city: '阳江市', type: 'delegated' },
|
||
英德市: { province: '广东省', city: '清远市', type: 'delegated' },
|
||
连州市: { province: '广东省', city: '清远市', type: 'delegated' },
|
||
普宁市: { province: '广东省', city: '揭阳市', type: 'delegated' },
|
||
罗定市: { province: '广东省', city: '云浮市', type: 'delegated' },
|
||
岑溪市: { province: '广西壮族自治区', city: '梧州市', type: 'delegated' },
|
||
东兴市: { province: '广西壮族自治区', city: '防城港市', type: 'delegated' },
|
||
桂平市: { province: '广西壮族自治区', city: '贵港市', type: 'delegated' },
|
||
北流市: { province: '广西壮族自治区', city: '玉林市', type: 'delegated' },
|
||
靖西市: { province: '广西壮族自治区', city: '百色市', type: 'delegated' },
|
||
平果市: { province: '广西壮族自治区', city: '百色市', type: 'delegated' },
|
||
合山市: { province: '广西壮族自治区', city: '来宾市', type: 'delegated' },
|
||
凭祥市: { province: '广西壮族自治区', city: '崇左市', type: 'delegated' },
|
||
都江堰市: { province: '四川省', city: '成都市', type: 'delegated' },
|
||
彭州市: { province: '四川省', city: '成都市', type: 'delegated' },
|
||
邛崃市: { province: '四川省', city: '成都市', type: 'delegated' },
|
||
崇州市: { province: '四川省', city: '成都市', type: 'delegated' },
|
||
简阳市: { province: '四川省', city: '成都市', type: 'delegated' },
|
||
广汉市: { province: '四川省', city: '德阳市', type: 'delegated' },
|
||
什邡市: { province: '四川省', city: '德阳市', type: 'delegated' },
|
||
绵竹市: { province: '四川省', city: '德阳市', type: 'delegated' },
|
||
江油市: { province: '四川省', city: '绵阳市', type: 'delegated' },
|
||
峨眉山市: { province: '四川省', city: '乐山市', type: 'delegated' },
|
||
阆中市: { province: '四川省', city: '南充市', type: 'delegated' },
|
||
华蓥市: { province: '四川省', city: '广安市', type: 'delegated' },
|
||
万源市: { province: '四川省', city: '达州市', type: 'delegated' },
|
||
西昌市: { province: '四川省', city: '凉山彝族自治州', type: 'delegated' },
|
||
会理市: { province: '四川省', city: '凉山彝族自治州', type: 'delegated' },
|
||
康定市: { province: '四川省', city: '甘孜藏族自治州', type: 'delegated' },
|
||
马尔康市: { province: '四川省', city: '阿坝藏族羌族自治州', type: 'delegated' },
|
||
清镇市: { province: '贵州省', city: '贵阳市', type: 'delegated' },
|
||
盘州市: { province: '贵州省', city: '六盘水市', type: 'delegated' },
|
||
赤水市: { province: '贵州省', city: '遵义市', type: 'delegated' },
|
||
仁怀市: { province: '贵州省', city: '遵义市', type: 'delegated' },
|
||
兴义市: { province: '贵州省', city: '黔西南布依族苗族自治州', type: 'delegated' },
|
||
兴仁市: { province: '贵州省', city: '黔西南布依族苗族自治州', type: 'delegated' },
|
||
凯里市: { province: '贵州省', city: '黔东南苗族侗族自治州', type: 'delegated' },
|
||
都匀市: { province: '贵州省', city: '黔南布依族苗族自治州', type: 'delegated' },
|
||
福泉市: { province: '贵州省', city: '黔南布依族苗族自治州', type: 'delegated' },
|
||
安宁市: { province: '云南省', city: '昆明市', type: 'delegated' },
|
||
宣威市: { province: '云南省', city: '曲靖市', type: 'delegated' },
|
||
腾冲市: { province: '云南省', city: '保山市', type: 'delegated' },
|
||
水富市: { province: '云南省', city: '昭通市', type: 'delegated' },
|
||
楚雄市: { province: '云南省', city: '楚雄彝族自治州', type: 'delegated' },
|
||
禄丰市: { province: '云南省', city: '楚雄彝族自治州', type: 'delegated' },
|
||
个旧市: { province: '云南省', city: '红河哈尼族彝族自治州', type: 'delegated' },
|
||
开远市: { province: '云南省', city: '红河哈尼族彝族自治州', type: 'delegated' },
|
||
蒙自市: { province: '云南省', city: '红河哈尼族彝族自治州', type: 'delegated' },
|
||
弥勒市: { province: '云南省', city: '红河哈尼族彝族自治州', type: 'delegated' },
|
||
文山市: { province: '云南省', city: '文山壮族苗族自治州', type: 'delegated' },
|
||
景洪市: { province: '云南省', city: '西双版纳傣族自治州', type: 'delegated' },
|
||
大理市: { province: '云南省', city: '大理白族自治州', type: 'delegated' },
|
||
瑞丽市: { province: '云南省', city: '德宏傣族景颇族自治州', type: 'delegated' },
|
||
芒市: { province: '云南省', city: '德宏傣族景颇族自治州', type: 'delegated' },
|
||
泸水市: { province: '云南省', city: '怒江傈僳族自治州', type: 'delegated' },
|
||
香格里拉市: { province: '云南省', city: '迪庆藏族自治州', type: 'delegated' },
|
||
兴平市: { province: '陕西省', city: '咸阳市', type: 'delegated' },
|
||
彬州市: { province: '陕西省', city: '咸阳市', type: 'delegated' },
|
||
韩城市: { province: '陕西省', city: '渭南市', type: 'delegated' },
|
||
华阴市: { province: '陕西省', city: '渭南市', type: 'delegated' },
|
||
子长市: { province: '陕西省', city: '延安市', type: 'delegated' },
|
||
神木市: { province: '陕西省', city: '榆林市', type: 'delegated' },
|
||
玉门市: { province: '甘肃省', city: '酒泉市', type: 'delegated' },
|
||
敦煌市: { province: '甘肃省', city: '酒泉市', type: 'delegated' },
|
||
华亭市: { province: '甘肃省', city: '平凉市', type: 'delegated' },
|
||
合作市: { province: '甘肃省', city: '甘南藏族自治州', type: 'delegated' },
|
||
格尔木市: { province: '青海省', city: '海西蒙古族藏族自治州', type: 'delegated' },
|
||
茫崖市: { province: '青海省', city: '海西蒙古族藏族自治州', type: 'delegated' },
|
||
德令哈市: { province: '青海省', city: '海西蒙古族藏族自治州', type: 'delegated' },
|
||
玉树市: { province: '青海省', city: '玉树藏族自治州', type: 'delegated' },
|
||
灵武市: { province: '宁夏回族自治区', city: '银川市', type: 'delegated' },
|
||
青铜峡市: { province: '宁夏回族自治区', city: '吴忠市', type: 'delegated' },
|
||
奎屯市: { province: '新疆维吾尔自治区', city: '伊犁哈萨克自治州', type: 'delegated' },
|
||
霍尔果斯市: { province: '新疆维吾尔自治区', city: '伊犁哈萨克自治州', type: 'delegated' },
|
||
库尔勒市: { province: '新疆维吾尔自治区', city: '巴音郭楞蒙古自治州', type: 'delegated' },
|
||
阿克苏市: { province: '新疆维吾尔自治区', city: '阿克苏地区', type: 'delegated' },
|
||
库车市: { province: '新疆维吾尔自治区', city: '阿克苏地区', type: 'delegated' },
|
||
阿图什市: { province: '新疆维吾尔自治区', city: '克孜勒苏柯尔克孜自治州', type: 'delegated' },
|
||
喀什市: { province: '新疆维吾尔自治区', city: '喀什地区', type: 'delegated' },
|
||
和田市: { province: '新疆维吾尔自治区', city: '和田地区', type: 'delegated' },
|
||
博乐市: { province: '新疆维吾尔自治区', city: '博尔塔拉蒙古自治州', type: 'delegated' },
|
||
阿拉山口市: { province: '新疆维吾尔自治区', city: '博尔塔拉蒙古自治州', type: 'delegated' },
|
||
伊宁市: { province: '新疆维吾尔自治区', city: '伊犁哈萨克自治州', type: 'delegated' },
|
||
塔城市: { province: '新疆维吾尔自治区', city: '塔城地区', type: 'delegated' },
|
||
乌苏市: { province: '新疆维吾尔自治区', city: '塔城地区', type: 'delegated' },
|
||
沙湾市: { province: '新疆维吾尔自治区', city: '塔城地区', type: 'delegated' },
|
||
阿勒泰市: { province: '新疆维吾尔自治区', city: '阿勒泰地区', type: 'delegated' },
|
||
昌吉市: { province: '新疆维吾尔自治区', city: '昌吉回族自治州', type: 'delegated' },
|
||
阜康市: { province: '新疆维吾尔自治区', city: '昌吉回族自治州', type: 'delegated' },
|
||
哈密市: { province: '新疆维吾尔自治区', city: '哈密市', type: 'delegated' },
|
||
吐鲁番市: { province: '新疆维吾尔自治区', city: '吐鲁番市', type: 'delegated' },
|
||
});
|
||
|
||
/**
|
||
* 直辖市名称集合,用于判断是否为直辖市地址。
|
||
*/
|
||
const MUNICIPALITY_SET = new Set([
|
||
'北京市', '天津市', '上海市', '重庆市',
|
||
]);
|
||
|
||
/**
|
||
* 省份名称集合,用于 city/area 名反向匹配省份。
|
||
*/
|
||
const PROVINCE_LIST = [
|
||
'北京市', '天津市', '上海市', '重庆市',
|
||
'河北省', '山西省', '辽宁省', '吉林省', '黑龙江省',
|
||
'江苏省', '浙江省', '安徽省', '福建省', '江西省', '山东省',
|
||
'河南省', '湖北省', '湖南省', '广东省', '海南省',
|
||
'四川省', '贵州省', '云南省', '陕西省', '甘肃省', '青海省',
|
||
'台湾省',
|
||
'内蒙古自治区', '广西壮族自治区', '西藏自治区', '宁夏回族自治区', '新疆维吾尔自治区',
|
||
'香港特别行政区', '澳门特别行政区',
|
||
];
|
||
|
||
/**
|
||
* 根据已解析的地址字段,利用中国行政区划知识进行反向推断,补全缺失的 province/city/area。
|
||
*
|
||
* 处理逻辑:
|
||
* 1. 若 area 在 CHINA_ADMIN_DIVISION_MAP 中,直接补全 province 和 city
|
||
* 2. 若 province 为空但 city 或 area 不为空,尝试通过名称匹配推断省份
|
||
* 3. 若 city 为空但 area 不为空,尝试通过 area 名推断城市
|
||
* 4. 若 city 和 area 都为空,尝试从 town / detailAddress 中提取信息
|
||
* 5. 对不设区地级市,若 area 为空则用 city 填充
|
||
*
|
||
* @param {Object} parsed AI 解析后的原始结果 { province, city, area, town, detailAddress, name, mobile }
|
||
* @return {Object} 修正后的结果,结构与输入一致
|
||
*/
|
||
function reverseInferAddress(parsed) {
|
||
let { province, city, area, town } = parsed;
|
||
const { detailAddress } = parsed;
|
||
|
||
// 标准化:去除末尾的"市"、"省"等做模糊匹配用
|
||
const normalizeName = name => {
|
||
if (!name) return '';
|
||
let n = name.trim();
|
||
// 去掉末尾的"市"、"县"、"区"、"自治县"、"自治州" 等后缀
|
||
n = n.replace(/(市|县|区|自治县|自治州|地区|盟|林区)$/, '');
|
||
return n;
|
||
};
|
||
|
||
// --- 步骤1:area 命中行政区划映射表 ---
|
||
if (area) {
|
||
const entry = CHINA_ADMIN_DIVISION_MAP[area];
|
||
if (entry) {
|
||
province = province || entry.province;
|
||
city = city || entry.city;
|
||
// 不设区地级市:area 和 city 一样时补充说明
|
||
if (entry.type === 'no_district' && (!area || area === city || area === entry.city)) {
|
||
// area 已是 city 名,保持不变(允许 area = city 对于不设区地级市)
|
||
}
|
||
}
|
||
}
|
||
|
||
// --- 步骤2:province 为空,从 city 或 area 反查 ---
|
||
if (!province) {
|
||
// 尝试从 city 反查省份(去掉"市"后缀)
|
||
if (city) {
|
||
const cityNorm = normalizeName(city);
|
||
// 先在映射表中查(按 city 名匹配)
|
||
for (const [ , entry ] of Object.entries(CHINA_ADMIN_DIVISION_MAP)) {
|
||
if (entry.city && normalizeName(entry.city) === cityNorm && entry.province) {
|
||
province = entry.province;
|
||
break;
|
||
}
|
||
}
|
||
// 如果没找到,尝试判断是否本身是省份名
|
||
if (!province && PROVINCE_LIST.includes(city)) {
|
||
province = city;
|
||
}
|
||
}
|
||
// 如果 city 没有,尝试从 area 反查
|
||
if (!province && area) {
|
||
const entry = CHINA_ADMIN_DIVISION_MAP[area];
|
||
if (entry && entry.province) {
|
||
province = entry.province;
|
||
}
|
||
}
|
||
}
|
||
|
||
// --- 步骤3:city 为空但 area 不为空,反查城市 ---
|
||
if (!city && area) {
|
||
const entry = CHINA_ADMIN_DIVISION_MAP[area];
|
||
if (entry && entry.city) {
|
||
city = entry.city;
|
||
} else {
|
||
// 若 area 带"市"后缀,则 city 与 area 同名
|
||
if (area.endsWith('市') && !MUNICIPALITY_SET.has(area)) {
|
||
city = area;
|
||
}
|
||
}
|
||
}
|
||
|
||
// --- 步骤4:city 和 area 都为空,尝试从 town / detailAddress 提取 ---
|
||
if (!city && !area) {
|
||
const townStr = (town || '').trim();
|
||
const detailStr = (detailAddress || '').trim();
|
||
|
||
// 从 town 中匹配已知城市/区县
|
||
if (townStr) {
|
||
for (const [ key, entry ] of Object.entries(CHINA_ADMIN_DIVISION_MAP)) {
|
||
if (townStr.includes(key) || townStr.includes(normalizeName(key))) {
|
||
province = province || entry.province;
|
||
city = city || entry.city;
|
||
area = area || key;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 从 detailAddress 中尝试匹配
|
||
if (!city && !area && detailStr) {
|
||
for (const [ key, entry ] of Object.entries(CHINA_ADMIN_DIVISION_MAP)) {
|
||
if (detailStr.includes(key) || detailStr.includes(normalizeName(key))) {
|
||
province = province || entry.province;
|
||
city = city || entry.city;
|
||
area = area || key;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// --- 步骤5:不设区地级市兜底 ---
|
||
// 若 city 已知且为不设区地级市,area 为空则用 city 填充
|
||
if (city && !area) {
|
||
const cityNorm = normalizeName(city);
|
||
for (const [ , entry ] of Object.entries(CHINA_ADMIN_DIVISION_MAP)) {
|
||
if (entry.type === 'no_district' && normalizeName(entry.city) === cityNorm) {
|
||
area = entry.city; // 对于不设区地级市,area 填 city 名
|
||
province = province || entry.province;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
return { ...parsed, province: province || '', city: city || '', area: area || '' };
|
||
}
|
||
|
||
/**
|
||
* 从模型返回的文本中截取 JSON 片段(对象或数组),并清理 markdown 代码块标记。
|
||
* 对象取第一个 { 到最后一个 },数组取第一个 [ 到最后一个 ],自动忽略前后多余文本。
|
||
*
|
||
* @param {string} text 模型原始返回文本。
|
||
* @return {string} 截取后的 JSON 字符串;无有效片段时返回原文 trim。
|
||
*/
|
||
function extractJsonBlock(text) {
|
||
if (!text) return '';
|
||
let s = String(text).trim();
|
||
s = s.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '');
|
||
const firstBrace = s.indexOf('{');
|
||
const firstBracket = s.indexOf('[');
|
||
let start = -1;
|
||
if (firstBrace === -1) {
|
||
start = firstBracket;
|
||
} else if (firstBracket === -1) {
|
||
start = firstBrace;
|
||
} else {
|
||
start = Math.min(firstBrace, firstBracket);
|
||
}
|
||
const end = Math.max(s.lastIndexOf('}'), s.lastIndexOf(']'));
|
||
if (start === -1 || end === -1 || end <= start) {
|
||
return s;
|
||
}
|
||
return s.slice(start, end + 1);
|
||
}
|
||
|
||
const ADDRESS_PARSE_FIELDS = [
|
||
'province', 'city', 'area', 'town', 'detailAddress', 'name', 'mobile',
|
||
];
|
||
|
||
/**
|
||
* 从任意文本(如思维链模型的 reasoning_content)中提取地址解析字段,
|
||
* 支持 "province":"xx"、province=xx、province:xx 等常见写法。
|
||
*
|
||
* @param {string} text 原始文本。
|
||
* @return {Object|null} 提取到的字段对象;一个字段都没提取到则返回 null。
|
||
*/
|
||
function salvageFieldsFromText(text) {
|
||
if (!text) return null;
|
||
const src = String(text);
|
||
const out = {};
|
||
let foundAny = false;
|
||
for (const field of ADDRESS_PARSE_FIELDS) {
|
||
const patterns = [
|
||
new RegExp(`["']?${field}["']?\\s*[::=]\\s*["']([^"']{0,80})["']`, 'i'),
|
||
new RegExp(`["']?${field}["']?\\s*[::=]\\s*([^\\s,,;;\\n"']{0,80})`, 'i'),
|
||
];
|
||
for (const re of patterns) {
|
||
const m = src.match(re);
|
||
if (m && m[1] && m[1].trim()) {
|
||
out[field] = m[1].trim();
|
||
foundAny = true;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
return foundAny ? out : null;
|
||
}
|
||
|
||
/**
|
||
* 清洗手机号:仅保留合法 11 位大陆手机号;兜底提取的脏数据(如整段地址)置空。
|
||
*
|
||
* @param {*} mobile 原始手机号字段。
|
||
* @return {string} 合法手机号或空字符串。
|
||
*/
|
||
function sanitizeMobile(mobile) {
|
||
const m = String(mobile || '').trim();
|
||
return /^1[3-9]\d{9}$/.test(m) ? m : '';
|
||
}
|
||
|
||
/**
|
||
* 清洗收件人姓名:过滤过长的字符串与明显混入地址信息的脏数据。
|
||
*
|
||
* @param {*} name 原始姓名字段。
|
||
* @return {string} 合法姓名或空字符串。
|
||
*/
|
||
function sanitizeName(name) {
|
||
const n = String(name || '').trim();
|
||
if (!n || n.length > 20) return '';
|
||
if (/[省市县区镇街道路号村组栋座楼室单元乡]/.test(n)) return '';
|
||
return n;
|
||
}
|
||
|
||
/**
|
||
* 地址解析最终兜底:AI 解析与行政区划映射表均失败时,用正则按"省-市-区-镇"顺序
|
||
* 从原始地址字符串中提取行政区划。支持省份全称与简称(如"广东"、"内蒙古")。
|
||
*
|
||
* @param {string} text 原始地址字符串。
|
||
* @return {Object} { province, city, area, town },识别不到的字段为空字符串。
|
||
*/
|
||
function extractAddressByRegex(text) {
|
||
const src = String(text || '');
|
||
const result = { province: '', city: '', area: '', town: '' };
|
||
if (!src) return result;
|
||
|
||
// 省份:全称与简称按长度降序匹配,避免"河北/河南"等前缀误配
|
||
const shorten = p => p.replace(/(壮族自治区|回族自治区|维吾尔自治区|特别行政区|自治区|省|市)$/, '');
|
||
const provincePattern = PROVINCE_LIST
|
||
.reduce((list, p) => {
|
||
const short = shorten(p);
|
||
if (short !== p) list.push(short);
|
||
list.push(p);
|
||
return list;
|
||
}, [])
|
||
.sort((a, b) => b.length - a.length)
|
||
.join('|');
|
||
const provinceMatch = src.match(new RegExp(`(${provincePattern})`));
|
||
if (!provinceMatch) return result;
|
||
|
||
const provinceToken = provinceMatch[1];
|
||
const fullProvince = PROVINCE_LIST.find(p => p.startsWith(provinceToken));
|
||
result.province = fullProvince || provinceToken;
|
||
const rest = src.slice(provinceMatch.index + provinceToken.length);
|
||
|
||
const cityMatch = rest.match(/([\u4e00-\u9fa5]{2,10}?(?:自治州|地区|盟|市))/);
|
||
if (!cityMatch) return result;
|
||
result.city = cityMatch[1];
|
||
const restAfterCity = rest.slice(cityMatch.index + cityMatch[1].length);
|
||
|
||
const areaMatch = restAfterCity.match(/([\u4e00-\u9fa5]{2,10}?(?:自治县|区|县|市))/);
|
||
if (!areaMatch) return result;
|
||
result.area = areaMatch[1];
|
||
const restAfterArea = restAfterCity.slice(areaMatch.index + areaMatch[1].length);
|
||
|
||
const townMatch = restAfterArea.match(/([\u4e00-\u9fa5]{2,10}?(?:街道|办事处|镇|乡))/);
|
||
if (townMatch) {
|
||
result.town = townMatch[1];
|
||
}
|
||
return result;
|
||
}
|
||
|
||
class PendingOrderService extends OrderBaseService {
|
||
/**
|
||
* 初始化待处理订单系统方法的免登录、免权限、免日志和免鉴权配置。
|
||
*
|
||
* @param {Egg.Context} ctx 上下文对象。
|
||
*/
|
||
constructor(ctx) {
|
||
super(ctx);
|
||
const _noNeedLogin = '';
|
||
const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted';
|
||
const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted';
|
||
const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted';
|
||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||
}
|
||
|
||
/**
|
||
* 待处理订单列表。
|
||
* @param {Object} data 请求体。
|
||
* @return {Promise<Object>} 列表与分页信息。
|
||
*/
|
||
async list(data = {}) {
|
||
return await this.listByModule('pendingOrder', data);
|
||
}
|
||
|
||
/**
|
||
* 查询待处理订单详情。
|
||
*
|
||
* 仅返回订单头、商品明细与运单信息;
|
||
* 待处理详情不再返回 logs 字段,也不触发操作日志查询。
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @return {Promise<Object>} 订单头、商品明细和运单信息。
|
||
*/
|
||
async detail(data = {}) {
|
||
const requestData = this.isPlainObject(data) ? data : {};
|
||
const warehouseId = this.getWarehouseId();
|
||
const orderIds = this.normalizeOrderIds(requestData);
|
||
const tableType = this.resolveOrderTableType(requestData);
|
||
|
||
if (orderIds.length === 0) {
|
||
throw new Error('订单ID不能为空');
|
||
}
|
||
|
||
if (orderIds.length !== 1) {
|
||
throw new Error('订单详情仅支持查询单个订单');
|
||
}
|
||
|
||
const orderId = orderIds[0];
|
||
const orderModel = await this.getOrderModelByTableType(tableType, warehouseId);
|
||
const orderWhere = this.buildOrderWhere([ orderId ], warehouseId);
|
||
const order = await orderModel.findOne({
|
||
where: orderWhere,
|
||
raw: true,
|
||
});
|
||
|
||
if (!order) {
|
||
throw new Error('订单不存在或不属于当前仓库');
|
||
}
|
||
|
||
const orderItemsModel = await this.getOrderItemsModelByTableType(tableType, warehouseId);
|
||
const orderItems = await orderItemsModel.findAll({
|
||
where: {
|
||
order_id: orderId,
|
||
},
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
|
||
// 通过 getStockDetails(带缓存)批量查询 stock_warehouse 标准信息
|
||
// 返回以 stock_warehouse 格式为主、附带 plan_qty / order_line_no / stock_id / order_item_id / order_id 的数据
|
||
const orderItemsWithImages = await this.attachStockDetailsToOrderItems(orderItems, warehouseId);
|
||
|
||
// 构建 order_item_id → orderItem 的快速查找映射(仍基于原始 order_items)
|
||
const orderItemMap = new Map();
|
||
for (const item of orderItems) {
|
||
orderItemMap.set(item.id, item);
|
||
}
|
||
|
||
// 构建 stockMap:直接从 attachStockDetailsToOrderItems(已是 stock_warehouse 格式)中按 stock_id 建立映射
|
||
const stockMap = new Map();
|
||
for (const item of orderItemsWithImages) {
|
||
const stockId = Number(item.stock_id);
|
||
if (stockId) {
|
||
stockMap.set(stockId, item);
|
||
}
|
||
}
|
||
|
||
// 查询已分配的储位信息(排除已取消的分配记录)
|
||
const orderItemIds = orderItems.map(item => item.id).filter(Boolean);
|
||
const pickingMap = new Map();
|
||
const storageItems = [];
|
||
if (orderItemIds.length > 0) {
|
||
const { Op } = this.app.Sequelize;
|
||
const pickingModel = this.ctx.model.Picking;
|
||
if (pickingModel) {
|
||
const pickingRows = await pickingModel.findAll({
|
||
where: {
|
||
order_item_id: { [Op.in]: orderItemIds },
|
||
status: { [Op.ne]: 'cancel' },
|
||
},
|
||
raw: true,
|
||
});
|
||
for (const row of pickingRows) {
|
||
const key = row.order_item_id;
|
||
if (!pickingMap.has(key)) {
|
||
pickingMap.set(key, []);
|
||
}
|
||
pickingMap.get(key).push({
|
||
space_id: row.space_id,
|
||
space_name: row.space_name,
|
||
storage_id: row.storage_id,
|
||
quantity: row.quantity,
|
||
status: row.status,
|
||
});
|
||
|
||
// 按库位维度平铺 picking 记录,并附带商品库存信息
|
||
const orderItem = orderItemMap.get(row.order_item_id);
|
||
if (orderItem) {
|
||
const stockId = Number(orderItem.stock_id || 0);
|
||
const stockWarehouse = stockMap.get(stockId);
|
||
if (stockWarehouse) {
|
||
storageItems.push({
|
||
order_item_id: row.order_item_id,
|
||
space_id: row.space_id,
|
||
space_name: row.space_name,
|
||
storage_id: row.storage_id,
|
||
quantity: row.quantity,
|
||
status: row.status,
|
||
stock_id: stockId,
|
||
item_code: stockWarehouse.item_code,
|
||
item_name: stockWarehouse.item_name,
|
||
sku_property: stockWarehouse.sku_property,
|
||
stock_unit: stockWarehouse.stock_unit,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
const orderItemsWithPicking = orderItemsWithImages.map(item => ({
|
||
...item,
|
||
picking_locations: pickingMap.get(item.order_item_id) || [],
|
||
}));
|
||
|
||
const expresses = await this.getOrderExpressesByOrderId(orderId, order);
|
||
|
||
return {
|
||
detail: order,
|
||
items: orderItemsWithPicking,
|
||
expresses,
|
||
storage_items: storageItems,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 将待处理订单反审回待审核状态。
|
||
* @param {Object} data 请求体。
|
||
* @return {Promise<Object>} 更新后的订单信息。
|
||
*/
|
||
async reverseReviewOrder(data = {}) {
|
||
const requestData = this.isPlainObject(data) ? data : {};
|
||
const warehouseId = this.getWarehouseId();
|
||
const orderIds = this.normalizeOrderIds(requestData);
|
||
|
||
if (orderIds.length === 0) {
|
||
throw new Error('订单ID不能为空');
|
||
}
|
||
|
||
const model = await this.getOrderModel('order', warehouseId);
|
||
const where = this.buildOrderWhere(orderIds, warehouseId);
|
||
const step = this.resolveReviewStep('none');
|
||
const now = new Date();
|
||
const canUseTransaction = this.ctx.model && typeof this.ctx.model.transaction === 'function';
|
||
const transaction = canUseTransaction ? await this.ctx.model.transaction() : null;
|
||
const dbQueryOptions = transaction ? { transaction } : {};
|
||
|
||
try {
|
||
const targetOrders = await model.findAll({
|
||
attributes: [ 'id', 'wave_id', 'wave_no' ],
|
||
where,
|
||
raw: true,
|
||
...dbQueryOptions,
|
||
});
|
||
|
||
if (!Array.isArray(targetOrders) || targetOrders.length === 0) {
|
||
throw new Error('订单不存在或不属于当前仓库');
|
||
}
|
||
|
||
const targetOrderIds = targetOrders
|
||
.map(order => Number(order && order.id || 0))
|
||
.filter(id => Number.isInteger(id) && id > 0);
|
||
|
||
await this.assertOrdersWithoutWaybill(targetOrderIds, transaction);
|
||
|
||
const affectedWaveIds = [ ...new Set(targetOrders
|
||
.map(order => Number(order && order.wave_id || 0))
|
||
.filter(waveId => Number.isInteger(waveId) && waveId > 0)) ];
|
||
|
||
const updateValues = {
|
||
inspection_status: 'none',
|
||
step,
|
||
updated_at: now,
|
||
};
|
||
|
||
if (affectedWaveIds.length > 0) {
|
||
updateValues.wave_id = 0;
|
||
updateValues.wave_no = '';
|
||
}
|
||
|
||
const updateResult = await model.update(updateValues, {
|
||
where,
|
||
...dbQueryOptions,
|
||
});
|
||
|
||
const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0);
|
||
if (affectedRows <= 0) {
|
||
throw new Error('订单不存在或不属于当前仓库');
|
||
}
|
||
|
||
if (affectedWaveIds.length > 0) {
|
||
await this.syncWavesAfterReverseReview({
|
||
warehouseId,
|
||
waveIds: affectedWaveIds,
|
||
orderModel: model,
|
||
transaction: transaction || undefined,
|
||
});
|
||
}
|
||
|
||
const updatedOrders = await model.findAll({
|
||
where,
|
||
raw: true,
|
||
...dbQueryOptions,
|
||
});
|
||
|
||
if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) {
|
||
throw new Error('订单不存在或不属于当前仓库');
|
||
}
|
||
|
||
if (transaction) {
|
||
await transaction.commit();
|
||
}
|
||
|
||
const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ]));
|
||
const normalizedOrders = orderIds
|
||
.map(orderId => orderMap.get(orderId))
|
||
.filter(Boolean)
|
||
.map(order => ({
|
||
id: order.id,
|
||
inspection_status: order.inspection_status,
|
||
step: Number(order.step ?? step),
|
||
updated_at: order.updated_at,
|
||
}));
|
||
|
||
if (normalizedOrders.length === 0) {
|
||
throw new Error('订单不存在或不属于当前仓库');
|
||
}
|
||
|
||
const firstOrder = normalizedOrders[0];
|
||
return {
|
||
id: firstOrder.id,
|
||
inspection_status: firstOrder.inspection_status,
|
||
step: firstOrder.step,
|
||
updated_at: firstOrder.updated_at,
|
||
updated_count: affectedRows,
|
||
ids: normalizedOrders.map(order => order.id),
|
||
};
|
||
} catch (error) {
|
||
if (transaction) {
|
||
await transaction.rollback();
|
||
}
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 校验订单是否已分配运单号。
|
||
*
|
||
* 若任一订单存在非空运单号,直接抛出业务异常,阻止反审。
|
||
*
|
||
* @param {Array<number>} orderIds 订单ID集合。
|
||
* @param {Object} transaction Sequelize 事务对象。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async assertOrdersWithoutWaybill(orderIds = [], transaction) {
|
||
const normalizedOrderIds = Array.isArray(orderIds)
|
||
? orderIds
|
||
.map(orderId => Number(orderId || 0))
|
||
.filter(orderId => Number.isInteger(orderId) && orderId > 0)
|
||
: [];
|
||
|
||
if (normalizedOrderIds.length === 0) {
|
||
return;
|
||
}
|
||
|
||
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
|
||
if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') {
|
||
return;
|
||
}
|
||
|
||
const expressRows = await orderExpressModel.findAll({
|
||
attributes: [ 'order_id', 'waybill_code' ],
|
||
where: {
|
||
order_id: normalizedOrderIds,
|
||
},
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
|
||
const assignedOrderIds = [ ...new Set((Array.isArray(expressRows) ? expressRows : [])
|
||
.filter(row => String(row && row.waybill_code || '').trim())
|
||
.map(row => Number(row && row.order_id || 0))
|
||
.filter(orderId => Number.isInteger(orderId) && orderId > 0)) ];
|
||
|
||
if (assignedOrderIds.length > 0) {
|
||
const displayOrderIds = assignedOrderIds.slice(0, 10).join(',');
|
||
throw new Error(`订单[${displayOrderIds}]已分配运单号,禁止反审`);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 反审后同步波次统计与索引。
|
||
*
|
||
* 同一事务内重建目标波次索引,并回写波次总单量/处理量。
|
||
*
|
||
* @param {Object} params 同步参数。
|
||
* @param {number|string} params.warehouseId 仓库ID。
|
||
* @param {Array<number|string>} params.waveIds 受影响波次ID集合。
|
||
* @param {Object} params.orderModel 订单模型。
|
||
* @param {Object} params.transaction Sequelize 事务对象。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async syncWavesAfterReverseReview({ warehouseId, waveIds, orderModel, transaction } = {}) {
|
||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||
const normalizedWaveIds = Array.isArray(waveIds)
|
||
? [ ...new Set(waveIds
|
||
.map(waveId => Number(waveId || 0))
|
||
.filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]
|
||
: [];
|
||
|
||
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0 || normalizedWaveIds.length === 0) {
|
||
return;
|
||
}
|
||
|
||
const waveService = this.service.systemMethods.order.wave;
|
||
const remainingCountMap = await waveService.replaceOrderWaveIndexByWaveIds({
|
||
warehouseId: normalizedWarehouseId,
|
||
waveIds: normalizedWaveIds,
|
||
orderModel,
|
||
transaction,
|
||
});
|
||
|
||
const updatedWaveIds = [];
|
||
const emptiedWaveIds = [];
|
||
for (const waveId of normalizedWaveIds) {
|
||
const remainingCount = Number(remainingCountMap.get(waveId) || 0);
|
||
if (remainingCount > 0) {
|
||
updatedWaveIds.push(waveId);
|
||
} else {
|
||
emptiedWaveIds.push(waveId);
|
||
}
|
||
}
|
||
|
||
for (const waveId of updatedWaveIds) {
|
||
const remainingCount = Number(remainingCountMap.get(waveId) || 0);
|
||
const updateWaveSql = `
|
||
UPDATE wms_wave_batch
|
||
SET total_orders = :remainingCount,
|
||
processed_orders = LEAST(processed_orders, :remainingCount),
|
||
update_time = NOW()
|
||
WHERE warehouse_id = :warehouseId
|
||
AND wave_id = :waveId
|
||
`;
|
||
|
||
await this.ctx.model.query(updateWaveSql, {
|
||
replacements: {
|
||
warehouseId: normalizedWarehouseId,
|
||
waveId,
|
||
remainingCount,
|
||
},
|
||
transaction,
|
||
});
|
||
}
|
||
|
||
if (emptiedWaveIds.length > 0) {
|
||
const emptyWaveSql = `
|
||
UPDATE wms_wave_batch
|
||
SET total_orders = 0,
|
||
processed_orders = 0,
|
||
wave_status = -1,
|
||
update_time = NOW()
|
||
WHERE warehouse_id = :warehouseId
|
||
AND wave_id IN (:waveIds)
|
||
`;
|
||
|
||
await this.ctx.model.query(emptyWaveSql, {
|
||
replacements: {
|
||
warehouseId: normalizedWarehouseId,
|
||
waveIds: emptiedWaveIds,
|
||
},
|
||
transaction,
|
||
});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 将待处理订单批量分配储位。
|
||
*
|
||
* 该入口仅接受订单相关入参,不再接受 warehouse_id / warehouseId;
|
||
* 仓库上下文统一取当前登录用户的 store_id。
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @return {Promise<Object>} 统一 success 包装的受理结果,包含 request_id 与 warehouse_id。
|
||
*/
|
||
async allocateStorage(data = {}) {
|
||
console.log('[PendingOrderService.allocateStorage] 原始入参', data);
|
||
|
||
const requestData = this.isPlainObject(data) ? data : {};
|
||
const forbiddenWarehouseKeys = [ 'warehouse_id', 'warehouseId' ].filter(key => Object.prototype.hasOwnProperty.call(requestData, key));
|
||
|
||
if (forbiddenWarehouseKeys.length > 0) {
|
||
console.log('[PendingOrderService.allocateStorage] 检测到禁止传入的仓库字段', {
|
||
forbiddenWarehouseKeys,
|
||
requestData,
|
||
});
|
||
throw new Error('待处理订单储位分配接口不再接受 warehouse_id / warehouseId,请使用当前用户仓库上下文');
|
||
}
|
||
|
||
const normalizedData = {
|
||
allow_storage_location: requestData.allow_storage_location
|
||
?? requestData.allowStorageLocation
|
||
?? requestData.is_allow_storage
|
||
?? requestData.isAllowStorage,
|
||
order_ids: requestData.order_ids
|
||
?? requestData.orderIds
|
||
?? requestData.ids
|
||
?? requestData.order_id
|
||
?? requestData.orderId
|
||
?? requestData.id,
|
||
};
|
||
|
||
console.log('[PendingOrderService.allocateStorage] 归一化入参', normalizedData);
|
||
const warehouseId = this.getWarehouseId();
|
||
const timestamp = Date.now();
|
||
const randomToken = Math.random().toString(36).slice(2, 10);
|
||
const requestId = `storage_alloc_${warehouseId ?? 'unknown'}_${timestamp}_${randomToken}`;
|
||
const taskProgressState = {
|
||
total_count: 0,
|
||
processed_count: 0,
|
||
progress: 0,
|
||
};
|
||
|
||
await this.setAllocateStorageTaskProgress(requestId, {
|
||
status: 'submitted',
|
||
total_count: taskProgressState.total_count,
|
||
processed_count: taskProgressState.processed_count,
|
||
progress: taskProgressState.progress,
|
||
});
|
||
|
||
setImmediate(async () => {
|
||
try {
|
||
await this.setAllocateStorageTaskProgress(requestId, {
|
||
status: 'running',
|
||
total_count: taskProgressState.total_count,
|
||
processed_count: taskProgressState.processed_count,
|
||
progress: taskProgressState.progress,
|
||
});
|
||
|
||
const allocationRequest = {
|
||
allow_storage_location: normalizedData.allow_storage_location,
|
||
order_ids: normalizedData.order_ids,
|
||
progress_callback: async progressPayload => {
|
||
const safeProgressPayload = this.isPlainObject(progressPayload) ? progressPayload : {};
|
||
const totalCount = this.normalizeAllocateStorageTaskCount(
|
||
safeProgressPayload.total_count
|
||
?? safeProgressPayload.totalCount
|
||
?? taskProgressState.total_count,
|
||
taskProgressState.total_count
|
||
);
|
||
const processedCount = this.normalizeAllocateStorageTaskCount(
|
||
safeProgressPayload.processed_count
|
||
?? safeProgressPayload.processedCount
|
||
?? taskProgressState.processed_count,
|
||
taskProgressState.processed_count
|
||
);
|
||
|
||
taskProgressState.total_count = Math.max(taskProgressState.total_count, totalCount);
|
||
taskProgressState.processed_count = Math.min(
|
||
taskProgressState.total_count,
|
||
Math.max(taskProgressState.processed_count, processedCount)
|
||
);
|
||
taskProgressState.progress = this.normalizeAllocateStorageTaskProgress(
|
||
safeProgressPayload.progress,
|
||
'running',
|
||
taskProgressState.total_count,
|
||
taskProgressState.processed_count
|
||
);
|
||
|
||
await this.setAllocateStorageTaskProgress(requestId, {
|
||
status: 'running',
|
||
total_count: taskProgressState.total_count,
|
||
processed_count: taskProgressState.processed_count,
|
||
progress: taskProgressState.progress,
|
||
});
|
||
},
|
||
};
|
||
|
||
console.log('[PendingOrderService.allocateStorage] 后台开始处理储位分配', {
|
||
request_id: requestId,
|
||
allocationRequest: {
|
||
allow_storage_location: allocationRequest.allow_storage_location,
|
||
order_ids: allocationRequest.order_ids,
|
||
},
|
||
});
|
||
const result = await this.service.systems.orderStorageAllocation.allocateStorage(allocationRequest);
|
||
|
||
if (taskProgressState.total_count > 0) {
|
||
taskProgressState.processed_count = taskProgressState.total_count;
|
||
}
|
||
taskProgressState.progress = 100;
|
||
|
||
await this.setAllocateStorageTaskProgress(requestId, {
|
||
status: 'success',
|
||
total_count: taskProgressState.total_count,
|
||
processed_count: taskProgressState.processed_count,
|
||
progress: taskProgressState.progress,
|
||
result,
|
||
});
|
||
|
||
// 写操作日志(不影响主流程)
|
||
try {
|
||
const operator = this.getOrderLogOperator();
|
||
const warehouseId = this.getWarehouseId();
|
||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||
const orderIds = Array.isArray(normalizedData.order_ids)
|
||
? normalizedData.order_ids
|
||
: (normalizedData.order_ids ? [ normalizedData.order_ids ] : []);
|
||
|
||
// 从 result 中提取分配结果信息
|
||
const resultData = result && result.data ? result.data : (result || {});
|
||
const allocatedIds = Array.isArray(resultData.allocated_order_ids) ? resultData.allocated_order_ids : [];
|
||
const shortageIds = Array.isArray(resultData.shortage_order_ids) ? resultData.shortage_order_ids : [];
|
||
const skippedList = Array.isArray(resultData.skipped_orders) ? resultData.skipped_orders : [];
|
||
const allocatedSet = new Set(allocatedIds.map(Number));
|
||
const shortageSet = new Set(shortageIds.map(Number));
|
||
const skippedMap = new Map(
|
||
skippedList
|
||
.filter(item => Number(item && item.order_id) > 0)
|
||
.map(item => [ Number(item.order_id), item ])
|
||
);
|
||
|
||
if (orderIds.length > 0 && this.ctx.model && this.ctx.model.OperationLog) {
|
||
const operatorInfo = operator || {};
|
||
const operatorId = operatorInfo.id != null ? String(operatorInfo.id) : null;
|
||
const operatorName = operatorInfo.name ? String(operatorInfo.name) : 'system';
|
||
const now = new Date();
|
||
|
||
const logRows = orderIds.map(orderId => {
|
||
const oid = Number(orderId);
|
||
const allocated = allocatedSet.has(oid);
|
||
const shortage = shortageSet.has(oid);
|
||
const skippedItem = skippedMap.get(oid) || null;
|
||
const skippedReason = skippedItem ? String(skippedItem.skipped_reason || '').trim() : '';
|
||
const skippedMessage = skippedReason === 'intercepted'
|
||
? '储位分配跳过:订单已拦截'
|
||
: (skippedReason ? `储位分配跳过:${skippedReason}` : '');
|
||
const operationCode = allocated
|
||
? 'ORDER_STORAGE_ALLOCATE_SUCCESS'
|
||
: shortage
|
||
? 'ORDER_STORAGE_ALLOCATE_FAILED'
|
||
: skippedItem
|
||
? 'ORDER_STORAGE_ALLOCATE_FAILED'
|
||
: 'ORDER_STORAGE_ALLOCATE_SUCCESS';
|
||
const msg = allocated
|
||
? '储位分配成功'
|
||
: shortage
|
||
? '储位分配失败:库存不足'
|
||
: skippedMessage || '储位分配完成';
|
||
return {
|
||
business_type: 'order',
|
||
business_id: String(oid),
|
||
operation_code: operationCode,
|
||
operator_id: operatorId,
|
||
operator_name: operatorName,
|
||
external_log_type: 'NONE',
|
||
warehouse_id: logWarehouseId || null,
|
||
platform_code: 'SYSTEM',
|
||
message: msg,
|
||
created_at: now,
|
||
};
|
||
}).filter(row => Number(row.business_id) > 0);
|
||
|
||
if (logRows.length > 0) {
|
||
await this.ctx.model.OperationLog.bulkCreate(logRows);
|
||
}
|
||
}
|
||
} catch (logErr) {
|
||
this.ctx.logger.warn('[PendingOrderService.allocateStorage] 写入成功操作日志失败,不影响业务', logErr);
|
||
}
|
||
console.log('[PendingOrderService.allocateStorage] 后台储位分配处理成功', {
|
||
request_id: requestId,
|
||
normalizedData,
|
||
result,
|
||
});
|
||
} catch (error) {
|
||
await this.setAllocateStorageTaskProgress(requestId, {
|
||
status: 'failed',
|
||
total_count: taskProgressState.total_count,
|
||
processed_count: taskProgressState.processed_count,
|
||
progress: taskProgressState.progress,
|
||
error: error && error.message ? error.message : String(error),
|
||
});
|
||
|
||
// 写操作日志(不影响主流程)
|
||
try {
|
||
const operator = this.getOrderLogOperator();
|
||
const warehouseId = this.getWarehouseId();
|
||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||
const orderIds = Array.isArray(normalizedData.order_ids)
|
||
? normalizedData.order_ids
|
||
: (normalizedData.order_ids ? [ normalizedData.order_ids ] : []);
|
||
|
||
if (orderIds.length > 0 && this.ctx.model && this.ctx.model.OperationLog) {
|
||
const operatorInfo = operator || {};
|
||
const operatorId = operatorInfo.id != null ? String(operatorInfo.id) : null;
|
||
const operatorName = operatorInfo.name ? String(operatorInfo.name) : 'system';
|
||
const errorMsg = error && error.message ? error.message : String(error);
|
||
const now = new Date();
|
||
|
||
const logRows = orderIds.map(orderId => {
|
||
const oid = Number(orderId);
|
||
return {
|
||
business_type: 'order',
|
||
business_id: String(oid),
|
||
operation_code: 'ORDER_STORAGE_ALLOCATE_FAILED',
|
||
operator_id: operatorId,
|
||
operator_name: operatorName,
|
||
external_log_type: 'NONE',
|
||
warehouse_id: logWarehouseId || null,
|
||
platform_code: 'SYSTEM',
|
||
message: `储位分配失败:${errorMsg}`,
|
||
created_at: now,
|
||
};
|
||
}).filter(row => Number(row.business_id) > 0);
|
||
|
||
if (logRows.length > 0) {
|
||
await this.ctx.model.OperationLog.bulkCreate(logRows);
|
||
}
|
||
}
|
||
} catch (logErr) {
|
||
this.ctx.logger.warn('[PendingOrderService.allocateStorage] 写入失败操作日志失败,不影响业务', logErr);
|
||
}
|
||
console.log('[PendingOrderService.allocateStorage] 后台储位分配处理异常', {
|
||
request_id: requestId,
|
||
normalizedData,
|
||
error_message: error?.message,
|
||
error_stack: error?.stack,
|
||
});
|
||
}
|
||
});
|
||
|
||
return this.success('ok', {
|
||
request_id: requestId,
|
||
warehouse_id: warehouseId,
|
||
message: '请求已提交,后端处理中',
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 查询待处理订单储位分配任务进度。
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @param {string} data.request_id 请求ID(下划线写法)。
|
||
* @param {string} data.requestId 请求ID(驼峰写法)。
|
||
* @return {Promise<Object>} 统一响应,包含任务状态或结果。
|
||
*/
|
||
async allocateStorageProgress(data = {}) {
|
||
const requestId = this.normalizeAllocateStorageRequestId(data);
|
||
if (!requestId) {
|
||
return this.fail('request_id 参数不能为空', {}, 400);
|
||
}
|
||
|
||
const cachedProgress = await this.getAllocateStorageTaskProgress(requestId);
|
||
if (!cachedProgress) {
|
||
return this.success('ok', {
|
||
request_id: requestId,
|
||
status: 'not_found',
|
||
progress: ALLOCATE_STORAGE_PROGRESS_MAP.not_found,
|
||
total_count: 0,
|
||
processed_count: 0,
|
||
});
|
||
}
|
||
|
||
const normalizedStatus = String(cachedProgress.status || 'unknown').trim() || 'unknown';
|
||
const normalizedCounts = this.normalizeAllocateStorageTaskCounts(cachedProgress, normalizedStatus);
|
||
const normalizedProgress = this.normalizeAllocateStorageTaskProgress(
|
||
cachedProgress.progress,
|
||
normalizedStatus,
|
||
normalizedCounts.total_count,
|
||
normalizedCounts.processed_count
|
||
);
|
||
|
||
return this.success('ok', {
|
||
request_id: requestId,
|
||
...cachedProgress,
|
||
status: normalizedStatus,
|
||
progress: normalizedProgress,
|
||
total_count: normalizedCounts.total_count,
|
||
processed_count: normalizedCounts.processed_count,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 规范任务进度值,兼容历史缓存中缺失 progress 字段的场景。
|
||
*
|
||
* @param {number|string|null|undefined} progress 原始进度值。
|
||
* @param {string} status 任务状态。
|
||
* @param {number} totalCount 总任务数。
|
||
* @param {number} processedCount 已处理任务数。
|
||
* @return {number} 归一化后的进度百分比(0-100)。
|
||
*/
|
||
normalizeAllocateStorageTaskProgress(progress, status = 'unknown', totalCount = 0, processedCount = 0) {
|
||
const parsed = Number(progress);
|
||
if (Number.isFinite(parsed)) {
|
||
return Math.min(100, Math.max(0, Math.round(parsed)));
|
||
}
|
||
|
||
if (String(status || 'unknown').trim() === 'success') {
|
||
return 100;
|
||
}
|
||
|
||
const normalizedTotalCount = this.normalizeAllocateStorageTaskCount(totalCount, 0);
|
||
const normalizedProcessedCount = this.normalizeAllocateStorageTaskCount(processedCount, 0);
|
||
if (normalizedTotalCount > 0) {
|
||
return Math.round(Math.min(normalizedTotalCount, normalizedProcessedCount) / normalizedTotalCount * 100);
|
||
}
|
||
|
||
const normalizedStatus = String(status || 'unknown').trim() || 'unknown';
|
||
if (Object.prototype.hasOwnProperty.call(ALLOCATE_STORAGE_PROGRESS_MAP, normalizedStatus)) {
|
||
return ALLOCATE_STORAGE_PROGRESS_MAP[normalizedStatus];
|
||
}
|
||
|
||
return ALLOCATE_STORAGE_PROGRESS_MAP.unknown;
|
||
}
|
||
|
||
/**
|
||
* 规范任务计数字段。
|
||
*
|
||
* @param {number|string|null|undefined} value 原始计数值。
|
||
* @param {number} defaultValue 默认值。
|
||
* @return {number} 归一化后的非负整数。
|
||
*/
|
||
normalizeAllocateStorageTaskCount(value, defaultValue = 0) {
|
||
const parsed = Number(value);
|
||
if (!Number.isFinite(parsed)) {
|
||
return Math.max(0, Math.round(Number(defaultValue) || 0));
|
||
}
|
||
|
||
return Math.max(0, Math.round(parsed));
|
||
}
|
||
|
||
/**
|
||
* 规范任务总量与处理量,兼容历史缓存与别名字段。
|
||
*
|
||
* @param {Object} payload 原始缓存载荷。
|
||
* @param {string} status 任务状态。
|
||
* @return {{ total_count: number, processed_count: number }} 归一化后的计数信息。
|
||
*/
|
||
normalizeAllocateStorageTaskCounts(payload = {}, status = 'unknown') {
|
||
const safePayload = this.isPlainObject(payload) ? payload : {};
|
||
const totalCount = this.normalizeAllocateStorageTaskCount(
|
||
safePayload.total_count
|
||
?? safePayload.totalCount
|
||
?? safePayload.total,
|
||
0
|
||
);
|
||
let processedCount = this.normalizeAllocateStorageTaskCount(
|
||
safePayload.processed_count
|
||
?? safePayload.processedCount
|
||
?? safePayload.processed,
|
||
0
|
||
);
|
||
|
||
if (totalCount > 0) {
|
||
processedCount = Math.min(totalCount, processedCount);
|
||
} else {
|
||
processedCount = 0;
|
||
}
|
||
|
||
if (String(status || 'unknown').trim() === 'success' && totalCount > 0) {
|
||
processedCount = totalCount;
|
||
}
|
||
|
||
return {
|
||
total_count: totalCount,
|
||
processed_count: processedCount,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 规范待处理订单储位分配请求ID。
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @param {string} data.request_id 请求ID(下划线写法)。
|
||
* @param {string} data.requestId 请求ID(驼峰写法)。
|
||
* @return {string} 归一化后的请求ID。
|
||
*/
|
||
normalizeAllocateStorageRequestId(data = {}) {
|
||
const normalizedData = this.isPlainObject(data) ? data : {};
|
||
return String(normalizedData.request_id || normalizedData.requestId || '').trim();
|
||
}
|
||
|
||
/**
|
||
* 获取待处理订单储位分配任务缓存键。
|
||
*
|
||
* @param {string} requestId 请求ID。
|
||
* @return {string} 缓存键。
|
||
*/
|
||
getAllocateStorageTaskCacheKey(requestId = '') {
|
||
const normalizedRequestId = String(requestId || '').trim();
|
||
if (!normalizedRequestId) {
|
||
return '';
|
||
}
|
||
|
||
return `${ALLOCATE_STORAGE_TASK_CACHE_KEY_PREFIX}${normalizedRequestId}`;
|
||
}
|
||
|
||
/**
|
||
* 写入待处理订单储位分配任务进度。
|
||
*
|
||
* @param {string} requestId 请求ID。
|
||
* @param {Object} payload 任务状态与结果。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async setAllocateStorageTaskProgress(requestId = '', payload = {}) {
|
||
const cacheKey = this.getAllocateStorageTaskCacheKey(requestId);
|
||
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
|
||
return;
|
||
}
|
||
|
||
const safePayload = this.isPlainObject(payload) ? payload : {};
|
||
const normalizedStatus = String(safePayload.status || 'unknown').trim() || 'unknown';
|
||
const normalizedCounts = this.normalizeAllocateStorageTaskCounts(safePayload, normalizedStatus);
|
||
const normalizedProgress = this.normalizeAllocateStorageTaskProgress(
|
||
safePayload.progress,
|
||
normalizedStatus,
|
||
normalizedCounts.total_count,
|
||
normalizedCounts.processed_count
|
||
);
|
||
const progressPayload = {
|
||
...safePayload,
|
||
status: normalizedStatus,
|
||
progress: normalizedProgress,
|
||
total_count: normalizedCounts.total_count,
|
||
processed_count: normalizedCounts.processed_count,
|
||
request_id: String(requestId || '').trim(),
|
||
update_time: Date.now(),
|
||
};
|
||
|
||
try {
|
||
await this.app.setCacheAsync(cacheKey, progressPayload, ALLOCATE_STORAGE_TASK_CACHE_TTL_SECONDS);
|
||
} catch (error) {
|
||
this.ctx.logger.warn('[pendingOrder.allocateStorage] 写入任务进度缓存失败: %s', error && error.message ? error.message : error);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 读取待处理订单储位分配任务进度。
|
||
*
|
||
* @param {string} requestId 请求ID。
|
||
* @return {Promise<Object|null>} 任务缓存结果。
|
||
*/
|
||
async getAllocateStorageTaskProgress(requestId = '') {
|
||
const cacheKey = this.getAllocateStorageTaskCacheKey(requestId);
|
||
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
|
||
return null;
|
||
}
|
||
|
||
try {
|
||
const cached = await this.app.getCacheAsync(cacheKey);
|
||
if (!this.isPlainObject(cached)) {
|
||
return null;
|
||
}
|
||
|
||
return cached;
|
||
} catch (error) {
|
||
this.ctx.logger.warn('[pendingOrder.allocateStorage] 读取任务进度缓存失败: %s', error && error.message ? error.message : error);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
// ========== allocateExpressCode 异步任务进度缓存工具方法 ==========
|
||
|
||
/**
|
||
* 获取快递分配任务缓存键。
|
||
*
|
||
* @param {string} taskId 任务ID。
|
||
* @return {string} 缓存键。
|
||
*/
|
||
getAllocateExpressTaskCacheKey(taskId = '') {
|
||
const normalizedTaskId = String(taskId || '').trim();
|
||
if (!normalizedTaskId) {
|
||
return '';
|
||
}
|
||
return `${ALLOCATE_EXPRESS_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
|
||
}
|
||
|
||
/**
|
||
* 规范快递分配任务ID。
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @return {string} 归一化后的任务ID。
|
||
*/
|
||
normalizeAllocateExpressTaskId(data = {}) {
|
||
const normalizedData = this.isPlainObject(data) ? data : {};
|
||
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
|
||
}
|
||
|
||
/**
|
||
* 写入快递分配任务进度。
|
||
*
|
||
* @param {string} taskId 任务ID。
|
||
* @param {Object} payload 任务状态与结果。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async setAllocateExpressTaskProgress(taskId = '', payload = {}) {
|
||
const cacheKey = this.getAllocateExpressTaskCacheKey(taskId);
|
||
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
|
||
return;
|
||
}
|
||
|
||
const safePayload = this.isPlainObject(payload) ? payload : {};
|
||
const progressPayload = {
|
||
task_id: String(taskId || '').trim(),
|
||
status: String(safePayload.status || 'unknown').trim(),
|
||
progress: Number(safePayload.progress || 0),
|
||
message: String(safePayload.message || ''),
|
||
result: safePayload.result || null,
|
||
error: String(safePayload.error || ''),
|
||
update_time: Date.now(),
|
||
};
|
||
|
||
try {
|
||
await this.app.setCacheAsync(cacheKey, progressPayload, ALLOCATE_EXPRESS_TASK_CACHE_TTL_SECONDS);
|
||
} catch (error) {
|
||
this.ctx.logger.warn('[pendingOrder.allocateExpressCode] 写入任务进度缓存失败: %s', error && error.message ? error.message : error);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 读取快递分配任务进度。
|
||
*
|
||
* @param {string} taskId 任务ID。
|
||
* @return {Promise<Object|null>} 任务缓存结果。
|
||
*/
|
||
async getAllocateExpressTaskProgress(taskId = '') {
|
||
const cacheKey = this.getAllocateExpressTaskCacheKey(taskId);
|
||
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
|
||
return null;
|
||
}
|
||
|
||
try {
|
||
const cached = await this.app.getCacheAsync(cacheKey);
|
||
if (!this.isPlainObject(cached)) {
|
||
return null;
|
||
}
|
||
return cached;
|
||
} catch (error) {
|
||
this.ctx.logger.warn('[pendingOrder.allocateExpressCode] 读取任务进度缓存失败: %s', error && error.message ? error.message : error);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
// ========== syncOrderIds 异步任务进度缓存工具方法 ==========
|
||
|
||
/**
|
||
* 获取订单同步任务缓存键。
|
||
*
|
||
* @param {string} requestId 请求ID。
|
||
* @return {string} 缓存键。
|
||
*/
|
||
getSyncOrderIdsTaskCacheKey(requestId = '') {
|
||
const normalizedRequestId = String(requestId || '').trim();
|
||
if (!normalizedRequestId) {
|
||
return '';
|
||
}
|
||
|
||
return `${SYNC_ORDER_IDS_TASK_CACHE_KEY_PREFIX}${normalizedRequestId}`;
|
||
}
|
||
|
||
/**
|
||
* 规范订单同步任务请求ID。
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @return {string} 归一化后的请求ID。
|
||
*/
|
||
normalizeSyncOrderIdsRequestId(data = {}) {
|
||
const normalizedData = this.isPlainObject(data) ? data : {};
|
||
return String(normalizedData.request_id || normalizedData.requestId || '').trim();
|
||
}
|
||
|
||
/**
|
||
* 写入订单同步任务进度。
|
||
*
|
||
* @param {string} requestId 请求ID。
|
||
* @param {Object} payload 任务状态与结果。
|
||
* @return {Promise<void>}
|
||
*/
|
||
async setSyncOrderIdsTaskProgress(requestId = '', payload = {}) {
|
||
const cacheKey = this.getSyncOrderIdsTaskCacheKey(requestId);
|
||
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
|
||
return;
|
||
}
|
||
|
||
const safePayload = this.isPlainObject(payload) ? payload : {};
|
||
const progressPayload = {
|
||
...safePayload,
|
||
request_id: String(requestId || '').trim(),
|
||
update_time: Date.now(),
|
||
};
|
||
|
||
try {
|
||
await this.app.setCacheAsync(cacheKey, progressPayload, SYNC_ORDER_IDS_TASK_CACHE_TTL_SECONDS);
|
||
} catch (error) {
|
||
this.ctx.logger.warn('[pendingOrder.syncOrderIds] 写入任务进度缓存失败: %s', error && error.message ? error.message : error);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 读取订单同步任务进度。
|
||
*
|
||
* @param {string} requestId 请求ID。
|
||
* @return {Promise<Object|null>} 任务缓存结果。
|
||
*/
|
||
async getSyncOrderIdsTaskProgress(requestId = '') {
|
||
const cacheKey = this.getSyncOrderIdsTaskCacheKey(requestId);
|
||
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
|
||
return null;
|
||
}
|
||
|
||
try {
|
||
const cached = await this.app.getCacheAsync(cacheKey);
|
||
if (!this.isPlainObject(cached)) {
|
||
return null;
|
||
}
|
||
|
||
return cached;
|
||
} catch (error) {
|
||
this.ctx.logger.warn('[pendingOrder.syncOrderIds] 读取任务进度缓存失败: %s', error && error.message ? error.message : error);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
// ========== syncOrderIds 异步任务进度缓存工具方法结束 ==========
|
||
|
||
/**
|
||
* 将待处理订单批量取消储位分配。
|
||
*
|
||
* 该入口仅接受订单 ID 相关入参,不再接受 allow_storage_location 相关字段或 warehouse_id / warehouseId;
|
||
* 仓库上下文统一取当前登录用户的 store_id。
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @return {Promise<Object>} 统一 success 包装的储位取消分配结果。
|
||
*/
|
||
async cancelAllocateStorage(data = {}) {
|
||
const requestData = this.isPlainObject(data) ? data : {};
|
||
const forbiddenWarehouseKeys = [ 'warehouse_id', 'warehouseId' ].filter(key => Object.prototype.hasOwnProperty.call(requestData, key));
|
||
|
||
if (forbiddenWarehouseKeys.length > 0) {
|
||
console.log('[PendingOrderService.cancelAllocateStorage] 检测到禁止传入的仓库字段', {
|
||
forbiddenWarehouseKeys,
|
||
});
|
||
throw new Error('待处理订单储位取消分配接口不再接受 warehouse_id / warehouseId,请使用当前用户仓库上下文');
|
||
}
|
||
|
||
const normalizedData = {
|
||
order_ids: requestData.order_ids
|
||
?? requestData.orderIds
|
||
?? requestData.ids
|
||
?? requestData.order_id
|
||
?? requestData.orderId
|
||
?? requestData.id,
|
||
};
|
||
|
||
console.log('[PendingOrderService.cancelAllocateStorage] 归一化入参', normalizedData);
|
||
|
||
// 前置校验:拣货完成的订单不允许取消分配储位
|
||
const rawCancelOrderIds = Array.isArray(normalizedData.order_ids)
|
||
? normalizedData.order_ids
|
||
: (normalizedData.order_ids != null ? [ normalizedData.order_ids ] : []);
|
||
const cancelOrderIds = [ ...new Set(rawCancelOrderIds.map(id => Number(id)).filter(id => Number.isFinite(id) && id > 0)) ];
|
||
|
||
if (cancelOrderIds.length > 0) {
|
||
const model = await this.getOrderModel('order', this.getWarehouseId());
|
||
const where = this.buildOrderWhere(cancelOrderIds, this.getWarehouseId());
|
||
const orders = await model.findAll({
|
||
where,
|
||
attributes: [ 'id', 'pick_status' ],
|
||
raw: true,
|
||
});
|
||
|
||
const pickedOrderIds = (Array.isArray(orders) ? orders : [])
|
||
.filter(o => o.pick_status === 'fin')
|
||
.map(o => Number(o.id));
|
||
|
||
if (pickedOrderIds.length > 0) {
|
||
throw new Error(
|
||
`以下订单已拣货完成,不允许取消分配储位:${pickedOrderIds.join(', ')}`
|
||
);
|
||
}
|
||
}
|
||
|
||
try {
|
||
console.log('[PendingOrderService.cancelAllocateStorage] 调用 orderStorageAllocation.cancelAllocateStorage 前', normalizedData);
|
||
const result = await this.service.systems.orderStorageAllocation.cancelAllocateStorage(normalizedData);
|
||
console.log('[PendingOrderService.cancelAllocateStorage] 调用 orderStorageAllocation.cancelAllocateStorage 成功', result);
|
||
|
||
try {
|
||
if (this.ctx.model && this.ctx.model.OperationLog) {
|
||
const operator = this.getOrderLogOperator() || {};
|
||
const operatorId = operator.id != null ? String(operator.id) : null;
|
||
const operatorName = operator.name ? String(operator.name) : 'system';
|
||
const logWarehouseId = this.getOrderLogWarehouseId(this.getWarehouseId()) || null;
|
||
const resultData = result && result.data ? result.data : {};
|
||
const cancellableOrderIds = Array.isArray(resultData.cancellable_order_ids) ? resultData.cancellable_order_ids : [];
|
||
const now = new Date();
|
||
const logRows = [];
|
||
|
||
for (const orderId of cancellableOrderIds) {
|
||
const normalizedOrderId = Number(orderId);
|
||
if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) {
|
||
continue;
|
||
}
|
||
|
||
logRows.push({
|
||
business_type: 'order',
|
||
business_id: String(normalizedOrderId),
|
||
operation_code: 'ORDER_STORAGE_UNALLOCATE_SUCCESS',
|
||
operator_id: operatorId,
|
||
operator_name: operatorName,
|
||
external_log_type: 'NONE',
|
||
warehouse_id: logWarehouseId,
|
||
platform_code: 'SYSTEM',
|
||
message: '取消储位分配成功',
|
||
created_at: now,
|
||
});
|
||
}
|
||
|
||
if (logRows.length > 0) {
|
||
await this.ctx.model.OperationLog.bulkCreate(logRows);
|
||
}
|
||
}
|
||
} catch (logError) {
|
||
this.ctx.logger.warn('[PendingOrderService.cancelAllocateStorage] 写入取消储位分配日志失败,不影响主流程', logError);
|
||
}
|
||
|
||
return this.success('ok', result);
|
||
} catch (error) {
|
||
try {
|
||
if (this.ctx.model && this.ctx.model.OperationLog) {
|
||
const rawOrderIds = Array.isArray(normalizedData.order_ids)
|
||
? normalizedData.order_ids
|
||
: (normalizedData.order_ids != null ? [ normalizedData.order_ids ] : []);
|
||
const orderIds = [ ...new Set(rawOrderIds.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0)) ];
|
||
|
||
if (orderIds.length > 0) {
|
||
const operator = this.getOrderLogOperator() || {};
|
||
const operatorId = operator.id != null ? String(operator.id) : null;
|
||
const operatorName = operator.name ? String(operator.name) : 'system';
|
||
const logWarehouseId = this.getOrderLogWarehouseId(this.getWarehouseId()) || null;
|
||
const errorMessage = error && error.message ? error.message : String(error);
|
||
const now = new Date();
|
||
const logRows = orderIds.map(orderId => ({
|
||
business_type: 'order',
|
||
business_id: String(orderId),
|
||
operation_code: 'ORDER_STORAGE_UNALLOCATE_FAILED',
|
||
operator_id: operatorId,
|
||
operator_name: operatorName,
|
||
external_log_type: 'NONE',
|
||
warehouse_id: logWarehouseId,
|
||
platform_code: 'SYSTEM',
|
||
message: `取消储位分配失败:${errorMessage}`,
|
||
created_at: now,
|
||
}));
|
||
|
||
await this.ctx.model.OperationLog.bulkCreate(logRows);
|
||
}
|
||
}
|
||
} catch (logError) {
|
||
this.ctx.logger.warn('[PendingOrderService.cancelAllocateStorage] 写入取消储位分配失败日志失败,不影响主流程', logError);
|
||
}
|
||
|
||
console.log('[PendingOrderService.cancelAllocateStorage] 调用 orderStorageAllocation.cancelAllocateStorage 异常', {
|
||
normalizedData,
|
||
error,
|
||
});
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 同步待处理订单(异步模式)。
|
||
*
|
||
* 立即生成 request_id 并返回,后台通过 setImmediate 异步执行实际的订单同步流程。
|
||
* 调用方可通过 syncOrderIdsProgress 接口轮询任务进度与最终结果。
|
||
*
|
||
* 后台处理流程:
|
||
* ① 事务内查询订单 + 校验(SN、快递状态)+ 更新 sync_status='padding' + commit
|
||
* ② 按 create_channel 分组并行派发(QM / MANUAL / API)
|
||
* ③ 单订单失败静默写入 error 状态 + 异常标记,不影响整批结果
|
||
* ④ 写入操作日志 + 更新最终进度
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @param {Array<number|string>|string|number} data.order_ids 订单ID(支持数组、逗号字符串、单个ID,兼容 orderIds/ids 等多种别名)。
|
||
* @return {Promise<Object>} 统一 success 包装,含 request_id。
|
||
*/
|
||
async syncOrderIds(data = {}) {
|
||
const requestData = this.isPlainObject(data) ? data : {};
|
||
const normalizedData = {
|
||
order_ids: requestData.order_ids
|
||
?? requestData.orderIds
|
||
?? requestData.ids
|
||
?? requestData.order_id
|
||
?? requestData.orderId
|
||
?? requestData.id,
|
||
};
|
||
|
||
// 快照 ctx 数据(setImmediate 回调中 ctx 可能已失效)
|
||
const warehouseId = this.getWarehouseId();
|
||
const operator = this.getOrderLogOperator();
|
||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||
|
||
const timestamp = Date.now();
|
||
const randomToken = Math.random().toString(36).slice(2, 10);
|
||
const requestId = `sync_order_${warehouseId ?? 'unknown'}_${timestamp}_${randomToken}`;
|
||
|
||
// 初始化进度:submitted
|
||
await this.setSyncOrderIdsTaskProgress(requestId, {
|
||
status: 'submitted',
|
||
total_count: 0,
|
||
processed_count: 0,
|
||
progress: 0,
|
||
warehouse_id: warehouseId,
|
||
order_ids: normalizedData.order_ids,
|
||
});
|
||
|
||
this.ctx.logger.info('[PendingOrderService.syncOrderIds] 任务已提交', {
|
||
request_id: requestId,
|
||
warehouseId,
|
||
orderCount: Array.isArray(normalizedData.order_ids)
|
||
? normalizedData.order_ids.length
|
||
: (normalizedData.order_ids ? 1 : 0),
|
||
});
|
||
|
||
// 后台异步执行
|
||
setImmediate(async () => {
|
||
try {
|
||
await this.setSyncOrderIdsTaskProgress(requestId, {
|
||
status: 'running',
|
||
total_count: 0,
|
||
processed_count: 0,
|
||
progress: 0,
|
||
warehouse_id: warehouseId,
|
||
});
|
||
|
||
const result = await this.service.systems.orderStorageAllocation.syncOrderIds({
|
||
...normalizedData,
|
||
warehouse_id: warehouseId,
|
||
request_id: requestId,
|
||
});
|
||
|
||
// 最终进度:success(从结果中取真实数量)
|
||
const resultData = result && result.data ? result.data : {};
|
||
const finalTotal = Number(resultData.pending_count || 0);
|
||
const finalProcessed = finalTotal;
|
||
const finalProgress = 100;
|
||
|
||
await this.setSyncOrderIdsTaskProgress(requestId, {
|
||
status: 'success',
|
||
total_count: finalTotal,
|
||
processed_count: finalProcessed,
|
||
progress: finalProgress,
|
||
warehouse_id: warehouseId,
|
||
result,
|
||
});
|
||
|
||
// 静默写操作日志(不影响主流程)
|
||
try {
|
||
const opLogService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog;
|
||
if (opLogService && typeof opLogService.createOperationLogs === 'function') {
|
||
const rawOrderIds = Array.isArray(normalizedData.order_ids)
|
||
? normalizedData.order_ids
|
||
: (normalizedData.order_ids ? [ normalizedData.order_ids ] : []);
|
||
|
||
const resultData = result && result.data ? result.data : {};
|
||
const pendingSet = new Set((resultData.pending_order_ids || []).map(Number));
|
||
const skippedMap = new Map();
|
||
const failedMap = new Map();
|
||
|
||
for (const item of (resultData.skipped_orders || [])) {
|
||
skippedMap.set(Number(item.order_id), item.skipped_reason || 'unknown');
|
||
}
|
||
for (const item of (resultData.failed_orders || [])) {
|
||
failedMap.set(Number(item.order_id), item.failed_reason || 'unknown');
|
||
}
|
||
|
||
const skipReasonMap = { not_found: '订单不存在', already_synced: '已同步' };
|
||
const failReasonMap = { express_unallocated: '快递未分配', sn_batch_forbidden: 'SN订单不支持批量' };
|
||
const dispatchChannels = (resultData.dispatch_results || [])
|
||
.map(r => r.create_channel).filter(Boolean).join('/') || 'unknown';
|
||
|
||
const logPayloads = rawOrderIds.map(orderId => {
|
||
const oid = Number(orderId);
|
||
let msg;
|
||
|
||
if (pendingSet.has(oid)) {
|
||
msg = `同步到${dispatchChannels}渠道`;
|
||
} else if (failedMap.has(oid)) {
|
||
const reason = failedMap.get(oid);
|
||
msg = `同步跳过:${failReasonMap[reason] || reason}`;
|
||
} else if (skippedMap.has(oid)) {
|
||
const reason = skippedMap.get(oid);
|
||
msg = `同步跳过:${skipReasonMap[reason] || reason}`;
|
||
} else {
|
||
msg = '同步跳过';
|
||
}
|
||
|
||
return {
|
||
businessType: 'order',
|
||
businessId: String(oid),
|
||
operationCode: 'ORDER_SYNC',
|
||
operator,
|
||
extras: {
|
||
message: msg,
|
||
warehouseId: logWarehouseId,
|
||
externalLogType: 'NONE',
|
||
},
|
||
};
|
||
}).filter(item => Number(item.businessId) > 0);
|
||
|
||
if (logPayloads.length > 0) {
|
||
await opLogService.createOperationLogs(logPayloads);
|
||
}
|
||
}
|
||
} catch (logErr) {
|
||
this.ctx.logger.warn('[PendingOrderService.syncOrderIds] 写入操作日志失败,不影响主流程', {
|
||
request_id: requestId,
|
||
error: logErr && logErr.message,
|
||
});
|
||
}
|
||
|
||
this.ctx.logger.info('[PendingOrderService.syncOrderIds] 后台同步任务完成', {
|
||
request_id: requestId,
|
||
status: result && result.code,
|
||
message: result && result.message,
|
||
});
|
||
} catch (error) {
|
||
// 整体失败也静默写入进度
|
||
try {
|
||
const cached = await this.getSyncOrderIdsTaskProgress(requestId);
|
||
const cachedTotal = cached && Number(cached.total_count || 0);
|
||
await this.setSyncOrderIdsTaskProgress(requestId, {
|
||
status: 'failed',
|
||
total_count: cachedTotal || 0,
|
||
processed_count: cached && Number(cached.processed_count || 0),
|
||
progress: cached && Number(cached.progress || 0),
|
||
warehouse_id: warehouseId,
|
||
error: error && error.message ? error.message : String(error),
|
||
});
|
||
} catch (cacheErr) {
|
||
this.ctx.logger.warn('[PendingOrderService.syncOrderIds] 写入失败进度缓存失败', {
|
||
request_id: requestId,
|
||
error: cacheErr && cacheErr.message,
|
||
});
|
||
}
|
||
|
||
// 写操作日志:崩溃场景下 service 层可能不可用,直接用 model 直写
|
||
try {
|
||
const rawOrderIds = Array.isArray(normalizedData.order_ids)
|
||
? normalizedData.order_ids
|
||
: (normalizedData.order_ids ? [ normalizedData.order_ids ] : []);
|
||
const errorMsg = error && error.message ? String(error.message) : String(error);
|
||
|
||
if (rawOrderIds.length > 0 && this.ctx.model && this.ctx.model.OperationLog) {
|
||
const operatorId = operator.id;
|
||
const operatorName = operator.name || 'system';
|
||
const now = new Date();
|
||
|
||
const logRows = rawOrderIds.map(orderId => ({
|
||
business_type: 'order',
|
||
business_id: String(orderId),
|
||
operation_code: 'ORDER_SYNC_FAILED',
|
||
operator_id: operatorId,
|
||
operator_name: operatorName,
|
||
external_log_type: 'NONE',
|
||
warehouse_id: logWarehouseId || null,
|
||
platform_code: 'SYSTEM',
|
||
message: `订单同步失败:${errorMsg}`,
|
||
created_at: now,
|
||
})).filter(row => Number(row.business_id) > 0);
|
||
|
||
if (logRows.length > 0) {
|
||
await this.ctx.model.OperationLog.bulkCreate(logRows);
|
||
}
|
||
}
|
||
} catch (logErr) {
|
||
this.ctx.logger.warn('[PendingOrderService.syncOrderIds] 写入失败操作日志失败,不影响主流程', {
|
||
request_id: requestId,
|
||
error: logErr && logErr.message,
|
||
});
|
||
}
|
||
|
||
this.ctx.logger.error('[PendingOrderService.syncOrderIds] 后台同步任务异常', {
|
||
request_id: requestId,
|
||
warehouseId,
|
||
error: error && error.message ? error.message : error,
|
||
stack: error && error.stack ? error.stack : '',
|
||
});
|
||
}
|
||
});
|
||
|
||
// 立即返回 request_id
|
||
return this.success('同步任务已提交,可通过 syncOrderIdsProgress 查询进度', {
|
||
request_id: requestId,
|
||
warehouse_id: warehouseId,
|
||
message: '同步任务已提交,后台处理中',
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 查询订单同步任务进度。
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @param {string} data.request_id 请求ID(下划线写法)。
|
||
* @param {string} data.requestId 请求ID(驼峰写法)。
|
||
* @return {Promise<Object>} 任务进度响应,含 status / progress / total_count / processed_count / result。
|
||
*/
|
||
async syncOrderIdsProgress(data = {}) {
|
||
const requestId = this.normalizeSyncOrderIdsRequestId(data);
|
||
if (!requestId) {
|
||
return this.fail('request_id 参数不能为空', {}, 400);
|
||
}
|
||
|
||
const cachedProgress = await this.getSyncOrderIdsTaskProgress(requestId);
|
||
if (!cachedProgress) {
|
||
return this.success('ok', {
|
||
request_id: requestId,
|
||
status: 'not_found',
|
||
progress: SYNC_ORDER_IDS_PROGRESS_MAP.not_found,
|
||
total_count: 0,
|
||
processed_count: 0,
|
||
});
|
||
}
|
||
|
||
const normalizedStatus = String(cachedProgress.status || 'unknown').trim() || 'unknown';
|
||
|
||
return this.success('ok', {
|
||
request_id: requestId,
|
||
status: normalizedStatus,
|
||
progress: Number.isFinite(Number(cachedProgress.progress))
|
||
? Math.min(100, Math.max(0, Math.round(Number(cachedProgress.progress))))
|
||
: (SYNC_ORDER_IDS_PROGRESS_MAP[normalizedStatus] ?? SYNC_ORDER_IDS_PROGRESS_MAP.unknown),
|
||
total_count: Number(cachedProgress.total_count || 0),
|
||
processed_count: Number(cachedProgress.processed_count || 0),
|
||
warehouse_id: Number(cachedProgress.warehouse_id || 0),
|
||
result: cachedProgress.result || null,
|
||
error: cachedProgress.error || '',
|
||
update_time: cachedProgress.update_time || null,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 批量分配待处理订单的快递号,并复用现有运单创建核心链路。
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @param {Array<number>} data.ids 订单 ID 数组(推荐)。
|
||
* @param {Array<Object>} [data.orders] 订单对象数组(兼容旧格式,新调用方请使用 ids)。
|
||
* @return {Promise<Object>} 统一 success 包装,立即返回 task_id。
|
||
*/
|
||
async allocateExpressCode(data) {
|
||
const { ids, orders: legacyOrders } = data || {};
|
||
|
||
// 新格式:ids,直接转为管线所需格式(business_key 固定为 1)
|
||
let orders;
|
||
if (Array.isArray(ids) && ids.length > 0) {
|
||
orders = ids.map(id => ({ order_id: Number(id), business_key: 1 }));
|
||
} else if (Array.isArray(legacyOrders)) {
|
||
// 兼容旧格式:orders 对象数组
|
||
orders = legacyOrders;
|
||
} else {
|
||
throw new Error('分配快递号接口需要传入 ids(订单ID数组)或 orders(订单对象数组)');
|
||
}
|
||
|
||
const { service } = this;
|
||
|
||
// 生成任务ID,立即返回给前端
|
||
const taskId = `exp_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
||
const taskPayload = {
|
||
task_id: taskId,
|
||
status: 'submitted',
|
||
progress: ALLOCATE_EXPRESS_PROGRESS_MAP.submitted,
|
||
message: '分配快递任务已提交',
|
||
result: null,
|
||
error: '',
|
||
};
|
||
await this.setAllocateExpressTaskProgress(taskId, taskPayload);
|
||
|
||
// 捕获 warehouseId 供 setImmediate 异步回调使用,
|
||
// 避免 Qimen 等链路中 withPatchedCtxUser 补丁已撤销导致 getCurrentWarehouseId() 返回 0。
|
||
const capturedWarehouseId = Number(
|
||
this.ctx && this.ctx.user && this.ctx.user.store_id || 0
|
||
);
|
||
|
||
// 后台异步执行
|
||
setImmediate(async () => {
|
||
try {
|
||
await this.setAllocateExpressTaskProgress(taskId, {
|
||
status: 'running',
|
||
progress: ALLOCATE_EXPRESS_PROGRESS_MAP.running,
|
||
message: '快递分配处理中',
|
||
});
|
||
|
||
const result = await service.systems.express.createWaybillCodePipeline(orders, {
|
||
awaitTasks: true,
|
||
warehouseId: capturedWarehouseId,
|
||
});
|
||
|
||
await this.setAllocateExpressTaskProgress(taskId, {
|
||
status: 'success',
|
||
progress: ALLOCATE_EXPRESS_PROGRESS_MAP.success,
|
||
message: '快递分配完成',
|
||
result,
|
||
});
|
||
} catch (error) {
|
||
const errorMessage = error && error.message ? error.message : String(error);
|
||
|
||
// 异常标记和失败日志仍在 asyncTask 内部处理,这里仅记录任务状态
|
||
await this.setAllocateExpressTaskProgress(taskId, {
|
||
status: 'failed',
|
||
progress: ALLOCATE_EXPRESS_PROGRESS_MAP.failed,
|
||
message: '快递分配失败',
|
||
error: errorMessage,
|
||
});
|
||
|
||
// 回滚无运单号订单的 post_status
|
||
try {
|
||
const orderIds = [ ...new Set(
|
||
orders
|
||
.map(order => Number(order && (order.order_id || order.id)))
|
||
.filter(orderId => Number.isFinite(orderId) && orderId > 0)
|
||
) ];
|
||
|
||
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
|
||
const orderDeliveryModel = orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function'
|
||
? await orderDeliveryFactory.getCurrentModel()
|
||
: null;
|
||
|
||
if (orderDeliveryModel && orderIds.length > 0) {
|
||
const currentOrders = await orderDeliveryModel.findAll({
|
||
// eslint-disable-next-line array-bracket-spacing
|
||
where: { id: { [this.app.Sequelize.Op.in]: orderIds } },
|
||
attributes: [ 'id', 'express_code', 'post_status' ],
|
||
raw: true,
|
||
});
|
||
|
||
const noWaybillOrderIds = (Array.isArray(currentOrders) ? currentOrders : [])
|
||
.filter(o => !String(o.express_code || '').trim())
|
||
.map(o => Number(o.id))
|
||
.filter(id => id > 0);
|
||
|
||
if (noWaybillOrderIds.length > 0) {
|
||
await orderDeliveryModel.update(
|
||
{ post_status: 'none', updated_at: new Date() },
|
||
// eslint-disable-next-line array-bracket-spacing
|
||
{ where: { id: { [this.app.Sequelize.Op.in]: noWaybillOrderIds } } }
|
||
);
|
||
this.ctx.logger.info('[PendingOrderService.allocateExpressCode] 回滚 post_status 为 none', {
|
||
orderIds: noWaybillOrderIds,
|
||
});
|
||
}
|
||
}
|
||
} catch (markError) {
|
||
this.ctx.logger.warn('[PendingOrderService.allocateExpressCode] 回写订单状态失败,不影响主流程', markError);
|
||
}
|
||
}
|
||
});
|
||
|
||
return this.success('ok', {
|
||
...taskPayload,
|
||
update_time: Date.now(),
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 查询快递分配任务进度。
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @param {string} data.task_id 任务ID(下划线写法)。
|
||
* @param {string} data.taskId 任务ID(驼峰写法)。
|
||
* @return {Promise<Object>} 统一 success 包装。
|
||
*/
|
||
async allocateExpressCodeTaskProgress(data = {}) {
|
||
const taskId = this.normalizeAllocateExpressTaskId(data);
|
||
if (!taskId) {
|
||
return this.success('ok', {
|
||
task_id: '',
|
||
status: 'not_found',
|
||
progress: ALLOCATE_EXPRESS_PROGRESS_MAP.not_found,
|
||
message: '任务不存在',
|
||
result: null,
|
||
error: '',
|
||
update_time: Date.now(),
|
||
});
|
||
}
|
||
|
||
const cachedTask = await this.getAllocateExpressTaskProgress(taskId);
|
||
if (!cachedTask) {
|
||
return this.success('ok', {
|
||
task_id: taskId,
|
||
status: 'not_found',
|
||
progress: ALLOCATE_EXPRESS_PROGRESS_MAP.not_found,
|
||
message: '任务不存在',
|
||
result: null,
|
||
error: '',
|
||
update_time: Date.now(),
|
||
});
|
||
}
|
||
|
||
return this.success('ok', {
|
||
...cachedTask,
|
||
update_time: cachedTask.update_time || Date.now(),
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 将待处理订单批量标记为待出库。
|
||
* @param {Object} data 请求体。
|
||
* @param {number[]} data.ids 订单ID 数组。
|
||
* @return {Promise<Object>} 更新后的订单信息。
|
||
*/
|
||
async markPendingOutboundOrder(data = {}) {
|
||
const requestData = this.isPlainObject(data) ? data : {};
|
||
const warehouseId = this.getWarehouseId();
|
||
const orderIds = this.normalizePendingOutboundOrderIds(requestData);
|
||
|
||
if (orderIds.length === 0) {
|
||
throw new Error('订单ID不能为空');
|
||
}
|
||
|
||
const model = await this.getOrderModel('order', warehouseId);
|
||
const where = this.buildOrderWhere(orderIds, warehouseId);
|
||
const existingOrders = await model.findAll({
|
||
where,
|
||
raw: true,
|
||
});
|
||
|
||
if (!Array.isArray(existingOrders) || existingOrders.length === 0) {
|
||
return this.success('取消成功', {
|
||
updated_count: 0,
|
||
ids: [],
|
||
});
|
||
}
|
||
|
||
if (existingOrders.length !== orderIds.length) {
|
||
throw new Error('订单不存在或不属于当前仓库');
|
||
}
|
||
|
||
const now = new Date();
|
||
const updateValues = {
|
||
outbound_status: PENDING_OUTBOUND_STATUS,
|
||
step: PENDING_OUTBOUND_STEP,
|
||
updated_at: now,
|
||
};
|
||
|
||
const updateResult = await model.update(updateValues, {
|
||
where,
|
||
});
|
||
|
||
const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0);
|
||
if (affectedRows <= 0) {
|
||
throw new Error('订单不存在或不属于当前仓库');
|
||
}
|
||
|
||
const updatedOrders = await model.findAll({
|
||
where,
|
||
raw: true,
|
||
});
|
||
|
||
if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) {
|
||
throw new Error('订单不存在或不属于当前仓库');
|
||
}
|
||
|
||
const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ]));
|
||
const normalizedOrders = orderIds
|
||
.map(orderId => orderMap.get(orderId))
|
||
.filter(Boolean)
|
||
.map(order => ({
|
||
id: order.id,
|
||
outbound_status: order.outbound_status,
|
||
updated_at: order.updated_at,
|
||
}));
|
||
|
||
if (normalizedOrders.length === 0) {
|
||
throw new Error('订单不存在或不属于当前仓库');
|
||
}
|
||
|
||
const firstOrder = normalizedOrders[0];
|
||
|
||
return {
|
||
id: firstOrder.id,
|
||
outbound_status: firstOrder.outbound_status,
|
||
updated_at: firstOrder.updated_at,
|
||
updated_count: affectedRows,
|
||
ids: normalizedOrders.map(order => order.id),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 将待处理订单取消,并关闭到已取消状态。
|
||
* 仅允许取消当前仓库内处于待审核、待处理、待处理异常语义的订单。
|
||
* @param {Object} data 请求体。
|
||
* @param {number[]} data.ids 订单ID 数组。
|
||
* @return {Promise<Object>} 更新后的订单信息。
|
||
*/
|
||
async cancelOrder(data = {}) {
|
||
const requestData = this.isPlainObject(data) ? data : {};
|
||
const warehouseId = this.getWarehouseId();
|
||
const orderIds = this.normalizePendingCancelOrderIds(requestData);
|
||
|
||
if (orderIds.length === 0) {
|
||
throw new Error('订单ID不能为空');
|
||
}
|
||
|
||
const model = await this.getOrderModel('order', warehouseId);
|
||
const where = this.buildOrderWhere(orderIds, warehouseId);
|
||
const existingOrders = await model.findAll({
|
||
where,
|
||
raw: true,
|
||
});
|
||
|
||
if (!Array.isArray(existingOrders) || existingOrders.length === 0) {
|
||
return this.success('取消成功', {
|
||
updated_count: 0,
|
||
ids: [],
|
||
});
|
||
}
|
||
|
||
if (existingOrders.length !== orderIds.length) {
|
||
throw new Error('订单不存在或不属于当前仓库');
|
||
}
|
||
|
||
const nonCancelableOrder = existingOrders.find(order => !this.isCancelablePendingOrder(order));
|
||
if (nonCancelableOrder) {
|
||
throw new Error('订单当前状态不允许取消');
|
||
}
|
||
|
||
// 已同步订单不允许取消,转为拦截处理
|
||
const syncedOrders = existingOrders.filter(
|
||
order => String(order.sync_status || '').trim() === 'fin'
|
||
);
|
||
if (syncedOrders.length > 0) {
|
||
const syncedOrderIds = syncedOrders.map(order => Number(order.id)).filter(
|
||
id => Number.isInteger(id) && id > 0
|
||
);
|
||
if (syncedOrderIds.length > 0) {
|
||
const syncNow = new Date();
|
||
await model.update(
|
||
{
|
||
intercept_status: 'requested',
|
||
updated_at: syncNow,
|
||
},
|
||
{
|
||
where: {
|
||
id: syncedOrderIds,
|
||
},
|
||
}
|
||
);
|
||
// 同步更新运单表拦截标记
|
||
try {
|
||
const { Op: cancelOp } = this.app.Sequelize;
|
||
await this.ctx.model.OrderExpress.update(
|
||
{ is_intercept: 'Y' },
|
||
{ where: { order_id: { [cancelOp.in]: syncedOrderIds }, warehouse_id: warehouseId } }
|
||
);
|
||
} catch (expressErr) {
|
||
this.ctx.logger.warn(
|
||
`[PendingOrderService.cancelOrder] 更新运单拦截标记失败, count=${syncedOrderIds.length}, error=${expressErr.message}`
|
||
);
|
||
}
|
||
this.ctx.logger.info(
|
||
`[PendingOrderService.cancelOrder] 订单已同步,不可取消,已转为拦截处理,订单ID: ${syncedOrderIds.join(',')}`
|
||
);
|
||
}
|
||
const syncedCodes = syncedOrders
|
||
.map(order => String(order.delivery_order_code || order.pre_delivery_order_code || order.id || '').trim())
|
||
.filter(Boolean)
|
||
.join(', ');
|
||
throw new Error(`订单已同步,不可取消,已转为拦截处理:${syncedCodes}`);
|
||
}
|
||
|
||
const now = new Date();
|
||
const updateValues = {
|
||
status: PENDING_CANCEL_STATUS,
|
||
step: PENDING_CANCEL_STEP,
|
||
outbound_status: PENDING_OUTBOUND_STATUS,
|
||
updated_at: now,
|
||
};
|
||
|
||
const updateResult = await model.update(updateValues, {
|
||
where,
|
||
});
|
||
|
||
const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0);
|
||
if (affectedRows <= 0) {
|
||
throw new Error('订单不存在或不属于当前仓库');
|
||
}
|
||
|
||
const ordersWithWave = existingOrders.filter(order => Number(order.wave_id) > 0);
|
||
if (ordersWithWave.length > 0) {
|
||
try {
|
||
const { Op } = this.app.Sequelize;
|
||
const WaveBatch = this.ctx.model.WaveBatch;
|
||
|
||
const waveOrderIds = ordersWithWave
|
||
.map(order => Number(order.id))
|
||
.filter(orderId => Number.isInteger(orderId) && orderId > 0);
|
||
|
||
if (waveOrderIds.length > 0) {
|
||
await model.update(
|
||
{
|
||
wave_id: 0,
|
||
wave_no: '',
|
||
updated_at: now,
|
||
},
|
||
{
|
||
where: {
|
||
id: {
|
||
[Op.in]: waveOrderIds,
|
||
},
|
||
warehouse_id: warehouseId,
|
||
},
|
||
}
|
||
);
|
||
|
||
await this.ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({
|
||
warehouseId,
|
||
orderIds: waveOrderIds,
|
||
transaction: undefined,
|
||
});
|
||
|
||
// 重建受影响波次的订单索引(wave_index 重新排序)
|
||
const affectedWaveIds = [ ...new Set(ordersWithWave
|
||
.map(order => Number(order.wave_id))
|
||
.filter(waveId => Number.isInteger(waveId) && waveId > 0)) ];
|
||
if (affectedWaveIds.length > 0) {
|
||
await this.ctx.service.systemMethods.order.wave.replaceOrderWaveIndexByWaveIds({
|
||
warehouseId,
|
||
waveIds: affectedWaveIds,
|
||
orderModel: model,
|
||
});
|
||
}
|
||
}
|
||
|
||
if (WaveBatch) {
|
||
const waveIdCountMap = new Map();
|
||
for (const order of ordersWithWave) {
|
||
const waveId = Number(order.wave_id);
|
||
if (!Number.isInteger(waveId) || waveId <= 0) {
|
||
continue;
|
||
}
|
||
waveIdCountMap.set(waveId, (waveIdCountMap.get(waveId) || 0) + 1);
|
||
}
|
||
|
||
for (const [ waveId, canceledCount ] of waveIdCountMap.entries()) {
|
||
await WaveBatch.decrement('total_orders', {
|
||
by: canceledCount,
|
||
where: {
|
||
wave_id: waveId,
|
||
warehouse_id: warehouseId,
|
||
total_orders: {
|
||
[Op.gt]: 0,
|
||
},
|
||
},
|
||
});
|
||
|
||
const wave = await WaveBatch.findOne({
|
||
where: {
|
||
wave_id: waveId,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
attributes: [ 'wave_id', 'total_orders', 'wave_status' ],
|
||
raw: true,
|
||
});
|
||
|
||
if (!wave) {
|
||
continue;
|
||
}
|
||
|
||
const totalOrders = Number(wave.total_orders);
|
||
const normalizedTotalOrders = Number.isFinite(totalOrders) ? totalOrders : 0;
|
||
if (normalizedTotalOrders <= 0) {
|
||
await WaveBatch.update(
|
||
{
|
||
total_orders: 0,
|
||
wave_status: -1,
|
||
update_time: now,
|
||
},
|
||
{
|
||
where: {
|
||
wave_id: waveId,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
}
|
||
);
|
||
} else {
|
||
await WaveBatch.update(
|
||
{
|
||
update_time: now,
|
||
},
|
||
{
|
||
where: {
|
||
wave_id: waveId,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
}
|
||
);
|
||
}
|
||
}
|
||
}
|
||
} catch (waveErr) {
|
||
this.ctx.logger.warn('[PendingOrderService.cancelOrder] 清理波次关联失败,不影响订单取消', waveErr);
|
||
}
|
||
}
|
||
|
||
// 释放储位分配和库存锁定
|
||
try {
|
||
await this.service.systems.orderStorageAllocation.cancelAllocateStorage({
|
||
order_ids: orderIds,
|
||
});
|
||
} catch (allocErr) {
|
||
this.ctx.logger.warn('[PendingOrderService.cancelOrder] 释放储位分配失败,不影响订单取消', allocErr);
|
||
}
|
||
|
||
// 释放创建锁(lockItemStorages 加的锁,不含 picking 锁)
|
||
try {
|
||
await this.releaseCreationLockForCancel({
|
||
orderIds,
|
||
warehouseId,
|
||
});
|
||
} catch (releaseErr) {
|
||
this.ctx.logger.warn('[PendingOrderService.cancelOrder] 释放创建锁失败,不影响订单取消', releaseErr);
|
||
}
|
||
|
||
const updatedOrders = await model.findAll({
|
||
where,
|
||
raw: true,
|
||
});
|
||
|
||
if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) {
|
||
throw new Error('订单不存在或不属于当前仓库');
|
||
}
|
||
|
||
const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ]));
|
||
const normalizedOrders = orderIds
|
||
.map(orderId => orderMap.get(orderId))
|
||
.filter(Boolean)
|
||
.map(order => ({
|
||
id: order.id,
|
||
status: order.status,
|
||
step: Number(order.step ?? PENDING_CANCEL_STEP),
|
||
updated_at: order.updated_at,
|
||
}));
|
||
|
||
if (normalizedOrders.length === 0) {
|
||
throw new Error('订单不存在或不属于当前仓库');
|
||
}
|
||
|
||
const firstOrder = normalizedOrders[0];
|
||
|
||
// 写入取消操作日志(不影响主流程)
|
||
try {
|
||
const operator = this.getOrderLogOperator();
|
||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||
if (normalizedOrders.length > 0 && this.ctx.model && this.ctx.model.OperationLog) {
|
||
const operatorInfo = operator || {};
|
||
const operatorId = operatorInfo.id != null ? String(operatorInfo.id) : null;
|
||
const operatorName = operatorInfo.name ? String(operatorInfo.name) : 'system';
|
||
const now = new Date();
|
||
|
||
const logRows = normalizedOrders.map(order => ({
|
||
business_type: 'order',
|
||
business_id: String(order.id),
|
||
operation_code: 'ORDER_CANCEL',
|
||
operator_id: operatorId,
|
||
operator_name: operatorName,
|
||
external_log_type: 'NONE',
|
||
warehouse_id: logWarehouseId || null,
|
||
platform_code: 'SYSTEM',
|
||
message: '订单取消',
|
||
created_at: now,
|
||
})).filter(row => Number(row.business_id) > 0);
|
||
|
||
if (logRows.length > 0) {
|
||
await this.ctx.model.OperationLog.bulkCreate(logRows);
|
||
}
|
||
}
|
||
} catch (logErr) {
|
||
this.ctx.logger.warn('[PendingOrderService.cancelOrder] 写入取消操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
return {
|
||
id: firstOrder.id,
|
||
status: firstOrder.status,
|
||
step: firstOrder.step,
|
||
updated_at: firstOrder.updated_at,
|
||
updated_count: affectedRows,
|
||
ids: normalizedOrders.map(order => order.id),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 规范待处理出库订单ID入参,仅接受 ids 数组且元素必须为正整数。
|
||
* @param {Object} data 请求体。
|
||
* @return {number[]} 订单ID 数组。
|
||
*/
|
||
normalizePendingOutboundOrderIds(data = {}) {
|
||
const requestData = this.isPlainObject(data) ? data : {};
|
||
const unexpectedKeys = Object.keys(requestData).filter(key => key !== 'ids');
|
||
|
||
if (unexpectedKeys.length > 0) {
|
||
throw new Error('待处理出库接口仅支持 ids 数组入参,不再支持 id、order_id、逗号字符串或其他兼容字段');
|
||
}
|
||
|
||
if (!Array.isArray(requestData.ids)) {
|
||
throw new Error('待处理出库接口仅支持 ids 数组入参');
|
||
}
|
||
|
||
const normalizedIds = requestData.ids.map(value => {
|
||
if (!Number.isInteger(value) || value <= 0) {
|
||
throw new Error('ids 仅支持正整数数组');
|
||
}
|
||
|
||
return value;
|
||
});
|
||
|
||
return Array.from(new Set(normalizedIds));
|
||
}
|
||
|
||
/**
|
||
* 规范待处理取消订单ID入参,仅接受 ids 数组且元素必须为正整数。
|
||
* @param {Object} data 请求体。
|
||
* @return {number[]} 订单ID 数组。
|
||
*/
|
||
normalizePendingCancelOrderIds(data = {}) {
|
||
const requestData = this.isPlainObject(data) ? data : {};
|
||
const unexpectedKeys = Object.keys(requestData).filter(key => key !== 'ids');
|
||
|
||
if (unexpectedKeys.length > 0) {
|
||
throw new Error('待处理取消接口仅支持 ids 数组入参,不再支持 id、order_id、逗号字符串或其他兼容字段');
|
||
}
|
||
|
||
if (!Array.isArray(requestData.ids)) {
|
||
throw new Error('待处理取消接口仅支持 ids 数组入参');
|
||
}
|
||
|
||
const normalizedIds = requestData.ids.map(value => {
|
||
if (!Number.isInteger(value) || value <= 0) {
|
||
throw new Error('ids 仅支持正整数数组');
|
||
}
|
||
|
||
return value;
|
||
});
|
||
|
||
return Array.from(new Set(normalizedIds));
|
||
}
|
||
|
||
/**
|
||
* 判断订单是否允许从待处理模块取消。
|
||
* 仅允许处于待审核、待处理、待处理异常语义的订单取消。
|
||
* @param {Object} order 订单记录。
|
||
* @return {boolean} 是否允许取消。
|
||
*/
|
||
isCancelablePendingOrder(order = {}) {
|
||
const step = Number(order.step);
|
||
const status = String(order.status || '').trim().toLowerCase();
|
||
const outboundStatus = String(order.outbound_status || '').trim();
|
||
|
||
if (status === PENDING_CANCEL_STATUS) {
|
||
return false;
|
||
}
|
||
|
||
if (!PENDING_CANCEL_ALLOWED_STEPS.has(step)) {
|
||
return false;
|
||
}
|
||
|
||
if (PENDING_CANCEL_PENDING_STEPS.has(step) && outboundStatus === PENDING_OUTBOUND_STATUS) {
|
||
return false;
|
||
}
|
||
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* 批量修改待处理订单的平台信息。
|
||
*
|
||
* 用 code 查找 wms_platform 表中对应的平台记录,若存在则将订单的
|
||
* sys_platform_code 和 sys_platform_name 更新为该平台的 code 和 name;
|
||
* 若不存在则返回错误。只操作当前仓库的当前订单表,不处理其他订单表。
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @param {number[]} data.order_ids 订单ID 数组。
|
||
* @param {string} data.code 平台编码。
|
||
* @return {Promise<Object>} 统一 success 包装的更新结果。
|
||
*/
|
||
async updateOrderPlatform(data = {}) {
|
||
const requestData = this.isPlainObject(data) ? data : {};
|
||
const warehouseId = this.getWarehouseId();
|
||
const operator = this.getOrderLogOperator();
|
||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||
|
||
const rawOrderIds = requestData.order_ids;
|
||
if (!Array.isArray(rawOrderIds) || rawOrderIds.length === 0) {
|
||
throw new Error('order_ids 不能为空');
|
||
}
|
||
|
||
const orderIds = Array.from(new Set(rawOrderIds.map(v => {
|
||
const n = Number(v);
|
||
if (!Number.isInteger(n) || n <= 0) {
|
||
throw new Error('order_ids 仅支持正整数数组');
|
||
}
|
||
return n;
|
||
})));
|
||
|
||
const code = String(requestData.code || '').trim();
|
||
if (!code) {
|
||
throw new Error('code 不能为空');
|
||
}
|
||
|
||
const platformList = await this.service.systems.platform.getPlatformList(true, true);
|
||
const platform = Array.isArray(platformList)
|
||
? platformList.find(item => String(item.code || item.platform_code || '').trim() === code)
|
||
: null;
|
||
|
||
if (!platform) {
|
||
throw new Error(`平台编码 ${code} 不存在`);
|
||
}
|
||
|
||
const model = await this.getOrderModel('order', warehouseId);
|
||
const where = {
|
||
...this.buildOrderWhere(orderIds, warehouseId),
|
||
post_status: 'none',
|
||
};
|
||
|
||
const [ affectedRows ] = await model.update({
|
||
sys_platform_code: platform.code,
|
||
sys_platform_name: String(platform.name || '').trim(),
|
||
updated_at: new Date(),
|
||
}, { where });
|
||
|
||
const count = Number(affectedRows || 0);
|
||
|
||
// 记录操作日志
|
||
try {
|
||
await this.ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'order',
|
||
businessId: logWarehouseId,
|
||
operationCode: 'ORDER_UPDATE_PLATFORM',
|
||
operator,
|
||
extras: {
|
||
warehouseId: logWarehouseId,
|
||
orderIds,
|
||
sys_platform_code: platform.code,
|
||
sys_platform_name: String(platform.name || '').trim(),
|
||
updated_count: count,
|
||
message: `批量修改订单平台:订单ID [${orderIds.join(', ')}],平台 ${platform.code}(${String(platform.name || '').trim()}),共更新 ${count} 条`,
|
||
},
|
||
beforeChanges: null,
|
||
});
|
||
} catch (logErr) {
|
||
this.ctx.logger.warn('[PendingOrderService.updateOrderPlatform] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
return this.success('ok', {
|
||
updated_count: count,
|
||
sys_platform_code: platform.code,
|
||
sys_platform_name: String(platform.name || '').trim(),
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 批量修改待处理订单的快递信息。
|
||
*
|
||
* 用 express_code 从当前仓库快递列表(带缓存)中查找对应项:
|
||
* - 若为自定义映射(is_system_setting=true),则 sys_logistics_code/sys_logistics_name 写系统快递
|
||
* 的 express_code/name,logistics_code/logistics_name 写自定义编码和名称;
|
||
* - 若为系统快递(is_system_setting=false),则 sys_logistics_code/sys_logistics_name 和
|
||
* logistics_code/logistics_name 均写系统快递的 code/name;
|
||
* - 未找到则报错。
|
||
* 只操作当前仓库的当前订单表,不处理其他订单表。
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @param {number[]} data.order_ids 订单ID 数组。
|
||
* @param {string} data.express_code 快递编码(系统编码或自定义编码)。
|
||
* @return {Promise<Object>} 统一 success 包装的更新结果。
|
||
*/
|
||
async updateOrderExpress(data = {}) {
|
||
const requestData = this.isPlainObject(data) ? data : {};
|
||
const warehouseId = this.getWarehouseId();
|
||
const operator = this.getOrderLogOperator();
|
||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||
|
||
const rawOrderIds = requestData.order_ids;
|
||
if (!Array.isArray(rawOrderIds) || rawOrderIds.length === 0) {
|
||
throw new Error('order_ids 不能为空');
|
||
}
|
||
|
||
const orderIds = Array.from(new Set(rawOrderIds.map(v => {
|
||
const n = Number(v);
|
||
if (!Number.isInteger(n) || n <= 0) {
|
||
throw new Error('order_ids 仅支持正整数数组');
|
||
}
|
||
return n;
|
||
})));
|
||
|
||
const expressCode = String(requestData.express_code || '').trim();
|
||
if (!expressCode) {
|
||
throw new Error('express_code 不能为空');
|
||
}
|
||
|
||
// 使用带缓存的仓库快递列表
|
||
const expressList = await this.service.systems.express.getExpressList();
|
||
const expressItem = Array.isArray(expressList)
|
||
? expressList.find(item => String(item.code || item.value || '').trim() === expressCode)
|
||
: null;
|
||
|
||
if (!expressItem) {
|
||
throw new Error(`快递编码 ${expressCode} 不存在`);
|
||
}
|
||
|
||
let sysLogisticsCode;
|
||
let sysLogisticsName;
|
||
let logisticsCode;
|
||
let logisticsName;
|
||
|
||
if (expressItem.is_system_setting) {
|
||
// 自定义映射:express_code 字段存储对应的系统快递编码
|
||
sysLogisticsCode = String(expressItem.express_code || '').trim();
|
||
// 系统快递名称从列表中查找
|
||
const sysItem = expressList.find(item => !item.is_system_setting && String(item.code || '').trim() === sysLogisticsCode);
|
||
sysLogisticsName = sysItem ? String(sysItem.name || '').trim() : sysLogisticsCode;
|
||
logisticsCode = expressItem.code;
|
||
logisticsName = String(expressItem.alias || expressItem.name || '').trim();
|
||
} else {
|
||
// 系统快递:logistics_code/name 与 sys 一致
|
||
sysLogisticsCode = expressItem.code;
|
||
sysLogisticsName = String(expressItem.name || '').trim();
|
||
logisticsCode = expressItem.code;
|
||
logisticsName = sysLogisticsName;
|
||
}
|
||
|
||
const model = await this.getOrderModel('order', warehouseId);
|
||
const where = {
|
||
...this.buildOrderWhere(orderIds, warehouseId),
|
||
post_status: 'none',
|
||
};
|
||
|
||
const [ affectedRows ] = await model.update({
|
||
sys_logistics_code: sysLogisticsCode,
|
||
sys_logistics_name: sysLogisticsName,
|
||
logistics_code: logisticsCode,
|
||
logistics_name: logisticsName,
|
||
updated_at: new Date(),
|
||
}, { where });
|
||
|
||
const count = Number(affectedRows || 0);
|
||
|
||
// 记录操作日志
|
||
try {
|
||
await this.ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'order',
|
||
businessId: logWarehouseId,
|
||
operationCode: 'ORDER_UPDATE_EXPRESS',
|
||
operator,
|
||
extras: {
|
||
warehouseId: logWarehouseId,
|
||
orderIds,
|
||
express_code: expressCode,
|
||
sys_logistics_code: sysLogisticsCode,
|
||
sys_logistics_name: sysLogisticsName,
|
||
logistics_code: logisticsCode,
|
||
logistics_name: logisticsName,
|
||
updated_count: count,
|
||
message: `批量修改订单快递:订单ID [${orderIds.join(', ')}],快递 ${logisticsCode}(${logisticsName}),系统快递 ${sysLogisticsCode}(${sysLogisticsName}),共更新 ${count} 条`,
|
||
},
|
||
beforeChanges: null,
|
||
});
|
||
} catch (logErr) {
|
||
this.ctx.logger.warn('[PendingOrderService.updateOrderExpress] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
return this.success('ok', {
|
||
updated_count: count,
|
||
sys_logistics_code: sysLogisticsCode,
|
||
sys_logistics_name: sysLogisticsName,
|
||
logistics_code: logisticsCode,
|
||
logistics_name: logisticsName,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 批量修改待处理订单的收件地址信息。
|
||
*
|
||
* 地址字段仅允许在未分配快递(post_status = 'none')时修改。
|
||
* 支持批量操作,返回更新数量和受影响的订单 ID 列表。
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @param {number[]} data.ids 订单 ID 数组(必填)。
|
||
* @param {string} [data.name] 收件人姓名。
|
||
* @param {string} [data.mobile] 手机号。
|
||
* @param {string} [data.tel] 电话。
|
||
* @param {string} [data.zip_code] 邮编。
|
||
* @param {string} [data.province] 省份。
|
||
* @param {string} [data.city] 城市。
|
||
* @param {string} [data.area] 区/县。
|
||
* @param {string} [data.town] 镇/街道。
|
||
* @param {string} [data.detail_address] 详细地址。
|
||
* @return {Promise<Object>} 统一 success 包装的更新结果,含 updated_count 与 ids。
|
||
*/
|
||
async updateAddress(data = {}) {
|
||
const requestData = this.isPlainObject(data) ? data : {};
|
||
const warehouseId = this.getWarehouseId();
|
||
const operator = this.getOrderLogOperator();
|
||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||
|
||
// 解析订单 ID
|
||
const orderIds = this.normalizeOrderIds(requestData);
|
||
if (orderIds.length === 0) {
|
||
throw new Error('ids 不能为空');
|
||
}
|
||
|
||
// 收集可更新的地址字段
|
||
const addressFields = [
|
||
'name', 'mobile', 'tel', 'zip_code',
|
||
'province', 'city', 'area', 'town', 'detail_address',
|
||
];
|
||
const addressUpdates = {};
|
||
for (const field of addressFields) {
|
||
const value = requestData[field];
|
||
if (value !== undefined && value !== null && String(value).trim() !== '') {
|
||
addressUpdates[field] = String(value).trim();
|
||
}
|
||
}
|
||
|
||
const hasAddressUpdates = Object.keys(addressUpdates).length > 0;
|
||
if (!hasAddressUpdates) {
|
||
throw new Error('至少需要提供一个地址字段进行修改');
|
||
}
|
||
|
||
const model = await this.getOrderModel('order', warehouseId);
|
||
const baseWhere = this.buildOrderWhere(orderIds, warehouseId);
|
||
const now = new Date();
|
||
|
||
let addressUpdatedCount = 0;
|
||
|
||
// 地址字段更新(受 post_status='none' 限制)
|
||
if (hasAddressUpdates) {
|
||
addressUpdates.updated_at = now;
|
||
const addressWhere = { ...baseWhere, post_status: 'none' };
|
||
const [ rows ] = await model.update(addressUpdates, { where: addressWhere });
|
||
addressUpdatedCount = Number(rows || 0);
|
||
}
|
||
|
||
// 记录操作日志
|
||
try {
|
||
const updatedFieldNames = Object.keys(addressUpdates).filter(k => k !== 'updated_at');
|
||
await this.ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'order',
|
||
businessId: logWarehouseId,
|
||
operationCode: 'ORDER_UPDATE_ADDRESS',
|
||
operator,
|
||
extras: {
|
||
warehouseId: logWarehouseId,
|
||
orderIds,
|
||
updated_fields: updatedFieldNames,
|
||
updated_count: addressUpdatedCount,
|
||
address_updated_count: addressUpdatedCount,
|
||
message: `批量修改订单收件地址:订单ID [${orderIds.join(', ')}],更新字段 [${updatedFieldNames.join(', ')}],地址更新 ${addressUpdatedCount} 条`,
|
||
},
|
||
beforeChanges: null,
|
||
});
|
||
} catch (logErr) {
|
||
this.ctx.logger.warn('[PendingOrderService.updateAddress] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
return this.success('ok', {
|
||
updated_count: addressUpdatedCount,
|
||
ids: orderIds,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 批量修改待处理订单的备注(remark)字段。
|
||
*
|
||
* 与 updateAddress 中的 remark 更新逻辑相似,
|
||
* 但作为独立接口只负责备注修改,不涉及地址字段。
|
||
* remark 修改不受 post_status 限制,对所有状态的订单均可生效。
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @param {Array<number>} data.ids 订单ID数组(必填,正整数数组)。
|
||
* @param {string} data.remark 备注内容(必填,最大500字符)。
|
||
* @return {Promise<Object>} 统一 success 包装的更新结果,含 updated_count 与 ids。
|
||
*/
|
||
async updateRemark(data = {}) {
|
||
const requestData = this.isPlainObject(data) ? data : {};
|
||
const warehouseId = this.getWarehouseId();
|
||
const operator = this.getOrderLogOperator();
|
||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||
|
||
// 解析订单 ID(仅支持数组)
|
||
const rawOrderIds = requestData.ids;
|
||
if (!Array.isArray(rawOrderIds) || rawOrderIds.length === 0) {
|
||
throw new Error('ids 不能为空,且必须是正整数数组');
|
||
}
|
||
|
||
const orderIds = Array.from(new Set(rawOrderIds.map(v => {
|
||
const n = Number(v);
|
||
if (!Number.isInteger(n) || n <= 0) {
|
||
throw new Error('ids 仅支持正整数数组');
|
||
}
|
||
return n;
|
||
})));
|
||
|
||
// 解析 remark
|
||
const rawRemark = requestData.remark;
|
||
if (rawRemark === undefined || rawRemark === null) {
|
||
throw new Error('remark 不能为空');
|
||
}
|
||
const trimmed = String(rawRemark).trim();
|
||
if (trimmed === '') {
|
||
throw new Error('remark 不能为空字符串');
|
||
}
|
||
const remarkValue = trimmed.substring(0, 500);
|
||
|
||
const model = await this.getOrderModel('order', warehouseId);
|
||
const where = this.buildOrderWhere(orderIds, warehouseId);
|
||
const now = new Date();
|
||
|
||
const [ affectedRows ] = await model.update(
|
||
{ remark: remarkValue, updated_at: now },
|
||
{ where }
|
||
);
|
||
const count = Number(affectedRows || 0);
|
||
|
||
// 记录操作日志
|
||
try {
|
||
await this.ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'order',
|
||
businessId: logWarehouseId,
|
||
operationCode: 'ORDER_UPDATE_REMARK',
|
||
operator,
|
||
extras: {
|
||
warehouseId: logWarehouseId,
|
||
orderIds,
|
||
remark: remarkValue,
|
||
updated_count: count,
|
||
message: `批量修改订单备注:订单ID [${orderIds.join(', ')}],备注内容 [${remarkValue}],共更新 ${count} 条`,
|
||
},
|
||
beforeChanges: null,
|
||
});
|
||
} catch (logErr) {
|
||
this.ctx.logger.warn('[PendingOrderService.updateRemark] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
return this.success('ok', {
|
||
updated_count: count,
|
||
ids: orderIds,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 克隆待处理订单。
|
||
*
|
||
* 流程:
|
||
* 1. 查找原订单,校验可取消状态(step 0/1/2/3);
|
||
* 2. 若原订单已分配储位(storage_status='fin'),先清除已分配库存;
|
||
* 3. 取消原订单(step->9, status->'cancel')并记录"克隆"日志;
|
||
* 4. 以原订单业务数据创建新订单,所有流程状态字段重置为初始落库状态;
|
||
* 5. 对新订单记录"克隆创建"日志。
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @param {number} data.order_id 原订单ID。
|
||
* @return {Promise<Object>} 统一 success 包装,含新订单 id。
|
||
*/
|
||
async cloneOrder(data = {}) {
|
||
const requestData = this.isPlainObject(data) ? data : {};
|
||
const warehouseId = this.getWarehouseId();
|
||
const operator = this.getOrderLogOperator();
|
||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||
|
||
const orderId = Number(requestData.order_id || requestData.id);
|
||
if (!Number.isInteger(orderId) || orderId <= 0) {
|
||
throw new Error('order_id 不能为空');
|
||
}
|
||
|
||
const model = await this.getOrderModel('order', warehouseId);
|
||
const where = this.buildOrderWhere([ orderId ], warehouseId);
|
||
|
||
// 1. 查原订单
|
||
const existingOrders = await model.findAll({ where, raw: true });
|
||
if (!Array.isArray(existingOrders) || existingOrders.length === 0) {
|
||
throw new Error('订单不存在或不属于当前仓库');
|
||
}
|
||
const original = existingOrders[0];
|
||
|
||
if (!this.isCancelablePendingOrder(original)) {
|
||
throw new Error('订单当前状态不允许克隆');
|
||
}
|
||
|
||
// 2. 若已分配储位,先清除库存
|
||
if (String(original.storage_status || '').trim() === 'fin') {
|
||
try {
|
||
await this.service.systems.orderStorageAllocation.cancelAllocateStorage({
|
||
order_ids: [ orderId ],
|
||
});
|
||
} catch (storageErr) {
|
||
throw new Error(`清除已分配库存失败:${storageErr.message}`);
|
||
}
|
||
}
|
||
|
||
const now = new Date();
|
||
const originalWaveId = Number(original.wave_id || 0);
|
||
|
||
// 3. 取消原订单(若在波次中需清除波次关联)
|
||
const cancelUpdateValues = {
|
||
status: 'cancel',
|
||
step: 9,
|
||
outbound_status: 'padding',
|
||
updated_at: now,
|
||
};
|
||
if (originalWaveId > 0) {
|
||
cancelUpdateValues.wave_id = 0;
|
||
cancelUpdateValues.wave_no = '';
|
||
}
|
||
await model.update(cancelUpdateValues, { where });
|
||
|
||
// 克隆时清理波次索引(不影响主流程)
|
||
if (originalWaveId > 0) {
|
||
try {
|
||
await this.ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({
|
||
warehouseId,
|
||
orderIds: [ orderId ],
|
||
});
|
||
await this.ctx.service.systemMethods.order.wave.replaceOrderWaveIndexByWaveIds({
|
||
warehouseId,
|
||
waveIds: [ originalWaveId ],
|
||
orderModel: model,
|
||
});
|
||
} catch (waveErr) {
|
||
this.ctx.logger.warn('[PendingOrderService.cloneOrder] 清理波次关联失败,不影响克隆', waveErr);
|
||
}
|
||
}
|
||
|
||
// 记录原订单"克隆"日志
|
||
try {
|
||
await this.ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'order',
|
||
businessId: orderId,
|
||
operationCode: 'ORDER_CLONE_SOURCE',
|
||
operator,
|
||
extras: {
|
||
warehouseId: logWarehouseId,
|
||
message: `订单克隆:原订单 ${orderId} 已取消,将创建新订单`,
|
||
},
|
||
beforeChanges: null,
|
||
});
|
||
} catch (logErr) {
|
||
this.ctx.logger.warn('[PendingOrderService.cloneOrder] 写入原订单克隆日志失败', logErr);
|
||
}
|
||
|
||
// 4. 构造新订单数据 — 保留业务字段,重置所有流程状态
|
||
const RESET_FIELDS = {
|
||
step: 0,
|
||
status: 'created',
|
||
inspection_status: 'none',
|
||
recheck_status: 'none',
|
||
storage_status: 'none',
|
||
post_status: 'none',
|
||
pick_status: 'none',
|
||
pack_status: 'none',
|
||
print_status: 'none',
|
||
claim_status: 'none',
|
||
outbound_status: 'none',
|
||
lock_status: 'none',
|
||
intercept_status: 'none',
|
||
sync_status: 'padding',
|
||
order_flag: '',
|
||
wave_id: 0,
|
||
delivery_time: null,
|
||
operate_time: null,
|
||
operator_name: null,
|
||
express_code: null,
|
||
logistics_area_code: null,
|
||
delete_at: null,
|
||
create_at: now,
|
||
updated_at: now,
|
||
};
|
||
|
||
// 业务字段白名单(从原订单复制)
|
||
const COPY_FIELDS = [
|
||
'delivery_order_code', 'pre_delivery_order_code', 'pre_delivery_order_id',
|
||
'order_type', 'warehouse_code', 'warehouse_id', 'store_id', 'from_key',
|
||
'source_platform_code', 'source_platform_name', 'source_order_codes',
|
||
'sys_platform_code', 'sys_platform_name',
|
||
'place_order_time', 'pay_time', 'pay_no',
|
||
'service_code', 'shop_nick', 'seller_nick', 'buyer_nick',
|
||
'total_amount', 'item_amount', 'discount_amount', 'freight',
|
||
'ar_amount', 'got_amount', 'service_fee',
|
||
'logistics_code', 'logistics_name', 'sys_logistics_code', 'sys_logistics_name',
|
||
'delivery_type', 'weight_type', 'is_urgency', 'invoice_flag',
|
||
'name', 'zip_code', 'tel', 'mobile', 'email',
|
||
'country_code', 'province', 'city', 'area', 'town', 'detail_address',
|
||
'id_type', 'id_number', 'oaid',
|
||
'items', 'items_count', 'items_total', 'items_weight', 'items_hash', 'items_crc',
|
||
];
|
||
|
||
const newOrderData = { ...RESET_FIELDS };
|
||
for (const field of COPY_FIELDS) {
|
||
if (original[field] !== undefined) {
|
||
newOrderData[field] = original[field];
|
||
}
|
||
}
|
||
|
||
// 克隆单同样由仓库序列表统一发号;发号失败直接抛错,不回退分表自增,
|
||
// 避免分表自增与序列表发号区间重叠产生冲突 id
|
||
await this.ctx.model.OrderDeliveryFactory.ensureLocationSequenceTable(warehouseId);
|
||
const allocatedOrderId = await this.ctx.model.OrderDeliveryFactory.allocateOrderId(warehouseId, null, 'current');
|
||
|
||
const newOrder = await model.create({ ...newOrderData, id: allocatedOrderId });
|
||
const newOrderId = Number(newOrder.id || newOrder.dataValues && newOrder.dataValues.id);
|
||
|
||
// 5. 克隆订单明细
|
||
try {
|
||
const orderItemsFactory = this.ctx.model && this.ctx.model.OrderItemsFactory;
|
||
if (orderItemsFactory && typeof orderItemsFactory.getCurrentModel === 'function') {
|
||
const itemsModel = await orderItemsFactory.getCurrentModel(warehouseId);
|
||
if (itemsModel && typeof itemsModel.findAll === 'function') {
|
||
const originalItems = await itemsModel.findAll({
|
||
where: { order_id: orderId },
|
||
raw: true,
|
||
});
|
||
|
||
if (Array.isArray(originalItems) && originalItems.length > 0) {
|
||
const ITEM_COPY_FIELDS = [
|
||
'actual_price', 'retail_price', 'ext_code', 'inventory_type',
|
||
'item_code', 'item_id', 'item_name', 'order_line_no', 'owner_code',
|
||
'plan_qty', 'source_order_code', 'sub_source_order_code',
|
||
'extend_props', 'stock_id', 'item_snapshot',
|
||
];
|
||
const newItems = originalItems.map(item => {
|
||
const newItem = { order_id: newOrderId, created_at: now, updated_at: now };
|
||
for (const field of ITEM_COPY_FIELDS) {
|
||
if (item[field] !== undefined) {
|
||
newItem[field] = item[field];
|
||
}
|
||
}
|
||
return newItem;
|
||
});
|
||
await itemsModel.bulkCreate(newItems);
|
||
}
|
||
}
|
||
}
|
||
} catch (itemsErr) {
|
||
this.ctx.logger.warn('[PendingOrderService.cloneOrder] 克隆订单明细失败', itemsErr);
|
||
throw new Error(`克隆订单明细失败:${itemsErr.message}`);
|
||
}
|
||
|
||
// 6. 记录新订单"克隆创建"日志
|
||
try {
|
||
await this.ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'order',
|
||
businessId: newOrderId,
|
||
operationCode: 'ORDER_CLONE_TARGET',
|
||
operator,
|
||
extras: {
|
||
warehouseId: logWarehouseId,
|
||
message: `克隆创建:由原订单 ${orderId} 克隆生成,新订单 ID ${newOrderId}`,
|
||
},
|
||
beforeChanges: null,
|
||
});
|
||
} catch (logErr) {
|
||
this.ctx.logger.warn('[PendingOrderService.cloneOrder] 写入新订单克隆创建日志失败', logErr);
|
||
}
|
||
|
||
return this.success('ok', {
|
||
source_order_id: orderId,
|
||
new_order_id: newOrderId,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 智能地址解析:使用 DeepSeek 将用户输入的地址字符串解析为结构化地址。
|
||
*
|
||
* 支持单条解析与数组批量解析两种模式:
|
||
* - 单条:data.address 传字符串,返回单条解析结果(与原行为一致)
|
||
* - 批量:data.addresses(或 data.address)传字符串数组,按数组顺序返回 data.list,
|
||
* 每条元素含 address/flag/message 与解析字段,失败条目不影响其他条目
|
||
*
|
||
* 采用"AI 解析 + 反向识别兜底"双层策略:
|
||
* 1. 先由 DeepSeek AI 进行语义级地址解析
|
||
* 2. 若 AI 返回的省/市/区字段缺失,通过内置的中国行政区划映射表反向补全
|
||
* 3. 仅在两层策略均无法确定 province 时才判定失败
|
||
*
|
||
* @param {Object} data 请求数据。
|
||
* @param {string|string[]} data.address 原始地址字符串或字符串数组(必填)。
|
||
* @param {string[]} [data.addresses] 批量地址字符串数组(与 address 数组二选一)。
|
||
* @return {Promise<Object>} 解析结果;批量模式返回 data.list 数组。
|
||
*/
|
||
async parseAddress(data = {}) {
|
||
// 批量模式:addresses 数组优先,其次 address 数组
|
||
const rawAddresses = Array.isArray(data.addresses)
|
||
? data.addresses
|
||
: (Array.isArray(data.address) ? data.address : null);
|
||
|
||
if (rawAddresses) {
|
||
if (!rawAddresses.length) {
|
||
return this.fail('地址数组不能为空');
|
||
}
|
||
if (rawAddresses.length > 50) {
|
||
return this.fail('单次批量解析最多支持 50 条地址');
|
||
}
|
||
// 批量提速:每 10 条合并为一次 DeepSeek 请求(实测 10 条约 18s、无截断),
|
||
// 所有块异步并行发出,全部完成后按输入顺序聚合返回;失败/缺失条目逐条回退单条解析。
|
||
const CHUNK_SIZE = 10;
|
||
const EMPTY_FIELDS = { province: '', city: '', area: '', town: '', detailAddress: '', name: '', mobile: '' };
|
||
const toListItem = r => ({
|
||
address: r.address,
|
||
flag: r.flag,
|
||
message: r.message,
|
||
...(r.fields || EMPTY_FIELDS),
|
||
});
|
||
const chunks = [];
|
||
for (let i = 0; i < rawAddresses.length; i += CHUNK_SIZE) {
|
||
chunks.push(rawAddresses.slice(i, i + CHUNK_SIZE));
|
||
}
|
||
const chunkResults = await Promise.all(chunks.map(chunk => this._parseAddressBatchOneShot(chunk)));
|
||
const results = await Promise.all(rawAddresses.map((item, idx) => {
|
||
const r = chunkResults[Math.floor(idx / CHUNK_SIZE)];
|
||
const inChunk = r && r[idx % CHUNK_SIZE];
|
||
return inChunk && inChunk.ok ? inChunk : this._parseSingleAddress(item);
|
||
}));
|
||
return this.success('地址解析成功', { list: results.map(toListItem) });
|
||
}
|
||
|
||
// 单条模式(向后兼容)
|
||
const single = await this._parseSingleAddress(data.address);
|
||
if (!single.ok) {
|
||
return this.fail(single.message);
|
||
}
|
||
return this.success('地址解析成功', single.fields);
|
||
}
|
||
|
||
/**
|
||
* 块内一次性解析:把一组地址(建议 10 条)合并为一次 DeepSeek 请求,
|
||
* 让模型按编号返回 JSON 数组,省去逐条请求的网络开销。
|
||
*
|
||
* @param {string[]} addressList 地址字符串数组。
|
||
* @return {Promise<Array|null>} 与入参顺序对齐的逐条结果数组;
|
||
* 请求失败/JSON 解析失败/被截断时返回 null,由调用方逐条回退单条解析。
|
||
*/
|
||
async _parseAddressBatchOneShot(addressList) {
|
||
const apiKey = this.config.deepseek.apiKey;
|
||
const baseUrl = this.config.deepseek.baseUrl || 'https://api.deepseek.com';
|
||
if (!apiKey) return null;
|
||
|
||
const numbered = addressList.map((a, i) => `${i + 1}. ${a}`).join('\n');
|
||
const prompt = `你是一个专业的中文地址解析助手。请一次性解析以下 ${addressList.length} 条地址,按编号顺序返回JSON数组,每条为:
|
||
{"index":编号,"province":"省","city":"市","area":"区/县","town":"乡镇/街道","detailAddress":"详细地址","name":"收件人","mobile":"手机号"}
|
||
规则:
|
||
1. 地址重复拼接时先智能去重再解析
|
||
2. 直辖市:province与city都填直辖市名,area填市辖区名
|
||
3. 无法识别的字段填空字符串
|
||
4. 只返回JSON数组,不含解释或markdown
|
||
|
||
地址列表:
|
||
${numbered}`;
|
||
|
||
try {
|
||
const result = await this.ctx.curl(`${baseUrl}/v1/chat/completions`, {
|
||
method: 'POST',
|
||
contentType: 'json',
|
||
dataType: 'json',
|
||
headers: {
|
||
Authorization: `Bearer ${apiKey}`,
|
||
},
|
||
data: {
|
||
model: 'deepseek-v4-flash',
|
||
messages: [
|
||
{ role: 'system', content: '你是一个专业的地址解析助手,只返回JSON格式结果。' },
|
||
{ role: 'user', content: prompt },
|
||
],
|
||
temperature: 0,
|
||
max_tokens: 32000,
|
||
},
|
||
timeout: 120000,
|
||
});
|
||
|
||
if (result.status !== 200 || !result.data) {
|
||
return null;
|
||
}
|
||
const choice = result.data.choices?.[0] || {};
|
||
// 被截断时整体回退,避免残缺数组造成大量错位
|
||
if ((choice.finish_reason || '') === 'length') {
|
||
return null;
|
||
}
|
||
|
||
const content = String(choice.message?.content || '').trim();
|
||
const arr = JSON.parse(extractJsonBlock(content));
|
||
if (!Array.isArray(arr)) {
|
||
return null;
|
||
}
|
||
this.ctx.logger.info('[parseAddress] 批量块请求完成:入参 %d 条,finish_reason=%s,返回 %d 条', addressList.length, choice.finish_reason, arr.length);
|
||
|
||
return addressList.map((address, idx) => {
|
||
if (!String(address || '').trim()) {
|
||
return { address, ok: false, flag: 'failure', message: '地址字符串不能为空', fields: null };
|
||
}
|
||
const item = arr.find(x => x && Number(x.index) === idx + 1);
|
||
if (!item) {
|
||
return { address, ok: false, flag: 'failure', message: '批量解析未返回该条结果', fields: null };
|
||
}
|
||
|
||
let province = String(item.province || '').trim();
|
||
let city = String(item.city || '').trim();
|
||
let area = String(item.area || '').trim();
|
||
let town = String(item.town || '').trim();
|
||
const detailAddress = String(item.detailAddress || '').trim();
|
||
const name = sanitizeName(item.name);
|
||
const mobile = sanitizeMobile(item.mobile);
|
||
|
||
// 反向识别兜底 + 正则兜底,与单条解析保持一致
|
||
const inferred = reverseInferAddress({ province, city, area, town, detailAddress, name, mobile });
|
||
province = inferred.province;
|
||
city = inferred.city;
|
||
area = inferred.area;
|
||
if (!province) {
|
||
const regexResult = extractAddressByRegex(address);
|
||
if (regexResult.province) {
|
||
province = regexResult.province;
|
||
city = city || regexResult.city;
|
||
area = area || regexResult.area;
|
||
town = town || regexResult.town;
|
||
}
|
||
}
|
||
|
||
if (!province || province === '暂未识别' || province === '其他') {
|
||
return { address, ok: false, flag: 'failure', message: '地址解析失败:省市区无法识别,请补充更多地址信息后重试', fields: null };
|
||
}
|
||
return {
|
||
address,
|
||
ok: true,
|
||
flag: 'success',
|
||
message: 'ok',
|
||
fields: { province, city, area, town, detailAddress, name, mobile },
|
||
};
|
||
});
|
||
} catch (error) {
|
||
this.ctx.logger.warn('[parseAddress] 批量一次性解析失败,将逐条回退: %s', error.message);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 解析单条地址(parseAddress 单条/批量模式共用)。
|
||
*
|
||
* @param {*} item 原始地址。
|
||
* @return {Promise<Object>} { address, ok, flag, message, fields };fields 为解析字段对象或 null。
|
||
*/
|
||
async _parseSingleAddress(item) {
|
||
const address = String(item || '').trim();
|
||
if (!address) {
|
||
return { address, ok: false, flag: 'failure', message: '地址字符串不能为空', fields: null };
|
||
}
|
||
|
||
const apiKey = this.config.deepseek.apiKey;
|
||
const baseUrl = this.config.deepseek.baseUrl || 'https://api.deepseek.com';
|
||
if (!apiKey) {
|
||
return { address, ok: false, flag: 'failure', message: 'DeepSeek API Key 未配置', fields: null };
|
||
}
|
||
|
||
try {
|
||
// 仅在 parseAddress 使用 v4-flash(速度优先,适合批量解析),不改全局配置
|
||
const model = 'deepseek-v4-flash';
|
||
const prompt = `你是一个专业的中文地址解析助手,拥有丰富的中国地理知识。请解析以下地址字符串。
|
||
|
||
规则:
|
||
1. 提取字段:province(省)、city(市)、area(区/县)、town(乡镇/街道)、detailAddress(详细地址)、name(收件人)、mobile(手机号)
|
||
2. **中国行政区划特殊规则(非常重要)**:
|
||
- 四大直辖市(北京、天津、上海、重庆):province填直辖市名,city填直辖市名,area填市辖区名(如"朝阳区")
|
||
- 省直辖县级市(如湖北仙桃/潜江/天门、河南济源、海南五指山/琼海/文昌/万宁/东方、新疆石河子等):province填省名,city填省名或留空,area填县级市名
|
||
- 不设区的地级市(如东莞、中山、嘉峪关、儋州、三沙):province填省名,city填地级市名,area填地级市名或留空
|
||
- 普通地级市代管的县级市(如苏州代管昆山、无锡代管江阴、潍坊代管寿光等):province填省名,city填地级市名,area填县级市名
|
||
3. **利用你的中国地理知识**:如果地址缺少省份或城市信息,请检索你的知识库反向推断。例如:
|
||
- "仙桃市xxx路" → province=湖北省, city=湖北省, area=仙桃市(省直辖县级市)
|
||
- "昆山市xxx镇" → province=江苏省, city=苏州市, area=昆山市(苏州代管县级市)
|
||
- "广东省东莞市xxx镇" → province=广东省, city=东莞市, area=东莞市(不设区的地级市)
|
||
- "浙江省xxx村" → 根据村名命名习惯和方言特征推测所属城市
|
||
4. 如果实在无法确定,province填"",city和area同理填"",收件人和name同理填"",mobile同理填""。
|
||
5. detailAddress去除省市区部分,只保留街道/村/门牌号
|
||
6. 地址字符串若出现重复拼接(如"陕西省延安市志丹县"出现两次),先智能去重再解析,合并保留重复部分中的街道/村信息
|
||
7. 只返回纯JSON,不含解释或markdown
|
||
|
||
地址字符串: "${address}"
|
||
|
||
请返回JSON:`;
|
||
|
||
const requestDeepSeek = async maxTokens => {
|
||
const result = await this.ctx.curl(`${baseUrl}/v1/chat/completions`, {
|
||
method: 'POST',
|
||
contentType: 'json',
|
||
dataType: 'json',
|
||
headers: {
|
||
Authorization: `Bearer ${apiKey}`,
|
||
},
|
||
data: {
|
||
model,
|
||
messages: [
|
||
{ role: 'system', content: '你是一个专业的地址解析助手,只返回JSON格式结果。' },
|
||
{ role: 'user', content: prompt },
|
||
],
|
||
temperature: 0,
|
||
max_tokens: maxTokens,
|
||
},
|
||
timeout: 60000,
|
||
});
|
||
|
||
if (result.status !== 200 || !result.data) {
|
||
return null;
|
||
}
|
||
const choice = result.data.choices?.[0] || {};
|
||
return {
|
||
content: String(choice.message?.content || '').trim(),
|
||
reasoningContent: String(choice.message?.reasoning_content || '').trim(),
|
||
finishReason: choice.finish_reason || '',
|
||
};
|
||
};
|
||
|
||
// deepseek-v4-flash 为思维链模型,max_tokens 过小时推理会耗尽全部配额,
|
||
// 导致 content 为空且 finish_reason=length。首次给足 3000 tokens,
|
||
// 仍被截断且无法从 reasoning_content 兜底时,加大到 8000 重试一次。
|
||
let response = await requestDeepSeek(3000);
|
||
if (
|
||
response
|
||
&& response.finishReason === 'length'
|
||
&& !response.content
|
||
&& !salvageFieldsFromText(response.reasoningContent)
|
||
) {
|
||
this.ctx.logger.warn('[parseAddress] 首次调用被截断(finish_reason=length),以 max_tokens=8000 重试');
|
||
response = await requestDeepSeek(8000);
|
||
}
|
||
|
||
if (!response) {
|
||
return { address, ok: false, flag: 'failure', message: '地址解析服务请求失败', fields: null };
|
||
}
|
||
|
||
const { content, reasoningContent, finishReason } = response;
|
||
this.ctx.logger.info('[parseAddress] DeepSeek原始返回 finish_reason=%s content: %s', finishReason, content || '(空)');
|
||
|
||
const tryParseJson = raw => {
|
||
try {
|
||
return JSON.parse(raw);
|
||
} catch (parseError) {
|
||
return null;
|
||
}
|
||
};
|
||
|
||
// 清理 markdown 代码块标记,并截取第一个 { 到最后一个 } 之间的 JSON 片段
|
||
let parsed = tryParseJson(extractJsonBlock(content));
|
||
if (!parsed) {
|
||
// 轻量修复:去除对象/数组内的尾随逗号后重试
|
||
parsed = tryParseJson(extractJsonBlock(content).replace(/,\s*([}\]])/g, '$1'));
|
||
}
|
||
|
||
// JSON 解析失败时,尝试从 content 或 reasoning_content 文本中做字段级提取兜底
|
||
if (!parsed) {
|
||
parsed = salvageFieldsFromText(content || reasoningContent);
|
||
if (parsed) {
|
||
this.ctx.logger.warn('[parseAddress] 正文字段提取兜底结果: %j', parsed);
|
||
}
|
||
}
|
||
|
||
if (!parsed) {
|
||
this.ctx.logger.warn('[parseAddress] JSON解析失败,finish_reason=%s,原始返回: %s', finishReason, content || reasoningContent);
|
||
if (finishReason === 'length') {
|
||
return { address, ok: false, flag: 'failure', message: '地址解析超时,请重试', fields: null };
|
||
}
|
||
return { address, ok: false, flag: 'failure', message: '地址解析结果格式异常,请重试', fields: null };
|
||
}
|
||
|
||
let province = String(parsed.province || '').trim();
|
||
let city = String(parsed.city || '').trim();
|
||
let area = String(parsed.area || '').trim();
|
||
let town = String(parsed.town || '').trim();
|
||
const detailAddress = String(parsed.detailAddress || '').trim();
|
||
const name = sanitizeName(parsed.name);
|
||
const mobile = sanitizeMobile(parsed.mobile);
|
||
|
||
// --- 反向识别兜底:使用内置行政区划映射表补全缺失字段 ---
|
||
const inferred = reverseInferAddress({
|
||
province,
|
||
city,
|
||
area,
|
||
town,
|
||
detailAddress,
|
||
name,
|
||
mobile,
|
||
});
|
||
province = inferred.province;
|
||
city = inferred.city;
|
||
area = inferred.area;
|
||
|
||
// --- 最终兜底:AI 与映射表均失败时,用正则从原始地址提取省市区 ---
|
||
if (!province) {
|
||
const regexResult = extractAddressByRegex(address);
|
||
if (regexResult.province) {
|
||
province = regexResult.province;
|
||
city = city || regexResult.city;
|
||
area = area || regexResult.area;
|
||
if (!town) {
|
||
town = regexResult.town;
|
||
}
|
||
this.ctx.logger.warn('[parseAddress] 正则兜底解析结果: %j', regexResult);
|
||
}
|
||
}
|
||
|
||
// 反向识别后仍无 province 才判定失败
|
||
if (!province || province === '暂未识别' || province === '其他') {
|
||
return { address, ok: false, flag: 'failure', message: '地址解析失败:省市区无法识别,请补充更多地址信息后重试', fields: null };
|
||
}
|
||
|
||
return {
|
||
address,
|
||
ok: true,
|
||
flag: 'success',
|
||
message: 'ok',
|
||
fields: {
|
||
province,
|
||
city,
|
||
area,
|
||
town,
|
||
detailAddress,
|
||
name,
|
||
mobile,
|
||
},
|
||
};
|
||
} catch (error) {
|
||
this.ctx.logger.error('[parseAddress] DeepSeek请求异常: %s', error.message);
|
||
return { address, ok: false, flag: 'failure', message: `地址解析失败: ${error.message}`, fields: null };
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 手动创建待处理订单。
|
||
*
|
||
* 根据货主策略(need_order_approval)自动决定订单初始步骤:
|
||
* - need_order_approval=1(默认)→ step=0 待审核
|
||
* - need_order_approval=0 → step=1 直接进待处理
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @param {number} data.store_id 货主ID(必填)。
|
||
* @param {string} data.name 收件人姓名(必填)。
|
||
* @param {string} [data.mobile] 收件人手机号(mobile/tel 至少一项必填)。
|
||
* @param {string} [data.tel] 收件人电话。
|
||
* @param {string} data.detail_address 详细地址(必填)。
|
||
* @param {string} [data.province] 省份。
|
||
* @param {string} [data.city] 城市。
|
||
* @param {string} [data.area] 区/县。
|
||
* @param {string} [data.town] 镇/街道。
|
||
* @param {string} [data.zip_code] 邮编。
|
||
* @param {Array<Object>} data.items 订单明细(必填,每项含 item_id 与 plan_qty)。
|
||
* @param {string} [data.delivery_order_code] 订单号,不传则自动生成。
|
||
* @param {string} [data.logistics_code] 快递编码,不传则读货主默认快递策略。
|
||
* @param {string} [data.logistics_name] 快递名称。
|
||
* @param {string} [data.sys_platform_code] 系统平台编码,不传则读货主默认平台策略。
|
||
* @param {string} [data.source_platform_code] 来源平台编码。
|
||
* @param {string} [data.source_order_codes] 来源订单号。
|
||
* @param {string} [data.order_type] 订单类型。
|
||
* @param {string} [data.is_urgency] 是否紧急(Y/N),默认 N。
|
||
* @param {string} [data.invoice_flag] 是否需要发票(Y/N),默认 N。
|
||
* @return {Promise<Object>} 统一 success 包装,含新订单 id 与 step 信息。
|
||
*/
|
||
async createOrder(data = {}) {
|
||
const requestData = this.isPlainObject(data) ? data : {};
|
||
const warehouseId = this.getWarehouseId();
|
||
|
||
// 1. 参数校验
|
||
const storeId = Number(requestData.store_id);
|
||
if (!Number.isInteger(storeId) || storeId <= 0) {
|
||
throw new Error('store_id(货主ID)不能为空');
|
||
}
|
||
|
||
const name = String(requestData.name || '').trim();
|
||
if (!name) {
|
||
throw new Error('收件人姓名不能为空');
|
||
}
|
||
|
||
const mobile = String(requestData.mobile || '').trim();
|
||
const tel = String(requestData.tel || '').trim();
|
||
if (!mobile && !tel) {
|
||
throw new Error('收件人手机号或电话至少填写一项');
|
||
}
|
||
|
||
const detailAddress = String(requestData.detail_address || '').trim();
|
||
if (!detailAddress) {
|
||
throw new Error('详细地址不能为空');
|
||
}
|
||
|
||
const province = String(requestData.province || '').trim();
|
||
if (!province) {
|
||
throw new Error('省份不能为空');
|
||
}
|
||
|
||
const city = String(requestData.city || '').trim();
|
||
if (!city) {
|
||
throw new Error('城市不能为空');
|
||
}
|
||
|
||
const area = String(requestData.area || '').trim();
|
||
if (!area) {
|
||
throw new Error('区县不能为空');
|
||
}
|
||
|
||
const rawItems = requestData.items;
|
||
if (!Array.isArray(rawItems) || rawItems.length === 0) {
|
||
throw new Error('订单明细 items 不能为空');
|
||
}
|
||
|
||
// 2. 适配明细格式并校验(转为 addOrder 所需的驼峰格式)
|
||
// 手工单:item_id 即为仓库 stock_id,无需查 stock_store 做映射
|
||
const orderLineItems = rawItems.map((item, idx) => {
|
||
if (!item || typeof item !== 'object') {
|
||
throw new Error(`第${idx + 1}行明细格式无效`);
|
||
}
|
||
const itemId = Number(item.item_id);
|
||
if (!Number.isInteger(itemId) || itemId <= 0) {
|
||
throw new Error(`第${idx + 1}行商品 item_id 必须为正整数`);
|
||
}
|
||
const planQty = Number(item.plan_qty);
|
||
if (!Number.isInteger(planQty) || planQty <= 0) {
|
||
throw new Error(`第${idx + 1}行计划数量 plan_qty 必须为正整数`);
|
||
}
|
||
return {
|
||
itemCode: String(item.item_code || '').trim(),
|
||
itemId,
|
||
itemName: String(item.item_name || '').trim() || '商品',
|
||
planQty,
|
||
stockId: itemId,
|
||
orderLineNo: String(item.order_line_no || String(idx + 1)).trim(),
|
||
actualPrice: Number(item.actual_price) || 0,
|
||
};
|
||
});
|
||
|
||
// 3. 自动生成订单号(如未传)
|
||
const deliveryOrderCode = String(requestData.delivery_order_code || '').trim()
|
||
|| `SYS${Date.now()}${Math.floor(Math.random() * 9000) + 1000}`;
|
||
// 4. 适配为 addOrder 所需的奇门嵌套格式
|
||
const adaptedData = {
|
||
request: {
|
||
deliveryOrder: {
|
||
deliveryOrderCode,
|
||
orderType: String(requestData.order_type || '').trim(),
|
||
sourcePlatformCode: String(requestData.source_platform_code || requestData.sys_platform_code || '').trim(),
|
||
sourcePlatformName: String(requestData.source_platform_name || '').trim(),
|
||
createChannel: String(requestData.create_channel || requestData.createChannel || 'MANUAL').trim().toUpperCase() || 'MANUAL',
|
||
logisticsCode: String(requestData.logistics_code || '').trim(),
|
||
logisticsName: String(requestData.logistics_name || '').trim(),
|
||
isUrgency: [ 'Y', 'N' ].includes(requestData.is_urgency) ? requestData.is_urgency : 'N',
|
||
invoiceFlag: [ 'Y', 'N' ].includes(requestData.invoice_flag) ? requestData.invoice_flag : 'N',
|
||
shopNick: String(requestData.shop_nick || requestData.shopNick || '').trim(),
|
||
receiverInfo: {
|
||
name,
|
||
mobile,
|
||
tel,
|
||
province,
|
||
city,
|
||
area,
|
||
town: String(requestData.town || '').trim(),
|
||
detailAddress,
|
||
zipCode: String(requestData.zip_code || '').trim(),
|
||
},
|
||
remark: String(requestData.remark || '').trim(),
|
||
},
|
||
orderLines: {
|
||
orderLine: orderLineItems,
|
||
},
|
||
},
|
||
};
|
||
|
||
const info = {
|
||
storeId,
|
||
warehouseId,
|
||
appKey: (this.ctx.user && this.ctx.user.app_key) || '',
|
||
};
|
||
|
||
// 6. 委托 addOrder 执行完整逻辑(库存预占、平台快递解析、入队列、操作日志)
|
||
const result = await this.service.systems.deliveryOrder.addOrder(adaptedData, info);
|
||
|
||
if (!result.success) {
|
||
throw new Error(result.message || '订单创建失败');
|
||
}
|
||
|
||
// 重复订单视为错误(与原逻辑保持一致)
|
||
if (result.message === '订单已存在' || (result.data && result.data.deliveryOrderId)) {
|
||
throw new Error(`订单号 ${deliveryOrderCode} 已存在`);
|
||
}
|
||
|
||
const orderId = result.data && result.data.orderId;
|
||
const step = result.data && result.data.step;
|
||
const itemsTotal = orderLineItems.reduce((sum, item) => sum + item.planQty, 0);
|
||
|
||
return this.success('ok', {
|
||
order_id: orderId,
|
||
delivery_order_code: deliveryOrderCode,
|
||
step,
|
||
step_label: step === 0 ? '待审核' : (step === 1 ? '待处理' : ''),
|
||
items_count: orderLineItems.length,
|
||
items_total: itemsTotal,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 下载创建订单导入模板。
|
||
*
|
||
* 返回 base64 编码的 Excel 文件内容,前端解码后作为 .xlsx 文件下载。
|
||
*
|
||
* @return {Promise<Object>} 统一 success 包装,含 base64 字符串与文件名。
|
||
*/
|
||
async downloadCreateTemplate() {
|
||
const ExcelJS = require('exceljs');
|
||
const workbook = new ExcelJS.Workbook();
|
||
const sheet = workbook.addWorksheet('创建订单导入模板');
|
||
|
||
const columns = [
|
||
// 必填
|
||
{ header: '*订单号', key: 'delivery_order_code', width: 24 },
|
||
{ header: '店铺名称', key: 'shop_nick', width: 20 },
|
||
{ header: '*收件人姓名', key: 'name', width: 16 },
|
||
{ header: '*手机号(mobile/tel至少填一项)', key: 'mobile', width: 28 },
|
||
{ header: '*详细地址', key: 'detail_address', width: 36 },
|
||
{ header: '*商品编码', key: 'item_code', width: 20 },
|
||
{ header: '*计划数量', key: 'plan_qty', width: 12 },
|
||
// 非必填
|
||
{ header: '货主ID', key: 'store_id', width: 12 },
|
||
{ header: '电话', key: 'tel', width: 16 },
|
||
{ header: '省份', key: 'province', width: 12 },
|
||
{ header: '城市', key: 'city', width: 12 },
|
||
{ header: '区/县', key: 'area', width: 12 },
|
||
{ header: '镇/街道', key: 'town', width: 12 },
|
||
{ header: '邮编', key: 'zip_code', width: 12 },
|
||
{ header: '快递编码', key: 'logistics_code', width: 16 },
|
||
{ header: '快递名称', key: 'logistics_name', width: 16 },
|
||
{ header: '系统平台编码', key: 'sys_platform_code', width: 16 },
|
||
{ header: '来源平台编码', key: 'source_platform_code', width: 16 },
|
||
{ header: '来源订单号', key: 'source_order_codes', width: 20 },
|
||
{ header: '订单类型', key: 'order_type', width: 14 },
|
||
{ header: '是否紧急(Y/N)', key: 'is_urgency', width: 16 },
|
||
{ header: '是否需要发票(Y/N)', key: 'invoice_flag', width: 18 },
|
||
{ header: '商品名称', key: 'item_name', width: 24 },
|
||
{ header: '行号', key: 'order_line_no', width: 10 },
|
||
{ header: '实际价格', key: 'actual_price', width: 12 },
|
||
];
|
||
|
||
sheet.columns = columns;
|
||
|
||
const headerRow = sheet.getRow(1);
|
||
headerRow.eachCell((cell, colNumber) => {
|
||
const col = columns[colNumber - 1];
|
||
const isRequired = col && col.header.startsWith('*');
|
||
cell.font = { bold: true, color: { argb: 'FF000000' } };
|
||
cell.fill = {
|
||
type: 'pattern',
|
||
pattern: 'solid',
|
||
fgColor: { argb: isRequired ? 'FFFFC000' : 'FFD9D9D9' },
|
||
};
|
||
cell.alignment = { vertical: 'middle', horizontal: 'center', wrapText: true };
|
||
cell.border = {
|
||
top: { style: 'thin' },
|
||
left: { style: 'thin' },
|
||
bottom: { style: 'thin' },
|
||
right: { style: 'thin' },
|
||
};
|
||
});
|
||
headerRow.height = 36;
|
||
|
||
sheet.addRow({
|
||
delivery_order_code: 'ORD20260421001',
|
||
store_id: 1,
|
||
name: '张三',
|
||
mobile: '13800138000',
|
||
tel: '',
|
||
detail_address: 'XX路XX号',
|
||
province: '广东省',
|
||
city: '深圳市',
|
||
area: '南山区',
|
||
town: '',
|
||
zip_code: '518000',
|
||
logistics_code: 'STO',
|
||
logistics_name: '申通快递',
|
||
sys_platform_code: 'TB',
|
||
source_platform_code: '',
|
||
source_order_codes: '',
|
||
order_type: '',
|
||
is_urgency: 'N',
|
||
invoice_flag: 'N',
|
||
item_code: 'SKU001',
|
||
item_name: '商品A',
|
||
plan_qty: 2,
|
||
order_line_no: '1',
|
||
actual_price: 9.90,
|
||
shop_nick: '',
|
||
});
|
||
|
||
sheet.addRow({
|
||
delivery_order_code: 'ORD20260421001',
|
||
store_id: 1,
|
||
name: '张三',
|
||
mobile: '13800138000',
|
||
tel: '',
|
||
detail_address: 'XX路XX号',
|
||
province: '广东省',
|
||
city: '深圳市',
|
||
area: '南山区',
|
||
town: '',
|
||
zip_code: '518000',
|
||
logistics_code: 'STO',
|
||
logistics_name: '申通快递',
|
||
sys_platform_code: 'TB',
|
||
source_platform_code: '',
|
||
source_order_codes: '',
|
||
order_type: '',
|
||
is_urgency: 'N',
|
||
invoice_flag: 'N',
|
||
item_code: 'SKU002',
|
||
item_name: '商品B',
|
||
plan_qty: 1,
|
||
order_line_no: '2',
|
||
actual_price: 19.90,
|
||
shop_nick: '',
|
||
});
|
||
|
||
const noteSheet = workbook.addWorksheet('填写说明');
|
||
noteSheet.getColumn(1).width = 80;
|
||
const notes = [
|
||
'【填写说明】',
|
||
'1. 带 * 的列为必填项,表头背景为橙色。',
|
||
'2. 每一行代表一条商品明细;同一订单的多个商品,订单号(delivery_order_code)必须相同。',
|
||
'3. 同一订单的所有行中,订单头信息(收件人、地址等)取第一行的值,后续行可省略但不影响解析。',
|
||
'4. mobile 和 tel 至少填写一项。',
|
||
'5. 计划数量(plan_qty)必须为正整数。',
|
||
'6. 是否紧急、是否需要发票只接受 Y 或 N(大写),不填默认 N。',
|
||
'7. 快递编码、系统平台编码不填时,系统会读取货主默认策略自动补充;不填货主ID时,系统会从当前登录用户的上下文自动获取。',
|
||
'8. 同一文件内,相同订单号只会创建一个订单,不会重复创建。',
|
||
];
|
||
notes.forEach((note, i) => {
|
||
const row = noteSheet.getRow(i + 1);
|
||
row.getCell(1).value = note;
|
||
if (i === 0) {
|
||
row.getCell(1).font = { bold: true, size: 13 };
|
||
}
|
||
});
|
||
|
||
const buffer = await workbook.xlsx.writeBuffer();
|
||
const base64 = Buffer.from(buffer).toString('base64');
|
||
|
||
return this.success('ok', {
|
||
base64,
|
||
filename: '创建订单导入模板.xlsx',
|
||
mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 归一化 ids 入参为去重后的正整数数组。
|
||
*
|
||
* 支持数组、逗号分隔字符串、单个 number/string。
|
||
*
|
||
* @param {Array<number|string>|number|string} value 原始 ids 入参。
|
||
* @return {Array<number>} 归一化后的 ids 数组。
|
||
*/
|
||
normalizeIdsInput(value) {
|
||
let sourceList = [];
|
||
|
||
if (Array.isArray(value)) {
|
||
sourceList = value;
|
||
} else if (typeof value === 'string') {
|
||
sourceList = value.split(',');
|
||
} else if (typeof value === 'number') {
|
||
sourceList = [ value ];
|
||
} else {
|
||
sourceList = [];
|
||
}
|
||
|
||
const normalizedIds = sourceList
|
||
.map(item => String(item === undefined || item === null ? '' : item).trim())
|
||
.filter(item => item !== '')
|
||
.map(item => Number(item))
|
||
.filter(item => Number.isInteger(item) && item > 0);
|
||
|
||
return [ ...new Set(normalizedIds) ];
|
||
}
|
||
|
||
/**
|
||
* 批量拦截订单。
|
||
*
|
||
* 提交后台异步任务,将给定订单的 intercept_status 更新为 'requested'。
|
||
* 仅处理当前仓库上下文内的订单。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @param {Array<number|string>} [data.order_ids] 订单ID数组(下划线写法)。
|
||
* @param {Array<number|string>} [data.orderIds] 订单ID数组(驼峰别名)。
|
||
* @param {Array<number|string>} [data.ids] 订单ID数组(简写别名)。
|
||
* @param {string} [data.task_id] 任务ID(用于查询进度)。
|
||
* @param {string} [data.taskId] 任务ID(驼峰别名)。
|
||
* @return {Promise<Object>} 提交结果,包含 task_id、状态与 accepted_at。
|
||
*/
|
||
async batchIntercept(data = {}) {
|
||
const warehouseId = Number(this.getWarehouseId() || 0);
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||
throw new Error('未识别到当前仓库上下文');
|
||
}
|
||
const normalizedOrderIds = this.normalizeBatchInterceptOrderIds(data);
|
||
if (normalizedOrderIds.length === 0) {
|
||
throw new Error('order_ids 参数不能为空或格式错误');
|
||
}
|
||
|
||
const requestedTaskId = this.normalizeBatchInterceptTaskId(data);
|
||
const taskId = requestedTaskId || this.generateBatchInterceptTaskId(warehouseId);
|
||
const existingTask = await this.getBatchInterceptTaskProgress(taskId);
|
||
|
||
if (existingTask) {
|
||
return this.success('ok', {
|
||
status: 'success',
|
||
task_id: taskId,
|
||
warehouse_id: Number(existingTask.warehouse_id || warehouseId),
|
||
state: String(existingTask.state || 'submitted').trim() || 'submitted',
|
||
message: '批量拦截任务已存在,请勿重复提交。',
|
||
accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(),
|
||
});
|
||
}
|
||
|
||
const acceptedAt = new Date().toISOString();
|
||
await this.setBatchInterceptTaskProgress(taskId, 'submitted', {
|
||
warehouse_id: warehouseId,
|
||
order_ids: normalizedOrderIds.join(','),
|
||
order_id_list: normalizedOrderIds,
|
||
total_order_count: normalizedOrderIds.length,
|
||
processed_order_count: 0,
|
||
intercepted_order_count: 0,
|
||
progress_percent: 0,
|
||
submitted_at: Date.now(),
|
||
accepted_at: acceptedAt,
|
||
result: null,
|
||
error: '',
|
||
error_code: '',
|
||
});
|
||
|
||
this.ctx.logger.info('[order.pendingOrder.batchIntercept] 任务提交成功', {
|
||
taskId,
|
||
warehouseId,
|
||
orderCount: normalizedOrderIds.length,
|
||
});
|
||
|
||
setImmediate(() => {
|
||
this.runBatchInterceptTask({
|
||
taskId,
|
||
warehouseId,
|
||
orderIds: normalizedOrderIds,
|
||
}).catch(error => {
|
||
this.ctx.logger.error('[order.pendingOrder.batchIntercept] 后台任务异常', {
|
||
taskId,
|
||
warehouseId,
|
||
orderCount: normalizedOrderIds.length,
|
||
error: error && error.message ? error.message : error,
|
||
stack: error && error.stack ? error.stack : '',
|
||
});
|
||
});
|
||
});
|
||
|
||
return this.success('ok', {
|
||
status: 'success',
|
||
task_id: taskId,
|
||
warehouse_id: warehouseId,
|
||
message: '批量拦截任务已提交。',
|
||
accepted_at: acceptedAt,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 查询批量拦截任务进度。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @param {string} data.task_id 任务ID(下划线写法)。
|
||
* @param {string} data.taskId 任务ID(驼峰写法)。
|
||
* @return {Promise<Object>} 任务进度响应。
|
||
*/
|
||
async batchInterceptTaskProgress(data = {}) {
|
||
const taskId = this.normalizeBatchInterceptTaskId(data);
|
||
if (!taskId) {
|
||
return this.fail('task_id 参数不能为空', 400);
|
||
}
|
||
|
||
const cachedProgress = await this.getBatchInterceptTaskProgress(taskId);
|
||
if (!cachedProgress) {
|
||
return this.success('ok', {
|
||
task_id: taskId,
|
||
state: 'not_found',
|
||
});
|
||
}
|
||
|
||
const state = String(cachedProgress.state || 'submitted').trim() || 'submitted';
|
||
const payload = {
|
||
task_id: taskId,
|
||
state,
|
||
warehouse_id: Number(cachedProgress.warehouse_id || 0),
|
||
submitted_at: cachedProgress.submitted_at || null,
|
||
start_time: cachedProgress.start_time || null,
|
||
end_time: cachedProgress.end_time || null,
|
||
};
|
||
|
||
if (state === 'submitted' || state === 'running') {
|
||
payload.progress_percent = Number(cachedProgress.progress_percent || 0);
|
||
payload.total_order_count = Number(cachedProgress.total_order_count || 0);
|
||
payload.processed_order_count = Number(cachedProgress.processed_order_count || 0);
|
||
payload.intercepted_order_count = Number(cachedProgress.intercepted_order_count || 0);
|
||
}
|
||
|
||
if (state === 'success') {
|
||
const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {};
|
||
payload.progress_percent = Number(cachedProgress.progress_percent || 100);
|
||
payload.total_order_count = Number(result.total_order_count || 0);
|
||
payload.intercepted_order_count = Number(result.intercepted_order_count || 0);
|
||
payload.intercepted_order_ids = this.normalizeIdsInput(result.intercepted_order_ids);
|
||
payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0);
|
||
}
|
||
|
||
if (state === 'failed') {
|
||
payload.progress_percent = Number(cachedProgress.progress_percent || 0);
|
||
payload.total_order_count = Number(cachedProgress.total_order_count || 0);
|
||
payload.intercepted_order_count = Number(cachedProgress.intercepted_order_count || 0);
|
||
payload.error_message = String(cachedProgress.error || '').trim();
|
||
payload.error_code = String(cachedProgress.error_code || '').trim() || 'BATCH_INTERCEPT_FAILED';
|
||
payload.duration_ms = Number(cachedProgress.duration_ms || 0);
|
||
}
|
||
|
||
return this.success('ok', payload);
|
||
}
|
||
|
||
/**
|
||
* 生成可追踪的批量拦截任务ID。
|
||
*
|
||
* 格式:order_intercept_{warehouseId}_{timestamp}_{rand}。
|
||
*
|
||
* @param {number|string} warehouseId 仓库ID。
|
||
* @return {string} 任务ID。
|
||
*/
|
||
generateBatchInterceptTaskId(warehouseId = 0) {
|
||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||
const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0
|
||
? normalizedWarehouseId
|
||
: 0;
|
||
const timestamp = Math.floor(Date.now() / 1000);
|
||
const randomPart = Math.random().toString(36).slice(2, 6);
|
||
return `order_intercept_${safeWarehouseId}_${timestamp}_${randomPart}`;
|
||
}
|
||
|
||
/**
|
||
* 归一化批量拦截任务ID。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @param {string} data.task_id 任务ID(下划线写法)。
|
||
* @param {string} data.taskId 任务ID(驼峰写法)。
|
||
* @return {string} 归一化后的任务ID。
|
||
*/
|
||
normalizeBatchInterceptTaskId(data = {}) {
|
||
const normalizedData = this.isPlainObject(data) ? data : {};
|
||
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
|
||
}
|
||
|
||
/**
|
||
* 归一化批量拦截的订单ID参数。
|
||
* 兼容 order_ids / orderIds / ids 三种入参别名。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @return {Array<number>} 归一化后的订单ID数组。
|
||
*/
|
||
normalizeBatchInterceptOrderIds(data = {}) {
|
||
const normalizedData = this.isPlainObject(data) ? data : {};
|
||
const rawOrderIds = normalizedData.order_ids !== undefined
|
||
? normalizedData.order_ids
|
||
: normalizedData.orderIds !== undefined
|
||
? normalizedData.orderIds
|
||
: normalizedData.ids !== undefined
|
||
? normalizedData.ids
|
||
: [];
|
||
|
||
return this.normalizeIdsInput(rawOrderIds);
|
||
}
|
||
|
||
/**
|
||
* 获取批量拦截任务缓存键。
|
||
*
|
||
* @param {string} taskId 任务ID。
|
||
* @return {string} 缓存键。
|
||
*/
|
||
getBatchInterceptTaskCacheKey(taskId = '') {
|
||
const normalizedTaskId = String(taskId || '').trim();
|
||
if (!normalizedTaskId) {
|
||
return '';
|
||
}
|
||
|
||
return `${BATCH_INTERCEPT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
|
||
}
|
||
|
||
/**
|
||
* 写入批量拦截任务进度缓存。
|
||
*
|
||
* @param {string} taskId 任务ID。
|
||
* @param {string} state 任务状态(submitted|running|success|failed)。
|
||
* @param {Object} data 进度或结果数据。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async setBatchInterceptTaskProgress(taskId = '', state = 'submitted', data = {}) {
|
||
const cacheKey = this.getBatchInterceptTaskCacheKey(taskId);
|
||
if (!cacheKey) {
|
||
return;
|
||
}
|
||
|
||
const safeData = this.isPlainObject(data) ? data : {};
|
||
const mergedPayload = {
|
||
...(await this.getBatchInterceptTaskProgress(taskId) || {}),
|
||
...safeData,
|
||
task_id: String(taskId || '').trim(),
|
||
state: String(state || '').trim() || 'submitted',
|
||
update_time: Date.now(),
|
||
};
|
||
|
||
try {
|
||
await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_INTERCEPT_TASK_CACHE_TTL_SECONDS);
|
||
} catch (error) {
|
||
this.ctx.logger.warn(
|
||
`[order.pendingOrder.batchIntercept] 写入任务进度缓存失败: ${error && error.message ? error.message : error}`
|
||
);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 读取批量拦截任务进度缓存。
|
||
*
|
||
* @param {string} taskId 任务ID。
|
||
* @return {Promise<Object|null>} 缓存对象。
|
||
*/
|
||
async getBatchInterceptTaskProgress(taskId = '') {
|
||
const cacheKey = this.getBatchInterceptTaskCacheKey(taskId);
|
||
if (!cacheKey) {
|
||
return null;
|
||
}
|
||
|
||
try {
|
||
const cached = await this.app.getCacheAsync(cacheKey);
|
||
if (!this.isPlainObject(cached)) {
|
||
return null;
|
||
}
|
||
|
||
return cached;
|
||
} catch (error) {
|
||
this.ctx.logger.warn(
|
||
`[order.pendingOrder.batchIntercept] 读取任务进度缓存失败: ${error && error.message ? error.message : error}`
|
||
);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 执行批量拦截后台任务。
|
||
*
|
||
* 直接对给定订单ID数组,将 intercept_status 更新为 'requested',并写入操作日志。
|
||
* 仅处理当前仓库上下文内的订单。
|
||
*
|
||
* @param {Object} params 任务参数。
|
||
* @param {string} params.taskId 任务ID。
|
||
* @param {number|string} [params.warehouseId] 仓库ID(兜底)。
|
||
* @param {Array<number|string>|number|string} [params.orderIds] 订单ID集合(兜底)。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async runBatchInterceptTask(params = {}) {
|
||
const { ctx } = this;
|
||
const normalizedTaskId = String(params && params.taskId || '').trim();
|
||
if (!normalizedTaskId) {
|
||
throw new Error('taskId 不能为空');
|
||
}
|
||
|
||
const cachedTask = await this.getBatchInterceptTaskProgress(normalizedTaskId);
|
||
const warehouseId = Number(
|
||
cachedTask && cachedTask.warehouse_id !== undefined
|
||
? cachedTask.warehouse_id
|
||
: params && params.warehouseId
|
||
);
|
||
const orderIds = this.normalizeIdsInput(
|
||
cachedTask && cachedTask.order_ids !== undefined
|
||
? cachedTask.order_ids
|
||
: params && params.orderIds
|
||
);
|
||
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||
await this.setBatchInterceptTaskProgress(normalizedTaskId, 'failed', {
|
||
end_time: Date.now(),
|
||
error: 'warehouse_id 参数不合法',
|
||
error_code: 'INVALID_WAREHOUSE_ID',
|
||
});
|
||
return;
|
||
}
|
||
|
||
if (orderIds.length === 0) {
|
||
await this.setBatchInterceptTaskProgress(normalizedTaskId, 'failed', {
|
||
warehouse_id: warehouseId,
|
||
end_time: Date.now(),
|
||
error: 'order_ids 参数不能为空或格式错误',
|
||
error_code: 'INVALID_ORDER_IDS',
|
||
});
|
||
return;
|
||
}
|
||
|
||
const startTime = Date.now();
|
||
await this.setBatchInterceptTaskProgress(normalizedTaskId, 'running', {
|
||
warehouse_id: warehouseId,
|
||
order_ids: orderIds.join(','),
|
||
order_id_list: orderIds,
|
||
total_order_count: orderIds.length,
|
||
processed_order_count: 0,
|
||
intercepted_order_count: 0,
|
||
progress_percent: 0,
|
||
start_time: startTime,
|
||
end_time: null,
|
||
result: null,
|
||
error: '',
|
||
error_code: '',
|
||
failed_order_id: 0,
|
||
});
|
||
|
||
try {
|
||
const orderModel = await this.getOrderModel('pendingOrder', warehouseId);
|
||
const { Op } = this.app.Sequelize;
|
||
|
||
// 分批查询订单是否存在且属于当前仓库
|
||
const BATCH_SIZE = 500;
|
||
const validOrderRows = [];
|
||
|
||
for (let i = 0; i < orderIds.length; i += BATCH_SIZE) {
|
||
const chunkOrderIds = orderIds.slice(i, i + BATCH_SIZE);
|
||
if (chunkOrderIds.length === 0) {
|
||
continue;
|
||
}
|
||
|
||
const orderRows = await orderModel.findAll({
|
||
attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code' ],
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
id: {
|
||
[Op.in]: chunkOrderIds,
|
||
},
|
||
},
|
||
raw: true,
|
||
});
|
||
|
||
for (const row of (Array.isArray(orderRows) ? orderRows : [])) {
|
||
validOrderRows.push(row);
|
||
}
|
||
}
|
||
|
||
const interceptedOrderIds = [];
|
||
const operator = this.getOrderLogOperator();
|
||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||
|
||
const normalizedOrderRows = Array.isArray(validOrderRows) ? validOrderRows : [];
|
||
const totalOrderCount = orderIds.length;
|
||
const validOrderCount = normalizedOrderRows.length;
|
||
|
||
await this.setBatchInterceptTaskProgress(normalizedTaskId, 'running', {
|
||
warehouse_id: warehouseId,
|
||
total_order_count: totalOrderCount,
|
||
valid_order_count: validOrderCount,
|
||
});
|
||
|
||
if (validOrderCount === 0) {
|
||
const durationMs = Date.now() - startTime;
|
||
await this.setBatchInterceptTaskProgress(normalizedTaskId, 'success', {
|
||
warehouse_id: warehouseId,
|
||
total_order_count: totalOrderCount,
|
||
intercepted_order_count: 0,
|
||
progress_percent: 100,
|
||
end_time: Date.now(),
|
||
duration_ms: durationMs,
|
||
result: {
|
||
order_ids: orderIds,
|
||
intercepted_order_ids: [],
|
||
intercepted_order_count: 0,
|
||
total_order_count: totalOrderCount,
|
||
duration_ms: durationMs,
|
||
message: '未找到可拦截的当前仓库订单',
|
||
},
|
||
});
|
||
return;
|
||
}
|
||
|
||
// 分批更新拦截状态,每批最多500条
|
||
const UPDATE_CHUNK_SIZE = 500;
|
||
for (let i = 0; i < normalizedOrderRows.length; i += UPDATE_CHUNK_SIZE) {
|
||
const chunkRows = normalizedOrderRows.slice(i, i + UPDATE_CHUNK_SIZE);
|
||
if (chunkRows.length === 0) {
|
||
continue;
|
||
}
|
||
|
||
const chunkOrderIds = chunkRows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0);
|
||
if (chunkOrderIds.length === 0) {
|
||
continue;
|
||
}
|
||
|
||
const now = new Date();
|
||
const updateValues = {
|
||
intercept_status: 'requested',
|
||
updated_at: now,
|
||
};
|
||
|
||
await orderModel.update(updateValues, {
|
||
where: {
|
||
id: {
|
||
[Op.in]: chunkOrderIds,
|
||
},
|
||
},
|
||
});
|
||
|
||
// 同步更新运单表拦截标记
|
||
try {
|
||
await ctx.model.OrderExpress.update(
|
||
{ is_intercept: 'Y' },
|
||
{ where: { order_id: { [Op.in]: chunkOrderIds }, warehouse_id: warehouseId } }
|
||
);
|
||
} catch (expressErr) {
|
||
ctx.logger.warn(
|
||
`[order.pendingOrder.batchIntercept] 更新运单拦截标记失败, count=${chunkOrderIds.length}, error=${expressErr.message}`
|
||
);
|
||
}
|
||
|
||
// 创建售后工单 + 通知快递群(失败不影响主流程)
|
||
try {
|
||
const op = this.getOrderLogOperator();
|
||
await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({
|
||
orderIds: chunkOrderIds,
|
||
warehouseId,
|
||
creatorLabel: op.name || '系统',
|
||
});
|
||
} catch (workOrderErr) {
|
||
ctx.logger.warn(
|
||
`[order.pendingOrder.batchIntercept] 创建工单/通知失败, count=${chunkOrderIds.length}, error=${workOrderErr.message}`
|
||
);
|
||
}
|
||
|
||
// 写入操作日志
|
||
const logPayloads = chunkRows.map(row => {
|
||
const orderId = Number(row.id || 0);
|
||
const orderNo = String(row.delivery_order_code || row.pre_delivery_order_code || '').trim();
|
||
if (!Number.isInteger(orderId) || orderId <= 0) {
|
||
return null;
|
||
}
|
||
|
||
return {
|
||
businessType: 'order',
|
||
businessId: orderId,
|
||
operationCode: 'ORDER_INTERCEPT_REQUEST',
|
||
operator,
|
||
extras: {
|
||
warehouseId: logWarehouseId,
|
||
orderId,
|
||
orderNo,
|
||
newInterceptStatus: 'requested',
|
||
},
|
||
beforeChanges: null,
|
||
};
|
||
}).filter(Boolean);
|
||
|
||
if (logPayloads.length > 0) {
|
||
try {
|
||
const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
|
||
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
|
||
await operationLogService.createOperationLogs(logPayloads);
|
||
}
|
||
} catch (logErr) {
|
||
ctx.logger.warn(
|
||
`[order.pendingOrder.batchIntercept] 批量写操作日志失败,不影响主流程, count=${logPayloads.length}, error=${logErr.message}`
|
||
);
|
||
}
|
||
}
|
||
|
||
for (const orderId of chunkOrderIds) {
|
||
interceptedOrderIds.push(orderId);
|
||
}
|
||
|
||
// 更新进度
|
||
const progressPercent = validOrderCount > 0
|
||
? Math.min(99, Math.round((interceptedOrderIds.length / validOrderCount) * 100))
|
||
: 0;
|
||
|
||
await this.setBatchInterceptTaskProgress(normalizedTaskId, 'running', {
|
||
warehouse_id: warehouseId,
|
||
total_order_count: totalOrderCount,
|
||
intercepted_order_count: interceptedOrderIds.length,
|
||
progress_percent: progressPercent,
|
||
});
|
||
}
|
||
|
||
const durationMs = Date.now() - startTime;
|
||
await this.setBatchInterceptTaskProgress(normalizedTaskId, 'success', {
|
||
warehouse_id: warehouseId,
|
||
total_order_count: totalOrderCount,
|
||
intercepted_order_count: interceptedOrderIds.length,
|
||
progress_percent: 100,
|
||
end_time: Date.now(),
|
||
duration_ms: durationMs,
|
||
result: {
|
||
order_ids: orderIds,
|
||
intercepted_order_ids: interceptedOrderIds,
|
||
intercepted_order_count: interceptedOrderIds.length,
|
||
total_order_count: totalOrderCount,
|
||
duration_ms: durationMs,
|
||
message: `已拦截 ${interceptedOrderIds.length} 条订单`,
|
||
},
|
||
});
|
||
} catch (error) {
|
||
await this.setBatchInterceptTaskProgress(normalizedTaskId, 'failed', {
|
||
warehouse_id: warehouseId,
|
||
progress_percent: 0,
|
||
end_time: Date.now(),
|
||
duration_ms: Date.now() - startTime,
|
||
error: error && error.message ? error.message : `${error}`,
|
||
error_code: 'BATCH_INTERCEPT_FAILED',
|
||
});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 批量锁定订单(异步任务模式)。
|
||
*
|
||
* 将给定订单的 lock_status 批量更新为 'warehouse',并写入操作日志 ORDER_LOCK。
|
||
* 仅操作当前仓库上下文内的订单,每批最多 500 条。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @param {Array<number>} data.order_ids 订单ID数组。
|
||
* @param {string} [data.task_id] 可选的任务ID(用于幂等续查)。
|
||
* @return {Promise<Object>} 提交响应,含 task_id。
|
||
*/
|
||
async batchLock(data = {}) {
|
||
const warehouseId = Number(this.getWarehouseId() || 0);
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||
throw new Error('未识别到当前仓库上下文');
|
||
}
|
||
const normalizedOrderIds = this.normalizeBatchLockOrderIds(data);
|
||
if (normalizedOrderIds.length === 0) {
|
||
throw new Error('order_ids 参数不能为空或格式错误');
|
||
}
|
||
|
||
const requestedTaskId = this.normalizeBatchLockTaskId(data);
|
||
const taskId = requestedTaskId || this.generateBatchLockTaskId(warehouseId);
|
||
const existingTask = await this.getBatchLockTaskProgress(taskId);
|
||
|
||
if (existingTask) {
|
||
return this.success('ok', {
|
||
status: 'success',
|
||
task_id: taskId,
|
||
warehouse_id: Number(existingTask.warehouse_id || warehouseId),
|
||
state: String(existingTask.state || 'submitted').trim() || 'submitted',
|
||
message: '批量锁定任务已存在,请勿重复提交。',
|
||
accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(),
|
||
});
|
||
}
|
||
|
||
const acceptedAt = new Date().toISOString();
|
||
await this.setBatchLockTaskProgress(taskId, 'submitted', {
|
||
warehouse_id: warehouseId,
|
||
order_ids: normalizedOrderIds.join(','),
|
||
order_id_list: normalizedOrderIds,
|
||
total_order_count: normalizedOrderIds.length,
|
||
processed_order_count: 0,
|
||
locked_order_count: 0,
|
||
progress_percent: 0,
|
||
submitted_at: Date.now(),
|
||
accepted_at: acceptedAt,
|
||
result: null,
|
||
error: '',
|
||
error_code: '',
|
||
});
|
||
|
||
this.ctx.logger.info('[order.pendingOrder.batchLock] 任务提交成功', {
|
||
taskId,
|
||
warehouseId,
|
||
orderCount: normalizedOrderIds.length,
|
||
});
|
||
|
||
setImmediate(() => {
|
||
this.runBatchLockTask({
|
||
taskId,
|
||
warehouseId,
|
||
orderIds: normalizedOrderIds,
|
||
}).catch(error => {
|
||
this.ctx.logger.error('[order.pendingOrder.batchLock] 后台任务异常', {
|
||
taskId,
|
||
warehouseId,
|
||
orderCount: normalizedOrderIds.length,
|
||
error: error && error.message ? error.message : error,
|
||
stack: error && error.stack ? error.stack : '',
|
||
});
|
||
});
|
||
});
|
||
|
||
return this.success('ok', {
|
||
status: 'success',
|
||
task_id: taskId,
|
||
warehouse_id: warehouseId,
|
||
message: '批量锁定任务已提交。',
|
||
accepted_at: acceptedAt,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 查询批量锁定任务进度。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @param {string} data.task_id 任务ID(下划线写法)。
|
||
* @param {string} data.taskId 任务ID(驼峰写法)。
|
||
* @return {Promise<Object>} 任务进度响应。
|
||
*/
|
||
async batchLockTaskProgress(data = {}) {
|
||
const taskId = this.normalizeBatchLockTaskId(data);
|
||
if (!taskId) {
|
||
return this.fail('task_id 参数不能为空', 400);
|
||
}
|
||
|
||
const cachedProgress = await this.getBatchLockTaskProgress(taskId);
|
||
if (!cachedProgress) {
|
||
return this.success('ok', {
|
||
task_id: taskId,
|
||
state: 'not_found',
|
||
});
|
||
}
|
||
|
||
const state = String(cachedProgress.state || 'submitted').trim() || 'submitted';
|
||
const payload = {
|
||
task_id: taskId,
|
||
state,
|
||
warehouse_id: Number(cachedProgress.warehouse_id || 0),
|
||
submitted_at: cachedProgress.submitted_at || null,
|
||
start_time: cachedProgress.start_time || null,
|
||
end_time: cachedProgress.end_time || null,
|
||
};
|
||
|
||
if (state === 'submitted' || state === 'running') {
|
||
payload.progress_percent = Number(cachedProgress.progress_percent || 0);
|
||
payload.total_order_count = Number(cachedProgress.total_order_count || 0);
|
||
payload.processed_order_count = Number(cachedProgress.processed_order_count || 0);
|
||
payload.locked_order_count = Number(cachedProgress.locked_order_count || 0);
|
||
}
|
||
|
||
if (state === 'success') {
|
||
const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {};
|
||
payload.progress_percent = Number(cachedProgress.progress_percent || 100);
|
||
payload.total_order_count = Number(result.total_order_count || 0);
|
||
payload.locked_order_count = Number(result.locked_order_count || 0);
|
||
payload.locked_order_ids = this.normalizeIdsInput(result.locked_order_ids);
|
||
payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0);
|
||
}
|
||
|
||
if (state === 'failed') {
|
||
payload.progress_percent = Number(cachedProgress.progress_percent || 0);
|
||
payload.total_order_count = Number(cachedProgress.total_order_count || 0);
|
||
payload.locked_order_count = Number(cachedProgress.locked_order_count || 0);
|
||
payload.error_message = String(cachedProgress.error || '').trim();
|
||
payload.error_code = String(cachedProgress.error_code || '').trim() || 'BATCH_LOCK_FAILED';
|
||
payload.duration_ms = Number(cachedProgress.duration_ms || 0);
|
||
}
|
||
|
||
return this.success('ok', payload);
|
||
}
|
||
|
||
/**
|
||
* 生成可追踪的批量锁定任务ID。
|
||
*
|
||
* 格式:order_lock_{warehouseId}_{timestamp}_{rand}。
|
||
*
|
||
* @param {number|string} warehouseId 仓库ID。
|
||
* @return {string} 任务ID。
|
||
*/
|
||
generateBatchLockTaskId(warehouseId = 0) {
|
||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||
const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0
|
||
? normalizedWarehouseId
|
||
: 0;
|
||
const timestamp = Math.floor(Date.now() / 1000);
|
||
const randomPart = Math.random().toString(36).slice(2, 6);
|
||
return `order_lock_${safeWarehouseId}_${timestamp}_${randomPart}`;
|
||
}
|
||
|
||
/**
|
||
* 归一化批量锁定任务ID。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @param {string} data.task_id 任务ID(下划线写法)。
|
||
* @param {string} data.taskId 任务ID(驼峰写法)。
|
||
* @return {string} 归一化后的任务ID。
|
||
*/
|
||
normalizeBatchLockTaskId(data = {}) {
|
||
const normalizedData = this.isPlainObject(data) ? data : {};
|
||
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
|
||
}
|
||
|
||
/**
|
||
* 归一化批量锁定的订单ID参数。
|
||
* 兼容 order_ids / orderIds / ids 三种入参别名。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @return {Array<number>} 归一化后的订单ID数组。
|
||
*/
|
||
normalizeBatchLockOrderIds(data = {}) {
|
||
const normalizedData = this.isPlainObject(data) ? data : {};
|
||
const rawOrderIds = normalizedData.order_ids !== undefined
|
||
? normalizedData.order_ids
|
||
: normalizedData.orderIds !== undefined
|
||
? normalizedData.orderIds
|
||
: normalizedData.ids !== undefined
|
||
? normalizedData.ids
|
||
: [];
|
||
|
||
return this.normalizeIdsInput(rawOrderIds);
|
||
}
|
||
|
||
/**
|
||
* 获取批量锁定任务缓存键。
|
||
*
|
||
* @param {string} taskId 任务ID。
|
||
* @return {string} 缓存键。
|
||
*/
|
||
getBatchLockTaskCacheKey(taskId = '') {
|
||
const normalizedTaskId = String(taskId || '').trim();
|
||
if (!normalizedTaskId) {
|
||
return '';
|
||
}
|
||
|
||
return `${BATCH_LOCK_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
|
||
}
|
||
|
||
/**
|
||
* 写入批量锁定任务进度缓存。
|
||
*
|
||
* @param {string} taskId 任务ID。
|
||
* @param {string} state 任务状态(submitted|running|success|failed)。
|
||
* @param {Object} data 进度或结果数据。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async setBatchLockTaskProgress(taskId = '', state = 'submitted', data = {}) {
|
||
const cacheKey = this.getBatchLockTaskCacheKey(taskId);
|
||
if (!cacheKey) {
|
||
return;
|
||
}
|
||
|
||
const safeData = this.isPlainObject(data) ? data : {};
|
||
const mergedPayload = {
|
||
...(await this.getBatchLockTaskProgress(taskId) || {}),
|
||
...safeData,
|
||
task_id: String(taskId || '').trim(),
|
||
state: String(state || '').trim() || 'submitted',
|
||
update_time: Date.now(),
|
||
};
|
||
|
||
try {
|
||
await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_LOCK_TASK_CACHE_TTL_SECONDS);
|
||
} catch (error) {
|
||
this.ctx.logger.warn(
|
||
`[order.pendingOrder.batchLock] 写入任务进度缓存失败: ${error && error.message ? error.message : error}`
|
||
);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 读取批量锁定任务进度缓存。
|
||
*
|
||
* @param {string} taskId 任务ID。
|
||
* @return {Promise<Object|null>} 缓存对象。
|
||
*/
|
||
async getBatchLockTaskProgress(taskId = '') {
|
||
const cacheKey = this.getBatchLockTaskCacheKey(taskId);
|
||
if (!cacheKey) {
|
||
return null;
|
||
}
|
||
|
||
try {
|
||
const cached = await this.app.getCacheAsync(cacheKey);
|
||
if (!this.isPlainObject(cached)) {
|
||
return null;
|
||
}
|
||
|
||
return cached;
|
||
} catch (error) {
|
||
this.ctx.logger.warn(
|
||
`[order.pendingOrder.batchLock] 读取任务进度缓存失败: ${error && error.message ? error.message : error}`
|
||
);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 执行批量锁定后台任务。
|
||
*
|
||
* 直接对给定订单ID数组,将 lock_status 更新为 'warehouse',并写入操作日志 ORDER_LOCK。
|
||
* 仅处理当前仓库上下文内的订单,每批最多 500 条。
|
||
*
|
||
* @param {Object} params 任务参数。
|
||
* @param {string} params.taskId 任务ID。
|
||
* @param {number|string} [params.warehouseId] 仓库ID(兜底)。
|
||
* @param {Array<number|string>|number|string} [params.orderIds] 订单ID集合(兜底)。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async runBatchLockTask(params = {}) {
|
||
const { ctx } = this;
|
||
const normalizedTaskId = String(params && params.taskId || '').trim();
|
||
if (!normalizedTaskId) {
|
||
throw new Error('taskId 不能为空');
|
||
}
|
||
|
||
const cachedTask = await this.getBatchLockTaskProgress(normalizedTaskId);
|
||
const warehouseId = Number(
|
||
cachedTask && cachedTask.warehouse_id !== undefined
|
||
? cachedTask.warehouse_id
|
||
: params && params.warehouseId
|
||
);
|
||
const orderIds = this.normalizeIdsInput(
|
||
cachedTask && cachedTask.order_ids !== undefined
|
||
? cachedTask.order_ids
|
||
: params && params.orderIds
|
||
);
|
||
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||
await this.setBatchLockTaskProgress(normalizedTaskId, 'failed', {
|
||
end_time: Date.now(),
|
||
error: 'warehouse_id 参数不合法',
|
||
error_code: 'INVALID_WAREHOUSE_ID',
|
||
});
|
||
return;
|
||
}
|
||
|
||
if (orderIds.length === 0) {
|
||
await this.setBatchLockTaskProgress(normalizedTaskId, 'failed', {
|
||
warehouse_id: warehouseId,
|
||
end_time: Date.now(),
|
||
error: 'order_ids 参数不能为空或格式错误',
|
||
error_code: 'INVALID_ORDER_IDS',
|
||
});
|
||
return;
|
||
}
|
||
|
||
const startTime = Date.now();
|
||
await this.setBatchLockTaskProgress(normalizedTaskId, 'running', {
|
||
warehouse_id: warehouseId,
|
||
order_ids: orderIds.join(','),
|
||
order_id_list: orderIds,
|
||
total_order_count: orderIds.length,
|
||
processed_order_count: 0,
|
||
locked_order_count: 0,
|
||
progress_percent: 0,
|
||
start_time: startTime,
|
||
end_time: null,
|
||
result: null,
|
||
error: '',
|
||
error_code: '',
|
||
failed_order_id: 0,
|
||
});
|
||
|
||
try {
|
||
const orderModel = await this.getOrderModel('pendingOrder', warehouseId);
|
||
const { Op } = this.app.Sequelize;
|
||
|
||
// 分批查询订单是否存在且属于当前仓库
|
||
const BATCH_SIZE = 500;
|
||
const validOrderRows = [];
|
||
|
||
for (let i = 0; i < orderIds.length; i += BATCH_SIZE) {
|
||
const chunkOrderIds = orderIds.slice(i, i + BATCH_SIZE);
|
||
if (chunkOrderIds.length === 0) {
|
||
continue;
|
||
}
|
||
|
||
const orderRows = await orderModel.findAll({
|
||
attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code' ],
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
id: {
|
||
[Op.in]: chunkOrderIds,
|
||
},
|
||
},
|
||
raw: true,
|
||
});
|
||
|
||
for (const row of (Array.isArray(orderRows) ? orderRows : [])) {
|
||
validOrderRows.push(row);
|
||
}
|
||
}
|
||
|
||
const lockedOrderIds = [];
|
||
const operator = this.getOrderLogOperator();
|
||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||
|
||
const normalizedOrderRows = Array.isArray(validOrderRows) ? validOrderRows : [];
|
||
const totalOrderCount = orderIds.length;
|
||
const validOrderCount = normalizedOrderRows.length;
|
||
|
||
await this.setBatchLockTaskProgress(normalizedTaskId, 'running', {
|
||
warehouse_id: warehouseId,
|
||
total_order_count: totalOrderCount,
|
||
valid_order_count: validOrderCount,
|
||
});
|
||
|
||
if (validOrderCount === 0) {
|
||
const durationMs = Date.now() - startTime;
|
||
await this.setBatchLockTaskProgress(normalizedTaskId, 'success', {
|
||
warehouse_id: warehouseId,
|
||
total_order_count: totalOrderCount,
|
||
locked_order_count: 0,
|
||
progress_percent: 100,
|
||
end_time: Date.now(),
|
||
duration_ms: durationMs,
|
||
result: {
|
||
order_ids: orderIds,
|
||
locked_order_ids: [],
|
||
locked_order_count: 0,
|
||
total_order_count: totalOrderCount,
|
||
duration_ms: durationMs,
|
||
message: '未找到可锁定的当前仓库订单',
|
||
},
|
||
});
|
||
return;
|
||
}
|
||
|
||
// 分批更新锁定状态,每批最多500条
|
||
const UPDATE_CHUNK_SIZE = 500;
|
||
for (let i = 0; i < normalizedOrderRows.length; i += UPDATE_CHUNK_SIZE) {
|
||
const chunkRows = normalizedOrderRows.slice(i, i + UPDATE_CHUNK_SIZE);
|
||
if (chunkRows.length === 0) {
|
||
continue;
|
||
}
|
||
|
||
const chunkOrderIds = chunkRows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0);
|
||
if (chunkOrderIds.length === 0) {
|
||
continue;
|
||
}
|
||
|
||
const now = new Date();
|
||
const updateValues = {
|
||
lock_status: 'warehouse',
|
||
updated_at: now,
|
||
};
|
||
|
||
await orderModel.update(updateValues, {
|
||
where: {
|
||
id: {
|
||
[Op.in]: chunkOrderIds,
|
||
},
|
||
},
|
||
});
|
||
|
||
// 写入操作日志 ORDER_LOCK
|
||
const logPayloads = chunkRows.map(row => {
|
||
const orderId = Number(row.id || 0);
|
||
const orderNo = String(row.delivery_order_code || row.pre_delivery_order_code || '').trim();
|
||
if (!Number.isInteger(orderId) || orderId <= 0) {
|
||
return null;
|
||
}
|
||
|
||
return {
|
||
businessType: 'order',
|
||
businessId: logWarehouseId,
|
||
operationCode: 'ORDER_LOCK',
|
||
operator,
|
||
extras: {
|
||
warehouseId: logWarehouseId,
|
||
orderId,
|
||
orderNo,
|
||
newLockStatus: 'warehouse',
|
||
},
|
||
beforeChanges: null,
|
||
};
|
||
}).filter(Boolean);
|
||
|
||
if (logPayloads.length > 0) {
|
||
try {
|
||
const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
|
||
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
|
||
await operationLogService.createOperationLogs(logPayloads);
|
||
}
|
||
} catch (logErr) {
|
||
ctx.logger.warn(
|
||
`[order.pendingOrder.batchLock] 批量写操作日志失败,不影响主流程, count=${logPayloads.length}, error=${logErr.message}`
|
||
);
|
||
}
|
||
}
|
||
|
||
for (const orderId of chunkOrderIds) {
|
||
lockedOrderIds.push(orderId);
|
||
}
|
||
|
||
// 更新进度
|
||
const progressPercent = validOrderCount > 0
|
||
? Math.min(99, Math.round((lockedOrderIds.length / validOrderCount) * 100))
|
||
: 0;
|
||
|
||
await this.setBatchLockTaskProgress(normalizedTaskId, 'running', {
|
||
warehouse_id: warehouseId,
|
||
total_order_count: totalOrderCount,
|
||
locked_order_count: lockedOrderIds.length,
|
||
progress_percent: progressPercent,
|
||
});
|
||
}
|
||
|
||
const durationMs = Date.now() - startTime;
|
||
await this.setBatchLockTaskProgress(normalizedTaskId, 'success', {
|
||
warehouse_id: warehouseId,
|
||
total_order_count: totalOrderCount,
|
||
locked_order_count: lockedOrderIds.length,
|
||
progress_percent: 100,
|
||
end_time: Date.now(),
|
||
duration_ms: durationMs,
|
||
result: {
|
||
order_ids: orderIds,
|
||
locked_order_ids: lockedOrderIds,
|
||
locked_order_count: lockedOrderIds.length,
|
||
total_order_count: totalOrderCount,
|
||
duration_ms: durationMs,
|
||
message: `已锁定 ${lockedOrderIds.length} 条订单`,
|
||
},
|
||
});
|
||
} catch (error) {
|
||
await this.setBatchLockTaskProgress(normalizedTaskId, 'failed', {
|
||
warehouse_id: warehouseId,
|
||
progress_percent: 0,
|
||
end_time: Date.now(),
|
||
duration_ms: Date.now() - startTime,
|
||
error: error && error.message ? error.message : `${error}`,
|
||
error_code: 'BATCH_LOCK_FAILED',
|
||
});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 批量解锁订单(异步任务模式)。
|
||
*
|
||
* 将给定订单的 lock_status 批量更新为 'none',并写入操作日志 ORDER_UNLOCK。
|
||
* 仅操作当前仓库上下文内的订单。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @param {Array<number>} data.order_ids 订单ID数组。
|
||
* @param {string} [data.task_id] 可选的任务ID(用于幂等续查)。
|
||
* @return {Promise<Object>} 提交响应,含 task_id。
|
||
*/
|
||
async batchUnlock(data = {}) {
|
||
const warehouseId = Number(this.getWarehouseId() || 0);
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||
throw new Error('未识别到当前仓库上下文');
|
||
}
|
||
const normalizedOrderIds = this.normalizeBatchUnlockOrderIds(data);
|
||
if (normalizedOrderIds.length === 0) {
|
||
throw new Error('order_ids 参数不能为空或格式错误');
|
||
}
|
||
|
||
const requestedTaskId = this.normalizeBatchUnlockTaskId(data);
|
||
const taskId = requestedTaskId || this.generateBatchUnlockTaskId(warehouseId);
|
||
const existingTask = await this.getBatchUnlockTaskProgress(taskId);
|
||
|
||
if (existingTask) {
|
||
return this.success('ok', {
|
||
status: 'success',
|
||
task_id: taskId,
|
||
warehouse_id: Number(existingTask.warehouse_id || warehouseId),
|
||
state: String(existingTask.state || 'submitted').trim() || 'submitted',
|
||
message: '批量解锁任务已存在,请勿重复提交。',
|
||
accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(),
|
||
});
|
||
}
|
||
|
||
const acceptedAt = new Date().toISOString();
|
||
await this.setBatchUnlockTaskProgress(taskId, 'submitted', {
|
||
warehouse_id: warehouseId,
|
||
order_ids: normalizedOrderIds.join(','),
|
||
order_id_list: normalizedOrderIds,
|
||
total_order_count: normalizedOrderIds.length,
|
||
processed_order_count: 0,
|
||
unlocked_order_count: 0,
|
||
progress_percent: 0,
|
||
submitted_at: Date.now(),
|
||
accepted_at: acceptedAt,
|
||
result: null,
|
||
error: '',
|
||
error_code: '',
|
||
});
|
||
|
||
this.ctx.logger.info('[order.pendingOrder.batchUnlock] 任务提交成功', {
|
||
taskId,
|
||
warehouseId,
|
||
orderCount: normalizedOrderIds.length,
|
||
});
|
||
|
||
setImmediate(() => {
|
||
this.runBatchUnlockTask({
|
||
taskId,
|
||
warehouseId,
|
||
orderIds: normalizedOrderIds,
|
||
}).catch(error => {
|
||
this.ctx.logger.error('[order.pendingOrder.batchUnlock] 后台任务异常', {
|
||
taskId,
|
||
warehouseId,
|
||
orderCount: normalizedOrderIds.length,
|
||
error: error && error.message ? error.message : error,
|
||
stack: error && error.stack ? error.stack : '',
|
||
});
|
||
});
|
||
});
|
||
|
||
return this.success('ok', {
|
||
status: 'success',
|
||
task_id: taskId,
|
||
warehouse_id: warehouseId,
|
||
message: '批量解锁任务已提交。',
|
||
accepted_at: acceptedAt,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 查询批量解锁任务进度。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @param {string} data.task_id 任务ID(下划线写法)。
|
||
* @param {string} data.taskId 任务ID(驼峰写法)。
|
||
* @return {Promise<Object>} 任务进度响应。
|
||
*/
|
||
async batchUnlockTaskProgress(data = {}) {
|
||
const taskId = this.normalizeBatchUnlockTaskId(data);
|
||
if (!taskId) {
|
||
return this.fail('task_id 参数不能为空', 400);
|
||
}
|
||
|
||
const cachedProgress = await this.getBatchUnlockTaskProgress(taskId);
|
||
if (!cachedProgress) {
|
||
return this.success('ok', {
|
||
task_id: taskId,
|
||
state: 'not_found',
|
||
});
|
||
}
|
||
|
||
const state = String(cachedProgress.state || 'submitted').trim() || 'submitted';
|
||
const payload = {
|
||
task_id: taskId,
|
||
state,
|
||
warehouse_id: Number(cachedProgress.warehouse_id || 0),
|
||
submitted_at: cachedProgress.submitted_at || null,
|
||
start_time: cachedProgress.start_time || null,
|
||
end_time: cachedProgress.end_time || null,
|
||
};
|
||
|
||
if (state === 'submitted' || state === 'running') {
|
||
payload.progress_percent = Number(cachedProgress.progress_percent || 0);
|
||
payload.total_order_count = Number(cachedProgress.total_order_count || 0);
|
||
payload.processed_order_count = Number(cachedProgress.processed_order_count || 0);
|
||
payload.unlocked_order_count = Number(cachedProgress.unlocked_order_count || 0);
|
||
}
|
||
|
||
if (state === 'success') {
|
||
const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {};
|
||
payload.progress_percent = Number(cachedProgress.progress_percent || 100);
|
||
payload.total_order_count = Number(result.total_order_count || 0);
|
||
payload.unlocked_order_count = Number(result.unlocked_order_count || 0);
|
||
payload.unlocked_order_ids = this.normalizeIdsInput(result.unlocked_order_ids);
|
||
payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0);
|
||
}
|
||
|
||
if (state === 'failed') {
|
||
payload.progress_percent = Number(cachedProgress.progress_percent || 0);
|
||
payload.total_order_count = Number(cachedProgress.total_order_count || 0);
|
||
payload.unlocked_order_count = Number(cachedProgress.unlocked_order_count || 0);
|
||
payload.error_message = String(cachedProgress.error || '').trim();
|
||
payload.error_code = String(cachedProgress.error_code || '').trim() || 'BATCH_UNLOCK_FAILED';
|
||
payload.duration_ms = Number(cachedProgress.duration_ms || 0);
|
||
}
|
||
|
||
return this.success('ok', payload);
|
||
}
|
||
|
||
/**
|
||
* 生成可追踪的批量解锁任务ID。
|
||
*
|
||
* 格式:order_unlock_{warehouseId}_{timestamp}_{rand}。
|
||
*
|
||
* @param {number|string} warehouseId 仓库ID。
|
||
* @return {string} 任务ID。
|
||
*/
|
||
generateBatchUnlockTaskId(warehouseId = 0) {
|
||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||
const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0
|
||
? normalizedWarehouseId
|
||
: 0;
|
||
const timestamp = Math.floor(Date.now() / 1000);
|
||
const randomPart = Math.random().toString(36).slice(2, 6);
|
||
return `order_unlock_${safeWarehouseId}_${timestamp}_${randomPart}`;
|
||
}
|
||
|
||
/**
|
||
* 归一化批量解锁任务ID。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @param {string} data.task_id 任务ID(下划线写法)。
|
||
* @param {string} data.taskId 任务ID(驼峰写法)。
|
||
* @return {string} 归一化后的任务ID。
|
||
*/
|
||
normalizeBatchUnlockTaskId(data = {}) {
|
||
const normalizedData = this.isPlainObject(data) ? data : {};
|
||
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
|
||
}
|
||
|
||
/**
|
||
* 归一化批量解锁的订单ID参数。
|
||
* 兼容 order_ids / orderIds / ids 三种入参别名。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @return {Array<number>} 归一化后的订单ID数组。
|
||
*/
|
||
normalizeBatchUnlockOrderIds(data = {}) {
|
||
const normalizedData = this.isPlainObject(data) ? data : {};
|
||
const rawOrderIds = normalizedData.order_ids !== undefined
|
||
? normalizedData.order_ids
|
||
: normalizedData.orderIds !== undefined
|
||
? normalizedData.orderIds
|
||
: normalizedData.ids !== undefined
|
||
? normalizedData.ids
|
||
: [];
|
||
|
||
return this.normalizeIdsInput(rawOrderIds);
|
||
}
|
||
|
||
/**
|
||
* 获取批量解锁任务缓存键。
|
||
*
|
||
* @param {string} taskId 任务ID。
|
||
* @return {string} 缓存键。
|
||
*/
|
||
getBatchUnlockTaskCacheKey(taskId = '') {
|
||
const normalizedTaskId = String(taskId || '').trim();
|
||
if (!normalizedTaskId) {
|
||
return '';
|
||
}
|
||
|
||
return `${BATCH_UNLOCK_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
|
||
}
|
||
|
||
/**
|
||
* 写入批量解锁任务进度缓存。
|
||
*
|
||
* @param {string} taskId 任务ID。
|
||
* @param {string} state 任务状态(submitted|running|success|failed)。
|
||
* @param {Object} data 进度或结果数据。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async setBatchUnlockTaskProgress(taskId = '', state = 'submitted', data = {}) {
|
||
const cacheKey = this.getBatchUnlockTaskCacheKey(taskId);
|
||
if (!cacheKey) {
|
||
return;
|
||
}
|
||
|
||
const safeData = this.isPlainObject(data) ? data : {};
|
||
const mergedPayload = {
|
||
...(await this.getBatchUnlockTaskProgress(taskId) || {}),
|
||
...safeData,
|
||
task_id: String(taskId || '').trim(),
|
||
state: String(state || '').trim() || 'submitted',
|
||
update_time: Date.now(),
|
||
};
|
||
|
||
try {
|
||
await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_UNLOCK_TASK_CACHE_TTL_SECONDS);
|
||
} catch (error) {
|
||
this.ctx.logger.warn(
|
||
`[order.pendingOrder.batchUnlock] 写入任务进度缓存失败: ${error && error.message ? error.message : error}`
|
||
);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 读取批量解锁任务进度缓存。
|
||
*
|
||
* @param {string} taskId 任务ID。
|
||
* @return {Promise<Object|null>} 缓存对象。
|
||
*/
|
||
async getBatchUnlockTaskProgress(taskId = '') {
|
||
const cacheKey = this.getBatchUnlockTaskCacheKey(taskId);
|
||
if (!cacheKey) {
|
||
return null;
|
||
}
|
||
|
||
try {
|
||
const cached = await this.app.getCacheAsync(cacheKey);
|
||
if (!this.isPlainObject(cached)) {
|
||
return null;
|
||
}
|
||
|
||
return cached;
|
||
} catch (error) {
|
||
this.ctx.logger.warn(
|
||
`[order.pendingOrder.batchUnlock] 读取任务进度缓存失败: ${error && error.message ? error.message : error}`
|
||
);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 执行批量解锁后台任务。
|
||
*
|
||
* 直接对给定订单ID数组,将 lock_status 更新为 'none',并写入操作日志 ORDER_UNLOCK。
|
||
* 仅处理当前仓库上下文内的订单。
|
||
*
|
||
* @param {Object} params 任务参数。
|
||
* @param {string} params.taskId 任务ID。
|
||
* @param {number|string} [params.warehouseId] 仓库ID(兜底)。
|
||
* @param {Array<number|string>|number|string} [params.orderIds] 订单ID集合(兜底)。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async runBatchUnlockTask(params = {}) {
|
||
const { ctx } = this;
|
||
const normalizedTaskId = String(params && params.taskId || '').trim();
|
||
if (!normalizedTaskId) {
|
||
throw new Error('taskId 不能为空');
|
||
}
|
||
|
||
const cachedTask = await this.getBatchUnlockTaskProgress(normalizedTaskId);
|
||
const warehouseId = Number(
|
||
cachedTask && cachedTask.warehouse_id !== undefined
|
||
? cachedTask.warehouse_id
|
||
: params && params.warehouseId
|
||
);
|
||
const orderIds = this.normalizeIdsInput(
|
||
cachedTask && cachedTask.order_ids !== undefined
|
||
? cachedTask.order_ids
|
||
: params && params.orderIds
|
||
);
|
||
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||
await this.setBatchUnlockTaskProgress(normalizedTaskId, 'failed', {
|
||
end_time: Date.now(),
|
||
error: 'warehouse_id 参数不合法',
|
||
error_code: 'INVALID_WAREHOUSE_ID',
|
||
});
|
||
return;
|
||
}
|
||
|
||
if (orderIds.length === 0) {
|
||
await this.setBatchUnlockTaskProgress(normalizedTaskId, 'failed', {
|
||
warehouse_id: warehouseId,
|
||
end_time: Date.now(),
|
||
error: 'order_ids 参数不能为空或格式错误',
|
||
error_code: 'INVALID_ORDER_IDS',
|
||
});
|
||
return;
|
||
}
|
||
|
||
const startTime = Date.now();
|
||
await this.setBatchUnlockTaskProgress(normalizedTaskId, 'running', {
|
||
warehouse_id: warehouseId,
|
||
order_ids: orderIds.join(','),
|
||
order_id_list: orderIds,
|
||
total_order_count: orderIds.length,
|
||
processed_order_count: 0,
|
||
unlocked_order_count: 0,
|
||
progress_percent: 0,
|
||
start_time: startTime,
|
||
end_time: null,
|
||
result: null,
|
||
error: '',
|
||
error_code: '',
|
||
failed_order_id: 0,
|
||
});
|
||
|
||
try {
|
||
const orderModel = await this.getOrderModel('pendingOrder', warehouseId);
|
||
const { Op } = this.app.Sequelize;
|
||
|
||
// 分批查询订单是否存在且属于当前仓库
|
||
const BATCH_SIZE = 500;
|
||
const validOrderRows = [];
|
||
|
||
for (let i = 0; i < orderIds.length; i += BATCH_SIZE) {
|
||
const chunkOrderIds = orderIds.slice(i, i + BATCH_SIZE);
|
||
if (chunkOrderIds.length === 0) {
|
||
continue;
|
||
}
|
||
|
||
const orderRows = await orderModel.findAll({
|
||
attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code' ],
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
id: {
|
||
[Op.in]: chunkOrderIds,
|
||
},
|
||
},
|
||
raw: true,
|
||
});
|
||
|
||
for (const row of (Array.isArray(orderRows) ? orderRows : [])) {
|
||
validOrderRows.push(row);
|
||
}
|
||
}
|
||
|
||
const unlockedOrderIds = [];
|
||
const operator = this.getOrderLogOperator();
|
||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||
|
||
const normalizedOrderRows = Array.isArray(validOrderRows) ? validOrderRows : [];
|
||
const totalOrderCount = orderIds.length;
|
||
const validOrderCount = normalizedOrderRows.length;
|
||
|
||
await this.setBatchUnlockTaskProgress(normalizedTaskId, 'running', {
|
||
warehouse_id: warehouseId,
|
||
total_order_count: totalOrderCount,
|
||
valid_order_count: validOrderCount,
|
||
});
|
||
|
||
if (validOrderCount === 0) {
|
||
const durationMs = Date.now() - startTime;
|
||
await this.setBatchUnlockTaskProgress(normalizedTaskId, 'success', {
|
||
warehouse_id: warehouseId,
|
||
total_order_count: totalOrderCount,
|
||
unlocked_order_count: 0,
|
||
progress_percent: 100,
|
||
end_time: Date.now(),
|
||
duration_ms: durationMs,
|
||
result: {
|
||
order_ids: orderIds,
|
||
unlocked_order_ids: [],
|
||
unlocked_order_count: 0,
|
||
total_order_count: totalOrderCount,
|
||
duration_ms: durationMs,
|
||
message: '未找到可解锁的当前仓库订单',
|
||
},
|
||
});
|
||
return;
|
||
}
|
||
|
||
// 分批更新解锁状态,每批最多500条
|
||
const UPDATE_CHUNK_SIZE = 500;
|
||
for (let i = 0; i < normalizedOrderRows.length; i += UPDATE_CHUNK_SIZE) {
|
||
const chunkRows = normalizedOrderRows.slice(i, i + UPDATE_CHUNK_SIZE);
|
||
if (chunkRows.length === 0) {
|
||
continue;
|
||
}
|
||
|
||
const chunkOrderIds = chunkRows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0);
|
||
if (chunkOrderIds.length === 0) {
|
||
continue;
|
||
}
|
||
|
||
const now = new Date();
|
||
const updateValues = {
|
||
lock_status: 'none',
|
||
updated_at: now,
|
||
};
|
||
|
||
await orderModel.update(updateValues, {
|
||
where: {
|
||
id: {
|
||
[Op.in]: chunkOrderIds,
|
||
},
|
||
},
|
||
});
|
||
|
||
// 写入操作日志 ORDER_UNLOCK
|
||
const logPayloads = chunkRows.map(row => {
|
||
const orderId = Number(row.id || 0);
|
||
const orderNo = String(row.delivery_order_code || row.pre_delivery_order_code || '').trim();
|
||
if (!Number.isInteger(orderId) || orderId <= 0) {
|
||
return null;
|
||
}
|
||
|
||
return {
|
||
businessType: 'order',
|
||
businessId: logWarehouseId,
|
||
operationCode: 'ORDER_UNLOCK',
|
||
operator,
|
||
extras: {
|
||
warehouseId: logWarehouseId,
|
||
orderId,
|
||
orderNo,
|
||
newLockStatus: 'none',
|
||
},
|
||
beforeChanges: null,
|
||
};
|
||
}).filter(Boolean);
|
||
|
||
if (logPayloads.length > 0) {
|
||
try {
|
||
const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
|
||
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
|
||
await operationLogService.createOperationLogs(logPayloads);
|
||
}
|
||
} catch (logErr) {
|
||
ctx.logger.warn(
|
||
`[order.pendingOrder.batchUnlock] 批量写操作日志失败,不影响主流程, count=${logPayloads.length}, error=${logErr.message}`
|
||
);
|
||
}
|
||
}
|
||
|
||
for (const orderId of chunkOrderIds) {
|
||
unlockedOrderIds.push(orderId);
|
||
}
|
||
|
||
// 更新进度
|
||
const progressPercent = validOrderCount > 0
|
||
? Math.min(99, Math.round((unlockedOrderIds.length / validOrderCount) * 100))
|
||
: 0;
|
||
|
||
await this.setBatchUnlockTaskProgress(normalizedTaskId, 'running', {
|
||
warehouse_id: warehouseId,
|
||
total_order_count: totalOrderCount,
|
||
unlocked_order_count: unlockedOrderIds.length,
|
||
progress_percent: progressPercent,
|
||
});
|
||
}
|
||
|
||
const durationMs = Date.now() - startTime;
|
||
await this.setBatchUnlockTaskProgress(normalizedTaskId, 'success', {
|
||
warehouse_id: warehouseId,
|
||
total_order_count: totalOrderCount,
|
||
unlocked_order_count: unlockedOrderIds.length,
|
||
progress_percent: 100,
|
||
end_time: Date.now(),
|
||
duration_ms: durationMs,
|
||
result: {
|
||
order_ids: orderIds,
|
||
unlocked_order_ids: unlockedOrderIds,
|
||
unlocked_order_count: unlockedOrderIds.length,
|
||
total_order_count: totalOrderCount,
|
||
duration_ms: durationMs,
|
||
message: `已解锁 ${unlockedOrderIds.length} 条订单`,
|
||
},
|
||
});
|
||
} catch (error) {
|
||
await this.setBatchUnlockTaskProgress(normalizedTaskId, 'failed', {
|
||
warehouse_id: warehouseId,
|
||
progress_percent: 0,
|
||
end_time: Date.now(),
|
||
duration_ms: Date.now() - startTime,
|
||
error: error && error.message ? error.message : `${error}`,
|
||
error_code: 'BATCH_UNLOCK_FAILED',
|
||
});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 批量解除拦截订单(异步任务模式)。
|
||
*
|
||
* 将给定订单的 intercept_status 批量更新为 'none',并写入操作日志 ORDER_INTERCEPT_CANCEL。
|
||
* 仅操作当前仓库上下文内的订单。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @param {Array<number|string>} [data.order_ids] 订单ID数组(下划线写法)。
|
||
* @param {Array<number|string>} [data.orderIds] 订单ID数组(驼峰别名)。
|
||
* @param {Array<number|string>} [data.ids] 订单ID数组(简写别名)。
|
||
* @param {string} [data.task_id] 任务ID(用于查询进度)。
|
||
* @param {string} [data.taskId] 任务ID(驼峰别名)。
|
||
* @return {Promise<Object>} 提交结果,包含 task_id、状态与 accepted_at。
|
||
*/
|
||
async batchUnintercept(data = {}) {
|
||
const warehouseId = Number(this.getWarehouseId() || 0);
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||
throw new Error('未识别到当前仓库上下文');
|
||
}
|
||
const normalizedOrderIds = this.normalizeBatchUninterceptOrderIds(data);
|
||
if (normalizedOrderIds.length === 0) {
|
||
throw new Error('order_ids 参数不能为空或格式错误');
|
||
}
|
||
|
||
const requestedTaskId = this.normalizeBatchUninterceptTaskId(data);
|
||
const taskId = requestedTaskId || this.generateBatchUninterceptTaskId(warehouseId);
|
||
const existingTask = await this.getBatchUninterceptTaskProgress(taskId);
|
||
|
||
if (existingTask) {
|
||
return this.success('ok', {
|
||
status: 'success',
|
||
task_id: taskId,
|
||
warehouse_id: Number(existingTask.warehouse_id || warehouseId),
|
||
state: String(existingTask.state || 'submitted').trim() || 'submitted',
|
||
message: '批量解除拦截任务已存在,请勿重复提交。',
|
||
accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(),
|
||
});
|
||
}
|
||
|
||
const acceptedAt = new Date().toISOString();
|
||
await this.setBatchUninterceptTaskProgress(taskId, 'submitted', {
|
||
warehouse_id: warehouseId,
|
||
order_ids: normalizedOrderIds.join(','),
|
||
order_id_list: normalizedOrderIds,
|
||
total_order_count: normalizedOrderIds.length,
|
||
processed_order_count: 0,
|
||
unintercepted_order_count: 0,
|
||
progress_percent: 0,
|
||
submitted_at: Date.now(),
|
||
accepted_at: acceptedAt,
|
||
result: null,
|
||
error: '',
|
||
error_code: '',
|
||
});
|
||
|
||
this.ctx.logger.info('[order.pendingOrder.batchUnintercept] 任务提交成功', {
|
||
taskId,
|
||
warehouseId,
|
||
orderCount: normalizedOrderIds.length,
|
||
});
|
||
|
||
setImmediate(() => {
|
||
this.runBatchUninterceptTask({
|
||
taskId,
|
||
warehouseId,
|
||
orderIds: normalizedOrderIds,
|
||
}).catch(error => {
|
||
this.ctx.logger.error('[order.pendingOrder.batchUnintercept] 后台任务异常', {
|
||
taskId,
|
||
warehouseId,
|
||
orderCount: normalizedOrderIds.length,
|
||
error: error && error.message ? error.message : error,
|
||
stack: error && error.stack ? error.stack : '',
|
||
});
|
||
});
|
||
});
|
||
|
||
return this.success('ok', {
|
||
status: 'success',
|
||
task_id: taskId,
|
||
warehouse_id: warehouseId,
|
||
message: '批量解除拦截任务已提交。',
|
||
accepted_at: acceptedAt,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 查询批量解除拦截任务进度。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @param {string} data.task_id 任务ID(下划线写法)。
|
||
* @param {string} data.taskId 任务ID(驼峰写法)。
|
||
* @return {Promise<Object>} 任务进度响应。
|
||
*/
|
||
async batchUninterceptTaskProgress(data = {}) {
|
||
const taskId = this.normalizeBatchUninterceptTaskId(data);
|
||
if (!taskId) {
|
||
return this.fail('task_id 参数不能为空', 400);
|
||
}
|
||
|
||
const cachedProgress = await this.getBatchUninterceptTaskProgress(taskId);
|
||
if (!cachedProgress) {
|
||
return this.success('ok', {
|
||
task_id: taskId,
|
||
state: 'not_found',
|
||
});
|
||
}
|
||
|
||
const state = String(cachedProgress.state || 'submitted').trim() || 'submitted';
|
||
const payload = {
|
||
task_id: taskId,
|
||
state,
|
||
warehouse_id: Number(cachedProgress.warehouse_id || 0),
|
||
submitted_at: cachedProgress.submitted_at || null,
|
||
start_time: cachedProgress.start_time || null,
|
||
end_time: cachedProgress.end_time || null,
|
||
};
|
||
|
||
if (state === 'submitted' || state === 'running') {
|
||
payload.progress_percent = Number(cachedProgress.progress_percent || 0);
|
||
payload.total_order_count = Number(cachedProgress.total_order_count || 0);
|
||
payload.processed_order_count = Number(cachedProgress.processed_order_count || 0);
|
||
payload.unintercepted_order_count = Number(cachedProgress.unintercepted_order_count || 0);
|
||
}
|
||
|
||
if (state === 'success') {
|
||
const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {};
|
||
payload.progress_percent = Number(cachedProgress.progress_percent || 100);
|
||
payload.total_order_count = Number(result.total_order_count || 0);
|
||
payload.unintercepted_order_count = Number(result.unintercepted_order_count || 0);
|
||
payload.unintercepted_order_ids = this.normalizeIdsInput(result.unintercepted_order_ids);
|
||
payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0);
|
||
}
|
||
|
||
if (state === 'failed') {
|
||
payload.progress_percent = Number(cachedProgress.progress_percent || 0);
|
||
payload.total_order_count = Number(cachedProgress.total_order_count || 0);
|
||
payload.unintercepted_order_count = Number(cachedProgress.unintercepted_order_count || 0);
|
||
payload.error_message = String(cachedProgress.error || '').trim();
|
||
payload.error_code = String(cachedProgress.error_code || '').trim() || 'BATCH_UNINTERCEPT_FAILED';
|
||
payload.duration_ms = Number(cachedProgress.duration_ms || 0);
|
||
}
|
||
|
||
return this.success('ok', payload);
|
||
}
|
||
|
||
/**
|
||
* 生成可追踪的批量解除拦截任务ID。
|
||
*
|
||
* 格式:order_unintercept_{warehouseId}_{timestamp}_{rand}。
|
||
*
|
||
* @param {number|string} warehouseId 仓库ID。
|
||
* @return {string} 任务ID。
|
||
*/
|
||
generateBatchUninterceptTaskId(warehouseId = 0) {
|
||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||
const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0
|
||
? normalizedWarehouseId
|
||
: 0;
|
||
const timestamp = Math.floor(Date.now() / 1000);
|
||
const randomPart = Math.random().toString(36).slice(2, 6);
|
||
return `order_unintercept_${safeWarehouseId}_${timestamp}_${randomPart}`;
|
||
}
|
||
|
||
/**
|
||
* 归一化批量解除拦截任务ID。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @param {string} data.task_id 任务ID(下划线写法)。
|
||
* @param {string} data.taskId 任务ID(驼峰写法)。
|
||
* @return {string} 归一化后的任务ID。
|
||
*/
|
||
normalizeBatchUninterceptTaskId(data = {}) {
|
||
const normalizedData = this.isPlainObject(data) ? data : {};
|
||
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
|
||
}
|
||
|
||
/**
|
||
* 归一化批量解除拦截的订单ID参数。
|
||
* 兼容 order_ids / orderIds / ids 三种入参别名。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @return {Array<number>} 归一化后的订单ID数组。
|
||
*/
|
||
normalizeBatchUninterceptOrderIds(data = {}) {
|
||
const normalizedData = this.isPlainObject(data) ? data : {};
|
||
const rawOrderIds = normalizedData.order_ids !== undefined
|
||
? normalizedData.order_ids
|
||
: normalizedData.orderIds !== undefined
|
||
? normalizedData.orderIds
|
||
: normalizedData.ids !== undefined
|
||
? normalizedData.ids
|
||
: [];
|
||
|
||
return this.normalizeIdsInput(rawOrderIds);
|
||
}
|
||
|
||
/**
|
||
* 获取批量解除拦截任务缓存键。
|
||
*
|
||
* @param {string} taskId 任务ID。
|
||
* @return {string} 缓存键。
|
||
*/
|
||
getBatchUninterceptTaskCacheKey(taskId = '') {
|
||
const normalizedTaskId = String(taskId || '').trim();
|
||
if (!normalizedTaskId) {
|
||
return '';
|
||
}
|
||
|
||
return `${BATCH_UNINTERCEPT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
|
||
}
|
||
|
||
/**
|
||
* 写入批量解除拦截任务进度缓存。
|
||
*
|
||
* @param {string} taskId 任务ID。
|
||
* @param {string} state 任务状态(submitted|running|success|failed)。
|
||
* @param {Object} data 进度或结果数据。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async setBatchUninterceptTaskProgress(taskId = '', state = 'submitted', data = {}) {
|
||
const cacheKey = this.getBatchUninterceptTaskCacheKey(taskId);
|
||
if (!cacheKey) {
|
||
return;
|
||
}
|
||
|
||
const safeData = this.isPlainObject(data) ? data : {};
|
||
const mergedPayload = {
|
||
...(await this.getBatchUninterceptTaskProgress(taskId) || {}),
|
||
...safeData,
|
||
task_id: String(taskId || '').trim(),
|
||
state: String(state || '').trim() || 'submitted',
|
||
update_time: Date.now(),
|
||
};
|
||
|
||
try {
|
||
await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_UNINTERCEPT_TASK_CACHE_TTL_SECONDS);
|
||
} catch (error) {
|
||
this.ctx.logger.warn(
|
||
`[order.pendingOrder.batchUnintercept] 写入任务进度缓存失败: ${error && error.message ? error.message : error}`
|
||
);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 读取批量解除拦截任务进度缓存。
|
||
*
|
||
* @param {string} taskId 任务ID。
|
||
* @return {Promise<Object|null>} 缓存对象。
|
||
*/
|
||
async getBatchUninterceptTaskProgress(taskId = '') {
|
||
const cacheKey = this.getBatchUninterceptTaskCacheKey(taskId);
|
||
if (!cacheKey) {
|
||
return null;
|
||
}
|
||
|
||
try {
|
||
const cached = await this.app.getCacheAsync(cacheKey);
|
||
if (!this.isPlainObject(cached)) {
|
||
return null;
|
||
}
|
||
|
||
return cached;
|
||
} catch (error) {
|
||
this.ctx.logger.warn(
|
||
`[order.pendingOrder.batchUnintercept] 读取任务进度缓存失败: ${error && error.message ? error.message : error}`
|
||
);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 执行批量解除拦截后台任务。
|
||
*
|
||
* 直接对给定订单ID数组,将 intercept_status 更新为 'none',并写入操作日志 ORDER_INTERCEPT_CANCEL。
|
||
* 仅处理当前仓库上下文内的订单。
|
||
*
|
||
* @param {Object} params 任务参数。
|
||
* @param {string} params.taskId 任务ID。
|
||
* @param {number|string} [params.warehouseId] 仓库ID(兜底)。
|
||
* @param {Array<number|string>|number|string} [params.orderIds] 订单ID集合(兜底)。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async runBatchUninterceptTask(params = {}) {
|
||
const { ctx } = this;
|
||
const normalizedTaskId = String(params && params.taskId || '').trim();
|
||
if (!normalizedTaskId) {
|
||
throw new Error('taskId 不能为空');
|
||
}
|
||
|
||
const cachedTask = await this.getBatchUninterceptTaskProgress(normalizedTaskId);
|
||
const warehouseId = Number(
|
||
cachedTask && cachedTask.warehouse_id !== undefined
|
||
? cachedTask.warehouse_id
|
||
: params && params.warehouseId
|
||
);
|
||
const orderIds = this.normalizeIdsInput(
|
||
cachedTask && cachedTask.order_ids !== undefined
|
||
? cachedTask.order_ids
|
||
: params && params.orderIds
|
||
);
|
||
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||
await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'failed', {
|
||
end_time: Date.now(),
|
||
error: 'warehouse_id 参数不合法',
|
||
error_code: 'INVALID_WAREHOUSE_ID',
|
||
});
|
||
return;
|
||
}
|
||
|
||
if (orderIds.length === 0) {
|
||
await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'failed', {
|
||
warehouse_id: warehouseId,
|
||
end_time: Date.now(),
|
||
error: 'order_ids 参数不能为空或格式错误',
|
||
error_code: 'INVALID_ORDER_IDS',
|
||
});
|
||
return;
|
||
}
|
||
|
||
const startTime = Date.now();
|
||
await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'running', {
|
||
warehouse_id: warehouseId,
|
||
order_ids: orderIds.join(','),
|
||
order_id_list: orderIds,
|
||
total_order_count: orderIds.length,
|
||
processed_order_count: 0,
|
||
unintercepted_order_count: 0,
|
||
progress_percent: 0,
|
||
start_time: startTime,
|
||
end_time: null,
|
||
result: null,
|
||
error: '',
|
||
error_code: '',
|
||
failed_order_id: 0,
|
||
});
|
||
|
||
try {
|
||
const orderModel = await this.getOrderModel('pendingOrder', warehouseId);
|
||
const { Op } = this.app.Sequelize;
|
||
|
||
// 分批查询订单是否存在且属于当前仓库
|
||
const BATCH_SIZE = 500;
|
||
const validOrderRows = [];
|
||
|
||
for (let i = 0; i < orderIds.length; i += BATCH_SIZE) {
|
||
const chunkOrderIds = orderIds.slice(i, i + BATCH_SIZE);
|
||
if (chunkOrderIds.length === 0) {
|
||
continue;
|
||
}
|
||
|
||
const orderRows = await orderModel.findAll({
|
||
attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code' ],
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
id: {
|
||
[Op.in]: chunkOrderIds,
|
||
},
|
||
},
|
||
raw: true,
|
||
});
|
||
|
||
for (const row of (Array.isArray(orderRows) ? orderRows : [])) {
|
||
validOrderRows.push(row);
|
||
}
|
||
}
|
||
|
||
const uninterceptedOrderIds = [];
|
||
const operator = this.getOrderLogOperator();
|
||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||
|
||
const normalizedOrderRows = Array.isArray(validOrderRows) ? validOrderRows : [];
|
||
const totalOrderCount = orderIds.length;
|
||
const validOrderCount = normalizedOrderRows.length;
|
||
|
||
await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'running', {
|
||
warehouse_id: warehouseId,
|
||
total_order_count: totalOrderCount,
|
||
valid_order_count: validOrderCount,
|
||
});
|
||
|
||
if (validOrderCount === 0) {
|
||
const durationMs = Date.now() - startTime;
|
||
await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'success', {
|
||
warehouse_id: warehouseId,
|
||
total_order_count: totalOrderCount,
|
||
unintercepted_order_count: 0,
|
||
progress_percent: 100,
|
||
end_time: Date.now(),
|
||
duration_ms: durationMs,
|
||
result: {
|
||
order_ids: orderIds,
|
||
unintercepted_order_ids: [],
|
||
unintercepted_order_count: 0,
|
||
total_order_count: totalOrderCount,
|
||
duration_ms: durationMs,
|
||
message: '未找到可解除拦截的当前仓库订单',
|
||
},
|
||
});
|
||
return;
|
||
}
|
||
|
||
// 分批更新解除拦截状态,每批最多500条
|
||
const UPDATE_CHUNK_SIZE = 500;
|
||
for (let i = 0; i < normalizedOrderRows.length; i += UPDATE_CHUNK_SIZE) {
|
||
const chunkRows = normalizedOrderRows.slice(i, i + UPDATE_CHUNK_SIZE);
|
||
if (chunkRows.length === 0) {
|
||
continue;
|
||
}
|
||
|
||
const chunkOrderIds = chunkRows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0);
|
||
if (chunkOrderIds.length === 0) {
|
||
continue;
|
||
}
|
||
|
||
const now = new Date();
|
||
const updateValues = {
|
||
intercept_status: 'none',
|
||
updated_at: now,
|
||
};
|
||
|
||
await orderModel.update(updateValues, {
|
||
where: {
|
||
id: {
|
||
[Op.in]: chunkOrderIds,
|
||
},
|
||
},
|
||
});
|
||
|
||
// 同步清除运单表拦截标记(退回收到标记 is_back 保持不变,由退回收货流程单独管理)
|
||
try {
|
||
await ctx.model.OrderExpress.update(
|
||
{ is_intercept: 'N' },
|
||
{ where: { order_id: { [Op.in]: chunkOrderIds }, warehouse_id: warehouseId } }
|
||
);
|
||
} catch (expressErr) {
|
||
ctx.logger.warn(
|
||
`[order.pendingOrder.batchUnintercept] 清除运单拦截标记失败, count=${chunkOrderIds.length}, error=${expressErr.message}`
|
||
);
|
||
}
|
||
|
||
// 写入操作日志 ORDER_INTERCEPT_CANCEL
|
||
const logPayloads = chunkRows.map(row => {
|
||
const orderId = Number(row.id || 0);
|
||
const orderNo = String(row.delivery_order_code || row.pre_delivery_order_code || '').trim();
|
||
if (!Number.isInteger(orderId) || orderId <= 0) {
|
||
return null;
|
||
}
|
||
|
||
return {
|
||
businessType: 'order',
|
||
businessId: orderId,
|
||
operationCode: 'ORDER_INTERCEPT_CANCEL',
|
||
operator,
|
||
extras: {
|
||
warehouseId: logWarehouseId,
|
||
orderId,
|
||
orderNo,
|
||
newInterceptStatus: 'none',
|
||
},
|
||
beforeChanges: null,
|
||
};
|
||
}).filter(Boolean);
|
||
|
||
if (logPayloads.length > 0) {
|
||
try {
|
||
const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
|
||
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
|
||
await operationLogService.createOperationLogs(logPayloads);
|
||
}
|
||
} catch (logErr) {
|
||
ctx.logger.warn(
|
||
`[order.pendingOrder.batchUnintercept] 批量写操作日志失败,不影响主流程, count=${logPayloads.length}, error=${logErr.message}`
|
||
);
|
||
}
|
||
}
|
||
|
||
for (const orderId of chunkOrderIds) {
|
||
uninterceptedOrderIds.push(orderId);
|
||
}
|
||
|
||
// 更新进度
|
||
const progressPercent = validOrderCount > 0
|
||
? Math.min(99, Math.round((uninterceptedOrderIds.length / validOrderCount) * 100))
|
||
: 0;
|
||
|
||
await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'running', {
|
||
warehouse_id: warehouseId,
|
||
total_order_count: totalOrderCount,
|
||
unintercepted_order_count: uninterceptedOrderIds.length,
|
||
progress_percent: progressPercent,
|
||
});
|
||
}
|
||
|
||
const durationMs = Date.now() - startTime;
|
||
await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'success', {
|
||
warehouse_id: warehouseId,
|
||
total_order_count: totalOrderCount,
|
||
unintercepted_order_count: uninterceptedOrderIds.length,
|
||
progress_percent: 100,
|
||
end_time: Date.now(),
|
||
duration_ms: durationMs,
|
||
result: {
|
||
order_ids: orderIds,
|
||
unintercepted_order_ids: uninterceptedOrderIds,
|
||
unintercepted_order_count: uninterceptedOrderIds.length,
|
||
total_order_count: totalOrderCount,
|
||
duration_ms: durationMs,
|
||
message: `已解除拦截 ${uninterceptedOrderIds.length} 条订单`,
|
||
},
|
||
});
|
||
} catch (error) {
|
||
await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'failed', {
|
||
warehouse_id: warehouseId,
|
||
progress_percent: 0,
|
||
end_time: Date.now(),
|
||
duration_ms: Date.now() - startTime,
|
||
error: error && error.message ? error.message : `${error}`,
|
||
error_code: 'BATCH_UNINTERCEPT_FAILED',
|
||
});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 手工录入运单号。
|
||
*
|
||
* 为指定待处理订单创建一条运单记录(wms_order_express 表),
|
||
* 仅允许 step 在 [1,2,3] 且 outbound_status 不为 'padding' 的订单操作。
|
||
* 完成后同步更新订单表的 print_status 与 post_status 为 'fin',表示外部已打印。
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @param {number|string} data.order_id 订单ID(必填)。
|
||
* @param {string} data.waybill_code 运单号(必填)。
|
||
* @param {string} [data.logistics_interface_name] 物流接口名称(选填,手工填入的值)。
|
||
* @return {Promise<Object>} 统一 success 包装,含创建的运单记录。
|
||
*/
|
||
async manualWaybill(data = {}) {
|
||
const requestData = this.isPlainObject(data) ? data : {};
|
||
const warehouseId = this.getWarehouseId();
|
||
const operator = this.getOrderLogOperator();
|
||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||
|
||
// 1. 参数校验
|
||
const orderId = Number(requestData.order_id);
|
||
if (!Number.isInteger(orderId) || orderId <= 0) {
|
||
throw new Error('order_id 必须为正整数');
|
||
}
|
||
|
||
const waybillCode = String(requestData.waybill_code || '').trim();
|
||
if (!waybillCode) {
|
||
throw new Error('waybill_code(运单号)不能为空');
|
||
}
|
||
|
||
const logisticsInterfaceName = String(requestData.logistics_interface_name || '').trim() || null;
|
||
|
||
// 2. 查询订单并校验状态(待处理:step in [1,2,3] 且 outbound_status != 'padding')
|
||
const model = await this.getOrderModel('order', warehouseId);
|
||
const where = this.buildOrderWhere([ orderId ], warehouseId);
|
||
const order = await model.findOne({
|
||
where,
|
||
attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id', 'store_id', 'sys_logistics_code', 'sys_logistics_name', 'delivery_order_code', 'source_order_codes' ],
|
||
raw: true,
|
||
});
|
||
|
||
if (!order) {
|
||
throw new Error(`订单 ${orderId} 不存在或不属于当前仓库`);
|
||
}
|
||
|
||
const allowedSteps = new Set([ 1, 2, 3 ]);
|
||
if (!allowedSteps.has(order.step)) {
|
||
throw new Error(`订单 ${orderId} 当前步骤为 ${order.step},仅允许待处理状态(step 1/2/3)的订单手工录入运单号`);
|
||
}
|
||
|
||
if (order.outbound_status === PENDING_OUTBOUND_STATUS) {
|
||
throw new Error(`订单 ${orderId} 已标记待出库,不允许手工录入运单号`);
|
||
}
|
||
|
||
// 3. 创建运单记录
|
||
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
|
||
if (!orderExpressModel) {
|
||
throw new Error('OrderExpress 模型未加载');
|
||
}
|
||
|
||
// 3.0 检查是否已分配运单号:若已有 status=1 的记录,拒绝重复录入
|
||
const existingCompleted = await orderExpressModel.findOne({
|
||
where: {
|
||
order_id: orderId,
|
||
warehouse_id: Number(order.warehouse_id) || warehouseId,
|
||
status: 1,
|
||
},
|
||
attributes: [ 'id', 'waybill_code' ],
|
||
raw: true,
|
||
});
|
||
if (existingCompleted) {
|
||
const existingWaybill = String(existingCompleted.waybill_code || '').trim();
|
||
throw new Error(
|
||
`订单 ${orderId} 已分配运单号${existingWaybill ? `(${existingWaybill})` : ''},不允许重复手工录入`
|
||
);
|
||
}
|
||
|
||
// 3.1 计算 business_key 递增:查找当前订单已有最大 business_key,+1 递增
|
||
const maxBusinessKey = await orderExpressModel.max('business_key', {
|
||
where: {
|
||
order_id: orderId,
|
||
warehouse_id: Number(order.warehouse_id) || warehouseId,
|
||
},
|
||
});
|
||
const nextBusinessKey = Number.isFinite(Number(maxBusinessKey)) && Number(maxBusinessKey) > 0
|
||
? Number(maxBusinessKey) + 1
|
||
: 1;
|
||
|
||
const expressRecord = await orderExpressModel.create({
|
||
order_id: orderId,
|
||
waybill_code: waybillCode,
|
||
logistics_interface_name: logisticsInterfaceName,
|
||
logistics_code: String(order.sys_logistics_code || '').trim() || null,
|
||
logistics_name: String(order.sys_logistics_name || '').trim() || null,
|
||
delivery_order_code: String(order.delivery_order_code || '').trim() || null,
|
||
source_order_codes: String(order.source_order_codes || '').trim() || null,
|
||
warehouse_id: Number(order.warehouse_id) || warehouseId,
|
||
store_id: order.store_id != null ? Number(order.store_id) : null,
|
||
business_key: nextBusinessKey,
|
||
status: 1,
|
||
create_at: new Date(),
|
||
});
|
||
|
||
// 3.2 更新订单表的 print_status 与 post_status 为 'fin',表示外部已打印
|
||
await model.update(
|
||
{
|
||
print_status: 'fin',
|
||
post_status: 'fin',
|
||
updated_at: new Date(),
|
||
},
|
||
{
|
||
where: {
|
||
id: orderId,
|
||
},
|
||
}
|
||
);
|
||
|
||
// 4. 记录操作日志
|
||
try {
|
||
await this.ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'order',
|
||
businessId: String(orderId),
|
||
operationCode: 'ORDER_MANUAL_WAYBILL',
|
||
operator,
|
||
extras: {
|
||
warehouseId: logWarehouseId,
|
||
orderId,
|
||
waybillCode,
|
||
logisticsInterfaceName,
|
||
businessKey: nextBusinessKey,
|
||
expressRecordId: expressRecord.id,
|
||
message: `手工录入运单号:订单 ${orderId},运单号 ${waybillCode}`,
|
||
},
|
||
beforeChanges: null,
|
||
});
|
||
} catch (logErr) {
|
||
this.ctx.logger.warn('[PendingOrderService.manualWaybill] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
// 5. 自动同步回传(受合约策略 auto_sync_back 控制)
|
||
try {
|
||
const storeId = Number(order.store_id) || 0;
|
||
if (storeId > 0) {
|
||
const contractConfig = await this.service.systems.storeWarehouse.getContractConfig(
|
||
Number(order.warehouse_id) || warehouseId,
|
||
storeId
|
||
);
|
||
if (
|
||
contractConfig
|
||
&& contractConfig.policy_config
|
||
&& contractConfig.policy_config.auto_sync_back === 1
|
||
) {
|
||
this.syncOrderIds({ orderIds: [ orderId ] }).catch(err => {
|
||
this.ctx.logger.error(
|
||
`[auto_sync_back] manualWaybill 自动同步失败: ${err.message}`
|
||
);
|
||
});
|
||
}
|
||
}
|
||
} catch (err) {
|
||
this.ctx.logger.error(
|
||
`[auto_sync_back] manualWaybill 自动同步异常: ${err.message}`
|
||
);
|
||
}
|
||
|
||
return this.success('ok', {
|
||
id: expressRecord.id,
|
||
order_id: orderId,
|
||
waybill_code: waybillCode,
|
||
business_key: nextBusinessKey,
|
||
logistics_interface_name: logisticsInterfaceName,
|
||
create_at: expressRecord.create_at,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 取消订单时释放创建锁(lockItemStorages 添加的 wms_stock_warehouse.locked_quantity)。
|
||
*
|
||
* 直接从 wms_order_items 读取 plan_qty,按 stock_id 汇总后释放对应 wms_stock_warehouse.locked_quantity。
|
||
* 不依赖 wms_picking / wms_storage(储位分配的锁由 cancelAllocateStorage 负责释放)。
|
||
*
|
||
* @param {Object} options - 释放参数。
|
||
* @param {number[]} options.orderIds - 订单ID 数组。
|
||
* @param {number} options.warehouseId - 仓库ID。
|
||
* @return {Promise<void>}
|
||
*/
|
||
async releaseCreationLockForCancel({ orderIds, warehouseId } = {}) {
|
||
const { ctx, app } = this;
|
||
const { Op } = app.Sequelize;
|
||
|
||
if (!Array.isArray(orderIds) || orderIds.length === 0 || !warehouseId) {
|
||
return;
|
||
}
|
||
|
||
const stockModel = ctx.model.StockWarehouse;
|
||
if (!stockModel) {
|
||
ctx.logger.warn('[PendingOrderService.releaseCreationLockForCancel] StockWarehouse 模型不可用,跳过库存释放');
|
||
return;
|
||
}
|
||
|
||
const OrderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
|
||
if (!OrderItemsModel) {
|
||
ctx.logger.warn('[PendingOrderService.releaseCreationLockForCancel] OrderItems 模型不可用,跳过库存释放');
|
||
return;
|
||
}
|
||
|
||
const transaction = await ctx.model.transaction();
|
||
|
||
try {
|
||
// 直接从 order_items 读取 plan_qty,按 stock_id 汇总
|
||
const orderItems = await OrderItemsModel.findAll({
|
||
where: {
|
||
order_id: { [Op.in]: orderIds },
|
||
},
|
||
attributes: [ 'stock_id', 'plan_qty' ],
|
||
transaction,
|
||
lock: transaction.LOCK.UPDATE,
|
||
raw: true,
|
||
});
|
||
|
||
if (!Array.isArray(orderItems) || orderItems.length === 0) {
|
||
await transaction.commit();
|
||
return;
|
||
}
|
||
|
||
// 按 stock_id 汇总需要释放的创建锁数量
|
||
const stockReleaseMap = new Map();
|
||
for (const item of orderItems) {
|
||
const stockId = Number(item.stock_id || 0);
|
||
const planQty = Number(item.plan_qty || 0);
|
||
if (stockId > 0 && planQty > 0) {
|
||
stockReleaseMap.set(stockId, (stockReleaseMap.get(stockId) || 0) + planQty);
|
||
}
|
||
}
|
||
|
||
if (stockReleaseMap.size === 0) {
|
||
await transaction.commit();
|
||
return;
|
||
}
|
||
|
||
// 释放 wms_stock_warehouse.locked_quantity
|
||
const stockService = ctx.service && ctx.service.systems && ctx.service.systems.stockStore;
|
||
for (const [ stockId, quantity ] of stockReleaseMap.entries()) {
|
||
const releaseResult = await stockService.updateLockedQuantity(
|
||
stockId, -Number(quantity), transaction, {
|
||
remark: '系统取消订单-释放创建锁',
|
||
orderType: 'ORDER_CANCEL',
|
||
orderNo: orderIds.join(','),
|
||
orderId: 0,
|
||
}
|
||
);
|
||
|
||
if (!releaseResult.success) {
|
||
throw new Error(`库存主记录锁定数量不足,无法释放创建锁: stockId=${stockId}, quantity=${quantity}, ${releaseResult.error}`);
|
||
}
|
||
}
|
||
|
||
await transaction.commit();
|
||
} catch (error) {
|
||
try {
|
||
await transaction.rollback();
|
||
} catch (rollbackError) {
|
||
ctx.logger.error('[PendingOrderService.releaseCreationLockForCancel] 回滚失败', rollbackError);
|
||
}
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
// ========== allocateSubOrderNumber 子单号分配 ==========
|
||
|
||
/**
|
||
* 分配子单号(异步任务模式)。
|
||
*
|
||
* 为指定订单按 business_key(从 2 开始)逐个子单号分配运单号。
|
||
* 将所有 business_key 全量传入 createWaybillCodePipeline,
|
||
* 由 pipeline 内部事务 + UNIQUE(order_id,business_key,status,warehouse_id) 索引
|
||
* 保证并发安全:已分配(status=1)自动跳过,未分配 INSERT status=0 占位后分配。
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @param {number|string} data.order_id 订单ID(必填)。
|
||
* @param {number} data.sub_order_count 子单号数量(必填,>=1)。
|
||
* @return {Promise<Object>} 统一 success 包装,立即返回 task_id。
|
||
*/
|
||
async allocateSubOrderNumber(data = {}) {
|
||
const requestData = this.isPlainObject(data) ? data : {};
|
||
const warehouseId = this.getWarehouseId();
|
||
|
||
// 1. 参数校验
|
||
const orderId = Number(requestData.order_id);
|
||
if (!Number.isInteger(orderId) || orderId <= 0) {
|
||
throw new Error('order_id 必须为正整数');
|
||
}
|
||
|
||
const subOrderCount = Number(requestData.sub_order_count);
|
||
if (!Number.isInteger(subOrderCount) || subOrderCount < 1) {
|
||
throw new Error('sub_order_count 必须为正整数且 >= 1');
|
||
}
|
||
|
||
// 2. 查询订单并校验状态
|
||
// 先查 current 表;若不存在再查 dispatch 表(配送中订单可能已被定时任务迁移到 dispatch)
|
||
let model = await this.getOrderModel('order', warehouseId);
|
||
const where = this.buildOrderWhere([ orderId ], warehouseId);
|
||
let order = await model.findOne({
|
||
where,
|
||
attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id', 'store_id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'status' ],
|
||
raw: true,
|
||
});
|
||
|
||
if (!order) {
|
||
model = await this.getOrderModelByTableType('dispatch', warehouseId);
|
||
order = await model.findOne({
|
||
where,
|
||
attributes: [ 'id', 'step', 'outbound_status', 'warehouse_id', 'store_id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'status' ],
|
||
raw: true,
|
||
});
|
||
}
|
||
|
||
if (!order) {
|
||
throw new Error(`订单 ${orderId} 不存在或不属于当前仓库`);
|
||
}
|
||
|
||
if (order.status === PENDING_CANCEL_STATUS) {
|
||
throw new Error(`订单 ${orderId} 已取消,不允许分配子单号`);
|
||
}
|
||
|
||
const allowedSteps = new Set([ 1, 2, 3, 4 ]);
|
||
if (!allowedSteps.has(order.step)) {
|
||
throw new Error(`订单 ${orderId} 当前步骤为 ${order.step},仅允许待处理(step 1/2/3)或配送中(step 4)的订单分配子单号`);
|
||
}
|
||
|
||
// 仅待处理阶段(step 1/2/3)校验 outbound_status;配送中(step 4)不校验
|
||
if (order.step !== 4 && order.outbound_status === PENDING_OUTBOUND_STATUS) {
|
||
throw new Error(`订单 ${orderId} 已标记待出库,不允许分配子单号`);
|
||
}
|
||
|
||
// 3. 计算 business_key 列表(从 2 开始)
|
||
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
|
||
if (!orderExpressModel) {
|
||
throw new Error('OrderExpress 模型未加载');
|
||
}
|
||
|
||
// 3.1 校验主单号:必须已有 business_key=1 且 status=1 的主单号,才能拆子单号
|
||
const { Op } = this.app.Sequelize;
|
||
const mainWaybill = await orderExpressModel.findOne({
|
||
where: {
|
||
order_id: orderId,
|
||
warehouse_id: Number(order.warehouse_id) || warehouseId,
|
||
business_key: 1,
|
||
status: 1,
|
||
},
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
});
|
||
if (!mainWaybill) {
|
||
throw new Error(`订单 ${orderId} 尚未分配主单号,请先分配主单号后再拆子单号`);
|
||
}
|
||
|
||
const businessKeys = [];
|
||
for (let i = 0; i < subOrderCount; i++) {
|
||
businessKeys.push(2 + i);
|
||
}
|
||
|
||
// 4. 预查已有的已分配运单号(status=1),仅用于初始 details 展示与全部跳过优化
|
||
const existingCompleted = await orderExpressModel.findAll({
|
||
where: {
|
||
order_id: orderId,
|
||
warehouse_id: Number(order.warehouse_id) || warehouseId,
|
||
status: 1,
|
||
business_key: { [Op.in]: businessKeys },
|
||
},
|
||
attributes: [ 'business_key', 'waybill_code' ],
|
||
raw: true,
|
||
});
|
||
|
||
const completedBusinessKeyMap = new Map();
|
||
if (Array.isArray(existingCompleted)) {
|
||
for (const row of existingCompleted) {
|
||
completedBusinessKeyMap.set(Number(row.business_key), String(row.waybill_code || '').trim());
|
||
}
|
||
}
|
||
|
||
// 5. 生成任务ID,立即返回
|
||
const taskId = `sub_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
||
const taskPayload = {
|
||
task_id: taskId,
|
||
order_id: orderId,
|
||
status: 'submitted',
|
||
progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.submitted,
|
||
message: '子单号分配任务已提交',
|
||
result: {
|
||
total_count: businessKeys.length,
|
||
skip_count: completedBusinessKeyMap.size,
|
||
pending_count: businessKeys.length - completedBusinessKeyMap.size,
|
||
business_keys: businessKeys,
|
||
skipped_business_keys: businessKeys.filter(bk => completedBusinessKeyMap.has(bk)),
|
||
pending_business_keys: businessKeys.filter(bk => !completedBusinessKeyMap.has(bk)),
|
||
details: businessKeys.map(bk => ({
|
||
business_key: bk,
|
||
status: completedBusinessKeyMap.has(bk) ? 'skipped' : 'pending',
|
||
waybill_code: completedBusinessKeyMap.get(bk) || null,
|
||
})),
|
||
},
|
||
error: '',
|
||
};
|
||
await this.setAllocateSubOrderTaskProgress(taskId, taskPayload);
|
||
|
||
// 6. 如果全部已分配,跳过 pipeline 直接完成
|
||
if (completedBusinessKeyMap.size === businessKeys.length) {
|
||
await this.setAllocateSubOrderTaskProgress(taskId, {
|
||
...taskPayload,
|
||
status: 'success',
|
||
progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.success,
|
||
message: '子单号分配完成(全部已分配,无待处理项)',
|
||
});
|
||
return this.success('ok', {
|
||
...taskPayload,
|
||
status: 'success',
|
||
progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.success,
|
||
message: '子单号分配完成(全部已分配,无待处理项)',
|
||
update_time: Date.now(),
|
||
});
|
||
}
|
||
|
||
// 7. 后台异步执行分配(全量 business_key 传入 pipeline,由其内部事务保证去重与并发安全)
|
||
const orderWarehouseId = Number(order.warehouse_id) || warehouseId;
|
||
setImmediate(async () => {
|
||
try {
|
||
await this.setAllocateSubOrderTaskProgress(taskId, {
|
||
...taskPayload,
|
||
status: 'running',
|
||
progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.running,
|
||
message: '子单号分配处理中',
|
||
});
|
||
|
||
// 全量传入(含已分配的),pipeline 内部 createWaybillCode 事务会跳过 status=1 的记录
|
||
const ordersForPipeline = businessKeys.map(bk => ({
|
||
order_id: orderId,
|
||
business_key: bk,
|
||
sys_platform_code: order.sys_platform_code,
|
||
logistics_code: order.logistics_code,
|
||
sys_platform_name: order.sys_platform_name,
|
||
logistics_name: order.logistics_name,
|
||
store_id: order.store_id,
|
||
warehouse_id: Number(order.warehouse_id) || warehouseId,
|
||
}));
|
||
|
||
const pipelineResult = await this.service.systems.express.createWaybillCodePipeline(
|
||
ordersForPipeline,
|
||
{ awaitTasks: true }
|
||
);
|
||
|
||
// 回查最终分配结果
|
||
const updatedDetails = await this.buildSubOrderDetails(orderId, orderWarehouseId, businessKeys);
|
||
|
||
const successCount = updatedDetails.filter(d => d.status === 'allocated' || d.status === 'skipped').length;
|
||
const isPartial = successCount < businessKeys.length;
|
||
|
||
await this.setAllocateSubOrderTaskProgress(taskId, {
|
||
...taskPayload,
|
||
status: isPartial ? 'partial' : 'success',
|
||
progress: isPartial ? ALLOCATE_SUB_ORDER_PROGRESS_MAP.partial : ALLOCATE_SUB_ORDER_PROGRESS_MAP.success,
|
||
message: isPartial
|
||
? `子单号分配部分完成(${successCount}/${businessKeys.length})`
|
||
: '子单号分配完成',
|
||
result: {
|
||
...taskPayload.result,
|
||
pipeline_result: pipelineResult,
|
||
details: updatedDetails,
|
||
},
|
||
});
|
||
|
||
// 写入操作日志(成功)
|
||
try {
|
||
await this.writeAllocateSubOrderLog(orderId, orderWarehouseId, {
|
||
action: isPartial ? 'SUCCESS_PARTIAL' : 'SUCCESS',
|
||
subOrderCount: businessKeys.length,
|
||
successCount,
|
||
details: updatedDetails,
|
||
});
|
||
} catch (logErr) {
|
||
this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 写入成功操作日志失败: %s',
|
||
logErr && logErr.message ? logErr.message : logErr);
|
||
}
|
||
} catch (error) {
|
||
const errorMessage = error && error.message ? error.message : String(error);
|
||
|
||
await this.setAllocateSubOrderTaskProgress(taskId, {
|
||
...taskPayload,
|
||
status: 'failed',
|
||
progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.failed,
|
||
message: '子单号分配失败',
|
||
error: errorMessage,
|
||
});
|
||
|
||
// 写错误信息到 order_flag(尝试 current 和 dispatch 两张表)
|
||
try {
|
||
await this.writeAllocateSubOrderErrorFlag(orderId, orderWarehouseId, errorMessage);
|
||
} catch (flagErr) {
|
||
this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 写入 order_flag 失败: %s',
|
||
flagErr && flagErr.message ? flagErr.message : flagErr);
|
||
}
|
||
|
||
// 写入操作日志(失败)
|
||
try {
|
||
await this.writeAllocateSubOrderLog(orderId, orderWarehouseId, {
|
||
action: 'FAILED',
|
||
errorMessage,
|
||
});
|
||
} catch (logErr) {
|
||
this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 写入失败操作日志失败: %s',
|
||
logErr && logErr.message ? logErr.message : logErr);
|
||
}
|
||
}
|
||
});
|
||
|
||
return this.success('ok', {
|
||
...taskPayload,
|
||
update_time: Date.now(),
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 写入子单号分配的 order_flag 错误信息。
|
||
* 尝试更新 current 和 dispatch 两张表,任一成功即返回。
|
||
*
|
||
* @param {number} orderId 订单ID。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @param {string} errorMessage 错误信息。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async writeAllocateSubOrderErrorFlag(orderId, warehouseId, errorMessage) {
|
||
const flag = `[子单号分配失败] ${errorMessage}`.substring(0, 500);
|
||
const where = this.buildOrderWhere([ orderId ], warehouseId);
|
||
const updatePayload = { order_flag: flag, updated_at: new Date() };
|
||
|
||
// 尝试 current 表
|
||
try {
|
||
const currentModel = await this.getOrderModel('order', warehouseId);
|
||
if (currentModel && typeof currentModel.update === 'function') {
|
||
const [ affected ] = await currentModel.update(updatePayload, { where });
|
||
if (Number(affected) > 0) return;
|
||
}
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] current 表写入 order_flag 失败: %s',
|
||
err && err.message ? err.message : err);
|
||
}
|
||
|
||
// 尝试 dispatch 表
|
||
try {
|
||
const dispatchModel = await this.getOrderModelByTableType('dispatch', warehouseId);
|
||
if (dispatchModel && typeof dispatchModel.update === 'function') {
|
||
await dispatchModel.update(updatePayload, { where });
|
||
}
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] dispatch 表写入 order_flag 失败: %s',
|
||
err && err.message ? err.message : err);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 写入子单号分配的操作日志。
|
||
*
|
||
* @param {number} orderId 订单ID。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @param {Object} opts 日志详情。
|
||
* @param {string} opts.action 操作动作(SUCCESS/SUCCESS_PARTIAL/FAILED)。
|
||
* @param {number} [opts.subOrderCount] 子单总数。
|
||
* @param {number} [opts.successCount] 成功数。
|
||
* @param {string} [opts.errorMessage] 错误信息。
|
||
* @param {Array<Object>} [opts.details] 分配详情。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async writeAllocateSubOrderLog(orderId, warehouseId, opts = {}) {
|
||
const operator = this.getOrderLogOperator();
|
||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||
const now = new Date();
|
||
|
||
// 状态中文映射
|
||
const STATUS_CN = { allocated: '成功', failed: '失败', skipped: '跳过', pending: '处理中' };
|
||
const detailSummary = Array.isArray(opts.details)
|
||
? opts.details.slice(0, 10).map(d => {
|
||
const cn = STATUS_CN[d.status] || d.status;
|
||
let seg = `子单${d.business_key}:${cn}`;
|
||
if (d.status === 'failed' && d.note) {
|
||
seg += `(${d.note})`;
|
||
}
|
||
return seg;
|
||
}).join(', ')
|
||
: '';
|
||
|
||
let message = `子单号分配${opts.action === 'FAILED' ? '失败' : '完成'}`;
|
||
if (opts.action === 'SUCCESS_PARTIAL') {
|
||
message = `子单号分配部分完成(${opts.successCount}/${opts.subOrderCount})`;
|
||
}
|
||
if (opts.errorMessage) {
|
||
message += ` - ${opts.errorMessage}`;
|
||
}
|
||
if (detailSummary) {
|
||
message += ` | ${detailSummary}`;
|
||
}
|
||
|
||
const logRow = {
|
||
business_type: 'order',
|
||
business_id: String(orderId),
|
||
operation_code: '子单号分配',
|
||
operator_id: operator.id,
|
||
operator_name: operator.name,
|
||
external_log_type: 'NONE',
|
||
warehouse_id: logWarehouseId || null,
|
||
platform_code: 'SYSTEM',
|
||
message: message.substring(0, 1000),
|
||
created_at: now,
|
||
};
|
||
|
||
if (this.ctx.model && this.ctx.model.OperationLog) {
|
||
await this.ctx.model.OperationLog.create(logRow);
|
||
} else if (this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog) {
|
||
await this.ctx.service.systems.operationLog.createOperationLog(logRow);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 查询子单号分配任务进度。
|
||
*
|
||
* 可按 task_id 或 business_key 查询。
|
||
* 若传入 business_key,返回该 business_key 对应的分配详情。
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @param {string} data.task_id 任务ID。
|
||
* @param {string} data.taskId 任务ID(驼峰写法)。
|
||
* @param {number} [data.business_key] 子单号业务ID(可选,按业务ID过滤)。
|
||
* @param {number} [data.businessKey] 子单号业务ID(可选,驼峰写法)。
|
||
* @return {Promise<Object>} 统一 success 包装。
|
||
*/
|
||
async allocateSubOrderNumberProgress(data = {}) {
|
||
const requestData = this.isPlainObject(data) ? data : {};
|
||
const taskId = String(requestData.task_id || requestData.taskId || '').trim();
|
||
const businessKey = Number(requestData.business_key || requestData.businessKey);
|
||
|
||
if (!taskId) {
|
||
return this.success('ok', {
|
||
task_id: '',
|
||
status: 'not_found',
|
||
progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.not_found,
|
||
message: '任务不存在',
|
||
result: null,
|
||
error: '',
|
||
update_time: Date.now(),
|
||
});
|
||
}
|
||
|
||
const cachedTask = await this.getAllocateSubOrderTaskProgress(taskId);
|
||
if (!cachedTask) {
|
||
return this.success('ok', {
|
||
task_id: taskId,
|
||
status: 'not_found',
|
||
progress: ALLOCATE_SUB_ORDER_PROGRESS_MAP.not_found,
|
||
message: '任务不存在',
|
||
result: null,
|
||
error: '',
|
||
update_time: Date.now(),
|
||
});
|
||
}
|
||
|
||
// 如果传入了 business_key,过滤出该业务ID对应的详情
|
||
let filteredResult = cachedTask.result;
|
||
if (Number.isInteger(businessKey) && businessKey > 0 && cachedTask.result) {
|
||
const details = Array.isArray(cachedTask.result.details) ? cachedTask.result.details : [];
|
||
const matchedDetail = details.find(d => Number(d.business_key) === businessKey);
|
||
filteredResult = {
|
||
...cachedTask.result,
|
||
filtered_business_key: businessKey,
|
||
matched_detail: matchedDetail || null,
|
||
};
|
||
}
|
||
|
||
return this.success('ok', {
|
||
...cachedTask,
|
||
result: filteredResult,
|
||
update_time: cachedTask.update_time || Date.now(),
|
||
});
|
||
}
|
||
|
||
// ========== allocateSubOrderNumber 缓存工具方法 ==========
|
||
|
||
/**
|
||
* 获取子单号分配任务缓存键。
|
||
*
|
||
* @param {string} taskId 任务ID。
|
||
* @return {string} 缓存键。
|
||
*/
|
||
getAllocateSubOrderTaskCacheKey(taskId = '') {
|
||
const normalizedTaskId = String(taskId || '').trim();
|
||
if (!normalizedTaskId) {
|
||
return '';
|
||
}
|
||
return `${ALLOCATE_SUB_ORDER_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
|
||
}
|
||
|
||
/**
|
||
* 写入子单号分配任务进度。
|
||
*
|
||
* @param {string} taskId 任务ID。
|
||
* @param {Object} payload 任务状态与结果。
|
||
* @return {Promise<void>}
|
||
*/
|
||
async setAllocateSubOrderTaskProgress(taskId = '', payload = {}) {
|
||
const cacheKey = this.getAllocateSubOrderTaskCacheKey(taskId);
|
||
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
|
||
return;
|
||
}
|
||
|
||
const safePayload = this.isPlainObject(payload) ? payload : {};
|
||
const progressPayload = {
|
||
task_id: String(taskId || '').trim(),
|
||
order_id: safePayload.order_id || null,
|
||
status: String(safePayload.status || 'unknown').trim(),
|
||
progress: Number(safePayload.progress || 0),
|
||
message: String(safePayload.message || ''),
|
||
result: safePayload.result || null,
|
||
error: String(safePayload.error || ''),
|
||
update_time: Date.now(),
|
||
};
|
||
|
||
try {
|
||
await this.app.setCacheAsync(cacheKey, progressPayload, ALLOCATE_SUB_ORDER_TASK_CACHE_TTL_SECONDS);
|
||
} catch (error) {
|
||
this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 写入任务进度缓存失败: %s', error && error.message ? error.message : error);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 读取子单号分配任务进度。
|
||
*
|
||
* @param {string} taskId 任务ID。
|
||
* @return {Promise<Object|null>} 任务缓存结果。
|
||
*/
|
||
async getAllocateSubOrderTaskProgress(taskId = '') {
|
||
const cacheKey = this.getAllocateSubOrderTaskCacheKey(taskId);
|
||
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
|
||
return null;
|
||
}
|
||
|
||
try {
|
||
const cached = await this.app.getCacheAsync(cacheKey);
|
||
if (!this.isPlainObject(cached)) {
|
||
return null;
|
||
}
|
||
return cached;
|
||
} catch (error) {
|
||
this.ctx.logger.warn('[pendingOrder.allocateSubOrderNumber] 读取任务进度缓存失败: %s', error && error.message ? error.message : error);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 回查子单号分配结果详情(pipeline 执行后调用)。
|
||
*
|
||
* 根据 order_express 表最终状态判断每个 business_key 的结果:
|
||
* - status=1 且 waybill_code 非空 → allocated(本次分配成功或之前已分配)
|
||
* - status=0 → pipeline 占位但 API 未完成 → failed
|
||
* - 无记录 → failed(pipeline 未处理到)
|
||
*
|
||
* @param {number} orderId 订单ID。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @param {number[]} businessKeys 全部 business_key 列表。
|
||
* @return {Promise<Array<Object>>} 每个 business_key 的分配详情。
|
||
*/
|
||
async buildSubOrderDetails(orderId, warehouseId, businessKeys) {
|
||
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
|
||
if (!orderExpressModel) {
|
||
return businessKeys.map(bk => ({
|
||
business_key: bk,
|
||
status: 'unknown',
|
||
waybill_code: null,
|
||
note: 'OrderExpress 模型未加载',
|
||
}));
|
||
}
|
||
|
||
const { Op } = this.app.Sequelize;
|
||
const allRecords = await orderExpressModel.findAll({
|
||
where: {
|
||
order_id: orderId,
|
||
warehouse_id: warehouseId,
|
||
business_key: { [Op.in]: businessKeys },
|
||
},
|
||
attributes: [ 'business_key', 'waybill_code', 'status' ],
|
||
raw: true,
|
||
});
|
||
|
||
const recordMap = new Map();
|
||
if (Array.isArray(allRecords)) {
|
||
for (const row of allRecords) {
|
||
// 同一 business_key 可能有多条(status 不同),优先取 status=1 的
|
||
const existing = recordMap.get(Number(row.business_key));
|
||
if (!existing || Number(row.status) === 1) {
|
||
recordMap.set(Number(row.business_key), row);
|
||
}
|
||
}
|
||
}
|
||
|
||
// 兜底:如果 order_express 中一条记录都没有,尝试从订单表的 order_flag 获取异常信息
|
||
let orderFlagNote = '';
|
||
if (recordMap.size === 0) {
|
||
try {
|
||
const orderWhere = this.buildOrderWhere([ orderId ], warehouseId);
|
||
// 查 current 表
|
||
let orderModel = await this.getOrderModel('order', warehouseId);
|
||
let orderRow = await orderModel.findOne({
|
||
where: orderWhere,
|
||
attributes: [ 'order_flag' ],
|
||
raw: true,
|
||
});
|
||
// 查 dispatch 表兜底
|
||
if (!orderRow) {
|
||
orderModel = await this.getOrderModelByTableType('dispatch', warehouseId);
|
||
orderRow = await orderModel.findOne({
|
||
where: orderWhere,
|
||
attributes: [ 'order_flag' ],
|
||
raw: true,
|
||
});
|
||
}
|
||
if (orderRow && orderRow.order_flag) {
|
||
orderFlagNote = `(订单异常: ${String(orderRow.order_flag).trim()})`;
|
||
}
|
||
} catch (err) {
|
||
// 查 order_flag 失败不影响主流程
|
||
this.ctx.logger.warn('[pendingOrder.buildSubOrderDetails] 查询 order_flag 失败: %s',
|
||
err && err.message ? err.message : err);
|
||
}
|
||
}
|
||
|
||
return businessKeys.map(bk => {
|
||
const record = recordMap.get(bk);
|
||
if (record && Number(record.status) === 1 && String(record.waybill_code || '').trim()) {
|
||
return {
|
||
business_key: bk,
|
||
status: 'allocated',
|
||
waybill_code: String(record.waybill_code || '').trim(),
|
||
note: '子单号分配成功',
|
||
};
|
||
}
|
||
|
||
if (record && Number(record.status) === 0) {
|
||
return {
|
||
business_key: bk,
|
||
status: 'failed',
|
||
waybill_code: null,
|
||
note: '运单占位已创建但 API 未返回运单号(status=0)',
|
||
};
|
||
}
|
||
|
||
const baseNote = '未找到分配的运单记录';
|
||
return {
|
||
business_key: bk,
|
||
status: 'failed',
|
||
waybill_code: null,
|
||
note: orderFlagNote ? `${baseNote}${orderFlagNote}` : baseNote,
|
||
};
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 批量设置订单为已打印状态。
|
||
*
|
||
* 将给定订单 ID 列表中属于当前仓库的订单的 print_status 更新为 'fin'。
|
||
* 先查 current 表(wms_order_delivery_{warehouseId}),再查 dispatch 表
|
||
* (wms_order_delivery_{warehouseId}_dispatch)兜底。
|
||
* 仅允许 step 在 [1,2,3] 且 status 不为 'cancel' 的订单操作,已打印(print_status='fin')的订单会被静默跳过。
|
||
*
|
||
* @param {Object} data 请求体。
|
||
* @param {Array<number|string>|number|string} [data.order_ids] 订单ID集合(下划线写法)。
|
||
* @param {Array<number|string>|number|string} [data.orderIds] 订单ID集合(驼峰别名)。
|
||
* @param {Array<number|string>|number|string} [data.ids] 订单ID集合(简写别名)。
|
||
* @return {Promise<Object>} 统一 success 包装的更新结果。
|
||
*/
|
||
async batchMarkPrinted(data = {}) {
|
||
const requestData = this.isPlainObject(data) ? data : {};
|
||
const warehouseId = this.getWarehouseId();
|
||
const operator = this.getOrderLogOperator();
|
||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||
throw new Error('未识别到当前仓库上下文');
|
||
}
|
||
|
||
const rawIds = requestData.order_ids !== undefined ? requestData.order_ids
|
||
: requestData.orderIds !== undefined ? requestData.orderIds
|
||
: requestData.ids;
|
||
const orderIds = this.normalizeIdsInput(rawIds);
|
||
if (orderIds.length === 0) {
|
||
throw new Error('order_ids 参数不能为空或格式错误');
|
||
}
|
||
|
||
const { Op } = this.app.Sequelize;
|
||
const now = new Date();
|
||
|
||
const buildWhere = () => ({
|
||
step: { [Op.in]: [ 1, 2, 3 ] },
|
||
status: { [Op.ne]: 'cancel' },
|
||
print_status: { [Op.ne]: 'fin' },
|
||
});
|
||
|
||
// 1. 先查 current 表
|
||
const currentModel = await this.getOrderModel('order', warehouseId);
|
||
const currentWhere = {
|
||
...this.buildOrderWhere(orderIds, warehouseId),
|
||
...buildWhere(),
|
||
};
|
||
|
||
const [ currentAffected ] = await currentModel.update(
|
||
{ print_status: 'fin', updated_at: now },
|
||
{ where: currentWhere }
|
||
);
|
||
let updatedCount = Number(currentAffected || 0);
|
||
|
||
// 2. 查询 current 表中已存在的订单 ID,计算出未命中的 ID
|
||
const currentFoundRows = await currentModel.findAll({
|
||
attributes: [ 'id' ],
|
||
where: this.buildOrderWhere(orderIds, warehouseId),
|
||
raw: true,
|
||
});
|
||
const currentFoundIds = new Set(
|
||
(Array.isArray(currentFoundRows) ? currentFoundRows : []).map(row => Number(row.id))
|
||
);
|
||
const missingIds = orderIds.filter(id => !currentFoundIds.has(id));
|
||
|
||
// 3. dispatch 表兜底
|
||
if (missingIds.length > 0) {
|
||
try {
|
||
const dispatchModel = await this.ctx.model.OrderDeliveryFactory.getDispatchModel(warehouseId);
|
||
if (dispatchModel && typeof dispatchModel.update === 'function') {
|
||
const dispatchWhere = {
|
||
id: { [Op.in]: missingIds },
|
||
warehouse_id: warehouseId,
|
||
...buildWhere(),
|
||
};
|
||
|
||
const [ dispatchAffected ] = await dispatchModel.update(
|
||
{ print_status: 'fin', updated_at: now },
|
||
{ where: dispatchWhere }
|
||
);
|
||
updatedCount += Number(dispatchAffected || 0);
|
||
}
|
||
} catch (dispatchErr) {
|
||
this.ctx.logger.warn('[PendingOrderService.batchMarkPrinted] dispatch 表更新失败,不影响 current 表结果', dispatchErr);
|
||
}
|
||
}
|
||
|
||
// 写入操作日志(不影响主流程)
|
||
try {
|
||
const opLogService = this.ctx && this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog;
|
||
if (opLogService && typeof opLogService.createOperationLogs === 'function') {
|
||
const logPayloads = orderIds.map(orderId => ({
|
||
businessType: 'order',
|
||
businessId: String(orderId),
|
||
operationCode: 'ORDER_BATCH_MARK_PRINTED',
|
||
operator,
|
||
extras: {
|
||
warehouseId: logWarehouseId,
|
||
orderId,
|
||
message: `批量标记已打印:订单 ${orderId}`,
|
||
},
|
||
beforeChanges: null,
|
||
}));
|
||
await opLogService.createOperationLogs(logPayloads);
|
||
}
|
||
} catch (logErr) {
|
||
this.ctx.logger.warn('[PendingOrderService.batchMarkPrinted] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
return this.success('ok', {
|
||
updated_count: updatedCount,
|
||
ids: orderIds,
|
||
});
|
||
}
|
||
|
||
}
|
||
|
||
module.exports = PendingOrderService;
|