user_model.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. /**
  2. * 用户业务模型
  3. *
  4. * @author CaiAoLin
  5. * @date 2017/6/9
  6. * @version
  7. */
  8. const mongoose = require("mongoose");
  9. const Request = require("request");
  10. const BaseModel = require("../../common/base/base_model")
  11. const LogModel = require("./log_model");
  12. const config = require("../../../config/config.js");
  13. class UserModel extends BaseModel {
  14. /**
  15. * 企业所在地区
  16. *
  17. * @var {object}
  18. */
  19. province = ['北京', '天津', '河北', '山西', '内蒙古', '辽宁', '吉林', '黑龙江', '上海', '江苏', '浙江', '安徽',
  20. '福建', '江西', '山东', '河南', '湖北', '湖南', '广东', '广西', '海南', '重庆', '四川', '贵州', '云南', '西藏',
  21. '陕西', '甘肃', '青海', '宁夏', '新疆', '台湾', '香港', '澳门',];
  22. /**
  23. * 企业类型
  24. *
  25. * @var
  26. */
  27. companyType = ['建设单位', '设计单位', '施工单位', '监理单位', '审核单位', '咨询公司', '招标代理', '住建部', '财政', '审计',
  28. '造价管理站', '学校', '个人', '其他'];
  29. /**
  30. * 企业规模
  31. *
  32. * @var
  33. */
  34. companyScale = ['1-50', '50-100', '100-500', '500+'];
  35. /**
  36. * 最近天数
  37. *
  38. * @var
  39. */
  40. dayMsg = ['所有', '最近24小时', '最近3天', '最近7天', '最近30天'];
  41. /**
  42. * 构造函数
  43. *
  44. * @return {void}
  45. */
  46. constructor() {
  47. let parent = super();
  48. parent.model = mongoose.model('user');
  49. parent.init();
  50. }
  51. /**
  52. * 根据用户名密码调用SSO接口获取信息
  53. *
  54. * @param {string} username
  55. * @param {string} password
  56. * @return {object}
  57. */
  58. async getInfoFromSSO(username, password) {
  59. let postData = {
  60. url: 'http://sso.smartcost.com.cn/api/jzlogin',
  61. form: { username: username, userpasswd: password },
  62. encoding: 'utf8'
  63. };
  64. return new Promise(function (resolve, reject) {
  65. try {
  66. // 请求接口
  67. Request.post(postData, function (err, postResponse, body) {
  68. if (err) {
  69. console.log(err);
  70. reject('请求错误');
  71. }
  72. if(!postResponse) reject('请求错误');
  73. if (postResponse.statusCode !== 200) {
  74. reject('通行证验证失败!');
  75. }
  76. resolve(body);
  77. });
  78. } catch (error) {
  79. reject([]);
  80. }
  81. });
  82. }
  83. /**
  84. * 根据用户手机号码调用SSO接口获取信息
  85. *
  86. * @param {string} mobile
  87. * @param {string} login 1为登录,不存在则是查询
  88. * @return {object}
  89. */
  90. async getInfoFromSSOMobile(mobile, login = '1') {
  91. const fromData = { account: mobile };
  92. if (login === '1') {
  93. fromData.login = 1;
  94. }
  95. let postData = {
  96. url: 'http://sso.smartcost.com.cn/building/api/mobile/login',
  97. form: fromData,
  98. encoding: 'utf8'
  99. };
  100. return new Promise(function (resolve, reject) {
  101. try {
  102. // 请求接口
  103. Request.post(postData, function (err, postResponse, body) {
  104. if (err) {
  105. console.log('111');
  106. reject('请求错误');
  107. }
  108. if (postResponse.statusCode !== 200) {
  109. reject('通行证验证失败!');
  110. }
  111. resolve(body);
  112. });
  113. } catch (error) {
  114. reject([]);
  115. }
  116. });
  117. }
  118. /**
  119. * 根据用户id和token调用SSO接口获取信息
  120. *
  121. * @param {string} username
  122. * @param {string} password
  123. * @return {object}
  124. */
  125. async getInfoFromSSO2(ssoID, token) {
  126. let postData = {
  127. url: 'http://sso.smartcost.com.cn/building/api/login/auth',
  128. form: { ssoID: ssoID, token: token },
  129. encoding: 'utf8'
  130. };
  131. return new Promise(function (resolve, reject) {
  132. try {
  133. // 请求接口
  134. Request.post(postData, function (err, postResponse, body) {
  135. if (err) {
  136. console.log('111');
  137. reject('请求错误');
  138. }
  139. if (postResponse.statusCode !== 200) {
  140. reject('通行证验证失败!');
  141. }
  142. resolve(body);
  143. });
  144. } catch (error) {
  145. reject([]);
  146. }
  147. });
  148. }
  149. /**
  150. * 标记用户
  151. *
  152. * @param {object} userData
  153. * @param {Object} request
  154. * @return {Promise}
  155. */
  156. async markUser(userData, request = null) {
  157. let userDataFromDb = await this.findDataBySsoId(userData.ssoId);
  158. // let userDataFromDb = await this.findDataByName(userData.username); //后面新增的账号可淘汰这方法,当前使用是为了兼容旧的账号
  159. let result = false;
  160. userData.latest_login = new Date().getTime();
  161. if (userDataFromDb === null) {
  162. // 不存在用户则入库
  163. this.setScene();//恢复场景,用户有可能公司real_name等信息为空,不能设置为必填
  164. result = await this.addUser(userData);
  165. userDataFromDb = result;
  166. } else {
  167. // 存在则新增登录信息并更新账号信息
  168. let condition = {ssoId: userData.ssoId};
  169. // let condition = { username: userData.username };
  170. let UpdateData = {
  171. email: userData.email,
  172. mobile: userData.mobile,
  173. // ssoId: userData.ssoId,
  174. qq: userData.qq,
  175. latest_login: userData.latest_login,
  176. isUserActive: userData.isUserActive,
  177. token: userData.token,
  178. };
  179. let updateResult = await this.updateUser(condition, UpdateData);
  180. if (updateResult.ok === 1) {
  181. let logModel = new LogModel();
  182. result = await logModel.addLoginLog(userDataFromDb._id, request);
  183. }
  184. }
  185. request.session.sessionUser.id = userDataFromDb._id;
  186. request.session.sessionUser.real_name = userDataFromDb.real_name;
  187. request.session.sessionUser.latest_used = userDataFromDb.latest_used;//设置最近使用的编办
  188. return result;
  189. }
  190. /**
  191. * 选择场景
  192. *
  193. * @param {string} scene
  194. */
  195. setScene(scene = '') {
  196. /* switch (scene) {
  197. case 'saveInfo':
  198. this.model.schema.path('real_name').required(true);
  199. this.model.schema.path('company').required(true);
  200. this.model.schema.path('province').required(true);
  201. this.model.schema.path('version').required(true);
  202. break;
  203. case '':
  204. this.model.schema.path('real_name').required(false);
  205. this.model.schema.path('company').required(false);
  206. this.model.schema.path('province').required(false);
  207. this.model.schema.path('version').required(false);
  208. }*/
  209. }
  210. /**
  211. * 根据用户名查找数据
  212. *
  213. * @param {string} username
  214. * @return {object}
  215. */
  216. findDataByName(username) {
  217. return this.db.findOne({ username: username });
  218. }
  219. /**
  220. * 根据ssoID查找数据
  221. *
  222. * @param {string} ssoId
  223. * @return {object}
  224. */
  225. findDataBySsoId(ssoId) {
  226. return this.db.findOne({ ssoId: ssoId });
  227. }
  228. /**
  229. * 根据手机号查找数据
  230. *
  231. * @param {string} mobile
  232. * @return {object}
  233. */
  234. findDataByMobile(mobile) {
  235. return this.db.findOne({ mobile: mobile });
  236. }
  237. /**
  238. * 根据userId查找数据
  239. *
  240. * @param {string} ssoId
  241. * @return {object}
  242. */
  243. async findDataById(id, fields) {
  244. const objId = mongoose.Types.ObjectId(id);
  245. return fields ? await this.db.findOne({_id: objId}, fields) : await this.db.findOne({_id: objId});
  246. }
  247. /**
  248. * 验证用户token正确性
  249. * 一个账号不允许多处同时在线,每次登陆都会更新session和数据库的token,每个请求都会比对session和数据库的token
  250. * @param {String} id - 用户ID
  251. * @param {String} token - 登陆生成的token
  252. * @return {Boolean}
  253. */
  254. async checkToken(id, token) {
  255. const user = await this.findDataById(id, '-_id token');
  256. if (!user.token) { // 兼容第一次上线,已登陆的用户还没token,需要返回验证正确
  257. return true;
  258. }
  259. return user.token === token;
  260. }
  261. async findDataByAccount(account) {
  262. let userinfo = await this.db.findOne({ mobile: account });
  263. let userinfo2 = await this.db.findOne({ email: account });
  264. if (userinfo) {
  265. return userinfo;
  266. } else if (userinfo2) {
  267. return userinfo2;
  268. } else {
  269. return false;
  270. }
  271. }
  272. /**
  273. * 新增用户
  274. *
  275. * @param {object} userData
  276. * @return {Promise|boolean}
  277. */
  278. addUser(userData) {
  279. let insertData = {
  280. ssoId: userData.ssoId,
  281. username: userData.username,
  282. email: userData.email,
  283. mobile: userData.mobile,
  284. qq: userData.qq,
  285. create_time: new Date().getTime(),
  286. latest_login: new Date().getTime(),
  287. isUserActive: userData.isUserActive,
  288. token: userData.token
  289. };
  290. return this.db.create(insertData);
  291. }
  292. //更新最近使用编办ID
  293. async updateLatestUsed(userID, compilationID) {
  294. if (userID && compilationID) {
  295. return await this.db.update({ '_id': userID }, { 'latest_used': compilationID });
  296. }
  297. }
  298. /**
  299. * 更新用户数据
  300. *
  301. * @param {object} updateData
  302. * @return {Promise}
  303. */
  304. async updateUser(condition, updateData) {
  305. if (Object.keys(condition).length <= 0 || Object.keys(updateData).length <= 0) {
  306. return null;
  307. }
  308. return await this.db.update(condition, updateData);
  309. }
  310. async addVersion(condition, versionInfo) {
  311. return await this.db.findOneAndUpdate(condition, { $addToSet: { versionInfo: versionInfo } });
  312. }
  313. async removeVersion(userId, compilationId) {
  314. let userObjId = mongoose.Types.ObjectId(userId);
  315. return await this.db.findOneAndUpdate({ _id: userObjId }, { $pull: { versionInfo: { compilationId: compilationId } } });
  316. }
  317. /**
  318. * 判断用户使用免费版还是专业版
  319. *
  320. * @param ssoId
  321. * @param compilationId
  322. * @return {version}
  323. */
  324. async getVersionFromUpgrade(ssoId, compilationId) {
  325. let title = config[process.env.NODE_ENV].title?config[process.env.NODE_ENV].title:"纵横公路养护云造价";
  326. let versionText = title === '纵横公路云造价'?'免费版':'学习版';
  327. let version = `${title}(${versionText})`;//'纵横公路养护造价(免费云版)'; 2019-03-28 需求修改,听说不知道多久的以后还会改回来--勿删!!!!!
  328. let lock = 0;
  329. let userData = await this.findDataBySsoId(ssoId);
  330. if (userData.upgrade_list !== undefined) {
  331. let compilationInfo = userData.upgrade_list.find(function (item) {
  332. return item.compilationID === compilationId;
  333. });
  334. if (compilationInfo !== undefined && compilationInfo.isUpgrade === true) {
  335. version = title+'(专业版)';
  336. if (compilationInfo.lock !== undefined && compilationInfo.lock !== 0) {
  337. lock = compilationInfo.lock;
  338. }
  339. }
  340. }
  341. return {version: version, lock: lock};
  342. }
  343. /**
  344. * 判断用户是免费版还是专业版用户
  345. */
  346. async isFree(ssoId, compilationId) {
  347. const userData = await this.findDataBySsoId(ssoId);
  348. if (!userData) {
  349. throw '不存在此用户';
  350. }
  351. const upgrade_list = userData.upgrade_list;
  352. let free = true;
  353. if (upgrade_list && upgrade_list.length > 0) {
  354. const upgrade = upgrade_list.find(function (item) {
  355. return item.compilationID === compilationId && item.isUpgrade === true;
  356. });
  357. if (upgrade) {
  358. free = false;
  359. }
  360. }
  361. return free
  362. }
  363. /**
  364. * 从session中判断用户是否是免费版
  365. * @param {String} sessionVersion
  366. * @return {Boolean}
  367. */
  368. isFreeFromSession(sessionVersion) {
  369. if (!sessionVersion) {
  370. return true;
  371. }
  372. return sessionVersion.indexOf('学习') >= 0;
  373. }
  374. /*
  375. * 添加联系人,互相添加
  376. */
  377. async addContact(userID, contactID) {
  378. const data = [
  379. { user: userID, contact: contactID },
  380. { user: contactID, contact: userID }
  381. ];
  382. const task = [];
  383. for (const { user, contact } of data) {
  384. const hasThisContact = await this.model.count({ _id: mongoose.Types.ObjectId(user), 'contacts.userID': contact });
  385. // 没有则添加
  386. if (!hasThisContact) {
  387. task.push(this.model.update({ _id: mongoose.Types.ObjectId(user) }, { $push: { contacts: { userID: contact } } }));
  388. }
  389. }
  390. if (task.length) {
  391. await Promise.all(task);
  392. }
  393. }
  394. async getContacts(userID) {
  395. const user = await this.model.findOne({ _id: mongoose.Types.ObjectId(userID) }, 'contacts').lean();
  396. if (!user || !user.contacts || !user.contacts.length) {
  397. return [];
  398. }
  399. const userIDList = user.contacts.map(item => mongoose.Types.ObjectId(item.userID));
  400. const users = await this.model.find({ _id: { $in: userIDList } }, 'real_name mobile company');
  401. return users;
  402. }
  403. /**
  404. * 获取列表
  405. *
  406. * @param {object} condition
  407. * @param {number} page
  408. * @param {Number} pageSize
  409. * @return {promise}
  410. */
  411. async getList(condition = null, page = 1, pageSize = 30, sort = {_id:-1}) {
  412. page = parseInt(page);
  413. page = page <= 1 ? 1 : page;
  414. let option = {pageSize: pageSize, offset: parseInt((page - 1) * pageSize), sort: sort};
  415. let userList = await this.db.find(condition, null, option);
  416. userList = userList.length > 0 ? userList : [];
  417. return userList;
  418. }
  419. /**
  420. * 获取过滤条件
  421. *
  422. * @return {Object}
  423. */
  424. getFilterCondition(request) {
  425. let condition = {};
  426. let regtime = request.query.regtime;
  427. regtime = regtime !== '' && regtime !== undefined ? parseInt(regtime) : 0;
  428. if (regtime !== 0) {
  429. condition.create_time = this.getTimestamp(regtime);
  430. }
  431. //最近登录时间
  432. let loginTime = request.query.loginTime;
  433. loginTime = loginTime !== '' && loginTime !== undefined ? parseInt(loginTime) : 0;
  434. if (loginTime !== 0) {
  435. condition.latest_login = this.getTimestamp(loginTime);
  436. }
  437. let version = request.query.version;
  438. if(version !== '' && version !== undefined) {
  439. condition.version = version;
  440. }
  441. // 已升级费用定额
  442. let upGrade = request.query.upGrade;
  443. if(upGrade !== '' && upGrade !== undefined){
  444. condition.upgrade_list = {"$elemMatch":{"compilationID":upGrade,"isUpgrade":true}};
  445. }
  446. // 最近使用费用定额
  447. let latestUsed = request.query.latestUsed;
  448. if(latestUsed !== '' && latestUsed !== undefined){
  449. condition.latest_used = latestUsed;
  450. }
  451. // 最近登录时长
  452. let onlineTimes = request.query.onlineTimes;
  453. onlineTimes = onlineTimes !== '' && onlineTimes !== undefined ? parseInt(onlineTimes) : 0;
  454. if (onlineTimes !== 0) {
  455. condition.online_times = this.getOnlineTimestamp(onlineTimes);
  456. }
  457. // 企业所在地区
  458. let province = request.query.province;
  459. province = province !== '' && province !== undefined ? parseInt(province) : 0;
  460. if (province !== 0) {
  461. condition.province = province;
  462. }
  463. let keyword = request.query.keyword;
  464. if (keyword !== '' && keyword !== undefined) {
  465. condition.$or = [{real_name : {$regex: keyword}},{email : {$regex: keyword}},{mobile : {$regex: keyword}},{qq : {$regex: keyword}},{company : {$regex: keyword}}];
  466. }
  467. return condition;
  468. }
  469. /**
  470. * 获取时间戳区间
  471. *
  472. * @return {Object}
  473. */
  474. getTimestamp(type) {
  475. let startTime = '';
  476. switch (type) {
  477. case 1 :
  478. startTime = Date.parse(new Date())-86400*1000;
  479. break;
  480. case 2 :
  481. startTime = Date.parse(new Date())-86400*1000*3;
  482. break;
  483. case 3 :
  484. startTime = Date.parse(new Date())-86400*1000*7;
  485. break;
  486. case 4 :
  487. startTime = Date.parse(new Date())-86400*1000*30;
  488. break;
  489. default :
  490. break;
  491. }
  492. let endTime = Date.parse(new Date());
  493. return startTime === '' ? '' : {'$gte': startTime, '$lt': endTime};
  494. }
  495. /**
  496. * 获取时间戳区间
  497. *
  498. * @return {Object}
  499. */
  500. getOnlineTimestamp(type) {
  501. let startTime = 0;
  502. switch (type) {
  503. case 1 :
  504. startTime = 1800*1000;
  505. break;
  506. case 2 :
  507. startTime = 3600*1000;
  508. break;
  509. case 3 :
  510. startTime = 3600*1000*2;
  511. break;
  512. case 4 :
  513. startTime = 3600*1000*3;
  514. break;
  515. default :
  516. break;
  517. }
  518. return startTime === 0 ? '' : {'$gte': startTime};
  519. }
  520. /**
  521. * 获取daymsg
  522. *
  523. */
  524. getDayMsg(index){
  525. return this.dayMsg[index];
  526. }
  527. }
  528. module.exports = UserModel;