user.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. import { MerchantEntity } from './../../../payment/entity/merchant';
  2. import { Inject, InjectClient, Provide } from '@midwayjs/decorator';
  3. import { BaseService, CoolCommException } from '@cool-midway/core';
  4. import { InjectEntityModel } from '@midwayjs/typeorm';
  5. import { Equal, In, Repository } from 'typeorm';
  6. import { BaseSysUserEntity } from '../../entity/sys/user';
  7. import { BaseSysPermsService } from './perms';
  8. import * as _ from 'lodash';
  9. import { BaseSysUserRoleEntity } from '../../entity/sys/user_role';
  10. import * as md5 from 'md5';
  11. import { BaseSysDepartmentEntity } from '../../entity/sys/department';
  12. import { CachingFactory, MidwayCache } from '@midwayjs/cache-manager';
  13. import { IndividualEntity } from './../../../payment/entity/individual';
  14. import { BusinessEntity } from './../../../payment/entity/business';
  15. /**
  16. * 系统用户
  17. */
  18. @Provide()
  19. export class BaseSysUserService extends BaseService {
  20. @InjectEntityModel(BaseSysUserEntity)
  21. baseSysUserEntity: Repository<BaseSysUserEntity>;
  22. @InjectEntityModel(MerchantEntity)
  23. merchantEntity: Repository<MerchantEntity>;
  24. @InjectEntityModel(BaseSysUserRoleEntity)
  25. baseSysUserRoleEntity: Repository<BaseSysUserRoleEntity>;
  26. @InjectEntityModel(BaseSysDepartmentEntity)
  27. baseSysDepartmentEntity: Repository<BaseSysDepartmentEntity>;
  28. @InjectEntityModel(IndividualEntity)
  29. individualEntity: Repository<IndividualEntity>;
  30. @InjectEntityModel(BusinessEntity)
  31. businessEntity: Repository<BusinessEntity>;
  32. @InjectClient(CachingFactory, 'default')
  33. midwayCache: MidwayCache;
  34. @Inject()
  35. baseSysPermsService: BaseSysPermsService;
  36. @Inject()
  37. ctx;
  38. /**
  39. * 分页查询
  40. * @param query
  41. */
  42. async page(query) {
  43. const { keyWord, status, departmentIds = [] } = query;
  44. const permsDepartmentArr = await this.baseSysPermsService.departmentIds(
  45. this.ctx.admin.userId
  46. ); // 部门权限
  47. const sql = `
  48. SELECT
  49. a.id,a.name,a.nickName,a.headImg,a.email,a.remark,a.status,a.createTime,a.updateTime,a.username,a.phone,a.departmentId,
  50. b.name as "departmentName"
  51. FROM
  52. base_sys_user a
  53. LEFT JOIN base_sys_department b on a.departmentId = b.id
  54. WHERE 1 = 1
  55. ${this.setSql(
  56. !_.isEmpty(departmentIds),
  57. 'and a.departmentId in (?)',
  58. [departmentIds]
  59. )}
  60. ${this.setSql(status, 'and a.status = ?', [status])}
  61. ${this.setSql(keyWord, 'and (a.name LIKE ? or a.username LIKE ?)', [
  62. `%${keyWord}%`,
  63. `%${keyWord}%`,
  64. ])}
  65. ${this.setSql(true, 'and a.username != ?', ['admin'])}
  66. ${this.setSql(
  67. this.ctx.admin.username !== 'admin',
  68. 'and a.departmentId in (?)',
  69. [!_.isEmpty(permsDepartmentArr) ? permsDepartmentArr : [null]]
  70. )} `;
  71. const result = await this.sqlRenderPage(sql, query);
  72. // 匹配角色
  73. if (!_.isEmpty(result.list)) {
  74. const userIds = result.list.map(e => e.id);
  75. const roles = await this.nativeQuery(
  76. 'SELECT b.name, a.userId FROM base_sys_user_role a LEFT JOIN base_sys_role b ON a.roleId = b.id WHERE a.userId in (?) ',
  77. [userIds]
  78. );
  79. result.list.forEach(e => {
  80. e['roleName'] = roles
  81. .filter(role => role.userId == e.id)
  82. .map(role => role.name)
  83. .join(',');
  84. });
  85. }
  86. return result;
  87. }
  88. /**
  89. * 移动部门
  90. * @param departmentId
  91. * @param userIds
  92. */
  93. async move(departmentId, userIds) {
  94. await this.baseSysUserEntity.update({ id: In(userIds) }, { departmentId });
  95. }
  96. /**
  97. * 获得个人信息
  98. */
  99. async person(userId) {
  100. const info = await this.baseSysUserEntity.findOneBy({
  101. id: Equal(userId),
  102. });
  103. // 只获取基本商户信息
  104. const merchant = await this.merchantEntity.findOne({
  105. where: {
  106. userId: Equal(userId),
  107. },
  108. });
  109. // 如果需要获取关联信息,可以分别查询
  110. let individualInfo = null;
  111. let businessInfo = null;
  112. if (merchant) {
  113. // 分别查询个人或企业信息
  114. individualInfo = await this.individualEntity.findOneBy({
  115. merchantId: merchant.mchId
  116. });
  117. businessInfo = await this.businessEntity.findOneBy({
  118. merchantId: merchant.mchId
  119. });
  120. }
  121. delete info?.password;
  122. return {
  123. ...info,
  124. merchant: merchant
  125. ? {
  126. ...merchant,
  127. individual: individualInfo,
  128. business: businessInfo,
  129. }
  130. : null,
  131. };
  132. }
  133. /**
  134. * 更新用户角色关系
  135. * @param user
  136. */
  137. async updateUserRole(user) {
  138. if (_.isEmpty(user.roleIdList)) {
  139. return;
  140. }
  141. if (user.username === 'admin') {
  142. throw new CoolCommException('非法操作~');
  143. }
  144. await this.baseSysUserRoleEntity.delete({ userId: user.id });
  145. if (user.roleIdList) {
  146. for (const roleId of user.roleIdList) {
  147. await this.baseSysUserRoleEntity.save({ userId: user.id, roleId });
  148. }
  149. }
  150. await this.baseSysPermsService.refreshPerms(user.id);
  151. }
  152. /**
  153. * 新增
  154. * @param param
  155. */
  156. async add(param) {
  157. const exists = await this.baseSysUserEntity.findOneBy({
  158. username: param.username,
  159. });
  160. if (!_.isEmpty(exists)) {
  161. throw new CoolCommException('用户名已经存在~');
  162. }
  163. param.password = md5(param.password);
  164. await this.baseSysUserEntity.save(param);
  165. await this.updateUserRole(param);
  166. return param.id;
  167. }
  168. /**
  169. * 根据ID获得信息
  170. * @param id
  171. */
  172. public async info(id) {
  173. const info = await this.baseSysUserEntity.findOneBy({ id });
  174. const userRoles = await this.nativeQuery(
  175. 'select a.roleId from base_sys_user_role a where a.userId = ?',
  176. [id]
  177. );
  178. const department = await this.baseSysDepartmentEntity.findOneBy({
  179. id: info.departmentId,
  180. });
  181. if (info) {
  182. delete info.password;
  183. if (userRoles) {
  184. info.roleIdList = userRoles.map(e => {
  185. return parseInt(e.roleId);
  186. });
  187. }
  188. }
  189. delete info.password;
  190. if (department) {
  191. info.departmentName = department.name;
  192. }
  193. return info;
  194. }
  195. /**
  196. * 修改个人信息
  197. * @param param
  198. */
  199. public async personUpdate(param) {
  200. param.id = this.ctx.admin.userId;
  201. if (!_.isEmpty(param.password)) {
  202. param.password = md5(param.password);
  203. const oldPassword = md5(param.oldPassword);
  204. const userInfo = await this.baseSysUserEntity.findOneBy({ id: param.id });
  205. if (!userInfo) {
  206. throw new CoolCommException('用户不存在');
  207. }
  208. if (oldPassword !== userInfo.password) {
  209. throw new CoolCommException('原密码错误');
  210. }
  211. param.passwordV = userInfo.passwordV + 1;
  212. await this.midwayCache.set(
  213. `admin:passwordVersion:${param.id}`,
  214. param.passwordV
  215. );
  216. } else {
  217. delete param.password;
  218. }
  219. await this.baseSysUserEntity.save(param);
  220. }
  221. /**
  222. * 修改
  223. * @param param 数据
  224. */
  225. async update(param) {
  226. if (param.id && param.username === 'admin') {
  227. throw new CoolCommException('非法操作~');
  228. }
  229. if (!_.isEmpty(param.password)) {
  230. param.password = md5(param.password);
  231. const userInfo = await this.baseSysUserEntity.findOneBy({ id: param.id });
  232. if (!userInfo) {
  233. throw new CoolCommException('用户不存在');
  234. }
  235. param.passwordV = userInfo.passwordV + 1;
  236. await this.midwayCache.set(
  237. `admin:passwordVersion:${param.id}`,
  238. param.passwordV
  239. );
  240. } else {
  241. delete param.password;
  242. }
  243. if (param.status === 0) {
  244. await this.forbidden(param.id);
  245. }
  246. await this.baseSysUserEntity.save(param);
  247. await this.updateUserRole(param);
  248. }
  249. /**
  250. * 禁用用户
  251. * @param userId
  252. */
  253. async forbidden(userId) {
  254. await this.midwayCache.del(`admin:token:${userId}`);
  255. }
  256. }