901 lines
27 KiB
JavaScript
901 lines
27 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
|
||
|
||
const RESERVED_EMPLOYEE_NAME = '测试工号保留';
|
||
|
||
class SettingAccountService extends Service {
|
||
getListWhereSpecialFieldMap() {
|
||
return {
|
||
employee_id: {
|
||
field: 'id',
|
||
},
|
||
account_id: {
|
||
field: 'account_id',
|
||
},
|
||
username: {
|
||
field: '$account.username$',
|
||
},
|
||
phone: {
|
||
field: '$account.phone$',
|
||
},
|
||
email: {
|
||
field: '$account.email$',
|
||
},
|
||
quickWhere: {
|
||
bucket: 'quick',
|
||
},
|
||
};
|
||
}
|
||
|
||
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;
|
||
}
|
||
|
||
getCurrentEmployeeId() {
|
||
const employeeId = Number(this.ctx.user && this.ctx.user.employees_id);
|
||
if (!Number.isFinite(employeeId) || employeeId <= 0) {
|
||
return null;
|
||
}
|
||
return employeeId;
|
||
}
|
||
|
||
normalizeAccountId(value, fieldName = 'account_id') {
|
||
const accountId = Number(value);
|
||
if (!Number.isFinite(accountId) || accountId <= 0) {
|
||
throw this.createError(`${fieldName} 参数不能为空`, 400);
|
||
}
|
||
return accountId;
|
||
}
|
||
|
||
getWmsClient() {
|
||
return this.ctx.app.mysql.get('wms');
|
||
}
|
||
|
||
normalizePhone(phone) {
|
||
return typeof phone === 'string' ? phone.trim() : '';
|
||
}
|
||
|
||
isValidPhone(phone) {
|
||
return /^1[3-9]\d{9}$/.test(phone);
|
||
}
|
||
|
||
normalizeName(name) {
|
||
return typeof name === 'string' ? name.trim() : '';
|
||
}
|
||
|
||
normalizeUsername(username) {
|
||
return typeof username === 'string' ? username.trim() : '';
|
||
}
|
||
|
||
generateUsername() {
|
||
const suffix = `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
|
||
return `acct_${suffix}`;
|
||
}
|
||
|
||
async findRawAccountByPhone(phone) {
|
||
const rows = await this.getWmsClient().select('wms_account', {
|
||
where: { phone },
|
||
columns: [ 'id', 'username', 'phone', 'email', 'real_name', 'status' ],
|
||
limit: 1,
|
||
});
|
||
return rows && rows.length > 0 ? rows[0] : null;
|
||
}
|
||
|
||
async findRawAccountByUsername(username) {
|
||
const rows = await this.getWmsClient().select('wms_account', {
|
||
where: { username },
|
||
columns: [ 'id', 'username', 'phone', 'email', 'real_name', 'status' ],
|
||
limit: 1,
|
||
});
|
||
return rows && rows.length > 0 ? rows[0] : null;
|
||
}
|
||
|
||
async getAvatarMeta(employeeId) {
|
||
const { ctx } = this;
|
||
const avatarRef = await ctx.model.FileReference.findOne({
|
||
where: {
|
||
business_type: 'avater',
|
||
business_id: String(employeeId),
|
||
},
|
||
include: [
|
||
{
|
||
model: ctx.model.File,
|
||
as: 'file',
|
||
attributes: [ 'id', 'file_url', 'file_name' ],
|
||
required: false,
|
||
},
|
||
],
|
||
order: [[ 'created_at', 'DESC' ]],
|
||
});
|
||
|
||
return {
|
||
avatar_file_id: Number(avatarRef && avatarRef.file_id ? avatarRef.file_id : 0) || null,
|
||
avatar_url: avatarRef && avatarRef.file ? avatarRef.file.file_url : '',
|
||
avatar_name: avatarRef && avatarRef.file ? avatarRef.file.file_name : '',
|
||
};
|
||
}
|
||
|
||
async resolveRoleId(data = {}) {
|
||
const { ctx } = this;
|
||
const explicitRoleId = Number(data.role_id || data.roleId || 0);
|
||
if (Number.isFinite(explicitRoleId) && explicitRoleId > 0) {
|
||
const role = await ctx.model.Role.findOne({
|
||
where: {
|
||
id: explicitRoleId,
|
||
status: 1,
|
||
},
|
||
});
|
||
if (!role) {
|
||
throw this.createError('指定角色不存在或已禁用', 400);
|
||
}
|
||
return explicitRoleId;
|
||
}
|
||
|
||
const currentEmployeeId = this.getCurrentEmployeeId();
|
||
if (!currentEmployeeId) {
|
||
throw this.createError('未识别到当前操作人工号,无法继承角色', 400);
|
||
}
|
||
|
||
const currentRole = await ctx.model.EmployeeRole.findOne({
|
||
where: { employee_id: currentEmployeeId },
|
||
order: [[ 'id', 'ASC' ]],
|
||
});
|
||
if (!currentRole) {
|
||
throw this.createError('当前操作人工号未绑定角色,无法创建新工号', 400);
|
||
}
|
||
|
||
return Number(currentRole.role_id);
|
||
}
|
||
|
||
normalizeRoleIds(ids) {
|
||
if (!Array.isArray(ids) || ids.length === 0) {
|
||
throw this.createError('ids 参数不能为空', 400);
|
||
}
|
||
|
||
const roleIds = [];
|
||
for (const roleId of ids) {
|
||
const normalized = Number(roleId);
|
||
if (!Number.isFinite(normalized) || normalized <= 0) {
|
||
throw this.createError('ids 必须是正整数数组', 400);
|
||
}
|
||
roleIds.push(normalized);
|
||
}
|
||
return Array.from(new Set(roleIds));
|
||
}
|
||
|
||
flattenRoleTreeMeta(roleNodes, idCollector = [], parentMap = new Map()) {
|
||
if (!Array.isArray(roleNodes) || roleNodes.length === 0) {
|
||
return { idCollector, parentMap };
|
||
}
|
||
|
||
for (const node of roleNodes) {
|
||
const roleId = Number(node && node.role_id);
|
||
if (Number.isFinite(roleId) && roleId > 0) {
|
||
idCollector.push(roleId);
|
||
parentMap.set(roleId, Number(node && node.pid ? node.pid : 0));
|
||
}
|
||
|
||
const children = Array.isArray(node && node.children) ? node.children : [];
|
||
this.flattenRoleTreeMeta(children, idCollector, parentMap);
|
||
}
|
||
|
||
return { idCollector, parentMap };
|
||
}
|
||
|
||
async resolveAssignableRoleScope() {
|
||
const roleResult = await this.ctx.service.systems.setting.role.list({
|
||
includeDisabled: false,
|
||
includeSystem: false,
|
||
});
|
||
|
||
const roleTree = roleResult && roleResult.data && Array.isArray(roleResult.data.roles)
|
||
? roleResult.data.roles
|
||
: [];
|
||
const { idCollector, parentMap } = this.flattenRoleTreeMeta(roleTree, [], new Map());
|
||
return {
|
||
roleIdSet: new Set(idCollector),
|
||
parentMap,
|
||
};
|
||
}
|
||
|
||
pruneDescendantRoleIds(roleIds, parentMap) {
|
||
const selected = new Set(roleIds);
|
||
const pruned = [];
|
||
|
||
for (const roleId of roleIds) {
|
||
let current = roleId;
|
||
let keep = true;
|
||
const visited = new Set();
|
||
let parentId = Number(parentMap.get(current) || 0);
|
||
|
||
while (Number.isFinite(parentId) && parentId > 0) {
|
||
if (visited.has(parentId)) {
|
||
break;
|
||
}
|
||
visited.add(parentId);
|
||
|
||
if (selected.has(parentId)) {
|
||
keep = false;
|
||
break;
|
||
}
|
||
|
||
current = parentId;
|
||
parentId = Number(parentMap.get(current) || 0);
|
||
}
|
||
|
||
if (keep) {
|
||
pruned.push(roleId);
|
||
}
|
||
}
|
||
|
||
return Array.from(new Set(pruned));
|
||
}
|
||
|
||
async resolveRequestedRoleIds(data = {}, options = {}) {
|
||
const required = options.required === true;
|
||
const hasIds = Object.prototype.hasOwnProperty.call(data, 'ids');
|
||
const hasRoleIds = Object.prototype.hasOwnProperty.call(data, 'role_ids');
|
||
|
||
if (!hasIds && !hasRoleIds) {
|
||
if (required) {
|
||
throw this.createError('ids 参数不能为空', 400);
|
||
}
|
||
return null;
|
||
}
|
||
|
||
const rawRoleIds = hasIds ? data.ids : data.role_ids;
|
||
const roleIds = this.normalizeRoleIds(rawRoleIds);
|
||
|
||
const { roleIdSet, parentMap } = await this.resolveAssignableRoleScope();
|
||
if (roleIdSet.size === 0) {
|
||
throw this.createError('当前角色范围为空,无法分配角色', 400);
|
||
}
|
||
|
||
const outOfScopeIds = roleIds.filter(roleId => !roleIdSet.has(roleId));
|
||
if (outOfScopeIds.length > 0) {
|
||
throw this.createError(`包含超出当前角色范围的角色ID:${outOfScopeIds.join(',')}`, 400);
|
||
}
|
||
|
||
return this.pruneDescendantRoleIds(roleIds, parentMap);
|
||
}
|
||
|
||
async replaceEmployeeRoles(employeeId, roleIds) {
|
||
const { ctx } = this;
|
||
|
||
await ctx.model.EmployeeRole.destroy({
|
||
where: {
|
||
employee_id: employeeId,
|
||
},
|
||
});
|
||
|
||
const rows = roleIds.map(roleId => ({
|
||
employee_id: employeeId,
|
||
role_id: roleId,
|
||
}));
|
||
|
||
await ctx.model.EmployeeRole.bulkCreate(rows);
|
||
}
|
||
|
||
async buildEmployeeRoleGroupMap(employeeIds) {
|
||
const { ctx, app } = this;
|
||
const { Op } = app.Sequelize;
|
||
|
||
if (!Array.isArray(employeeIds) || employeeIds.length === 0) {
|
||
return new Map();
|
||
}
|
||
|
||
const employeeRoleRows = await ctx.model.EmployeeRole.findAll({
|
||
where: {
|
||
employee_id: employeeIds,
|
||
},
|
||
attributes: [ 'employee_id', 'role_id' ],
|
||
raw: true,
|
||
});
|
||
|
||
if (employeeRoleRows.length === 0) {
|
||
return new Map();
|
||
}
|
||
|
||
const roleIds = Array.from(new Set(employeeRoleRows
|
||
.map(item => Number(item.role_id))
|
||
.filter(roleId => Number.isFinite(roleId) && roleId > 0)));
|
||
|
||
const roleRows = await ctx.model.Role.findAll({
|
||
where: {
|
||
id: {
|
||
[Op.in]: roleIds,
|
||
},
|
||
},
|
||
attributes: [ 'id', 'role_code', 'role_name', 'pid', 'status' ],
|
||
raw: true,
|
||
});
|
||
const roleMap = new Map(roleRows.map(role => [ Number(role.id), role ]));
|
||
|
||
const employeeRoleMap = new Map();
|
||
for (const row of employeeRoleRows) {
|
||
const employeeId = Number(row.employee_id);
|
||
const roleId = Number(row.role_id);
|
||
if (!Number.isFinite(employeeId) || employeeId <= 0 || !Number.isFinite(roleId) || roleId <= 0) {
|
||
continue;
|
||
}
|
||
|
||
const role = roleMap.get(roleId);
|
||
if (!employeeRoleMap.has(employeeId)) {
|
||
employeeRoleMap.set(employeeId, {
|
||
role_ids: [],
|
||
roles: [],
|
||
});
|
||
}
|
||
|
||
const target = employeeRoleMap.get(employeeId);
|
||
target.role_ids.push(roleId);
|
||
target.roles.push({
|
||
role_id: roleId,
|
||
role_code: role && role.role_code ? role.role_code : '',
|
||
role_name: role && role.role_name ? role.role_name : '',
|
||
pid: role ? Number(role.pid || 0) : 0,
|
||
status: role ? Number(role.status) : 0,
|
||
});
|
||
}
|
||
|
||
for (const value of employeeRoleMap.values()) {
|
||
value.role_ids = Array.from(new Set(value.role_ids)).sort((a, b) => a - b);
|
||
value.roles.sort((a, b) => a.role_id - b.role_id);
|
||
}
|
||
|
||
return employeeRoleMap;
|
||
}
|
||
|
||
async buildWechatBindingMap(accountIds) {
|
||
if (!Array.isArray(accountIds) || accountIds.length === 0) {
|
||
return new Map();
|
||
}
|
||
|
||
const normalizedAccountIds = Array.from(new Set(accountIds
|
||
.map(accountId => Number(accountId))
|
||
.filter(accountId => Number.isFinite(accountId) && accountId > 0)));
|
||
if (normalizedAccountIds.length === 0) {
|
||
return new Map();
|
||
}
|
||
|
||
const ye4sClient = this.ctx.app.mysql.get('ye4s');
|
||
const bindingRows = await ye4sClient.select('ye4s_user', {
|
||
where: {
|
||
wms_account_id: normalizedAccountIds,
|
||
},
|
||
columns: [ 'id', 'wms_account_id' ],
|
||
orders: [[ 'id', 'DESC' ]],
|
||
});
|
||
|
||
const bindingMap = new Map();
|
||
for (const row of bindingRows) {
|
||
const accountId = Number(row && row.wms_account_id);
|
||
const ye4sUserId = Number(row && row.id);
|
||
if (!Number.isFinite(accountId) || accountId <= 0 || !Number.isFinite(ye4sUserId) || ye4sUserId <= 0) {
|
||
continue;
|
||
}
|
||
if (!bindingMap.has(accountId)) {
|
||
bindingMap.set(accountId, {
|
||
is_wechat_bound: true,
|
||
ye4s_user_id: ye4sUserId,
|
||
});
|
||
}
|
||
}
|
||
|
||
return bindingMap;
|
||
}
|
||
|
||
async getOperableEmployeeByAccountId(accountId, options = {}) {
|
||
const { ctx } = this;
|
||
const storeId = this.getCurrentStoreId();
|
||
const normalizedAccountId = this.normalizeAccountId(accountId, 'user_id');
|
||
const where = {
|
||
account_id: normalizedAccountId,
|
||
store_id: storeId,
|
||
};
|
||
|
||
if (options.includeDisabled !== true) {
|
||
where.status = 1;
|
||
}
|
||
|
||
const employees = await ctx.model.AccountStoreEmployee.findAll({
|
||
where,
|
||
order: [[ 'status', 'DESC' ], [ 'id', 'ASC' ]],
|
||
});
|
||
|
||
if (employees.length === 0) {
|
||
throw this.createError('目标账号不存在或无权限操作', 404);
|
||
}
|
||
|
||
const { roleIdSet } = await this.resolveAssignableRoleScope();
|
||
if (roleIdSet.size === 0) {
|
||
throw this.createError('当前角色范围为空,无法操作目标账号', 400);
|
||
}
|
||
|
||
const employeeIds = employees
|
||
.map(item => Number(item.id))
|
||
.filter(employeeId => Number.isFinite(employeeId) && employeeId > 0);
|
||
const employeeRoleMap = await this.buildEmployeeRoleGroupMap(employeeIds);
|
||
|
||
for (const employee of employees) {
|
||
const employeeId = Number(employee.id);
|
||
const roleGroup = employeeRoleMap.get(employeeId) || {
|
||
role_ids: [],
|
||
roles: [],
|
||
};
|
||
const hasOutOfScopeRole = roleGroup.role_ids
|
||
.some(roleId => !roleIdSet.has(Number(roleId)));
|
||
if (!hasOutOfScopeRole) {
|
||
return {
|
||
employee,
|
||
roleGroup,
|
||
};
|
||
}
|
||
}
|
||
|
||
throw this.createError('目标账号超出当前操作范围', 403);
|
||
}
|
||
|
||
async formatEmployeeRow(employee, options = {}) {
|
||
let account = options.account || null;
|
||
if (!account) {
|
||
account = await this.getWmsClient().get('wms_account', {
|
||
id: employee.account_id,
|
||
});
|
||
}
|
||
const avatar = await this.getAvatarMeta(employee.id);
|
||
|
||
return {
|
||
employee_id: Number(employee.id),
|
||
account_id: Number(employee.account_id),
|
||
store_id: Number(employee.store_id),
|
||
real_name: employee.real_name || '',
|
||
status: Number(employee.status),
|
||
created_at: employee.created_at,
|
||
updated_at: employee.updated_at,
|
||
username: account && account.username ? account.username : '',
|
||
phone: account && account.phone ? account.phone : '',
|
||
email: account && account.email ? account.email : '',
|
||
account_real_name: account && account.real_name ? account.real_name : '',
|
||
...avatar,
|
||
};
|
||
}
|
||
|
||
async list(data = {}) {
|
||
const { ctx, app } = this;
|
||
const { Op } = app.Sequelize;
|
||
|
||
const storeId = this.getCurrentStoreId();
|
||
const currentEmployeeId = this.getCurrentEmployeeId();
|
||
const normalizedWhere = ctx.where && typeof ctx.where === 'object'
|
||
? { ...ctx.where }
|
||
: (data.where && typeof data.where === 'object' ? { ...data.where } : {});
|
||
let parsedResult = ctx.whereParsed;
|
||
if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) {
|
||
const parsed = parseWhereConditions({
|
||
where: normalizedWhere,
|
||
app,
|
||
specialFieldMap: this.getListWhereSpecialFieldMap(),
|
||
});
|
||
if (!parsed.ok) {
|
||
throw this.createError(`where 参数解析失败: ${parsed.reason}`, 400);
|
||
}
|
||
parsedResult = parsed.result;
|
||
}
|
||
|
||
const andConditions = [
|
||
{
|
||
store_id: storeId,
|
||
},
|
||
];
|
||
const hasWhereStatus = Object.prototype.hasOwnProperty.call(normalizedWhere, 'status');
|
||
if (!hasWhereStatus) {
|
||
const statusFilter = data.includeDisabled === true
|
||
? undefined
|
||
: (data.status === 0 || data.status === '0' ? 0 : 1);
|
||
if (statusFilter === 0 || statusFilter === 1) {
|
||
andConditions.push({ status: statusFilter });
|
||
}
|
||
}
|
||
|
||
const dynamicConditions = parsedResult.dynamicConditions || [];
|
||
if (dynamicConditions.length > 0) {
|
||
andConditions.push({ [Op.and]: dynamicConditions });
|
||
}
|
||
|
||
const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|
||
|| normalizedWhere.quickWhere
|
||
|| null;
|
||
const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object'
|
||
? quickWhereInput.value
|
||
: quickWhereInput;
|
||
if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') {
|
||
const keyword = String(quickWhereValue).trim();
|
||
andConditions.push({
|
||
[Op.or]: [
|
||
{ real_name: { [Op.like]: `%${keyword}%` } },
|
||
{ '$account.username$': { [Op.like]: `%${keyword}%` } },
|
||
{ '$account.phone$': { [Op.like]: `%${keyword}%` } },
|
||
{ '$account.email$': { [Op.like]: `%${keyword}%` } },
|
||
],
|
||
});
|
||
}
|
||
|
||
const employees = await ctx.model.AccountStoreEmployee.findAll({
|
||
where: {
|
||
[Op.and]: andConditions,
|
||
},
|
||
include: [
|
||
{
|
||
model: ctx.model.Account,
|
||
as: 'account',
|
||
attributes: [ 'id', 'username', 'phone', 'email', 'real_name' ],
|
||
required: false,
|
||
},
|
||
],
|
||
order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]],
|
||
});
|
||
|
||
const { roleIdSet } = await this.resolveAssignableRoleScope();
|
||
if (roleIdSet.size === 0) {
|
||
return {
|
||
code: 200,
|
||
data: [],
|
||
};
|
||
}
|
||
|
||
const employeeIds = employees
|
||
.map(employee => Number(employee.id))
|
||
.filter(employeeId => Number.isFinite(employeeId) && employeeId > 0);
|
||
const employeeRoleMap = await this.buildEmployeeRoleGroupMap(employeeIds);
|
||
const accountIds = employees
|
||
.map(employee => Number(employee.account_id))
|
||
.filter(accountId => Number.isFinite(accountId) && accountId > 0);
|
||
const wechatBindingMap = await this.buildWechatBindingMap(accountIds);
|
||
|
||
const list = [];
|
||
for (const employee of employees) {
|
||
const employeeId = Number(employee.id);
|
||
if (currentEmployeeId && employeeId === currentEmployeeId) {
|
||
continue;
|
||
}
|
||
|
||
const roleGroup = employeeRoleMap.get(employeeId) || {
|
||
role_ids: [],
|
||
roles: [],
|
||
};
|
||
|
||
// 只展示当前账号可分配范围内的工号,避免越权操作。
|
||
const hasOutOfScopeRole = roleGroup.role_ids
|
||
.some(roleId => !roleIdSet.has(Number(roleId)));
|
||
if (hasOutOfScopeRole) {
|
||
continue;
|
||
}
|
||
|
||
const wechatBinding = wechatBindingMap.get(Number(employee.account_id)) || {
|
||
is_wechat_bound: false,
|
||
ye4s_user_id: null,
|
||
};
|
||
|
||
list.push({
|
||
...await this.formatEmployeeRow(employee, {
|
||
account: employee.account,
|
||
}),
|
||
is_wechat_bound: wechatBinding.is_wechat_bound,
|
||
ye4s_user_id: wechatBinding.ye4s_user_id,
|
||
role_ids: roleGroup.role_ids,
|
||
roles: roleGroup.roles,
|
||
});
|
||
}
|
||
|
||
return {
|
||
code: 200,
|
||
data: list,
|
||
};
|
||
}
|
||
|
||
async add(data = {}) {
|
||
const { ctx, service } = this;
|
||
let createdAccountId = 0;
|
||
|
||
try {
|
||
const storeId = this.getCurrentStoreId();
|
||
const phone = this.normalizePhone(data.phone);
|
||
const realName = this.normalizeName(data.real_name || data.realName);
|
||
const password = typeof data.password === 'string' && data.password.trim()
|
||
? data.password.trim()
|
||
: '111111';
|
||
|
||
if (!phone) {
|
||
throw this.createError('phone 参数不能为空', 400);
|
||
}
|
||
if (!this.isValidPhone(phone)) {
|
||
throw this.createError('phone 格式不正确', 400);
|
||
}
|
||
if (!realName) {
|
||
throw this.createError('real_name 参数不能为空', 400);
|
||
}
|
||
if (realName === RESERVED_EMPLOYEE_NAME) {
|
||
throw this.createError(`新增工号禁止直接使用保留名称 ${RESERVED_EMPLOYEE_NAME}`, 400);
|
||
}
|
||
|
||
const roleIds = await this.resolveRequestedRoleIds(data, {
|
||
required: true,
|
||
});
|
||
let account = await this.findRawAccountByPhone(phone);
|
||
|
||
if (account && Number(account.status) !== 1) {
|
||
throw this.createError('该手机号对应账号已禁用,无法新增工号', 409);
|
||
}
|
||
|
||
if (!account) {
|
||
let username = this.normalizeUsername(data.username);
|
||
if (!username) {
|
||
username = this.generateUsername();
|
||
}
|
||
|
||
const existingUsername = await this.findRawAccountByUsername(username);
|
||
if (existingUsername) {
|
||
throw this.createError('username 已存在', 409);
|
||
}
|
||
|
||
const salt = service.systems.auth.user.generateSalt();
|
||
const passwordHash = await service.systems.auth.user.encryptPassword(password, salt);
|
||
const email = typeof data.email === 'string' && data.email.trim()
|
||
? data.email.trim()
|
||
: `${username}@autotest.local`;
|
||
|
||
const insertRet = await this.getWmsClient().insert('wms_account', {
|
||
username,
|
||
phone,
|
||
email,
|
||
password_hash: passwordHash,
|
||
real_name: realName,
|
||
status: 1,
|
||
salt,
|
||
created_at: new Date(),
|
||
updated_at: new Date(),
|
||
});
|
||
|
||
createdAccountId = Number(insertRet && insertRet.insertId ? insertRet.insertId : 0);
|
||
account = await this.getWmsClient().get('wms_account', { id: createdAccountId });
|
||
}
|
||
|
||
const activeBinding = await ctx.model.AccountStoreEmployee.findOne({
|
||
where: {
|
||
account_id: account.id,
|
||
store_id: storeId,
|
||
status: 1,
|
||
},
|
||
});
|
||
if (activeBinding) {
|
||
throw this.createError('该手机号已绑定当前主体工号', 409);
|
||
}
|
||
|
||
const { employee } = await service.systems.store.ensureEmployeeRoleBinding({
|
||
accountId: Number(account.id),
|
||
storeId,
|
||
roleId: roleIds[0],
|
||
realName,
|
||
});
|
||
|
||
await this.replaceEmployeeRoles(Number(employee.id), roleIds);
|
||
|
||
await service.systems.auth.user.clearUserCache(Number(account.id));
|
||
|
||
const formatted = await this.formatEmployeeRow(employee);
|
||
return {
|
||
code: 200,
|
||
data: {
|
||
...formatted,
|
||
role_id: roleIds[0],
|
||
role_ids: roleIds,
|
||
is_new_account: createdAccountId > 0,
|
||
},
|
||
};
|
||
} catch (error) {
|
||
if (createdAccountId > 0) {
|
||
await this.getWmsClient().delete('wms_account', { id: createdAccountId });
|
||
}
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
async delete(data = {}) {
|
||
const { ctx, service } = this;
|
||
|
||
const storeId = this.getCurrentStoreId();
|
||
const currentEmployeeId = this.getCurrentEmployeeId();
|
||
const employeeId = Number(data.employee_id || data.id || 0);
|
||
|
||
if (!employeeId) {
|
||
throw this.createError('employee_id 参数不能为空', 400);
|
||
}
|
||
if (currentEmployeeId && employeeId === currentEmployeeId) {
|
||
throw this.createError('不允许删除当前登录工号', 400);
|
||
}
|
||
|
||
const employee = await ctx.model.AccountStoreEmployee.findOne({
|
||
where: {
|
||
id: employeeId,
|
||
store_id: storeId,
|
||
},
|
||
});
|
||
if (!employee) {
|
||
throw this.createError('工号不存在或无权限删除', 404);
|
||
}
|
||
|
||
if (Number(employee.status) !== 1) {
|
||
return {
|
||
code: 200,
|
||
data: {
|
||
employee_id: employeeId,
|
||
account_id: Number(employee.account_id),
|
||
status: 'deleted',
|
||
already_deleted: true,
|
||
},
|
||
};
|
||
}
|
||
|
||
await employee.update({
|
||
status: 0,
|
||
updated_at: new Date(),
|
||
});
|
||
|
||
await ctx.model.AccountPlatformActive.destroy({
|
||
where: {
|
||
employee_id: employeeId,
|
||
},
|
||
});
|
||
|
||
await service.systems.auth.user.clearUserCache(Number(employee.account_id));
|
||
|
||
return {
|
||
code: 200,
|
||
data: {
|
||
employee_id: employeeId,
|
||
account_id: Number(employee.account_id),
|
||
status: 'deleted',
|
||
},
|
||
};
|
||
}
|
||
|
||
async update(data = {}) {
|
||
const { ctx, service } = this;
|
||
|
||
const storeId = this.getCurrentStoreId();
|
||
const employeeId = Number(data.employee_id || data.id || 0);
|
||
const hasRealName = Object.prototype.hasOwnProperty.call(data, 'real_name') || Object.prototype.hasOwnProperty.call(data, 'realName');
|
||
const hasFileId = Object.prototype.hasOwnProperty.call(data, 'file_id') || Object.prototype.hasOwnProperty.call(data, 'avatar_file_id') || Object.prototype.hasOwnProperty.call(data, 'fileId');
|
||
const hasRoleIds = Object.prototype.hasOwnProperty.call(data, 'ids') || Object.prototype.hasOwnProperty.call(data, 'role_ids');
|
||
const realName = this.normalizeName(data.real_name || data.realName);
|
||
const fileId = Number(data.file_id || data.avatar_file_id || data.fileId || 0);
|
||
|
||
if (!employeeId) {
|
||
throw this.createError('employee_id 参数不能为空', 400);
|
||
}
|
||
if (!hasRoleIds) {
|
||
throw this.createError('ids 参数不能为空', 400);
|
||
}
|
||
if (hasRealName && !realName) {
|
||
throw this.createError('real_name 参数不能为空', 400);
|
||
}
|
||
if (hasFileId && !fileId) {
|
||
throw this.createError('file_id 参数不能为空', 400);
|
||
}
|
||
|
||
const employee = await ctx.model.AccountStoreEmployee.findOne({
|
||
where: {
|
||
id: employeeId,
|
||
store_id: storeId,
|
||
status: 1,
|
||
},
|
||
});
|
||
if (!employee) {
|
||
throw this.createError('工号不存在或无权限更新', 404);
|
||
}
|
||
|
||
if (hasRealName && realName !== employee.real_name) {
|
||
await employee.update({
|
||
real_name: realName,
|
||
updated_at: new Date(),
|
||
});
|
||
}
|
||
|
||
if (hasFileId) {
|
||
const file = await ctx.model.File.findOne({
|
||
where: {
|
||
id: fileId,
|
||
is_deleted: false,
|
||
},
|
||
});
|
||
if (!file) {
|
||
throw this.createError('头像文件不存在', 404);
|
||
}
|
||
|
||
await service.systems.file.ReferenceFile({
|
||
id: employeeId,
|
||
type: 'avater',
|
||
images: [
|
||
{
|
||
file_id: fileId,
|
||
sort_order: 0,
|
||
},
|
||
],
|
||
});
|
||
}
|
||
|
||
const roleIds = await this.resolveRequestedRoleIds(data, {
|
||
required: true,
|
||
});
|
||
await this.replaceEmployeeRoles(employeeId, roleIds);
|
||
|
||
await service.systems.auth.user.clearUserCache(Number(employee.account_id));
|
||
|
||
const refreshed = await ctx.model.AccountStoreEmployee.findByPk(employeeId);
|
||
const roleRows = await ctx.model.EmployeeRole.findAll({
|
||
where: {
|
||
employee_id: employeeId,
|
||
},
|
||
attributes: [ 'role_id' ],
|
||
order: [[ 'role_id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
const boundRoleIds = roleRows
|
||
.map(item => Number(item.role_id))
|
||
.filter(roleId => Number.isFinite(roleId) && roleId > 0);
|
||
|
||
return {
|
||
code: 200,
|
||
data: {
|
||
...await this.formatEmployeeRow(refreshed),
|
||
role_ids: Array.from(new Set(boundRoleIds)),
|
||
},
|
||
};
|
||
}
|
||
|
||
async getBindWechatCode(data = {}) {
|
||
const { service } = this.ctx;
|
||
const accountId = data.user_id || data.account_id || data.id;
|
||
const { employee } = await this.getOperableEmployeeByAccountId(accountId);
|
||
const result = await service.systems.auth.user.getBindWechatCodeByAccountId(Number(employee.account_id), data, {
|
||
missingAccountMessage: '目标账号不存在,无法生成绑定码',
|
||
});
|
||
|
||
if (!result || Number(result.code) !== 200) {
|
||
throw this.createError(result && result.message ? result.message : '获取绑定码失败', Number(result && result.code) || 500);
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
async unbindWechat(data = {}) {
|
||
const { service } = this.ctx;
|
||
const accountId = data.user_id || data.account_id || data.id;
|
||
const { employee } = await this.getOperableEmployeeByAccountId(accountId);
|
||
const result = await service.systems.auth.user.unbindWechatByAccountId(Number(employee.account_id), {
|
||
missingAccountMessage: '目标账号不存在,无法解绑',
|
||
});
|
||
|
||
if (!result || Number(result.code) !== 200) {
|
||
throw this.createError(result && result.message ? result.message : '解绑失败', Number(result && result.code) || 500);
|
||
}
|
||
|
||
return result;
|
||
}
|
||
}
|
||
|
||
module.exports = SettingAccountService;
|