adminUser.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. 'use strict';
  2. const Service = require('egg').Service;
  3. const md5 = require('md5-node');
  4. const Excel = require("exceljs");
  5. const path = require("path");
  6. class AdminUserService extends Service {
  7. async login(name, password) {
  8. let { ctx , config, app} = this;
  9. let pwdmd5 = md5(password);
  10. let mysql = app.mysql;
  11. console.log( "pwdmd5=>", pwdmd5);
  12. let data = null;
  13. try {
  14. return await this.appLogin(name, pwdmd5);
  15. } catch(error) {
  16. data = await mysql.get("admin_user", {name, password: pwdmd5});
  17. if( !data ) {
  18. throw "账号密码错误"
  19. }
  20. }
  21. let info = data;
  22. if( info.status == 2) {
  23. throw "账号已被冻结";
  24. }
  25. await mysql.query("update admin_user set last_login_time=now() , last_login_ip=? where id=?", [ctx.ip, info.id]);
  26. let teacherRoleId = await mysql.query("select ur.id from admin_user_role as ur left join admin_role ar on ar.id=ur.role_id where ur.user_id=? and ar.role_code='role_teacher'", [data.id])
  27. let configAdmin = config.loginAdmin;
  28. let token = await ctx.jwtSign({name:info.name, id:info.id, type:1}, configAdmin.secret, { expiresIn: configAdmin.expiresIn });
  29. if( teacherRoleId.length == 1) return {token, name:info.name, avatar:info.avatar, realname:info.realname, id:info.id, role: 1, type:2};
  30. return {token, name:info.name, avatar:info.avatar, realname:info.realname, id:info.id, type:1};
  31. }
  32. async appLogin(name, pwdmd5){ //参训人员登录
  33. let { ctx , config, app} = this;
  34. let mysql = app.mysql;
  35. let data = await mysql.get("users", {name, pwd: pwdmd5});
  36. if( !data ) {
  37. throw "账号密码错误";
  38. }
  39. let info = data;
  40. if( info.status == 2) {
  41. throw "账号已被冻结";
  42. }
  43. let configAdmin = config.loginAdmin;
  44. let token = await ctx.jwtSign({name:info.name, id:info.id, type:2, role:info.role}, configAdmin.secret, { expiresIn: configAdmin.expiresIn });
  45. return {token, name:info.name, avatar:info.avatar, realname:info.realname, id:info.id, type:2, role:info.role};
  46. }
  47. async list(query) {
  48. let mysql = this.app.mysql;
  49. let pageNo = query.pageNo;
  50. let pageSize = query.pageSize;
  51. pageNo = parseInt( pageNo );
  52. pageSize = parseInt( pageSize );
  53. let name = query.name;
  54. let role = query.role;
  55. let ret = {records:[], total: 0, };
  56. let where = name ? `where name like '%${name}%' or realname like '%${name}%' `: "";
  57. if( role != undefined ) {
  58. where = where?where + `and role=${role}`: `where role=${role}`;
  59. }
  60. let sql = `select id, name, realname, code, role,avatar, date_format(last_login_time,'%Y-%m-%d') as last_login_time, last_login_ip from users ${where}`
  61. let total = await mysql.query("select count(id) as count from users " + where);
  62. ret.total = total[0].count;
  63. let data = await mysql.query( `${sql} limit ${(pageNo-1)*pageSize},${pageSize}`);
  64. ret.records = data;
  65. return ret;
  66. }
  67. async delete(id)
  68. {
  69. let mysql = this.app.mysql;
  70. let ret = await mysql.query("delete from users where id=?",[id]);
  71. return "删除成功";
  72. }
  73. async edit(data) {
  74. let mysql = this.app.mysql;
  75. if( data.add_time ) delete data.add_time;
  76. console.log("editxx", data);
  77. let ret = await mysql.update("users", data, {where:{id: data.id}});
  78. return ret;
  79. }
  80. async add( data ) {
  81. let mysql = this.app.mysql;
  82. data.add_time = mysql.literals.now;
  83. let ret = await mysql.insert("users", data);
  84. return ret;
  85. }
  86. async resetpwd( data ) {
  87. let mysql = this.app.mysql;
  88. if( !data.id ) throw "ID不能为空";
  89. if( !data.pwd ) throw "密码不能为空";
  90. if( data.pwd ) data.pwd = md5( data.pwd );
  91. let ret = await mysql.update("users", data, {where:{id: data.id}});
  92. return ret;
  93. }
  94. async getUserProfile(query) {
  95. let {ctx} = this;
  96. console.log("getUserProfile", ctx.header.authorization);
  97. let id = query.id;
  98. if( !id ) {
  99. let authToken = ctx.header.authorization;
  100. if ( !authToken ) {
  101. throw "用户ID为空";
  102. }
  103. let config = this.app.config.loginAdmin;
  104. let ret = await ctx.jwtVerify(authToken, config.secret);
  105. if( !ret.verify )
  106. {
  107. throw "用户ID为空";
  108. }
  109. let message = ret.message;
  110. console.log("message", message);
  111. if( message.type == 2 ) { //参训人员登录
  112. id = message.id;
  113. }
  114. }
  115. if( !id ) throw "查看的参训人员ID为空";
  116. let mysql = this.app.mysql;
  117. let info = await mysql.query("select id,avatar,realname,code from users where id=? ", [id])
  118. info = info[0];
  119. //参训总次数,最早参训时间,最后参训时间
  120. let state = await mysql.query("select count(rid) as rid, date_format(max(add_time), '%Y-%m-%d') as lastTime, date_format(min(add_time),'%Y-%m-%d') as farTime from train_records_users where uid=?", [id]);
  121. state = state[0];
  122. console.log( state );
  123. //参训科目数
  124. let subjectIds = await mysql.query("select count(*) as num from (select r.template_id from train_records_users as u left join train_records as r on r.id = u.rid where u.uid=? group by r.template_id) as ids", [id]);
  125. subjectIds = subjectIds[0];
  126. console.log("subject ids " + id, subjectIds);
  127. //累计训练时长
  128. let totalTime = await mysql.query("select sum(r.duration) as num from train_records_users as u left join train_records as r on r.id = u.rid where uid=?", [id]);
  129. totalTime = totalTime[0]?totalTime[0].num: 0;
  130. // console.log(state, subjectIds);
  131. return {...info, rids: state.rid, lastTime: state.lastTime, farTime: state.farTime, subjects: subjectIds.num, totalTime: `${Math.ceil(totalTime/60)} 分钟`};
  132. }
  133. async commentUserRecord(data) {
  134. let rid = data.rid;
  135. let uid = data.uid;
  136. if( !rid || !uid ) throw "ID为空";
  137. let mysql = this.app.mysql;
  138. return await mysql.query(`update train_records_users set comment='${data.text}' where rid=${rid} and uid=${uid}`);
  139. }
  140. async exportUserListXls(query) {
  141. console.log("exportXls==>", query );
  142. let sql = `select id, name, realname, code, date_format(last_login_time,'%Y-%m-%d') as login_time from users`
  143. if( query.selections ) { //导出指定的内容,否则导出所有
  144. sql += ` where id in (${query.selections})`;
  145. }
  146. let mysql = this.app.mysql;
  147. let ret = await mysql.query( sql );
  148. let workbook = new Excel.Workbook();
  149. let sheet = workbook.addWorksheet("参训学员列表", {
  150. // views: [{xSplit:1, ySplit:1}],
  151. pageSetup:{pageSize:9, orientation:'portrait', fitToPage:true, showGridLines:true, horizontalCentered:true},
  152. headerFooter:{
  153. firstHeader:"舰航仿真模拟训练人员名单",
  154. firstFooter:"舰航仿真模拟训练人员名单",
  155. oddFooter:"第 &P 页,共 &N页"
  156. }
  157. });
  158. let style = {alignment: {vertical:'middle', horizontal:'center'}};
  159. let columns = [
  160. {
  161. style,
  162. header: '#ID',
  163. key: 'id',
  164. },{
  165. style,
  166. header: '登录名',
  167. key: 'name',
  168. width:20,
  169. },{
  170. style,
  171. width:20,
  172. header: '真实姓名',
  173. key: 'realname',
  174. },{
  175. style,
  176. width:20,
  177. header: '编号',
  178. key: 'code',
  179. },{
  180. style,
  181. width:20,
  182. header: '最后登录时间',
  183. key: 'login_time',
  184. }
  185. ];
  186. sheet.columns = columns;
  187. sheet.addRows( ret );
  188. return await workbook.xlsx.writeBuffer();
  189. }
  190. async exportProfileXls(query) {
  191. let ret = await this.getUserProfile(query);
  192. console.log( "exportXls", ret);
  193. let workbook = new Excel.Workbook();
  194. let sheet = workbook.addWorksheet(ret.realname, {
  195. // views: [{xSplit:1, ySplit:1}],
  196. pageSetup:{pageSize:9, orientation:'portrait', fitToPage:true, horizontalCentered:true},
  197. headerFooter:{
  198. firstHeader:"舰航仿真模拟训练个人统计",
  199. firstFooter:"舰航仿真模拟训练个人统计",
  200. }
  201. });
  202. let style = {alignment: {vertical:'middle', horizontal:'center'}, font:{size: 16}};
  203. let columns = [
  204. {
  205. style:{alignment: {vertical:'middle', horizontal:'left'}, font:{size: 16}},
  206. key: 'left',
  207. width:22,
  208. },{
  209. style,
  210. key: 'center',
  211. width:21,
  212. },{
  213. style:{alignment: {vertical:'middle', horizontal:'right'}, font:{size: 16}},
  214. width:20,
  215. key: 'right',
  216. }
  217. ];
  218. sheet.columns = columns;
  219. let rows = [{ left: ""},{ left: ""}, {left:ret.realname},{ center: ""}, {left: "系统编号:" + ret.code},{ center: ""}];
  220. rows.push({left: "参训总次数", right:ret.rids + "次"});
  221. rows.push({left: "参训科目数", right:ret.subjects + "项"});
  222. rows.push({left: "参训总时间", right:ret.totalTime });
  223. rows.push({left: "首次参训时间", right:ret.farTime});
  224. rows.push({left: "最后参训时间", right:ret.lastTime});
  225. sheet.addRows(rows);
  226. sheet.getRow(1).height = 115;
  227. sheet.getRow(3).font = {bold:true, size: 22, name:"Arial"}
  228. let imageHost = this.app.config.serverhosts.image;
  229. sheet.getRow(7).border = {bottom: {style:'thin'}};
  230. sheet.getRow(8).border = {bottom: {style:'thin'}};
  231. sheet.getRow(9).border = {bottom: {style:'thin'}};
  232. sheet.getRow(10).border = {bottom: {style:'thin'}};
  233. sheet.getRow(11).border = {bottom: {style:'thin'}};
  234. sheet.getRow(7).height = 40;
  235. sheet.getRow(8).height = 40;
  236. sheet.getRow(9).height = 40;
  237. sheet.getRow(10).height = 40;
  238. sheet.getRow(11).height = 40;
  239. if( ret.avatar ) {
  240. let image = await this.ctx.curl(imageHost + ret.avatar);
  241. let extension = path.extname(ret.avatar);
  242. extension = extension.substr(1);
  243. let id = workbook.addImage({buffer: image.data, extension});
  244. sheet.addImage(id, { tl: {col: 0, row:0}, ext: {width: 120, height: 120} , editAs:undefined});
  245. console.log( extension, id);
  246. }
  247. return await workbook.xlsx.writeBuffer();
  248. }
  249. }
  250. module.exports = AdminUserService;