sysUserService.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. 'use strict';
  2. const uuid = require('uuid/v1');
  3. const md5 = require('md5');
  4. const Service = require('../service/baseService');
  5. const mongoose = require('mongoose');
  6. const { sma4: sm4 } = require('../util/sm4');
  7. class SysUserService extends Service {
  8. tag() {
  9. return this.ctx.model.SysUserModel;
  10. }
  11. async login(data) {
  12. const { model } = this.ctx;
  13. const pop = this.ctx.getUserPop();
  14. const result = await model.SysUserModel
  15. .find({ loginName: data.loginName, loginPwd: data.loginPwd })
  16. .populate(pop);
  17. if (result.length === 1) {
  18. const newUser = JSON.parse(JSON.stringify(result[0]));
  19. newUser.sessionId = uuid()
  20. .replace(/-/g, '');
  21. delete newUser.loginPwd;
  22. await this.app.redis.set(newUser.sessionId, JSON.stringify(newUser), 'EX',
  23. this.ctx.app.config.sessionTimeOut);
  24. return newUser.sessionId;
  25. }
  26. return null;
  27. }
  28. async updatePwdWithOpenId(query) {
  29. const { ctx, service } = this;
  30. const { oldPwd, pwd } = query;
  31. const users = await service.sysUserService.list({ openId: ctx.openId, loginPwd: md5(oldPwd) });
  32. if (users.length === 1) {
  33. return await service.sysUserService.update(users[0]._id, { loginPwd: md5(pwd) });
  34. }
  35. return null;
  36. }
  37. async bing(query) {
  38. const { service, ctx } = this;
  39. const { name, pwd, openId } = query;
  40. const user = ctx.user;
  41. const result = await service.sysUserService.oneData({ loginName: name, loginPwd: pwd });
  42. if (result) {
  43. if ('' + result.role._id === this.app.config.defaultUserRoleId) { // 采集员
  44. if (user && user.loginName === name) {
  45. console.log('user.loginName === name' + name);
  46. return null;
  47. }
  48. if (!result.openId || result.openId === '') {
  49. if (result.file && result.file !== '') {
  50. if (result.userName && result.sex
  51. && result.company && result.job
  52. && result.politicalOutlook && result.phone) {
  53. const res = await service.sysUserService.update(result._id, { openId: ctx.get('openId') });
  54. // const res = await service.sysUserService.update(result._id, { openId });
  55. console.log('result._id=======' + result._id);
  56. console.log('openId===========' + ctx.get('openId'));
  57. console.log('updateRes========' + JSON.stringify(res));
  58. return null;
  59. }
  60. return '请管理员到后台完善资料方可登录!';
  61. }
  62. return '请管理员到后台上传认证文件方可登录!';
  63. }
  64. return '该账号已被其他用户绑定!';
  65. }
  66. return '请使用采集员账号!';
  67. }
  68. return '用户名或者密码错误,请联系管理员!';
  69. }
  70. async deleteWithSub(data) {
  71. const { ctx, service } = this;
  72. const { model } = ctx;
  73. const infoList = await service.infoService.list({ userid: data.id });
  74. if (infoList.length > 0) {
  75. return ' 账号下已有采集数据,禁止删除 ';
  76. }
  77. const visitList = await service.visitService.list({ userid: data.id });
  78. if (visitList.length > 0) {
  79. return ' 账号下已有探访数据,禁止删除 ';
  80. }
  81. const user = await this.one(data.id, ctx.getUserPop());
  82. if (user.role._id == this.app.config.defaultAdminRoleId) {
  83. return '没有权限,不能删除';
  84. }
  85. if (data.userId == data.id) {
  86. return '不能删除自己';
  87. }
  88. await model.SysUserModel.deleteOne({ _id: data.id });
  89. return null;
  90. }
  91. async batchAdd(data) {
  92. const { model } = this.ctx;
  93. // 通过传来的 deptId 获取当前code
  94. const dept = await model.SysDeptModel.find({ _id: data.deptId });
  95. const code = dept[0].code;
  96. const level = dept[0].level;
  97. // dept1 - 5 前端传入 type 前端传入 admin 是管理员 user 是采集员
  98. if (data.type == 'admin') {
  99. delete data.type;
  100. // 生成管理员
  101. const users = await model.SysUserModel.find({
  102. loginName: code,
  103. role: this.app.config.defaultManagerRoleId, dept: data.deptId,
  104. });
  105. if (users.length > 0) {
  106. return { code: 1, data: {}, message: '当前地区已存在管理员' };
  107. }
  108. data.dept = data.deptId;
  109. data.role = this.app.config.defaultManagerRoleId;
  110. data.loginName = code;
  111. data.loginPwd = md5(this.app.config.defaultPassword);
  112. await model.SysUserModel.create(data);
  113. // 生成地区自主上报员
  114. if (level === '5') {
  115. const ownerCode = code + '000';
  116. const ownerUser = await model.SysUserModel.find({
  117. loginName: ownerCode,
  118. role: this.app.config.defaultOwnerManagerRoleId, dept: data.deptId,
  119. });
  120. if (ownerUser.length === 0) {
  121. data.role = this.app.config.defaultOwnerManagerRoleId;
  122. data.loginName = ownerCode;
  123. data.loginPwd = md5(this.app.config.defaultPassword);
  124. await model.SysUserModel.create(data);
  125. }
  126. }
  127. return { code: 0, data: {}, message: code };
  128. } else if (data.type == 'user' && data.deptId == data.dept5) {
  129. delete data.type;
  130. let str = '';
  131. const userCodes = [];
  132. let userNum = data.userNum || 1;
  133. userNum = parseInt(userNum) > 20 ? '20' : userNum;
  134. for (let i = 0; i < userNum; i++) {
  135. const users = await model.SysUserModel.find({
  136. role: this.app.config.defaultUserRoleId, dept: data.deptId,
  137. })
  138. .sort({ loginName: 1 });
  139. if (users.length > 0) {
  140. // 如果存在 就取最后一个
  141. let number = users[users.length - 1].loginName.replace(code, '');
  142. number = parseInt(number);
  143. number++;
  144. let num = '' + number;
  145. while (num.length < 3) {
  146. num = '0' + num;
  147. }
  148. data.dept = data.deptId;
  149. data.role = this.app.config.defaultUserRoleId;
  150. data.loginName = code + num;
  151. data.loginPwd = md5(this.app.config.defaultPassword);
  152. await model.SysUserModel.create(data);
  153. userCodes.push(code + num);
  154. } else {
  155. data.dept = data.deptId;
  156. data.role = this.app.config.defaultUserRoleId;
  157. data.loginName = code + '001';
  158. data.loginPwd = md5(this.app.config.defaultPassword);
  159. await model.SysUserModel.create(data);
  160. userCodes.push(code + '001');
  161. }
  162. }
  163. str += userCodes.join(',');
  164. // 生成采集员
  165. return { code: 0, data: {}, message: str };
  166. }
  167. return { code: 1, data: {}, message: '参数错误' };
  168. }
  169. // async valueByUser(data) {
  170. // const { ctx } = this;
  171. // const { model } = ctx;
  172. //
  173. // const result = await this.listForPage(data, ctx.getUserPop());
  174. // // const result = await this.listForPage(data);
  175. // const newResult = [];
  176. // for (const item of result.list) {
  177. // const valueInfoCount = await model.ValueModel.find({ userid: item._id, type: '0' })
  178. // .countDocuments();
  179. // const valueVisitCount = await model.ValueModel.find({ userid: item._id, type: '1' })
  180. // .countDocuments();
  181. // newResult.push({ _id: item._id,
  182. // loginName: item.loginName,
  183. // userName: item.userName,
  184. // dept: item.dept1.name + item.dept2.name + item.dept3.name + item.dept4.name + item.dept5.name,
  185. // valueInfoCount, valueVisitCount });
  186. // }
  187. //
  188. // return { list: newResult, count: result.count };
  189. // }
  190. // 积分数据列表查询---倒序显示
  191. async valueByUser(data) {
  192. const { ctx } = this;
  193. const { model } = ctx;
  194. // const page = parseInt(data.page);
  195. // const rows = parseInt(data.rows);
  196. const page = data.page || 1;
  197. const rows = Number.parseInt(data.rows) || this.app.config.defaultPageSize;
  198. const where = {};
  199. if (data.dept1) {
  200. where.dept1 = this.app.mongoose.Types.ObjectId(data.dept1);// 省
  201. }
  202. if (data.dept2) {
  203. where.dept2 = this.app.mongoose.Types.ObjectId(data.dept2); // 市
  204. }
  205. if (data.dept3) {
  206. where.dept3 = this.app.mongoose.Types.ObjectId(data.dept3); // 区
  207. }
  208. if (data.dept4) {
  209. where.dept4 = this.app.mongoose.Types.ObjectId(data.dept4); // 乡
  210. }
  211. if (data.dept5) {
  212. where.dept5 = this.app.mongoose.Types.ObjectId(data.dept5); // 社区
  213. }
  214. if (data.queryName) {
  215. const oneUser = await model.SysUserModel.find({ loginName: data.queryName });
  216. if (oneUser.length > 0) {
  217. where.userid = oneUser[0]._id;
  218. }
  219. }
  220. if (data.userName) {
  221. const oneUser = await model.SysUserModel.find({ userName: sm4.encrypt_ECB(data.userName) });
  222. if (oneUser.length > 0) {
  223. where.userid = oneUser[0]._id;
  224. }
  225. }
  226. const restltList = await this.ctx.model.ValueModel.aggregate([
  227. {
  228. $match: where,
  229. },
  230. { $group:
  231. {
  232. _id: '$userid',
  233. dept1: { $first: '$dept1' },
  234. dept2: { $first: '$dept2' },
  235. dept3: { $first: '$dept3' },
  236. dept4: { $first: '$dept4' },
  237. dept5: { $first: '$dept5' },
  238. type0: { $sum: {
  239. $cond: [{ $eq: [ '$type', '0' ] }, 1, 0 ], // 采集审核通过数
  240. } },
  241. type1: { $sum: {
  242. $cond: [{ $eq: [ '$type', '1' ] }, 1, 0 ], // 探访数
  243. } },
  244. },
  245. },
  246. { $project: {
  247. _id: 1,
  248. dept1: 1,
  249. dept2: 1,
  250. dept3: 1,
  251. dept4: 1,
  252. dept5: 1,
  253. type0: 1,
  254. type1: 1,
  255. totalValue: { $add: [{ $multiply: [ '$type0', 5 ] }, { $multiply: [ '$type1', 1 ] }] },
  256. } },
  257. { $sort: { totalValue: -1 } },
  258. {
  259. $skip: rows * (parseInt(page) - 1),
  260. },
  261. {
  262. $limit: rows,
  263. },
  264. { $lookup: { from: 'sys_user', localField: '_id', foreignField: '_id', as: 'user' } },
  265. { $unwind: { path: '$user', preserveNullAndEmptyArrays: true } },
  266. { $lookup: { from: 'sys_dept', localField: 'dept1', foreignField: '_id', as: 'dept1' } },
  267. { $unwind: { path: '$dept1', preserveNullAndEmptyArrays: true } },
  268. { $lookup: { from: 'sys_dept', localField: 'dept2', foreignField: '_id', as: 'dept2' } },
  269. { $unwind: { path: '$dept2', preserveNullAndEmptyArrays: true } },
  270. { $lookup: { from: 'sys_dept', localField: 'dept3', foreignField: '_id', as: 'dept3' } },
  271. { $unwind: { path: '$dept3', preserveNullAndEmptyArrays: true } },
  272. { $lookup: { from: 'sys_dept', localField: 'dept4', foreignField: '_id', as: 'dept4' } },
  273. { $unwind: { path: '$dept4', preserveNullAndEmptyArrays: true } },
  274. { $lookup: { from: 'sys_dept', localField: 'dept5', foreignField: '_id', as: 'dept5' } },
  275. { $unwind: { path: '$dept5', preserveNullAndEmptyArrays: true } },
  276. { $project: {
  277. _id: 1,
  278. loginName: '$user.loginName',
  279. userName: '$user.userName',
  280. valueInfoCount: '$type0',
  281. valueVisitCount: '$type1',
  282. totalValue: '$totalValue',
  283. dept: { $concat: [ '$dept1.name', '$dept2.name', '$dept3.name', '$dept4.name', '$dept5.name' ] },
  284. } },
  285. ]).allowDiskUse(true);// 允许使用磁盘缓存
  286. const countList = await this.ctx.model.ValueModel.aggregate([
  287. {
  288. $match: where,
  289. },
  290. { $group:
  291. {
  292. _id: '$userid',
  293. },
  294. },
  295. ]).allowDiskUse(true);// 允许使用磁盘缓存
  296. return { list: restltList, count: countList.length };
  297. }
  298. async valueByUserOne() {
  299. const { ctx } = this;
  300. const { model } = ctx;
  301. const user = ctx.user;
  302. const valueInfoCount = await model.ValueModel.find({ userid: user._id, type: '0' })
  303. .countDocuments();
  304. const valueVisitCount = await model.ValueModel.find({ userid: user._id, type: '1' })
  305. .countDocuments();
  306. return { _id: user._id, loginName: user.loginName, valueInfoCount, valueVisitCount };
  307. }
  308. // 个人积分排名
  309. async sumUserOne() {
  310. const { ctx } = this;
  311. const { model } = ctx;
  312. const user = ctx.user;
  313. // const infoCount = await model.InfoModel.aggregate([
  314. // { $match: { dept1: user.dept1._id, userid: user._id, status: '3' } },
  315. // { $group: { _id: '$_id', count: { $sum: 1 } } },
  316. // { $count: 'count' },
  317. // ]).allowDiskUse(true);
  318. const totalCount = await model.VisitModel.find({ userid: user._id }).countDocuments();
  319. const visitCount = await model.VisitModel.aggregate([
  320. { $match: { dept1: user.dept1._id, userid: user._id } },
  321. { $group: { _id: '$infoId', count: { $sum: 1 } } },
  322. { $count: 'count' },
  323. ]).allowDiskUse(true);
  324. const visitOrder = await model.VisitModel.aggregate([
  325. { $match: { dept1: user.dept1._id } },
  326. { $group: { _id: '$userid', count: { $sum: 1 } } }, // 地区下所有采集员的探访次数
  327. { $group: { _id: '$count', rank: { $sum: 1 } } }, // 探访次数 统计
  328. { $match: { _id: { $gt: totalCount } } }, // 排名
  329. { $group: { _id: null, count: { $sum: '$rank' } } },
  330. { $project: { _id: 0, count: 1 } },
  331. ]).allowDiskUse(true);
  332. if (visitOrder.length == 0) {
  333. const arr = { count: 0 };
  334. visitOrder.push(arr);
  335. }
  336. return { _id: user._id, loginName: user.loginName, userName: user.userName, totalCount, visitCount, visitOrder };
  337. }
  338. // getUserCond(data, page, rows, sort) {
  339. // const cond = [];
  340. //
  341. // cond.push({ $match: data });
  342. // console.log('提交件', data);
  343. //
  344. // if (sort) {
  345. // cond.push({ $sort: sort });
  346. // }
  347. // cond.push({ $skip: (page - 1) * rows });
  348. // cond.push({ $limit: rows });
  349. // cond.push({
  350. // $lookup:
  351. // {
  352. // from: 'value',
  353. // localField: '_id',
  354. // foreignField: 'userid',
  355. // as: 'values',
  356. // },
  357. // });
  358. // cond.push({ $unwind: { path: '$values', preserveNullAndEmptyArrays: true } });
  359. // cond.push({ $group:
  360. // {
  361. // _id: { id: '$_id', type: '$values.type' },
  362. // loginName: { $first: '$loginName' },
  363. // counter: { $sum: {
  364. // $cond: [ '$values', 1, 0 ],
  365. // } },
  366. // },
  367. // });
  368. // cond.push({
  369. // $group:
  370. // {
  371. // _id: { id: '$_id.id' },
  372. // loginName: { $first: '$loginName' },
  373. // number: { $push: { counter: '$counter', type: '$_id.type' } },
  374. // },
  375. // });
  376. // cond.push({
  377. // $project: {
  378. // _id: '$_id.id',
  379. // loginName: 1,
  380. // number: 1,
  381. // },
  382. // });
  383. // return cond;
  384. //
  385. // }
  386. async findAdminUser() {
  387. return await this.ctx.model.SysUserModel.findOne({ loginName: 'admin' });
  388. }
  389. async findUser(deptName, level, userName, parentName) {
  390. const { ctx } = this;
  391. const { model } = ctx;
  392. ctx.logger.error('level', deptName, level, parentName);
  393. if (level > 3) {
  394. const res = await model.SysUserModel.aggregate([
  395. { $lookup: { from: 'sys_dept', localField: 'dept', foreignField: '_id', as: 'deptName' } },
  396. { $lookup: { from: 'sys_dept', localField: `dept${level - 1}`, foreignField: '_id', as: `dept${level - 1}Name` } },
  397. { $unwind: { path: '$deptName', preserveNullAndEmptyArrays: true } },
  398. { $unwind: { path: '$dept' + (level - 1) + 'Name', preserveNullAndEmptyArrays: true } },
  399. { $match: {
  400. 'deptName.name': deptName,
  401. ['dept' + (level - 1) + 'Name.name']: parentName,
  402. role: this.app.mongoose.Types.ObjectId(this.app.config.defaultManagerRoleId),
  403. } },
  404. ]).allowDiskUse(true);
  405. if (res.length > 0) {
  406. const filters = res.filter(item => item.loginName == userName || userName.indexOf(item.loginName) == 0);
  407. if (filters.length > 0) {
  408. return filters[0];
  409. }
  410. return res[0];
  411. }
  412. } else {
  413. const res = await model.SysUserModel.aggregate([
  414. { $lookup: { from: 'sys_dept', localField: 'dept', foreignField: '_id', as: 'deptName' } },
  415. { $unwind: { path: '$deptName', preserveNullAndEmptyArrays: true } },
  416. { $match: {
  417. 'deptName.name': deptName,
  418. loginName: { $ne: 'admin' },
  419. role: this.app.mongoose.Types.ObjectId(this.app.config.defaultManagerRoleId),
  420. } },
  421. ]).allowDiskUse(true);
  422. if (res.length > 0) {
  423. const filters = res.filter(item => item.loginName == userName || userName.indexOf(item.loginName) == 0);
  424. if (filters.length > 0) {
  425. return filters[0];
  426. }
  427. return res[0];
  428. }
  429. }
  430. return null;
  431. }
  432. }
  433. module.exports = SysUserService;