user_model.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. console.log("updateUser 开始 -------------------------------");
  171. let updateResult = await this.updateUser(condition,UpdateData);
  172. console.log("updateUser 完成 -------------------------------");
  173. if (updateResult.ok === 1) {
  174. let logModel = new LogModel();
  175. result = await logModel.addLoginLog(userDataFromDb._id, request);
  176. console.log("addLoginLog 完成 -------------------------------");
  177. }
  178. }
  179. request.session.sessionUser.id = userDataFromDb._id;
  180. request.session.sessionUser.real_name = userDataFromDb.real_name;
  181. request.session.sessionUser.latest_used = userDataFromDb.latest_used;//设置最近使用的编办
  182. return result;
  183. }
  184. /**
  185. * 选择场景
  186. *
  187. * @param {string} scene
  188. */
  189. setScene(scene = '') {
  190. /* switch (scene) {
  191. case 'saveInfo':
  192. this.model.schema.path('real_name').required(true);
  193. this.model.schema.path('company').required(true);
  194. this.model.schema.path('province').required(true);
  195. this.model.schema.path('version').required(true);
  196. break;
  197. case '':
  198. this.model.schema.path('real_name').required(false);
  199. this.model.schema.path('company').required(false);
  200. this.model.schema.path('province').required(false);
  201. this.model.schema.path('version').required(false);
  202. }*/
  203. }
  204. /**
  205. * 根据用户名查找数据
  206. *
  207. * @param {string} username
  208. * @return {object}
  209. */
  210. findDataByName(username) {
  211. return this.db.findOne({username: username});
  212. }
  213. /**
  214. * 根据ssoID查找数据
  215. *
  216. * @param {string} ssoId
  217. * @return {object}
  218. */
  219. findDataBySsoId(ssoId) {
  220. return this.db.findOne({ssoId: ssoId});
  221. }
  222. /**
  223. * 根据手机号查找数据
  224. *
  225. * @param {string} mobile
  226. * @return {object}
  227. */
  228. findDataByMobile(mobile) {
  229. return this.db.findOne({mobile: mobile});
  230. }
  231. /**
  232. * 根据userId查找数据
  233. *
  234. * @param {string} ssoId
  235. * @return {object}
  236. */
  237. async findDataById(id) {
  238. let objId = mongoose.Types.ObjectId(id);
  239. return await this.db.findOne({_id: objId});
  240. }
  241. async findDataByAccount(account) {
  242. let userinfo = await this.db.findOne({mobile: account});
  243. let userinfo2 = await this.db.findOne({email: account});
  244. if (userinfo) {
  245. return userinfo;
  246. } else if (userinfo2) {
  247. return userinfo2;
  248. } else {
  249. return false;
  250. }
  251. }
  252. /**
  253. * 新增用户
  254. *
  255. * @param {object} userData
  256. * @return {Promise|boolean}
  257. */
  258. addUser(userData) {
  259. let insertData = {
  260. ssoId: userData.ssoId,
  261. username: userData.username,
  262. email: userData.email,
  263. mobile: userData.mobile,
  264. qq: userData.qq,
  265. create_time: new Date().getTime(),
  266. latest_login: new Date().getTime(),
  267. isUserActive: userData.isUserActive,
  268. };
  269. return this.db.create(insertData);
  270. }
  271. //更新最近使用编办ID
  272. async updateLatestUsed(userID,compilationID){
  273. if(userID && compilationID){
  274. return await this.db.update({'_id':userID},{'latest_used':compilationID});
  275. }
  276. }
  277. /**
  278. * 更新用户数据
  279. *
  280. * @param {object} updateData
  281. * @return {Promise}
  282. */
  283. async updateUser(condition, updateData) {
  284. if (Object.keys(condition).length <= 0 || Object.keys(updateData).length <= 0) {
  285. return null;
  286. }
  287. return await this.db.update(condition, updateData);
  288. }
  289. async addVersion(condition, versionInfo){
  290. return await this.db.findOneAndUpdate(condition, {$addToSet: {versionInfo: versionInfo}});
  291. }
  292. async removeVersion(userId, compilationId){
  293. let userObjId = mongoose.Types.ObjectId(userId);
  294. return await this.db.findOneAndUpdate({_id: userObjId}, {$pull: {versionInfo: {compilationId: compilationId}}});
  295. }
  296. /**
  297. * 判断用户使用免费版还是专业版
  298. *
  299. * @param ssoId
  300. * @param compilationId
  301. * @return {version}
  302. */
  303. async getVersionFromUpgrade(ssoId, compilationId){
  304. let version = '大司空云计价(免费公用版)';
  305. let userData = await this.findDataBySsoId(ssoId);
  306. if (userData.upgrade_list !== undefined) {
  307. let compilationInfo = userData.upgrade_list.find(function (item) {
  308. return item.compilationID === compilationId;
  309. });
  310. if (compilationInfo !== undefined && compilationInfo.isUpgrade === true) {
  311. version = '大司空云计价(专业版)';
  312. }
  313. }
  314. return version;
  315. }
  316. /**
  317. * 判断用户是免费版还是专业版用户
  318. */
  319. async isFree(ssoId, compilationId) {
  320. const userData = await this.findDataBySsoId(ssoId);
  321. if (!userData) {
  322. throw '不存在此用户';
  323. }
  324. const upgrade_list = userData.upgrade_list;
  325. let free = true;
  326. if (upgrade_list && upgrade_list.length > 0) {
  327. const upgrade = upgrade_list.find(function (item) {
  328. return item.compilationID === compilationId && item.isUpgrade === true;
  329. });
  330. if (upgrade) {
  331. free = false;
  332. }
  333. }
  334. return free
  335. }
  336. /*
  337. * 添加联系人,互相添加
  338. */
  339. async addContact(userID, contactID) {
  340. const data = [
  341. { user: userID, contact: contactID },
  342. { user: contactID, contact: userID }
  343. ];
  344. const task = [];
  345. for (const { user, contact } of data) {
  346. const hasThisContact = await this.model.count({_id: mongoose.Types.ObjectId(user), 'contacts.userID': contact});
  347. // 没有则添加
  348. if (!hasThisContact) {
  349. task.push(this.model.update({_id: mongoose.Types.ObjectId(user)}, {$push: {contacts: {userID: contact}}}));
  350. }
  351. }
  352. if (task.length) {
  353. await Promise.all(task);
  354. }
  355. }
  356. async getContacts(userID) {
  357. const user = await this.model.findOne({_id: mongoose.Types.ObjectId(userID)}, 'contacts').lean();
  358. if (!user) {
  359. return [];
  360. }
  361. const userIDList = user.contacts.map(item => mongoose.Types.ObjectId(item.userID));
  362. const users = await this.model.find({_id: {$in: userIDList}}, 'real_name mobile company');
  363. return users;
  364. }
  365. }
  366. export default UserModel;