'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); } 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; } 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.toPositiveNumber(data.id, 'id', { allowEmpty: true }); if (relationId) { where.id = relationId; } const rawCounterpartyId = data.counterparty_id !== undefined ? data.counterparty_id : (currentSubject.isWarehouse ? data.store_id : data.warehouse_id); const counterpartyId = this.toPositiveNumber(rawCounterpartyId, 'counterparty_id', { allowEmpty: true }); if (counterpartyId) { if (currentSubject.isWarehouse) { where.store_id = counterpartyId; } else { where.warehouse_id = counterpartyId; } } const authStatus = this.normalizeAuthStatus(data.auth_status); if (authStatus !== null) { where.auth_status = authStatus; } const rawUseStatus = data.use_status !== undefined ? data.use_status : (data.warehouse_use_status !== undefined ? data.warehouse_use_status : data.store_use_status); const useStatus = this.normalizeStatusFlag(rawUseStatus, 'use_status', null); if (useStatus !== null) { if (currentSubject.isWarehouse) { where.warehouse_use_status = useStatus; } else { where.store_use_status = useStatus; } } return where; } 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, }, ]; } 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) { const item = relation && typeof relation.get === 'function' ? relation.get({ plain: true }) : (relation || {}); 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 = counterparty && counterparty.company_name ? counterparty.company_name : ''; let isAuthValid = false; let remainingDays = 0; if (authStatus === 2 && item.auth_start && item.auth_end) { const now = Date.now(); const start = new Date(item.auth_start).getTime(); const end = new Date(item.auth_end).getTime(); if (!Number.isNaN(start) && !Number.isNaN(end) && now >= start && now <= end) { isAuthValid = true; remainingDays = Math.max(0, Math.ceil((end - now) / (1000 * 60 * 60 * 24))); } } return { id: Number(item.id || 0), store_id: Number(item.store_id || 0), store_name: storeName, warehouse_id: Number(item.warehouse_id || 0), warehouse_name: warehouseName, counterparty_id: counterparty && counterparty.id ? Number(counterparty.id) : 0, counterparty_name: counterpartyName, 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: currentIsWarehouse ? Number(item.warehouse_use_status || 0) : Number(item.store_use_status || 0), warehouse_use_status: Number(item.warehouse_use_status || 0), store_use_status: Number(item.store_use_status || 0), is_auth_valid: isAuthValid, remaining_days: remainingDays, }; } async findScopedRelation(data, currentSubject, transaction) { const { ctx } = this; const where = currentSubject.isWarehouse ? { warehouse_id: currentSubject.id } : { store_id: currentSubject.id }; const relationId = this.toPositiveNumber(data.id, 'id', { allowEmpty: true }); 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, }); return { code: 200, data: { list: rows.map(item => { const serialized = this.serializeRelation(item, currentSubject); 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, }; }), 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 (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' }, }, }; } const { ctx } = this; const transaction = await ctx.model.transaction(); try { const currentSubject = await this.getCurrentSubject(); const accountId = this.getCurrentAccountId(); const pair = this.resolvePairIds(data, currentSubject); const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse'); const authStart = this.normalizeDate(data.auth_start, 'auth_start', { allowNull: true }) || new Date(); const authEnd = this.normalizeDate(data.auth_end, 'auth_end', { allowNull: true }); if (authEnd && authStart.getTime() > authEnd.getTime()) throw this.createError('auth_end 不能早于 auth_start', 400); const relationPatch = { store_id: pair.storeId, warehouse_id: pair.warehouseId, auth_status: 1, apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000), apply_time: new Date(), print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0), review_time: null, auth_start: authStart, auth_end: authEnd, actual_end: null, applied_by: accountId, reviewed_by: null, ended_by: null, initiator_subject_id: currentSubject.id, warehouse_use_status: 1, store_use_status: 1, print_quantity_locked: 0, }; Object.assign(relationPatch, this.buildCurrentRemaskPatch(data, currentSubject)); let relation = await ctx.model.StoreWarehouse.findOne({ where: { store_id: pair.storeId, warehouse_id: pair.warehouseId }, transaction }); const isCreate = !relation; if (relation) { if (relation.applied_by === accountId && relation.auth_status === 1) { await relation.update(relationPatch, { transaction }); } else if (relation.applied_by === accountId && relation.auth_status >= 2) { const existing = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction }); await transaction.rollback(); return { code: 200, data: { mode: 'already_confirmed', exists_status: relation.auth_status, exists_status_label: '已签约', contract: this.trimContract(this.serializeRelation(existing, currentSubject)) } }; } else { const existing = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction }); await transaction.rollback(); return { code: 200, data: { mode: 'already_exists', exists_status: relation.auth_status, exists_status_label: relation.auth_status === 2 ? '已签约' : '待确认', contract: this.trimContract(this.serializeRelation(existing, currentSubject)) } }; } } else { relation = await ctx.model.StoreWarehouse.create(relationPatch, { transaction }); } const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction }); 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; } } 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 }; } 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 = {}) { 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, }); await transaction.commit(); return { code: 200, data: { contract: this.serializeRelation(result, currentSubject), }, }; } 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 !== undefined ? data.use_status : data.warehouse_use_status, 'warehouse_use_status', 0); const patch = currentSubject.isWarehouse ? { warehouse_use_status: nextUseStatus } : { store_use_status: nextUseStatus }; await relation.update(patch, { transaction }); const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { include: this.getRelationIncludes(), transaction, }); await transaction.commit(); return { code: 200, data: { contract: this.serializeRelation(result, currentSubject), }, }; } catch (error) { await transaction.rollback(); throw error; } } } module.exports = SettingStoreWarehouseService;