2483 lines
174 KiB
JavaScript
2483 lines
174 KiB
JavaScript
'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|浠f敹璐ф|鍒颁粯|鎷︽埅浠秥瀹氭椂娲鹃€亅涓婇棬鍙栨棫鎹㈡柊/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<string>} [nestedKeys=[]] 瀵硅薄鍖呰9鏃剁殑鍊欓€夊瓙瀛楁鍚? * @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<string>} [nestedKeys=[]] 瀵硅薄鍖呰9鏃剁殑鍊欓€夊瓙瀛楁鍚? * @return {Array} 棣栦釜闈炵┖鐨勬爣鍑嗗寲鏁扮粍
|
||
*/
|
||
function normalizeFirstWrappedArray(values, nestedKeys = []) {
|
||
for (const value of normalizeArray(values)) {
|
||
const normalized = normalizeWrappedArray(value, nestedKeys);
|
||
|
||
if (normalized.length) {
|
||
return normalized;
|
||
}
|
||
}
|
||
|
||
return [];
|
||
}
|
||
|
||
/**
|
||
* 瑙勮寖鍖栬彍楦熸爣鍑嗘ā鏉垮瓙椤瑰垪琛ㄣ€? *
|
||
* @param {*} standardTemplates 鑿滈笩鏍囧噯妯℃澘瀛楁
|
||
* @return {Array<Object>} 鏍囧噯妯℃澘瀛愰」鍒楄〃
|
||
*/
|
||
// eslint-disable-next-line no-unused-vars
|
||
function normalizeCainiaoStandardTemplateList(standardTemplates) {
|
||
return normalizeWrappedArray(standardTemplates, [ 'standard_template_do' ]);
|
||
}
|
||
|
||
/**
|
||
* 鎸夊師濮嬬粨鏋勫洖濉彍楦熸爣鍑嗘ā鏉垮瓙椤瑰垪琛ㄣ€? *
|
||
* @param {*} standardTemplates 鑿滈笩鏍囧噯妯℃澘瀛楁
|
||
* @param {Array<Object>} 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;
|
||
}, {});
|
||
}
|
||
|
||
/**
|
||
* 瑙f瀽骞跺啓鍏ュ揩閫掓槧灏勯敭锛屽吋瀹瑰師鍊间笌澶у啓閿€? *
|
||
* @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 绯荤粺蹇€掑垪琛? * @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 {};
|
||
}
|
||
|
||
/**
|
||
* 瑙f瀽鎷煎澶氱數瀛愰潰鍗曠綉鐐规煡璇㈠搷搴旓紝鏀舵暃涓哄墠绔槗娑堣垂鐨勭粨鏋勩€? *
|
||
* @param {*} responseData 鎷煎澶氬師濮嬪搷搴? * @param {Object} [expressNameMap={}] 骞冲彴蹇€掔紪鐮佸埌绯荤粺蹇€掍俊鎭殑鏄犲皠
|
||
* @return {Object} 瑙f瀽鍚庣殑鐢靛瓙闈㈠崟缃戠偣缁撴瀯
|
||
*/
|
||
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 accounts = normalizeArray(subscriptionItem.branch_account_cols).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 = normalizeArray(accountItem.shipp_address_cols).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),
|
||
detail: normalizeText(addressItem.detail),
|
||
full_address: normalizeText(addressItem.full_address),
|
||
};
|
||
});
|
||
const services = normalizeArray(accountItem.service_info_cols).map(service => {
|
||
const serviceItem = service && typeof service === 'object' ? service : {};
|
||
const attributes = normalizeArray(serviceItem.service_attributes).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),
|
||
};
|
||
});
|
||
|
||
return {
|
||
service_code: normalizeText(serviceItem.service_code),
|
||
service_name: normalizeText(serviceItem.service_name),
|
||
service_desc: normalizeText(serviceItem.service_desc),
|
||
required: Boolean(serviceItem.required),
|
||
attributes,
|
||
};
|
||
});
|
||
|
||
return {
|
||
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 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),
|
||
accounts,
|
||
};
|
||
});
|
||
|
||
return {
|
||
request_id: normalizeText(waybillResponse.request_id),
|
||
total: subscriptions.length,
|
||
list,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 瑙f瀽鎶栭煶锛圥olyAPI锛夌數瀛愰潰鍗曠綉鐐规煡璇㈠搷搴旓紝鏀舵暃涓轰笌鎷煎澶氫竴鑷寸殑缁熶竴缁撴瀯銆? *
|
||
* @param {*} responseData 鎶栭煶鍘熷鍝嶅簲
|
||
* @param {Object} [expressNameMap={}] 骞冲彴蹇€掔紪鐮佸埌绯荤粺蹇€掍俊鎭殑鏄犲皠
|
||
* @return {Object} 瑙f瀽鍚庣殑鐢靛瓙闈㈠崟缃戠偣缁撴瀯
|
||
*/
|
||
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.cp_code
|
||
|| subscriptionItem.cpcode
|
||
|| subscriptionItem.logistics_code
|
||
|| subscriptionItem.express_code
|
||
);
|
||
const expressMapping = resolveExpressMapping(expressNameMap, [
|
||
subscriptionItem.cp_code,
|
||
subscriptionItem.cpcode,
|
||
subscriptionItem.wp_code,
|
||
subscriptionItem.logistics_code,
|
||
subscriptionItem.express_code,
|
||
sysExpressCode,
|
||
wpCode,
|
||
]);
|
||
|
||
const accounts = 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' ]).map(account => {
|
||
const accountItem = account && typeof account === 'object' ? account : {};
|
||
const customerCodes = normalizeWrappedArray(
|
||
accountItem.customer_code_list
|
||
|| accountItem.customerCodeList
|
||
|| accountItem.customer_codes
|
||
|| accountItem.customerCodes,
|
||
[ 'string', 'list', 'code' ]
|
||
).map(item => normalizeText(item)).filter(Boolean);
|
||
const shipAddresses = normalizeFirstWrappedArray([
|
||
accountItem.shipp_address_cols,
|
||
accountItem.ship_addresses,
|
||
accountItem.shipAddresses,
|
||
accountItem.address_dto,
|
||
accountItem.addresses,
|
||
accountItem.shippers,
|
||
], [ '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 || addressItem.town),
|
||
district: normalizeText(addressItem.district || addressItem.area),
|
||
detail: normalizeText(addressItem.detail || addressItem.address_detail || addressItem.address),
|
||
full_address: normalizeText(addressItem.full_address || addressItem.fullAddress || ''),
|
||
};
|
||
});
|
||
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,
|
||
};
|
||
});
|
||
console.log("accountItem",subscriptionItem.logisticsaccount,"\n\n")
|
||
const result = {
|
||
branch_code: accountItem.sitecode,
|
||
branch_name: 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,
|
||
ship_addresses: shipAddresses,
|
||
services,
|
||
};
|
||
if(subscriptionItem.logisticsaccount){
|
||
result.customer_code_list = [subscriptionItem.logisticsaccount];
|
||
}
|
||
if(subscriptionItem.shopid){
|
||
result.platform_shop_id = subscriptionItem.shopid;
|
||
}
|
||
return result;
|
||
});
|
||
|
||
if (!groupedByWpCode.has(wpCode)) {
|
||
groupedByWpCode.set(wpCode, {
|
||
wp_code: wpCode,
|
||
wp_name: normalizeText(expressMapping.name)
|
||
|| normalizeText(subscriptionItem.wp_name || subscriptionItem.cp_name || subscriptionItem.cpname),
|
||
sys_express_code: normalizeText(expressMapping.sys_express_code || sysExpressCode),
|
||
wp_type: normalizeText(subscriptionItem.wp_type || subscriptionItem.waybill_type || subscriptionItem.type),
|
||
accounts: [],
|
||
shipAddressKeys: new Set(),
|
||
});
|
||
}
|
||
|
||
const groupedItem = groupedByWpCode.get(wpCode);
|
||
|
||
if (!groupedItem.wp_name) {
|
||
groupedItem.wp_name = normalizeText(expressMapping.name)
|
||
|| normalizeText(subscriptionItem.wp_name || 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.waybill_type || subscriptionItem.type);
|
||
}
|
||
|
||
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,
|
||
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<Object>} 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<Object>} 鏍囧噯鍖栧悗鐨勭绾﹁闃呭垪琛? */
|
||
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' ]
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 瑙f瀽娣樺疂鑿滈笩鐢靛瓙闈㈠崟缃戠偣鏌ヨ鍝嶅簲锛屾敹鏁涗负鍓嶇鏄撴秷璐圭殑缁熶竴缁撴瀯銆? *
|
||
* @param {*} responseData 娣樺疂鍘熷鍝嶅簲
|
||
* @param {Object} [expressNameMap={}] 骞冲彴蹇€掔紪鐮佸埌绯荤粺蹇€掍俊鎭殑鏄犲皠
|
||
* @return {Object} 瑙f瀽鍚庣殑鐢靛瓙闈㈠崟缃戠偣缁撴瀯
|
||
*/
|
||
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';
|
||
const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl';
|
||
const _noNeedLog = '*';
|
||
const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl';
|
||
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 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<Object>} 璇嗗埆缁撴灉
|
||
*/
|
||
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 鎷煎澶氭帴鍙e悕锛屼緥濡?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<Object>} 璋冪敤缁撴灉
|
||
*/
|
||
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]) {
|
||
current[key] = {};
|
||
}
|
||
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, // 濡傛灉鏈夊€煎氨淇濆瓨锛屽惁鍒檔ull
|
||
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 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<Object>} 杩斿洖濂囬棬搴旂敤鍒楄〃缁撴灉
|
||
*/
|
||
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<Object>} 杩斿洖缁撴灉
|
||
*/
|
||
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<Object>} 杩斿洖缁撴灉
|
||
*/
|
||
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] 鏄惁浠呰繑鍥炵郴缁熷熀纭€骞冲彴鍒楄〃锛? 琛ㄧず浠呰繑鍥炵郴缁熷钩鍙? * @param {boolean} [data.systemOnly] 鏄惁浠呰繑鍥炵郴缁熷熀纭€骞冲彴鍒楄〃
|
||
* @param {boolean} [data.full] 鏄惁杩斿洖鍏ㄩ噺瀛楁
|
||
* @return {Promise<Object>} 杩斿洖缁撴灉
|
||
*/
|
||
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 });
|
||
}
|
||
|
||
/**
|
||
* 鑾峰彇鎵撳嵃骞冲彴鍏ㄩ噺鍒楄〃銆? *
|
||
* 渚涘墠绔柊澧炪€佷慨鏀瑰揩閫掓帴鍙f椂涓嬫媺閫夋嫨浣跨敤锛屼笉杩斿洖鍒嗛〉缁撴瀯銆? *
|
||
* @return {Promise<Object>} 杩斿洖缁撴灉
|
||
*/
|
||
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<string>} 鏍囧噯鍖栧悗鐨勬墦鍗板钩鍙扮紪鐮? */
|
||
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<Object>} 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<Object>} 杩斿洖搴楅摵鍒楄〃缁撴灉
|
||
*/
|
||
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<Object>} 鎷煎澶氬師濮嬪搷搴旀暟鎹? * @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] 搴楅摵鎺堟潈浠ょ墝锛坰ession锛夛紝涓虹┖鏃朵笉涓嬪彂
|
||
* @param {string} [payload.cpCode] 蹇€掑叕鍙哥紪鐮? * @return {Promise<Object>} 娣樺疂鍘熷鍝嶅簲鏁版嵁
|
||
* @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<Object>} 娣樺疂鍘熷鍝嶅簲鏁版嵁
|
||
* @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 鑿犺悵娲惧钩鍙版爣璇? * @return {Promise<Array<Object>>} 褰掍竴鍖栧悗鐨勬ā鏉挎暟缁? * @throws {Error} 褰撻厤缃己澶辨垨鎺ュ彛杩斿洖澶辫触鏃舵姏鍑哄紓甯? */
|
||
async requestPolyStdTemplates(appSecret,platid) {
|
||
const { service } = this;
|
||
if(!appSecret || !platid){
|
||
throw new Error('鑿犺悵娲炬帴鍙i厤缃己澶?);
|
||
}
|
||
const responseData = await service.systems.poloApi.request('Differ.JH.Logistics.GetTemplates', {
|
||
templatestype:"ALL"
|
||
}, {
|
||
interface_url: 'https://api.polyapi.com/OpenAPI/do',
|
||
appkey: this.app.config.poloApi.appKey,
|
||
app_secret: this.app.config.poloApi.appSecret,
|
||
token:appSecret,
|
||
platid: platid,
|
||
version: '1.0',
|
||
});
|
||
console.log('璇锋眰鑿犺悵娲炬爣鍑嗘ā鏉挎帴鍙e搷搴?, 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<Object>} 杩斿洖搴楅摵瀵瑰簲鐨勫揩閫掔绾﹀垪琛? */
|
||
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 瑙f瀽缁撴灉', 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");
|
||
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 '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', {
|
||
}, {
|
||
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;
|
||
}
|
||
|
||
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<Object>} 杩斿洖妯℃澘鍒楄〃缁撴灉
|
||
*/
|
||
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<Set<string>>} 鍙敤浜庢ā鏉胯繃婊ょ殑蹇€掔紪鐮侀泦鍚? */
|
||
async getTemplateAllowedExpressCodeSet(platformCode, expressCode) {
|
||
const fieldName = this.getExpressPlatformFieldName(platformCode);
|
||
const expressRows = await this.ctx.model.Express.findAll({
|
||
attributes: [ 'code', fieldName ],
|
||
where: {
|
||
[fieldName]: expressCode,
|
||
},
|
||
});
|
||
|
||
const allowedCodeSet = new Set();
|
||
|
||
for (const expressRow of Array.isArray(expressRows) ? expressRows : []) {
|
||
const plainRow = expressRow && typeof expressRow.get === 'function'
|
||
? expressRow.get({ plain: true })
|
||
: expressRow || {};
|
||
const code = String(plainRow[fieldName] || '').trim().toUpperCase();
|
||
|
||
if (code) {
|
||
allowedCodeSet.add(code);
|
||
}
|
||
}
|
||
|
||
return allowedCodeSet;
|
||
}
|
||
|
||
/**
|
||
* 鎸夊揩閫掔紪鐮佽繃婊ゆ墦鍗板钩鍙版ā鏉垮搷搴斻€? *
|
||
* @param {Object} responseData 骞冲彴妯℃澘鍘熷鍝嶅簲
|
||
* @param {string} platformCode 鎵撳嵃骞冲彴缂栫爜
|
||
* @param {string} expressCode 鍏ュ弬蹇€掔紪鐮? * @return {Promise<Object|undefined>} 杩囨护鍚庣殑棣栦釜鍝嶅簲鏁版嵁锛涙湭鍛戒腑鏃惰繑鍥?undefined
|
||
*/
|
||
async filterPrintPlatformTemplateResponseData(responseData, platformCode, expressCode) {
|
||
console.log('鍏ュ弬', platformCode, expressCode);
|
||
// 鑾峰彇瀵瑰簲鐨剋p_code
|
||
const allowedCodeSet = await this.getTemplateAllowedExpressCodeSet(platformCode, expressCode);
|
||
const normalizedResponseData = Array.isArray(responseData)
|
||
? responseData
|
||
: [];
|
||
console.log('allowedCodeSet', allowedCodeSet);
|
||
console.log('normalizedResponseData', normalizedResponseData);
|
||
// normalizedResponseData鏁扮粍涓殑cp_code瀛楁涓巃llowedCodeSet鍖归厤鐨勭涓€涓璞? return normalizedResponseData.find(item => {
|
||
const itemCpCode = String(item.cp_code || '').trim().toUpperCase();
|
||
return allowedCodeSet.has(itemCpCode);
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 鑾峰彇鎵撳嵃骞冲彴妯℃澘缂撳瓨閿€? *
|
||
* @param {string} platformCode 骞冲彴缂栫爜
|
||
* @return {string} 缂撳瓨閿? */
|
||
getPrintPlatformTemplateCacheKey(platformCode) {
|
||
if (platformCode === 'CAINIAO') {
|
||
return 'index:cainiao:stfTemplates:responseData';
|
||
}
|
||
|
||
return `index:printPlatform:${platformCode}:templates:responseData`;
|
||
}
|
||
|
||
/**
|
||
* 鎸夊钩鍙扮紪鐮佽姹傛ā鏉垮垪琛ㄣ€? *
|
||
* 褰撳墠宸插疄鐜?CAINIAO 骞冲彴锛屽叾瀹冨钩鍙拌繑鍥炵┖瀵硅薄锛屼究浜庡悗缁墿灞曘€? *
|
||
* @param {string} platformCode 骞冲彴缂栫爜
|
||
* @return {Promise<Object>} 骞冲彴妯℃澘鍝嶅簲
|
||
*/
|
||
async requestPrintPlatformTemplateList(platformCode,s = null,platid = null) {
|
||
const platformRequesters = {
|
||
CAINIAO: async () => await this.requestTbCainiaoStdTemplates(),
|
||
KS: async () => await this.requestPolyStdTemplates(s, platid),
|
||
};
|
||
const requester = platformRequesters[platformCode];
|
||
|
||
if (!requester) {
|
||
return {};
|
||
}
|
||
|
||
return await requester();
|
||
}
|
||
|
||
/**
|
||
* 鑾峰彇鎵撳嵃骞冲彴妯℃澘鍒楄〃銆? *
|
||
* 鍏ュ弬浼犲叆鍝釜骞冲彴缂栫爜锛屽氨杩斿洖璇ュ钩鍙板搴旂殑妯℃澘鏁版嵁銆? *
|
||
* @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<Object>} 杩斿洖妯℃澘鍒楄〃缁撴灉
|
||
*/
|
||
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 (!expressCode) {
|
||
return this.fail('express_code 涓嶈兘涓虹┖', { code: 400 });
|
||
}
|
||
|
||
const shouldBypassCache = Number.isFinite(shopId) && shopId > 0;
|
||
const cacheKey = this.getPrintPlatformTemplateCacheKey(platformCode);
|
||
const cached = shouldBypassCache ? null : await this.app.getCacheAsync(cacheKey);
|
||
|
||
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 hasShopRequestParams = Boolean(accessToken) && Number.isFinite(platid);
|
||
|
||
const responseDataFromSource = cached !== null && cached !== undefined
|
||
? cached
|
||
: hasShopRequestParams
|
||
? await this.requestPrintPlatformTemplateList(platformCode, accessToken, platid)
|
||
: await this.requestPrintPlatformTemplateList(platformCode);
|
||
// console.log('鎵撳嵃骞冲彴妯℃澘鏌ヨ鍘熷鍝嶅簲:', JSON.stringify(responseDataFromSource));
|
||
|
||
if (cached === null || cached === undefined) {
|
||
// await this.app.setCacheAsync(cacheKey, responseDataFromSource, 3600);
|
||
}
|
||
|
||
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} 鏂版巿鏉冮鍗犺8鐮? */
|
||
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<Object>} 杩斿洖鍖呭惈骞冲彴缂栫爜銆佹巿鏉冮摼鎺ュ拰鐙珛鎺堟潈鐮佺殑缁撴灉
|
||
*/
|
||
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<Object>} 鐩戝惉缁撴灉
|
||
*/
|
||
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绯荤粺涓畬鎴愮櫥褰曠姸鎬佺殑缁戝畾銆傜櫥褰曠爜鍙啓鍏ュ埌缂撳瓨涓紝涓嶅瓨鍌ㄥ湪鏁版嵁搴擄紝鍏锋湁杈冪煭鐨勮繃鏈熸椂闂达紙濡?鍒嗛挓锛夛紝骞朵笖鍙兘浣跨敤涓€娆°€? *
|
||
* @return {Promise<Object>} 杩斿洖鐧诲綍鐮佸強鐢ㄦ埛淇℃伅
|
||
*/
|
||
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,
|
||
});
|
||
}
|
||
}
|
||
module.exports = indexService;
|