'use strict'; const MainService = require('../main'); const crypto = require('crypto'); const PddClient = require('../../lib/pdd_client'); const { buildNotDeletedShopWhere } = require('../../lib/shop_soft_delete'); const DEFAULT_PDD_ROUTER_URL = 'https://gw-api.pinduoduo.com/api/router'; const DEFAULT_TB_ROUTER_URL = 'https://eco.taobao.com/router/rest'; const SHOP_MASK_PLACEHOLDER = '***'; const TB_FILTERED_SERVICE_REGEXP = /\b(?:COD|RECEIVER[-_ ]?PAY)\b|代收货款|到付|拦截件|定时派送|上门取旧换新/i; /** * 脱敏通用敏感文本。 * * @param {*} value 原始敏感值 * @return {string|null} 脱敏后的值;原值为空时返回 null */ function maskSensitiveText(value) { if (value === null || value === undefined || String(value).trim() === '') { return null; } return SHOP_MASK_PLACEHOLDER; } /** * 脱敏店铺归属人标识。 * * @param {*} ownerId 店铺归属人标识 * @return {string|null} 脱敏后的归属人标识;原值为空时返回 null */ function maskShopOwnerId(ownerId) { if (ownerId === null || ownerId === undefined || String(ownerId).trim() === '') { return null; } const ownerIdText = String(ownerId); if (ownerIdText.length <= 5) { return SHOP_MASK_PLACEHOLDER; } return `${ownerIdText.slice(0, 3)}${SHOP_MASK_PLACEHOLDER}${ownerIdText.slice(-2)}`; } /** * 将店铺记录裁剪为安全的列表输出。 * * @param {Object} shopItem 店铺记录或模型实例 * @return {Object} 脱敏后的店铺列表项 */ function maskShopListItem(shopItem) { const plainItem = shopItem && typeof shopItem.get === 'function' ? shopItem.get({ plain: true }) : shopItem || {}; const printPlatform = plainItem.printPlatform && typeof plainItem.printPlatform === 'object' ? plainItem.printPlatform : null; return { id: plainItem.id, warehouse_id: plainItem.warehouse_id, platform_code: plainItem.platform_code, platform_name: printPlatform ? printPlatform.platform_name || printPlatform.platform_code || '' : '', shop_name: plainItem.shop_name, custom_name: plainItem.custom_name, status: plainItem.status, auth_expire_at: plainItem.auth_expire_at, token_expires_at: plainItem.token_expires_at, refresh_token_expires_at: plainItem.refresh_token_expires_at, scope: plainItem.scope, created_at: plainItem.created_at, updated_at: plainItem.updated_at, owner_id: maskShopOwnerId(plainItem.owner_id), access_token: maskSensitiveText(plainItem.access_token), refresh_token: maskSensitiveText(plainItem.refresh_token), auth_random_code: maskSensitiveText(plainItem.auth_random_code), }; } /** * 将任意值标准化为空字符串。 * * @param {*} value 原始值 * @return {string} 标准化后的字符串 */ function normalizeText(value) { if (value === null || value === undefined) { return ''; } return String(value); } /** * 判断淘宝菜鸟服务项是否属于代收货款、到付、拦截件、定时派送或上门取旧换新类服务。 * * @param {Object} serviceItem 淘宝菜鸟服务项 * @return {boolean} 是否需要从统一返回结果中过滤 */ function shouldFilterTbService(serviceItem) { const currentServiceItem = serviceItem && typeof serviceItem === 'object' ? serviceItem : {}; const candidateTexts = [ currentServiceItem.service_code, currentServiceItem.service_name, currentServiceItem.service_desc, ].map(item => normalizeText(item).trim()).filter(Boolean); return candidateTexts.some(item => TB_FILTERED_SERVICE_REGEXP.test(item)); } /** * 将任意值标准化为数组。 * * @param {*} value 原始值 * @return {Array} 数组值;非数组时返回空数组 */ function normalizeArray(value) { return Array.isArray(value) ? value : []; } /** * 将对象包裹的集合字段标准化为数组。 * * @param {*} value 原始集合值 * @param {Array} [nestedKeys=[]] 对象包裹时的候选子字段名 * @return {Array} 标准化后的数组 */ function normalizeWrappedArray(value, nestedKeys = []) { if (Array.isArray(value)) { return value; } if (!value || typeof value !== 'object') { return []; } for (const nestedKey of normalizeArray(nestedKeys)) { if (!nestedKey || !Object.prototype.hasOwnProperty.call(value, nestedKey)) { continue; } const nestedValue = value[nestedKey]; if (Array.isArray(nestedValue)) { return nestedValue; } if (nestedValue !== null && nestedValue !== undefined) { return [ nestedValue ]; } } return Object.keys(value).length ? [ value ] : []; } /** * 按候选来源顺序提取首个非空包裹集合。 * * @param {Array<*>} values 候选来源列表 * @param {Array} [nestedKeys=[]] 对象包裹时的候选子字段名 * @return {Array} 首个非空的标准化数组 */ function normalizeFirstWrappedArray(values, nestedKeys = []) { for (const value of normalizeArray(values)) { const normalized = normalizeWrappedArray(value, nestedKeys); if (normalized.length) { return normalized; } } return []; } /** * 按候选字段顺序提取首个非空值。 * * @param {Array<*>} values 候选值列表 * @return {*} 首个非空值;未命中时返回空字符串 */ function resolveFirstNonEmptyValue(values = []) { for (const value of normalizeArray(values)) { if (value === null || value === undefined) { continue; } if (String(value).trim() === '') { continue; } return value; } return ''; } /** * 将 JD 模板响应中的标准模板列表扁平化为前端易消费结构。 * * @param {Object} templateResponseItem JD 模板命中对象 * @return {Array} 扁平化后的模板列表 */ function normalizeJdTemplateList(templateResponseItem) { const currentTemplateResponseItem = templateResponseItem && typeof templateResponseItem === 'object' ? templateResponseItem : {}; const cpCode = normalizeText(resolveFirstNonEmptyValue([ currentTemplateResponseItem.cp_code, currentTemplateResponseItem.cpcode, currentTemplateResponseItem.cpCode, ])).trim(); const standardTemplateList = normalizeFirstWrappedArray([ currentTemplateResponseItem.standard_templates, currentTemplateResponseItem.standardTemplates, currentTemplateResponseItem.standard_template_do, currentTemplateResponseItem.standardTemplateDo, ], [ 'standard_template_do', 'standardTemplateDo' ]); return standardTemplateList.map(templateItem => { const currentTemplateItem = templateItem && typeof templateItem === 'object' ? templateItem : {}; const brandCode = normalizeText(resolveFirstNonEmptyValue([ currentTemplateItem.brand_code, currentTemplateItem.brandcode, currentTemplateItem.brandCode, ])).trim(); const standardWaybillType = normalizeText(resolveFirstNonEmptyValue([ currentTemplateItem.standard_waybill_type, currentTemplateItem.templatetype, currentTemplateItem.templateType, ])).trim(); return { template_id: normalizeText(resolveFirstNonEmptyValue([ currentTemplateItem.standard_template_id, currentTemplateItem.id, currentTemplateItem.templateid, currentTemplateItem.templateId, ])).trim(), template_name: normalizeText(resolveFirstNonEmptyValue([ currentTemplateItem.standard_template_name, currentTemplateItem.name, currentTemplateItem.templatename, currentTemplateItem.templateName, ])).trim(), template_url: normalizeText(resolveFirstNonEmptyValue([ currentTemplateItem.standard_template_url, currentTemplateItem.url, currentTemplateItem.templateurl, currentTemplateItem.templateUrl, currentTemplateItem.tempurl, currentTemplateItem.tempUrl, ])).trim(), cp_code: cpCode || normalizeText(resolveFirstNonEmptyValue([ currentTemplateItem.cp_code, currentTemplateItem.cpcode, currentTemplateItem.cpCode, ])).trim(), wp_code: brandCode || standardWaybillType, }; }); } /** * 为 JD 模板命中结果补充扁平化模板列表,保持原始字段不变。 * * @param {Object} templateResponseItem JD 模板命中对象 * @return {Object} 补充 list 字段后的 JD 模板响应 */ function appendJdTemplateList(templateResponseItem) { const currentTemplateResponseItem = templateResponseItem && typeof templateResponseItem === 'object' ? templateResponseItem : {}; return { ...currentTemplateResponseItem, list: normalizeJdTemplateList(currentTemplateResponseItem), }; } /** * 规范化菜鸟标准模板子项列表。 * * @param {*} standardTemplates 菜鸟标准模板字段 * @return {Array} 标准模板子项列表 */ // eslint-disable-next-line no-unused-vars function normalizeCainiaoStandardTemplateList(standardTemplates) { return normalizeWrappedArray(standardTemplates, [ 'standard_template_do' ]); } /** * 按原始结构回填菜鸟标准模板子项列表。 * * @param {*} standardTemplates 菜鸟标准模板字段 * @param {Array} templateList 过滤后的标准模板子项列表 * @return {*} 回填后的标准模板字段 */ // eslint-disable-next-line no-unused-vars function rebuildCainiaoStandardTemplates(standardTemplates, templateList) { if (Array.isArray(standardTemplates)) { return templateList; } if (standardTemplates && typeof standardTemplates === 'object') { if (Object.prototype.hasOwnProperty.call(standardTemplates, 'standard_template_do')) { return { ...standardTemplates, standard_template_do: templateList, }; } return Object.keys(standardTemplates).length ? { ...standardTemplates, standard_template_do: templateList, } : templateList; } return templateList; } /** * 根据平台编码构建平台侧快递编码到系统快递信息的映射。 * * @param {Array} expressList 系统快递列表 * @param {string} platformCode 平台编码 * @return {Object} 平台侧快递编码到系统快递信息的映射 */ function buildPlatformExpressNameMap(expressList, platformCode) { const normalizedPlatformCode = String(platformCode || '').trim().toUpperCase(); if (!normalizedPlatformCode) { return {}; } return normalizeArray(expressList).reduce((result, expressItem) => { const currentExpressItem = expressItem && typeof expressItem === 'object' ? expressItem : {}; const platformExpressCode = normalizeText(currentExpressItem[normalizedPlatformCode]).trim(); if (!platformExpressCode) { return result; } result[platformExpressCode] = { name: normalizeText(currentExpressItem.name), sys_express_code: normalizeText(currentExpressItem.code), }; return result; }, {}); } /** * 解析并写入快递映射键,兼容原值与大写键。 * * @param {Object} targetMap 目标映射表 * @param {string} rawKey 原始映射键 * @param {Object} mappingItem 映射值 */ function appendExpressMappingKey(targetMap, rawKey, mappingItem) { const mappingKey = normalizeText(rawKey).trim(); if (!mappingKey) { return; } targetMap[mappingKey] = mappingItem; const upperKey = mappingKey.toUpperCase(); if (!Object.prototype.hasOwnProperty.call(targetMap, upperKey)) { targetMap[upperKey] = mappingItem; } } /** * 构建抖音电子面单快递映射表。 * * @param {Array} expressList 系统快递列表 * @param {string} [platformCode='DY'] 平台编码,默认为 'DY' * @return {Object} 支持 DY 平台编码与系统快递编码双键的映射表 */ function buildExpressNameMap(expressList, platformCode = 'DY') { return normalizeArray(expressList).reduce((result, expressItem) => { const currentExpressItem = expressItem && typeof expressItem === 'object' ? expressItem : {}; const mappingItem = { name: normalizeText(currentExpressItem.name), sys_express_code: normalizeText(currentExpressItem.code), }; appendExpressMappingKey(result, currentExpressItem[platformCode], mappingItem); appendExpressMappingKey(result, currentExpressItem.code, mappingItem); return result; }, {}); } /** * 按候选键顺序匹配首个可用快递映射。 * * @param {Object} expressNameMap 快递映射表 * @param {Array<*>} candidateKeys 候选映射键 * @return {Object} 命中的快递映射,未命中时返回空对象 */ function resolveExpressMapping(expressNameMap, candidateKeys = []) { const mapObject = expressNameMap && typeof expressNameMap === 'object' ? expressNameMap : {}; for (const candidateKey of normalizeArray(candidateKeys)) { const normalizedKey = normalizeText(candidateKey).trim(); if (!normalizedKey) { continue; } if (mapObject[normalizedKey] && typeof mapObject[normalizedKey] === 'object') { return mapObject[normalizedKey]; } const upperKey = normalizedKey.toUpperCase(); if (mapObject[upperKey] && typeof mapObject[upperKey] === 'object') { return mapObject[upperKey]; } } return {}; } /** * 解析拼多多电子面单网点查询响应,收敛为前端易消费的结构。 * * @param {*} responseData 拼多多原始响应 * @param {Object} [expressNameMap={}] 平台快递编码到系统快递信息的映射 * @return {Object} 解析后的电子面单网点结构 */ function formatPddWaybillSearchResponse(responseData, expressNameMap = {}) { const waybillResponse = responseData && typeof responseData === 'object' ? responseData.pdd_waybill_search_response || {} : {}; const subscriptions = normalizeArray(waybillResponse.waybill_apply_subscription_cols); const list = subscriptions.map(subscription => { const subscriptionItem = subscription && typeof subscription === 'object' ? subscription : {}; const accountSources = normalizeFirstWrappedArray([ subscriptionItem.branch_account_cols, subscriptionItem.branchAccounts, subscriptionItem.branch_accounts, subscriptionItem.accounts, subscriptionItem.waybill_branch_account, ], [ 'waybill_branch_account', 'branch_account', 'account', 'list' ]); const firstAccountSource = accountSources[0] && typeof accountSources[0] === 'object' ? accountSources[0] : {}; const providerid = normalizeText( subscriptionItem.providerid || subscriptionItem.providerId || subscriptionItem.ProviderID || firstAccountSource.providerid || firstAccountSource.providerId || firstAccountSource.ProviderID ); const accounts = accountSources.map(account => { const accountItem = account && typeof account === 'object' ? account : {}; const preferredCustomerCode = normalizeText( accountItem.logisticsaccount || subscriptionItem.logisticsaccount || accountItem.shipperno || subscriptionItem.shipperno ); const customerCodes = normalizeWrappedArray( accountItem.customer_code_list || accountItem.customerCodeList || accountItem.customer_codes || accountItem.customerCodes, [ 'string', 'list', 'code' ] ) .map(item => normalizeText(item)) .filter(Boolean); if (!customerCodes.length && preferredCustomerCode) { customerCodes.push(preferredCustomerCode); } const shipAddresses = normalizeFirstWrappedArray([ accountItem.shipp_address_cols, accountItem.ship_addresses, accountItem.shipAddresses, accountItem.address_dto, accountItem.addresses, accountItem.address, subscriptionItem.address, ], [ 'address_dto', 'waybill_address', 'list' ]).map(address => { const rawAddressItem = address && typeof address === 'object' ? address : {}; const addressItem = rawAddressItem.address && typeof rawAddressItem.address === 'object' ? rawAddressItem.address : rawAddressItem; const province = normalizeText(addressItem.province); const city = normalizeText(addressItem.city); const district = normalizeText(addressItem.district || addressItem.area); const town = normalizeText(addressItem.town); const detail = normalizeText(addressItem.detail || addressItem.address_detail || addressItem.address); const fullAddress = normalizeText(addressItem.full_address || addressItem.fullAddress); return { country: normalizeText(addressItem.country), province, city, district, town, detail, full_address: fullAddress || `${province}${city}${district}${town}${detail}`, }; }); const services = normalizeFirstWrappedArray([ accountItem.service_info_cols, accountItem.service_info_dto, accountItem.services, accountItem.serviceInfos, ], [ 'service_info_dto', 'waybill_service_info', 'service', 'list' ]).map(service => { const serviceItem = service && typeof service === 'object' ? service : {}; const attributes = normalizeFirstWrappedArray([ serviceItem.service_attributes, serviceItem.service_attribute_dto, serviceItem.attributes, ], [ 'service_attribute_dto', 'waybill_service_attribute', 'attribute', 'list' ]).map(attribute => { const attributeItem = attribute && typeof attribute === 'object' ? attribute : {}; return { attribute_code: normalizeText(attributeItem.attribute_code || attributeItem.attributeCode), attribute_name: normalizeText(attributeItem.attribute_name || attributeItem.attributeName), attribute_type: normalizeText(attributeItem.attribute_type || attributeItem.attributeType), type_desc: normalizeText(attributeItem.type_desc || attributeItem.attribute_type_name || attributeItem.typeDesc), }; }); return { service_code: normalizeText(serviceItem.service_code || serviceItem.serviceCode), service_name: normalizeText(serviceItem.service_name || serviceItem.serviceName), service_desc: normalizeText(serviceItem.service_desc || serviceItem.description || serviceItem.serviceDesc), required: Boolean(serviceItem.required), attributes, }; }); const result = { branch_code: normalizeText(accountItem.branch_code), branch_name: normalizeText(accountItem.branch_name), quantity: accountItem.quantity === null || accountItem.quantity === undefined ? 0 : accountItem.quantity, cancel_quantity: accountItem.cancel_quantity ?? 0, recycled_quantity: accountItem.recycled_quantity ?? 0, allocated_quantity: accountItem.allocated_quantity ?? 0, customer_code_list: customerCodes, ship_addresses: shipAddresses, services, }; const platformShopId = normalizeText( accountItem.shopid || accountItem.shop_id || subscriptionItem.shopid || subscriptionItem.shop_id || accountItem.providerid || subscriptionItem.providerid ); if (platformShopId) { result.platform_shop_id = platformShopId; } return result; }); const wpCode = normalizeText(subscriptionItem.wp_code); const expressMapping = expressNameMap[wpCode] && typeof expressNameMap[wpCode] === 'object' ? expressNameMap[wpCode] : {}; return { wp_code: wpCode, wp_name: normalizeText(expressMapping.name) || '', sys_express_code: normalizeText(expressMapping.sys_express_code) || '', wp_type: normalizeText(subscriptionItem.wp_type), providerid, accounts, }; }); return { request_id: normalizeText(waybillResponse.request_id), total: subscriptions.length, list, }; } /** * 解析抖音(PolyAPI)电子面单网点查询响应,收敛为与拼多多一致的统一结构。 * * @param {*} responseData 抖音原始响应 * @param {Object} [expressNameMap={}] 平台快递编码到系统快递信息的映射 * @return {Object} 解析后的电子面单网点结构 */ function formatDyWaybillSearchResponse(responseData, expressNameMap = {}) { const normalizedResponse = responseData && typeof responseData === 'object' ? responseData : {}; const waybillResponse = [ normalizedResponse.data, normalizedResponse.result, normalizedResponse.results, normalizedResponse, ].find(item => item && typeof item === 'object') || {}; const subscriptions = normalizeFirstWrappedArray([ waybillResponse.waybill_apply_subscription_cols, waybillResponse.waybillApplySubscriptionCols, waybillResponse.waybill_apply_subscription_info, waybillResponse.waybillApplySubscriptionInfo, waybillResponse.results, waybillResponse.result, waybillResponse.list, waybillResponse.waybill_condition_list, waybillResponse.waybillConditionList, normalizedResponse.results, normalizedResponse.result, ], [ 'waybill_apply_subscription_info', 'list', 'waybill_condition', 'waybillCondition' ]); const groupedByWpCode = new Map(); for (const subscription of subscriptions) { const subscriptionItem = subscription && typeof subscription === 'object' ? subscription : {}; const sysExpressCode = normalizeText( subscriptionItem.sys_express_code || subscriptionItem.sysExpressCode || subscriptionItem.express_sys_code || subscriptionItem.expressSysCode ); const wpCode = normalizeText( subscriptionItem.wp_code || subscriptionItem.providercode || subscriptionItem.cp_code || subscriptionItem.cpcode || subscriptionItem.logistics_code || subscriptionItem.express_code ); const expressMapping = resolveExpressMapping(expressNameMap, [ subscriptionItem.providercode, subscriptionItem.cp_code, subscriptionItem.cpcode, subscriptionItem.wp_code, subscriptionItem.logistics_code, subscriptionItem.express_code, sysExpressCode, wpCode, ]); const accountSources = normalizeFirstWrappedArray([ subscriptionItem.branch_account_cols, subscriptionItem.branchAccounts, subscriptionItem.branch_accounts, subscriptionItem.accounts, subscriptionItem.waybill_branch_account, subscriptionItem.results, subscriptionItem.result, subscriptionItem.list, ], [ 'waybill_branch_account', 'branch_account', 'account', 'results', 'result', 'list' ]); const firstAccountSource = accountSources[0] && typeof accountSources[0] === 'object' ? accountSources[0] : {}; const providerid = normalizeText( subscriptionItem.providerid || subscriptionItem.providerId || subscriptionItem.ProviderID || firstAccountSource.providerid || firstAccountSource.providerId || firstAccountSource.ProviderID ); const accounts = (accountSources.length ? accountSources : [ subscriptionItem ]).map(account => { const accountItem = account && typeof account === 'object' ? account : {}; const preferredCustomerCode = normalizeText( accountItem.logisticsaccount || subscriptionItem.logisticsaccount || accountItem.shipperno || subscriptionItem.shipperno ); const customerCodes = normalizeWrappedArray( accountItem.customer_code_list || accountItem.customerCodeList || accountItem.customer_codes || accountItem.customerCodes, [ 'string', 'list', 'code' ] ).map(item => normalizeText(item)).filter(Boolean); if (!customerCodes.length && preferredCustomerCode) { customerCodes.push(preferredCustomerCode); } const shipAddresses = normalizeFirstWrappedArray([ accountItem.shipp_address_cols, accountItem.ship_addresses, accountItem.shipAddresses, accountItem.address_dto, accountItem.addresses, accountItem.address, subscriptionItem.address, accountItem.shippers, ], [ 'address_dto', 'waybill_address' ]).map(address => { const rawAddressItem = address && typeof address === 'object' ? address : {}; const addressItem = rawAddressItem.address && typeof rawAddressItem.address === 'object' ? rawAddressItem.address : rawAddressItem; const province = normalizeText(addressItem.province); const city = normalizeText(addressItem.city); const district = normalizeText(addressItem.district || addressItem.area); const town = normalizeText(addressItem.town); const detail = normalizeText(addressItem.detail || addressItem.address_detail || addressItem.address); const fullAddress = normalizeText(addressItem.full_address || addressItem.fullAddress); return { country: normalizeText(addressItem.country), province, city, district, town, detail, full_address: fullAddress || `${province}${city}${district}${town}${detail}`, }; }); const services = normalizeFirstWrappedArray([ accountItem.service_info_cols, accountItem.service_info_dto, accountItem.services, accountItem.serviceInfos, ], [ 'service_info_dto', 'waybill_service_info', 'service' ]).map(service => { const serviceItem = service && typeof service === 'object' ? service : {}; const attributes = normalizeFirstWrappedArray([ serviceItem.service_attributes, serviceItem.service_attribute_dto, serviceItem.attributes, ], [ 'service_attribute_dto', 'waybill_service_attribute', 'attribute' ]).map(attribute => { const attributeItem = attribute && typeof attribute === 'object' ? attribute : {}; return { attribute_code: normalizeText(attributeItem.attribute_code), attribute_name: normalizeText(attributeItem.attribute_name), attribute_type: normalizeText(attributeItem.attribute_type), type_desc: normalizeText(attributeItem.type_desc || attributeItem.attribute_type_name), }; }); return { service_code: normalizeText(serviceItem.service_code), service_name: normalizeText(serviceItem.service_name), service_desc: normalizeText(serviceItem.service_desc || serviceItem.description), required: Boolean(serviceItem.required), attributes, }; }); const result = { branch_code: normalizeText(accountItem.branch_code || accountItem.branchCode || accountItem.sitecode), branch_name: normalizeText(accountItem.branch_name || accountItem.branchName || accountItem.sitename), quantity: accountItem.quantity === null || accountItem.quantity === undefined ? 0 : accountItem.quantity, cancel_quantity: accountItem.cancel_quantity ?? 0, recycled_quantity: accountItem.recycled_quantity ?? 0, allocated_quantity: accountItem.allocated_quantity ?? 0, customer_code_list: customerCodes, ship_addresses: shipAddresses, services, }; const platformShopId = normalizeText( accountItem.shopid || subscriptionItem.shopid || accountItem.providerid || subscriptionItem.providerid ); if (platformShopId) { result.platform_shop_id = platformShopId; } return result; }); if (!groupedByWpCode.has(wpCode)) { groupedByWpCode.set(wpCode, { wp_code: wpCode, wp_name: normalizeText(expressMapping.name) || normalizeText( subscriptionItem.wp_name || subscriptionItem.providername || subscriptionItem.cp_name || subscriptionItem.cpname ), sys_express_code: normalizeText(expressMapping.sys_express_code || sysExpressCode), wp_type: normalizeText( subscriptionItem.wp_type || subscriptionItem.providertype || subscriptionItem.waybill_type || subscriptionItem.type ), providerid, accounts: [], shipAddressKeys: new Set(), }); } const groupedItem = groupedByWpCode.get(wpCode); if (!groupedItem.wp_name) { groupedItem.wp_name = normalizeText(expressMapping.name) || normalizeText( subscriptionItem.wp_name || subscriptionItem.providername || subscriptionItem.cp_name || subscriptionItem.cpname ); } if (!groupedItem.sys_express_code) { groupedItem.sys_express_code = normalizeText(expressMapping.sys_express_code || sysExpressCode); } if (!groupedItem.wp_type) { groupedItem.wp_type = normalizeText( subscriptionItem.wp_type || subscriptionItem.providertype || subscriptionItem.waybill_type || subscriptionItem.type ); } if (!groupedItem.providerid && providerid) { groupedItem.providerid = providerid; } const dedupedAccounts = accounts.map(accountItem => { const accountAddressKeys = new Set(); const dedupedShipAddresses = normalizeArray(accountItem.ship_addresses).filter(addressItem => { const addressKey = [ normalizeText(addressItem && addressItem.country), normalizeText(addressItem && addressItem.province), normalizeText(addressItem && addressItem.city), normalizeText(addressItem && addressItem.district), normalizeText(addressItem && addressItem.detail), normalizeText(addressItem && addressItem.full_address), ].join('|'); if (accountAddressKeys.has(addressKey) || groupedItem.shipAddressKeys.has(addressKey)) { return false; } accountAddressKeys.add(addressKey); groupedItem.shipAddressKeys.add(addressKey); return true; }); return { ...accountItem, ship_addresses: dedupedShipAddresses, }; }); groupedItem.accounts.push(...dedupedAccounts); } const list = Array.from(groupedByWpCode.values()).map(item => ({ wp_code: item.wp_code, wp_name: item.wp_name, sys_express_code: item.sys_express_code, wp_type: item.wp_type, providerid: item.providerid, accounts: item.accounts, })); const totalValue = Number(waybillResponse.total); return { request_id: normalizeText(waybillResponse.request_id || normalizedResponse.request_id), total: Number.isFinite(totalValue) ? totalValue : list.length, list, }; } /** * 判断是否命中拼多多顺丰定时派送服务。 * * @param {Array} list 拼多多网点解析列表 * @return {boolean} 是否命中同步条件 */ function hasPddSfTimedDeliveryService(list = []) { const normalizedList = Array.isArray(list) ? list : []; return normalizedList.some(expressItem => { const expressCode = String(expressItem && expressItem.sys_express_code || '').trim().toUpperCase(); if (expressCode !== 'SF' && expressCode !== 'SHUNFENG') { return false; } const accounts = Array.isArray(expressItem && expressItem.accounts) ? expressItem.accounts : []; return accounts.some(account => { const services = Array.isArray(account && account.services) ? account.services : []; return services.some(serviceItem => String(serviceItem && serviceItem.service_code || '').trim().toUpperCase() === 'TIMED-DELIVERY'); }); }); } /** * 归一化淘宝菜鸟服务属性的类型描述。 * * @param {*} typeDesc 原始类型描述 * @return {string} 归一化后的类型描述字符串 */ function normalizeTbAttributeTypeDesc(typeDesc) { const normalizedTypeDesc = normalizeText(typeDesc); if (!normalizedTypeDesc) { return normalizedTypeDesc; } try { const parsedTypeDesc = JSON.parse(normalizedTypeDesc); if (parsedTypeDesc && typeof parsedTypeDesc === 'object' && Object.prototype.hasOwnProperty.call(parsedTypeDesc, 'desc')) { const descText = JSON.stringify(parsedTypeDesc.desc); if (typeof descText === 'string') { return descText; } } } catch (error) { // 非 JSON 字符串保持原样,兼容原有返回结构。 } return normalizedTypeDesc; } /** * 提取淘宝菜鸟电子面单响应中的签约订阅列表。 * * @param {*} responseData 淘宝原始响应 * @return {Array} 标准化后的签约订阅列表 */ function extractTbWaybillSubscriptions(responseData) { const waybillResponse = responseData && typeof responseData === 'object' ? responseData.cainiao_waybill_ii_search_response || {} : {}; const waybillModules = waybillResponse.modules && typeof waybillResponse.modules === 'object' ? waybillResponse.modules : {}; return normalizeFirstWrappedArray( [ waybillModules.waybill_apply_subscription_cols, waybillResponse.waybill_apply_subscription_cols ], [ 'waybill_apply_subscription_info' ] ); } /** * 解析淘宝菜鸟电子面单网点查询响应,收敛为前端易消费的统一结构。 * * @param {*} responseData 淘宝原始响应 * @param {Object} [expressNameMap={}] 平台快递编码到系统快递信息的映射 * @return {Object} 解析后的电子面单网点结构 */ function formatTbWaybillSearchResponse(responseData, expressNameMap = {}) { const waybillResponse = responseData && typeof responseData === 'object' ? responseData.cainiao_waybill_ii_search_response || {} : {}; const subscriptions = extractTbWaybillSubscriptions(responseData); const list = subscriptions.map(subscription => { const subscriptionItem = subscription && typeof subscription === 'object' ? subscription : {}; const wpCode = normalizeText(subscriptionItem.cp_code || subscriptionItem.wp_code); const expressMapping = expressNameMap[wpCode] && typeof expressNameMap[wpCode] === 'object' ? expressNameMap[wpCode] : {}; const accounts = normalizeFirstWrappedArray( [ subscriptionItem.branch_account_cols, subscriptionItem.waybill_branch_account ], [ 'waybill_branch_account' ] ).map(account => { const accountItem = account && typeof account === 'object' ? account : {}; const customerCodes = normalizeWrappedArray(accountItem.customer_code_list, [ 'string' ]) .map(item => normalizeText(item)) .filter(Boolean); const shipAddresses = normalizeFirstWrappedArray( [ accountItem.shipp_address_cols, accountItem.address_dto ], [ 'address_dto', 'waybill_address', 'address' ] ).map(address => { const addressItem = address && typeof address === 'object' ? address : {}; return { country: normalizeText(addressItem.country) || '中国', province: normalizeText(addressItem.province), city: normalizeText(addressItem.city), district: normalizeText(addressItem.district || addressItem.area), detail: normalizeText(addressItem.detail || addressItem.address_detail || addressItem.address), full_address: normalizeText(addressItem.full_address), }; }); const services = normalizeFirstWrappedArray( [ accountItem.service_info_cols, accountItem.service_info_dto ], [ 'service_info_dto', 'waybill_service_info' ] ).map(service => { const serviceItem = service && typeof service === 'object' ? service : {}; const attributes = normalizeFirstWrappedArray( [ serviceItem.service_attributes, serviceItem.service_attribute_dto ], [ 'service_attribute_dto', 'waybill_service_attribute' ] ).map(attribute => { const attributeItem = attribute && typeof attribute === 'object' ? attribute : {}; return { attribute_code: normalizeText(attributeItem.attribute_code), attribute_name: normalizeText(attributeItem.attribute_name), attribute_type: normalizeText(attributeItem.attribute_type), type_desc: normalizeTbAttributeTypeDesc(attributeItem.type_desc || attributeItem.attribute_type_name), }; }); return { service_code: normalizeText(serviceItem.service_code), service_name: normalizeText(serviceItem.service_name), service_desc: normalizeText(serviceItem.service_desc || serviceItem.description), required: Boolean(serviceItem.required), attributes, }; }).filter(serviceItem => !shouldFilterTbService(serviceItem) && serviceItem.attributes.length > 0); return { branch_code: normalizeText(accountItem.branch_code) || normalizeText(customerCodes[0]), branch_name: normalizeText(accountItem.branch_name), quantity: accountItem.quantity === null || accountItem.quantity === undefined ? 0 : accountItem.quantity, cancel_quantity: accountItem.cancel_quantity ?? 0, recycled_quantity: accountItem.recycled_quantity ?? 0, allocated_quantity: accountItem.allocated_quantity ?? 0, customer_code_list: customerCodes, ship_addresses: shipAddresses, services, }; }); return { wp_code: wpCode, wp_name: normalizeText(expressMapping.name) || normalizeText(subscriptionItem.cp_name), sys_express_code: normalizeText(expressMapping.sys_express_code), wp_type: normalizeText(subscriptionItem.wp_type || subscriptionItem.waybill_type), accounts, }; }); const totalValue = Number(waybillResponse.total); return { request_id: normalizeText(waybillResponse.request_id), total: Number.isFinite(totalValue) ? totalValue : subscriptions.length, list, }; } class indexService extends MainService { /** * 初始化基础方法的免登录、免权限、免鉴权和免日志配置。 * * @param {Egg.Context} ctx 上下文对象 */ constructor(ctx) { super(ctx); const _noNeedLogin = 'getI18nMessage,putI18nCollect,test,getCainiaoStfTemplates,polyapiAuthorizeUrl,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken'; const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken'; const _noNeedLog = '*'; const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } async fastWhereTree(data) { const { service } = this; const { type } = data; const result = await service.systems.fastWhere.getTreeByType(type); return this.success('ok', { presetTree: result, code: 200 }); } async loadStores() { const { service } = this; const result = await service.systems.store.loadStores(); return this.success('ok', { stores: result, code: 200 }); } async loadWarehouses() { const { service } = this; const result = await service.systems.store.loadWarehouses(); return this.success('ok', { warehouses: result, code: 200 }); } async loadExpressInterfaces(data = {}) { const { service } = this; const { systemExpressCode } = data; const result = await service.systems.setting.expressInterface.loadExpressInterfaces({ systemExpressCode }); return this.success('ok', { expressInterfaces: result, code: 200 }); } async getCOSUploadConfig(datas) { const { service } = this; const { data } = datas; const result = await service.systems.upload.getUploadParams(data); return this.success('ok', { data: result, code: 200 }); } async getImages(data) { const { service } = this; const result = await service.systems.file.getImages(data); return this.success('ok', { data: result, code: 200 }); } async uploadSuccessNotify(data) { const { service } = this; const result = await service.systems.upload.uploadSuccessNotify(data); return this.success('ok', { data: result, code: 200 }); } /** * 识别车牌号码。 * * @param {Object} data 请求参数 * @param {string} data.base64 base64 图片 * @param {string} [data.imageBase64] 兼容的 base64 字段 * @param {string} [data.image_base64] 兼容的 base64 字段 * @return {Promise} 识别结果 */ async recognizeLicensePlate(data) { const { service, ctx } = this; const { base64 = '', imageBase64 = '', image_base64 = '' } = data || {}; const imageBase64Value = String(base64 || imageBase64 || image_base64 || '').trim(); if (!imageBase64Value) { return this.fail('base64 图片不能为空', { code: 400 }); } try { const result = await service.systems.licensePlate.recognizeLicensePlate(imageBase64Value); return this.success('ok', { data: result, code: 200 }); } catch (error) { ctx.logger.error('车牌识别失败:', error); return this.fail(error.message || '车牌识别失败', { code: 500 }); } } async ReferenceFile(data) { const { service } = this; const result = await service.systems.file.ReferenceFile(data); return this.success('ok', { data: result, code: 200 }); } async getMessageDetail(data) { const { service } = this; const result = await service.systems.operationLog.getMessageDetail(data); return this.success('ok', { data: result, code: 200 }); } /** * 后台专用的拼多多接口测试入口。 * * @param {Object} data 请求参数 * @param {string} data.type 拼多多接口名,例如 pdd.order.number.list.get * @param {Object} [data.bizParams] 业务参数对象 * @param {Object} [data.request] 业务参数别名,兼容旧调用方式 * @param {string} [data.accessToken] 用户授权令牌 * @param {string} [data.dataType='JSON'] 响应格式 * @param {string} [data.version] API 版本 * @param {string|number} [data.timestamp] 时间戳 * @param {string} [data.clientId] client_id 覆盖值 * @param {string} [data.clientSecret] client_secret 覆盖值 * @param {string} [data.baseUrl] 请求地址 * @param {Object} [data.headers] 额外请求头 * @param {number} [data.timeout] 请求超时 * @return {Promise} 调用结果 */ async test(data = {}) { const { ctx } = this; const input = data && typeof data === 'object' ? data : {}; const { type, access_token: accessTokenSnake, accessToken, data_type: dataTypeSnake, dataType = 'JSON', version, timestamp, client_id: clientIdSnake, clientId, client_secret: clientSecretSnake, clientSecret, base_url: baseUrlSnake, baseUrl = DEFAULT_PDD_ROUTER_URL, headers = {}, timeout, bizParams, biz_params: bizParamsSnake, request, ...rest } = input; if (!String(type || '').trim()) { return this.fail('type 不能为空', { code: 400 }); } const requestParams = {}; if (rest && typeof rest === 'object' && !Array.isArray(rest)) { Object.assign(requestParams, rest); } if (bizParams && typeof bizParams === 'object' && !Array.isArray(bizParams)) { Object.assign(requestParams, bizParams); } if (request && typeof request === 'object' && !Array.isArray(request)) { Object.assign(requestParams, request); } const normalizedAccessToken = accessToken !== undefined ? accessToken : accessTokenSnake; const normalizedDataType = dataTypeSnake !== undefined ? dataTypeSnake : dataType; const normalizedClientId = clientId !== undefined ? clientId : clientIdSnake; const normalizedClientSecret = clientSecret !== undefined ? clientSecret : clientSecretSnake; const normalizedBaseUrl = baseUrlSnake !== undefined ? baseUrlSnake : baseUrl; if (bizParamsSnake && typeof bizParamsSnake === 'object' && !Array.isArray(bizParamsSnake)) { Object.assign(requestParams, bizParamsSnake); } const pddClient = new PddClient(ctx); const builtRequest = pddClient.buildRequest({ type, accessToken: normalizedAccessToken, dataType: normalizedDataType, version, timestamp, clientId: normalizedClientId, clientSecret: normalizedClientSecret, bizParams: requestParams, }); try { const response = await ctx.curl(String(normalizedBaseUrl || DEFAULT_PDD_ROUTER_URL), { method: 'POST', headers: { 'Content-Type': 'application/json', ...(headers && typeof headers === 'object' ? headers : {}), }, dataType: String(normalizedDataType || 'json').toLowerCase() === 'xml' ? 'text' : 'json', data: builtRequest.requestBody, timeout, }); const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data') ? response.data : response; const parsedResponse = type === 'pdd.waybill.search' ? formatPddWaybillSearchResponse(responseData) : null; return this.success('ok', { data: { requestBody: builtRequest.requestBody, signText: builtRequest.signText, sortedPairs: builtRequest.sortedPairs, response: responseData, parsed_response: parsedResponse, baseUrl: String(normalizedBaseUrl || DEFAULT_PDD_ROUTER_URL), }, code: 200, }); } catch (error) { ctx.logger.error('PDD 测试接口调用失败:', error); return this.fail(error.message || 'PDD 测试接口调用失败', { code: 500, data: { requestBody: builtRequest.requestBody, signText: builtRequest.signText, sortedPairs: builtRequest.sortedPairs, baseUrl: String(normalizedBaseUrl || DEFAULT_PDD_ROUTER_URL), }, }); } } // app/controller/i18n.js 中 async getI18nMessage(data) { const { ctx } = this; const { language = 'zh-CN' } = data || ctx.query; try { // 1. 查询当前项目的所有翻译(默认项目为 'wms') const translations = await ctx.model.I18nTranslation.findAll({ include: [{ model: ctx.model.I18nKey, as: 'key', where: { project: 'wms', }, attributes: [ 'key_name' ], }], where: { language, }, }); // 2. 构建嵌套结构的翻译对象 const result = {}; translations.forEach(item => { if (item.key && item.key.key_name) { const keys = item.key.key_name.split('.'); let current = result; // 构建嵌套路径 for (let i = 0; i < keys.length - 1; i++) { const key = keys[i]; // 如果路径节点已存在但非对象(被其他叶子键占用),先保存旧值再转为对象 if (!current[key] || typeof current[key] !== 'object') { const oldValue = current[key]; current[key] = {}; if (oldValue !== undefined) { current[key]._self = oldValue; } } current = current[key]; } // 设置翻译值 const lastKey = keys[keys.length - 1]; current[lastKey] = item.translation || item.key.key_name; } }); // 3. 获取统计信息 const totalKeys = await ctx.model.I18nKey.count({ where: { project: 'wms' }, }); const translatedCount = await ctx.model.I18nTranslation.count({ include: [{ model: ctx.model.I18nKey, as: 'key', where: { project: 'wms' }, }], where: { language, translation: { [ctx.app.Sequelize.Op.ne]: null }, // 非空 }, }); return this.success('ok', { data: { success: true, messages: result, stats: { language, total: totalKeys, translated: translatedCount, untranslated: totalKeys - translatedCount, progress: totalKeys > 0 ? Math.round((translatedCount / totalKeys) * 100) : 0, timestamp: new Date().toISOString(), }, }, code: 200, }); } catch (error) { ctx.logger.error('获取翻译失败:', error); // 失败时返回空结果 return this.success('ok', { data: { success: true, messages: {}, stats: { language, total: 0, translated: 0, untranslated: 0, progress: 0, timestamp: new Date().toISOString(), }, }, code: 200, }); } } async putI18nCollect(data) { const { ctx } = this; const { keys = [], locale = 'zh-CN', project = 'wms', source = 'frontend-auto' } = data || ctx.request.body; try { const result = { processed: 0, createdKeys: 0, createdTranslations: 0, updatedKeys: 0, details: [], }; for (const keyData of keys) { const { key, value, context, timestamp } = keyData; try { // 1. 查找或创建键值记录 let keyRecord = await ctx.model.I18nKey.findOne({ where: { key_name: key, project }, }); let keyAction = 'exists'; if (!keyRecord) { // 创建新键值 keyRecord = await ctx.model.I18nKey.create({ key_name: key, project, module: this.extractModule(key), description: context ? JSON.stringify(context) : null, status: 1, created_by: source, }); keyAction = 'created'; result.createdKeys++; } else { // 更新使用次数(可以添加一个 usage_count 字段) keyRecord.updated_at = new Date(); await keyRecord.save(); keyAction = 'updated'; result.updatedKeys++; } // 2. 创建或更新翻译记录 let translation = await ctx.model.I18nTranslation.findOne({ where: { key_id: keyRecord.id, language: locale }, }); if (!translation) { // 创建翻译记录(默认未翻译) translation = await ctx.model.I18nTranslation.create({ key_id: keyRecord.id, language: locale, translation: value || null, // 如果有值就保存,否则null translation_status: value ? 1 : 0, // 有值设为待审核,没有就是未翻译 auto_generated: source.includes('auto') ? 1 : 0, translator: source, created_at: new Date(timestamp || Date.now()), }); result.createdTranslations++; } else if (value && !translation.translation) { // 如果已有记录但没有翻译,现在有值了就更新 translation.translation = value; translation.translation_status = 1; // 设为待审核 translation.updated_at = new Date(); await translation.save(); } result.details.push({ key, keyId: keyRecord.id, keyAction, translationExists: !!translation, translationValue: translation?.translation || null, }); } catch (error) { ctx.logger.error(`处理键值 ${key} 失败:`, error); result.details.push({ key, error: error.message, success: false, }); } } result.processed = keys.length; // 3. 尝试自动翻译(可选) if (result.createdTranslations > 0) { await this.tryAutoTranslateNewKeys(project, locale); } return this.success('ok', { data: { success: true, processed: result.processed, stats: { totalKeys: await ctx.model.I18nKey.count({ where: { project } }), totalTranslations: await ctx.model.I18nTranslation.count({ include: [{ model: ctx.model.I18nKey, as: 'key', where: { project }, }], where: { language: locale }, }), newKeys: result.createdKeys, newTranslations: result.createdTranslations, }, details: result.details, }, code: 200, }); } catch (error) { ctx.logger.error('批量处理键值失败:', error); return this.success('ok', { data: { success: false, error: error.message, processed: 0, }, code: 500, }); } } /** * 从键名提取模块 * @param {string} keyName 键名 */ extractModule(keyName) { if (!keyName) return 'common'; const parts = keyName.split('.'); if (parts.length > 1) { const possibleModules = [ 'warehouse', 'inventory', 'order', 'shipment', 'user', 'system', 'common' ]; if (possibleModules.includes(parts[0])) { return parts[0]; } } return 'common'; } /** * 尝试自动翻译新键值(可选功能) * @param {string} project 项目 * @param {string} targetLanguage 目标语言 */ async tryAutoTranslateNewKeys(project, targetLanguage) { const { ctx } = this; // 只有目标语言不是中文时才需要翻译 if (targetLanguage === 'zh-CN') return; try { // 查找需要翻译的记录(中文有翻译,但目标语言没有) const needTranslate = await ctx.model.I18nTranslation.findAll({ include: [{ model: ctx.model.I18nKey, as: 'key', where: { project }, }], where: { language: 'zh-CN', translation: { [ctx.app.Sequelize.Op.ne]: null }, }, }); const chineseTranslations = {}; needTranslate.forEach(item => { if (item.key) { chineseTranslations[item.key.id] = item.translation; } }); // 检查目标语言是否已有翻译 const existingTranslations = await ctx.model.I18nTranslation.findAll({ where: { key_id: Object.keys(chineseTranslations).map(id => parseInt(id)), language: targetLanguage, translation: { [ctx.app.Sequelize.Op.ne]: null }, }, }); const existingKeyIds = new Set(existingTranslations.map(t => t.key_id)); // 批量创建未翻译的记录 const createPromises = []; for (const [ keyId ] of Object.entries(chineseTranslations)) { if (!existingKeyIds.has(parseInt(keyId))) { createPromises.push( ctx.model.I18nTranslation.create({ key_id: parseInt(keyId), language: targetLanguage, translation: null, // 这里可以调用翻译API自动填充 translation_status: 0, auto_generated: 1, translator: 'auto-translate', }) ); } } if (createPromises.length > 0) { await Promise.all(createPromises); ctx.logger.info(`为 ${createPromises.length} 个键值创建了 ${targetLanguage} 的翻译占位`); } } catch (error) { ctx.logger.error('自动翻译处理失败:', error); } } async searchSpace(data) { const { service } = this; const result = await service.systems.space.searchSpace(data); return this.success('ok', result); } async searchSpaces(data) { const { service } = this; const result = await service.systems.space.searchSpaces(data); return this.success('ok', result); } async listInterfaceTypes() { const { ctx } = this; const rows = await ctx.model.InterfaceType.findAll({ where: { is_enabled: 1, is_store: 1 }, attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'description', 'is_enabled' ], order: [[ 'id', 'ASC' ]], }); const list = rows.map(row => { const item = row.get({ plain: true }); return { id: Number(item.id || 0), interface_code: item.interface_code || '', interface_name: item.interface_name || '', interface_category: item.interface_category || '', description: item.description || '', is_enabled: Number(item.is_enabled || 0), }; }); return this.success('ok', { list, total: list.length, code: 200 }); } async getLocationTypeList() { const { ctx } = this; const { Op } = this.app.Sequelize; const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : null; const cacheKey = `index:locationTypeList:${warehouseId || 'global'}`; const cached = await this.app.getCacheAsync(cacheKey); if (Array.isArray(cached)) { return this.success('ok', { list: cached, total: cached.length, code: 200 }); } const where = { is_active: true, }; if (warehouseId) { where[Op.or] = [ { warehouse_id: warehouseId }, { warehouse_id: null }, ]; } else { where.warehouse_id = null; } const rows = await ctx.model.LocationType.findAll({ where, attributes: [ 'id', 'type_code', 'type_name', 'temperature_zone', 'allow_allocation', 'allow_transfer_out', 'description', 'warehouse_id', ], order: [[ 'warehouse_id', 'ASC' ], [ 'id', 'ASC' ]], raw: true, }); const list = rows.map(item => ({ id: Number(item.id || 0), type_code: item.type_code || '', type_name: item.type_name || '', temperature_zone: item.temperature_zone || '', allow_allocation: Boolean(item.allow_allocation), allow_transfer_out: Boolean(item.allow_transfer_out), description: item.description || '', warehouse_id: item.warehouse_id === null || item.warehouse_id === undefined ? null : Number(item.warehouse_id), })); await this.app.setCacheAsync(cacheKey, list, 300); return this.success('ok', { list, total: list.length, code: 200 }); } /** * 获取奇门应用列表。 * * @return {Promise} 返回奇门应用列表结果 */ async getQimenAppList() { const { ctx } = this; const cacheKey = 'index:qimenAppList'; const cached = await this.app.getCacheAsync(cacheKey); if (Array.isArray(cached)) { return this.success('ok', { list: cached, total: cached.length, code: 200 }); } const rows = await ctx.model.QimenApp.findAll({ attributes: [ 'id', 'name', 'app_key' ], order: [[ 'id', 'ASC' ]], }); const list = rows.map(row => { const item = typeof row.get === 'function' ? row.get({ plain: true }) : row; return { id: Number(item.id || 0), name: item.name || '', app_key: item.app_key || '', }; }); await this.app.setCacheAsync(cacheKey, list, 300); return this.success('ok', { list, total: list.length, code: 200 }); } /** * 获取快递列表。 * * @param {Object} data 请求参数 * @param {boolean} [data.systemOnly] 是否仅返回系统基础快递列表 * @param {string} [data.express_code] 快递公司编码 * @return {Promise} 返回结果 */ async getExpressList(data) { const { service } = this; const { systemOnly, express_code: expressCode = '', } = data || {}; const isSystemOnly = [ true, 1, '1', 'true' ].includes(systemOnly); const normalizedExpressCode = String(expressCode || '').trim(); const result = await service.systems.express.getExpressList(isSystemOnly, normalizedExpressCode); return this.success('ok', { data: result, code: 200 }); } /** * 获取快递产品类型列表。 * * @param {Object} data 请求参数 * @param {string} [data.express_code] 快递公司编码 * @return {Promise} 返回结果 */ async getExpressProductTypeList(data) { const { service } = this; const { express_code: expressCode = '' } = data || {}; const result = await service.systems.express.getExpressProductTypeList(expressCode); return this.success('ok', { data: result, code: 200 }); } /** * 获取平台列表。 * * @param {Object} data 请求参数 * @param {number|string|boolean} [data.is_system=0] 是否仅返回系统基础平台列表,1 表示仅返回系统平台 * @param {boolean} [data.systemOnly] 是否仅返回系统基础平台列表 * @param {boolean} [data.full] 是否返回全量字段 * @return {Promise} 返回结果 */ async getPlatformList(data) { const { service } = this; const payload = data || {}; const { is_system: isSystem = 0, systemOnly, full } = payload; const systemFilter = Object.prototype.hasOwnProperty.call(payload, 'is_system') ? isSystem : systemOnly; const isSystemOnly = [ true, 1, '1', 'true' ].includes(systemFilter); const isFull = [ true, 1, '1', 'true' ].includes(full); const result = await service.systems.platform.getPlatformList(isSystemOnly, isFull); return this.success('ok', { data: result, code: 200 }); } /** * 获取打印平台全量列表。 * * 供前端新增、修改快递接口时下拉选择使用,不返回分页结构。 * * @return {Promise} 返回结果 */ async getPrintPlatformList() { const { service } = this; const result = await service.systems.setting.expressInterface.getPrintPlatformList(); return this.success('ok', { data: result, code: 200 }); } /** * 校验店铺打印平台编码是否存在。 * * 运行环境未注册 `PrintPlatform` 模型时,仅做大写标准化,避免单测桩环境报错; * 已注册模型时,强制以 `wms_print_platform.platform_code` 为准。 * * @param {string} platformCode 打印平台编码 * @param {boolean} [isAll=false] 是否返回平台完整信息 * @return {Promise} 标准化后的打印平台编码 */ async ensureShopPrintPlatformExists(platformCode, isAll = false) { const normalizedPlatformCode = String(platformCode || '').trim().toUpperCase(); const printPlatformModel = this.ctx && this.ctx.model && this.ctx.model.PrintPlatform; if (!normalizedPlatformCode) { throw new Error('平台编码不能为空'); } if (!printPlatformModel || typeof printPlatformModel.findOne !== 'function') { return normalizedPlatformCode; } const printPlatform = await printPlatformModel.findOne({ where: { platform_code: normalizedPlatformCode, deleted: 0, status: 'ACTIVE', }, attributes: [ 'platform_code', 'platid' ], }); if (!printPlatform) { throw new Error('platform_code 未匹配到打印平台编码'); } if (isAll) { return printPlatform; } return normalizedPlatformCode; } /** * 构建店铺关联打印平台的 Sequelize include 配置。 * * @param {boolean} [required=false] 是否强制要求命中打印平台 * @return {Array} include 配置列表 */ buildShopPrintPlatformInclude(required = false) { const printPlatformModel = this.ctx && this.ctx.model && this.ctx.model.PrintPlatform; if (!printPlatformModel) { return []; } return [{ model: printPlatformModel, as: 'printPlatform', required, attributes: [ 'platform_code', 'platform_name', 'status' ], where: { deleted: 0, status: 'ACTIVE', }, }]; } /** * 获取当前仓库下的店铺列表。 * * @param {Object} [data={}] 请求参数 * @param {string} [data.platform_code] 平台编码 * @param {string} [data.platformCode] 平台编码,兼容驼峰字段 * @return {Promise} 返回店铺列表结果 */ async getShopList(data = {}) { const { ctx } = this; const { platform_code: platformCodeSnake = '', platformCode: platformCodeCamel = '' } = data || {}; const warehouseId = Number(ctx.user?.store_id); if (!warehouseId) { return this.fail('未识别到当前仓库', { code: 400 }); } const platformCode = String(platformCodeSnake || platformCodeCamel || '').trim().toUpperCase(); const where = { warehouse_id: warehouseId, status: 1, ...buildNotDeletedShopWhere(this.app), }; if (platformCode) { where.platform_code = await this.ensureShopPrintPlatformExists(platformCode); } const list = await ctx.model.Shop.findAll({ where, include: this.buildShopPrintPlatformInclude(false), order: [[ 'status', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], }); const maskedList = list.map(maskShopListItem); return this.success('ok', { data: { list: maskedList }, code: 200 }); } /** * 实时请求拼多多电子面单网点列表。 * * @param {string} accessToken 店铺授权令牌 * @return {Promise} 拼多多原始响应数据 * @throws {Error} 拼多多返回错误结构或请求失败时抛出异常 */ async requestPddWaybillSearch(accessToken) { const { ctx } = this; const pddClient = new PddClient(ctx); const builtRequest = pddClient.buildRequest({ type: 'pdd.waybill.search', accessToken, dataType: 'JSON', }); const response = await ctx.curl(DEFAULT_PDD_ROUTER_URL, { method: 'POST', headers: { 'Content-Type': 'application/json', }, dataType: 'json', data: builtRequest.requestBody, }); const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data') ? response.data : response; if (responseData && typeof responseData === 'object' && responseData.error_response) { const errorResponse = responseData.error_response; throw new Error(errorResponse.error_msg || '拼多多电子面单查询失败'); } return responseData; } /** * 实时请求拼多多官方标准模板接口。 * * @param {Object} payload 请求参数 * @param {string} payload.accessToken 店铺授权令牌 * @param {string} payload.wpCode 拼多多平台快递编码 * @return {Promise} 拼多多原始响应数据 * @throws {Error} 拼多多返回错误结构或请求失败时抛出异常 */ async requestPddStdTemplates(payload = {}) { const { ctx } = this; const { accessToken = '', wpCode = '', } = payload || {}; const normalizedAccessToken = String(accessToken || '').trim(); const normalizedWpCode = String(wpCode || '').trim(); if (!normalizedAccessToken) { throw new Error('拼多多模板查询 accessToken 不能为空'); } if (!normalizedWpCode) { throw new Error('拼多多模板查询 wp_code 不能为空'); } const pddClient = new PddClient(ctx); const builtRequest = pddClient.buildRequest({ type: 'pdd.cloudprint.stdtemplates.get', accessToken: normalizedAccessToken, request: { wp_code: normalizedWpCode, }, dataType: 'JSON', }); const response = await ctx.curl(DEFAULT_PDD_ROUTER_URL, { method: 'POST', headers: { 'Content-Type': 'application/json', }, dataType: 'json', data: builtRequest.requestBody, }); const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data') ? response.data : response; if (responseData && typeof responseData === 'object' && responseData.error_response) { const errorResponse = responseData.error_response; throw new Error(errorResponse.error_msg || '拼多多标准模板查询失败'); } return responseData; } /** * 实时请求淘宝菜鸟电子面单网点列表。 * * @param {Object} payload 请求载荷 * @param {string} [payload.accessToken] 店铺授权令牌(session),为空时不下发 * @param {string} [payload.cpCode] 快递公司编码 * @return {Promise} 淘宝原始响应数据 * @throws {Error} 淘宝返回错误结构或请求失败时抛出异常 */ async requestTbWaybillSearch(payload = {}) { const { ctx } = this; const { accessToken, cpCode = '', } = payload || {}; const appKey = String(this.app.config?.qimen?.appKey || '').trim(); const appSecret = String(this.app.config?.qimen?.security || '').trim(); if (!appKey || !appSecret) { throw new Error('淘宝接口配置缺失'); } const signService = this.service.systems.sign; if (!signService || typeof signService.signTopRequest !== 'function') { throw new Error('签名服务不可用'); } const requestParams = { method: 'cainiao.waybill.ii.search', app_key: appKey, timestamp: this.app.formatDate(new Date()), format: 'json', v: '2.0', sign_method: 'md5', }; const normalizedAccessToken = String(accessToken || '').trim(); if (normalizedAccessToken) { requestParams.session = normalizedAccessToken; } const normalizedCpCode = String(cpCode || '').trim(); if (normalizedCpCode) { requestParams.cp_code = normalizedCpCode; } const sign = signService.signTopRequest(requestParams, '', appSecret, 'md5'); const response = await ctx.curl(DEFAULT_TB_ROUTER_URL, { method: 'POST', contentType: 'form', dataType: 'json', data: { ...requestParams, sign, }, }); const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data') ? response.data : response; if (responseData && typeof responseData === 'object' && responseData.error_response) { const errorResponse = responseData.error_response; throw new Error(errorResponse.sub_msg || errorResponse.msg || '淘宝菜鸟电子面单查询失败'); } return responseData; } /** * 实时请求淘宝菜鸟公共标准面单模板列表。 * * @return {Promise} 淘宝原始响应数据 * @throws {Error} 淘宝返回错误结构或请求失败时抛出异常 */ async requestTbCainiaoStdTemplates() { const { ctx } = this; const appKey = String(this.app.config?.qimen?.appKey || '').trim(); const appSecret = String(this.app.config?.qimen?.security || '').trim(); if (!appKey || !appSecret) { throw new Error('淘宝接口配置缺失'); } const signService = this.service.systems.sign; if (!signService || typeof signService.signTopRequest !== 'function') { throw new Error('签名服务不可用'); } const requestParams = { method: 'cainiao.cloudprint.stdtemplates.get', app_key: appKey, timestamp: this.app.formatDate(new Date()), format: 'json', v: '2.0', sign_method: 'md5', }; const sign = signService.signTopRequest(requestParams, '', appSecret, 'md5'); const response = await ctx.curl(DEFAULT_TB_ROUTER_URL, { method: 'POST', contentType: 'form', dataType: 'json', data: { ...requestParams, sign, }, }); const responseData = response && Object.prototype.hasOwnProperty.call(response, 'data') ? response.data : response; if (responseData && typeof responseData === 'object' && responseData.error_response) { const errorResponse = responseData.error_response; throw new Error(errorResponse.sub_msg || errorResponse.msg || '淘宝菜鸟标准模板查询失败'); } return responseData.cainiao_cloudprint_stdtemplates_get_response.result.datas.standard_template_result || []; } /** * 请求菠萝派标准模板并归一化为菜鸟链路兼容数组。 * * @param {string} appSecret 菠萝派访问令牌 * @param {string|number} platid 菠萝派平台标识 * @param {boolean} [isJD=false] 是否为京东平台 * @return {Promise>} 归一化后的模板数组 * @throws {Error} 当配置缺失或接口返回失败时抛出异常 */ async requestPolyStdTemplates(appSecret, platid, isJD = false) { console.log('请求菠萝派标准模板接口入参', { appSecret: String(appSecret || '').trim() ? '***' : '', platid }); const { service } = this; if (!appSecret || !platid) { throw new Error('菠萝派接口配置缺失'); } const query_data = { templatestype: 'ALL' }; if (platid === 673) { query_data.BizVersion = '2'; } if (platid === 544) { platid = 611; } let interface_url = 'https://api.polyapi.com/OpenAPI/do'; if (isJD) { interface_url = 'https://apijd.polyapi.com/OpenAPI/do'; } const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetTemplates', query_data, { interface_url, appkey: this.app.config.poloApi.appKey, app_secret: this.app.config.poloApi.appSecret, token: appSecret, platid, version: '1.0', }); console.log('请求菠萝派标准模板接口响应', JSON.stringify(responseData)); const normalizedResponseData = responseData && typeof responseData === 'object' ? { ...responseData, code: [ 0, '0', 10000, '10000' ].includes(responseData.code) ? 0 : responseData.code, results: Array.isArray(responseData.results) && responseData.results.length > 0 ? responseData.results : Array.isArray(responseData.data) ? responseData.data : responseData.results, } : responseData; if (normalizedResponseData && normalizedResponseData.code !== 0) { throw new Error(responseData.message || '菠萝派标准模板查询失败'); } const normalizeTemplateItems = items => (Array.isArray(items) ? items : []).map(item => { const sourceItem = item && typeof item === 'object' ? item : {}; const { results: nestedResults, data: nestedData, standard_templates: nestedStandardTemplates, cp_code: itemCpCode, cpcode: itemCpcode, cpCode: itemCpCodeCamel, ...restItem } = sourceItem; const standardTemplatesSource = Array.isArray(nestedResults) ? nestedResults : Array.isArray(nestedStandardTemplates) ? nestedStandardTemplates : Array.isArray(nestedData) ? nestedData : []; const cpCode = itemCpCode ?? itemCpcode ?? itemCpCodeCamel; return { ...restItem, cp_code: cpCode, standard_templates: { standard_template_do: standardTemplatesSource.map(template => { const sourceTemplate = template && typeof template === 'object' ? template : {}; return { brand_code: sourceTemplate.brand_code || sourceTemplate.brandcode || 'default', standard_template_id: sourceTemplate.standard_template_id || sourceTemplate.id || '', standard_template_name: sourceTemplate.standard_template_name || sourceTemplate.name || '', standard_template_url: sourceTemplate.standard_template_url || sourceTemplate.url || '', standard_waybill_type: sourceTemplate.standard_waybill_type || sourceTemplate.templatetype || '', }; }), }, }; }); const normalizedResults = normalizeTemplateItems(normalizedResponseData?.results); if (normalizedResults.length > 0) { return normalizedResults; } return normalizeTemplateItems(normalizedResponseData?.data); } /** * 获取指定店铺的快递签约列表。 * * @param {Object} data 请求参数 * @param {string|number} [data.shop_id] 店铺 ID * @param {string|number} [data.shopId] 店铺 ID,兼容驼峰字段 * @return {Promise} 返回店铺对应的快递签约列表 */ async getShopExpressList(data = {}) { const { ctx, service } = this; const { shop_id: shopIdSnake, shopId: shopIdCamel, cp_code: cpCodeSnake, cpCode: cpCodeCamel, } = data || {}; const shopId = [ shopIdSnake, shopIdCamel ].find(item => item !== undefined && item !== null && String(item).trim() !== ''); if (shopId === undefined) { return this.fail('shop_id 不能为空', { code: 400 }); } const warehouseId = Number(ctx.user?.store_id); if (!warehouseId) { return this.fail('未识别到当前仓库', { code: 400 }); } const shop = await ctx.model.Shop.findOne({ where: { id: shopId, warehouse_id: warehouseId, ...buildNotDeletedShopWhere(this.app), }, include: this.buildShopPrintPlatformInclude(true), }); if (!shop) { return this.fail('店铺不存在', { code: 404 }); } const shopPlain = typeof shop.get === 'function' ? shop.get({ plain: true }) : shop; const platformCode_info = await this.ensureShopPrintPlatformExists(shopPlain.platform_code, true); let list = []; const platformCode = platformCode_info.platform_code; const platid = platformCode_info.platid; console.log('请求的店铺的platformCode', platformCode); switch (platformCode) { case 'PDD': { const accessToken = String(shopPlain.access_token || '').trim(); if (!accessToken) { return this.fail('店铺未授权', { code: 400 }); } const expressList = await this.service.systems.express.getExpressList(true); const expressNameMap = buildPlatformExpressNameMap(expressList, platformCode); const responseData = await this.requestPddWaybillSearch(accessToken); const parsed = formatPddWaybillSearchResponse(responseData, expressNameMap); if (hasPddSfTimedDeliveryService(parsed.list)) { await this.service.systems.express.syncPddSfTimedDeliveryExpressProductTypes({ shopExpressList: parsed.list, }); } list = parsed.list; break; } case 'CAINIAO': { const accessToken = String(shopPlain.access_token || '').trim(); if (!accessToken) { return this.fail('店铺未授权', { code: 400 }); } const cpCode = String(cpCodeSnake || cpCodeCamel || '').trim(); const expressList = await this.service.systems.express.getExpressList(true); const expressNameMap = buildPlatformExpressNameMap(expressList, 'CAINIAO'); const responseData = await this.requestTbWaybillSearch({ accessToken, cpCode, }); const parsed = formatTbWaybillSearchResponse(responseData, expressNameMap); ctx.logger.info('[SystemMethods.getShopExpressList] cainiao.waybill.ii.search 响应', JSON.stringify({ shop_id: shopPlain.id, cp_code: cpCode, response: responseData, })); ctx.logger.info('[SystemMethods.getShopExpressList] cainiao.waybill.ii.search 解析结果', JSON.stringify({ shop_id: shopPlain.id, cp_code: cpCode, parsed, })); list = parsed.list; break; } case 'DY': { const accessToken = String(shopPlain.access_token || '').trim(); const expressList = await this.service.systems.express.getExpressList(true); const expressNameMap = buildExpressNameMap(expressList, 'DY'); const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetWayBillCondition', { }, { interface_url: 'https://api.polyapi.com/OpenAPI/do', appkey: this.app.config.poloApi.appKey, app_secret: this.app.config.poloApi.appSecret, platid, version: '1.5', token: accessToken, }); console.log('请求的店铺的platformCode', platformCode, '接口响应', JSON.stringify(responseData)); const parsed = formatDyWaybillSearchResponse(responseData, expressNameMap); list = parsed.list; break; } case 'KS':{ const accessToken = String(shopPlain.access_token || '').trim(); const expressList = await this.service.systems.express.getExpressList(true); const expressNameMap = buildExpressNameMap(expressList, 'KS'); const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetWayBillCondition', { }, { interface_url: 'https://api.polyapi.com/OpenAPI/do', appkey: this.app.config.poloApi.appKey, app_secret: this.app.config.poloApi.appSecret, platid, version: '1.5', token: accessToken, }); console.log('请求的店铺的platformCode', platformCode, '接口响应', JSON.stringify(responseData)); const parsed = formatDyWaybillSearchResponse(responseData, expressNameMap); list = parsed.list; break; } case 'SPH':{ const accessToken = String(shopPlain.access_token || '').trim(); const expressList = await this.service.systems.express.getExpressList(true); const expressNameMap = buildExpressNameMap(expressList, 'SPH'); await this.app.setCacheAsync('SPHquery', JSON.stringify({ interface_url: 'https://api.polyapi.com/OpenAPI/do', appkey: this.app.config.poloApi.appKey, app_secret: this.app.config.poloApi.appSecret, platid, version: '1.5', token: accessToken, }), 3600); const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetWayBillCondition', { }, { interface_url: 'https://api.polyapi.com/OpenAPI/do', appkey: this.app.config.poloApi.appKey, app_secret: this.app.config.poloApi.appSecret, platid, version: '1.5', token: accessToken, }); await this.app.setCacheAsync('SPHrequest', JSON.stringify(responseData), 3600); const parsed = formatDyWaybillSearchResponse(responseData, expressNameMap); list = parsed.list; break; } case 'XHS':{ const accessToken = String(shopPlain.access_token || '').trim(); const expressList = await this.service.systems.express.getExpressList(true); const expressNameMap = buildExpressNameMap(expressList, 'XHS'); const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetWayBillCondition', { BizVersion: '2', }, { interface_url: 'https://api.polyapi.com/OpenAPI/do', appkey: this.app.config.poloApi.appKey, app_secret: this.app.config.poloApi.appSecret, platid, version: '1.5', token: accessToken, }); console.log('请求的店铺的platformCode', platformCode, '接口响应', JSON.stringify(responseData)); const parsed = formatDyWaybillSearchResponse(responseData, expressNameMap); list = parsed.list; break; } case 'JD':{ const accessToken = String(shopPlain.access_token || '').trim(); const expressList = await this.service.systems.express.getExpressList(true); const expressNameMap = buildExpressNameMap(expressList, 'JD'); const jdExpressNameMap = { ...expressNameMap }; normalizeArray(expressList).forEach(expressItem => { const currentExpressItem = expressItem && typeof expressItem === 'object' ? expressItem : {}; const mappingItem = { name: normalizeText(currentExpressItem.name), sys_express_code: normalizeText(currentExpressItem.code), }; appendExpressMappingKey(jdExpressNameMap, currentExpressItem.name, mappingItem); }); const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetProvider', { }, { interface_url: 'https://jd.polyapi.com/OpenAPI/do', appkey: this.app.config.poloApi.appKey, app_secret: this.app.config.poloApi.appSecret, platid, version: '1.5', token: accessToken, }); console.log('请求的店铺的platformCode', platformCode, '接口响应', JSON.stringify(responseData)); const parsed = formatDyWaybillSearchResponse(responseData, jdExpressNameMap); parsed.list = normalizeArray(parsed.list).map(item => { const currentItem = item && typeof item === 'object' ? item : {}; const expressMapping = resolveExpressMapping(jdExpressNameMap, [ currentItem.sys_express_code, currentItem.wp_code, currentItem.wpCode, currentItem.wp_name, currentItem.wpName, currentItem.providername, currentItem.cp_name, currentItem.cpname, currentItem.providercode, currentItem.cp_code, currentItem.cpcode, ]); if (!Object.keys(expressMapping).length) { return currentItem; } return { ...currentItem, wp_name: normalizeText(expressMapping.name) || normalizeText(currentItem.wp_name) || normalizeText(currentItem.wpName), sys_express_code: normalizeText(expressMapping.sys_express_code) || normalizeText(currentItem.sys_express_code), }; }); const unresolvedItems = normalizeArray(parsed.list).filter(item => { const currentItem = item && typeof item === 'object' ? item : {}; return !normalizeText(currentItem.sys_express_code).trim(); }); const compensationCandidateCodeSet = new Set(); normalizeArray(unresolvedItems).forEach(item => { const currentItem = item && typeof item === 'object' ? item : {}; [ currentItem.wp_code, currentItem.wpCode, currentItem.providercode, currentItem.cp_code, currentItem.cpcode, ].forEach(candidateCode => { const normalizedCandidateCode = normalizeText(candidateCode).trim().toUpperCase(); if (normalizedCandidateCode) { compensationCandidateCodeSet.add(normalizedCandidateCode); } }); }); const compensationCandidateCodes = Array.from(compensationCandidateCodeSet); if (compensationCandidateCodes.length) { const { Op } = this.app.Sequelize; const expressRows = await ctx.model.Express.findAll({ attributes: [ 'code', 'name', 'JD' ], where: { [Op.or]: [ { code: { [Op.in]: compensationCandidateCodes, }, }, { JD: { [Op.in]: compensationCandidateCodes, }, }, ], }, }); const compensationExpressMap = {}; normalizeArray(expressRows).forEach(expressRow => { const currentExpressRow = expressRow && typeof expressRow.get === 'function' ? expressRow.get({ plain: true }) : expressRow || {}; const compensationMappingItem = { name: normalizeText(currentExpressRow.name), sys_express_code: normalizeText(currentExpressRow.code), }; appendExpressMappingKey(compensationExpressMap, currentExpressRow.code, compensationMappingItem); appendExpressMappingKey(compensationExpressMap, currentExpressRow.JD, compensationMappingItem); }); parsed.list = normalizeArray(parsed.list).map(item => { const currentItem = item && typeof item === 'object' ? item : {}; const currentSysExpressCode = normalizeText(currentItem.sys_express_code).trim(); if (currentSysExpressCode) { return currentItem; } const compensationMapping = resolveExpressMapping(compensationExpressMap, [ currentItem.wp_code, currentItem.wpCode, currentItem.providercode, currentItem.cp_code, currentItem.cpcode, ]); if (!Object.keys(compensationMapping).length) { return currentItem; } const currentWpName = normalizeText(currentItem.wp_name) || normalizeText(currentItem.wpName); return { ...currentItem, wp_name: currentWpName || normalizeText(compensationMapping.name), sys_express_code: normalizeText(compensationMapping.sys_express_code), }; }); } list = parsed.list; break; } default: list = []; break; } return this.success('ok', { data: { shop_id: shopPlain.id, platform_code: platformCode, list, }, code: 200, }); } /** * 获取淘宝菜鸟 STF 模板列表。 * * @param {Object} [data={}] 请求参数 * @param {string} data.express_code 快递公司编码 * @return {Promise} 返回模板列表结果 */ async getCainiaoStfTemplates(data = {}) { const { express_code: expressCode = '' } = data || {}; return await this.getPrintPlatformTemplateList({ platform_code: 'CAINIAO', express_code: expressCode, }); } /** * 规范化打印模板查询的平台编码。 * * @param {Object} [data={}] 请求参数 * @param {string} [data.platform_code] 平台编码(下划线) * @param {string} [data.platformCode] 平台编码(驼峰) * @return {string} 规范化后的平台编码 */ normalizeTemplatePlatformCode(data = {}) { const normalizedPlatformCode = String( data.platform_code !== undefined ? data.platform_code : data.platformCode ).trim().toUpperCase(); return normalizedPlatformCode || 'CAINIAO'; } /** * 规范化打印模板查询的快递编码。 * * @param {Object} [data={}] 请求参数 * @param {string} [data.express_code] 快递编码(下划线) * @param {string} [data.expressCode] 快递编码(驼峰) * @return {string} 规范化后的快递编码 */ normalizeTemplateExpressCode(data = {}) { const expressCode = data.express_code !== undefined ? data.express_code : data.expressCode; if (expressCode === null || expressCode === undefined) { return ''; } return String(expressCode).trim().toUpperCase(); } /** * 获取 wms_express 中指定打印平台对应的字段名。 * * @param {string} platformCode 打印平台编码 * @return {string} 平台对应字段名 */ getExpressPlatformFieldName(platformCode) { const expressModel = this.ctx.model && this.ctx.model.Express; const rawAttributes = expressModel && expressModel.rawAttributes ? expressModel.rawAttributes : {}; if (rawAttributes[platformCode]) { return platformCode; } const matchedAttributeName = Object.keys(rawAttributes).find(attributeName => { const attribute = rawAttributes[attributeName] || {}; const attributeField = String(attribute.field || attributeName || '').trim().toUpperCase(); return attributeField === platformCode; }); if (matchedAttributeName) { return matchedAttributeName; } throw new Error(`platform_code 未匹配到 wms_express 平台字段: ${platformCode}`); } /** * 按平台字段与快递编码解析模板可用的快递编码集合。 * * @param {string} platformCode 打印平台编码 * @param {string} expressCode 入参快递编码 * @return {Promise>} 可用于模板过滤的快递编码集合 */ async getTemplateAllowedExpressCodeSet(platformCode, expressCode) { const fieldName = this.getExpressPlatformFieldName(platformCode); const normalizedExpressCode = String(expressCode || '').trim().toUpperCase(); const { Op } = this.app.Sequelize; const expressRows = await this.ctx.model.Express.findAll({ attributes: [ 'code', fieldName ], where: { [Op.or]: [ { code: normalizedExpressCode }, { [fieldName]: normalizedExpressCode }, ], }, }); console.log('expressCode', normalizedExpressCode); console.log('expressRows', expressRows); console.log('fieldName', fieldName); const allowedCodeSet = new Set(); if (normalizedExpressCode) { allowedCodeSet.add(normalizedExpressCode); } for (const expressRow of Array.isArray(expressRows) ? expressRows : []) { const plainRow = expressRow && typeof expressRow.get === 'function' ? expressRow.get({ plain: true }) : expressRow || {}; const candidateCodes = [ plainRow.code, plainRow[fieldName], ].map(item => String(item || '').trim().toUpperCase()).filter(Boolean); for (const code of candidateCodes) { allowedCodeSet.add(code); } } return allowedCodeSet; } /** * 按快递编码过滤打印平台模板响应。 * * @param {Object} responseData 平台模板原始响应 * @param {string} platformCode 打印平台编码 * @param {string} expressCode 入参快递编码 * @return {Promise} 过滤后的首个响应数据;未命中时返回 undefined */ async filterPrintPlatformTemplateResponseData(responseData, platformCode, expressCode) { console.log('入参', platformCode, expressCode); const normalizedExpressCode = String(expressCode || '').trim().toUpperCase(); const normalizedResponseData = Array.isArray(responseData) ? responseData : []; // 非 PDD 平台允许不传快递编码,直接回退首条模板。 if (platformCode !== 'PDD' && !normalizedExpressCode) { const fallbackTemplateResponseItem = normalizedResponseData[0]; if (platformCode === 'JD' && fallbackTemplateResponseItem) { return appendJdTemplateList(fallbackTemplateResponseItem); } return fallbackTemplateResponseItem; } // 获取对应的wp_code const allowedCodeSet = await this.getTemplateAllowedExpressCodeSet(platformCode, normalizedExpressCode); console.log('allowedCodeSet', allowedCodeSet); // console.log('normalizedResponseData', JSON.stringify(normalizedResponseData)); // normalizedResponseData数组中的cp_code字段与allowedCodeSet匹配的第一个对象 const matchedTemplateResponseItem = normalizedResponseData.find(item => { const itemCpCode = normalizeText(resolveFirstNonEmptyValue([ item?.cp_code, item?.cpcode, item?.cpCode, ])).trim().toUpperCase(); return allowedCodeSet.has(itemCpCode); }); if (platformCode === 'JD' && matchedTemplateResponseItem) { return appendJdTemplateList(matchedTemplateResponseItem); } return matchedTemplateResponseItem; } /** * 获取打印平台模板缓存键。 * * @param {string} platformCode 平台编码 * @return {string} 缓存键 */ getPrintPlatformTemplateCacheKey(platformCode) { if (platformCode === 'CAINIAO') { return 'index:cainiao:stfTemplates:responseData'; } if (platformCode === 'PDD') { return 'index:printPlatform:PDD:templates:v2:responseData'; } return `index:printPlatform:${platformCode}:templates:responseData`; } /** * 按平台编码请求模板列表。 * * 当前已实现 CAINIAO 平台,其它平台返回空对象,便于后续扩展。 * * @param {string} platformCode 平台编码 * @param {string|null} [s=null] 平台密钥或令牌 * @param {string|number|null} [platid=null] 平台标识ID * @param {string} [expressCode=''] 快递编码 * @return {Promise} 平台模板响应 */ async requestPrintPlatformTemplateList(platformCode, s = null, platid = null, expressCode = '') { console.log('请求打印平台模板列表,平台编码:', platformCode, platid); const platformRequesters = { CAINIAO: async () => await this.requestTbCainiaoStdTemplates(), PDD: async () => await this.requestPddTemplateSourceList(s, expressCode), KS: async () => await this.requestPolyStdTemplates(s, platid), XHS: async () => await this.requestPolyStdTemplates(s, platid), SPH: async () => await this.requestPolyStdTemplates(s, platid), DY: async () => await this.requestPolyStdTemplates(s, platid), JD: async () => await this.requestPolyStdTemplates(s, platid, true), }; const requester = platformRequesters[platformCode]; if (!requester) { return {}; } return await requester(); } /** * 基于快递编码解析拼多多模板查询候选 wp_code。 * * 优先使用 wms_express 的 PDD 平台字段,未命中时回退为入参快递编码。 * * @param {string} expressCode 入参快递编码 * @return {Promise>} 候选 wp_code 数组 */ async resolvePddTemplateWpCodeCandidates(expressCode) { const normalizedExpressCode = String(expressCode || '').trim().toUpperCase(); if (!normalizedExpressCode) { return []; } let fieldName = 'PDD'; try { fieldName = this.getExpressPlatformFieldName('PDD'); } catch (error) { return [ normalizedExpressCode ]; } const { Op } = this.app.Sequelize; const expressRows = await this.ctx.model.Express.findAll({ attributes: [ 'code', fieldName ], where: { [Op.or]: [ { code: normalizedExpressCode, }, { [fieldName]: normalizedExpressCode, }, ], }, }); const wpCodeList = []; const wpCodeSet = new Set(); const appendWpCode = value => { const wpCode = String(value || '').trim().toUpperCase(); if (!wpCode || wpCodeSet.has(wpCode)) { return; } wpCodeSet.add(wpCode); wpCodeList.push(wpCode); }; for (const expressRow of normalizeArray(expressRows)) { const plainRow = expressRow && typeof expressRow.get === 'function' ? expressRow.get({ plain: true }) : expressRow || {}; appendWpCode(plainRow[fieldName]); appendWpCode(plainRow.code); } if (!wpCodeList.length) { appendWpCode(normalizedExpressCode); } return wpCodeList; } /** * 基于拼多多官方模板直连接口构建模板源列表。 * * @param {string} accessToken 店铺授权令牌 * @param {string} expressCode 入参快递编码 * @return {Promise>} 模板源数组(包含 cp_code、wp_code 与标准模板结构) */ async requestPddTemplateSourceList(accessToken, expressCode = '') { const normalizedAccessToken = String(accessToken || '').trim(); if (!normalizedAccessToken) { return []; } const wpCodeCandidates = await this.resolvePddTemplateWpCodeCandidates(expressCode); if (!wpCodeCandidates.length) { return []; } const templateSourceList = []; for (const wpCodeCandidate of wpCodeCandidates) { const responseData = await this.requestPddStdTemplates({ accessToken: normalizedAccessToken, wpCode: wpCodeCandidate, }); const responseRoot = responseData && typeof responseData === 'object' ? responseData.pdd_cloudprint_stdtemplates_get_response || responseData : {}; const templateResponseItems = normalizeFirstWrappedArray([ responseRoot.result, responseRoot.results, responseRoot.standard_template_result, responseRoot.standard_templates, responseRoot.datas, responseRoot.data, ], [ 'standard_template_result', 'standard_templates', 'results', 'result', 'datas', 'data', 'list' ]); const normalizedTemplateResponseItems = templateResponseItems.length ? templateResponseItems : [ responseRoot ]; for (const templateResponseItem of normalizedTemplateResponseItems) { const sourceItem = templateResponseItem && typeof templateResponseItem === 'object' ? templateResponseItem : {}; const itemWpCode = normalizeText(resolveFirstNonEmptyValue([ sourceItem.wp_code, sourceItem.wpCode, sourceItem.cp_code, sourceItem.cpcode, sourceItem.cpCode, wpCodeCandidate, ])).trim().toUpperCase(); const standardTemplateSourceList = normalizeFirstWrappedArray([ sourceItem.standard_templates, sourceItem.standard_template_do, sourceItem.standardTemplateDo, sourceItem.templates, sourceItem.template_list, sourceItem.templateList, sourceItem.standard_template_result, sourceItem.results, sourceItem.result, sourceItem.datas, sourceItem.data, ], [ 'standard_template_do', 'standardTemplateDo', 'standard_template_result', 'results', 'result', 'datas', 'data', 'list' ]); const normalizedStandardTemplateSourceList = standardTemplateSourceList.length ? standardTemplateSourceList : sourceItem.standard_template_id || sourceItem.standard_template_name || sourceItem.standard_template_url ? [ sourceItem ] : []; const normalizedTemplateList = normalizedStandardTemplateSourceList.map(templateItem => { const sourceTemplate = templateItem && typeof templateItem === 'object' ? templateItem : {}; return { standard_template_id: normalizeText(resolveFirstNonEmptyValue([ sourceTemplate.standard_template_id, sourceTemplate.id, sourceTemplate.template_id, sourceTemplate.templateId, ])).trim(), standard_template_name: normalizeText(resolveFirstNonEmptyValue([ sourceTemplate.standard_template_name, sourceTemplate.name, sourceTemplate.template_name, sourceTemplate.templateName, ])).trim(), standard_template_url: normalizeText(resolveFirstNonEmptyValue([ sourceTemplate.standard_template_url, sourceTemplate.url, sourceTemplate.template_url, sourceTemplate.templateUrl, ])).trim(), }; }); const seenTemplateUrlSet = new Set(); const dedupedTemplateList = normalizedTemplateList.filter(templateItem => { const templateUrl = templateItem && typeof templateItem === 'object' ? templateItem.standard_template_url : ''; if (seenTemplateUrlSet.has(templateUrl)) { return false; } seenTemplateUrlSet.add(templateUrl); return true; }); templateSourceList.push({ cp_code: itemWpCode, wp_code: itemWpCode, standard_templates: { standard_template_do: dedupedTemplateList, }, }); } } return templateSourceList; } /** * 获取打印平台模板列表。 * * 入参传入哪个平台编码,就返回该平台对应的模板数据。 * * @param {Object} [data={}] 请求参数 * @param {string} [data.platform_code] 平台编码(下划线) * @param {string} [data.platformCode] 平台编码(驼峰) * @param {string} data.express_code 快递编码(下划线) * @param {string} [data.expressCode] 快递编码(驼峰) * @param {string} [data.shopId] 店铺ID(驼峰) * * @return {Promise} 返回模板列表结果 */ async getPrintPlatformTemplateList(data = {}) { console.log('获取打印平台模板列表请求参数', data); const platformCode = this.normalizeTemplatePlatformCode(data); const expressCode = this.normalizeTemplateExpressCode(data); const { ctx } = this; const warehouseId = Number(ctx.user?.store_id); if (!warehouseId) { return this.fail('未识别到当前仓库', { code: 400 }); } const rawShopId = data.shop_id !== undefined ? data.shop_id : data.shopId; const shopId = rawShopId !== undefined && rawShopId !== null && rawShopId !== '' ? Number(rawShopId) : null; let shop = null; if (Number.isFinite(shopId) && shopId > 0) { shop = await ctx.model.Shop.findOne({ where: { id: shopId, warehouse_id: warehouseId, ...buildNotDeletedShopWhere(this.app), }, include: this.buildShopPrintPlatformInclude(true), }); } if (platformCode === 'PDD' && !expressCode) { return this.fail('express_code 不能为空', { code: 400 }); } let accessToken = ''; let platid = null; if (shop) { const shopPlain = typeof shop.get === 'function' ? shop.get({ plain: true }) : shop; accessToken = String(shopPlain.access_token || '').trim(); const printPlatformInfo = await this.ensureShopPrintPlatformExists(shopPlain.platform_code, true); platid = Number(printPlatformInfo && printPlatformInfo.platid); } const hasShopId = Number.isFinite(shopId) && shopId > 0; const shouldBypassCache = platformCode === 'PDD' ? hasShopId && Boolean(accessToken) : hasShopId; const cacheKey = this.getPrintPlatformTemplateCacheKey(platformCode); const cached = shouldBypassCache ? null : await this.app.getCacheAsync(cacheKey); const hasShopRequestParams = Boolean(accessToken) && Number.isFinite(platid); const responseDataFromSource = cached !== null && cached !== undefined ? cached : hasShopRequestParams ? await this.requestPrintPlatformTemplateList(platformCode, accessToken, platid, expressCode) : await this.requestPrintPlatformTemplateList(platformCode, null, null, expressCode); console.log('打印平台模板查询原始响应:', JSON.stringify(responseDataFromSource)); if (platformCode === 'PDD' && Boolean(accessToken) && (cached === null || cached === undefined)) { await this.app.setCacheAsync(cacheKey, responseDataFromSource, 3600); } console.log('过滤入参', platformCode, expressCode); const responseData = await this.filterPrintPlatformTemplateResponseData( responseDataFromSource, platformCode, expressCode ); console.log('打印平台模板查询过滤后响应:', JSON.stringify(responseData)); return this.success('ok', { data: responseData || {}, code: 200, }); } /** * 判断是否为店铺预占记录的唯一约束冲突。 * * @param {Error} error 异常对象 * @return {boolean} 是否可重试的唯一约束冲突 */ isPlatformOauthReservationDuplicateError(error) { if (!error || error.name !== 'SequelizeUniqueConstraintError') { return false; } const fields = Array.isArray(error.errors) ? error.errors.map(item => item && item.path).filter(Boolean) : []; return fields.length === 0 || fields.includes('auth_random_code') || fields.includes('shop_name'); } /** * 获取平台授权预占码前缀配置。 * * @return {string} 授权预占码前缀 */ getPlatformOauthReservationCodePrefix() { const { app } = this; return String(app.config.platformOauthReservationCodePrefix || '').trim(); } /** * 判断授权预占码是否已带当前前缀。 * * @param {string} authRandomCode 授权预占码 * @param {string} prefix 授权预占码前缀 * @return {boolean} 是否已带前缀 */ hasPlatformOauthReservationCodePrefix(authRandomCode, prefix) { if (!prefix) { return true; } return String(authRandomCode || '').startsWith(prefix); } /** * 规范化平台授权预占码。 * * @param {string} authRandomCode 授权预占码 * @param {string} prefix 授权预占码前缀 * @return {string} 去掉当前前缀后的裸码,若未带前缀则原样返回 */ normalizePlatformOauthReservationCode(authRandomCode, prefix) { const normalizedCode = String(authRandomCode || '').trim(); if (!normalizedCode) { return ''; } if (prefix && this.hasPlatformOauthReservationCodePrefix(normalizedCode, prefix)) { return normalizedCode.slice(prefix.length); } return normalizedCode; } /** * 生成平台授权预占裸码。 * * @return {string} 新授权预占裸码 */ generatePlatformOauthReservationCode() { return crypto.randomBytes(24).toString('hex'); } /** * 创建平台授权的店铺预占记录。 * * @param {Object} data 请求参数 * @param {string|number} data.warehouseId 仓库 ID * @param {string} data.platformCode 平台编码 * @return {Promise<{ shop: Object, authRandomCode: string }>} 预占结果 */ async createPlatformOauthReservation(data) { const { ctx } = this; const { warehouseId, platformCode } = data; const normalizedPlatformCode = await this.ensureShopPrintPlatformExists(platformCode); const maxRetryCount = 5; const prefix = this.getPlatformOauthReservationCodePrefix(); const shop = await ctx.model.Shop.findOne({ where: { warehouse_id: warehouseId, platform_code: normalizedPlatformCode, status: 0, ...buildNotDeletedShopWhere(this.app), }, order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], }); if (shop) { const storedAuthRandomCode = String(shop.auth_random_code || '').trim(); if (storedAuthRandomCode) { const authRandomCode = this.normalizePlatformOauthReservationCode(storedAuthRandomCode, prefix); if (authRandomCode !== storedAuthRandomCode) { shop.auth_random_code = authRandomCode; await shop.save(); } return { shop, authRandomCode, }; } } for (let retryIndex = 0; retryIndex < maxRetryCount; retryIndex++) { const authRandomCode = this.generatePlatformOauthReservationCode(); try { if (shop) { shop.auth_random_code = authRandomCode; await shop.save(); return { shop, authRandomCode, }; } const createdShop = await ctx.model.Shop.create({ warehouse_id: warehouseId, platform_code: normalizedPlatformCode, shop_name: `PENDING_${authRandomCode}`, status: 0, auth_expire_at: null, auth_random_code: authRandomCode, }); return { shop: createdShop, authRandomCode, }; } catch (error) { if (this.isPlatformOauthReservationDuplicateError(error) && retryIndex < maxRetryCount - 1) { continue; } if (this.isPlatformOauthReservationDuplicateError(error)) { throw new Error('生成唯一授权码失败,请稍后重试'); } throw error; } } throw new Error('生成唯一授权码失败,请稍后重试'); } /** * 获取平台授权链接。 * * @param {Object} data 请求参数 * @param {string} [data.code] 平台编码 * @param {string} [data.platform_code] 平台编码 * @param {string} [data.platformCode] 平台编码 * @return {Promise} 返回包含平台编码、授权链接和独立授权码的结果 */ async getPlatformOauthLink(data) { const { ctx } = this; const { code = '', platform_code: platformCodeSnake = '', platformCode = '', } = data || {}; const rawPlatformCode = String(code || platformCodeSnake || platformCode || '').trim().toUpperCase(); const warehouseId = String(ctx.user?.store_id ?? '').trim(); if (!rawPlatformCode) { return this.fail('平台编码不能为空', { code: 400 }); } if (!warehouseId) { return this.fail('未识别到当前仓库', { code: 400 }); } let platform_code = ''; try { platform_code = await this.ensureShopPrintPlatformExists(rawPlatformCode); } catch (error) { return this.fail(error.message || '平台不存在', { code: 400 }); } const printPlatform = await ctx.model.PrintPlatform.findOne({ where: { platform_code, deleted: 0, status: 'ACTIVE', }, attributes: [ 'platform_code', 'auth_base_url' ], }); if (!printPlatform) { return this.fail('平台不存在', { code: 400 }); } const authBaseUrl = String(printPlatform.auth_base_url || '').trim(); if (!authBaseUrl) { return this.fail('平台授权基础地址未配置', { code: 400 }); } let reservation; try { reservation = await this.createPlatformOauthReservation({ warehouseId, platformCode: platform_code }); } catch (error) { ctx.logger.error('创建平台授权预占记录失败:', error); return this.fail(error.message || '创建平台授权预占记录失败', { code: 500 }); } const prefix = this.getPlatformOauthReservationCodePrefix(); const oauthLink = `${authBaseUrl}${encodeURIComponent(`${prefix}${platform_code}_${reservation.authRandomCode}`)}`; return this.success('ok', { data: { code: reservation.authRandomCode, platform_code, oauth_link: oauthLink, }, code: 200, }); } /** * 监听平台授权绑定结果。 * * @param {Object} data 请求参数 * @param {string} [data.code] 业务编码 * @param {string} [data.businessCode] 业务编码 * @param {boolean} [data.longPoll] 是否启用长轮询 * @return {Promise} 监听结果 */ async listenPlatformOauthBind(data = {}) { const { service } = this; const { code = '', businessCode = '', business_code: businessCodeSnake = '', longPoll = false, long_poll: longPollSnake = false, wait = false, timeoutMs, timeout_ms: timeoutMsSnake, } = data || {}; const result = await service.systems.platform.listenPlatformOauthBind({ code: code || businessCode || businessCodeSnake, longPoll: longPoll || longPollSnake || wait, timeoutMs: timeoutMs || timeoutMsSnake, }); if (result.code) { return this.success('获取平台授权绑定状态成功', result); } return this.fail(`获取平台授权绑定状态失败:${result.message}`, result); } /** * 前端请求生成唯一的登录码,后续可以通过这个登录码在IM系统中完成登录状态的绑定。登录码只写入到缓存中,不存储在数据库,具有较短的过期时间(如5分钟),并且只能使用一次。 * * @return {Promise} 返回登录码及用户信息 */ async loginToIm() { const { ctx } = this; const { user } = ctx; if (!user || !user.id) { return this.fail('用户未登录', { code: 401 }); } const employeeId = String(user.employees_id ?? '').trim(); const employeeName = String(user.employees_name ?? '').trim(); const subjectId = String(user.store_id ?? '').trim(); const subjectName = String(user.store_name ?? '').trim(); const avatar = String(user.avatar ?? '').trim(); const storeType = String(user.store_type ?? '').trim(); if (!employeeId || !employeeName || !subjectId || !subjectName || !storeType) { return this.fail('用户信息不完整', { code: 400 }); } const keyName = crypto.randomBytes(32).toString('hex'); const cacheKey = `im:sso:code:${keyName}`; const payload = { employees_id: employeeId, employees_name: employeeName, subject: { id: subjectId, name: subjectName, type: storeType, }, avatar, created_at: Date.now(), }; await this.app.setCacheAsync(cacheKey, payload, 300); return this.success('ok', { data: { code: keyName, employees_id: employeeId, employees_name: employeeName, subject: payload.subject, store_type: storeType, avatar, }, code: 200, }); } async polyapiAuthorizeUrl() { const { service } = this; const respone = await service.systems.poloApi.request('Differ.JH.BuildeAuthorizeUrl', { appkey: this.app.config.poloApi.appKey, appsecret: this.app.config.poloApi.appSecret, callbackurl: 'http://39.100.57.68/', state: '1223456', itemcode: 'JH_001', }, { interface_url: 'http://aliyun.polyapi.com/OpenAPI/do', appkey: this.app.config.poloApi.appKey, app_secret: this.app.config.poloApi.appSecret, platid: '544', version: '1.5', token: 'db820eeeb6c8425eb3f1cc25a28fb2f8', shoptype: 'JH_001', ordersource: 'KUAI_SHOU', }); return this.success('ok', { data: { respone, }, code: 200, }); } /** * 根据运单号快速查询订单 ID 及其所属波次信息。 * * @param {Object} data 请求参数。 * @param {string} data.waybill_code 运单号。 * @return {Promise} 统一成功包装响应,包含 order_id 和 waves 数组。 */ async toOrder(data = {}) { const { service } = this; const { waybill_code: waybillCode } = data; const result = await service.systems.waybill.toOrder({ waybill_code: waybillCode }); return this.success('查询成功', result); } /** * 获取工作台绑定码(免登录、免鉴权) * 不传 client_code:返回新会话的 client_code + 绑定码; * 传 client_code:等待绑定完成返回 token,超时/缓存失效时重新生成绑定码后返回。 * @param {Object} data - { clientCode | client_code } */ async getWorkbenchBindCode(data) { const { service } = this; try { const result = await service.systems.workbench.getWorkbenchBindCode(data || {}); if (result && result.success) { return this.success('获取工作台绑定码成功', result); } return this.fail(result && result.message ? result.message : '获取工作台绑定码失败', undefined); } catch (error) { return this.fail(error.message); } } /** * 通过工作台登录码登录,获取 token(免登录、免鉴权) * @param {Object} data - { loginCode | login_code } */ async LoginWorkbenchByCode(data) { const { service } = this; try { const result = await service.systems.workbench.loginWorkbenchByCode(data || {}); if (result && result.success) { return this.success('工作台登录成功', result); } const statusCode = result && result.statusCode; return this.fail( result && result.message ? result.message : '工作台登录失败', statusCode ? { code: statusCode } : undefined ); } catch (error) { return this.fail(error.message); } } /** * 根据 token 查询用户信息(免登录、免鉴权,工作台工牌扫码用)。 * * 支持两种 token: * 1. 微信工牌码(登录码):base64 的 {uuid:'{oauth_id}_{6位随机}',form:'wechat'}, * 按 uuid 前缀取 wms_user_oauth.id → 返回 nickname / user_id; * 已绑定账号(user_id>0)时返回 wms_account_store_employee 的工号名称(real_name), * 未绑定时直接返回 wms_user_oauth.nickname。 * 2. ye4s 登录临时码:对应 ye4s_user.tmp_code(旧流程兜底)。 * * @param {Object} data 请求参数 * @param {string} data.token 微信工牌码(base64)或 ye4s 登录临时码 * @return {Promise} 统一响应结构;命中时返回 real_name 与 user_id/wms_account_id,未命中时返回失败响应(code=404) */ async queryUserByToken(data = {}) { const { ctx } = this; const { token } = data || {}; if (!token || !String(token).trim()) { return this.fail('token 不能为空', { code: 400 }); } const rawToken = String(token).trim(); // 微信工牌码(base64 + uuid + wechat 来源):走 wms_user_oauth 查询 const wechatBadge = this.parseWechatBadgeCode(rawToken); if (wechatBadge) { try { return await this.queryUserByWechatBadge(wechatBadge.oauthId); } catch (error) { ctx.logger.error('工牌查询用户失败:', error); return this.fail(error.message || '查询用户失败', { code: 500 }); } } try { const ye4sClient = ctx.app.mysql.get('ye4s'); const rows = await ye4sClient.select('ye4s_user', { where: { tmp_code: rawToken, }, columns: [ 'real_name', 'wms_account_id' ], limit: 1, }); if (!rows || rows.length === 0) { return this.fail('用户不存在', { code: 404 }); } const userRecord = rows[0]; return this.success('查询成功', { real_name: userRecord.real_name ?? '', wms_account_id: userRecord.wms_account_id ?? null, code: 200, }); } catch (error) { ctx.logger.error('查询用户失败:', error); return this.fail(error.message || '查询用户失败', { code: 500 }); } } /** * 解析微信工牌码:base64 的 {uuid:'{oauth_id}_{6位随机}',form:'wechat'} * - 解码为 JSON 且来源为 wechat 时返回 { oauthId }(wms_user_oauth.id) * - 其他内容(ye4s 临时码等)返回 null,由调用方走旧逻辑 * * @param {string} token 工牌码原文 * @return {{oauthId: number}|null} 解析结果 */ parseWechatBadgeCode(token) { try { const text = String(token || '').trim(); // 快速预判:长度与字符集需符合 base64,避免每条码都走解码 if (!text || text.length < 16 || !/^[A-Za-z0-9+/=_-]+$/.test(text)) { return null; } const b64 = text.replace(/-/g, '+').replace(/_/g, '/'); const decoded = Buffer.from(b64, 'base64').toString('utf8'); if (!decoded || !decoded.trim().startsWith('{')) { return null; } const payload = JSON.parse(decoded); if (!payload || typeof payload !== 'object') { return null; } const form = payload.form || payload.source || ''; const uuid = payload.uuid || ''; if (String(form) !== 'wechat' || !uuid) { return null; } // uuid 形如 {oauth_id}_{6位随机},取前缀作为 wms_user_oauth.id const oauthId = Number(String(uuid).split('_')[0]); if (!Number.isInteger(oauthId) || oauthId <= 0) { return null; } return { oauthId }; } catch (error) { return null; } } /** * 微信工牌查询用户:按 wms_user_oauth.id 取 nickname/user_id; * 已绑定账号(user_id>0)时返回 wms_account_store_employee 的工号名称(real_name), * 未绑定/无工号记录时直接返回 wms_user_oauth.nickname。 * * @param {number} oauthId wms_user_oauth.id * @return {Promise} 统一响应结构 */ async queryUserByWechatBadge(oauthId) { const { ctx } = this; const oauth = await ctx.model.UserOauth.findByPk(oauthId); if (!oauth) { return this.fail('用户不存在', { code: 404 }); } const userId = Number(oauth.user_id) || 0; let realName = oauth.nickname || ''; // 已绑定账号:拉取 wms_account_store_employee 工号名称(real_name,status=1) if (userId > 0) { const employee = await ctx.model.AccountStoreEmployee.findOne({ where: { account_id: userId, status: 1 }, order: [[ 'id', 'ASC' ]], }); if (employee && employee.real_name) { realName = employee.real_name; } } return this.success('查询成功', { real_name: realName, user_id: userId > 0 ? userId : null, wms_account_id: userId > 0 ? userId : null, nickname: oauth.nickname || '', code: 200, }); } } module.exports = indexService;