- app/model/store.js、app/service/systems/store.js、app/service/systems/store_warehouse.js:移除 logo_url/domain 字段定义与创建写入,app/ 下无残留引用 - database/migrations/20260907140000-drop-logo-url-and-domain-from-wms-store.js:删除 wms_store 的 logo_url、domain 两列(开发库已执行完成)
3626 lines
127 KiB
JavaScript
3626 lines
127 KiB
JavaScript
'use strict';
|
||
|
||
const crypto = require('node:crypto');
|
||
const fs = require('node:fs');
|
||
const fsp = require('node:fs/promises');
|
||
const os = require('node:os');
|
||
const path = require('node:path');
|
||
const ExcelJS = require('exceljs');
|
||
const Service = require('egg').Service;
|
||
const { Op } = require('sequelize');
|
||
|
||
const SIGN_TEMP_EXPIRE_SECONDS = 600;
|
||
const AUTH_STATUS_LABELS = Object.freeze({
|
||
1: '申请中',
|
||
2: '已通过',
|
||
3: '已拒绝',
|
||
4: '已解除',
|
||
5: '已过期',
|
||
});
|
||
|
||
const CHANGE_TYPE_LABEL_MAP = Object.freeze({
|
||
manual_adjust: '人工调整',
|
||
order_deduct: '订单扣减',
|
||
});
|
||
|
||
const BUSINESS_TYPE_LABEL_MAP = Object.freeze({
|
||
order_express: '快递订单',
|
||
});
|
||
|
||
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,
|
||
}
|
||
);
|
||
} else {
|
||
await this.app.setCacheAsync(this.getPolicyConfigCacheKey(normalizedId), policyConfig, 86400 * 30);
|
||
}
|
||
|
||
// 清除签约策略缓存(sw_policy:{storeId}:{warehouseId}):
|
||
// 该缓存内嵌 policy_config 快照与 allowOversell 判定,策略变更(如开启允许超卖)后必须失效,
|
||
// 否则奇门推送订单会继续读取旧快照,导致超卖开关生效前仍提示库存不足。
|
||
const relation = await this.ctx.model.StoreWarehouse.findByPk(normalizedId, {
|
||
attributes: [ 'store_id', 'warehouse_id' ],
|
||
raw: true,
|
||
});
|
||
if (relation) {
|
||
await this.app.delCacheAsync(`sw_policy:${relation.store_id}:${relation.warehouse_id}`);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 获取策略配置默认值。
|
||
*
|
||
* @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} 对方主体不存在时抛出,状态码为 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);
|
||
}
|
||
|
||
return counterparty;
|
||
}
|
||
|
||
/**
|
||
* 构建列表查询条件(按 store_id 维度)。
|
||
*
|
||
* 当前主体始终作为 store_id 方(货主方/消费方),对方为 warehouse_id 方(仓库方/提供方)。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @param {Object} currentSubject 当前主体。
|
||
* @return {Object} where 查询条件。
|
||
*/
|
||
buildListWhereByStoreId(data, currentSubject) {
|
||
const where = {
|
||
store_id: currentSubject.id,
|
||
};
|
||
|
||
const relationId = this.resolveRelationId(data);
|
||
if (relationId) {
|
||
where.id = relationId;
|
||
}
|
||
|
||
const counterpartyId = this.toPositiveNumber(data.counterparty_id || data.warehouse_id, 'counterparty_id', { allowEmpty: true });
|
||
if (counterpartyId) {
|
||
where.warehouse_id = counterpartyId;
|
||
}
|
||
|
||
const authStatus = this.normalizeAuthStatus(data.auth_status);
|
||
if (authStatus !== null) {
|
||
where.auth_status = authStatus;
|
||
}
|
||
|
||
const rawUseStatus = data.use_status !== undefined ? data.use_status : data.store_use_status;
|
||
const useStatus = this.normalizeStatusFlag(rawUseStatus, 'use_status', null);
|
||
if (useStatus !== null) {
|
||
where.store_use_status = useStatus;
|
||
}
|
||
|
||
return where;
|
||
}
|
||
|
||
/**
|
||
* 构建列表查询条件(兼容旧逻辑,保留以供其他方法使用)。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @param {Object} currentSubject 当前主体。
|
||
* @return {Object} where 查询条件。
|
||
* @deprecated 新代码请使用 buildListWhereByStoreId。
|
||
*/
|
||
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 rawUseStatus = data.use_status !== undefined ? data.use_status
|
||
: (data.warehouse_use_status !== undefined ? data.warehouse_use_status : data.store_use_status);
|
||
const useStatus = this.normalizeStatusFlag(rawUseStatus, 'use_status', null);
|
||
if (useStatus !== null) {
|
||
if (currentSubject.isWarehouse) {
|
||
where.warehouse_use_status = useStatus;
|
||
} else {
|
||
where.store_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);
|
||
}
|
||
|
||
/**
|
||
* 根据奇门 AppKey 解析客户标识。
|
||
*
|
||
* @param {string|null} qimenAppKey 奇门应用 AppKey。
|
||
* @param {Object} [options={}] 查询选项。
|
||
* @param {Object|null} [options.transaction=null] 事务对象。
|
||
* @return {Promise<string|null>} 命中的客户标识;未传 AppKey 时返回 null。
|
||
* @throws {Error} 当 AppKey 不存在或未配置 customer_id 时抛出,状态码为 400。
|
||
*/
|
||
async resolveQimenCustomerIdByAppKey(qimenAppKey, options = {}) {
|
||
const { ctx } = this;
|
||
const { transaction = null } = options;
|
||
const normalizedAppKey = this.normalizeText(qimenAppKey, 'qimen_app_key', 100);
|
||
if (!normalizedAppKey) {
|
||
return null;
|
||
}
|
||
|
||
const qimenApp = await ctx.model.QimenApp.findOne({
|
||
where: {
|
||
app_key: normalizedAppKey,
|
||
},
|
||
attributes: [ 'id', 'app_key', 'customer_id' ],
|
||
transaction,
|
||
});
|
||
|
||
if (!qimenApp) {
|
||
throw this.createError('未找到与 qimen_app_key 对应的奇门应用配置', 400);
|
||
}
|
||
|
||
const customerId = this.normalizeText(qimenApp.customer_id, 'customer_id', 100);
|
||
if (!customerId) {
|
||
throw this.createError('对应的奇门应用未配置 customer_id,无法保存接口配置', 400);
|
||
}
|
||
|
||
return customerId;
|
||
}
|
||
|
||
/**
|
||
* 根据奇门 AppKey 列表查询 ERP 名称映射。
|
||
*
|
||
* @param {Array<string>} appKeys 奇门 AppKey 列表。
|
||
* @param {Object} [options={}] 查询选项。
|
||
* @param {Object|null} [options.transaction=null] 事务对象。
|
||
* @return {Promise<Map<string, string>>} AppKey 到 ERP 名称的映射。
|
||
*/
|
||
async getQimenErpNameMapByAppKeys(appKeys = [], options = {}) {
|
||
const { ctx } = this;
|
||
const { transaction = null } = options;
|
||
const normalizedAppKeys = [ ...new Set(
|
||
appKeys
|
||
.map(value => this.normalizeText(value, 'qimen_app_key', 100, { allowEmpty: true }))
|
||
.filter(Boolean)
|
||
) ];
|
||
|
||
if (!normalizedAppKeys.length) {
|
||
return new Map();
|
||
}
|
||
|
||
const rows = await ctx.model.QimenApp.findAll({
|
||
where: {
|
||
app_key: normalizedAppKeys,
|
||
},
|
||
attributes: [ 'app_key', 'name' ],
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
|
||
return new Map(rows.map(item => [
|
||
String(item.app_key || ''),
|
||
String(item.name || ''),
|
||
]));
|
||
}
|
||
|
||
/**
|
||
* 序列化奇门配置。
|
||
*
|
||
* @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 || '',
|
||
erp_name: item.erp_name || item.erpName || '',
|
||
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。
|
||
*
|
||
* 规则:当前主体(签约发起方)始终为 store_id 方(货主方/消费方),
|
||
* 对方始终为 warehouse_id 方(仓库方/提供方)。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @param {Object} currentSubject 当前主体。
|
||
* @return {Object} 包含 storeId、warehouseId、counterpartyId 的对象。
|
||
* @throws {Error} 对方主体参数非法时抛出,状态码为 400。
|
||
*/
|
||
resolvePairIds(data, currentSubject) {
|
||
const rawCounterpartyId = data.counterparty_id !== undefined
|
||
? data.counterparty_id
|
||
: (data.store_id && Number(data.store_id) !== currentSubject.id ? data.store_id : data.warehouse_id);
|
||
const counterpartyId = this.toPositiveNumber(rawCounterpartyId, 'counterparty_id / 对方主体ID');
|
||
|
||
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 subjectId = currentSubject ? Number(currentSubject.id) : 0;
|
||
|
||
// 根据当前主体在 store_id 还是 warehouse_id 判定对方主体(兼容新旧签约数据)
|
||
const subjectIsStore = subjectId > 0 && subjectId === Number(item.store_id || 0);
|
||
const subjectIsWarehouse = subjectId > 0 && subjectId === Number(item.warehouse_id || 0);
|
||
const counterparty = subjectIsStore ? item.warehouse : item.store;
|
||
const counterpartyRole = counterparty && counterparty.project === 'warehouse' ? 'warehouse' : 'store';
|
||
|
||
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 = counterparty && counterparty.company_name ? counterparty.company_name : '';
|
||
|
||
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,
|
||
counterparty_role: counterpartyRole,
|
||
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: subjectIsWarehouse ? (item.store_remask || '') : (item.warehouse_remask || ''),
|
||
use_status: subjectIsWarehouse
|
||
? Number(item.warehouse_use_status || 0)
|
||
: Number(item.store_use_status || 0),
|
||
warehouse_use_status: Number(item.warehouse_use_status || 0),
|
||
store_use_status: Number(item.store_use_status || 0),
|
||
is_auth_valid: isAuthValid,
|
||
remaining_days: remainingDays,
|
||
api_config: normalizedQimenConfig || null,
|
||
apiConfig: normalizedQimenConfig || null,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 获取受限范围内的签约关系(兼容新旧签约数据)。
|
||
*
|
||
* 新数据:当前主体在 store_id(发起方/消费方)。
|
||
* 旧数据:仓库主体可能在 warehouse_id(提供方)。
|
||
* 使用 OR 查询两边,确保新旧数据都能被操作。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @param {Object} currentSubject 当前主体。
|
||
* @param {Object} transaction 事务对象。
|
||
* @return {Promise<Object>} 签约关系实例。
|
||
* @throws {Error} 签约关系不存在或无权限操作时抛出,状态码为 404。
|
||
*/
|
||
async findScopedRelation(data, currentSubject, transaction) {
|
||
const { ctx } = this;
|
||
const { Op } = ctx.app.Sequelize;
|
||
|
||
const scopedWhere = {};
|
||
|
||
const relationId = this.resolveRelationId(data);
|
||
if (relationId) {
|
||
scopedWhere.id = relationId;
|
||
} else {
|
||
const pair = this.resolvePairIds(data, currentSubject);
|
||
scopedWhere.store_id = pair.storeId;
|
||
scopedWhere.warehouse_id = pair.warehouseId;
|
||
}
|
||
|
||
const relation = await ctx.model.StoreWarehouse.findOne({
|
||
where: {
|
||
...scopedWhere,
|
||
[Op.or]: [
|
||
{ store_id: currentSubject.id },
|
||
{ warehouse_id: currentSubject.id },
|
||
],
|
||
},
|
||
include: this.getRelationIncludes(),
|
||
transaction,
|
||
});
|
||
|
||
if (!relation) {
|
||
throw this.createError('签约关系不存在或无权限操作', 404);
|
||
}
|
||
|
||
return relation;
|
||
}
|
||
|
||
/**
|
||
* 构建货主侧签约列表查询条件(仓库在 warehouse_id 方,对方货主在 store_id 方)。
|
||
*
|
||
* 供 listForStore / exportListForStore 复用,保证列表与导出的筛选语义一致。
|
||
*
|
||
* @param {Object} data 请求参数。
|
||
* @param {Object} currentSubject 当前主体。
|
||
* @return {Object} where 查询条件。
|
||
*/
|
||
buildListForStoreWhere(data = {}, currentSubject) {
|
||
const { Op } = this.app.Sequelize;
|
||
|
||
// 仓库查看自己签约的货主列表:仓库在 warehouse_id 方,货主在 store_id 方
|
||
const where = {
|
||
warehouse_id: currentSubject.id,
|
||
};
|
||
|
||
const relationId = this.resolveRelationId(data);
|
||
if (relationId) {
|
||
where.id = relationId;
|
||
}
|
||
|
||
const counterpartyId = this.toPositiveNumber(data.counterparty_id || data.store_id, 'counterparty_id', { allowEmpty: true });
|
||
if (counterpartyId) {
|
||
// 对方(货主)在 store_id 方
|
||
where.store_id = counterpartyId;
|
||
}
|
||
|
||
const authStatus = this.normalizeAuthStatus(data.auth_status);
|
||
if (authStatus !== null) {
|
||
where.auth_status = authStatus;
|
||
}
|
||
|
||
const rawUseStatus = data.use_status !== undefined ? data.use_status : data.warehouse_use_status;
|
||
if (rawUseStatus !== undefined && rawUseStatus !== null && rawUseStatus !== '') {
|
||
where.warehouse_use_status = Number(rawUseStatus);
|
||
}
|
||
|
||
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}%` } },
|
||
];
|
||
}
|
||
|
||
return where;
|
||
}
|
||
|
||
/**
|
||
* 货主侧查询签约关系列表(兼容新旧签约数据)。
|
||
*
|
||
* 使用 OR 查询 store_id / warehouse_id 两边,确保新旧签约数据都能被正确展示。
|
||
*
|
||
* @param {Object} [data={}] 请求参数。
|
||
* @return {Promise<Object>} 接口响应对象。
|
||
*/
|
||
async listForStore(data = {}) {
|
||
const { ctx } = this;
|
||
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;
|
||
|
||
// 仓库查看自己签约的货主列表:仓库在 warehouse_id 方,货主在 store_id 方
|
||
const where = this.buildListForStoreWhere(data, currentSubject);
|
||
|
||
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);
|
||
serialized.has_qimen_config = qimenConfigMap.has(serialized.id);
|
||
return {
|
||
id: serialized.id,
|
||
store_id: serialized.store_id,
|
||
warehouse_id: serialized.warehouse_id,
|
||
counterparty_id: serialized.counterparty_id,
|
||
counterparty_name: serialized.counterparty_name,
|
||
counterparty_role: serialized.counterparty_role,
|
||
remask: serialized.remask,
|
||
use_status: serialized.use_status,
|
||
auth_status: serialized.auth_status,
|
||
auth_status_label: serialized.auth_status_label,
|
||
auth_end: serialized.auth_end,
|
||
print_quantity: serialized.print_quantity,
|
||
has_qimen_config: serialized.has_qimen_config,
|
||
needs_my_confirm: Number(item.auth_status || 0) === 1
|
||
&& Number(item.initiator_subject_id || 0) !== currentSubject.id,
|
||
};
|
||
}),
|
||
total: Number(count || 0),
|
||
page,
|
||
page_size: pageSize,
|
||
current_subject: {
|
||
store_id: currentSubject.id,
|
||
company_name: currentSubject.company_name,
|
||
role: currentSubject.isWarehouse ? 'warehouse' : 'store',
|
||
},
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 导出货主侧签约列表(与 storeWarehouse.store.list / listForStore 筛选语义一致)。
|
||
*
|
||
* 全量查询当前主体(仓库在 warehouse_id 方)可见的签约关系,生成 Excel 上传至 COS。
|
||
* 忽略分页参数,复用 buildListForStoreWhere 的筛选条件;每行输出与 listForStore 对齐的
|
||
* 序列化字段(含 has_qimen_config、needs_my_confirm),并对角色/启用状态/有效性等做中文展示。
|
||
*
|
||
* @param {Object} [data={}] 请求参数(与 listForStore 一致,page/page_size 被忽略)。
|
||
* @return {Promise<Object>} 包含 filename、fileKey、url、cdnUrl、cosUrl、total_count 的对象。
|
||
*/
|
||
async exportListForStore(data = {}) {
|
||
const { ctx } = this;
|
||
const currentSubject = await this.getCurrentSubject();
|
||
const where = this.buildListForStoreWhere(data, currentSubject);
|
||
|
||
// 全量查询所有匹配记录(不翻页),与列表使用相同关联与排序
|
||
const rows = await ctx.model.StoreWarehouse.findAll({
|
||
where,
|
||
include: this.getRelationIncludes(),
|
||
order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
|
||
});
|
||
|
||
// 奇门配置映射(与列表一致)
|
||
const contractIds = rows.map(item => Number(item.id || 0)).filter(id => id > 0);
|
||
const qimenConfigMap = contractIds.length
|
||
? await this.getQimenConfigMap(contractIds)
|
||
: new Map();
|
||
|
||
// 生成 Excel
|
||
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'store_relation_export_'));
|
||
const filename = `货主签约列表_${currentSubject.id}_${Date.now()}.xlsx`;
|
||
const filePath = path.join(tempDir, filename);
|
||
|
||
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
|
||
filename: filePath,
|
||
useStyles: true,
|
||
useSharedStrings: true,
|
||
});
|
||
const worksheet = workbook.addWorksheet('货主签约列表');
|
||
|
||
worksheet.columns = [
|
||
{ header: '签约关系ID', key: 'id', width: 14 },
|
||
{ header: '货主ID', key: 'store_id', width: 10 },
|
||
{ header: '货主名称', key: 'store_name', width: 24 },
|
||
{ header: '仓库ID', key: 'warehouse_id', width: 10 },
|
||
{ header: '仓库名称', key: 'warehouse_name', width: 24 },
|
||
{ header: '对方主体ID', key: 'counterparty_id', width: 12 },
|
||
{ header: '对方主体名称', key: 'counterparty_name', width: 24 },
|
||
{ header: '对方主体角色', key: 'counterparty_role_label', width: 12 },
|
||
{ header: '备注名', key: 'remask', width: 20 },
|
||
{ header: '当前视角启用状态', key: 'use_status_label', width: 16 },
|
||
{ header: '货主侧启用状态', key: 'store_use_status_label', width: 16 },
|
||
{ header: '仓库侧启用状态', key: 'warehouse_use_status_label', width: 16 },
|
||
{ header: '签约状态', key: 'auth_status_label', width: 12 },
|
||
{ header: '签约是否有效', key: 'is_auth_valid_label', width: 14 },
|
||
{ header: '剩余有效天数', key: 'remaining_days', width: 14 },
|
||
{ header: '面单余额', key: 'print_quantity', width: 12 },
|
||
{ header: '锁定面单余额', key: 'print_quantity_locked', width: 14 },
|
||
{ header: '授权开始时间', key: 'auth_start', width: 22 },
|
||
{ header: '授权结束时间', key: 'auth_end', width: 22 },
|
||
{ header: '实际结束时间', key: 'actual_end', width: 22 },
|
||
{ header: '申请时间', key: 'apply_time', width: 22 },
|
||
{ header: '审核时间', key: 'review_time', width: 22 },
|
||
{ header: '申请原因', key: 'apply_reason', width: 30 },
|
||
{ header: '审核评语', key: 'review_comment', width: 30 },
|
||
{ header: '是否已配置奇门', key: 'has_qimen_config_label', width: 16 },
|
||
{ header: '是否需要我确认', key: 'needs_my_confirm_label', width: 16 },
|
||
];
|
||
|
||
const roleLabel = role => {
|
||
if (role === 'warehouse') return '仓库';
|
||
if (role === 'store') return '货主';
|
||
return role ? String(role) : '';
|
||
};
|
||
const statusLabel = value => (Number(value) === 1 ? '启用' : '禁用');
|
||
const yesNoLabel = value => (value ? '是' : '否');
|
||
|
||
for (const item of rows) {
|
||
const serialized = this.serializeRelation(item, currentSubject);
|
||
const hasQimenConfig = qimenConfigMap.has(serialized.id);
|
||
worksheet.addRow({
|
||
id: serialized.id,
|
||
store_id: serialized.store_id,
|
||
store_name: serialized.store_name || '',
|
||
warehouse_id: serialized.warehouse_id,
|
||
warehouse_name: serialized.warehouse_name || '',
|
||
counterparty_id: serialized.counterparty_id,
|
||
counterparty_name: serialized.counterparty_name || '',
|
||
counterparty_role_label: roleLabel(serialized.counterparty_role),
|
||
remask: serialized.remask || '',
|
||
use_status_label: statusLabel(serialized.use_status),
|
||
store_use_status_label: statusLabel(serialized.store_use_status),
|
||
warehouse_use_status_label: statusLabel(serialized.warehouse_use_status),
|
||
auth_status_label: serialized.auth_status_label || '',
|
||
is_auth_valid_label: yesNoLabel(serialized.is_auth_valid),
|
||
remaining_days: serialized.remaining_days,
|
||
print_quantity: serialized.print_quantity,
|
||
print_quantity_locked: serialized.print_quantity_locked,
|
||
auth_start: serialized.auth_start ? String(serialized.auth_start) : '',
|
||
auth_end: serialized.auth_end ? String(serialized.auth_end) : '',
|
||
actual_end: serialized.actual_end ? String(serialized.actual_end) : '',
|
||
apply_time: serialized.apply_time ? String(serialized.apply_time) : '',
|
||
review_time: serialized.review_time ? String(serialized.review_time) : '',
|
||
apply_reason: serialized.apply_reason || '',
|
||
review_comment: serialized.review_comment || '',
|
||
has_qimen_config_label: yesNoLabel(hasQimenConfig),
|
||
needs_my_confirm_label: yesNoLabel(
|
||
Number(item.auth_status || 0) === 1
|
||
&& Number(item.initiator_subject_id || 0) !== currentSubject.id
|
||
),
|
||
}).commit();
|
||
}
|
||
|
||
worksheet.commit();
|
||
await workbook.commit();
|
||
|
||
// 上传至 COS
|
||
const uploadService = ctx.service && ctx.service.systems && ctx.service.systems.upload;
|
||
let uploadResult = {};
|
||
if (uploadService && typeof uploadService.uploadFile === 'function') {
|
||
const stat = await fsp.stat(filePath);
|
||
const uploadStream = fs.createReadStream(filePath);
|
||
uploadStream.filename = filename;
|
||
uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
|
||
uploadStream.fileSize = stat.size;
|
||
|
||
uploadResult = await uploadService.uploadFile(uploadStream, {
|
||
key: `export/store_relation/${currentSubject.id}/${filename}`,
|
||
category: 'document',
|
||
mimetype: 'xls,xlsx,csv',
|
||
});
|
||
|
||
if (typeof uploadService.uploadSuccessNotify === 'function') {
|
||
await uploadService.uploadSuccessNotify({
|
||
url: uploadResult.fileName,
|
||
fileKey: uploadResult.fileName,
|
||
fileName: filename,
|
||
fileType: 'document',
|
||
mimeType: uploadStream.mimeType,
|
||
fileSize: stat.size,
|
||
category: 'document',
|
||
businessType: 'storeRelationListExport',
|
||
businessId: String(currentSubject.id),
|
||
uploaderType: ctx.user?.role || 'system_api',
|
||
uploaderDept: ctx.user?.department || '',
|
||
}).catch(err => {
|
||
ctx.logger.warn('[storeWarehouse.exportListForStore] 上传通知失败: %s', err.message);
|
||
});
|
||
}
|
||
}
|
||
|
||
// 清理临时文件
|
||
try {
|
||
await fsp.rm(tempDir, { recursive: true, force: true });
|
||
} catch (cleanErr) {
|
||
ctx.logger.warn('[storeWarehouse.exportListForStore] 清理临时文件失败: %s', cleanErr.message);
|
||
}
|
||
|
||
return {
|
||
filename,
|
||
fileKey: uploadResult.fileName || '',
|
||
url: uploadResult.url || uploadResult.cdnUrl || uploadResult.cosUrl || '',
|
||
cdnUrl: uploadResult.cdnUrl || uploadResult.url || '',
|
||
cosUrl: uploadResult.cosUrl || '',
|
||
total_count: rows.length,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 仓库侧查询签约关系列表(兼容新旧签约数据)。
|
||
*
|
||
* 使用 OR 查询 store_id / warehouse_id 两边,确保新旧签约数据都能被正确展示。
|
||
* 支持查询仓库与外部合作仓库的关系。
|
||
*
|
||
* @param {Object} [data={}] 请求参数。
|
||
* @return {Promise<Object>} 接口响应对象。
|
||
*/
|
||
async listForWarehouse(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;
|
||
|
||
// 货主查看自己签约的仓库列表:货主在 store_id 方,仓库在 warehouse_id 方
|
||
const where = {
|
||
store_id: currentSubject.id,
|
||
};
|
||
|
||
const relationId = this.resolveRelationId(data);
|
||
if (relationId) {
|
||
where.id = relationId;
|
||
}
|
||
|
||
const counterpartyId = this.toPositiveNumber(data.counterparty_id || data.warehouse_id, 'counterparty_id', { allowEmpty: true });
|
||
if (counterpartyId) {
|
||
// 对方(仓库)在 warehouse_id 方
|
||
where.warehouse_id = counterpartyId;
|
||
}
|
||
|
||
const authStatus = this.normalizeAuthStatus(data.auth_status);
|
||
if (authStatus !== null) {
|
||
where.auth_status = authStatus;
|
||
}
|
||
|
||
const rawUseStatus = data.use_status !== undefined ? data.use_status : data.store_use_status;
|
||
if (rawUseStatus !== undefined && rawUseStatus !== null && rawUseStatus !== '') {
|
||
where.store_use_status = Number(rawUseStatus);
|
||
}
|
||
|
||
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);
|
||
serialized.has_qimen_config = qimenConfigMap.has(serialized.id);
|
||
return {
|
||
id: serialized.id,
|
||
store_id: serialized.store_id,
|
||
store_name: serialized.store_name,
|
||
warehouse_id: serialized.warehouse_id,
|
||
warehouse_name: serialized.warehouse_name,
|
||
counterparty_id: serialized.counterparty_id,
|
||
counterparty_name: serialized.counterparty_name,
|
||
counterparty_role: serialized.counterparty_role,
|
||
remask: serialized.remask,
|
||
use_status: serialized.store_use_status,
|
||
auth_status: serialized.auth_status,
|
||
auth_status_label: serialized.auth_status_label,
|
||
auth_end: serialized.auth_end,
|
||
print_quantity: serialized.print_quantity,
|
||
has_qimen_config: serialized.has_qimen_config,
|
||
needs_my_confirm: Number(item.auth_status || 0) === 1
|
||
&& Number(item.initiator_subject_id || 0) !== currentSubject.id,
|
||
};
|
||
}),
|
||
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>} 接口响应对象。
|
||
* @deprecated 新代码请使用 listForStore 或 listForWarehouse。
|
||
*/
|
||
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);
|
||
serialized.has_qimen_config = qimenConfigMap.has(serialized.id);
|
||
return {
|
||
id: serialized.id,
|
||
store_id: serialized.store_id,
|
||
warehouse_id: serialized.warehouse_id,
|
||
counterparty_name: serialized.counterparty_name,
|
||
remask: serialized.remask,
|
||
use_status: serialized.use_status,
|
||
auth_status: serialized.auth_status,
|
||
auth_status_label: serialized.auth_status_label,
|
||
auth_end: serialized.auth_end,
|
||
print_quantity: serialized.print_quantity,
|
||
has_qimen_config: serialized.has_qimen_config,
|
||
needs_my_confirm: Number(item.auth_status || 0) === 1
|
||
&& Number(item.initiator_subject_id || 0) !== currentSubject.id,
|
||
};
|
||
}),
|
||
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 (action === 'preview') {
|
||
const currentSubject = await this.getCurrentSubject();
|
||
const pair = this.resolvePairIds(data, currentSubject);
|
||
const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse');
|
||
return {
|
||
code: 200,
|
||
data: {
|
||
mode: 'preview',
|
||
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: counterparty.project === 'warehouse' ? 'warehouse' : 'store',
|
||
},
|
||
},
|
||
};
|
||
}
|
||
|
||
const { ctx } = this;
|
||
const transaction = await ctx.model.transaction();
|
||
|
||
try {
|
||
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 relationPatch = {
|
||
store_id: pair.storeId,
|
||
warehouse_id: pair.warehouseId,
|
||
auth_status: 1,
|
||
apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000),
|
||
apply_time: new Date(),
|
||
print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0),
|
||
review_time: null,
|
||
auth_start: authStart,
|
||
auth_end: authEnd,
|
||
actual_end: null,
|
||
applied_by: accountId,
|
||
reviewed_by: null,
|
||
ended_by: null,
|
||
initiator_subject_id: currentSubject.id,
|
||
warehouse_use_status: 1,
|
||
store_use_status: 1,
|
||
print_quantity_locked: 0,
|
||
};
|
||
|
||
Object.assign(relationPatch, this.buildCurrentRemaskPatch(data, currentSubject));
|
||
|
||
let relation = await ctx.model.StoreWarehouse.findOne({
|
||
where: {
|
||
store_id: pair.storeId,
|
||
warehouse_id: pair.warehouseId,
|
||
},
|
||
transaction,
|
||
});
|
||
const isCreate = !relation;
|
||
|
||
if (relation) {
|
||
if (relation.applied_by === accountId && relation.auth_status === 1) {
|
||
await relation.update(relationPatch, { transaction });
|
||
} else if (relation.applied_by === accountId && relation.auth_status >= 2) {
|
||
const existing = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction });
|
||
await transaction.rollback();
|
||
return {
|
||
code: 200,
|
||
data: {
|
||
mode: 'already_confirmed',
|
||
exists_status: relation.auth_status,
|
||
exists_status_label: '已签约',
|
||
contract: this.trimContract(this.serializeRelation(existing, currentSubject)),
|
||
},
|
||
};
|
||
} else {
|
||
const existing = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction });
|
||
await transaction.rollback();
|
||
return {
|
||
code: 200,
|
||
data: {
|
||
mode: 'already_exists',
|
||
exists_status: relation.auth_status,
|
||
exists_status_label: relation.auth_status === 2 ? '已签约' : '待确认',
|
||
contract: this.trimContract(this.serializeRelation(existing, currentSubject)),
|
||
},
|
||
};
|
||
}
|
||
} else {
|
||
relation = await ctx.model.StoreWarehouse.create(relationPatch, { transaction });
|
||
}
|
||
|
||
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
|
||
include: this.getRelationIncludes(),
|
||
transaction,
|
||
});
|
||
|
||
const wasExisting = !!relation._previousDataValues;
|
||
|
||
await transaction.commit();
|
||
|
||
return {
|
||
code: 200,
|
||
data: {
|
||
mode: 'initiate',
|
||
contract: this.trimContract(this.serializeRelation(result, currentSubject)),
|
||
action: isCreate ? 'create' : 'update',
|
||
},
|
||
};
|
||
} catch (error) {
|
||
await transaction.rollback();
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 精简签约对象,仅保留前端需要的字段。
|
||
* @param serialized
|
||
*/
|
||
trimContract(serialized) {
|
||
return {
|
||
id: serialized.id,
|
||
store_id: serialized.store_id,
|
||
warehouse_id: serialized.warehouse_id,
|
||
counterparty_name: serialized.counterparty_name,
|
||
remask: serialized.remask,
|
||
use_status: serialized.use_status,
|
||
auth_status: serialized.auth_status,
|
||
auth_status_label: serialized.auth_status_label,
|
||
auth_end: serialized.auth_end,
|
||
print_quantity: serialized.print_quantity,
|
||
has_qimen_config: serialized.has_qimen_config,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 确认签约:对方主体确认待签约的申请,状态从 1(申请中)变为 2(已通过)。
|
||
* 发起方不能确认自己的申请。
|
||
*
|
||
* @param {Object} [data={}] 请求参数。
|
||
* @param {number} data.id 签约关系ID。
|
||
* @return {Promise<Object>} 接口响应对象。
|
||
*/
|
||
async confirmSign(data = {}) {
|
||
const { ctx } = this;
|
||
const transaction = await ctx.model.transaction();
|
||
|
||
try {
|
||
const currentSubject = await this.getCurrentSubject();
|
||
const accountId = this.getCurrentAccountId();
|
||
const relationId = this.resolveRelationId(data);
|
||
|
||
if (!relationId) {
|
||
throw this.createError('id 参数不能为空', 400);
|
||
}
|
||
|
||
const relation = await ctx.model.StoreWarehouse.findOne({
|
||
where: { id: relationId },
|
||
include: this.getRelationIncludes(),
|
||
transaction,
|
||
});
|
||
|
||
if (!relation) {
|
||
throw this.createError('签约关系不存在', 404);
|
||
}
|
||
|
||
if (relation.auth_status !== 1) {
|
||
throw this.createError('当前签约状态不允许确认,仅待签约状态可确认', 400);
|
||
}
|
||
|
||
// 确定当前主体在签约中的角色
|
||
const isCurrentStore = relation.store_id === currentSubject.id;
|
||
const isCurrentWarehouse = relation.warehouse_id === currentSubject.id;
|
||
|
||
if (!isCurrentStore && !isCurrentWarehouse) {
|
||
throw this.createError('当前主体不在此签约关系中', 403);
|
||
}
|
||
|
||
// 发起签约的主体不能确认自己的申请,必须由对方主体确认
|
||
if (relation.initiator_subject_id === currentSubject.id) {
|
||
throw this.createError('发起方不能确认自己的签约申请', 403);
|
||
}
|
||
|
||
await relation.update({
|
||
auth_status: 2,
|
||
review_time: new Date(),
|
||
reviewed_by: accountId,
|
||
}, { transaction });
|
||
|
||
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
|
||
include: this.getRelationIncludes(),
|
||
transaction,
|
||
});
|
||
|
||
await transaction.commit();
|
||
|
||
return {
|
||
code: 200,
|
||
data: {
|
||
mode: 'confirm',
|
||
contract: this.trimContract(this.serializeRelation(result, currentSubject)),
|
||
},
|
||
};
|
||
} catch (error) {
|
||
await transaction.rollback();
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 修改签约关系脱敏名称。
|
||
*
|
||
* @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;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 按货主查询面单余额变更日志(分页)。
|
||
*
|
||
* @param {Object} [data={}] 请求参数。
|
||
* @param {number|string} data.store_id 货主 ID。
|
||
* @param {Object} [data.where] 动态筛选条件。
|
||
* @param {Object} [data.pagination] 分页对象。
|
||
* @param {number|string} [data.pagination.page] 页码。
|
||
* @param {number|string} [data.pagination.page_size] 每页条数。
|
||
* @return {Promise<Object>} 接口响应对象。
|
||
*/
|
||
async queryPrintQuantityLogs(data = {}) {
|
||
const { ctx } = this;
|
||
const currentSubject = await this.getCurrentSubject();
|
||
const storeId = this.toPositiveNumber(data.store_id, 'store_id');
|
||
const pagination = data.pagination && typeof data.pagination === 'object'
|
||
? data.pagination
|
||
: {};
|
||
const page = this.normalizePage(pagination.page, 'page', 1, 1000000);
|
||
const pageSize = this.normalizePage(pagination.page_size, 'page_size', 20, 200);
|
||
const offset = (page - 1) * pageSize;
|
||
|
||
if (!currentSubject.isWarehouse && Number(currentSubject.id) !== Number(storeId)) {
|
||
throw this.createError('仅可查询当前货主的面单余额变更日志', 403);
|
||
}
|
||
|
||
const where = {
|
||
store_id: Number(storeId),
|
||
};
|
||
|
||
if (currentSubject.isWarehouse) {
|
||
where.warehouse_id = Number(currentSubject.id);
|
||
}
|
||
|
||
const dynamicConditions = this.ctx.whereParsed && Array.isArray(this.ctx.whereParsed.dynamicConditions)
|
||
? this.ctx.whereParsed.dynamicConditions.filter(Boolean)
|
||
: [];
|
||
|
||
if (dynamicConditions.length > 0) {
|
||
where[Op.and] = dynamicConditions;
|
||
}
|
||
|
||
const { rows, count } = await ctx.model.StoreWarehousePrintQuantityLog.findAndCountAll({
|
||
where,
|
||
order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]],
|
||
offset,
|
||
limit: pageSize,
|
||
});
|
||
|
||
// 收集所有需要回填姓名的操作人 ID
|
||
const accountIdSet = new Set();
|
||
for (const item of rows) {
|
||
const payload = item && typeof item.get === 'function'
|
||
? item.get({ plain: true })
|
||
: (item || {});
|
||
if (payload.operator_id) accountIdSet.add(Number(payload.operator_id));
|
||
if (payload.created_by) accountIdSet.add(Number(payload.created_by));
|
||
}
|
||
const accountIds = Array.from(accountIdSet).filter(id => Number.isFinite(id) && id > 0);
|
||
|
||
// 批量查询账号姓名
|
||
const accountNameMap = {};
|
||
if (accountIds.length > 0) {
|
||
try {
|
||
const accounts = await ctx.model.Account.findAll({
|
||
attributes: [ 'id', 'real_name' ],
|
||
where: { id: { [Op.in]: accountIds } },
|
||
raw: true,
|
||
});
|
||
for (const acc of accounts) {
|
||
accountNameMap[Number(acc.id)] = acc.real_name || '';
|
||
}
|
||
} catch (err) {
|
||
ctx.logger.warn('[queryPrintQuantityLogs] 批量查询操作人姓名失败,不影响主流程: %s', err.message);
|
||
}
|
||
}
|
||
|
||
const total = Number(count || 0);
|
||
const totalPages = total > 0 ? Math.ceil(total / pageSize) : 0;
|
||
|
||
return {
|
||
code: 200,
|
||
data: {
|
||
list: rows.map(item => {
|
||
const payload = item && typeof item.get === 'function'
|
||
? item.get({ plain: true })
|
||
: (item || {});
|
||
|
||
const operatorId = payload.operator_id !== undefined && payload.operator_id !== null
|
||
? Number(payload.operator_id)
|
||
: null;
|
||
const createdBy = payload.created_by !== undefined && payload.created_by !== null
|
||
? Number(payload.created_by)
|
||
: null;
|
||
|
||
return {
|
||
id: Number(payload.id || 0),
|
||
contract_id: Number(payload.contract_id || 0),
|
||
store_id: Number(payload.store_id || 0),
|
||
warehouse_id: Number(payload.warehouse_id || 0),
|
||
change_type: payload.change_type ? String(payload.change_type) : '',
|
||
change_type_label: CHANGE_TYPE_LABEL_MAP[payload.change_type] || payload.change_type || '',
|
||
business_type: payload.business_type ? String(payload.business_type) : null,
|
||
business_type_label: payload.business_type
|
||
? (BUSINESS_TYPE_LABEL_MAP[payload.business_type] || payload.business_type)
|
||
: '-',
|
||
business_id: payload.business_id !== undefined && payload.business_id !== null
|
||
? Number(payload.business_id)
|
||
: null,
|
||
change_quantity: Number(payload.change_quantity || 0),
|
||
balance_before: Number(payload.balance_before || 0),
|
||
balance_after: Number(payload.balance_after || 0),
|
||
reason: payload.reason || '',
|
||
operator_id: operatorId,
|
||
operator_name: operatorId ? (accountNameMap[operatorId] || '') : '',
|
||
created_by: createdBy,
|
||
created_by_name: createdBy ? (accountNameMap[createdBy] || '') : '',
|
||
created_at: payload.created_at || null,
|
||
updated_at: payload.updated_at || null,
|
||
};
|
||
}),
|
||
pagination: {
|
||
page,
|
||
pageSize,
|
||
total,
|
||
totalPages,
|
||
hasPrevious: page > 1,
|
||
hasNext: totalPages > 0 && page < totalPages,
|
||
},
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 导出面单余额变更日志。
|
||
* 查询所有匹配条件的记录,生成 Excel 文件上传至 COS,返回下载信息。
|
||
*
|
||
* @param {Object} data 请求数据。
|
||
* @param {number|string} data.store_id 货主ID(必填)。
|
||
* @param {Object} [data.where] 动态筛选条件,与 queryPrintQuantityLogs 的 where 语义一致。
|
||
* @return {Promise<Object>} 包含 url、fileKey、filename 的对象。
|
||
*/
|
||
async exportPrintQuantityLogs(data = {}) {
|
||
const { ctx } = this;
|
||
const currentSubject = await this.getCurrentSubject();
|
||
const storeId = this.toPositiveNumber(data.store_id, 'store_id');
|
||
|
||
if (!currentSubject.isWarehouse && Number(currentSubject.id) !== Number(storeId)) {
|
||
throw this.createError('仅可导出当前货主的面单余额变更日志', 403);
|
||
}
|
||
|
||
const where = {
|
||
store_id: Number(storeId),
|
||
};
|
||
|
||
if (currentSubject.isWarehouse) {
|
||
where.warehouse_id = Number(currentSubject.id);
|
||
}
|
||
|
||
const dynamicConditions = this.ctx.whereParsed && Array.isArray(this.ctx.whereParsed.dynamicConditions)
|
||
? this.ctx.whereParsed.dynamicConditions.filter(Boolean)
|
||
: [];
|
||
|
||
if (dynamicConditions.length > 0) {
|
||
where[Op.and] = dynamicConditions;
|
||
}
|
||
|
||
// 查询全部匹配记录
|
||
const rows = await ctx.model.StoreWarehousePrintQuantityLog.findAll({
|
||
where,
|
||
order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]],
|
||
raw: true,
|
||
});
|
||
|
||
// 收集操作人 ID,批量查询姓名
|
||
const accountIdSet = new Set();
|
||
for (const item of rows) {
|
||
if (item.operator_id) accountIdSet.add(Number(item.operator_id));
|
||
if (item.created_by) accountIdSet.add(Number(item.created_by));
|
||
}
|
||
const accountIds = Array.from(accountIdSet).filter(id => Number.isFinite(id) && id > 0);
|
||
const accountNameMap = {};
|
||
if (accountIds.length > 0) {
|
||
const accounts = await ctx.model.Account.findAll({
|
||
attributes: [ 'id', 'real_name' ],
|
||
where: { id: { [Op.in]: accountIds } },
|
||
raw: true,
|
||
});
|
||
for (const acc of accounts) {
|
||
accountNameMap[Number(acc.id)] = acc.real_name || '';
|
||
}
|
||
}
|
||
|
||
// 生成 Excel
|
||
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'print_qty_log_export_'));
|
||
const filename = `面单余额变更日志_${storeId}_${Date.now()}.xlsx`;
|
||
const filePath = path.join(tempDir, filename);
|
||
|
||
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
|
||
filename: filePath,
|
||
useStyles: true,
|
||
useSharedStrings: true,
|
||
});
|
||
const worksheet = workbook.addWorksheet('面单余额变更日志');
|
||
|
||
worksheet.columns = [
|
||
{ header: '记录ID', key: 'id', width: 10 },
|
||
{ header: '签约关系ID', key: 'contract_id', width: 14 },
|
||
{ header: '货主ID', key: 'store_id', width: 10 },
|
||
{ header: '仓库ID', key: 'warehouse_id', width: 10 },
|
||
{ header: '变更类型', key: 'change_type_label', width: 12 },
|
||
{ header: '业务来源类型', key: 'business_type_label', width: 14 },
|
||
{ header: '业务关联ID', key: 'business_id', width: 14 },
|
||
{ header: '变更数量', key: 'change_quantity', width: 12 },
|
||
{ header: '变更前余额', key: 'balance_before', width: 14 },
|
||
{ header: '变更后余额', key: 'balance_after', width: 14 },
|
||
{ header: '变更原因', key: 'reason', width: 30 },
|
||
{ header: '操作人', key: 'operator_name', width: 14 },
|
||
{ header: '创建人', key: 'created_by_name', width: 14 },
|
||
{ header: '创建时间', key: 'created_at', width: 22 },
|
||
{ header: '更新时间', key: 'updated_at', width: 22 },
|
||
];
|
||
|
||
for (const item of rows) {
|
||
const operatorId = item.operator_id !== undefined && item.operator_id !== null
|
||
? Number(item.operator_id)
|
||
: null;
|
||
const createdBy = item.created_by !== undefined && item.created_by !== null
|
||
? Number(item.created_by)
|
||
: null;
|
||
|
||
worksheet.addRow({
|
||
id: Number(item.id || 0),
|
||
contract_id: Number(item.contract_id || 0),
|
||
store_id: Number(item.store_id || 0),
|
||
warehouse_id: Number(item.warehouse_id || 0),
|
||
change_type_label: CHANGE_TYPE_LABEL_MAP[item.change_type] || item.change_type || '',
|
||
business_type_label: item.business_type
|
||
? (BUSINESS_TYPE_LABEL_MAP[item.business_type] || item.business_type)
|
||
: '-',
|
||
business_id: item.business_id !== undefined && item.business_id !== null
|
||
? Number(item.business_id)
|
||
: '',
|
||
change_quantity: Number(item.change_quantity || 0),
|
||
balance_before: Number(item.balance_before || 0),
|
||
balance_after: Number(item.balance_after || 0),
|
||
reason: item.reason || '',
|
||
operator_name: operatorId ? (accountNameMap[operatorId] || '') : '',
|
||
created_by_name: createdBy ? (accountNameMap[createdBy] || '') : '',
|
||
created_at: item.created_at ? String(item.created_at) : '',
|
||
updated_at: item.updated_at ? String(item.updated_at) : '',
|
||
}).commit();
|
||
}
|
||
|
||
worksheet.commit();
|
||
await workbook.commit();
|
||
|
||
// 上传至 COS
|
||
const uploadService = ctx.service && ctx.service.systems && ctx.service.systems.upload;
|
||
let uploadResult = {};
|
||
if (uploadService && typeof uploadService.uploadFile === 'function') {
|
||
const stat = await fsp.stat(filePath);
|
||
const uploadStream = fs.createReadStream(filePath);
|
||
uploadStream.filename = filename;
|
||
uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
|
||
uploadStream.fileSize = stat.size;
|
||
|
||
uploadResult = await uploadService.uploadFile(uploadStream, {
|
||
key: `export/print_quantity_log/${storeId}/${filename}`,
|
||
category: 'document',
|
||
mimetype: 'xls,xlsx,csv',
|
||
});
|
||
|
||
if (typeof uploadService.uploadSuccessNotify === 'function') {
|
||
await uploadService.uploadSuccessNotify({
|
||
url: uploadResult.fileName,
|
||
fileKey: uploadResult.fileName,
|
||
fileName: filename,
|
||
fileType: 'document',
|
||
mimeType: uploadStream.mimeType,
|
||
fileSize: stat.size,
|
||
category: 'document',
|
||
businessType: 'printQuantityLogExport',
|
||
businessId: String(storeId),
|
||
uploaderType: ctx.user?.role || 'system_api',
|
||
uploaderDept: ctx.user?.department || '',
|
||
}).catch(err => {
|
||
ctx.logger.warn('[storeWarehouse.exportPrintQuantityLogs] 上传通知失败: %s', err.message);
|
||
});
|
||
}
|
||
}
|
||
|
||
// 清理临时文件
|
||
try {
|
||
await fsp.rm(tempDir, { recursive: true, force: true });
|
||
} catch (cleanErr) {
|
||
ctx.logger.warn('[storeWarehouse.exportPrintQuantityLogs] 清理临时文件失败: %s', cleanErr.message);
|
||
}
|
||
|
||
return {
|
||
filename,
|
||
fileKey: uploadResult.fileName || '',
|
||
url: uploadResult.url || uploadResult.cdnUrl || uploadResult.cosUrl || '',
|
||
cdnUrl: uploadResult.cdnUrl || uploadResult.url || '',
|
||
cosUrl: uploadResult.cosUrl || '',
|
||
total_count: rows.length,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 获取策略配置字段。
|
||
*
|
||
* @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.getEffectivePolicyConfigByContractId(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 effectivePolicyConfig = this.mergePolicyConfigWithDefaults(policyConfig);
|
||
|
||
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: effectivePolicyConfig,
|
||
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 qimenAppKeys = rows
|
||
.map(item => {
|
||
const plainItem = item && typeof item.get === 'function'
|
||
? item.get({ plain: true })
|
||
: item;
|
||
const interfaceCategory = plainItem?.interface_type?.interface_category || plainItem?.interface_category || '';
|
||
if (interfaceCategory !== 'QM_WMS') {
|
||
return null;
|
||
}
|
||
return plainItem?.qimen_app_key || null;
|
||
})
|
||
.filter(Boolean);
|
||
const qimenErpNameMap = await this.getQimenErpNameMapByAppKeys(qimenAppKeys);
|
||
|
||
const list = rows.map(item => {
|
||
const plainItem = item && typeof item.get === 'function'
|
||
? item.get({ plain: true })
|
||
: item;
|
||
const interfaceCategory = plainItem?.interface_type?.interface_category || plainItem?.interface_category || '';
|
||
const erpName = interfaceCategory === 'QM_WMS'
|
||
? (qimenErpNameMap.get(String(plainItem?.qimen_app_key || '')) || '')
|
||
: '';
|
||
|
||
return this.serializeQimenConfig({
|
||
...plainItem,
|
||
erp_name: erpName,
|
||
});
|
||
});
|
||
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;
|
||
|
||
// 外部入参优先,未传入时才从 qimen_app 表解析
|
||
const externalCustomerId = this.normalizeText(data.qimen_customer_id, 'qimen_customer_id', 100);
|
||
|
||
if (isQimenWms) {
|
||
qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100);
|
||
if (!qimenAppKey) {
|
||
throw this.createError('奇门接口类型下 qimen_app_key 参数不能为空', 400);
|
||
}
|
||
qimenCustomerId = externalCustomerId || await this.resolveQimenCustomerIdByAppKey(qimenAppKey, { transaction });
|
||
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 = externalCustomerId
|
||
|| (qimenAppKey ? await this.resolveQimenCustomerIdByAppKey(qimenAppKey, { transaction }) : 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 && qimenWarehouseCode) {
|
||
const duplicateWhere = {
|
||
interface_type_id: Number(interfaceType.id || 0),
|
||
qimen_app_key: qimenAppKey,
|
||
qimen_warehouse_code: qimenWarehouseCode,
|
||
};
|
||
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 和仓库编码 已绑定其他签约关系', 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,
|
||
callback_url: this.normalizeText(data.callback_url || data.callbackUrl, 'callback_url', 500) || null,
|
||
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 / 仓库编码 是否重复', 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 !== undefined ? data.use_status : data.warehouse_use_status,
|
||
'warehouse_use_status', 0);
|
||
const patch = currentSubject.isWarehouse
|
||
? { warehouse_use_status: nextUseStatus }
|
||
: { store_use_status: nextUseStatus };
|
||
|
||
await relation.update(patch, { 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 rawPolicyConfig = this.normalizePolicyConfig(row.policy_config, 'policy_config', {
|
||
allowEmpty: true,
|
||
sanitizeOnly: true,
|
||
});
|
||
const config = {
|
||
id: row.id,
|
||
store_id: row.store_id,
|
||
warehouse_id: row.warehouse_id,
|
||
auth_status: row.auth_status,
|
||
policy_config: this.mergePolicyConfigWithDefaults(rawPolicyConfig),
|
||
};
|
||
|
||
try {
|
||
await this.app.setCacheAsync(cacheKey, config, 600);
|
||
} catch (error) {
|
||
this.ctx.logger.warn('[storeWarehouse.getContractConfig] 写入缓存失败: %s', error.message);
|
||
}
|
||
|
||
return config;
|
||
}
|
||
|
||
/**
|
||
* 仓库代货主一键开户:注册账号、创建货主、签约三步合并。
|
||
*
|
||
* @param {Object} [data={}] 请求参数。
|
||
* @param {string} data.username 必填,登录账号。
|
||
* @param {string} data.password 必填,初始密码。
|
||
* @param {string} [data.real_name] 可选,真实姓名。
|
||
* @param {string} data.company_name 必填,公司全称。
|
||
* @param {string} data.business_license 必填,营业执照号。
|
||
* @param {string} data.contact_person 必填,联系人。
|
||
* @param {string} data.contact_phone 必填,联系电话。
|
||
* @param {string} [data.legal_person] 可选,法人代表。
|
||
* @param {string} [data.contact_email] 可选,联系邮箱。
|
||
* @param {string} [data.address] 可选,公司地址。
|
||
* @param {string} [data.industry] 可选,所属行业。
|
||
* @param {string} [data.auth_start] 可选,授权开始日期,默认当天。
|
||
* @param {string} [data.auth_end] 可选,授权结束日期。
|
||
* @param {number} [data.print_quantity=0] 可选,初始面单余额。
|
||
* @param {string} [data.apply_reason='仓库代开户'] 可选,申请原因。
|
||
* @param {string} [data.store_remask] 可选,货主备注名(≤50字符);不传或为空时默认取公司全称(截断 50 字符)填充。
|
||
* @param {string} [data.warehouse_remask] 可选,仓库备注名(≤50字符)。
|
||
* @return {Promise<Object>} 包含 store_id、account_id、contract_id、company_name、username 的响应对象。
|
||
* @throws {Error} 当前主体不是仓库时抛出 403,账号/公司名重复时抛出 409,参数校验失败时抛出 400。
|
||
*/
|
||
async openAccount(data = {}) {
|
||
const { ctx } = this;
|
||
|
||
// 1. 获取当前主体,必须是仓库
|
||
const currentSubject = await this.getCurrentSubject();
|
||
if (!currentSubject.isWarehouse) {
|
||
throw this.createError('仅仓库主体可执行代开户操作', 403);
|
||
}
|
||
|
||
// 2. 获取当前账号 ID
|
||
const accountId = this.getCurrentAccountId();
|
||
|
||
// 3. 密码自动生成
|
||
if (!data.password) {
|
||
data.password = crypto.randomBytes(8).toString('base64').replace(/[+/=]/g, '')
|
||
.slice(0, 12);
|
||
}
|
||
|
||
// 4. 必填字段校验
|
||
const requiredFields = [ 'username', 'company_name', 'contact_person' ];
|
||
for (const field of requiredFields) {
|
||
if (!data[field]) {
|
||
throw this.createError(`${field} 参数不能为空`, 400);
|
||
}
|
||
}
|
||
|
||
// 5. 公司名称唯一性校验
|
||
const existingStore = await ctx.model.Store.findOne({
|
||
where: { company_name: data.company_name },
|
||
});
|
||
if (existingStore) {
|
||
throw this.createError('公司名称已存在', 409);
|
||
}
|
||
|
||
// 6. 账号唯一性校验
|
||
const existingAccount = await ctx.model.Account.findOne({
|
||
where: { username: data.username },
|
||
});
|
||
if (existingAccount) {
|
||
throw this.createError('账号已存在', 409);
|
||
}
|
||
|
||
// 7. 备注长度校验
|
||
const storeRemask = this.normalizeText(data.store_remask, 'store_remask', 50);
|
||
const warehouseRemask = this.normalizeText(data.warehouse_remask, 'warehouse_remask', 50);
|
||
|
||
// 8. 规范化日期
|
||
const authStart = this.normalizeDate(data.auth_start, 'auth_start', { allowNull: true }) || new Date();
|
||
const authEnd = this.normalizeDate(data.auth_end, 'auth_end', { allowNull: true });
|
||
|
||
// 9. 在事务中依次执行注册、创建货主、签约
|
||
const transaction = await ctx.model.transaction();
|
||
|
||
try {
|
||
// a. 创建账号
|
||
// email 兜底:不传时生成占位邮箱,避免 Account model 的 notEmpty + isEmail 校验报错
|
||
const email = data.contact_email
|
||
? data.contact_email
|
||
: `${data.username}@placeholder.local`;
|
||
// real_name 兜底:不传时使用 contact_person(必填字段,长度 ≥ 2),避免 notEmpty + len[2,50] 校验报错
|
||
const realName = data.real_name || data.contact_person;
|
||
|
||
const registerResult = await ctx.service.systems.auth.user.register({
|
||
username: data.username,
|
||
password: data.password,
|
||
email,
|
||
real_name: realName,
|
||
}, transaction);
|
||
const userId = registerResult.userId;
|
||
|
||
// b. 创建货主
|
||
const storeData = {
|
||
company_name: data.company_name,
|
||
business_license: data.business_license,
|
||
legal_person: data.legal_person || null,
|
||
contact_phone: data.contact_phone || '-',
|
||
contact_email: data.contact_email || null,
|
||
contact_person: data.contact_person,
|
||
address: data.address || null,
|
||
industry: data.industry || null,
|
||
account_id: userId,
|
||
status: 1,
|
||
created_by: accountId,
|
||
is_warehouse: 0,
|
||
auth_end: authEnd,
|
||
};
|
||
|
||
const store = await ctx.model.Store.create(storeData, { transaction });
|
||
|
||
// c. 创建签约关系(auth_status=2 已通过,仓库代开户无需审核)
|
||
const relationData = {
|
||
store_id: store.id,
|
||
warehouse_id: currentSubject.id,
|
||
auth_status: 2,
|
||
apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000) || '仓库代开户',
|
||
apply_time: new Date(),
|
||
print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0),
|
||
print_quantity_locked: 0,
|
||
review_time: new Date(),
|
||
auth_start: authStart,
|
||
auth_end: authEnd,
|
||
actual_end: null,
|
||
applied_by: accountId,
|
||
reviewed_by: accountId,
|
||
ended_by: null,
|
||
warehouse_use_status: 1,
|
||
store_use_status: 1,
|
||
};
|
||
|
||
// store_remask 兜底:代开户未传货主备注名(或传空)时,默认取公司全称前 50 字符,
|
||
// 保证货主名称(签约表 store_remask 优先)在列表/导出中始终有值,与项目回退 company_name 口径一致
|
||
relationData.store_remask = storeRemask
|
||
? storeRemask
|
||
: String(store.company_name || '').slice(0, 50);
|
||
if (warehouseRemask !== null) {
|
||
relationData.warehouse_remask = warehouseRemask;
|
||
}
|
||
|
||
const relation = await ctx.model.StoreWarehouse.create(relationData, { transaction });
|
||
|
||
// d. 分配货主管理员角色
|
||
try {
|
||
await ctx.service.systems.store.assignAdminRoleToCreator(
|
||
store.id,
|
||
userId,
|
||
data.real_name || '',
|
||
transaction,
|
||
true
|
||
);
|
||
} catch (roleErr) {
|
||
throw this.createError(`分配管理员角色失败: ${roleErr.message}`, 500);
|
||
}
|
||
|
||
await transaction.commit();
|
||
|
||
// 记录操作日志
|
||
try {
|
||
await ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'store',
|
||
businessId: relation.id,
|
||
operationCode: 'STORE_OPEN_ACCOUNT',
|
||
operator: {
|
||
id: ctx.user?.employees_id || ctx.user?.id,
|
||
name: ctx.user?.employees_name || '',
|
||
},
|
||
extras: {
|
||
warehouseId: Number(currentSubject.id),
|
||
storeId: Number(store.id),
|
||
accountId: Number(userId),
|
||
},
|
||
beforeChanges: null,
|
||
});
|
||
} catch (logErr) {
|
||
ctx.logger.warn('[storeWarehouse.openAccount] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
return {
|
||
code: 200,
|
||
data: {
|
||
store_id: store.id,
|
||
account_id: userId,
|
||
contract_id: relation.id,
|
||
company_name: store.company_name,
|
||
username: data.username,
|
||
},
|
||
};
|
||
} catch (error) {
|
||
await transaction.rollback();
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 为货主创建用户:按用户名查询账号,不存在则注册账号并返回随机生成的密码,
|
||
* 两种情况统一完成货主工号绑定与货主管理员角色(wms_role.id=5)授权,幂等执行。
|
||
* 货主审核中(wms_store.status=2)时自动转为启用(1)。
|
||
*
|
||
* @param {Object} [data={}] 请求参数。
|
||
* @param {string} data.username 用户名(必填,3-50 位字母、数字或下划线)。
|
||
* @param {number|string} data.store_id 货主 ID(必填)。
|
||
* @return {Promise<Object>} 响应对象,data 包含 account_id、username、store_id、created;
|
||
* 仅新建账号时返回 password 明文密码。
|
||
* @throws {Error} 参数缺失或格式非法时抛出 400,货主不存在时抛出 404,
|
||
* 货主管理员角色未初始化时抛出 500。
|
||
*/
|
||
async createUser(data = {}) {
|
||
const { ctx } = this;
|
||
const {
|
||
username: rawUsername,
|
||
store_id: rawStoreId,
|
||
} = data;
|
||
|
||
// 1. 校验必填参数
|
||
const username = this.normalizeText(rawUsername, 'username', 50);
|
||
if (!username) {
|
||
throw this.createError('username 参数不能为空', 400);
|
||
}
|
||
if (!/^[a-zA-Z0-9_]{3,50}$/.test(username)) {
|
||
throw this.createError('用户名格式不合法,需为 3-50 位字母、数字或下划线', 400);
|
||
}
|
||
const storeId = this.toPositiveNumber(rawStoreId, 'store_id');
|
||
|
||
// 2. 校验货主存在(同时取 status 用于后续审核中状态修正)
|
||
const store = await ctx.model.Store.findOne({
|
||
where: { id: storeId },
|
||
attributes: [ 'id', 'status' ],
|
||
});
|
||
if (!store) {
|
||
throw this.createError('货主不存在', 404);
|
||
}
|
||
|
||
// 3. 查询账号是否存在
|
||
const existingAccount = await ctx.model.Account.findOne({
|
||
where: { username },
|
||
attributes: [ 'id', 'username' ],
|
||
});
|
||
|
||
// 4. 随机生成密码(仅新建账号时使用)
|
||
const randomPassword = crypto.randomBytes(8).toString('base64').replace(/[+/=]/g, '')
|
||
.slice(0, 12);
|
||
|
||
// 5. 事务内执行账号创建与授权绑定
|
||
const transaction = await ctx.model.transaction();
|
||
|
||
try {
|
||
// 5.0 货主审核中(status=2)时自动转为启用(1),store 实例在事务外查询,更新时显式传入事务
|
||
if (Number(store.status) === 2) {
|
||
await store.update({ status: 1 }, { transaction });
|
||
}
|
||
|
||
let accountId = null;
|
||
let created = false;
|
||
|
||
if (existingAccount) {
|
||
// 账号已存在:不创建、不返回密码
|
||
accountId = Number(existingAccount.id);
|
||
created = false;
|
||
} else {
|
||
// 账号不存在:复用注册服务,email/real_name 使用占位兜底
|
||
const registerResult = await ctx.service.systems.auth.user.register({
|
||
username,
|
||
password: randomPassword,
|
||
email: `${username}@placeholder.local`,
|
||
real_name: username,
|
||
}, transaction);
|
||
accountId = Number(registerResult.userId);
|
||
created = true;
|
||
}
|
||
|
||
// 6. 货主工号绑定(幂等:已存在但 status=0 时恢复为 1)
|
||
const [ employee ] = await ctx.model.AccountStoreEmployee.findOrCreate({
|
||
where: {
|
||
account_id: accountId,
|
||
store_id: storeId,
|
||
},
|
||
defaults: {
|
||
account_id: accountId,
|
||
store_id: storeId,
|
||
status: 1,
|
||
real_name: username,
|
||
},
|
||
transaction,
|
||
});
|
||
|
||
if (Number(employee.status) !== 1) {
|
||
await employee.update({
|
||
status: 1,
|
||
}, { transaction });
|
||
}
|
||
|
||
// 7. 确认货主管理员角色(wms_role.id=5)已初始化
|
||
const storeAdminRole = await ctx.model.Role.findByPk(5, { transaction });
|
||
if (!storeAdminRole) {
|
||
throw this.createError('货主管理员角色(id=5)未初始化', 500);
|
||
}
|
||
|
||
// 8. 授予货主管理员角色(幂等:findOrCreate)
|
||
await ctx.model.EmployeeRole.findOrCreate({
|
||
where: {
|
||
employee_id: employee.id,
|
||
role_id: 5,
|
||
},
|
||
defaults: {
|
||
employee_id: employee.id,
|
||
role_id: 5,
|
||
},
|
||
transaction,
|
||
});
|
||
|
||
await transaction.commit();
|
||
|
||
// 9. 记录操作日志(不影响业务主流程)
|
||
try {
|
||
await ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'store',
|
||
businessId: storeId,
|
||
operationCode: 'STORE_CREATE_USER',
|
||
operator: {
|
||
id: ctx.user?.employees_id || ctx.user?.id,
|
||
name: ctx.user?.employees_name || '',
|
||
},
|
||
extras: {
|
||
storeId: Number(storeId),
|
||
accountId: Number(accountId),
|
||
created,
|
||
},
|
||
beforeChanges: null,
|
||
});
|
||
} catch (logErr) {
|
||
ctx.logger.warn('[storeWarehouse.createUser] 写入操作日志失败,不影响业务', logErr);
|
||
}
|
||
|
||
// 10. 组装响应:仅新建账号时返回明文密码
|
||
const resultData = {
|
||
account_id: accountId,
|
||
username,
|
||
store_id: storeId,
|
||
created,
|
||
};
|
||
if (created) {
|
||
resultData.password = randomPassword;
|
||
}
|
||
|
||
return {
|
||
code: 200,
|
||
data: resultData,
|
||
};
|
||
} catch (error) {
|
||
await transaction.rollback();
|
||
throw error;
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = SettingStoreWarehouseService;
|