WMS_MAIN/app/service/systems/store_warehouse.js
2026-04-09 01:36:49 +08:00

1730 lines
59 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

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

'use strict';
const crypto = require('node:crypto');
const Service = require('egg').Service;
const SIGN_TEMP_EXPIRE_SECONDS = 600;
const AUTH_STATUS_LABELS = Object.freeze({
1: '申请中',
2: '已通过',
3: '已拒绝',
4: '已解除',
5: '已过期',
});
class SettingStoreWarehouseService extends Service {
createError(message, code = 500) {
const error = new Error(message);
error.code = code;
return error;
}
getCurrentStoreId() {
const storeId = Number(this.ctx.user && this.ctx.user.store_id);
if (!Number.isFinite(storeId) || storeId <= 0) {
throw this.createError('未识别到当前主体,无法操作签约关系', 400);
}
return storeId;
}
getCurrentAccountId() {
const accountId = Number(this.ctx.user && this.ctx.user.id);
if (!Number.isFinite(accountId) || accountId <= 0) {
throw this.createError('未识别到当前登录账号', 401);
}
return accountId;
}
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;
}
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);
}
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);
}
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);
}
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);
}
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;
}
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;
}
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);
}
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;
}
getPolicyConfigFieldList() {
const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse;
if (!storeWarehouseModel || typeof storeWarehouseModel.getPolicyConfigFieldList !== 'function') {
return [];
}
return storeWarehouseModel.getPolicyConfigFieldList();
}
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);
}
}
getPolicyConfigCacheKey(contractId) {
return `store_warehouse:policy:${contractId}`;
}
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;
}
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,
});
}
async savePolicyConfigByContractId(contractId, policyConfig, transaction = null) {
const normalizedId = Number(contractId || 0);
if (normalizedId <= 0) {
throw this.createError('id 参数不能为空', 400);
}
if (await this.hasPolicyConfigColumn()) {
await this.app.model.query(
'UPDATE wms_store_warehouse SET policy_config = :policy_config, updated_at = NOW() WHERE id = :id',
{
replacements: {
id: normalizedId,
policy_config: JSON.stringify(policyConfig),
},
transaction,
}
);
return;
}
await this.app.setCacheAsync(this.getPolicyConfigCacheKey(normalizedId), policyConfig, 86400 * 30);
}
ensureWarehouseSubject(currentSubject, actionLabel = '签约配置') {
if (!currentSubject || !currentSubject.isWarehouse) {
throw this.createError(`仅仓库主体可维护${actionLabel}`, 403);
}
}
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;
}
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,
},
});
}
resolveRelationId(data = {}) {
return this.toPositiveNumber(
data.id !== undefined ? data.id : (data.contract_id !== undefined ? data.contract_id : data.relation_id),
'id',
{ allowEmpty: true }
);
}
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;
}
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);
}
normalizeTempCode(value) {
const code = String(value || '').trim().toUpperCase();
if (!code) {
throw this.createError('temp_code 参数不能为空', 400);
}
return code;
}
getTempCodeCacheKey(tempCode) {
return `store_warehouse:sign:${tempCode}`;
}
createTempCode() {
return crypto.randomBytes(6).toString('hex').toUpperCase();
}
pickRemaskField(currentSubject) {
return currentSubject && currentSubject.isWarehouse ? 'store_remask' : 'warehouse_remask';
}
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);
}
buildCurrentRemaskPatch(data, currentSubject) {
const remask = this.resolveRemaskValue(data, currentSubject);
if (remask === null) {
return {};
}
return {
[this.pickRemaskField(currentSubject)]: remask,
};
}
requireCurrentRemaskPatch(data, currentSubject) {
const patch = this.buildCurrentRemaskPatch(data, currentSubject);
if (!Object.keys(patch).length) {
throw this.createError('remask 参数不能为空', 400);
}
return patch;
}
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,
};
}
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,
};
}
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);
}
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 || '',
},
};
}
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),
};
}
async getCounterparty(counterpartyId, expectedRole) {
const { ctx } = this;
const counterparty = await ctx.model.Store.findOne({
where: {
id: counterpartyId,
},
attributes: [ 'id', 'company_name', 'project', 'status' ],
});
if (!counterparty) {
throw this.createError('签约对象不存在', 404);
}
const isWarehouse = counterparty.project === 'warehouse';
if (expectedRole === 'warehouse' && !isWarehouse) {
throw this.createError('目标对象不是仓库主体,无法签约', 400);
}
if (expectedRole === 'store' && isWarehouse) {
throw this.createError('目标对象不是货主主体,无法签约', 400);
}
return counterparty;
}
buildListWhere(data, currentSubject) {
const where = {};
if (currentSubject.isWarehouse) {
where.warehouse_id = currentSubject.id;
} else {
where.store_id = currentSubject.id;
}
const relationId = this.resolveRelationId(data);
if (relationId) {
where.id = relationId;
}
const rawCounterpartyId = data.counterparty_id !== undefined
? data.counterparty_id
: (currentSubject.isWarehouse ? data.store_id : data.warehouse_id);
const counterpartyId = this.toPositiveNumber(rawCounterpartyId, 'counterparty_id', { allowEmpty: true });
if (counterpartyId) {
if (currentSubject.isWarehouse) {
where.store_id = counterpartyId;
} else {
where.warehouse_id = counterpartyId;
}
}
const authStatus = this.normalizeAuthStatus(data.auth_status);
if (authStatus !== null) {
where.auth_status = authStatus;
}
const useStatus = this.normalizeStatusFlag(data.use_status, 'use_status', null);
if (useStatus !== null) {
where.use_status = useStatus;
}
return where;
}
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,
},
];
}
getQimenContractCacheKey(appKey, customerId, warehouseCode) {
return `contract:${appKey}:${customerId}:${warehouseCode}`;
}
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)));
}
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;
}
async getQimenInterfaceType(data = {}, options = {}) {
return this.getApiInterfaceType(data, options);
}
serializeQimenConfig(config) {
if (!config) {
return null;
}
const item = config && typeof config.get === 'function'
? config.get({ plain: true })
: config;
const interfaceType = item.interface_type || {};
return {
id: Number(item.id || 0),
interface_type_id: Number(item.interface_type_id || 0),
interface_code: interfaceType.interface_code || item.interface_code || '',
interface_name: interfaceType.interface_name || item.interface_name || '',
interface_category: interfaceType.interface_category || item.interface_category || '',
contract_id: Number(item.contract_id || 0),
warehouse_id: item.warehouse_id ? Number(item.warehouse_id) : null,
app_name: item.app_name || '',
self_app_key: item.self_app_key || '',
self_app_secret: item.self_app_secret || '',
qimen_app_key: item.qimen_app_key || '',
qimen_customer_id: item.qimen_customer_id || '',
qimen_warehouse_code: item.qimen_warehouse_code || '',
api_version: item.api_version || '',
sign_method: item.sign_method || '',
rate_limit: Number(item.rate_limit || 0),
timeout_seconds: Number(item.timeout_seconds || 0),
contact_person: item.contact_person || '',
contact_phone: item.contact_phone || '',
email: item.email || '',
is_enabled: Number(item.is_enabled || 0),
created_at: item.created_at || null,
updated_at: item.updated_at || null,
callback_url: item.callback_url || '',
};
}
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;
}
async getSingleQimenConfig(contractId, options = {}) {
const configMap = await this.getQimenConfigMap([ contractId ], options);
return configMap.get(Number(contractId)) || null;
}
resolvePairIds(data, currentSubject) {
const fieldName = currentSubject.isWarehouse ? 'store_id / counterparty_id' : 'warehouse_id / counterparty_id';
const rawCounterpartyId = data.counterparty_id !== undefined
? data.counterparty_id
: (currentSubject.isWarehouse ? data.store_id : data.warehouse_id);
const counterpartyId = this.toPositiveNumber(rawCounterpartyId, fieldName);
if (currentSubject.isWarehouse) {
return {
storeId: counterpartyId,
warehouseId: currentSubject.id,
counterpartyId,
};
}
return {
storeId: currentSubject.id,
warehouseId: counterpartyId,
counterpartyId,
};
}
serializeRelation(relation, currentSubject, qimenConfig = null) {
const item = relation && typeof relation.get === 'function'
? relation.get({ plain: true })
: (relation || {});
const normalizedQimenConfig = qimenConfig !== null
? qimenConfig
: (item.qimen_config ? this.serializeQimenConfig(item.qimen_config) : null);
const authStatus = Number(item.auth_status || 0);
const currentIsWarehouse = !!(currentSubject && currentSubject.isWarehouse);
const counterparty = currentIsWarehouse ? item.store : item.warehouse;
const storeName = item.store_remask || (item.store && item.store.company_name ? item.store.company_name : '');
const warehouseName = item.warehouse_remask || (item.warehouse && item.warehouse.company_name ? item.warehouse.company_name : '');
const counterpartyName = currentIsWarehouse ? storeName : warehouseName;
let isAuthValid = false;
let remainingDays = 0;
if (authStatus === 2 && item.auth_start && item.auth_end) {
const now = Date.now();
const start = new Date(item.auth_start).getTime();
const end = new Date(item.auth_end).getTime();
if (!Number.isNaN(start) && !Number.isNaN(end) && now >= start && now <= end) {
isAuthValid = true;
remainingDays = Math.max(0, Math.ceil((end - now) / (1000 * 60 * 60 * 24)));
}
}
return {
id: Number(item.id || 0),
store_id: Number(item.store_id || 0),
store_name: storeName,
warehouse_id: Number(item.warehouse_id || 0),
warehouse_name: warehouseName,
counterparty_id: counterparty && counterparty.id ? Number(counterparty.id) : 0,
counterparty_name: counterpartyName,
current_subject_role: currentIsWarehouse ? 'warehouse' : 'store',
auth_status: authStatus,
auth_status_label: AUTH_STATUS_LABELS[authStatus] || '',
apply_reason: item.apply_reason || '',
review_comment: item.review_comment || '',
apply_time: item.apply_time || null,
review_time: item.review_time || null,
auth_start: item.auth_start || null,
auth_end: item.auth_end || null,
actual_end: item.actual_end || null,
print_quantity: Number(item.print_quantity || 0),
applied_by: item.applied_by ? Number(item.applied_by) : null,
reviewed_by: item.reviewed_by ? Number(item.reviewed_by) : null,
ended_by: item.ended_by ? Number(item.ended_by) : null,
remask: currentIsWarehouse ? (item.store_remask || '') : (item.warehouse_remask || ''),
use_status: Number(item.use_status || 0),
policy_config: item.policy_config && typeof item.policy_config === 'object' ? item.policy_config : null,
is_auth_valid: isAuthValid,
remaining_days: remainingDays,
api_config: normalizedQimenConfig || null,
apiConfig: normalizedQimenConfig || null,
};
}
async findScopedRelation(data, currentSubject, transaction) {
const { ctx } = this;
const where = currentSubject.isWarehouse
? { warehouse_id: currentSubject.id }
: { store_id: currentSubject.id };
const relationId = this.resolveRelationId(data);
if (relationId) {
where.id = relationId;
} else {
const pair = this.resolvePairIds(data, currentSubject);
where.store_id = pair.storeId;
where.warehouse_id = pair.warehouseId;
}
const relation = await ctx.model.StoreWarehouse.findOne({
where,
include: this.getRelationIncludes(),
transaction,
});
if (!relation) {
throw this.createError('签约关系不存在或无权限操作', 404);
}
return relation;
}
async list(data = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const currentSubject = await this.getCurrentSubject();
const page = this.normalizePage(data.page, 'page', 1, 1000000);
const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200);
const offset = (page - 1) * pageSize;
const where = this.buildListWhere(data, currentSubject);
const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : '';
if (keyword) {
where[Op.or] = [
{ store_remask: { [Op.like]: `%${keyword}%` } },
{ warehouse_remask: { [Op.like]: `%${keyword}%` } },
{ '$store.company_name$': { [Op.like]: `%${keyword}%` } },
{ '$warehouse.company_name$': { [Op.like]: `%${keyword}%` } },
];
}
const { rows, count } = await ctx.model.StoreWarehouse.findAndCountAll({
where,
include: this.getRelationIncludes(),
order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
offset,
limit: pageSize,
distinct: true,
});
const contractIds = rows.map(item => Number(item.id || 0)).filter(id => id > 0);
const qimenConfigMap = contractIds.length
? await this.getQimenConfigMap(contractIds)
: new Map();
return {
code: 200,
data: {
list: rows.map(item => {
const serialized = this.serializeRelation(item, currentSubject);
delete serialized.api_config;
delete serialized.apiConfig;
serialized.has_qimen_config = qimenConfigMap.has(serialized.id);
return serialized;
}),
total: Number(count || 0),
page,
page_size: pageSize,
current_subject: {
store_id: currentSubject.id,
company_name: currentSubject.company_name,
role: currentSubject.isWarehouse ? 'warehouse' : 'store',
},
},
};
}
async sign(data = {}) {
const action = this.normalizeSignAction(data.action || data.mode);
if (data.temp_code || data.tempCode || action === 'preview') {
const { ctx } = this;
const transaction = await ctx.model.transaction();
try {
const currentSubject = await this.getCurrentSubject();
const accountId = this.getCurrentAccountId();
const { tempCode, payload } = await this.getTempSignPayload(data.temp_code || data.tempCode);
const isParticipant = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ]
.includes(Number(currentSubject.id));
if (!isParticipant) {
throw this.createError('当前主体无权使用该临时码', 403);
}
if (action === 'preview' || data.preview === 1 || data.preview === '1') {
await transaction.rollback();
return {
code: 200,
data: this.buildTempSignView(tempCode, payload, currentSubject),
};
}
if (Number(currentSubject.id) !== Number(payload.counterparty_id || 0)) {
throw this.createError('需由对方主体确认后才可生效', 400);
}
const relationPatch = {
store_id: Number(payload.store_id || 0),
warehouse_id: Number(payload.warehouse_id || 0),
auth_status: 2,
apply_reason: payload.apply_reason || '',
apply_time: payload.created_at ? new Date(payload.created_at) : new Date(),
print_quantity: Number(payload.print_quantity || 0),
review_time: new Date(),
auth_start: payload.auth_start ? new Date(payload.auth_start) : new Date(),
auth_end: payload.auth_end ? new Date(payload.auth_end) : null,
actual_end: null,
applied_by: Number(payload.initiated_by || 0) || accountId,
reviewed_by: accountId,
ended_by: null,
use_status: 1,
};
if (payload.store_remask !== undefined) {
relationPatch.store_remask = payload.store_remask;
}
if (payload.warehouse_remask !== undefined) {
relationPatch.warehouse_remask = payload.warehouse_remask;
}
Object.assign(relationPatch, this.buildCurrentRemaskPatch(data, currentSubject));
let relation = await ctx.model.StoreWarehouse.findOne({
where: {
store_id: relationPatch.store_id,
warehouse_id: relationPatch.warehouse_id,
},
transaction,
});
const isCreate = !relation;
if (relation) {
await relation.update(relationPatch, { transaction });
} else {
relation = await ctx.model.StoreWarehouse.create(relationPatch, { transaction });
}
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
include: this.getRelationIncludes(),
transaction,
});
const qimenConfig = await this.getSingleQimenConfig(relation.id, {
allowDisabled: true,
transaction,
});
await this.clearTempSignPayload(tempCode);
await transaction.commit();
// 记录操作日志
try {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'store',
businessId: relation.id,
operationCode: 'STORE_SIGN',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: Number(payload.warehouse_id || 0),
},
beforeChanges: null,
});
} catch (logErr) {
ctx.logger.warn('[storeWarehouse.sign] 写入操作日志失败,不影响业务', logErr);
}
return {
code: 200,
data: {
mode: 'confirm',
temp_code: tempCode,
contract: this.serializeRelation(result, currentSubject, qimenConfig),
action: isCreate ? 'create' : 'update',
},
};
} catch (error) {
await transaction.rollback();
throw error;
}
}
const currentSubject = await this.getCurrentSubject();
const accountId = this.getCurrentAccountId();
const pair = this.resolvePairIds(data, currentSubject);
const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse');
const authStart = this.normalizeDate(data.auth_start, 'auth_start', { allowNull: true }) || new Date();
const authEnd = this.normalizeDate(data.auth_end, 'auth_end', { allowNull: true });
if (authEnd && authStart.getTime() > authEnd.getTime()) {
throw this.createError('auth_end 不能早于 auth_start', 400);
}
const remask = this.resolveRemaskValue(data, currentSubject);
const payload = {
initiated_by: accountId,
initiator_subject_id: currentSubject.id,
initiator_role: currentSubject.isWarehouse ? 'warehouse' : 'store',
initiator_name: currentSubject.company_name,
counterparty_id: Number(counterparty.id || 0),
counterparty_role: currentSubject.isWarehouse ? 'store' : 'warehouse',
counterparty_name: counterparty.company_name || '',
store_id: pair.storeId,
warehouse_id: pair.warehouseId,
auth_start: authStart.toISOString(),
auth_end: authEnd ? authEnd.toISOString() : null,
print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0),
apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000),
remask: remask || '',
created_at: new Date().toISOString(),
...this.buildCurrentRemaskPatch(data, currentSubject),
};
const signPayload = await this.saveTempSignPayload(payload);
return {
code: 200,
data: {
mode: 'initiate',
temp_code: signPayload.tempCode,
expires_at: signPayload.expiresAt,
expires_in: signPayload.expiresIn,
can_confirm: false,
current_subject: {
store_id: currentSubject.id,
company_name: currentSubject.company_name,
role: currentSubject.isWarehouse ? 'warehouse' : 'store',
},
counterparty: {
id: Number(counterparty.id || 0),
company_name: counterparty.company_name || '',
role: currentSubject.isWarehouse ? 'store' : 'warehouse',
},
},
};
}
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;
}
}
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;
}
}
async getPolicyConfigFields() {
return {
code: 200,
data: this.getPolicyConfigFieldList(),
};
}
async getPolicyConfig(data = {}) {
const currentSubject = await this.getCurrentSubject();
const relation = await this.findScopedRelation(data, currentSubject);
const qimenConfig = await this.getSingleQimenConfig(relation.id, {
allowDisabled: true,
});
const policyConfig = await this.loadPolicyConfigByContractId(relation.id);
return {
code: 200,
data: {
contract_id: Number(relation.id || 0),
policy_config: policyConfig,
contract: this.serializeRelation(relation, currentSubject, qimenConfig),
},
};
}
async savePolicyConfig(data = {}) {
const { ctx } = this;
const transaction = await ctx.model.transaction();
try {
const currentSubject = await this.getCurrentSubject();
const relation = await this.findScopedRelation(data, currentSubject, transaction);
this.ensureWarehouseSubject(currentSubject, '签约策略配置');
const policyConfig = this.normalizePolicyConfig(
data.policy_config !== undefined ? data.policy_config : data.policy
);
await this.savePolicyConfigByContractId(relation.id, policyConfig, transaction);
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
include: this.getRelationIncludes(),
transaction,
});
const qimenConfig = await this.getSingleQimenConfig(relation.id, {
allowDisabled: true,
transaction,
});
await transaction.commit();
// 记录操作日志
try {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'store',
businessId: relation.id,
operationCode: 'STORE_SAVE_POLICY_CONFIG',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: Number(relation.warehouse_id || 0),
},
beforeChanges: null,
});
} catch (logErr) {
ctx.logger.warn('[storeWarehouse.savePolicyConfig] 写入操作日志失败,不影响业务', logErr);
}
return {
code: 200,
data: {
contract_id: Number(relation.id || 0),
policy_config: policyConfig,
contract: this.serializeRelation(result, currentSubject, qimenConfig),
},
};
} catch (error) {
await transaction.rollback();
throw error;
}
}
async listApiConfig(data = {}) {
const { ctx } = this;
const currentSubject = await this.getCurrentSubject();
const relation = await this.findScopedRelation(data, currentSubject);
const interfaceTypeId = this.toPositiveNumber(data.interface_type_id, 'interface_type_id', { allowEmpty: true });
const where = {
contract_id: Number(relation.id || 0),
};
if (interfaceTypeId) {
const interfaceType = await this.getApiInterfaceType({ interface_type_id: interfaceTypeId }, {
allowDisabled: true,
});
where.interface_type_id = Number(interfaceType.id || 0);
}
const rows = await ctx.model.ApiApp.findAll({
where,
include: [
{
model: ctx.model.InterfaceType,
as: 'interface_type',
attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ],
required: false,
},
],
order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
});
const list = rows.map(item => this.serializeQimenConfig(item));
const primaryApiConfig = list.length ? list[0] : null;
return {
code: 200,
data: {
contract_id: Number(relation.id || 0),
contract: this.serializeRelation(relation, currentSubject, primaryApiConfig),
list,
total: list.length,
},
};
}
async saveApiConfig(data = {}) {
const { ctx, app } = this;
const transaction = await ctx.model.transaction();
try {
const currentSubject = await this.getCurrentSubject();
const relation = await this.findScopedRelation(data, currentSubject, transaction);
this.ensureWarehouseSubject(currentSubject, '接口配置');
const interfaceType = await this.getApiInterfaceType(data, { transaction, requireId: true });
const isOpenApi = interfaceType.interface_category === 'OPEN_API';
const isQimenWms = interfaceType.interface_category === 'QM_WMS';
// 奇门相关字段:QM_WMS 必填,OPEN_API 不需要
let qimenAppKey = null;
let qimenCustomerId = null;
let qimenWarehouseCode = null;
if (isQimenWms) {
qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100);
if (!qimenAppKey) {
throw this.createError('奇门接口类型下 qimen_app_key 参数不能为空', 400);
}
qimenCustomerId = this.normalizeText(data.qimen_customer_id, 'qimen_customer_id', 100);
if (!qimenCustomerId) {
throw this.createError('奇门接口类型下 qimen_customer_id 参数不能为空', 400);
}
qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100);
if (!qimenWarehouseCode) {
throw this.createError('奇门接口类型下 qimen_warehouse_code 参数不能为空', 400);
}
} else {
// OPEN_API: 奇门字段可选输入
qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100) || null;
qimenCustomerId = this.normalizeText(data.qimen_customer_id, 'qimen_customer_id', 100) || null;
qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100) || null;
}
const appName = this.normalizeText(data.app_name, 'app_name', 200);
if (!appName) {
throw this.createError('app_name 参数不能为空', 400);
}
const apiVersion = this.normalizeText(data.api_version, 'api_version', 50) || '1.0';
const signMethod = (this.normalizeText(data.sign_method, 'sign_method', 50) || 'md5').toLowerCase();
if (![ 'md5', 'hmac', 'sha256' ].includes(signMethod)) {
throw this.createError('sign_method 参数不合法', 400);
}
const rateLimit = this.normalizeIntegerRange(data.rate_limit, 'rate_limit', 1000, 1, 100000);
const timeoutSeconds = this.normalizeIntegerRange(data.timeout_seconds, 'timeout_seconds', 30, 1, 300);
const contactPerson = this.normalizeText(data.contact_person, 'contact_person', 100);
const contactPhone = this.normalizeText(data.contact_phone, 'contact_phone', 20);
const email = this.normalizeEmail(data.email);
const isEnabled = this.normalizeStatusFlag(data.is_enabled, 'is_enabled', 1);
const where = {
interface_type_id: Number(interfaceType.id || 0),
contract_id: Number(relation.id || 0),
};
let config = await ctx.model.ApiApp.findOne({
where,
include: [
{
model: ctx.model.InterfaceType,
as: 'interface_type',
attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ],
required: false,
},
],
transaction,
});
const { Op } = app.Sequelize;
// 重复检测:按接口类型不同检查策略
let duplicateConfig = null;
if (isQimenWms && qimenAppKey && qimenCustomerId) {
const duplicateWhere = {
interface_type_id: Number(interfaceType.id || 0),
qimen_app_key: qimenAppKey,
qimen_customer_id: qimenCustomerId,
};
if (config && config.id) {
duplicateWhere.id = { [Op.ne]: config.id };
}
duplicateConfig = await ctx.model.ApiApp.findOne({
where: duplicateWhere,
attributes: [ 'id', 'contract_id' ],
transaction,
});
if (duplicateConfig) {
throw this.createError('该 AppKey 和客户ID 已绑定其他签约关系', 409);
}
}
// OPEN_API: 创建时自动生成 self_app_key 和 self_app_secret
let selfAppKey = null;
let selfAppSecret = null;
if (isOpenApi) {
if (config) {
// 更新时保留已有密钥
selfAppKey = config.self_app_key;
selfAppSecret = config.self_app_secret;
} else {
// 创建时生成新密钥
const crypto = require('crypto');
selfAppKey = `WMS${crypto.randomBytes(16).toString('hex').toUpperCase()}`;
selfAppSecret = crypto.randomBytes(32).toString('hex');
}
}
const configPayload = {
app_name: appName,
interface_type_id: Number(interfaceType.id || 0),
contract_id: Number(relation.id || 0),
warehouse_id: relation.warehouse_id ? Number(relation.warehouse_id) : null,
self_app_key: selfAppKey,
self_app_secret: selfAppSecret,
qimen_app_key: qimenAppKey,
qimen_customer_id: qimenCustomerId,
qimen_warehouse_code: qimenWarehouseCode,
api_version: apiVersion,
sign_method: signMethod,
rate_limit: rateLimit,
timeout_seconds: timeoutSeconds,
contact_person: contactPerson || null,
contact_phone: contactPhone || null,
email,
is_enabled: isEnabled,
};
const previousConfig = config ? this.serializeQimenConfig(config) : null;
const action = config ? 'update' : 'create';
if (config) {
await config.update(configPayload, { transaction });
} else {
config = await ctx.model.ApiApp.create(configPayload, { transaction });
}
const savedConfig = await ctx.model.ApiApp.findByPk(config.id, {
include: [
{
model: ctx.model.InterfaceType,
as: 'interface_type',
attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ],
required: false,
},
],
transaction,
});
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
include: this.getRelationIncludes(),
transaction,
});
const apiConfig = this.serializeQimenConfig(savedConfig);
await transaction.commit();
// 记录操作日志
try {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'store',
businessId: relation.id,
operationCode: 'STORE_SAVE_API_CONFIG',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: Number(relation.warehouse_id || 0),
},
beforeChanges: null,
});
} catch (logErr) {
ctx.logger.warn('[storeWarehouse.saveApiConfig] 写入操作日志失败,不影响业务', logErr);
}
await this.clearQimenContractCache([ previousConfig, apiConfig ]).catch(error => {
ctx.logger.warn('[storeWarehouse.saveApiConfig] 清理奇门缓存失败: %s', error.message);
});
return {
code: 200,
data: {
action,
contract: this.serializeRelation(result, currentSubject, apiConfig),
api_config: apiConfig,
apiConfig,
},
};
} catch (error) {
await transaction.rollback();
if (error && error.name === 'SequelizeUniqueConstraintError') {
throw this.createError('接口配置已存在,请检查应用名或 AppKey / 客户ID 是否重复', 409);
}
if (error && error.name === 'SequelizeValidationError') {
const message = error.errors && error.errors.length ? error.errors[0].message : '接口配置参数校验失败';
throw this.createError(message, 400);
}
throw error;
}
}
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;
}
}
async unbind(data = {}) {
const { ctx } = this;
const transaction = await ctx.model.transaction();
try {
const currentSubject = await this.getCurrentSubject();
const relation = await this.findScopedRelation(data, currentSubject, transaction);
const nextUseStatus = this.normalizeStatusFlag(data.use_status, 'use_status', 0);
await relation.update({
use_status: nextUseStatus,
}, { transaction });
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
include: this.getRelationIncludes(),
transaction,
});
const qimenConfig = await this.getSingleQimenConfig(relation.id, {
allowDisabled: true,
transaction,
});
await transaction.commit();
// 记录操作日志
try {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'store',
businessId: relation.id,
operationCode: 'STORE_UNBIND',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: Number(relation.warehouse_id || 0),
},
beforeChanges: null,
});
} catch (logErr) {
ctx.logger.warn('[storeWarehouse.unbind] 写入操作日志失败,不影响业务', logErr);
}
return {
code: 200,
data: {
contract: this.serializeRelation(result, currentSubject, qimenConfig),
},
};
} catch (error) {
await transaction.rollback();
throw error;
}
}
}
module.exports = SettingStoreWarehouseService;