WMS_MAIN/app/service/systems/store_warehouse.js

1442 lines
47 KiB
JavaScript

'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: '已过期',
});
const POLICY_CONFIG_FIELD_RULES = Object.freeze({
receive_mode: {
type: 'enum',
values: [ 'standard', 'strict', 'manual' ],
},
sku_visibility: {
type: 'enum',
values: [ 'all', 'whitelist', 'blacklist' ],
},
auto_allocate_bin: {
type: 'flag',
},
allow_mix_batch: {
type: 'flag',
},
allow_temp_storage: {
type: 'flag',
},
max_daily_inbound: {
type: 'integer',
min: 0,
max: 1000000,
},
remark: {
type: 'string',
maxLength: 200,
},
});
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);
}
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;
}
normalizePolicyConfig(value, fieldName = 'policy_config', options = {}) {
const { allowEmpty = false } = options;
if (value === undefined || value === null || value === '') {
if (allowEmpty) {
return null;
}
throw this.createError(`${fieldName} 参数不能为空`, 400);
}
const parsed = typeof value === 'string' ? (() => {
try {
return JSON.parse(value);
} catch {
throw this.createError(`${fieldName} 不是合法JSON`, 400);
}
})() : value;
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw this.createError(`${fieldName} 必须为对象`, 400);
}
const allowedKeys = Object.keys(POLICY_CONFIG_FIELD_RULES);
const unsupportedKeys = Object.keys(parsed).filter(key => !allowedKeys.includes(key));
if (unsupportedKeys.length) {
throw this.createError(`${fieldName} 包含不支持字段: ${unsupportedKeys.join(', ')};仅允许字段: ${allowedKeys.join(', ')}`, 400);
}
const normalized = {};
for (const [ key, rawValue ] of Object.entries(parsed)) {
const rule = POLICY_CONFIG_FIELD_RULES[key];
if (!rule) {
continue;
}
if (rule.type === 'enum') {
const valueText = String(rawValue || '').trim();
if (!rule.values.includes(valueText)) {
throw this.createError(`${fieldName}.${key} 参数不合法`, 400);
}
normalized[key] = valueText;
continue;
}
if (rule.type === 'flag') {
if (rawValue === true || rawValue === 1 || rawValue === '1') {
normalized[key] = 1;
continue;
}
if (rawValue === false || rawValue === 0 || rawValue === '0') {
normalized[key] = 0;
continue;
}
throw this.createError(`${fieldName}.${key} 参数不合法`, 400);
}
if (rule.type === 'integer') {
const num = Number(rawValue);
if (!Number.isFinite(num) || num < rule.min || num > rule.max) {
throw this.createError(`${fieldName}.${key} 参数不合法`, 400);
}
normalized[key] = Math.floor(num);
continue;
}
if (rule.type === 'string') {
const text = this.normalizeText(rawValue, `${fieldName}.${key}`, rule.maxLength);
normalized[key] = text || '';
}
}
return normalized;
}
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;
if (raw === null || raw === undefined || raw === '') {
return null;
}
if (typeof raw === 'object') {
return raw;
}
try {
return JSON.parse(raw);
} catch {
return null;
}
}
const cached = await this.app.getCacheAsync(this.getPolicyConfigCacheKey(normalizedId));
return cached && typeof cached === 'object' ? cached : null;
}
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) {
if (!currentSubject || !currentSubject.isWarehouse) {
throw this.createError('仅仓库主体可维护奇门接口配置', 403);
}
}
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 getQimenInterfaceType(data = {}, options = {}) {
const { ctx } = this;
const { allowDisabled = false, transaction = null } = options;
const interfaceTypeId = this.toPositiveNumber(data.interface_type_id, 'interface_type_id', { allowEmpty: true });
const where = {
interface_category: 'QM_WMS',
};
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;
}
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 || '',
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,
};
}
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();
}
let interfaceTypeIds = [];
if (interfaceTypeId) {
interfaceTypeIds = [ Number(interfaceTypeId) ];
} else {
const interfaceWhere = {
interface_category: 'QM_WMS',
};
if (!allowDisabled) {
interfaceWhere.is_enabled = 1;
}
const interfaceTypes = await ctx.model.InterfaceType.findAll({
where: interfaceWhere,
attributes: [ 'id' ],
transaction,
});
interfaceTypeIds = interfaceTypes.map(item => Number(item.id)).filter(Boolean);
}
if (!interfaceTypeIds.length) {
return new Map();
}
const rows = await ctx.model.ApiApp.findAll({
where: {
contract_id: normalizedContractIds,
interface_type_id: interfaceTypeIds,
},
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,
qimen_config: 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 qimenConfigMap = await this.getQimenConfigMap(rows.map(item => Number(item.id || 0)), {
allowDisabled: true,
});
return {
code: 200,
data: {
list: rows.map(item => this.serializeRelation(item, currentSubject, qimenConfigMap.get(Number(item.id || 0)) || null)),
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();
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();
return {
code: 200,
data: {
contract: this.serializeRelation(result, currentSubject, qimenConfig),
},
};
} catch (error) {
await transaction.rollback();
throw error;
}
}
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();
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 listQimenConfig(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 interfaceWhere = {
interface_category: 'QM_WMS',
};
if (interfaceTypeId) {
interfaceWhere.id = interfaceTypeId;
}
const interfaceTypes = await ctx.model.InterfaceType.findAll({
where: interfaceWhere,
attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ],
order: [[ 'id', 'ASC' ]],
});
const interfaceTypeIds = interfaceTypes.map(item => Number(item.id)).filter(Boolean);
if (!interfaceTypeIds.length) {
return {
code: 200,
data: {
contract_id: Number(relation.id || 0),
contract: this.serializeRelation(relation, currentSubject, null),
list: [],
total: 0,
},
};
}
const rows = await ctx.model.ApiApp.findAll({
where: {
contract_id: Number(relation.id || 0),
interface_type_id: interfaceTypeIds,
},
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 primaryQimenConfig = list.length ? list[0] : null;
return {
code: 200,
data: {
contract_id: Number(relation.id || 0),
contract: this.serializeRelation(relation, currentSubject, primaryQimenConfig),
list,
total: list.length,
},
};
}
async saveQimenConfig(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.getQimenInterfaceType(data, { transaction });
const qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100);
if (!qimenAppKey) {
throw this.createError('qimen_app_key 参数不能为空', 400);
}
const qimenCustomerId = this.normalizeText(data.qimen_customer_id, 'qimen_customer_id', 100);
if (!qimenCustomerId) {
throw this.createError('qimen_customer_id 参数不能为空', 400);
}
const qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100);
if (!qimenWarehouseCode) {
throw this.createError('qimen_warehouse_code 参数不能为空', 400);
}
const relationPlain = relation && typeof relation.get === 'function'
? relation.get({ plain: true })
: relation;
const defaultAppName = [
relationPlain && relationPlain.store_remask ? relationPlain.store_remask : currentSubject.company_name,
relationPlain && relationPlain.warehouse_remask
? relationPlain.warehouse_remask
: (relationPlain && relationPlain.warehouse && relationPlain.warehouse.company_name ? relationPlain.warehouse.company_name : `contract-${relation.id}`),
'奇门接口',
].filter(Boolean).join('-').slice(0, 200);
const appName = this.normalizeText(data.app_name, 'app_name', 200) || defaultAppName;
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;
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 };
}
const duplicateConfig = await ctx.model.ApiApp.findOne({
where: duplicateWhere,
attributes: [ 'id', 'contract_id' ],
transaction,
});
if (duplicateConfig) {
throw this.createError('该奇门 AppKey 和客户ID 已绑定其他签约关系', 409);
}
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,
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 qimenConfig = this.serializeQimenConfig(savedConfig);
await transaction.commit();
await this.clearQimenContractCache([ previousConfig, qimenConfig ]).catch(error => {
ctx.logger.warn('[storeWarehouse.saveQimenConfig] 清理奇门缓存失败: %s', error.message);
});
return {
code: 200,
data: {
action,
contract: this.serializeRelation(result, currentSubject, qimenConfig),
qimen_config: qimenConfig,
},
};
} 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.getQimenInterfaceType(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();
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),
qimen_config: 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();
return {
code: 200,
data: {
contract: this.serializeRelation(result, currentSubject, qimenConfig),
},
};
} catch (error) {
await transaction.rollback();
throw error;
}
}
}
module.exports = SettingStoreWarehouseService;