'use strict'; const Service = require('egg').Service; const { parsePagination } = require('../lib/pagination'); /** 明细接口可能返回的敏感字段(不回显给前端) */ const SENSITIVE_DETAIL_KEYS = [ 'CustomerPwd', 'Password', 'Secret', 'Token', 'AppSecret', 'PrivateKey' ]; /** * 递归屏蔽明细里的凭据字段,避免电子面单账号密码通过接口泄露 * @param {*} value 原始值 * @return {*} 屏蔽后的值 */ function maskSensitive(value) { if (Array.isArray(value)) return value.map(maskSensitive); if (!value || typeof value !== 'object') return value; const result = {}; for (const [ key, item ] of Object.entries(value)) { result[key] = SENSITIVE_DETAIL_KEYS.includes(key) ? '******' : maskSensitive(item); } return result; } /** * 外部打单平台快递接口(面单模板)服务。 * * 数据来源:打单账号登录后,按账号下每个外部店铺的平台分区拉取全部面单模板; * 自定义编码与默认设置属于人工配置,同步时只刷新平台字段,不覆盖这些配置。 * 平台侧不再返回的模板不删除,标记 status=0(已失效),保证映射配置不丢失。 */ class ExternalPrintExpressInterfaceService extends Service { /** * 从平台全量拉取账号下所有店铺的快递接口并落库 * @param {Object} account 打单账号实例(需 include platform) * @param {number} principalId 主体ID * @return {Promise} 同步结果(总数 / 新增 / 更新 / 失效 / 店铺 / 错误) */ async sync(account, principalId) { const { ctx } = this; const platformService = ctx.service.externalPrintOrder.createPlatformService(account); if (typeof platformService.listExpressTemplates !== 'function') { const err = new Error(`外部打单平台 ${account.platform.name} 暂不支持拉取快递接口`); err.status = 400; throw err; } const shops = await ctx.model.Shop.findAll({ where: { principal_id: principalId, external_print_account_id: account.id, type: 2 }, order: [[ 'id', 'ASC' ]], }); if (!shops.length) { const err = new Error('该账号下还没有外部打单平台店铺,请先「查看店铺」并添加店铺后再拉取快递接口'); err.status = 400; throw err; } const merged = new Map(); const errors = []; const syncedShops = []; for (const shop of shops) { try { const result = await platformService.listExpressTemplates(shop.get({ plain: true })); for (const item of result.list) merged.set(item.template_id, item); for (const message of result.errors) errors.push(`${shop.name}:${message}`); if (result.list.length) syncedShops.push(shop.name); } catch (err) { errors.push(`${shop.name}:${err.message}`); } } // 只有全部店铺都拉取成功时才标记失效,避免部分分区失败导致映射被误判为失效 const fullScan = errors.length === 0; if (!merged.size && !fullScan) { const err = new Error(`拉取快递接口失败:${errors[0]}`); err.status = 400; throw err; } const now = new Date(); const transaction = await ctx.model.transaction(); let created = 0; let updated = 0; let invalidated = 0; try { const existing = await ctx.model.ExternalPrintExpressInterface.findAll({ where: { principal_id: principalId, account_id: account.id }, transaction, }); const byTemplate = new Map(existing.map(row => [ String(row.template_id), row ])); for (const item of merged.values()) { const patch = { platform_type: item.platform_type, platform_code: item.platform_code, platform_name: item.platform_name, template_name: item.template_name, express_company_id: item.express_company_id || null, express_company_code: item.express_company_code || null, express_company_name: item.express_company_name || null, shop_id: item.shop_id || null, shop_name: item.shop_name || null, dbname: item.dbname || null, cai_niao_auth_info_id: item.cai_niao_auth_info_id || null, platform_updated_at: item.platform_updated_at || null, synced_at: now, status: 1, raw: item.raw, }; const row = byTemplate.get(item.template_id); if (row) { await row.update(patch, { transaction }); updated += 1; byTemplate.delete(item.template_id); } else { await ctx.model.ExternalPrintExpressInterface.create({ principal_id: principalId, account_id: account.id, template_id: item.template_id, ...patch, }, { transaction }); created += 1; } } if (fullScan) { for (const row of byTemplate.values()) { if (Number(row.status) === 0) continue; // 失效后不再参与回读定位,但绑定的快递编码保留,便于平台恢复后继续使用 await row.update({ status: 0, synced_at: now }, { transaction }); invalidated += 1; } } await transaction.commit(); } catch (err) { await transaction.rollback(); throw err; } // 平台同步会新增/失效模板并改写绑定,清掉该账号的绑定缓存 await this.invalidateTemplateCache(account.id); return { total: merged.size, created, updated, invalidated, shops: syncedShops, errors, full_scan: fullScan, }; } /** * 分页查询已落库的快递接口 * @param {Object} account 打单账号实例 * @param {Object} params 查询参数(page / pageSize / status / platform_code / express_company_code / keyword) * @param {number} principalId 主体ID * @return {Promise<{list: Array, total: number}>} 列表与总数 */ async list(account, params, principalId) { const { ctx } = this; const Op = ctx.app.Sequelize.Op; const { page, pageSize, offset, limit } = parsePagination(params); const where = { principal_id: principalId, account_id: account.id }; if (params.status !== undefined && params.status !== '' && params.status !== null) { where.status = Number(params.status) === 0 ? 0 : 1; } if (params.platform_code) where.platform_code = String(params.platform_code).trim(); if (params.express_company_code) where.express_company_code = String(params.express_company_code).trim(); const keyword = String(params.keyword || '').trim(); if (keyword) { where[Op.or] = [ { template_name: { [Op.like]: `%${keyword}%` } }, { express_company_name: { [Op.like]: `%${keyword}%` } }, { express_company_code: { [Op.like]: `%${keyword}%` } }, { shop_name: { [Op.like]: `%${keyword}%` } }, { custom_code: { [Op.like]: `%${keyword}%` } }, ]; } const { count, rows } = await ctx.model.ExternalPrintExpressInterface.findAndCountAll({ where, offset, limit, // 列表不返回平台原始结构,避免大数据量拖慢列表 attributes: { exclude: [ 'raw' ] }, order: [ [ 'status', 'DESC' ], [ 'platform_code', 'ASC' ], [ 'express_company_name', 'ASC' ], [ 'template_name', 'ASC' ], [ 'id', 'ASC' ], ], include: [ { model: ctx.model.ExpressCompany, as: 'customExpressCompany', attributes: [ 'id', 'code', 'name' ], required: false, }, ], }); return { list: rows, total: count, page, pageSize }; } /** * 保存人工配置:绑定的快递编码 / 备注 * * 同一账号同一平台下,一个快递编码只能绑定一个模板(重复会拒绝), * 保证回读时按「账号 + 平台 + 编码」能唯一定位。 * @param {Object} account 打单账号实例 * @param {Array} items 待保存项 [{ id, custom_code, remark }] * @param {number} principalId 主体ID * @return {Promise<{updated: number}>} 更新条数 */ async saveSettings(account, items, principalId) { const { ctx } = this; const Op = ctx.app.Sequelize.Op; const list = Array.isArray(items) ? items : []; if (!list.length) { const err = new Error('items(待保存的快递接口)不能为空'); err.status = 400; throw err; } if (list.length > 500) { const err = new Error('单次最多保存 500 条快递接口设置'); err.status = 400; throw err; } const ids = [ ...new Set(list.map(item => Number(item && item.id)).filter(id => Number.isInteger(id) && id > 0)) ]; if (ids.length !== list.length) { const err = new Error('存在无效或重复的快递接口ID'); err.status = 400; throw err; } const rows = await ctx.model.ExternalPrintExpressInterface.findAll({ where: { id: { [Op.in]: ids }, principal_id: principalId, account_id: account.id }, }); if (rows.length !== ids.length) { const err = new Error(`存在 ${ids.length - rows.length} 条快递接口不存在或不属于当前账号`); err.status = 400; throw err; } const byId = new Map(rows.map(row => [ Number(row.id), row ])); const patches = []; for (const item of list) { const row = byId.get(Number(item.id)); const patch = {}; if (item.custom_code !== undefined) { // 绑定的快递编码(系统或自定义),仅限制长度;同一账号同平台下必须唯一 patch.custom_code = String(item.custom_code || '').trim().slice(0, 50) || null; } if (item.remark !== undefined) { patch.remark = String(item.remark || '').trim().slice(0, 255) || null; } if (Object.keys(patch).length) patches.push({ row, patch }); } if (!patches.length) return { updated: 0 }; // 同一账号 + 同一平台内,一个快递编码只能绑定一个模板(不同平台互不影响,可绑定相同编码): // 回读运单号按「订单平台 + 外部携带的快递编码」定位,同平台重复绑定会查到多条而无法确定用哪个 const proposals = patches .filter(({ patch }) => patch.custom_code !== undefined && patch.custom_code) .map(({ row, patch }) => ({ row, code: patch.custom_code })); for (const { row, code } of proposals) { const label = `${row.platform_name || row.platform_code || '未知平台'}`; const sameBatch = proposals.find(other => Number(other.row.id) !== Number(row.id) && other.row.platform_code === row.platform_code && other.code === code ); if (sameBatch) { const err = new Error( `平台「${label}」内快递编码「${code}」重复绑定:本次同时绑定到「${row.template_name || row.template_id}」和「${sameBatch.row.template_name || sameBatch.row.template_id}」,同平台内一个编码只能绑定一个模板,请改用其它编码(不同平台不受影响)` ); err.status = 400; throw err; } const occupied = await ctx.model.ExternalPrintExpressInterface.findOne({ where: { principal_id: principalId, account_id: account.id, platform_code: row.platform_code, custom_code: code, status: 1, id: { [Op.ne]: row.id }, }, attributes: [ 'id', 'template_name', 'template_id' ], }); if (occupied) { const err = new Error( `平台「${label}」内快递编码「${code}」已绑定模板「${occupied.template_name || occupied.template_id}」,同平台内一个编码只能绑定一个模板,请先解除或改用其它编码(不同平台不受影响)` ); err.status = 400; throw err; } } const transaction = await ctx.model.transaction(); try { for (const { row, patch } of patches) { await row.update(patch, { transaction }); } await transaction.commit(); } catch (err) { await transaction.rollback(); throw err; } // 绑定关系变更:清掉该账号的「平台+编码 → 模板」缓存,避免取号短时间仍命中旧模板 await this.invalidateTemplateCache(account.id); return { updated: patches.length }; } /** * 清除某打单账号的快递编码绑定缓存(绑定变更 / 平台同步后调用) * @param {number} accountId 打单账号ID * @return {Promise} 无返回值 */ async invalidateTemplateCache(accountId) { const cache = this.ctx.service && this.ctx.service.cache; if (cache && typeof cache.invalidateExternalPrintAccount === 'function') { await cache.invalidateExternalPrintAccount(accountId); } } /** * 回读运单号时定位快递接口 * * WMS 发起取号会携带快递编码,且必须使用该订单所属外部打单账号(跨打单平台无法打印); * 本方法按「打单账号 + 订单平台(平台编码)+ 绑定的快递编码」唯一定位模板。 * 不再参考订单上设置的物流公司,也不按店铺区分(店管家店铺是商家,共用账号下的接口)。 * @param {number} accountId 打单账号ID * @param {Object} params 查询条件 * @param {string} params.platformCode OMS 平台编码(如 TB) * @param {string} params.expressCode 外部携带的快递编码(系统或自定义) * @param {number} principalId 主体ID * @return {Promise} 命中的接口;未绑定或重复绑定时返回 null */ async resolveByCode(accountId, { platformCode, expressCode } = {}, principalId) { const { ctx } = this; if (!platformCode || !expressCode) return null; const loader = async () => { const rows = await ctx.model.ExternalPrintExpressInterface.findAll({ where: { principal_id: principalId, account_id: accountId, platform_code: platformCode, custom_code: expressCode, status: 1, }, limit: 2, }); // 唯一命中才返回;出现重复绑定(历史数据 / 平台变更)时返回 null,避免随意挑一个 return rows.length === 1 ? rows[0].toJSON() : null; }; // 绑定关系查询高频(取号逐单定位模板),走缓存;绑定变更时由 sync / saveSettings 主动失效 const cache = ctx.service && ctx.service.cache; if (cache && typeof cache.getExpressTemplate === 'function') { return await cache.getExpressTemplate(accountId, platformCode, expressCode, loader); } return await loader(); } /** * 查看单个快递接口的平台明细(实时请求平台单独接口) * @param {Object} account 打单账号实例(需 include platform) * @param {number} interfaceId 快递接口记录ID * @param {number} principalId 主体ID * @return {Promise<{interface: Object, detail: Object|null}>} 接口记录与平台明细 */ async detail(account, interfaceId, principalId) { const { ctx } = this; const row = await ctx.model.ExternalPrintExpressInterface.findOne({ where: { id: interfaceId, principal_id: principalId, account_id: account.id }, }); if (!row) { const err = new Error('快递接口不存在'); err.status = 404; throw err; } if (Number(row.status) === 0) { const err = new Error('该快递接口在平台已失效,无法查看明细;请先重新拉取'); err.status = 400; throw err; } const platformService = ctx.service.externalPrintOrder.createPlatformService(account); if (typeof platformService.fetchWaybillAccountDetail !== 'function') { const err = new Error(`外部打单平台 ${account.platform.name} 暂不支持查看快递接口明细`); err.status = 400; throw err; } const detail = await platformService.fetchWaybillAccountDetail(row.get({ plain: true })); return { interface: row, detail: maskSensitive(detail) }; } } module.exports = ExternalPrintExpressInterfaceService;