project.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. 'use strict';
  2. /**
  3. * 项目数据模型
  4. *
  5. * @author CaiAoLin
  6. * @date 2017/11/16
  7. * @version
  8. */
  9. module.exports = app => {
  10. class Project extends app.BaseService {
  11. /**
  12. * 构造函数
  13. *
  14. * @param {Object} ctx - egg全局变量
  15. * @return {void}
  16. */
  17. constructor(ctx) {
  18. super(ctx);
  19. this.tableName = 'project';
  20. // 状态相关
  21. this.status = {
  22. TRY: 1,
  23. NORMAL: 2,
  24. DISABLE: 3,
  25. };
  26. }
  27. /**
  28. * 数据规则
  29. *
  30. * @param {String} scene - 场景
  31. * @return {Object} - 返回数据规则
  32. */
  33. rule(scene) {
  34. let rule = {};
  35. switch (scene) {
  36. case 'saveInfo':
  37. rule = {
  38. name: { type: 'string', required: true, min: 2 },
  39. };
  40. break;
  41. default:
  42. break;
  43. }
  44. return rule;
  45. }
  46. /**
  47. * 根据项目code获取项目数据
  48. *
  49. * @param {String} code - 项目code
  50. * @return {Object} - 返回项目数据
  51. */
  52. async getProjectByCode(code) {
  53. // 获取项目状态为非禁止的项目
  54. this.initSqlBuilder();
  55. this.sqlBuilder.setAndWhere('code', {
  56. value: this.db.escape(code),
  57. operate: '=',
  58. });
  59. this.sqlBuilder.setAndWhere('status', {
  60. value: this.status.DISABLE,
  61. operate: '<',
  62. });
  63. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  64. const projectData = await this.db.queryOne(sql, sqlParam);
  65. return projectData;
  66. }
  67. /**
  68. * 切换项目
  69. *
  70. * @param {Number} projectId - 项目id
  71. * @return {Boolean} - 返回切换结果
  72. */
  73. async switchProject(projectId) {
  74. // 获取该用户拥有的项目数据
  75. const sessionUser = this.ctx.session.sessionUser;
  76. const projectInfo = await this.ctx.service.projectAccount.getProjectInfoByAccount(sessionUser.account);
  77. let result = false;
  78. // 判断切换的项目是否属于对应用户
  79. if (projectInfo.length < 0) {
  80. return result;
  81. }
  82. let targetProject = {};
  83. for (const tmp of projectInfo) {
  84. if (tmp.id === projectId) {
  85. result = true;
  86. targetProject = tmp;
  87. }
  88. }
  89. // 成功后更改session
  90. if (result) {
  91. this.ctx.session.sessionProject = {
  92. id: targetProject.id,
  93. name: targetProject.name,
  94. userAccount: targetProject.user_account,
  95. };
  96. }
  97. return result;
  98. }
  99. }
  100. return Project;
  101. };