refactor(storeWarehouse): 签约体系重构 — 统一主体维度、移除角色校验、list 拆分

- sign: 统一当前主体→store_id(货主方/消费方),对方→warehouse_id(仓库方/提供方)

- getCounterparty: 移除 expectedRole 角色校验,仓库可签仓库、货主可签货主

- list: 拆分为 listForStore/listForWarehouse,warehouse 侧支持查询外部合作仓库

- 新增 buildListWhereByStoreId 统一按 store_id 维度构建查询条件

- 响应新增 counterparty_role / needs_my_confirm / has_qimen_config 字段
This commit is contained in:
liufumingren 2026-07-09 03:36:09 +08:00
parent 14a5f13ad5
commit b9ead1fba2
4 changed files with 575 additions and 332 deletions

View File

@ -26,14 +26,14 @@ class StoreWarehouseStoreService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,sign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig';
const _noNeedRight = 'list,sign,confirmSign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig';
const _noNeedLog = '*';
const _noNeedAuth = 'list,sign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig';
const _noNeedAuth = 'list,sign,confirmSign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 获取签约列表。
* 获取签约列表(货主侧)。
*
* @param {Object} data 请求数据。
* @return {Promise<Object>} 统一响应结果。
@ -41,7 +41,7 @@ class StoreWarehouseStoreService extends MainService {
async list(data = {}) {
const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse;
if (!targetService || typeof targetService.list !== 'function') {
if (!targetService || typeof targetService.listForStore !== 'function') {
return this.fail('获取签约列表失败', {
code: 500,
});
@ -49,7 +49,7 @@ class StoreWarehouseStoreService extends MainService {
try {
const payload = normalizeStoreWarehousePayload(data);
const result = await targetService.list(payload);
const result = await targetService.listForStore(payload);
return this.success('ok', result);
} catch (error) {
return this.fail(error.message || '获取签约列表失败', {
@ -84,6 +84,30 @@ class StoreWarehouseStoreService extends MainService {
}
}
/**
* 确认签约:对方主体确认待签约的申请。
*
* @param {Object} data 请求数据。
* @return {Promise<Object>} 统一响应结果。
*/
async confirmSign(data = {}) {
const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse;
if (!targetService || typeof targetService.confirmSign !== 'function') {
return this.fail('确认签约失败', { code: 500 });
}
try {
const payload = normalizeStoreWarehousePayload(data);
const result = await targetService.confirmSign(payload);
return this.success('ok', result);
} catch (error) {
return this.fail(error.message || '确认签约失败', {
code: Number(error.code) || 500,
});
}
}
/**
* 修改签约名称。
*

View File

@ -19,14 +19,14 @@ class StoreWarehouseWarehouseService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list';
const _noNeedRight = 'list,sign,confirmSign';
const _noNeedLog = '*';
const _noNeedAuth = 'list';
const _noNeedAuth = 'list,sign,confirmSign';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 仓库侧获取签约列表。
* 仓库侧获取签约列表(含外部合作仓库)。
*
* @param {Object} data 请求数据。
* @return {Promise<Object>} 统一响应结果。
@ -34,13 +34,13 @@ class StoreWarehouseWarehouseService extends MainService {
async list(data = {}) {
const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse;
if (!targetService || typeof targetService.list !== 'function') {
if (!targetService || typeof targetService.listForWarehouse !== 'function') {
return this.fail('获取签约列表失败', { code: 500 });
}
try {
const payload = normalizeWarehouseStorePayload(data);
const result = await targetService.list(payload);
const result = await targetService.listForWarehouse(payload);
return this.success('ok', result);
} catch (error) {
return this.fail(error.message || '获取签约列表失败', {
@ -48,6 +48,40 @@ class StoreWarehouseWarehouseService extends MainService {
});
}
}
/**
* 仓库侧发起签约。
*/
async sign(data = {}) {
const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse;
if (!targetService || typeof targetService.sign !== 'function') {
return this.fail('签约失败', { code: 500 });
}
try {
const payload = normalizeWarehouseStorePayload(data);
const result = await targetService.sign(payload);
return this.success('ok', result);
} catch (error) {
return this.fail(error.message || '签约失败', { code: Number(error.code) || 500 });
}
}
/**
* 仓库侧确认签约。
*/
async confirmSign(data = {}) {
const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse;
if (!targetService || typeof targetService.confirmSign !== 'function') {
return this.fail('确认签约失败', { code: 500 });
}
try {
const payload = normalizeWarehouseStorePayload(data);
const result = await targetService.confirmSign(payload);
return this.success('ok', result);
} catch (error) {
return this.fail(error.message || '确认签约失败', { code: Number(error.code) || 500 });
}
}
}
module.exports = StoreWarehouseWarehouseService;

View File

@ -509,7 +509,6 @@ class SettingStoreWarehouseService extends Service {
auth_status_label: serialized.auth_status_label,
auth_end: serialized.auth_end,
print_quantity: serialized.print_quantity,
policy_config: serialized.policy_config,
};
}),
total: Number(count || 0),
@ -526,149 +525,90 @@ class SettingStoreWarehouseService extends Service {
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();
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: currentSubject.isWarehouse ? 'store' : 'warehouse' },
},
};
}
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));
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);
if (!isParticipant) {
throw this.createError('当前主体无权使用该临时码', 403);
}
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));
if (action === 'preview' || data.preview === 1 || data.preview === '1') {
await transaction.rollback();
return {
code: 200,
data: this.buildTempSignView(tempCode, payload, currentSubject),
};
}
let relation = await ctx.model.StoreWarehouse.findOne({ where: { store_id: pair.storeId, warehouse_id: pair.warehouseId }, transaction });
const isCreate = !relation;
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,
warehouse_use_status: 1,
store_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) {
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 {
relation = await ctx.model.StoreWarehouse.create(relationPatch, { transaction });
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)) } };
}
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
include: this.getRelationIncludes(),
transaction,
});
await this.clearTempSignPayload(tempCode);
await transaction.commit();
return {
code: 200,
data: {
mode: 'confirm',
temp_code: tempCode,
contract: this.serializeRelation(result, currentSubject),
action: isCreate ? 'create' : 'update',
},
};
} catch (error) {
await transaction.rollback();
throw error;
} else {
relation = await ctx.model.StoreWarehouse.create(relationPatch, { transaction });
}
}
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 result = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction });
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; }
}
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),
};
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 };
}
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 confirmSign(data = {}) {
const { ctx } = this;
const transaction = await ctx.model.transaction();
try {
const currentSubject = await this.getCurrentSubject();
const accountId = this.getCurrentAccountId();
const relationId = this.toPositiveNumber(data.id, 'id');
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; }
}
async rename(data = {}) {

View File

@ -854,14 +854,14 @@ class SettingStoreWarehouseService extends Service {
}
/**
* 获取签约对方主体信息。
* 获取签约对方主体信息(不校验项目角色,仓库可签仓库、货主可签货主)。
*
* @param {number} counterpartyId 对方主体 ID。
* @param {string} expectedRole 期望角色。
* @param {string} [_expectedRole] 期望角色(已废弃,保留参数兼容)。
* @return {Promise<Object>} 对方主体对象。
* @throws {Error} 对方主体不存在或角色不匹配时抛出,状态码为 400/404。
* @throws {Error} 对方主体不存在时抛出,状态码为 404。
*/
async getCounterparty(counterpartyId, expectedRole) {
async getCounterparty(counterpartyId, _expectedRole) {
const { ctx } = this;
const counterparty = await ctx.model.Store.findOne({
where: {
@ -874,24 +874,55 @@ class SettingStoreWarehouseService extends Service {
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;
}
/**
* 构建列表查询条件。
* 构建列表查询条件(按 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 = {};
@ -1254,25 +1285,19 @@ class SettingStoreWarehouseService extends Service {
/**
* 解析成对的合同主体 ID。
*
* 规则:当前主体(签约发起方)始终为 store_id 方(货主方/消费方),
* 对方始终为 warehouse_id 方(仓库方/提供方)。
*
* @param {Object} data 请求参数。
* @param {Object} currentSubject 当前主体。
* @return {Object} 包含 storeId、warehouseId、counterpartyId 的对象。
* @throws {Error} 对方主体参数非法时抛出,状态码为 400。
*/
resolvePairIds(data, currentSubject) {
const fieldName = currentSubject.isWarehouse ? 'store_id / counterparty_id' : 'warehouse_id / counterparty_id';
const rawCounterpartyId = data.counterparty_id !== undefined
? data.counterparty_id
: (currentSubject.isWarehouse ? data.store_id : data.warehouse_id);
const counterpartyId = this.toPositiveNumber(rawCounterpartyId, fieldName);
if (currentSubject.isWarehouse) {
return {
storeId: counterpartyId,
warehouseId: currentSubject.id,
counterpartyId,
};
}
: (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,
@ -1299,7 +1324,11 @@ class SettingStoreWarehouseService extends Service {
const authStatus = Number(item.auth_status || 0);
const currentIsWarehouse = !!(currentSubject && currentSubject.isWarehouse);
const counterparty = currentIsWarehouse ? item.store : item.warehouse;
// 当前主体始终在 store_id 方(货主方/消费方),对方始终在 warehouse_id 方(仓库方/提供方)
const counterparty = item.warehouse;
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 : '';
@ -1324,6 +1353,7 @@ class SettingStoreWarehouseService extends Service {
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] || '',
@ -1345,7 +1375,6 @@ class SettingStoreWarehouseService extends Service {
: Number(item.store_use_status || 0),
warehouse_use_status: Number(item.warehouse_use_status || 0),
store_use_status: Number(item.store_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,
@ -1354,7 +1383,11 @@ class SettingStoreWarehouseService extends Service {
}
/**
* 获取受限范围内的签约关系。
* 获取受限范围内的签约关系(兼容新旧签约数据)。
*
* 新数据:当前主体在 store_id(发起方/消费方)。
* 旧数据:仓库主体可能在 warehouse_id(提供方)。
* 使用 OR 查询两边,确保新旧数据都能被操作。
*
* @param {Object} data 请求参数。
* @param {Object} currentSubject 当前主体。
@ -1364,21 +1397,27 @@ class SettingStoreWarehouseService extends Service {
*/
async findScopedRelation(data, currentSubject, transaction) {
const { ctx } = this;
const where = currentSubject.isWarehouse
? { warehouse_id: currentSubject.id }
: { store_id: currentSubject.id };
const { Op } = ctx.app.Sequelize;
const scopedWhere = {};
const relationId = this.resolveRelationId(data);
if (relationId) {
where.id = relationId;
scopedWhere.id = relationId;
} else {
const pair = this.resolvePairIds(data, currentSubject);
where.store_id = pair.storeId;
where.warehouse_id = pair.warehouseId;
scopedWhere.store_id = pair.storeId;
scopedWhere.warehouse_id = pair.warehouseId;
}
const relation = await ctx.model.StoreWarehouse.findOne({
where,
where: {
...scopedWhere,
[Op.or]: [
{ store_id: currentSubject.id },
{ warehouse_id: currentSubject.id },
],
},
include: this.getRelationIncludes(),
transaction,
});
@ -1391,11 +1430,169 @@ class SettingStoreWarehouseService extends Service {
}
/**
* 查询签约关系列表。
* 货主侧查询签约关系列表。
*
* 当前货主主体在 store_id 方,对方仓库在 warehouse_id 方。
*
* @param {Object} [data={}] 请求参数。
* @return {Promise<Object>} 接口响应对象。
*/
async listForStore(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.buildListWhereByStoreId(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_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',
},
},
};
}
/**
* 仓库侧查询签约关系列表。
*
* 当前仓库主体在 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;
const where = this.buildListWhereByStoreId(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,
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;
@ -1447,7 +1644,8 @@ class SettingStoreWarehouseService extends Service {
auth_end: serialized.auth_end,
print_quantity: serialized.print_quantity,
has_qimen_config: serialized.has_qimen_config,
policy_config: serialized.policy_config,
needs_my_confirm: Number(item.auth_status || 0) === 1
&& Number(item.initiator_subject_id || 0) !== currentSubject.id,
};
}),
total: Number(count || 0),
@ -1470,174 +1668,221 @@ class SettingStoreWarehouseService extends Service {
*/
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();
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',
},
},
};
}
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));
const { ctx } = this;
const transaction = await ctx.model.transaction();
if (!isParticipant) {
throw this.createError('当前主体无权使用该临时码', 403);
}
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);
}
if (action === 'preview' || data.preview === 1 || data.preview === '1') {
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: this.buildTempSignView(tempCode, payload, currentSubject),
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)),
},
};
}
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,
warehouse_use_status: 1,
store_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;
} 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;
}
}
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);
/**
* 精简签约对象,仅保留前端需要的字段。
*/
trimContract(serialized) {
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',
},
},
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;
}
}
/**
* 修改签约关系脱敏名称。
*