WMS_MAIN/app/service/systems/store_warehouse.js
liufumingren 5ce689d771 1
Co-authored-by: Copilot <copilot@github.com>
2026-04-30 19:20:31 +08:00

2319 lines
77 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const crypto = require('node:crypto');
const Service = require('egg').Service;
const SIGN_TEMP_EXPIRE_SECONDS = 600;
const AUTH_STATUS_LABELS = Object.freeze({
1: '申请中',
2: '已通过',
3: '已拒绝',
4: '已解除',
5: '已过期',
});
class SettingStoreWarehouseService extends Service {
/**
* 创建统一错误对象。
*
* @param {string} message 错误信息。
* @param {number} [code=500] HTTP 状态码。
* @return {Error} 带 code 属性的错误对象。
*/
createError(message, code = 500) {
const error = new Error(message);
error.code = code;
return error;
}
/**
* 获取当前登录主体的货主 ID。
*
* @return {number} 当前主体的货主 ID。
* @throws {Error} 当无法识别当前主体时抛出,状态码为 400。
*/
getCurrentStoreId() {
const storeId = Number(this.ctx.user && this.ctx.user.store_id);
if (!Number.isFinite(storeId) || storeId <= 0) {
throw this.createError('未识别到当前主体,无法操作签约关系', 400);
}
return storeId;
}
/**
* 获取当前登录账号 ID。
*
* @return {number} 当前登录账号 ID。
* @throws {Error} 当无法识别当前登录账号时抛出,状态码为 401。
*/
getCurrentAccountId() {
const accountId = Number(this.ctx.user && this.ctx.user.id);
if (!Number.isFinite(accountId) || accountId <= 0) {
throw this.createError('未识别到当前登录账号', 401);
}
return accountId;
}
/**
* 将输入值规范化为正数。
*
* @param {*} value 待转换的值。
* @param {string} fieldName 字段名。
* @param {Object} [options={}] 配置项。
* @param {boolean} [options.allowEmpty=false] 是否允许空值返回 null。
* @return {number|null} 规范化后的正数或 null。
* @throws {Error} 参数非法时抛出,状态码为 400。
*/
toPositiveNumber(value, fieldName, options = {}) {
const { allowEmpty = false } = options;
if (allowEmpty && (value === undefined || value === null || value === '')) {
return null;
}
const num = Number(value);
if (!Number.isFinite(num) || num <= 0) {
throw this.createError(`${fieldName} 参数不能为空`, 400);
}
return num;
}
/**
* 规范化分页参数。
*
* @param {*} value 待处理的页码或分页大小。
* @param {string} fieldName 字段名。
* @param {number} defaultValue 默认值。
* @param {number} maxValue 最大值。
* @return {number} 规范化后的分页值。
* @throws {Error} 参数非法时抛出,状态码为 400。
*/
normalizePage(value, fieldName, defaultValue, maxValue) {
if (value === undefined || value === null || value === '') {
return defaultValue;
}
const num = Number(value);
if (!Number.isFinite(num) || num <= 0) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
return Math.min(Math.floor(num), maxValue);
}
/**
* 规范化状态标记。
*
* @param {*} value 待处理的状态值。
* @param {string} fieldName 字段名。
* @param {number|null} [defaultValue=null] 默认值。
* @return {number|null} 0、1 或默认值。
* @throws {Error} 参数非法时抛出,状态码为 400。
*/
normalizeStatusFlag(value, fieldName, defaultValue = null) {
if (value === undefined || value === null || value === '') {
return defaultValue;
}
const num = Number(value);
if (num === 0 || num === 1) {
return num;
}
throw this.createError(`${fieldName} 参数不合法`, 400);
}
/**
* 规范化签约状态。
*
* @param {*} value 待处理的签约状态值。
* @return {number|null} 合法的签约状态或 null。
* @throws {Error} 参数非法时抛出,状态码为 400。
*/
normalizeAuthStatus(value) {
if (value === undefined || value === null || value === '') {
return null;
}
const num = Number(value);
if ([ 1, 2, 3, 4, 5 ].includes(num)) {
return num;
}
throw this.createError('auth_status 参数不合法', 400);
}
/**
* 规范化非负整数。
*
* @param {*} value 待处理的值。
* @param {string} fieldName 字段名。
* @param {number} [defaultValue=0] 默认值。
* @return {number} 非负整数。
* @throws {Error} 参数非法时抛出,状态码为 400。
*/
normalizeNonNegativeInteger(value, fieldName, defaultValue = 0) {
if (value === undefined || value === null || value === '') {
return defaultValue;
}
const num = Number(value);
if (!Number.isFinite(num) || num < 0) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
return Math.floor(num);
}
/**
* 规范化整数。
*
* @param {*} value 待处理的值。
* @param {string} fieldName 字段名。
* @param {Object} [options={}] 配置项。
* @param {boolean} [options.allowZero=true] 是否允许 0。
* @return {number} 整数值。
* @throws {Error} 参数非法时抛出,状态码为 400。
*/
normalizeInteger(value, fieldName, options = {}) {
const { allowZero = true } = options;
if (value === undefined || value === null || value === '') {
throw this.createError(`${fieldName} 参数不能为空`, 400);
}
const num = Number(value);
if (!Number.isFinite(num) || !Number.isInteger(num)) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
if (!allowZero && num === 0) {
throw this.createError(`${fieldName} 不能为 0`, 400);
}
return num;
}
/**
* 规范化文本内容。
*
* @param {*} value 待处理的值。
* @param {string} fieldName 字段名。
* @param {number} [maxLength=500] 最大长度。
* @return {string|null} 规范化后的文本或 null。
* @throws {Error} 文本超长时抛出,状态码为 400。
*/
normalizeText(value, fieldName, maxLength = 500) {
if (value === undefined || value === null) {
return null;
}
const normalized = String(value).trim();
if (normalized.length > maxLength) {
throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400);
}
return normalized;
}
/**
* 规范化区间整数。
*
* @param {*} value 待处理的值。
* @param {string} fieldName 字段名。
* @param {number} defaultValue 默认值。
* @param {number} minValue 最小值。
* @param {number} maxValue 最大值。
* @return {number} 区间内的整数。
* @throws {Error} 参数非法时抛出,状态码为 400。
*/
normalizeIntegerRange(value, fieldName, defaultValue, minValue, maxValue) {
if (value === undefined || value === null || value === '') {
return defaultValue;
}
const num = Number(value);
if (!Number.isFinite(num) || num < minValue || num > maxValue) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
return Math.floor(num);
}
/**
* 规范化邮箱地址。
*
* @param {*} value 待处理的邮箱值。
* @return {string|null} 合法邮箱或 null。
* @throws {Error} 邮箱格式非法时抛出,状态码为 400。
*/
normalizeEmail(value) {
const email = this.normalizeText(value, 'email', 100);
if (!email) {
return null;
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
throw this.createError('email 参数不合法', 400);
}
return email;
}
/**
* 获取策略配置字段清单。
*
* @return {Array} 策略配置字段数组。
*/
getPolicyConfigFieldList() {
const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse;
if (!storeWarehouseModel || typeof storeWarehouseModel.getPolicyConfigFieldList !== 'function') {
return [];
}
return storeWarehouseModel.getPolicyConfigFieldList();
}
/**
* 获取带动态选项的策略配置字段清单。
*
* @return {Promise<Array>} 策略配置字段数组。
*/
async getPolicyConfigFieldMetaList() {
const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse;
if (!storeWarehouseModel || typeof storeWarehouseModel.getPolicyConfigFieldListWithOptions !== 'function') {
return this.getPolicyConfigFieldList();
}
return storeWarehouseModel.getPolicyConfigFieldListWithOptions();
}
/**
* 规范化策略配置内容。
*
* @param {*} value 待处理的配置值。
* @param {string} [fieldName='policy_config'] 字段名。
* @param {Object} [options={}] 配置项。
* @param {boolean} [options.allowEmpty=false] 是否允许空值。
* @param {boolean} [options.sanitizeOnly=false] 是否仅做清洗不做强校验。
* @return {*|null} 规范化后的策略配置。
* @throws {Error} 模型未提供规则或参数非法时抛出,对应状态码为 400/500。
*/
normalizePolicyConfig(value, fieldName = 'policy_config', options = {}) {
const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse;
if (!storeWarehouseModel || typeof storeWarehouseModel.normalizePolicyConfig !== 'function') {
throw this.createError('StoreWarehouse model 未定义 policy_config 规则', 500);
}
try {
return storeWarehouseModel.normalizePolicyConfig(value, {
fieldName,
allowEmpty: options.allowEmpty === true,
sanitizeOnly: options.sanitizeOnly === true,
});
} catch (error) {
throw this.createError(error.message || `${fieldName} 参数不合法`, Number(error.code) || 400);
}
}
/**
* 生成策略配置缓存键。
*
* @param {number|string} contractId 合同 ID。
* @return {string} 缓存键。
*/
getPolicyConfigCacheKey(contractId) {
return `store_warehouse:policy:${contractId}`;
}
/**
* 判断表中是否存在 policy_config 字段。
*
* @return {Promise<boolean>} 是否存在该字段。
*/
async hasPolicyConfigColumn() {
if (this._hasPolicyConfigColumn !== undefined) {
return this._hasPolicyConfigColumn;
}
try {
const [ columns ] = await this.app.model.query(
"SHOW COLUMNS FROM `wms_store_warehouse` LIKE 'policy_config'"
);
this._hasPolicyConfigColumn = Array.isArray(columns) && columns.length > 0;
} catch {
this._hasPolicyConfigColumn = false;
}
return this._hasPolicyConfigColumn;
}
/**
* 按合同 ID 读取策略配置。
*
* @param {number|string} contractId 合同 ID。
* @param {Object|null} [transaction=null] 事务对象。
* @return {Promise<*>} 规范化后的策略配置。
*/
async loadPolicyConfigByContractId(contractId, transaction = null) {
const normalizedId = Number(contractId || 0);
if (normalizedId <= 0) {
return null;
}
if (await this.hasPolicyConfigColumn()) {
const [ rows ] = await this.app.model.query(
'SELECT policy_config FROM wms_store_warehouse WHERE id = :id LIMIT 1',
{
replacements: { id: normalizedId },
transaction,
}
);
const row = Array.isArray(rows) ? rows[0] : null;
const raw = row ? row.policy_config : null;
return this.normalizePolicyConfig(raw, 'policy_config', {
allowEmpty: true,
sanitizeOnly: true,
});
}
const cached = await this.app.getCacheAsync(this.getPolicyConfigCacheKey(normalizedId));
return this.normalizePolicyConfig(cached, 'policy_config', {
allowEmpty: true,
sanitizeOnly: true,
});
}
/**
* 按合同 ID 保存策略配置。
*
* @param {number|string} contractId 合同 ID。
* @param {*} policyConfig 策略配置内容。
* @param {Object|null} [transaction=null] 事务对象。
* @return {Promise<void>} 无返回值。
* @throws {Error} 合同 ID 非法时抛出,状态码为 400。
*/
async savePolicyConfigByContractId(contractId, policyConfig, transaction = null) {
const normalizedId = Number(contractId || 0);
if (normalizedId <= 0) {
throw this.createError('id 参数不能为空', 400);
}
if (await this.hasPolicyConfigColumn()) {
await this.app.model.query(
'UPDATE wms_store_warehouse SET policy_config = :policy_config, updated_at = NOW() WHERE id = :id',
{
replacements: {
id: normalizedId,
policy_config: JSON.stringify(policyConfig),
},
transaction,
}
);
return;
}
await this.app.setCacheAsync(this.getPolicyConfigCacheKey(normalizedId), policyConfig, 86400 * 30);
}
/**
* 获取策略配置默认值。
*
* @return {Object} 策略配置默认值对象。
*/
getPolicyConfigDefaults() {
return this.getPolicyConfigFieldList().reduce((result, field) => {
result[field.key] = field.default;
return result;
}, {});
}
/**
* 将策略配置与默认值合并。
*
* @param {*} policyConfig 已保存的策略配置。
* @return {Object} 合并后的策略配置对象。
*/
mergePolicyConfigWithDefaults(policyConfig) {
const defaults = this.getPolicyConfigDefaults();
if (!policyConfig || typeof policyConfig !== 'object') {
return defaults;
}
return {
...defaults,
...policyConfig,
};
}
/**
* 按合同 ID 读取带默认值的策略配置。
*
* @param {number|string} contractId 合同 ID。
* @param {Object|null} [transaction=null] 事务对象。
* @return {Promise<Object>} 带默认值的策略配置对象。
*/
async getEffectivePolicyConfigByContractId(contractId, transaction = null) {
const policyConfig = await this.loadPolicyConfigByContractId(contractId, transaction);
return this.mergePolicyConfigWithDefaults(policyConfig);
}
/**
* 校验当前主体是否为仓库主体。
*
* @param {Object} currentSubject 当前主体。
* @param {string} [actionLabel='签约配置'] 操作名称。
* @return {void}
* @throws {Error} 当前主体不是仓库主体时抛出,状态码为 403。
*/
ensureWarehouseSubject(currentSubject, actionLabel = '签约配置') {
if (!currentSubject || !currentSubject.isWarehouse) {
throw this.createError(`仅仓库主体可维护${actionLabel}`, 403);
}
}
/**
* 获取通知服务实例。
*
* @return {Object|null} 通知服务或 null。
*/
getNoticeService() {
const rawNoticeService = this.ctx && this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.notice;
if (rawNoticeService && typeof rawNoticeService.send === 'function') {
return rawNoticeService;
}
if (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function') {
return rawNoticeService.index;
}
return null;
}
/**
* 发送面单余额调整通知。
*
* @param {Object} options 通知参数。
* @param {Object} [options.relation] 签约关系。
* @param {Object} [options.currentSubject] 当前主体。
* @param {Object} [options.changeLog] 调整日志。
* @param {number} [options.operatorId] 操作人 ID。
* @param {number} [options.changeQuantity] 变更数量。
* @param {number} [options.balanceBefore] 调整前余额。
* @param {number} [options.balanceAfter] 调整后余额。
* @param {string} [options.reason] 调整原因。
* @return {Promise<Object|null>} 通知发送结果或 null。
*/
async sendPrintQuantityAdjustNotice({
relation,
currentSubject,
changeLog,
operatorId,
changeQuantity,
balanceBefore,
balanceAfter,
reason,
} = {}) {
const noticeService = this.getNoticeService();
if (!noticeService || !relation) {
return null;
}
const relationData = relation && typeof relation.get === 'function'
? relation.get({ plain: true })
: (relation || {});
const storeName = relationData.store_remask || (relationData.store && relationData.store.company_name) || '';
const warehouseName = relationData.warehouse_remask || (relationData.warehouse && relationData.warehouse.company_name) || '';
const operatorName = String(
(this.ctx.user && (this.ctx.user.real_name || this.ctx.user.employees_name || this.ctx.user.name || this.ctx.user.username)) || ''
).trim();
const changeLabel = changeQuantity === 0
? '无变化'
: changeQuantity > 0
? `增加 ${changeQuantity}`
: `扣减 ${Math.abs(changeQuantity)}`;
return await noticeService.send({
warehouseId: Number(relationData.warehouse_id || 0),
storeId: Number(relationData.store_id || 0) || undefined,
messageType: 'text',
businessName: 'store_warehouse',
event: 'store_warehouse_print_quantity_adjusted',
title: '货主面单余额已更新',
content: [
warehouseName ? `仓库:${warehouseName}` : '',
storeName ? `货主:${storeName}` : '',
`设置余额:${balanceAfter}`,
`变更:${changeLabel}`,
`余额:${balanceBefore} -> ${balanceAfter}`,
`原因:${reason}`,
operatorName ? `操作人:${operatorName}` : '',
].filter(Boolean).join(';'),
businessId: Number((changeLog && changeLog.id) || relationData.id || 0),
subject: {
id: Number(currentSubject && currentSubject.id || relationData.warehouse_id || 0),
type: currentSubject && currentSubject.isWarehouse ? 'warehouse' : 'store',
name: currentSubject && currentSubject.company_name ? currentSubject.company_name : warehouseName,
},
sender: {
id: Number(operatorId || 0) || null,
name: operatorName,
},
metadata: {
contractId: Number(relationData.id || 0),
storeId: Number(relationData.store_id || 0),
warehouseId: Number(relationData.warehouse_id || 0),
changeType: String(changeLog && changeLog.change_type || 'manual_adjust'),
businessType: changeLog && changeLog.business_type ? String(changeLog.business_type) : null,
businessId: changeLog && changeLog.business_id !== undefined && changeLog.business_id !== null
? Number(changeLog.business_id)
: null,
changeQuantity,
balanceBefore,
balanceAfter,
reason,
},
});
}
/**
* 解析签约关系 ID。
*
* @param {Object} [data={}] 请求参数。
* @return {number|null} 关系 ID 或 null。
*/
resolveRelationId(data = {}) {
return this.toPositiveNumber(
data.id !== undefined ? data.id : (data.contract_id !== undefined ? data.contract_id : data.relation_id),
'id',
{ allowEmpty: true }
);
}
/**
* 规范化日期值。
*
* @param {*} value 待处理的日期值。
* @param {string} fieldName 字段名。
* @param {Object} [options={}] 配置项。
* @param {boolean} [options.allowNull=true] 是否允许空值。
* @return {Date|null} 规范化后的日期对象或 null。
* @throws {Error} 日期非法时抛出,状态码为 400。
*/
normalizeDate(value, fieldName, options = {}) {
const { allowNull = true } = options;
if (value === undefined || value === null || value === '') {
if (allowNull) {
return null;
}
throw this.createError(`${fieldName} 参数不能为空`, 400);
}
const date = value instanceof Date ? value : new Date(value);
if (Number.isNaN(date.getTime())) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
return date;
}
/**
* 规范化签约动作。
*
* @param {*} value 待处理的动作值。
* @return {string} 规范化后的动作值。
* @throws {Error} 动作非法时抛出,状态码为 400。
*/
normalizeSignAction(value) {
if (value === undefined || value === null || value === '') {
return '';
}
const action = String(value).trim();
if ([ 'preview', 'confirm' ].includes(action)) {
return action;
}
throw this.createError('action 参数不合法', 400);
}
/**
* 规范化临时码。
*
* @param {*} value 待处理的临时码。
* @return {string} 大写后的临时码。
* @throws {Error} 临时码为空或非法时抛出,状态码为 400。
*/
normalizeTempCode(value) {
const code = String(value || '').trim().toUpperCase();
if (!code) {
throw this.createError('temp_code 参数不能为空', 400);
}
return code;
}
/**
* 生成临时码缓存键。
*
* @param {string} tempCode 临时码。
* @return {string} 缓存键。
*/
getTempCodeCacheKey(tempCode) {
return `store_warehouse:sign:${tempCode}`;
}
/**
* 生成临时码。
*
* @return {string} 临时码。
*/
createTempCode() {
return crypto.randomBytes(6).toString('hex').toUpperCase();
}
/**
* 选择当前主体对应的脱敏字段。
*
* @param {Object} currentSubject 当前主体。
* @return {string} 脱敏字段名。
*/
pickRemaskField(currentSubject) {
return currentSubject && currentSubject.isWarehouse ? 'store_remask' : 'warehouse_remask';
}
/**
* 解析脱敏展示名称。
*
* @param {Object} data 请求参数。
* @param {Object} currentSubject 当前主体。
* @return {string|null} 脱敏名称。
*/
resolveRemaskValue(data, currentSubject) {
const raw = data.remask !== undefined
? data.remask
: (currentSubject && currentSubject.isWarehouse ? data.store_remask : data.warehouse_remask);
return this.normalizeText(raw, 'remask', 50);
}
/**
* 构建当前主体的脱敏字段更新内容。
*
* @param {Object} data 请求参数。
* @param {Object} currentSubject 当前主体。
* @return {Object} 待更新字段对象。
*/
buildCurrentRemaskPatch(data, currentSubject) {
const remask = this.resolveRemaskValue(data, currentSubject);
if (remask === null) {
return {};
}
return {
[this.pickRemaskField(currentSubject)]: remask,
};
}
/**
* 构建强制要求的脱敏字段更新内容。
*
* @param {Object} data 请求参数。
* @param {Object} currentSubject 当前主体。
* @return {Object} 待更新字段对象。
* @throws {Error} 未提供脱敏名称时抛出,状态码为 400。
*/
requireCurrentRemaskPatch(data, currentSubject) {
const patch = this.buildCurrentRemaskPatch(data, currentSubject);
if (!Object.keys(patch).length) {
throw this.createError('remask 参数不能为空', 400);
}
return patch;
}
/**
* 保存临时签约载荷。
*
* @param {Object} payload 临时载荷。
* @return {Promise<Object>} 保存后的临时码信息。
*/
async saveTempSignPayload(payload) {
const now = Date.now();
const expiresAt = new Date(now + SIGN_TEMP_EXPIRE_SECONDS * 1000).toISOString();
const tempCode = this.createTempCode();
await this.app.setCacheAsync(this.getTempCodeCacheKey(tempCode), {
...payload,
expires_at: expiresAt,
}, SIGN_TEMP_EXPIRE_SECONDS);
return {
tempCode,
expiresAt,
expiresIn: SIGN_TEMP_EXPIRE_SECONDS,
};
}
/**
* 读取临时签约载荷。
*
* @param {string} tempCode 临时码。
* @return {Promise<Object>} 临时码与载荷信息。
* @throws {Error} 临时码无效或已过期时抛出,状态码为 404。
*/
async getTempSignPayload(tempCode) {
const normalizedCode = this.normalizeTempCode(tempCode);
const payload = await this.app.getCacheAsync(this.getTempCodeCacheKey(normalizedCode));
if (!payload) {
throw this.createError('临时码无效或已过期', 404);
}
return {
tempCode: normalizedCode,
payload,
};
}
/**
* 清理临时签约载荷。
*
* @param {string} tempCode 临时码。
* @return {Promise<void>} 无返回值。
*/
async clearTempSignPayload(tempCode) {
const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null;
if (cacheRedis && cacheRedis.del) {
await cacheRedis.del(this.getTempCodeCacheKey(tempCode));
return;
}
await this.app.setCacheAsync(this.getTempCodeCacheKey(tempCode), { consumed: true }, 1);
}
/**
* 构建临时签约预览视图。
*
* @param {string} tempCode 临时码。
* @param {Object} payload 临时载荷。
* @param {Object} currentSubject 当前主体。
* @return {Object} 预览视图对象。
*/
buildTempSignView(tempCode, payload, currentSubject) {
const participantIds = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ];
const currentSubjectId = Number(currentSubject && currentSubject.id);
const expiresAt = payload.expires_at || null;
const expiresMs = expiresAt ? new Date(expiresAt).getTime() : 0;
return {
mode: 'preview',
temp_code: tempCode,
expires_at: expiresAt,
expires_in: expiresMs ? Math.max(0, Math.ceil((expiresMs - Date.now()) / 1000)) : 0,
is_participant: participantIds.includes(currentSubjectId),
can_confirm: currentSubjectId > 0 && currentSubjectId === Number(payload.counterparty_id || 0),
initiator: {
id: Number(payload.initiator_subject_id || 0),
role: payload.initiator_role || '',
name: payload.initiator_name || '',
},
counterparty: {
id: Number(payload.counterparty_id || 0),
role: payload.counterparty_role || '',
name: payload.counterparty_name || '',
},
sign_info: {
store_id: Number(payload.store_id || 0),
warehouse_id: Number(payload.warehouse_id || 0),
auth_start: payload.auth_start || null,
auth_end: payload.auth_end || null,
print_quantity: Number(payload.print_quantity || 0),
apply_reason: payload.apply_reason || '',
remask: payload.remask || '',
},
};
}
/**
* 获取当前主体信息。
*
* @return {Promise<Object>} 当前主体对象。
* @throws {Error} 当前主体不存在时抛出,状态码为 404。
*/
async getCurrentSubject() {
const { ctx } = this;
const storeId = this.getCurrentStoreId();
const subject = await ctx.model.Store.findOne({
where: {
id: storeId,
},
attributes: [ 'id', 'company_name', 'project', 'status' ],
});
if (!subject) {
throw this.createError('当前主体不存在', 404);
}
return {
id: Number(subject.id),
company_name: subject.company_name || '',
project: subject.project || '',
isWarehouse: subject.project === 'warehouse',
status: Number(subject.status || 0),
};
}
/**
* 获取签约对方主体信息。
*
* @param {number} counterpartyId 对方主体 ID。
* @param {string} expectedRole 期望角色。
* @return {Promise<Object>} 对方主体对象。
* @throws {Error} 对方主体不存在或角色不匹配时抛出,状态码为 400/404。
*/
async getCounterparty(counterpartyId, expectedRole) {
const { ctx } = this;
const counterparty = await ctx.model.Store.findOne({
where: {
id: counterpartyId,
},
attributes: [ 'id', 'company_name', 'project', 'status' ],
});
if (!counterparty) {
throw this.createError('签约对象不存在', 404);
}
const isWarehouse = counterparty.project === 'warehouse';
if (expectedRole === 'warehouse' && !isWarehouse) {
throw this.createError('目标对象不是仓库主体,无法签约', 400);
}
if (expectedRole === 'store' && isWarehouse) {
throw this.createError('目标对象不是货主主体,无法签约', 400);
}
return counterparty;
}
/**
* 构建列表查询条件。
*
* @param {Object} data 请求参数。
* @param {Object} currentSubject 当前主体。
* @return {Object} where 查询条件。
*/
buildListWhere(data, currentSubject) {
const where = {};
if (currentSubject.isWarehouse) {
where.warehouse_id = currentSubject.id;
} else {
where.store_id = currentSubject.id;
}
const relationId = this.resolveRelationId(data);
if (relationId) {
where.id = relationId;
}
const rawCounterpartyId = data.counterparty_id !== undefined
? data.counterparty_id
: (currentSubject.isWarehouse ? data.store_id : data.warehouse_id);
const counterpartyId = this.toPositiveNumber(rawCounterpartyId, 'counterparty_id', { allowEmpty: true });
if (counterpartyId) {
if (currentSubject.isWarehouse) {
where.store_id = counterpartyId;
} else {
where.warehouse_id = counterpartyId;
}
}
const authStatus = this.normalizeAuthStatus(data.auth_status);
if (authStatus !== null) {
where.auth_status = authStatus;
}
const useStatus = this.normalizeStatusFlag(data.use_status, 'use_status', null);
if (useStatus !== null) {
where.use_status = useStatus;
}
return where;
}
/**
* 获取签约关系关联模型。
*
* @return {Array<Object>} 关联配置数组。
*/
getRelationIncludes() {
const { ctx } = this;
return [
{
model: ctx.model.Store,
as: 'store',
attributes: [ 'id', 'company_name', 'project', 'status' ],
required: false,
},
{
model: ctx.model.Store,
as: 'warehouse',
attributes: [ 'id', 'company_name', 'project', 'status' ],
required: false,
},
];
}
/**
* 生成奇门合同缓存键。
*
* @param {string} appKey 应用标识。
* @param {string} customerId 客户标识。
* @param {string} warehouseCode 仓库编码。
* @return {string} 缓存键。
*/
getQimenContractCacheKey(appKey, customerId, warehouseCode) {
return `contract:${appKey}:${customerId}:${warehouseCode}`;
}
/**
* 清理奇门合同缓存。
*
* @param {Array} configs 配置列表。
* @return {Promise<void>} 无返回值。
*/
async clearQimenContractCache(configs = []) {
const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null;
const keys = [ ...new Set(configs.map(item => {
const record = item && typeof item.get === 'function'
? item.get({ plain: true })
: item;
if (!record) {
return '';
}
const appKey = String(record.qimen_app_key || '').trim();
const customerId = String(record.qimen_customer_id || '').trim();
const warehouseCode = String(record.qimen_warehouse_code || '').trim();
if (!appKey || !customerId || !warehouseCode) {
return '';
}
return this.getQimenContractCacheKey(appKey, customerId, warehouseCode);
}).filter(Boolean)) ];
if (!keys.length) {
return;
}
if (cacheRedis && cacheRedis.del) {
await cacheRedis.del(...keys);
return;
}
await Promise.all(keys.map(key => this.app.setCacheAsync(key, null, 1).catch(() => null)));
}
/**
* 获取接口类型。
*
* @param {Object} [data={}] 请求参数。
* @param {Object} [options={}] 选项。
* @param {boolean} [options.allowDisabled=false] 是否允许禁用接口类型。
* @param {Object|null} [options.transaction=null] 事务对象。
* @param {boolean} [options.requireId=false] 是否必须传入 interface_type_id。
* @param {string|null} [options.interfaceCategory=null] 接口分类。
* @return {Promise<Object>} 接口类型对象。
* @throws {Error} 参数非法或接口类型不存在时抛出,状态码为 400/404。
*/
async getApiInterfaceType(data = {}, options = {}) {
const { ctx } = this;
const { allowDisabled = false, transaction = null, requireId = false, interfaceCategory = null } = options;
const interfaceTypeId = this.toPositiveNumber(data.interface_type_id, 'interface_type_id', { allowEmpty: true });
if (requireId && !interfaceTypeId) {
throw this.createError('interface_type_id 参数不能为空', 400);
}
const where = {};
if (interfaceCategory) {
where.interface_category = interfaceCategory;
}
if (!allowDisabled) {
where.is_enabled = 1;
}
if (interfaceTypeId) {
where.id = interfaceTypeId;
}
const interfaceType = await ctx.model.InterfaceType.findOne({
where,
attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ],
order: [[ 'id', 'ASC' ]],
transaction,
});
if (!interfaceType) {
throw this.createError(interfaceTypeId ? '指定的接口类型不存在或不可用' : '未配置可用的接口类型', 404);
}
return interfaceType;
}
/**
* 获取奇门接口类型。
*
* @param {Object} [data={}] 请求参数。
* @param {Object} [options={}] 选项。
* @return {Promise<Object>} 接口类型对象。
*/
async getQimenInterfaceType(data = {}, options = {}) {
return this.getApiInterfaceType(data, options);
}
/**
* 序列化奇门配置。
*
* @param {Object} config 配置实例或普通对象。
* @return {Object|null} 序列化后的配置对象。
*/
serializeQimenConfig(config) {
if (!config) {
return null;
}
const item = config && typeof config.get === 'function'
? config.get({ plain: true })
: config;
const interfaceType = item.interface_type || {};
return {
id: Number(item.id || 0),
interface_type_id: Number(item.interface_type_id || 0),
interface_code: interfaceType.interface_code || item.interface_code || '',
interface_name: interfaceType.interface_name || item.interface_name || '',
interface_category: interfaceType.interface_category || item.interface_category || '',
contract_id: Number(item.contract_id || 0),
warehouse_id: item.warehouse_id ? Number(item.warehouse_id) : null,
app_name: item.app_name || '',
self_app_key: item.self_app_key || '',
self_app_secret: item.self_app_secret || '',
qimen_app_key: item.qimen_app_key || '',
qimen_customer_id: item.qimen_customer_id || '',
qimen_warehouse_code: item.qimen_warehouse_code || '',
api_version: item.api_version || '',
sign_method: item.sign_method || '',
rate_limit: Number(item.rate_limit || 0),
timeout_seconds: Number(item.timeout_seconds || 0),
contact_person: item.contact_person || '',
contact_phone: item.contact_phone || '',
email: item.email || '',
is_enabled: Number(item.is_enabled || 0),
created_at: item.created_at || null,
updated_at: item.updated_at || null,
callback_url: item.callback_url || '',
};
}
/**
* 获取奇门配置映射。
*
* @param {Array} contractIds 合同 ID 列表。
* @param {Object} [options={}] 选项。
* @param {boolean} [options.allowDisabled=true] 是否允许禁用接口类型。
* @param {number|null} [options.interfaceTypeId=null] 指定接口类型 ID。
* @param {Object|null} [options.transaction=null] 事务对象。
* @return {Promise<Map>} 合同 ID 到配置的映射。
*/
async getQimenConfigMap(contractIds = [], options = {}) {
const { ctx } = this;
const { allowDisabled = true, interfaceTypeId = null, transaction = null } = options;
const normalizedContractIds = [ ...new Set(contractIds.map(value => Number(value)).filter(value => Number.isFinite(value) && value > 0)) ];
if (!normalizedContractIds.length || !ctx.model.ApiApp || !ctx.model.InterfaceType) {
return new Map();
}
const where = {
contract_id: normalizedContractIds,
};
if (interfaceTypeId) {
const interfaceType = await this.getApiInterfaceType({ interface_type_id: interfaceTypeId }, {
allowDisabled,
transaction,
});
where.interface_type_id = Number(interfaceType.id || 0);
}
const rows = await ctx.model.ApiApp.findAll({
where,
include: [
{
model: ctx.model.InterfaceType,
as: 'interface_type',
attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ],
required: false,
},
],
order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
transaction,
});
const configMap = new Map();
for (const row of rows) {
const contractId = Number(row.contract_id || 0);
if (!contractId || configMap.has(contractId)) {
continue;
}
configMap.set(contractId, this.serializeQimenConfig(row));
}
return configMap;
}
/**
* 获取单个奇门配置。
*
* @param {number|string} contractId 合同 ID。
* @param {Object} [options={}] 选项。
* @return {Promise<Object|null>} 单个配置对象或 null。
*/
async getSingleQimenConfig(contractId, options = {}) {
const configMap = await this.getQimenConfigMap([ contractId ], options);
return configMap.get(Number(contractId)) || null;
}
/**
* 解析成对的合同主体 ID。
*
* @param {Object} data 请求参数。
* @param {Object} currentSubject 当前主体。
* @return {Object} 包含 storeId、warehouseId、counterpartyId 的对象。
* @throws {Error} 对方主体参数非法时抛出,状态码为 400。
*/
resolvePairIds(data, currentSubject) {
const fieldName = currentSubject.isWarehouse ? 'store_id / counterparty_id' : 'warehouse_id / counterparty_id';
const rawCounterpartyId = data.counterparty_id !== undefined
? data.counterparty_id
: (currentSubject.isWarehouse ? data.store_id : data.warehouse_id);
const counterpartyId = this.toPositiveNumber(rawCounterpartyId, fieldName);
if (currentSubject.isWarehouse) {
return {
storeId: counterpartyId,
warehouseId: currentSubject.id,
counterpartyId,
};
}
return {
storeId: currentSubject.id,
warehouseId: counterpartyId,
counterpartyId,
};
}
/**
* 序列化签约关系。
*
* @param {Object} relation 签约关系实例或普通对象。
* @param {Object} currentSubject 当前主体。
* @param {Object|null} [qimenConfig=null] 奇门配置。
* @return {Object} 序列化后的签约关系对象。
*/
serializeRelation(relation, currentSubject, qimenConfig = null) {
const item = relation && typeof relation.get === 'function'
? relation.get({ plain: true })
: (relation || {});
const normalizedQimenConfig = qimenConfig !== null
? qimenConfig
: (item.qimen_config ? this.serializeQimenConfig(item.qimen_config) : null);
const authStatus = Number(item.auth_status || 0);
const currentIsWarehouse = !!(currentSubject && currentSubject.isWarehouse);
const counterparty = currentIsWarehouse ? item.store : item.warehouse;
const storeName = item.store_remask || (item.store && item.store.company_name ? item.store.company_name : '');
const warehouseName = item.warehouse_remask || (item.warehouse && item.warehouse.company_name ? item.warehouse.company_name : '');
const counterpartyName = currentIsWarehouse ? storeName : warehouseName;
let isAuthValid = false;
let remainingDays = 0;
if (authStatus === 2 && item.auth_start && item.auth_end) {
const now = Date.now();
const start = new Date(item.auth_start).getTime();
const end = new Date(item.auth_end).getTime();
if (!Number.isNaN(start) && !Number.isNaN(end) && now >= start && now <= end) {
isAuthValid = true;
remainingDays = Math.max(0, Math.ceil((end - now) / (1000 * 60 * 60 * 24)));
}
}
return {
id: Number(item.id || 0),
store_id: Number(item.store_id || 0),
store_name: storeName,
warehouse_id: Number(item.warehouse_id || 0),
warehouse_name: warehouseName,
counterparty_id: counterparty && counterparty.id ? Number(counterparty.id) : 0,
counterparty_name: counterpartyName,
current_subject_role: currentIsWarehouse ? 'warehouse' : 'store',
auth_status: authStatus,
auth_status_label: AUTH_STATUS_LABELS[authStatus] || '',
apply_reason: item.apply_reason || '',
review_comment: item.review_comment || '',
apply_time: item.apply_time || null,
review_time: item.review_time || null,
auth_start: item.auth_start || null,
auth_end: item.auth_end || null,
actual_end: item.actual_end || null,
print_quantity: Number(item.print_quantity || 0),
print_quantity_locked: Number(item.print_quantity_locked || 0),
applied_by: item.applied_by ? Number(item.applied_by) : null,
reviewed_by: item.reviewed_by ? Number(item.reviewed_by) : null,
ended_by: item.ended_by ? Number(item.ended_by) : null,
remask: currentIsWarehouse ? (item.store_remask || '') : (item.warehouse_remask || ''),
use_status: Number(item.use_status || 0),
policy_config: item.policy_config && typeof item.policy_config === 'object' ? item.policy_config : null,
is_auth_valid: isAuthValid,
remaining_days: remainingDays,
api_config: normalizedQimenConfig || null,
apiConfig: normalizedQimenConfig || null,
};
}
/**
* 获取受限范围内的签约关系。
*
* @param {Object} data 请求参数。
* @param {Object} currentSubject 当前主体。
* @param {Object} transaction 事务对象。
* @return {Promise<Object>} 签约关系实例。
* @throws {Error} 签约关系不存在或无权限操作时抛出,状态码为 404。
*/
async findScopedRelation(data, currentSubject, transaction) {
const { ctx } = this;
const where = currentSubject.isWarehouse
? { warehouse_id: currentSubject.id }
: { store_id: currentSubject.id };
const relationId = this.resolveRelationId(data);
if (relationId) {
where.id = relationId;
} else {
const pair = this.resolvePairIds(data, currentSubject);
where.store_id = pair.storeId;
where.warehouse_id = pair.warehouseId;
}
const relation = await ctx.model.StoreWarehouse.findOne({
where,
include: this.getRelationIncludes(),
transaction,
});
if (!relation) {
throw this.createError('签约关系不存在或无权限操作', 404);
}
return relation;
}
/**
* 查询签约关系列表。
*
* @param {Object} [data={}] 请求参数。
* @return {Promise<Object>} 接口响应对象。
*/
async list(data = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const currentSubject = await this.getCurrentSubject();
const page = this.normalizePage(data.page, 'page', 1, 1000000);
const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200);
const offset = (page - 1) * pageSize;
const where = this.buildListWhere(data, currentSubject);
const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : '';
if (keyword) {
where[Op.or] = [
{ store_remask: { [Op.like]: `%${keyword}%` } },
{ warehouse_remask: { [Op.like]: `%${keyword}%` } },
{ '$store.company_name$': { [Op.like]: `%${keyword}%` } },
{ '$warehouse.company_name$': { [Op.like]: `%${keyword}%` } },
];
}
const { rows, count } = await ctx.model.StoreWarehouse.findAndCountAll({
where,
include: this.getRelationIncludes(),
order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
offset,
limit: pageSize,
distinct: true,
});
const contractIds = rows.map(item => Number(item.id || 0)).filter(id => id > 0);
const qimenConfigMap = contractIds.length
? await this.getQimenConfigMap(contractIds)
: new Map();
return {
code: 200,
data: {
list: rows.map(item => {
const serialized = this.serializeRelation(item, currentSubject);
delete serialized.api_config;
delete serialized.apiConfig;
serialized.has_qimen_config = qimenConfigMap.has(serialized.id);
return serialized;
}),
total: Number(count || 0),
page,
page_size: pageSize,
current_subject: {
store_id: currentSubject.id,
company_name: currentSubject.company_name,
role: currentSubject.isWarehouse ? 'warehouse' : 'store',
},
},
};
}
/**
* 发起或确认签约。
*
* @param {Object} [data={}] 请求参数。
* @return {Promise<Object>} 接口响应对象。
*/
async sign(data = {}) {
const action = this.normalizeSignAction(data.action || data.mode);
if (data.temp_code || data.tempCode || action === 'preview') {
const { ctx } = this;
const transaction = await ctx.model.transaction();
try {
const currentSubject = await this.getCurrentSubject();
const accountId = this.getCurrentAccountId();
const { tempCode, payload } = await this.getTempSignPayload(data.temp_code || data.tempCode);
const isParticipant = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ]
.includes(Number(currentSubject.id));
if (!isParticipant) {
throw this.createError('当前主体无权使用该临时码', 403);
}
if (action === 'preview' || data.preview === 1 || data.preview === '1') {
await transaction.rollback();
return {
code: 200,
data: this.buildTempSignView(tempCode, payload, currentSubject),
};
}
if (Number(currentSubject.id) !== Number(payload.counterparty_id || 0)) {
throw this.createError('需由对方主体确认后才可生效', 400);
}
const relationPatch = {
store_id: Number(payload.store_id || 0),
warehouse_id: Number(payload.warehouse_id || 0),
auth_status: 2,
apply_reason: payload.apply_reason || '',
apply_time: payload.created_at ? new Date(payload.created_at) : new Date(),
print_quantity: Number(payload.print_quantity || 0),
review_time: new Date(),
auth_start: payload.auth_start ? new Date(payload.auth_start) : new Date(),
auth_end: payload.auth_end ? new Date(payload.auth_end) : null,
actual_end: null,
applied_by: Number(payload.initiated_by || 0) || accountId,
reviewed_by: accountId,
ended_by: null,
use_status: 1,
};
if (payload.store_remask !== undefined) {
relationPatch.store_remask = payload.store_remask;
}
if (payload.warehouse_remask !== undefined) {
relationPatch.warehouse_remask = payload.warehouse_remask;
}
Object.assign(relationPatch, this.buildCurrentRemaskPatch(data, currentSubject));
let relation = await ctx.model.StoreWarehouse.findOne({
where: {
store_id: relationPatch.store_id,
warehouse_id: relationPatch.warehouse_id,
},
transaction,
});
const isCreate = !relation;
if (relation) {
await relation.update(relationPatch, { transaction });
} else {
relation = await ctx.model.StoreWarehouse.create(relationPatch, { transaction });
}
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
include: this.getRelationIncludes(),
transaction,
});
const qimenConfig = await this.getSingleQimenConfig(relation.id, {
allowDisabled: true,
transaction,
});
await this.clearTempSignPayload(tempCode);
await transaction.commit();
// 记录操作日志
try {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'store',
businessId: relation.id,
operationCode: 'STORE_SIGN',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: Number(payload.warehouse_id || 0),
},
beforeChanges: null,
});
} catch (logErr) {
ctx.logger.warn('[storeWarehouse.sign] 写入操作日志失败,不影响业务', logErr);
}
return {
code: 200,
data: {
mode: 'confirm',
temp_code: tempCode,
contract: this.serializeRelation(result, currentSubject, qimenConfig),
action: isCreate ? 'create' : 'update',
},
};
} catch (error) {
await transaction.rollback();
throw error;
}
}
const currentSubject = await this.getCurrentSubject();
const accountId = this.getCurrentAccountId();
const pair = this.resolvePairIds(data, currentSubject);
const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse');
const authStart = this.normalizeDate(data.auth_start, 'auth_start', { allowNull: true }) || new Date();
const authEnd = this.normalizeDate(data.auth_end, 'auth_end', { allowNull: true });
if (authEnd && authStart.getTime() > authEnd.getTime()) {
throw this.createError('auth_end 不能早于 auth_start', 400);
}
const remask = this.resolveRemaskValue(data, currentSubject);
const payload = {
initiated_by: accountId,
initiator_subject_id: currentSubject.id,
initiator_role: currentSubject.isWarehouse ? 'warehouse' : 'store',
initiator_name: currentSubject.company_name,
counterparty_id: Number(counterparty.id || 0),
counterparty_role: currentSubject.isWarehouse ? 'store' : 'warehouse',
counterparty_name: counterparty.company_name || '',
store_id: pair.storeId,
warehouse_id: pair.warehouseId,
auth_start: authStart.toISOString(),
auth_end: authEnd ? authEnd.toISOString() : null,
print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0),
apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000),
remask: remask || '',
created_at: new Date().toISOString(),
...this.buildCurrentRemaskPatch(data, currentSubject),
};
const signPayload = await this.saveTempSignPayload(payload);
return {
code: 200,
data: {
mode: 'initiate',
temp_code: signPayload.tempCode,
expires_at: signPayload.expiresAt,
expires_in: signPayload.expiresIn,
can_confirm: false,
current_subject: {
store_id: currentSubject.id,
company_name: currentSubject.company_name,
role: currentSubject.isWarehouse ? 'warehouse' : 'store',
},
counterparty: {
id: Number(counterparty.id || 0),
company_name: counterparty.company_name || '',
role: currentSubject.isWarehouse ? 'store' : 'warehouse',
},
},
};
}
/**
* 修改签约关系脱敏名称。
*
* @param {Object} [data={}] 请求参数。
* @return {Promise<Object>} 接口响应对象。
*/
async rename(data = {}) {
const { ctx } = this;
const transaction = await ctx.model.transaction();
try {
const currentSubject = await this.getCurrentSubject();
const relation = await this.findScopedRelation(data, currentSubject, transaction);
const relationPatch = this.requireCurrentRemaskPatch(data, currentSubject);
await relation.update(relationPatch, { transaction });
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
include: this.getRelationIncludes(),
transaction,
});
const qimenConfig = await this.getSingleQimenConfig(relation.id, {
allowDisabled: true,
transaction,
});
await transaction.commit();
// 记录操作日志
try {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'store',
businessId: relation.id,
operationCode: 'STORE_RENAME',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: Number(relation.warehouse_id || 0),
},
beforeChanges: null,
});
} catch (logErr) {
ctx.logger.warn('[storeWarehouse.rename] 写入操作日志失败,不影响业务', logErr);
}
return {
code: 200,
data: {
contract: this.serializeRelation(result, currentSubject, qimenConfig),
},
};
} catch (error) {
await transaction.rollback();
throw error;
}
}
/**
* 调整面单余额。
*
* @param {Object} [data={}] 请求参数。
* @return {Promise<Object>} 接口响应对象。
*/
async adjustPrintQuantity(data = {}) {
const { ctx } = this;
const transaction = await ctx.model.transaction();
try {
const currentSubject = await this.getCurrentSubject();
this.ensureWarehouseSubject(currentSubject, '面单余额');
const relation = await this.findScopedRelation(data, currentSubject, transaction);
const operatorId = this.getCurrentAccountId();
const targetQuantityField = [
[ 'print_quantity', data.print_quantity ],
[ 'target_quantity', data.target_quantity ],
[ 'change_quantity', data.change_quantity ],
[ 'adjust_quantity', data.adjust_quantity ],
].find(([ , value ]) => value !== undefined && value !== null && value !== '');
if (!targetQuantityField) {
throw this.createError('print_quantity / target_quantity / change_quantity / adjust_quantity 参数不能为空', 400);
}
const [ targetQuantityFieldName, targetQuantityRaw ] = targetQuantityField;
const targetQuantity = this.normalizeInteger(targetQuantityRaw, targetQuantityFieldName, { allowZero: true });
if (targetQuantity < 0) {
throw this.createError(`${targetQuantityFieldName} 参数不合法`, 400);
}
const reason = this.normalizeText(data.reason, 'reason', 500);
if (!reason) {
throw this.createError('reason 参数不能为空', 400);
}
const businessType = this.normalizeText(data.business_type, 'business_type', 50);
const businessId = data.business_id === undefined || data.business_id === null || data.business_id === ''
? null
: this.toPositiveNumber(data.business_id, 'business_id');
const balanceBefore = Number(relation.print_quantity || 0);
const balanceAfter = targetQuantity;
const changeQuantity = balanceAfter - balanceBefore;
await relation.update({
print_quantity: balanceAfter,
}, { transaction });
const changeLogRecord = await ctx.model.StoreWarehousePrintQuantityLog.create({
contract_id: Number(relation.id || 0),
store_id: Number(relation.store_id || 0),
warehouse_id: Number(relation.warehouse_id || 0),
change_type: 'manual_adjust',
business_type: businessType,
business_id: businessId,
change_quantity: changeQuantity,
balance_before: balanceBefore,
balance_after: balanceAfter,
reason,
operator_id: operatorId,
created_by: operatorId,
}, { transaction });
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
include: this.getRelationIncludes(),
transaction,
});
const qimenConfig = await this.getSingleQimenConfig(relation.id, {
allowDisabled: true,
transaction,
});
await transaction.commit();
const changeLog = changeLogRecord && typeof changeLogRecord.get === 'function'
? changeLogRecord.get({ plain: true })
: (changeLogRecord || {});
// 记录操作日志
try {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'store',
businessId: relation.id,
operationCode: 'STORE_ADJUST_PRINT_QUANTITY',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: Number(relation.warehouse_id || 0),
},
beforeChanges: null,
});
} catch (logErr) {
ctx.logger.warn('[storeWarehouse.adjustPrintQuantity] 写入操作日志失败,不影响业务', logErr);
}
await this.sendPrintQuantityAdjustNotice({
relation: result,
currentSubject,
changeLog,
operatorId,
changeQuantity,
balanceBefore,
balanceAfter,
reason,
}).catch(error => {
ctx.logger.warn(`[storeWarehouse.adjustPrintQuantity] 通知发送失败: ${error.message}`);
});
return {
code: 200,
data: {
contract: this.serializeRelation(result, currentSubject, qimenConfig),
change_log: {
id: Number(changeLog.id || 0),
contract_id: Number(changeLog.contract_id || relation.id || 0),
change_type: String(changeLog.change_type || 'manual_adjust'),
business_type: changeLog.business_type ? String(changeLog.business_type) : null,
business_id: changeLog.business_id !== undefined && changeLog.business_id !== null
? Number(changeLog.business_id)
: null,
change_quantity: Number(changeLog.change_quantity || 0),
balance_before: Number(changeLog.balance_before !== undefined ? changeLog.balance_before : balanceBefore),
balance_after: Number(changeLog.balance_after !== undefined ? changeLog.balance_after : balanceAfter),
reason: changeLog.reason || reason,
operator_id: Number(changeLog.operator_id || operatorId),
created_at: changeLog.created_at || null,
},
},
};
} catch (error) {
await transaction.rollback();
throw error;
}
}
/**
* 获取策略配置字段。
*
* @return {Promise<Object>} 接口响应对象。
*/
async getPolicyConfigFields() {
return {
code: 200,
data: await this.getPolicyConfigFieldMetaList(),
};
}
/**
* 获取签约策略配置。
*
* @param {Object} [data={}] 请求参数。
* @return {Promise<Object>} 接口响应对象。
*/
async getPolicyConfig(data = {}) {
const currentSubject = await this.getCurrentSubject();
const relation = await this.findScopedRelation(data, currentSubject);
const qimenConfig = await this.getSingleQimenConfig(relation.id, {
allowDisabled: true,
});
const policyConfig = await this.loadPolicyConfigByContractId(relation.id);
return {
code: 200,
data: {
contract_id: Number(relation.id || 0),
policy_config: policyConfig,
contract: this.serializeRelation(relation, currentSubject, qimenConfig),
},
};
}
/**
* 保存签约策略配置。
*
* @param {Object} [data={}] 请求参数。
* @return {Promise<Object>} 接口响应对象。
*/
async savePolicyConfig(data = {}) {
const { ctx } = this;
const transaction = await ctx.model.transaction();
try {
const currentSubject = await this.getCurrentSubject();
const relation = await this.findScopedRelation(data, currentSubject, transaction);
this.ensureWarehouseSubject(currentSubject, '签约策略配置');
const policyConfig = this.normalizePolicyConfig(
data.policy_config !== undefined ? data.policy_config : data.policy
);
await this.savePolicyConfigByContractId(relation.id, policyConfig, transaction);
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
include: this.getRelationIncludes(),
transaction,
});
const qimenConfig = await this.getSingleQimenConfig(relation.id, {
allowDisabled: true,
transaction,
});
await transaction.commit();
await this.invalidateContractConfigCache(relation.warehouse_id, relation.store_id).catch(() => null);
// 记录操作日志
try {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'store',
businessId: relation.id,
operationCode: 'STORE_SAVE_POLICY_CONFIG',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: Number(relation.warehouse_id || 0),
},
beforeChanges: null,
});
} catch (logErr) {
ctx.logger.warn('[storeWarehouse.savePolicyConfig] 写入操作日志失败,不影响业务', logErr);
}
return {
code: 200,
data: {
contract_id: Number(relation.id || 0),
policy_config: policyConfig,
contract: this.serializeRelation(result, currentSubject, qimenConfig),
},
};
} catch (error) {
await transaction.rollback();
throw error;
}
}
/**
* 查询接口配置列表。
*
* @param {Object} [data={}] 请求参数。
* @return {Promise<Object>} 接口响应对象。
*/
async listApiConfig(data = {}) {
const { ctx } = this;
const currentSubject = await this.getCurrentSubject();
const relation = await this.findScopedRelation(data, currentSubject);
const interfaceTypeId = this.toPositiveNumber(data.interface_type_id, 'interface_type_id', { allowEmpty: true });
const where = {
contract_id: Number(relation.id || 0),
};
if (interfaceTypeId) {
const interfaceType = await this.getApiInterfaceType({ interface_type_id: interfaceTypeId }, {
allowDisabled: true,
});
where.interface_type_id = Number(interfaceType.id || 0);
}
const rows = await ctx.model.ApiApp.findAll({
where,
include: [
{
model: ctx.model.InterfaceType,
as: 'interface_type',
attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ],
required: false,
},
],
order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
});
const list = rows.map(item => this.serializeQimenConfig(item));
const primaryApiConfig = list.length ? list[0] : null;
return {
code: 200,
data: {
contract_id: Number(relation.id || 0),
contract: this.serializeRelation(relation, currentSubject, primaryApiConfig),
list,
total: list.length,
},
};
}
/**
* 保存接口配置。
*
* @param {Object} [data={}] 请求参数。
* @return {Promise<Object>} 接口响应对象。
*/
async saveApiConfig(data = {}) {
const { ctx, app } = this;
const transaction = await ctx.model.transaction();
try {
const currentSubject = await this.getCurrentSubject();
const relation = await this.findScopedRelation(data, currentSubject, transaction);
this.ensureWarehouseSubject(currentSubject, '接口配置');
const interfaceType = await this.getApiInterfaceType(data, { transaction, requireId: true });
const isOpenApi = interfaceType.interface_category === 'OPEN_API';
const isQimenWms = interfaceType.interface_category === 'QM_WMS';
// 奇门相关字段:QM_WMS 必填,OPEN_API 不需要
let qimenAppKey = null;
let qimenCustomerId = null;
let qimenWarehouseCode = null;
if (isQimenWms) {
qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100);
if (!qimenAppKey) {
throw this.createError('奇门接口类型下 qimen_app_key 参数不能为空', 400);
}
qimenCustomerId = this.normalizeText(data.qimen_customer_id, 'qimen_customer_id', 100);
if (!qimenCustomerId) {
throw this.createError('奇门接口类型下 qimen_customer_id 参数不能为空', 400);
}
qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100);
if (!qimenWarehouseCode) {
throw this.createError('奇门接口类型下 qimen_warehouse_code 参数不能为空', 400);
}
} else {
// OPEN_API: 奇门字段可选输入
qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100) || null;
qimenCustomerId = this.normalizeText(data.qimen_customer_id, 'qimen_customer_id', 100) || null;
qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100) || null;
}
const appName = this.normalizeText(data.app_name, 'app_name', 200);
if (!appName) {
throw this.createError('app_name 参数不能为空', 400);
}
const apiVersion = this.normalizeText(data.api_version, 'api_version', 50) || '1.0';
const signMethod = (this.normalizeText(data.sign_method, 'sign_method', 50) || 'md5').toLowerCase();
if (![ 'md5', 'hmac', 'sha256' ].includes(signMethod)) {
throw this.createError('sign_method 参数不合法', 400);
}
const rateLimit = this.normalizeIntegerRange(data.rate_limit, 'rate_limit', 1000, 1, 100000);
const timeoutSeconds = this.normalizeIntegerRange(data.timeout_seconds, 'timeout_seconds', 30, 1, 300);
const contactPerson = this.normalizeText(data.contact_person, 'contact_person', 100);
const contactPhone = this.normalizeText(data.contact_phone, 'contact_phone', 20);
const email = this.normalizeEmail(data.email);
const isEnabled = this.normalizeStatusFlag(data.is_enabled, 'is_enabled', 1);
const where = {
interface_type_id: Number(interfaceType.id || 0),
contract_id: Number(relation.id || 0),
};
let config = await ctx.model.ApiApp.findOne({
where,
include: [
{
model: ctx.model.InterfaceType,
as: 'interface_type',
attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ],
required: false,
},
],
transaction,
});
const { Op } = app.Sequelize;
// 重复检测:按接口类型不同检查策略
let duplicateConfig = null;
if (isQimenWms && qimenAppKey && qimenCustomerId) {
const duplicateWhere = {
interface_type_id: Number(interfaceType.id || 0),
qimen_app_key: qimenAppKey,
qimen_customer_id: qimenCustomerId,
};
if (config && config.id) {
duplicateWhere.id = { [Op.ne]: config.id };
}
duplicateConfig = await ctx.model.ApiApp.findOne({
where: duplicateWhere,
attributes: [ 'id', 'contract_id' ],
transaction,
});
if (duplicateConfig) {
throw this.createError('该 AppKey 和客户ID 已绑定其他签约关系', 409);
}
}
// OPEN_API: 创建时自动生成 self_app_key 和 self_app_secret
let selfAppKey = null;
let selfAppSecret = null;
if (isOpenApi) {
if (config) {
// 更新时保留已有密钥
selfAppKey = config.self_app_key;
selfAppSecret = config.self_app_secret;
} else {
// 创建时生成新密钥
const crypto = require('crypto');
selfAppKey = `WMS${crypto.randomBytes(16).toString('hex').toUpperCase()}`;
selfAppSecret = crypto.randomBytes(32).toString('hex');
}
}
const configPayload = {
app_name: appName,
interface_type_id: Number(interfaceType.id || 0),
contract_id: Number(relation.id || 0),
warehouse_id: relation.warehouse_id ? Number(relation.warehouse_id) : null,
self_app_key: selfAppKey,
self_app_secret: selfAppSecret,
qimen_app_key: qimenAppKey,
qimen_customer_id: qimenCustomerId,
qimen_warehouse_code: qimenWarehouseCode,
api_version: apiVersion,
sign_method: signMethod,
rate_limit: rateLimit,
timeout_seconds: timeoutSeconds,
contact_person: contactPerson || null,
contact_phone: contactPhone || null,
email,
is_enabled: isEnabled,
};
const previousConfig = config ? this.serializeQimenConfig(config) : null;
const action = config ? 'update' : 'create';
if (config) {
await config.update(configPayload, { transaction });
} else {
config = await ctx.model.ApiApp.create(configPayload, { transaction });
}
const savedConfig = await ctx.model.ApiApp.findByPk(config.id, {
include: [
{
model: ctx.model.InterfaceType,
as: 'interface_type',
attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ],
required: false,
},
],
transaction,
});
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
include: this.getRelationIncludes(),
transaction,
});
const apiConfig = this.serializeQimenConfig(savedConfig);
await transaction.commit();
// 记录操作日志
try {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'store',
businessId: relation.id,
operationCode: 'STORE_SAVE_API_CONFIG',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: Number(relation.warehouse_id || 0),
},
beforeChanges: null,
});
} catch (logErr) {
ctx.logger.warn('[storeWarehouse.saveApiConfig] 写入操作日志失败,不影响业务', logErr);
}
await this.clearQimenContractCache([ previousConfig, apiConfig ]).catch(error => {
ctx.logger.warn('[storeWarehouse.saveApiConfig] 清理奇门缓存失败: %s', error.message);
});
return {
code: 200,
data: {
action,
contract: this.serializeRelation(result, currentSubject, apiConfig),
api_config: apiConfig,
apiConfig,
},
};
} catch (error) {
await transaction.rollback();
if (error && error.name === 'SequelizeUniqueConstraintError') {
throw this.createError('接口配置已存在,请检查应用名或 AppKey / 客户ID 是否重复', 409);
}
if (error && error.name === 'SequelizeValidationError') {
const message = error.errors && error.errors.length ? error.errors[0].message : '接口配置参数校验失败';
throw this.createError(message, 400);
}
throw error;
}
}
/**
* 删除奇门接口配置。
*
* @param {Object} [data={}] 请求参数。
* @return {Promise<Object>} 接口响应对象。
*/
async deleteQimenConfig(data = {}) {
const { ctx } = this;
const transaction = await ctx.model.transaction();
try {
const currentSubject = await this.getCurrentSubject();
const relation = await this.findScopedRelation(data, currentSubject, transaction);
this.ensureWarehouseSubject(currentSubject, '接口配置');
const interfaceType = await this.getApiInterfaceType(data, {
allowDisabled: true,
transaction,
});
const config = await ctx.model.ApiApp.findOne({
where: {
contract_id: Number(relation.id || 0),
interface_type_id: Number(interfaceType.id || 0),
},
include: [
{
model: ctx.model.InterfaceType,
as: 'interface_type',
attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ],
required: false,
},
],
transaction,
});
if (!config) {
throw this.createError('接口配置不存在', 404);
}
const removedConfig = this.serializeQimenConfig(config);
await config.destroy({ transaction });
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
include: this.getRelationIncludes(),
transaction,
});
await transaction.commit();
// 记录操作日志
try {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'store',
businessId: relation.id,
operationCode: 'STORE_DELETE_API_CONFIG',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: Number(relation.warehouse_id || 0),
},
beforeChanges: null,
});
} catch (logErr) {
ctx.logger.warn('[storeWarehouse.deleteQimenConfig] 写入操作日志失败,不影响业务', logErr);
}
await this.clearQimenContractCache([ removedConfig ]).catch(error => {
ctx.logger.warn('[storeWarehouse.deleteQimenConfig] 清理奇门缓存失败: %s', error.message);
});
return {
code: 200,
data: {
deleted: true,
contract: this.serializeRelation(result, currentSubject, null),
api_config: null,
apiConfig: null,
removed: removedConfig,
},
};
} catch (error) {
await transaction.rollback();
throw error;
}
}
/**
* 解绑签约关系。
*
* @param {Object} [data={}] 请求参数。
* @return {Promise<Object>} 接口响应对象。
*/
async unbind(data = {}) {
const { ctx } = this;
const transaction = await ctx.model.transaction();
try {
const currentSubject = await this.getCurrentSubject();
const relation = await this.findScopedRelation(data, currentSubject, transaction);
const nextUseStatus = this.normalizeStatusFlag(data.use_status, 'use_status', 0);
await relation.update({
use_status: nextUseStatus,
}, { transaction });
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
include: this.getRelationIncludes(),
transaction,
});
const qimenConfig = await this.getSingleQimenConfig(relation.id, {
allowDisabled: true,
transaction,
});
await transaction.commit();
// 记录操作日志
try {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'store',
businessId: relation.id,
operationCode: 'STORE_UNBIND',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: Number(relation.warehouse_id || 0),
},
beforeChanges: null,
});
} catch (logErr) {
ctx.logger.warn('[storeWarehouse.unbind] 写入操作日志失败,不影响业务', logErr);
}
return {
code: 200,
data: {
contract: this.serializeRelation(result, currentSubject, qimenConfig),
},
};
} catch (error) {
await transaction.rollback();
throw error;
}
}
/**
* 生成货主合约配置缓存键。
*
* @param {number|string} warehouseId 仓库 ID。
* @param {number|string} storeId 货主 ID。
* @return {string} 缓存键。
*/
getContractConfigCacheKey(warehouseId, storeId) {
return `store_warehouse:contract_config:${Number(warehouseId || 0)}:${Number(storeId || 0)}`;
}
/**
* 使货主合约配置缓存失效。
*
* @param {number|string} warehouseId 仓库 ID。
* @param {number|string} storeId 货主 ID。
* @return {Promise<void>} 无返回值。
*/
async invalidateContractConfigCache(warehouseId, storeId) {
const key = this.getContractConfigCacheKey(warehouseId, storeId);
try {
const cacheRedis = this.app.redis && this.app.redis.get && this.app.redis.get('cache');
if (cacheRedis && typeof cacheRedis.del === 'function') {
await cacheRedis.del(key);
return;
}
await this.app.setCacheAsync(key, null, 1);
} catch (error) {
this.ctx.logger.warn('[storeWarehouse.invalidateContractConfigCache] 缓存失效失败: %s', error.message);
}
}
/**
* 按仓库 ID 和货主 ID 读取合约配置,优先读缓存。
*
* 缓存在 savePolicyConfig 或合约状态变更后立即失效。
*
* @param {number|string} warehouseId 仓库 ID。
* @param {number|string} storeId 货主 ID。
* @return {Promise<Object|null>} 合约配置对象,不存在时返回 null。
*/
async getContractConfig(warehouseId, storeId) {
const normalizedWarehouseId = Number(warehouseId || 0);
const normalizedStoreId = Number(storeId || 0);
if (normalizedWarehouseId <= 0 || normalizedStoreId <= 0) {
return null;
}
const cacheKey = this.getContractConfigCacheKey(normalizedWarehouseId, normalizedStoreId);
try {
const cached = await this.app.getCacheAsync(cacheKey);
if (cached !== null && cached !== undefined) {
return cached;
}
} catch (error) {
this.ctx.logger.warn('[storeWarehouse.getContractConfig] 读取缓存失败: %s', error.message);
}
const row = await this.ctx.model.StoreWarehouse.findOne({
where: {
warehouse_id: normalizedWarehouseId,
store_id: normalizedStoreId,
},
attributes: [ 'id', 'store_id', 'warehouse_id', 'auth_status', 'policy_config' ],
raw: true,
});
if (!row) {
return null;
}
const config = {
id: row.id,
store_id: row.store_id,
warehouse_id: row.warehouse_id,
auth_status: row.auth_status,
policy_config: this.normalizePolicyConfig(row.policy_config, 'policy_config', {
allowEmpty: true,
sanitizeOnly: true,
}),
};
try {
await this.app.setCacheAsync(cacheKey, config, 600);
} catch (error) {
this.ctx.logger.warn('[storeWarehouse.getContractConfig] 写入缓存失败: %s', error.message);
}
return config;
}
}
module.exports = SettingStoreWarehouseService;