'use strict'; /** * 店管家取号手工验证脚本(不参与线上流程) * * 默认只做「只读」步骤:查订单 → 查绑定 → 调店管家订单列表接口回读订单行 → 打印将要发送的取号报文。 * 只有显式加「--execute」才会真正调用 ExpressPrint(会消耗面单并产生费用); * 真实取号默认开启,如需禁止(DGJ_WAYBILL_ENABLE=0)则脚本会拒绝执行。 * * 用法: * node scripts/dgj-waybill-probe.js --order dgj-10000266092590 --express STO * node scripts/dgj-waybill-probe.js --order dgj-10000266092590 --express STO --execute * node scripts/dgj-waybill-probe.js --order dgj-10000266092590 --express STO --execute --package-count 2 */ const fs = require('fs'); const path = require('path'); const mm = require('egg-mock'); const { ORDER_TABLE_BY_STATUS } = require('../app/lib/orderStatus'); function readArg(name) { const index = process.argv.indexOf(`--${name}`); if (index > -1) return process.argv[index + 1]; const inline = process.argv.find(item => item.startsWith(`--${name}=`)); return inline ? inline.slice(name.length + 3) : ''; } (async () => { const orderNo = readArg('order'); const expressCode = readArg('express'); const execute = process.argv.includes('--execute'); const pkgIndexArg = readArg('pkg-index'); const packageCount = Number(readArg('package-count') || 0) || 0; if (!orderNo || !expressCode) { console.error('用法:node scripts/dgj-waybill-probe.js --order --express <快递编码> [--execute] [--pkg-index N] [--package-count N]'); process.exit(1); } // 包裹序号(0 基):默认取单号尾部 `_N`(N-1),显式传 --pkg-index 时以传参为准 const packageIndex = pkgIndexArg === '' ? null : Number(pkgIndexArg); const app = mm.app(); await app.ready(); const ctx = app.mockContext(); const index = await ctx.model.OrderIndex.findOne({ where: { order_no: orderNo } }); if (!index) throw new Error(`未找到订单:${orderNo}`); const order = await ctx.model[orderTableModel(app, index.current_status)].findByPk(index.id); if (!order) throw new Error(`订单状态行不存在:${orderNo}(${index.current_status})`); const shop = order.shop_id ? await ctx.model.Shop.findByPk(order.shop_id) : null; if (!shop || Number(shop.type) !== 2 || !shop.external_print_account_id) { throw new Error('订单店铺不是外部打单平台商家,无法取号'); } const account = await ctx.model.ExternalPrintAccount.findByPk(shop.external_print_account_id, { include: [{ model: ctx.model.ExternalPrintPlatform, as: 'platform' }], }); if (!account || !account.platform) throw new Error('打单账号或平台配置不存在'); const platformCode = String(order.source_platform_code || '').trim(); const template = await ctx.service.externalPrintExpressInterface.resolveByCode( account.id, { platformCode, expressCode }, order.principal_id ); console.log('==== 订单 / 账号 / 绑定 ===='); console.log({ order_no: order.order_no, parent_order_no: order.parent_order_no, status: index.current_status, platform_code: platformCode, shop: { id: shop.id, name: shop.name, type: shop.type }, account: { id: account.id, account: account.account, platform: account.platform.code, fetch_waybill_no: account.platform.fetch_waybill_no }, express_code: expressCode, template: template ? { id: template.id, template_id: template.template_id, template_name: template.template_name, platform_type: template.platform_type, dbname: template.dbname, express_company: `${template.express_company_code}(${template.express_company_name})`, } : null, }); if (!template) { console.log('\n❌ 该编码没有绑定快递接口,无法取号(先到「外部打单平台 → 快递接口」绑定)'); process.exit(0); } const service = ctx.service.externalPrintOrder.createPlatformService(account); const detail = template.get ? template.get({ plain: true }) : template; // 只读步骤:回读店管家订单行(不消耗面单) let traceId = ''; try { const info = await service.getUserInfo(); traceId = (info.data && info.data.TraceId) || ''; } catch (err) { console.log(`⚠️ 获取 traceId 失败(不阻断):${err.message}`); } const logicalOrderId = String(order.parent_order_no || orderNo.replace(/^[^-]+-/, '')); const platformOrderId = String((order.extend_props && order.extend_props.platform_order_no) || order.oaid_order_source_code || ''); console.log('\n==== 回读店管家订单行(只读) ===='); console.log({ logicalOrderId, platformOrderId, traceId: traceId ? '已获取' : '空' }); let row = null; try { row = await service.findPlatformOrderRow(service.constructor.resolveOrderHost(detail.platform_type), { traceId, dbname: detail.dbname, logicalOrderId, platformOrderId, placeOrderTime: order.place_order_time || order.pay_time || order.created_at, }); } catch (err) { console.log(`❌ 回读订单行失败:${err.message}`); } if (!row) { console.log('❌ 店管家未返回该订单行,取号会失败(检查系统编号/分区 dbname/登录态)'); process.exit(0); } console.log({ Id: row.Id, LogicOrderId: row.LogicOrderId, PlatformOrderId: row.PlatformOrderId, ShopId: row.ShopId, FxUserId: row.FxUserId, ErpState: row.ErpState, PrintState: row.PrintState, ExpressPrintTimes: row.ExpressPrintTimes, ExpressPrintTime: row.ExpressPrintTime, LastWaybillCode: row.LastWaybillCode, WaybillCodes: Array.isArray(row.WaybillCodes) ? `[] (${row.WaybillCodes.length} 个)` : row.WaybillCodes, IsMultiPack: row.IsMultiPack, SumPackageCount: row.SumPackageCount, SubOrders: Array.isArray(row.SubOrders) ? row.SubOrders.length : 0, }); // 组装「将要发送」的报文,方便手工核对(不发送) const host = service.constructor.resolveOrderHost(detail.platform_type); console.log('\n==== 平台已有运单号 ===='); console.log(row.LastWaybillCode ? `平台订单行已有运单号 ${row.LastWaybillCode}(仅用于对比:OMS 不再复用,真实取号会调 ExpressPrint 换新号)` : '(平台无运单号,真实取号会调用 ExpressPrint,消耗面单)'); console.log(`打印状态 PrintState=${row.PrintState}、已打印 ${row.ExpressPrintTimes || 0} 次、` + `WaybillCodes=${Array.isArray(row.WaybillCodes) ? row.WaybillCodes.length : 0} 个、IsMultiPack=${row.IsMultiPack}`); if (Array.isArray(row.WaybillCodes) && row.WaybillCodes.length) { console.log('WaybillCodes 明细:', JSON.stringify(row.WaybillCodes.map(code => ({ WaybillCode: code.WaybillCode, WaybillCodeId: code.WaybillCodeId, TemplateId: code.TemplateId, CreateTime: code.CreateTime || code.WaybillCodeCreateDate, })))); } console.log('(取号统一走「新单号打印」:PrintMethod=NewPrint + IsIgnoreWaybillRepeat=false,每次分配新号)'); const buildForm = service.constructor.buildForm; const effectivePkgIndex = packageIndex === null ? (String(orderNo).match(/_(\d+)$/) ? Math.max(Number(String(orderNo).match(/_(\d+)$/)[1]) - 1, 0) : 0) : packageIndex; console.log(`\n包裹序号 = ${effectivePkgIndex}(仅留痕,不下发给平台:每次取号都会分配新号);PackageCount = ${packageCount || 1}`); const checkForm = buildCheckForm(buildForm, detail.template_id, [ row ]); const printForm = buildPrintForm(buildForm, detail.template_id, [ row ], { DateNow: '', DayPrintBatchNumber: '' }, packageCount || 1); console.log('\n==== 将发送的 CheckTemplateAvaliable(只读接口) ===='); console.log(`POST https://${host}/TemplateSet/CheckTemplateAvaliable`); console.log(checkForm); console.log('\n==== 将发送的 ExpressPrint(会消耗面单) ===='); console.log(`POST https://${host}/NewOrder/ExpressPrint`); console.log(printForm); if (!execute) { console.log('\n✅ 已完成只读校验,未调用取号接口。需要真实取号时执行:'); console.log(`node scripts/dgj-waybill-probe.js --order ${orderNo} --express ${expressCode} --execute [--package-count N]`); process.exit(0); } if (!service.constructor.isWaybillEnabled()) { console.log('\n❌ 当前已用 DGJ_WAYBILL_ENABLE=0 关闭真实取号,脚本拒绝执行;去掉该环境变量后再试'); process.exit(1); } console.log('\n⚠️ 即将真实取号(消耗面单)...'); const result = await service.fetchWaybillNo(order.get({ plain: true }), { template: detail, expressCode, platformCode, packageIndex: effectivePkgIndex, packageCount: packageCount || 1, }); const dir = path.join(__dirname, '..', 'tmp'); fs.mkdirSync(dir, { recursive: true }); const file = path.join(dir, `dgj-expressprint-${orderNo}-${Date.now()}.json`); fs.writeFileSync(file, JSON.stringify(result.raw, null, 2), 'utf8'); console.log('==== 取号结果 ===='); console.log({ waybill_code: result.waybill_code, waybill_codes: result.waybill_codes, previous_code: result.previous_code || '', printinfo_len: (result.printinfo || '').length, printinfo_head: (result.printinfo || '').slice(0, 120), signature: result.signature ? '已返回' : '无', raw: file, }); if (result.previous_code && result.previous_code === result.waybill_code) { console.log(`⚠️ 本次调用 ExpressPrint,但平台仍返回原运单号 ${result.previous_code}(平台未换号)`); } })(); /** * 状态 → 模型名 * @param {Object} app egg application * @param {string} status 订单状态 * @return {string} 模型名 */ function orderTableModel(app, status) { const map = { pending: 'OrderStatusPending', queued: 'OrderStatusQueued', exception: 'OrderStatusException', outsourcing: 'OrderStatusOutsourcing', delivery: 'OrderStatusDelivery', void: 'OrderStatusVoid', }; if (!map[status]) throw new Error(`未知订单状态:${status}(表 ${ORDER_TABLE_BY_STATUS[status] || '-'})`); return map[status]; } /** * 组装 CheckTemplateAvaliable 表单(与 dgj.checkTemplateAvailable 同口径) * @param {Object} buildForm 平台服务的表单构造器(PHP http_build_query 口径) * @param {string} templateId 模板ID * @param {Array} rows 平台订单行 * @return {string} 表单字符串 */ function buildCheckForm(buildForm, templateId, rows) { return buildForm({ templateId: String(templateId), printCount: String(rows.length), needCheck: 'true', orders: rows.map(row => ({ SourceShopId: row.ShopId, UpFxUserId: row.FxUserId, SourceFxUserId: row.FxUserId, LogicOrderId: row.LogicOrderId, PlatformOrderId: row.LogicOrderId, IsAllowNegativeStock: 'false', SendType: row.SendState, DataFlag: row.IsCold, Items: (row.SubOrders || []).map(sub => ({ OrderItemCode: sub.OrderItemCode, LogicOrderItemId: sub.OrderItemId, Quantity: '1', })), })), isResend: '', pirntMethod: 'Normal', IsContinueForStock: 'false', IsCustomerOrder: 'false', FxPageType: '2', }).toString(); } /** * 组装 ExpressPrint 表单(仅用于打印核对) * @param {Object} buildForm 平台服务的表单构造器(PHP http_build_query 口径) * @param {string} templateId 模板ID * @param {Array} rows 平台订单行 * @param {Object} checkData CheckTemplateAvaliable 的 Data * @param {number} [packageCount] 包裹张数(>1 时把订单行重复 N 份,用于多包裹试验) * @return {string} 表单字符串 */ function buildPrintForm(buildForm, templateId, rows, checkData, packageCount = 1) { const repeat = Number(packageCount) > 1 ? Math.floor(Number(packageCount)) : 1; const sourceRows = []; for (let i = 0; i < repeat; i += 1) sourceRows.push(...(rows || [])); return buildForm({ TemplateId: String(templateId), PackageCount: String(repeat), PackageDesc: '', GoodsDesc: '', PrintMethod: 'Normal', IsIgnoreWaybillRepeat: 'true', PrinterName: '默认打印机', IsPreview: 'false', IsContinueForStock: 'false', PackageLength: '', PackageWidth: '', PackageHeight: '', ExpressSustenance: { name: '', desc: '' }, Branches: '', Orders: sourceRows.map((row, index) => ({ WaybillCodeId: '', Index: index + 1, Id: row.Id, LogicOrderId: row.LogicOrderId, PlatformOrderId: row.LogicOrderId, CustomerOrderId: row.PlatformOrderId, ShopId: row.ShopId, PathFlowCode: row.PathFlowCode, FxUserId: row.FxUserId, WaybillCode: '', Items: (row.SubOrders || []).map(sub => ({ OrderItemId: sub.OrderItemId, OrderItemCode: sub.OrderItemCode, Quantity: '1', })), })), RequestBatchNumber: `1/1/${checkData.DateNow || ''}${checkData.DayPrintBatchNumber || ''}`, IsCustomerOrder: 'false', FxPageType: '2', }).toString(); }