user_model.js 15 KB

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