user_model.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. * @return {void}
  38. */
  39. constructor() {
  40. let parent = super();
  41. parent.model = mongoose.model('user');
  42. parent.init();
  43. }
  44. /**
  45. * 根据用户名密码调用SSO接口获取信息
  46. *
  47. * @param {string} username
  48. * @param {string} password
  49. * @return {object}
  50. */
  51. async getInfoFromSSO(username, password) {
  52. let postData = {
  53. url: 'http://sso.smartcost.com.cn/api/jzlogin',
  54. form: { username: username, userpasswd: password },
  55. encoding: 'utf8'
  56. };
  57. return new Promise(function (resolve, reject) {
  58. try {
  59. // 请求接口
  60. Request.post(postData, function (err, postResponse, body) {
  61. if (err) {
  62. console.log('111');
  63. reject('请求错误');
  64. }
  65. if (postResponse.statusCode !== 200) {
  66. reject('通行证验证失败!');
  67. }
  68. resolve(body);
  69. });
  70. } catch (error) {
  71. reject([]);
  72. }
  73. });
  74. }
  75. /**
  76. * 根据用户手机号码调用SSO接口获取信息
  77. *
  78. * @param {string} mobile
  79. * @param {string} login 1为登录,不存在则是查询
  80. * @return {object}
  81. */
  82. async getInfoFromSSOMobile(mobile, login = '1') {
  83. const fromData = { account: mobile };
  84. if (login === '1') {
  85. fromData.login = 1;
  86. }
  87. let postData = {
  88. url: 'http://sso.smartcost.com.cn/building/api/mobile/login',
  89. form: fromData,
  90. encoding: 'utf8'
  91. };
  92. return new Promise(function (resolve, reject) {
  93. try {
  94. // 请求接口
  95. Request.post(postData, function (err, postResponse, body) {
  96. if (err) {
  97. console.log('111');
  98. reject('请求错误');
  99. }
  100. if (postResponse.statusCode !== 200) {
  101. reject('通行证验证失败!');
  102. }
  103. resolve(body);
  104. });
  105. } catch (error) {
  106. reject([]);
  107. }
  108. });
  109. }
  110. /**
  111. * 根据用户id和token调用SSO接口获取信息
  112. *
  113. * @param {string} username
  114. * @param {string} password
  115. * @return {object}
  116. */
  117. async getInfoFromSSO2(ssoID, token) {
  118. let postData = {
  119. url: 'http://sso.smartcost.com.cn/building/api/login/auth',
  120. form: { ssoID: ssoID, token: token },
  121. encoding: 'utf8'
  122. };
  123. return new Promise(function (resolve, reject) {
  124. try {
  125. // 请求接口
  126. Request.post(postData, function (err, postResponse, body) {
  127. if (err) {
  128. console.log('111');
  129. reject('请求错误');
  130. }
  131. if (postResponse.statusCode !== 200) {
  132. reject('通行证验证失败!');
  133. }
  134. resolve(body);
  135. });
  136. } catch (error) {
  137. reject([]);
  138. }
  139. });
  140. }
  141. /**
  142. * 标记用户
  143. *
  144. * @param {object} userData
  145. * @param {Object} request
  146. * @return {Promise}
  147. */
  148. async markUser(userData, request = null) {
  149. let userDataFromDb2 = await this.findDataBySsoId(userData.ssoId);
  150. let userDataFromDb = await this.findDataByName(userData.username); //后面新增的账号可淘汰这方法,当前使用是为了兼容旧的账号
  151. let result = false;
  152. userData.latest_login = new Date().getTime();
  153. if (userDataFromDb === null && userDataFromDb2 === null) {
  154. // 不存在用户则入库
  155. this.setScene();//恢复场景,用户有可能公司real_name等信息为空,不能设置为必填
  156. result = await this.addUser(userData);
  157. userDataFromDb = result;
  158. } else {
  159. // 存在则新增登录信息并更新账号信息
  160. // let condition = {ssoId: sessionUser.ssoId};
  161. let condition = { username: userData.username };
  162. let UpdateData = {
  163. email: userData.email,
  164. mobile: userData.mobile,
  165. ssoId: userData.ssoId,
  166. qq: userData.qq,
  167. latest_login: userData.latest_login,
  168. isUserActive: userData.isUserActive,
  169. };
  170. let updateResult = await this.updateUser(condition, UpdateData);
  171. if (updateResult.ok === 1) {
  172. let logModel = new LogModel();
  173. result = await logModel.addLoginLog(userDataFromDb._id, request);
  174. }
  175. }
  176. request.session.sessionUser.id = userDataFromDb._id;
  177. request.session.sessionUser.real_name = userDataFromDb.real_name;
  178. request.session.sessionUser.latest_used = userDataFromDb.latest_used;//设置最近使用的编办
  179. return result;
  180. }
  181. /**
  182. * 选择场景
  183. *
  184. * @param {string} scene
  185. */
  186. setScene(scene = '') {
  187. /* switch (scene) {
  188. case 'saveInfo':
  189. this.model.schema.path('real_name').required(true);
  190. this.model.schema.path('company').required(true);
  191. this.model.schema.path('province').required(true);
  192. this.model.schema.path('version').required(true);
  193. break;
  194. case '':
  195. this.model.schema.path('real_name').required(false);
  196. this.model.schema.path('company').required(false);
  197. this.model.schema.path('province').required(false);
  198. this.model.schema.path('version').required(false);
  199. }*/
  200. }
  201. /**
  202. * 根据用户名查找数据
  203. *
  204. * @param {string} username
  205. * @return {object}
  206. */
  207. findDataByName(username) {
  208. return this.db.findOne({ username: username });
  209. }
  210. /**
  211. * 根据ssoID查找数据
  212. *
  213. * @param {string} ssoId
  214. * @return {object}
  215. */
  216. findDataBySsoId(ssoId) {
  217. return this.db.findOne({ ssoId: ssoId });
  218. }
  219. /**
  220. * 根据手机号查找数据
  221. *
  222. * @param {string} mobile
  223. * @return {object}
  224. */
  225. findDataByMobile(mobile) {
  226. return this.db.findOne({ mobile: mobile });
  227. }
  228. /**
  229. * 根据userId查找数据
  230. *
  231. * @param {string} ssoId
  232. * @return {object}
  233. */
  234. async findDataById(id) {
  235. let objId = mongoose.Types.ObjectId(id);
  236. return await this.db.findOne({ _id: objId });
  237. }
  238. async findDataByAccount(account) {
  239. let userinfo = await this.db.findOne({ mobile: account });
  240. let userinfo2 = await this.db.findOne({ email: account });
  241. if (userinfo) {
  242. return userinfo;
  243. } else if (userinfo2) {
  244. return userinfo2;
  245. } else {
  246. return false;
  247. }
  248. }
  249. /**
  250. * 新增用户
  251. *
  252. * @param {object} userData
  253. * @return {Promise|boolean}
  254. */
  255. addUser(userData) {
  256. let insertData = {
  257. ssoId: userData.ssoId,
  258. username: userData.username,
  259. email: userData.email,
  260. mobile: userData.mobile,
  261. create_time: new Date().getTime(),
  262. latest_login: new Date().getTime(),
  263. isUserActive: userData.isUserActive,
  264. };
  265. return this.db.create(insertData);
  266. }
  267. //更新最近使用编办ID
  268. async updateLatestUsed(userID, compilationID) {
  269. if (userID && compilationID) {
  270. return await this.db.update({ '_id': userID }, { 'latest_used': compilationID });
  271. }
  272. }
  273. /**
  274. * 更新用户数据
  275. *
  276. * @param {object} updateData
  277. * @return {Promise}
  278. */
  279. async updateUser(condition, updateData) {
  280. if (Object.keys(condition).length <= 0 || Object.keys(updateData).length <= 0) {
  281. return null;
  282. }
  283. return await this.db.update(condition, updateData);
  284. }
  285. async addVersion(condition, versionInfo) {
  286. return await this.db.findOneAndUpdate(condition, { $addToSet: { versionInfo: versionInfo } });
  287. }
  288. async removeVersion(userId, compilationId) {
  289. let userObjId = mongoose.Types.ObjectId(userId);
  290. return await this.db.findOneAndUpdate({ _id: userObjId }, { $pull: { versionInfo: { compilationId: compilationId } } });
  291. }
  292. /**
  293. * 判断用户使用免费版还是专业版
  294. *
  295. * @param ssoId
  296. * @param compilationId
  297. * @return {version}
  298. */
  299. async getVersionFromUpgrade(ssoId, compilationId) {
  300. let version = '纵横公路养护云造价(免费公用版)';//'纵横公路养护造价(免费云版)'; 2019-03-28 需求修改,听说不知道多久的以后还会改回来--勿删!!!!!
  301. let userData = await this.findDataBySsoId(ssoId);
  302. if (userData.upgrade_list !== undefined) {
  303. let compilationInfo = userData.upgrade_list.find(function (item) {
  304. return item.compilationID === compilationId;
  305. });
  306. if (compilationInfo !== undefined && compilationInfo.isUpgrade === true) {
  307. version = '纵横公路养护云造价(专业版)';
  308. }
  309. }
  310. return version;
  311. }
  312. /**
  313. * 判断用户是免费版还是专业版用户
  314. */
  315. async isFree(ssoId, compilationId) {
  316. const userData = await this.findDataBySsoId(ssoId);
  317. if (!userData) {
  318. throw '不存在此用户';
  319. }
  320. const upgrade_list = userData.upgrade_list;
  321. let free = true;
  322. if (upgrade_list && upgrade_list.length > 0) {
  323. const upgrade = upgrade_list.find(function (item) {
  324. return item.compilationID === compilationId && item.isUpgrade === true;
  325. });
  326. if (upgrade) {
  327. free = false;
  328. }
  329. }
  330. return free
  331. }
  332. /*
  333. * 添加联系人,互相添加
  334. */
  335. async addContact(userID, contactID) {
  336. const data = [
  337. { user: userID, contact: contactID },
  338. { user: contactID, contact: userID }
  339. ];
  340. const task = [];
  341. for (const { user, contact } of data) {
  342. const hasThisContact = await this.model.count({ _id: mongoose.Types.ObjectId(user), 'contacts.userID': contact });
  343. // 没有则添加
  344. if (!hasThisContact) {
  345. task.push(this.model.update({ _id: mongoose.Types.ObjectId(user) }, { $push: { contacts: { userID: contact } } }));
  346. }
  347. }
  348. if (task.length) {
  349. await Promise.all(task);
  350. }
  351. }
  352. async getContacts(userID) {
  353. const user = await this.model.findOne({ _id: mongoose.Types.ObjectId(userID) }, 'contacts').lean();
  354. if (!user) {
  355. return [];
  356. }
  357. const userIDList = user.contacts.map(item => mongoose.Types.ObjectId(item.userID));
  358. const users = await this.model.find({ _id: { $in: userIDList } }, 'real_name mobile company');
  359. return users;
  360. }
  361. }
  362. export default UserModel;