887 lines
22 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

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

'use strict';
const Service = require('egg').Service;
class StoreService extends Service {
validateStoreData(data = {}) {
const errors = [];
const requiredFields = [ 'company_name', 'contact_person', 'contact_phone' ];
for (const field of requiredFields) {
if (!data[field]) {
errors.push(`${field} 不能为空`);
}
}
if (data.company_name && (data.company_name.length < 1 || data.company_name.length > 200)) {
errors.push('公司名称长度应在1-200个字符之间');
}
if (data.contact_email && data.contact_email.trim() !== '') {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(data.contact_email)) {
errors.push('联系邮箱格式不正确');
}
}
return errors;
}
async checkCompanyNameExists(companyName, excludeId = null) {
const where = {
company_name: companyName,
};
if (excludeId) {
where.id = {
[this.app.Sequelize.Op.ne]: excludeId,
};
}
const store = await this.app.model.Store.findOne({ where });
return !!store;
}
async findByAccountId(accountId) {
return await this.app.model.Store.findOne({
where: {
account_id: accountId,
status: 1,
},
});
}
async findAllEnabled() {
return await this.app.model.Store.findAll({
where: {
status: 1,
},
order: [[ 'company_name', 'ASC' ]],
});
}
async findAllWarehouses() {
return await this.app.model.Store.findAll({
where: {
status: 1,
project: 'warehouse',
},
order: [[ 'company_name', 'ASC' ]],
});
}
/**
* 根据ID获取商家信息
* @param storeId
*/
async getStoreName(storeId) {
try {
const store = await this.app.model.Store.findByPk(storeId, {
attributes: [ 'id', 'company_name', 'status', 'is_warehouse' ],
});
if (!store) {
return {
code: 404,
message: '商家不存在',
data: null,
};
}
return {
code: 200,
message: '获取成功',
data: store,
};
} catch (error) {
this.ctx.logger.error('获取商家信息失败:', error);
return {
code: 500,
message: '获取商家信息失败',
data: null,
};
}
}
/**
* 获取商家仓库备注名
* @param storeId
* @param warehouseId
*/
async getStoreRemaskName(storeId, warehouseId) {
try {
const relation = await this.app.model.StoreWarehouse.findOne({
where: {
store_id: storeId,
warehouse_id: warehouseId,
},
});
if (!relation) {
return {
code: 404,
message: '商家仓库关系不存在',
data: null,
};
}
return {
code: 200,
message: '获取成功',
data: relation,
};
} catch (error) {
this.ctx.logger.error('获取商家仓库关系失败:', error);
return {
code: 500,
message: '获取商家仓库关系失败',
data: null,
};
}
}
/**
* 创建商家(不需要审核)
* @param data
*/
async createStore(data) {
const {
ctx,
} = this;
const transaction = await ctx.model.transaction();
try {
const userId = ctx.userId || (ctx.user && ctx.user.id);
if (!userId) {
return {
code: 401,
message: '用户未登录',
data: null,
};
}
// 验证必填字段
const requiredFields = [ 'company_name', 'business_license', 'contact_person', 'contact_phone' ];
for (const field of requiredFields) {
if (!data[field]) {
return {
code: 400,
message: `字段 ${field} 不能为空`,
data: null,
};
}
}
// 检查公司名称是否已存在
const existingStore = await ctx.model.Store.findOne({
where: {
company_name: data.company_name,
},
});
if (existingStore) {
return {
code: 409,
message: '公司名称已存在',
data: null,
};
}
// 创建商家
const storeData = {
company_name: data.company_name,
business_license: data.business_license,
legal_person: data.legal_person,
contact_phone: data.contact_phone,
contact_email: data.contact_email,
contact_person: data.contact_person,
address: data.address,
industry: data.industry,
account_id: userId, // 商家管理员
status: 1, // 直接启用
created_by: userId,
is_warehouse: 0, // 默认不是仓库
logo_url: data.logo_url,
domain: data.domain,
auth_start: data.auth_start,
auth_end: data.auth_end,
};
const store = await ctx.model.Store.create(storeData, {
transaction,
});
// 为创建者自动分配商家管理员角色
const role_id = await this.assignAdminRoleToCreator(store.id, userId, data.contact_person, transaction);
console.log(role_id);
await transaction.commit();
return {
code: 200,
message: '商家创建成功',
data: {
store_id: store.id,
company_name: store.company_name,
role_id: role_id.id,
},
};
} catch (error) {
await transaction.rollback();
this.ctx.logger.error('创建商家失败:', error);
if (error.name === 'SequelizeUniqueConstraintError') {
return {
code: 409,
message: '商家信息已存在',
data: null,
};
}
return {
code: 500,
message: '创建商家失败',
data: null,
};
}
}
/**
* 创建仓库(需要审核)
* @param data
*/
async createWarehouse(data) {
const {
ctx,
} = this;
const transaction = await ctx.model.transaction();
try {
const userId = ctx.userId || (ctx.user && ctx.user.id);
if (!userId) {
return {
code: 401,
message: '用户未登录',
data: null,
};
}
// 验证必填字段
const requiredFields = [ 'company_name', 'contact_person', 'contact_phone' ];
for (const field of requiredFields) {
if (!data[field]) {
return {
code: 400,
message: `字段 ${field} 不能为空`,
data: null,
};
}
}
// 检查公司名称是否已存在
const existingStore = await ctx.model.Store.findOne({
where: {
company_name: data.company_name,
},
});
if (existingStore) {
return {
code: 409,
message: '公司名称已存在',
data: null,
};
}
// 创建仓库(也是商家,但 is_warehouse = 1)
const warehouseData = {
company_name: data.company_name,
business_license: data.business_license,
legal_person: data.legal_person,
contact_phone: data.contact_phone,
contact_email: data.contact_email,
contact_person: data.contact_person,
address: data.address,
industry: data.industry,
account_id: userId,
status: 1, // 直接通过
created_by: userId,
is_warehouse: 1, // 标记为仓库
logo_url: data.logo_url,
domain: data.domain,
auth_start: new Date(), // 设置当前时间为授权开始时间
auth_end: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 默认授权7天试用
};
const warehouse = await ctx.model.Store.create(warehouseData, {
transaction,
});
// 为创建者自动分配商家管理员角色
const role_id = await this.assignAdminRoleToCreator(warehouse.id, userId, data.contact_person,
transaction, false);
await transaction.commit();
return {
code: 200,
message: '仓库创建申请已提交,等待审核',
data: {
store_id: warehouse.id,
company_name: warehouse.company_name,
role_id: role_id.id,
},
};
} catch (error) {
await transaction.rollback();
this.ctx.logger.error('创建仓库申请失败:', error);
if (error.name === 'SequelizeUniqueConstraintError') {
return {
code: 409,
message: '仓库信息已存在',
data: null,
};
}
return {
code: 500,
message: '提交申请失败',
data: null,
};
}
}
/**
* 加入商家
* @param data
*/
async joinStore(data) {
const {
ctx,
} = this;
const transaction = await ctx.model.transaction();
try {
const userId = ctx.userId || (ctx.user && ctx.user.id);
console.log('申请参数', data);
// 验证必填字段
if (!data.employees_name) {
return {
code: 400,
message: '真实姓名不能为空',
data: null,
};
}
// 删除用户的其他待审核申请
await ctx.model.StoreJoin.destroy({
where: {
account_id: userId,
audit_status: 'pending',
},
transaction,
});
// 生成加入链接(用于分享给管理员)
const joinToken = this.generateJoinToken(userId, data.store_id);
// 创建加入申请
const applyData = {
account_id: userId,
real_name: data.employees_name,
warehouse: 0,
apply_time: new Date(),
apply_username: ctx.username || '',
audit_status: 'pending',
remark: data.remark,
join_token: joinToken,
};
const applyRecord = await ctx.model.StoreJoin.create(applyData, {
transaction,
});
await transaction.commit();
return {
code: 200,
message: '加入申请已提交',
data: {
apply_id: applyRecord.id,
joinToken,
},
};
} catch (error) {
await transaction.rollback();
console.log('error', error);
return {
code: 500,
message: '创建申请链接失败',
data: null,
};
}
}
/**
* 加入仓库
* @param data
*/
async joinWarehouse(data) {
const {
ctx,
} = this;
const transaction = await ctx.model.transaction();
try {
const userId = ctx.userId || (ctx.user && ctx.user.id);
console.log('申请参数', data);
// 验证必填字段
if (!data.employees_name) {
return {
code: 400,
message: '真实姓名不能为空',
data: null,
};
}
// 删除用户的其他待审核申请
await ctx.model.StoreJoin.destroy({
where: {
account_id: userId,
audit_status: 'pending',
},
transaction,
});
// 生成加入链接(用于分享给管理员)
const joinToken = this.generateJoinToken(userId, data.store_id);
// 创建加入申请
const applyData = {
account_id: userId,
real_name: data.employees_name,
warehouse: 1,
apply_time: new Date(),
apply_username: ctx.username || '',
audit_status: 'pending',
remark: data.remark,
join_token: joinToken,
};
const applyRecord = await ctx.model.StoreJoin.create(applyData, {
transaction,
});
await transaction.commit();
return {
code: 200,
message: '加入申请已提交',
data: {
apply_id: applyRecord.id,
joinToken,
},
};
} catch (error) {
await transaction.rollback();
console.log('error', error);
return {
code: 500,
message: '创建申请链接失败',
data: null,
};
}
}
// ==================== 辅助方法 ====================
async ensureEmployeeRoleBinding({ accountId, storeId, roleId, realName = '', transaction }) {
const { ctx } = this;
const [ employee ] = await ctx.model.AccountStoreEmployee.findOrCreate({
where: {
account_id: accountId,
store_id: storeId,
},
defaults: {
account_id: accountId,
store_id: storeId,
status: 1,
real_name: realName || '',
},
transaction,
});
const shouldRefreshEmployee = Number(employee.status) !== 1
|| (realName && employee.real_name !== realName);
if (shouldRefreshEmployee) {
await employee.update({
status: 1,
real_name: realName || employee.real_name || '',
}, { transaction });
}
const [ employeeRole ] = await ctx.model.EmployeeRole.findOrCreate({
where: {
employee_id: employee.id,
role_id: roleId,
},
defaults: {
employee_id: employee.id,
role_id: roleId,
},
transaction,
});
return { employee, employeeRole };
}
/**
* 为创建者分配管理员角色
* @param storeId
* @param userId
* @param realName
* @param transaction
* @param isStore
*/
async assignAdminRoleToCreator(storeId, userId, realName, transaction, isStore = true) {
const {
ctx,
} = this;
// 创建或获取管理员角色
const role_code = isStore ? 'store_admin_default' : 'warehouse_admin_default';
const adminRole = await ctx.model.Role.findOne({
where: {
store_id: 0,
role_code,
},
});
if (!adminRole) {
throw new Error(`未初始化${role_code}管理员角色`);
}
const { employee } = await this.ensureEmployeeRoleBinding({
accountId: userId,
storeId,
roleId: adminRole.id,
realName: realName || '',
transaction,
});
return employee;
}
/**
* 生成加入令牌
* @param userId
* @param storeId
* @param type
*/
generateJoinToken(userId, storeId, type = 'store') {
const crypto = require('crypto');
const timestamp = Date.now();
const randomStr = Math.random().toString(36).substring(2, 10);
const data = `${userId}_${storeId}_${type}_${timestamp}_${randomStr}`;
return crypto.createHash('sha256').update(data).digest('hex')
.substring(0, 32);
}
/**
* 发送通知
* @param notificationData
*/
async sendNotification(notificationData) {
const {
ctx,
} = this;
try {
await ctx.model.Notification.create({
...notificationData,
is_read: 0,
created_at: new Date(),
});
} catch (error) {
this.ctx.logger.error('发送通知失败:', error);
}
}
/**
* 发送通知给系统管理员
* @param notificationData
*/
async sendNotificationToAdmins(notificationData) {
const {
ctx,
} = this;
try {
// 获取所有系统管理员
const admins = await ctx.model.Account.findAll({
where: {
status: 1,
// 这里可以根据角色筛选系统管理员
},
attributes: [ 'id' ],
});
for (const admin of admins) {
await this.sendNotification({
...notificationData,
account_id: admin.id,
});
}
} catch (error) {
this.ctx.logger.error('发送管理员通知失败:', error);
}
}
async getStoreRoles(data) {
const {
ctx,
} = this;
try {
console.log('ctx', ctx.user.store_id);
const userId = ctx.user.id;
const storeId = ctx.user.store_id;
// 验证必填字段
if (!data.code) {
return {
code: 400,
message: '参数错误',
data: null,
};
}
const code = data.code;
console.log('申请参数', userId, storeId, code);
const applyData = await ctx.model.StoreJoin.findOne({
where: {
join_token: code,
audit_status: 'pending',
},
attributes: [ 'account_id', 'real_name', 'remark', 'audit_status', 'apply_time' ],
});
const store = await ctx.model.Store.findOne({
where: {
id: storeId,
status: 1,
},
attributes: [ 'company_name', 'id' ],
});
const Roles = await ctx.model.Role.findAll({
where: {
store_id: storeId,
deleted_at: null,
},
});
return {
code: 200,
message: '获取成功',
data: {
info: applyData,
store,
roles: Roles,
},
};
} catch (error) {
console.log('error', error);
return {
code: 500,
message: '请求失败',
data: null,
};
}
}
async auditApply(data) {
const { ctx } = this;
const transaction = await ctx.model.transaction();
try {
// 1. 验证必填字段 - 修复逻辑错误
if (!data.audit_status || !data.code || !data.store_id || !data.role_ids || data.role_ids.length === 0) {
await transaction.rollback();
return {
code: 400,
message: '参数错误:audit_status、code和role_ids为必填字段',
data: null,
};
}
// 2. 验证store_id
if (ctx.user.store_id != data.store_id) {
await transaction.rollback();
return {
code: 400,
message: '参数错误:审批角色与访问接口不一致',
data: null,
};
}
const { code, audit_status, role_ids } = data;
const store_id = ctx.user.store_id;
console.log('申请参数', data);
// 3. 查找申请记录
const applyData = await ctx.model.StoreJoin.findOne({
where: {
join_token: code,
audit_status: 'pending',
},
attributes: [ 'id', 'account_id', 'real_name', 'remark', 'audit_status', 'apply_time' ],
transaction,
});
if (!applyData) {
await transaction.rollback();
return {
code: 400,
message: '没有找到对应的申请信息,可能已被他人审核或者申请者重新提交了申请资料',
data: null,
};
}
// 4. 查询角色信息
const roles = await ctx.model.Role.findAll({
where: {
store_id,
deleted_at: null,
id: role_ids, // in查询
},
transaction,
});
// 5. 验证role_ids是否都存在
if (roles.length !== role_ids.length) {
await transaction.rollback();
const foundRoleIds = roles.map(role => role.id);
const missingRoleIds = role_ids.filter(id => !foundRoleIds.includes(id));
return {
code: 400,
message: `角色ID不存在或无权限:${missingRoleIds.join(',')}`,
data: null,
};
}
// 6. 根据审核状态处理不同的逻辑
if (audit_status === 'approved') {
// 审核通过:分配角色并更新申请状态
const { account_id, real_name } = applyData;
for (const role of roles) {
await this.ensureEmployeeRoleBinding({
accountId: account_id,
storeId: store_id,
roleId: role.id,
realName: real_name || '',
transaction,
});
}
// 更新申请记录状态
await ctx.model.StoreJoin.update({
audit_status: 'approved',
audit_time: new Date(),
auditor_id: ctx.user.account_id,
auditor_name: ctx.user.real_name || ctx.user.username,
}, {
where: { id: applyData.id },
transaction,
});
await this.ctx.Service.systems.auth.user.clearUserCache(ctx.user.account_id);// 立即清理用户缓存
await transaction.commit();
const result = await this.getStoreRoles({ code });
return {
code: 200,
message: '审批通过成功',
data: result.data,
};
} else if (audit_status === 'rejected') {
// 审核拒绝:只更新申请状态
await ctx.model.StoreJoin.update({
audit_status: 'rejected',
audit_time: new Date(),
auditor_id: ctx.user.account_id,
auditor_name: ctx.user.real_name || ctx.user.username,
reject_reason: data.reject_reason || '审核不通过',
}, {
where: { id: applyData.id },
transaction,
});
await transaction.commit();
return {
code: 200,
message: '审批拒绝成功',
data: null,
};
}
await transaction.rollback();
return {
code: 400,
message: 'audit_status参数错误,只能为approved或rejected',
data: null,
};
} catch (error) {
await transaction.rollback();
console.error('审核申请出错:', error);
// 根据错误类型返回更详细的错误信息
let errorMessage = '请求失败';
if (error.name === 'SequelizeValidationError') {
errorMessage = '数据验证失败';
} else if (error.name === 'SequelizeUniqueConstraintError') {
errorMessage = '数据已存在';
}
return {
code: 500,
message: errorMessage,
data: null,
error: process.env.NODE_ENV === 'development' ? error.message : undefined,
};
}
}
async loadStores() {
const { app, ctx } = this;
try {
const stores = await ctx.model.StoreWarehouse.findAll({
where: {
use_status: 1,
warehouse_id: ctx.user.store_id,
},
attributes: [
[ 'store_id', 'value' ], // store_id 字段别名为 value
[ 'store_remask', 'label' ], // store_remask 字段别名为 label
],
raw: true, // 可选:返回纯JSON数据
});
return stores;
} catch (error) {
ctx.logger.error('[Service.loadStores] 查询失败:', error);
throw error;
}
}
}
module.exports = StoreService;