Browse Source

第一次提交

XMLWAN 4 years ago
commit
c0750cd05c
100 changed files with 20242 additions and 0 deletions
  1. 123 0
      conf/app.conf
  2. 3 0
      controllers/Readme.md
  3. 124 0
      controllers/admin_user/admin_controller.go
  4. 297 0
      controllers/admin_user/org_controller.go
  5. 6 0
      controllers/admin_user/router_collector.go
  6. 1488 0
      controllers/article/article_controller.go
  7. 5 0
      controllers/article/router_collector.go
  8. 95 0
      controllers/base_api_controller.go
  9. 46 0
      controllers/base_controller.go
  10. 34 0
      controllers/base_view_controller.go
  11. 26 0
      controllers/global/district_controller.go
  12. 36 0
      controllers/global/error_controller.go
  13. 396 0
      controllers/global/open_wechat_controller.go
  14. 37 0
      controllers/global/qiniu_controller.go
  15. 9 0
      controllers/global/router_collector.go
  16. 50 0
      controllers/global/sms_controller.go
  17. 5 0
      controllers/kefu/router_collector.go
  18. 63 0
      controllers/kefu/tencent_usersig_api_controller.go
  19. 154 0
      controllers/login/login_controller.go
  20. 5 0
      controllers/login/router_collector.go
  21. 519 0
      controllers/marketing_tool/activity_controller.go
  22. 19 0
      controllers/marketing_tool/activity_vms.go
  23. 5 0
      controllers/marketing_tool/router_collector.go
  24. 496 0
      controllers/members/card_controller.go
  25. 657 0
      controllers/members/members_controller.go
  26. 7 0
      controllers/members/router_controller.go
  27. 395 0
      controllers/members/tags_controller.go
  28. 351 0
      controllers/micro/micro_controller.go
  29. 5 0
      controllers/micro/router_collector.go
  30. 179 0
      controllers/mpwechat/material_controller.go
  31. 280 0
      controllers/mpwechat/menu_controller.go
  32. 52 0
      controllers/mpwechat/mpwechat_controller.go
  33. 318 0
      controllers/mpwechat/reply_controller.go
  34. 8 0
      controllers/mpwechat/router_controller.go
  35. 43 0
      controllers/register/reigster_contrller.go
  36. 5 0
      controllers/register/router_collector.go
  37. 336 0
      controllers/role/admin_controller.go
  38. 227 0
      controllers/role/role_controller.go
  39. 6 0
      controllers/role/router_collector.go
  40. 5 0
      controllers/site/router_collector.go
  41. 5484 0
      controllers/site/site_controller.go
  42. 5 0
      controllers/sms/router_collector.go
  43. 236 0
      controllers/sms/sms_controller.go
  44. 5 0
      controllers/staff/router_collector.go
  45. 290 0
      controllers/staff/staff_controller.go
  46. 171 0
      enums/error_code.go
  47. 129 0
      jobcron/activity_short_url_job.go
  48. 201 0
      jobcron/open_wechat_job.go
  49. 44 0
      jobcron/qiniu_job.go
  50. 24 0
      jobcron/sms_job.go
  51. 35 0
      main.go
  52. 3 0
      models/Readme.md
  53. 100 0
      models/activity_models.go
  54. 69 0
      models/admin_user_models.go
  55. 123 0
      models/article_models.go
  56. 18 0
      models/district_models.go
  57. 27 0
      models/illness_models.go
  58. 19 0
      models/login_models.go
  59. 29 0
      models/org_fans_models.go
  60. 92 0
      models/org_models.go
  61. 37 0
      models/purview_models.go
  62. 61 0
      models/role_models.go
  63. 130 0
      models/service_models.go
  64. 557 0
      models/site_models.go
  65. 77 0
      models/sms_models.go
  66. 11 0
      models/subscibe_state_models.go
  67. 35 0
      models/user_customer_models.go
  68. 51 0
      models/user_membership_card_models.go
  69. 57 0
      models/user_models.go
  70. 28 0
      models/user_tag_models.go
  71. 104 0
      models/wechat_models.go
  72. 49 0
      routers/router.go
  73. 5 0
      service/Readme.md
  74. 383 0
      service/admin_service/verify_login_token_service.go
  75. 372 0
      service/article_service/article_category_service.go
  76. 10 0
      service/article_service/models.go
  77. 108 0
      service/db.go
  78. 11 0
      service/district_service/district_service.go
  79. 14 0
      service/login_service/login_service.go
  80. 221 0
      service/marketing_tool_service/activity_service.go
  81. 141 0
      service/member_service/cards_service.go
  82. 22 0
      service/member_service/illness_service.go
  83. 201 0
      service/member_service/member_service.go
  84. 56 0
      service/member_service/models.go
  85. 184 0
      service/member_service/tags_service.go
  86. 179 0
      service/micro_service/micro_service.go
  87. 14 0
      service/org_service/org_fans_service.go
  88. 14 0
      service/org_service/org_info_models.go
  89. 32 0
      service/org_service/org_info_service.go
  90. 29 0
      service/org_service/subscibe_service.go
  91. 21 0
      service/redis.go
  92. 407 0
      service/role_service/role_service.go
  93. 1913 0
      service/site_service/site_microwebsite_service.go
  94. 116 0
      service/sms_service/sms_db_service.go
  95. 325 0
      service/sms_service/sms_service.go
  96. 8 0
      service/sms_service/sms_vms.go
  97. 164 0
      service/sms_service/ucpaas.go
  98. 48 0
      service/staff_service/staff_manager_service.go
  99. 28 0
      service/tencentim_service/tencent_im_service.go
  100. 0 0
      service/tencentim_service/user_service.go

+ 123 - 0
conf/app.conf View File

@@ -0,0 +1,123 @@
1
+appname = SCRM
2
+httpport = 9534
3
+runmode =  dev
4
+
5
+copyrequestbody = true
6
+sessionon = true
7
+sessiongcmaxlifetime = 64800
8
+
9
+tokencookiemaxlifetime = 7200
10
+
11
+enablexsrf = false
12
+xsrfkey = 61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o
13
+xsrfexpire = 3600
14
+
15
+qiniu_accesskey = -l_Pcc1YJs0gh3w0YwN2uoaZO_5fY5J9SIYnSjg0
16
+qiniu_secretkey = DmZSp_Bmnp-9aUB7xUvoyViZpzmx1Rs2RL69GvlW
17
+qiniu_domain = https://images.shengws.com/
18
+qiniu_bucket = syhclub-storage
19
+
20
+aes_key = "shengws201804238"
21
+
22
+wxtoken = gh_ac6cd0cdde3d
23
+wxoriId = gh_ac6cd0cdde3d
24
+wxappId = wxbb9223f20bc11612
25
+# wxappsecret = a78c793c377268db25dde2eb971a2ebb
26
+# wxEncodingAESKey = 1vRDzqltXYOc9iMqhsQT7AkIRRpUaGl8MZlUcP7x4UK
27
+
28
+sms_appId = dcabb3aa7afd402794046ebbbf652bce
29
+sms_sid = a26cb0ceb3a811ca82143972f4ef38a4
30
+sms_token = ea475ed8d3de6c54c2b3f9d78db76d1e
31
+sms_baseUrl = https://open.ucpaas.com/ol/sms/
32
+ip_max_send_count = 20
33
+moblie_max_send_count = 5
34
+sms_verification_code_templateid = 329532
35
+
36
+appid = "wx43ad410d9eef426e"
37
+mchid = "1509573721"
38
+key = "e4SHrkiZu0pQEwVoGBapDBTf9N1Q6MxV"
39
+appsecret="61ee2e6268497d5aa9de0b0187c39aea"
40
+
41
+
42
+[prod]
43
+httpdomain = http://api.scrm.kuyicloud.com
44
+sso_domain = https://sso.kuyicloud.com
45
+front_end_domain = "http://jk.kuyicloud.com/#"
46
+
47
+openwechattoken = dwqofqon2e12en2o
48
+openwechatappid = wx9c877a6fc2acc742
49
+openwechatencodingaeskey = jiowefjw9pfjw9pfcw9pewjfow9huwgihg23hfwi8t4
50
+openwechatsecret = 5ac9ed5c6e3e8eee230befc7a7d04d37
51
+
52
+openwechatcomponentid = 1
53
+
54
+readmysqlhost = shengws1.mysql.rds.aliyuncs.com
55
+readmysqlport = 3306
56
+readmysqluser = syh
57
+readmysqlpass = xhPECP2nFObR8aUK
58
+readmysqlname = sgj_patient
59
+
60
+writemysqlhost = shengws1.mysql.rds.aliyuncs.com
61
+writemysqlport = 3306
62
+writemysqluser = syh
63
+writemysqlpass = xhPECP2nFObR8aUK
64
+writemysqlname = sgj_patient
65
+
66
+readuserhost = shengws1.mysql.rds.aliyuncs.com
67
+readuserport = 3306
68
+readuseruser = syh
69
+readuserpass = xhPECP2nFObR8aUK
70
+readusername = sgj_users
71
+
72
+writeuserhost = shengws1.mysql.rds.aliyuncs.com
73
+writeuserport = 3306
74
+writeuseruser = syh
75
+writeuserpass = xhPECP2nFObR8aUK
76
+writeusername = sgj_users
77
+
78
+redishost = 349e580b2a524290.redis.rds.aliyuncs.com
79
+redisport = 6379
80
+redispasswrod = TZtBW098WId3i27clkpj3q8dnUaVFP
81
+redisdb = 0
82
+
83
+[dev]
84
+httpdomain = http://api.test1.sgjyun.com
85
+sso_domain = https://testsso.sgjyun.com
86
+front_end_domain = "http://test1.sgjyun.com/#"
87
+
88
+openwechattoken = dwqofqon2e12en2o
89
+openwechatappid = wx710ed9839d337b2a
90
+openwechatencodingaeskey = jiowefjw9pfjw9pfcw9pewjfow9huwgihg23hfwi8t4
91
+openwechatsecret = bbce950b9404ed80a6727f2f3c2ec729
92
+
93
+openwechatcomponentid = 1
94
+
95
+readmysqlhost = rm-wz9rg531npf61q03tro.mysql.rds.aliyuncs.com
96
+readmysqlport = 3306
97
+readmysqluser = root
98
+readmysqlpass = 1Q2W3e4r!@#$
99
+readmysqlname = sgj_patient
100
+
101
+writemysqlhost = rm-wz9rg531npf61q03tro.mysql.rds.aliyuncs.com
102
+writemysqlport = 3306
103
+writemysqluser = root
104
+writemysqlpass = 1Q2W3e4r!@#$
105
+writemysqlname = sgj_patient
106
+
107
+readuserhost = rm-wz9rg531npf61q03tro.mysql.rds.aliyuncs.com
108
+readuserport = 3306
109
+readuseruser = root
110
+readuserpass = 1Q2W3e4r!@#$
111
+readusername = sgj_users
112
+
113
+writeuserhost = rm-wz9rg531npf61q03tro.mysql.rds.aliyuncs.com
114
+writeuserport = 3306
115
+writeuseruser = root
116
+writeuserpass = 1Q2W3e4r!@#$
117
+writeusername = sgj_users
118
+
119
+#redishost = 120.77.235.13
120
+redishost = 127.0.0.1
121
+redisport = 6379
122
+redispasswrod = syh@#$%123456!
123
+redisdb = 0

+ 3 - 0
controllers/Readme.md View File

@@ -0,0 +1,3 @@
1
+按业务分模块(包);  
2
+对于业务比较复杂的模块,再细分业务,拆分为多个控制器;
3
+每个控制器文件提供注册 router 的方法,每个模块建立一个 router_collector.go 文件,定义一个 RegisterRouters 方法,用以收集模块中控制器提供的注册 router 的方法,并在 router.go 中最终调用;

+ 124 - 0
controllers/admin_user/admin_controller.go View File

@@ -0,0 +1,124 @@
1
+package admin_user
2
+
3
+import (
4
+	base_ctl "SCRM/controllers"
5
+	"SCRM/enums"
6
+	base_service "SCRM/service"
7
+	"SCRM/service/admin_service"
8
+	"SCRM/service/role_service"
9
+	"SCRM/service/sms_service"
10
+	"strconv"
11
+	"time"
12
+
13
+	"fmt"
14
+	"github.com/astaxie/beego"
15
+)
16
+
17
+func AdminCtlRegistRouters() {
18
+	beego.Router("/api/password/code", &AdminController{}, "post:CodeOfModifyPwd")
19
+	beego.Router("/api/password/modify", &AdminController{}, "post:ModifyPwd")
20
+	beego.Router("/api/admin/edit_info", &AdminController{}, "post:EditAdminUserInfo")
21
+}
22
+
23
+type AdminController struct {
24
+	base_ctl.BaseAuthAPIController
25
+}
26
+
27
+// /api/admin/edit_info [post]
28
+// @param avatar:string
29
+// @param name:string
30
+// @param opwd?:string 没有原始密码的时候,认为不修改密码
31
+// @param npwd?:string
32
+func (this *AdminController) EditAdminUserInfo() {
33
+	adminUserInfo := this.GetAdminUserInfo()
34
+
35
+	avatar := this.GetString("avatar")
36
+	name := this.GetString("name")
37
+	if len(name) == 0 {
38
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeMissingUserName)
39
+		return
40
+	}
41
+	modifyErr := role_service.ModifyAdminUserInfo(adminUserInfo.AdminUser.Id, adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, name, avatar, "")
42
+	if modifyErr != nil {
43
+		this.ErrorLog("修改个人信息失败:%v", modifyErr)
44
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
45
+
46
+	} else {
47
+		appRole := adminUserInfo.AppRoles[adminUserInfo.CurrentAppId]
48
+		appRole.UserName = name
49
+		appRole.Avatar = avatar
50
+		this.ServeSuccessJSON(nil)
51
+	}
52
+}
53
+
54
+// /api/password/code [post]
55
+func (this *AdminController) CodeOfModifyPwd() {
56
+	adminUserInfo := this.GetAdminUserInfo()
57
+	mobile := adminUserInfo.AdminUser.Mobile
58
+
59
+	redisClient := base_service.RedisClient()
60
+	defer redisClient.Close()
61
+
62
+	cur_date := time.Now().Format("2006-01-02")
63
+	moblie_count, _ := redisClient.Get("scrm_verification_code_" + mobile + "_" + cur_date).Result()
64
+	moblie_count_int, _ := strconv.Atoi(moblie_count)
65
+	if moblie_max := 5; moblie_count_int >= moblie_max {
66
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeVerificationCodeLimit)
67
+		return
68
+	}
69
+
70
+	if code, err := sms_service.SMSSendVerificationCode(mobile); err != nil {
71
+		this.ErrorLog("修改密码发送验证码失败:%v", err)
72
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
73
+		return
74
+
75
+	} else {
76
+		cur_date := time.Now().Format("2006-01-02")
77
+		redisClient.Set("scrm_verification_code_"+mobile, code, time.Minute*10)
78
+		redisClient.Incr("scrm_verification_code_" + mobile + "_" + cur_date).Result()
79
+
80
+		this.ServeSuccessJSON(map[string]interface{}{
81
+			"msg": "短信发送成功,有效期为10分钟",
82
+		})
83
+	}
84
+}
85
+
86
+// /api/password/modify [post]
87
+// @param password:string
88
+// @param code:string
89
+func (this *AdminController) ModifyPwd() {
90
+	new_pwd := this.GetString("password")
91
+	code := this.GetString("code")
92
+	if len(new_pwd) == 0 || len(code) == 0 {
93
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
94
+		return
95
+	}
96
+
97
+	adminUserInfo := this.GetAdminUserInfo()
98
+	mobile := adminUserInfo.AdminUser.Mobile
99
+
100
+	redisClient := base_service.RedisClient()
101
+	defer redisClient.Close()
102
+	cachedCode, err := redisClient.Get("scrm_verification_code_" + mobile).Result()
103
+	fmt.Println("hhhhhhhhhhhhhh", cachedCode)
104
+	if err != nil {
105
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAccountOrVerCodeWrong)
106
+		return
107
+	}
108
+	if code != cachedCode {
109
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAccountOrVerCodeWrong)
110
+		return
111
+	}
112
+
113
+	if modifyErr := admin_service.ModifyPassword(adminUserInfo.AdminUser.Id, new_pwd); modifyErr != nil {
114
+		this.ErrorLog("修改密码失败:%v", modifyErr)
115
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
116
+		return
117
+	}
118
+
119
+	// 清除验证码
120
+	redisClient.Del("scrm_verification_code_" + mobile)
121
+	this.ServeSuccessJSON(map[string]interface{}{
122
+		"msg": "密码已修改",
123
+	})
124
+}

+ 297 - 0
controllers/admin_user/org_controller.go View File

@@ -0,0 +1,297 @@
1
+package admin_user
2
+
3
+import (
4
+	base_ctl "SCRM/controllers"
5
+	"SCRM/enums"
6
+	"SCRM/models"
7
+	"SCRM/service/district_service"
8
+	"SCRM/service/org_service"
9
+	"SCRM/utils"
10
+	"encoding/json"
11
+	"reflect"
12
+	"time"
13
+
14
+	"fmt"
15
+	"github.com/astaxie/beego"
16
+)
17
+
18
+func OrgInfoCtlRegistRouters() {
19
+	beego.Router("/api/orginfo/getinfo", &OrgInfoApiController{}, "get:GetOrgInfo")
20
+	beego.Router("/api/orginfo/savegallery", &OrgInfoApiController{}, "post:SaveOrgGallery")
21
+	beego.Router("/api/orginfo/deletegallery", &OrgInfoApiController{}, "delete:DeleteOrgGallery")
22
+	beego.Router("/api/orginfo/edit", &OrgInfoApiController{}, "post:EditOrgInfo")
23
+}
24
+
25
+type OrgInfoApiController struct {
26
+	base_ctl.BaseAuthAPIController
27
+}
28
+
29
+func (c *OrgInfoApiController) GetOrgInfo() {
30
+
31
+	adminUserInfo := c.GetAdminUserInfo()
32
+	fmt.Println("adminUserInfo是什么", adminUserInfo)
33
+	orgInfo := adminUserInfo.Orgs[adminUserInfo.CurrentOrgId]
34
+	fmt.Println("orgInfo是设么", orgInfo)
35
+	fmt.Println("orgInfo是什么", orgInfo.Province)
36
+	provinces, _ := district_service.GetDistrictsByUpid(0)
37
+	var citys []*models.District
38
+	var districts []*models.District
39
+	if orgInfo.Province > 0 {
40
+		citys, _ = district_service.GetDistrictsByUpid(orgInfo.Province)
41
+	}
42
+	if orgInfo.City > 0 {
43
+		districts, _ = district_service.GetDistrictsByUpid(orgInfo.City)
44
+	}
45
+
46
+	orgtypes, _ := org_service.GetOrgTypes()
47
+
48
+	illness, _ := org_service.GetIllnessList()
49
+
50
+	c.ServeSuccessJSON(map[string]interface{}{
51
+		"orginfo":   orgInfo,
52
+		"provinces": provinces,
53
+		"citys":     citys,
54
+		"districts": districts,
55
+		"orgtypes":  orgtypes,
56
+		"illness":   illness,
57
+	})
58
+	return
59
+}
60
+
61
+func (c *OrgInfoApiController) EditOrgInfo() {
62
+	adminUserInfo := c.GetAdminUserInfo()
63
+
64
+	if !adminUserInfo.AdminUser.IsSuperAdmin {
65
+		c.ServeFailJsonSend(enums.ErrorCodePermissionDenied, "权限不足")
66
+		return
67
+	}
68
+
69
+	dataBody := make(map[string]interface{}, 0)
70
+	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
71
+	if err != nil {
72
+		utils.ErrorLog(err.Error())
73
+		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
74
+		return
75
+	}
76
+
77
+	orgInfo := adminUserInfo.Orgs[adminUserInfo.CurrentOrgId]
78
+	org := *orgInfo
79
+
80
+	if dataBody["org_name"] == nil || reflect.TypeOf(dataBody["org_name"]).String() != "string" {
81
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:机构名称")
82
+		return
83
+	}
84
+	orgName, _ := dataBody["org_name"].(string)
85
+	if len(orgName) == 0 {
86
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "机构名称不能为空")
87
+		return
88
+	}
89
+	org.OrgName = orgName
90
+
91
+	if dataBody["contact_name"] == nil || reflect.TypeOf(dataBody["contact_name"]).String() != "string" {
92
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:联系人姓名")
93
+		return
94
+	}
95
+	contactName, _ := dataBody["contact_name"].(string)
96
+	if len(contactName) == 0 {
97
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "联系人姓名不能为空")
98
+		return
99
+	}
100
+	org.ContactName = contactName
101
+
102
+	// if dataBody["org_short_name"] == nil || reflect.TypeOf(dataBody["org_short_name"]).String() != "string" {
103
+	// 	c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:商家简称")
104
+	// 	return
105
+	// }
106
+	// orgShortName, _ := dataBody["org_short_name"].(string)
107
+	// if len(orgShortName) == 0 {
108
+	// 	c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "商家简称不能为空")
109
+	// 	return
110
+	// }
111
+	org.OrgShortName = orgName
112
+
113
+	if dataBody["org_introduction"] == nil || reflect.TypeOf(dataBody["org_introduction"]).String() != "string" {
114
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:机构介绍")
115
+		return
116
+	}
117
+	orgIntroduction, _ := dataBody["org_introduction"].(string)
118
+	if len(orgIntroduction) == 0 {
119
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "机构介绍不能为空")
120
+		return
121
+	}
122
+	org.OrgIntroduction = orgIntroduction
123
+
124
+	if dataBody["org_logo"] == nil || reflect.TypeOf(dataBody["org_logo"]).String() != "string" {
125
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:机构头像")
126
+		return
127
+	}
128
+	orgLogo, _ := dataBody["org_logo"].(string)
129
+	if len(orgLogo) == 0 {
130
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "机构头像不能为空")
131
+		return
132
+	}
133
+	org.OrgLogo = orgLogo
134
+
135
+	if dataBody["province"] != nil || reflect.TypeOf(dataBody["province"]).String() == "float64" {
136
+		province := int64(dataBody["province"].(float64))
137
+		org.Province = province
138
+	}
139
+
140
+	if dataBody["city"] != nil || reflect.TypeOf(dataBody["city"]).String() == "float64" {
141
+		city := int64(dataBody["city"].(float64))
142
+		org.City = city
143
+	}
144
+
145
+	if dataBody["district"] != nil || reflect.TypeOf(dataBody["district"]).String() == "float64" {
146
+		district := int64(dataBody["district"].(float64))
147
+		org.District = district
148
+	}
149
+
150
+	if dataBody["address"] != nil || reflect.TypeOf(dataBody["address"]).String() == "string" {
151
+		address, _ := dataBody["address"].(string)
152
+		org.Address = address
153
+	}
154
+
155
+	if dataBody["org_type"] != nil || reflect.TypeOf(dataBody["org_type"]).String() == "float64" {
156
+		orgType := int64(dataBody["org_type"].(float64))
157
+		org.OrgType = orgType
158
+	}
159
+
160
+	if dataBody["telephone"] != nil || reflect.TypeOf(dataBody["telephone"]).String() == "string" {
161
+		telephone, _ := dataBody["telephone"].(string)
162
+		org.Telephone = telephone
163
+	}
164
+
165
+	if dataBody["operating_state"] != nil || reflect.TypeOf(dataBody["operating_state"]).String() == "float64" {
166
+		operatingState := int64(dataBody["operating_state"].(float64))
167
+		org.OperatingState = operatingState
168
+	}
169
+
170
+	if dataBody["business_week"] != nil || reflect.TypeOf(dataBody["business_week"]).String() == "string" {
171
+		businessWeek, _ := dataBody["business_week"].(string)
172
+		org.BusinessWeek = businessWeek
173
+	}
174
+
175
+	if dataBody["business_time"] != nil || reflect.TypeOf(dataBody["business_time"]).String() == "string" {
176
+		businessTime, _ := dataBody["business_time"].(string)
177
+		org.BusinessTime = businessTime
178
+	}
179
+	if dataBody["illness"] != nil || reflect.TypeOf(dataBody["illness"]).String() == "string" {
180
+		illness, _ := dataBody["illness"].(string)
181
+		org.Illness = illness
182
+	}
183
+
184
+	timeNow := time.Now().Unix()
185
+	org.ModifyTime = timeNow
186
+	org.OrgGallery = nil
187
+	err = org_service.UpdateOrgInfo(&org)
188
+	if err != nil {
189
+		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
190
+		return
191
+	}
192
+
193
+	orgInfo.OrgName = orgName
194
+	orgInfo.OrgShortName = orgName
195
+	orgInfo.OrgIntroduction = orgIntroduction
196
+	orgInfo.OrgLogo = orgLogo
197
+	orgInfo.Province = org.Province
198
+	orgInfo.District = org.District
199
+	orgInfo.City = org.City
200
+	orgInfo.OrgType = org.OrgType
201
+	orgInfo.Telephone = org.Telephone
202
+	orgInfo.OperatingState = org.OperatingState
203
+	orgInfo.BusinessWeek = org.BusinessWeek
204
+	orgInfo.BusinessTime = org.BusinessTime
205
+	orgInfo.Illness = org.Illness
206
+	orgInfo.ContactName = org.ContactName
207
+
208
+	c.ServeSuccessJSON(map[string]interface{}{
209
+		"msg": "ok",
210
+	})
211
+	return
212
+}
213
+
214
+func (c *OrgInfoApiController) SaveOrgGallery() {
215
+	adminUserInfo := c.GetAdminUserInfo()
216
+
217
+	dataBody := make(map[string]interface{}, 0)
218
+	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
219
+	if err != nil {
220
+		utils.ErrorLog(err.Error())
221
+		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
222
+		return
223
+	}
224
+
225
+	if dataBody["type"] == nil || reflect.TypeOf(dataBody["type"]).String() != "float64" {
226
+		utils.ErrorLog("type")
227
+		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
228
+		return
229
+	}
230
+	galleryType := int64(dataBody["type"].(float64))
231
+	if galleryType != 1 && galleryType != 2 {
232
+		utils.ErrorLog("galleryType != 1&&2")
233
+		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
234
+		return
235
+	}
236
+
237
+	if dataBody["url"] == nil || reflect.TypeOf(dataBody["url"]).String() != "string" {
238
+		utils.ErrorLog("url")
239
+		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
240
+		return
241
+	}
242
+	url, _ := dataBody["url"].(string)
243
+	if len(url) == 0 {
244
+		utils.ErrorLog("len(url) == 0")
245
+		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
246
+		return
247
+	}
248
+
249
+	timeNow := time.Now().Unix()
250
+	var gallery models.OrgGallery
251
+	gallery.Type = galleryType
252
+	gallery.Url = url
253
+	gallery.OrgId = adminUserInfo.CurrentOrgId
254
+	gallery.Status = 1
255
+	gallery.Ctime = timeNow
256
+	gallery.Mtime = timeNow
257
+	err = org_service.CreateOrgGalleryItem(&gallery)
258
+	if err != nil {
259
+		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
260
+		return
261
+	}
262
+
263
+	orgInfo := adminUserInfo.Orgs[adminUserInfo.CurrentOrgId]
264
+	orgInfo.OrgGallery = append(orgInfo.OrgGallery, &gallery)
265
+	c.ServeSuccessJSON(map[string]interface{}{
266
+		"msg": "ok",
267
+	})
268
+	return
269
+
270
+}
271
+
272
+func (c *OrgInfoApiController) DeleteOrgGallery() {
273
+	adminUserInfo := c.GetAdminUserInfo()
274
+	id, _ := c.GetInt64("id", 0)
275
+	if id <= 0 {
276
+		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
277
+		return
278
+	}
279
+
280
+	err := org_service.DeleteOrgGalleryItem(id)
281
+	if err != nil {
282
+		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
283
+		return
284
+	}
285
+
286
+	orgInfo := adminUserInfo.Orgs[adminUserInfo.CurrentOrgId]
287
+	for index, item := range orgInfo.OrgGallery {
288
+		if item.ID == id {
289
+			orgInfo.OrgGallery = append(orgInfo.OrgGallery[:index], orgInfo.OrgGallery[index+1:]...)
290
+		}
291
+	}
292
+	c.ServeSuccessJSON(map[string]interface{}{
293
+		"msg": "ok",
294
+	})
295
+	return
296
+
297
+}

+ 6 - 0
controllers/admin_user/router_collector.go View File

@@ -0,0 +1,6 @@
1
+package admin_user
2
+
3
+func RegisterRouters() {
4
+	AdminCtlRegistRouters()
5
+	OrgInfoCtlRegistRouters()
6
+}

File diff suppressed because it is too large
+ 1488 - 0
controllers/article/article_controller.go


+ 5 - 0
controllers/article/router_collector.go View File

@@ -0,0 +1,5 @@
1
+package article
2
+
3
+func RegisterRouters() {
4
+	ArticleRouters()
5
+}

+ 95 - 0
controllers/base_api_controller.go View File

@@ -0,0 +1,95 @@
1
+package controllers
2
+
3
+import (
4
+	"SCRM/enums"
5
+	"SCRM/models"
6
+	"SCRM/service/admin_service"
7
+)
8
+
9
+type BaseAPIController struct {
10
+	BaseController
11
+}
12
+
13
+// 输出数据格式化
14
+/*
15
+	success json:
16
+	{
17
+		"state": 1,
18
+		"code": 0,
19
+		"data": json,
20
+	}
21
+
22
+	fail json:
23
+	{
24
+		"state": 0,
25
+		"code": int,
26
+		"msg": string,
27
+	}
28
+*/
29
+func (this *BaseAPIController) ServeSuccessJSON(data map[string]interface{}) {
30
+	this.Data["json"] = enums.MakeSuccessResponseJSON(data)
31
+	this.ServeJSON()
32
+}
33
+
34
+func (this *BaseAPIController) ServeFailJSONWithSGJErrorCode(code int) {
35
+	this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(code)
36
+	this.ServeJSON()
37
+}
38
+
39
+func (this *BaseAPIController) ServeFailJSONWithSGJError(err *enums.SGJError) {
40
+	this.Data["json"] = enums.MakeFailResponseJSONWithSGJError(err)
41
+	this.ServeJSON()
42
+}
43
+
44
+func (this *BaseAPIController) ServeFailJsonSend(code int, msg string) {
45
+	this.Data["json"] = enums.MakeFailResponseJSON(msg, code)
46
+	this.ServeJSON()
47
+}
48
+
49
+type BaseAuthAPIController struct {
50
+	BaseAPIController
51
+}
52
+
53
+func (this *BaseAuthAPIController) Prepare() {
54
+	this.BaseAPIController.Prepare()
55
+	if this.GetAdminUserInfo() == nil {
56
+		var userAdmin models.AdminUser
57
+		userAdmin.Id = 380
58
+		userAdmin.Mobile = "13532250447"
59
+		userAdmin.IsSuperAdmin = true
60
+		userAdmin.Status = 1
61
+		userAdmin.CreateTime = 1530786071
62
+		userAdmin.ModifyTime = 1530786071
63
+		var subscibe models.ServeSubscibe
64
+		subscibe.ID = 1
65
+		subscibe.OrgId = 4
66
+		subscibe.PeriodStart = 1538035409
67
+		subscibe.PeriodEnd = 1569571409
68
+		subscibe.State = 1
69
+		subscibe.Status = 1
70
+		subscibe.CreatedTime = 1538035409
71
+		subscibe.UpdatedTime = 1538035409
72
+		subscibes := make(map[int64]*models.ServeSubscibe, 0)
73
+		subscibes[4] = &subscibe
74
+		var adminUserInfo admin_service.AdminUserInfo
75
+		adminUserInfo.CurrentOrgId = 4
76
+		adminUserInfo.CurrentAppId = 5
77
+		adminUserInfo.AdminUser = &userAdmin
78
+		adminUserInfo.Subscibes = subscibes
79
+		this.SetSession("admin_user_info", &adminUserInfo)
80
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNotLogin)
81
+		this.StopRun()
82
+	}
83
+}
84
+
85
+type BaseServeAPIController struct {
86
+	BaseAPIController
87
+}
88
+
89
+func (this *BaseServeAPIController) Prepare() {
90
+	this.BaseAPIController.Prepare()
91
+	if this.GetAdminUserInfo() == nil {
92
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNotLogin)
93
+		this.StopRun()
94
+	}
95
+}

+ 46 - 0
controllers/base_controller.go View File

@@ -0,0 +1,46 @@
1
+package controllers
2
+
3
+import (
4
+	service "SCRM/service/admin_service"
5
+	"SCRM/utils"
6
+
7
+	"github.com/astaxie/beego"
8
+)
9
+
10
+type BaseController struct {
11
+	beego.Controller
12
+}
13
+
14
+func (this *BaseController) GetAdminUserInfo() *service.AdminUserInfo {
15
+	userInfo := this.GetSession("admin_user_info")
16
+	if userInfo == nil {
17
+		return nil
18
+	} else {
19
+		return userInfo.(*service.AdminUserInfo)
20
+	}
21
+}
22
+
23
+func (this *BaseController) ErrorLog(format string, a ...interface{}) {
24
+	//beego.Error(fmt.Sprintf(format, a...))
25
+	utils.ErrorLog(format, a...)
26
+}
27
+
28
+func (this *BaseController) WarnLog(format string, a ...interface{}) {
29
+	//beego.Warn(fmt.Sprintf(format, a...))
30
+	utils.WarningLog(format, a...)
31
+}
32
+
33
+func (this *BaseController) InfoLog(format string, a ...interface{}) {
34
+	//beego.Info(fmt.Sprintf(format, a...))
35
+	utils.InfoLog(format, a...)
36
+}
37
+
38
+func (this *BaseController) DebugLog(format string, a ...interface{}) {
39
+	//beego.Debug(fmt.Sprintf(format, a...))
40
+	utils.InfoLog(format, a...)
41
+}
42
+
43
+func (this *BaseController) TraceLog(format string, a ...interface{}) {
44
+	//beego.Trace(fmt.Sprintf(format, a...))
45
+	utils.TraceLog(format, a...)
46
+}

+ 34 - 0
controllers/base_view_controller.go View File

@@ -0,0 +1,34 @@
1
+package controllers
2
+
3
+type BaseViewController struct {
4
+	BaseController
5
+}
6
+
7
+// 设置模板
8
+// 第一个参数模板,第二个参数为layout
9
+func (this *BaseViewController) SetTpl(template ...string) {
10
+	var tplName string
11
+	layout := ""
12
+	switch {
13
+	case len(template) == 1:
14
+		tplName = template[0]
15
+	case len(template) == 2:
16
+		tplName = template[0]
17
+		layout = template[1]
18
+	default:
19
+		tplName = "index.tpl"
20
+	}
21
+	this.Layout = layout
22
+	this.TplName = tplName
23
+}
24
+
25
+// 重定向
26
+func (this *BaseViewController) Redirect302(url string) {
27
+	this.Redirect(url, 302)
28
+	this.StopRun()
29
+}
30
+
31
+// 错误页面
32
+func (this *BaseViewController) Abort404() {
33
+	this.Abort("404")
34
+}

+ 26 - 0
controllers/global/district_controller.go View File

@@ -0,0 +1,26 @@
1
+package global
2
+
3
+import (
4
+	base_ctl "SCRM/controllers"
5
+	"SCRM/service/district_service"
6
+
7
+	"github.com/astaxie/beego"
8
+)
9
+
10
+type DistrictApiController struct {
11
+	base_ctl.BaseAPIController
12
+}
13
+
14
+func DistrictCtlRegistRouters() {
15
+	beego.Router("/api/district/getdistrictsbyupid", &DistrictApiController{}, "get:GetDistrictsByUpid")
16
+}
17
+
18
+func (c *DistrictApiController) GetDistrictsByUpid() {
19
+	id, _ := c.GetInt64("id", 0)
20
+	citys, _ := district_service.GetDistrictsByUpid(id)
21
+
22
+	c.ServeSuccessJSON(map[string]interface{}{
23
+		"citys": citys,
24
+	})
25
+	return
26
+}

+ 36 - 0
controllers/global/error_controller.go View File

@@ -0,0 +1,36 @@
1
+package global
2
+
3
+import (
4
+	base_ctl "SCRM/controllers"
5
+	"SCRM/enums"
6
+	"fmt"
7
+
8
+	"github.com/astaxie/beego"
9
+)
10
+
11
+func ErrorCtlRegistRouters() {
12
+	beego.Router("/error", &ErrorViewController{}, "get:HandleError")
13
+}
14
+
15
+type ErrorViewController struct {
16
+	base_ctl.BaseViewController
17
+}
18
+
19
+// /handle_error [get]
20
+// @param code:int
21
+func (this *ErrorViewController) HandleError() {
22
+	code, _ := this.GetInt("code")
23
+	if code == enums.ErrorCodeNeverCreateTypeApp {
24
+		ssoDomain := beego.AppConfig.String("sso_domain")
25
+		createAppURL := fmt.Sprintf("%v/org/app/create", ssoDomain)
26
+		this.Redirect302(createAppURL)
27
+
28
+	} else if code == enums.ErrorCodeContactSuperAdminCreateTypeApp {
29
+		ssoDomain := beego.AppConfig.String("sso_domain")
30
+		hitURL := fmt.Sprintf("%v/create_app_hint", ssoDomain)
31
+		this.Redirect302(hitURL)
32
+
33
+	} else {
34
+		this.Abort404()
35
+	}
36
+}

+ 396 - 0
controllers/global/open_wechat_controller.go View File

@@ -0,0 +1,396 @@
1
+package global
2
+
3
+import (
4
+	base_ctl "SCRM/controllers"
5
+	"SCRM/enums"
6
+	"SCRM/models"
7
+	"fmt"
8
+	"strings"
9
+	"time"
10
+
11
+	"github.com/astaxie/beego"
12
+
13
+	"SCRM/service"
14
+	"SCRM/utils"
15
+	"encoding/base64"
16
+	"encoding/json"
17
+	"encoding/xml"
18
+	"strconv"
19
+
20
+	"SCRM/service/org_service"
21
+	"SCRM/service/wechat_service"
22
+
23
+	"io/ioutil"
24
+
25
+	crypter "github.com/heroicyang/wechat-crypter"
26
+)
27
+
28
+//OpenWechatAPIController 微信开放平台相关
29
+type OpenWechatAPIController struct {
30
+	base_ctl.BaseAPIController
31
+}
32
+
33
+func (c *OpenWechatAPIController) Prepare() {
34
+	c.EnableXSRF = false
35
+}
36
+
37
+//OpenWechatCtlRegistRouters 微信开放平台注册路由
38
+func OpenWechatCtlRegistRouters() {
39
+	beego.Router("/openwechat/authorizationevents", &OpenWechatAPIController{}, "*:AuthorizationEvents")
40
+	beego.Router("/openwechat/mp/notice/:appid", &OpenWechatAPIController{}, "Post:MpWechatNotice")
41
+	beego.Router("/openwechat/mp/authorization", &OpenWechatAPIController{}, "Get:Authorization")
42
+	beego.Router("/openwechat/mp/authorizerinfo/:id/:vtime/:vcode", &OpenWechatAPIController{}, "*:AuthorizerInfo")
43
+}
44
+
45
+// AuthorizationEvents 接收微信服务器推送的 授权事件
46
+// 有四个处理功能,由解密后的infoType决定
47
+// 每隔10分钟定时推送           component_verify_ticket
48
+// 公众号授权给第三方平台        authorized
49
+// 公众号对第三方平台取消授权    unauthorized
50
+// 公众号对第三方平台更新授权    updateauthorized
51
+func (c *OpenWechatAPIController) AuthorizationEvents() {
52
+	//接收微信服务器主动调起授权事件接收URL时,由微信服务器额外拼接在URL的几个参数,
53
+	// nonce := c.GetString("nonce")
54
+	// encryptType := c.GetString("encrypt_type")
55
+	// msgSignature := c.GetString("msg_signature")
56
+	// signature := c.GetString("signature")
57
+	// timestamp := c.GetString("timestamp")
58
+
59
+	// MsgEncrypt 类型的me,MsgEncrypt是根据接下来要读取的xml数据格式定义的struct,
60
+	var me wechat_service.MsgEncrypt
61
+	err := xml.Unmarshal(c.Ctx.Input.RequestBody, &me)
62
+	if err != nil {
63
+		utils.ErrorLog("read body error: %s", err)
64
+		c.Ctx.WriteString("success")
65
+		return
66
+	}
67
+
68
+	msgCrypter, _ := crypter.NewMessageCrypter(beego.AppConfig.String("openwechattoken"), beego.AppConfig.String("openwechatencodingaeskey"), beego.AppConfig.String("openwechatappid")) //这是github.com/heroicyang/config.WECHAT-crypter上的组件
69
+	msgDecrypt, _, err := msgCrypter.Decrypt(me.Encrypt)
70
+	if err != nil {
71
+		utils.ErrorLog("msgDecrypt error: %s", err)
72
+		c.Ctx.WriteString("success")
73
+		return
74
+	}
75
+	fmt.Println("msgDecrypt:", string(msgDecrypt))
76
+	//将上面解密后的xml读到InfoType struct
77
+	var requestBody wechat_service.ComponentRequestBody
78
+	err = xml.Unmarshal(msgDecrypt, &requestBody)
79
+	if err != nil {
80
+		utils.ErrorLog("Unmarshal ComponentRequestBody error: %s", err)
81
+		c.Ctx.WriteString("success")
82
+		return
83
+	}
84
+
85
+	//判断推送类型
86
+	// 	推送           component_verify_ticket
87
+	//  公众号授权给第三方平台        authorized
88
+	//  公众号对第三方平台取消授权    unauthorized
89
+	//  公众号对第三方平台更新授权    updateauthorized
90
+	if requestBody.InfoType == "component_verify_ticket" {
91
+		utils.InfoLog("接收到component_verify_ticket:%s, ", requestBody.ComponentVerifyTicket)
92
+		redisClient := service.RedisClient()
93
+
94
+		defer redisClient.Close()
95
+
96
+		err = redisClient.Set("sgj_patient:ComponentVerifyTicket", requestBody.ComponentVerifyTicket, 0).Err()
97
+		if err != nil {
98
+			utils.ErrorLog("redis set failed: %s", err)
99
+		}
100
+
101
+		componentID, err := beego.AppConfig.Int64("openwechatcomponentid")
102
+		if err != nil {
103
+			utils.ErrorLog("get component id failed: %s", err)
104
+		}
105
+
106
+		err = wechat_service.SaveWechatComponentVerifyTicket(componentID, requestBody.ComponentVerifyTicket)
107
+		if err != nil {
108
+			utils.ErrorLog("SaveWechatComponentVerifyTicket failed: %s", err)
109
+		}
110
+
111
+	} else if requestBody.InfoType == "authorized" {
112
+		utils.InfoLog("authorized: %s", requestBody.AuthorizerAppid)
113
+
114
+	} else if requestBody.InfoType == "unauthorized" {
115
+		utils.InfoLog("unauthorized: %s", requestBody.AuthorizerAppid)
116
+
117
+		err = wechat_service.SaveAuthorizerStatusByAppID(requestBody.AuthorizerAppid, 2)
118
+		if err != nil {
119
+			utils.ErrorLog("SaveAuthorizerStatus failed: %s", err)
120
+		}
121
+
122
+	} else if requestBody.InfoType == "updateauthorized" || requestBody.InfoType == "authorized" {
123
+		utils.InfoLog("%s: %s", requestBody.AuthorizerAppid, requestBody.InfoType)
124
+	} else {
125
+		utils.ErrorLog("Unkown infotype")
126
+		c.Ctx.WriteString("success")
127
+		return
128
+	}
129
+
130
+	c.Ctx.WriteString("success")
131
+}
132
+
133
+//MpWechatNotice 授权后公众号消息与事件接收URL
134
+func (c *OpenWechatAPIController) MpWechatNotice() {
135
+	appid := c.Ctx.Input.Param(":appid")
136
+	if len(appid) == 0 {
137
+		utils.ErrorLog("appid not found")
138
+		c.Ctx.WriteString("success")
139
+		return
140
+	}
141
+
142
+	authorizer, err := wechat_service.GetAuthorizationByOnlyAppID(appid)
143
+	if err != nil {
144
+		utils.ErrorLog("Get MP Info error: %s", err)
145
+		c.Ctx.WriteString("success")
146
+		return
147
+	}
148
+	if authorizer == nil {
149
+		utils.ErrorLog("Get MP Info error: 信息不存在")
150
+		c.Ctx.WriteString("success")
151
+		return
152
+	}
153
+
154
+	orgID := authorizer.UserOrgId
155
+	timestamp := c.GetString("timestamp")
156
+	nonce := c.GetString("nonce")
157
+	// openid := c.GetString("openid")
158
+	// encryptType := c.GetString("encrypt_type")
159
+	msgSignature := c.GetString("msg_signature")
160
+	// signature := c.GetString("signature")
161
+
162
+	r := c.Ctx.Request
163
+
164
+	body, err := ioutil.ReadAll(r.Body)
165
+	if err != nil {
166
+		utils.ErrorLog("read body error: %s", err)
167
+		c.Ctx.WriteString("success")
168
+		return
169
+	}
170
+	encryptRequestBody := &wechat_service.EncryptRequestBody{}
171
+	err = xml.Unmarshal(body, encryptRequestBody)
172
+	if err != nil {
173
+		utils.ErrorLog("Unmarshal body error: %s", err)
174
+		c.Ctx.WriteString("success")
175
+		return
176
+	}
177
+
178
+	// Validate mstBody signature
179
+	if !wechat_service.ValidateMsg(timestamp, nonce, encryptRequestBody.Encrypt, msgSignature) {
180
+		fmt.Println("aa")
181
+		c.Ctx.WriteString("success")
182
+		return
183
+	}
184
+
185
+	// Decode base64
186
+	cipherData, err := base64.StdEncoding.DecodeString(encryptRequestBody.Encrypt)
187
+	if err != nil {
188
+		c.Ctx.WriteString("success")
189
+		return
190
+	}
191
+
192
+	// AES Decrypt
193
+	plainData, err := wechat_service.AesDecrypt(cipherData, wechat_service.AesKey)
194
+	if err != nil {
195
+		utils.ErrorLog("AesDecrypt error: %s", err)
196
+		c.Ctx.WriteString("success")
197
+		return
198
+	}
199
+
200
+	//封装struct
201
+	textRequestBody, err := wechat_service.ParseEncryptTextRequestBody(plainData)
202
+	if err != nil {
203
+		c.Ctx.WriteString("success")
204
+		return
205
+	}
206
+
207
+	fmt.Println(textRequestBody)
208
+	tp := textRequestBody.MsgType
209
+
210
+	FromUserName := textRequestBody.ToUserName
211
+	ToUserName := textRequestBody.FromUserName
212
+
213
+	if tp == "text" {
214
+		//当用户向微信公众号发送消息时,回复ta
215
+		wechat_service.SendMsgTypeTextMessage(appid, ToUserName, FromUserName, textRequestBody.Content, nonce, timestamp, c.Ctx, orgID)
216
+		return
217
+	}
218
+	if tp == "event" {
219
+		eventType := textRequestBody.Event
220
+		if eventType == "subscribe" {
221
+			//当用户关注微信公众号,回复ta
222
+			wechat_service.SendSubscribeTextMessage(appid, ToUserName, FromUserName, nonce, timestamp, c.Ctx, orgID)
223
+			return
224
+		}
225
+
226
+		if eventType == "CLICK" {
227
+			//当用户点击click类型的菜单,回复ta
228
+			wechat_service.SendClickButtonMessage(appid, ToUserName, FromUserName, textRequestBody.EventKey, nonce, timestamp, c.Ctx, orgID)
229
+			return
230
+		}
231
+
232
+		if eventType == "unsubscribe" {
233
+			org_service.SetFansUnsubscribe(orgID, ToUserName)
234
+		}
235
+
236
+		//某个类型的消息暂时后台不作处理,也需要向微信服务器做出响应
237
+		c.Ctx.WriteString("success")
238
+		return
239
+	}
240
+	c.Ctx.WriteString("success")
241
+}
242
+
243
+func (c *OpenWechatAPIController) Authorization() {
244
+
245
+	id, _ := c.GetInt64("id", 0)
246
+	if id <= 0 {
247
+		c.Ctx.WriteString("没有选择授权对象")
248
+		return
249
+	}
250
+	vtime, _ := c.GetInt64("vtime", 0)
251
+	if vtime <= 0 {
252
+		c.Ctx.WriteString("缺少vtime参数")
253
+		return
254
+	}
255
+	vcode := c.GetString("vcode")
256
+	if len(vcode) == 0 {
257
+		c.Ctx.WriteString("缺少vtime参数")
258
+		return
259
+	}
260
+	vtime, tcode := utils.GetOrgIdCode(id, vtime)
261
+	if tcode != vcode {
262
+		c.Ctx.WriteString("无效的vcode")
263
+		return
264
+	}
265
+
266
+	code, err := wechat_service.GetReqPreAuthCode()
267
+	fmt.Println("code是什么", code, "错误", err)
268
+	if err != nil {
269
+		c.ServeFailJsonSend(enums.ErrorCodeDataException, "获取授权URL失败:("+err.Error()+")")
270
+		return
271
+	}
272
+
273
+	uri := fmt.Sprintf(beego.AppConfig.String("httpdomain")+"/openwechat/mp/authorizerinfo/%d/%d/%s", id, vtime, vcode)
274
+	url := "https://mp.weixin.qq.com/safe/bindcomponent?action=bindcomponent&auth_type=1&no_scan=1&component_appid=" + beego.AppConfig.String("openwechatappid") + "&pre_auth_code=" + code + "&redirect_uri=" + uri + "&auth_type=1#wechat_redirect"
275
+	fmt.Println("url是设么东西", url)
276
+	c.Data["url"] = url
277
+	c.TplName = "openwechat/authorization.html"
278
+
279
+}
280
+
281
+//AuthorizerInfo 拉取公众号授权信息和基本信息
282
+func (c *OpenWechatAPIController) AuthorizerInfo() {
283
+	idS := c.Ctx.Input.Param(":id")
284
+	vtimeS := c.Ctx.Input.Param(":vtime")
285
+	vcode := c.Ctx.Input.Param(":vcode")
286
+	id, err := strconv.ParseInt(idS, 10, 64)
287
+	if err != nil {
288
+		c.Data["msg"] = err.Error()
289
+		c.TplName = "openwechat/errorauth.html"
290
+		return
291
+	}
292
+	vtime, err := strconv.ParseInt(vtimeS, 10, 64)
293
+	if err != nil {
294
+		c.Data["msg"] = err.Error()
295
+		c.TplName = "openwechat/errorauth.html"
296
+		return
297
+	}
298
+	vtime, tcode := utils.GetOrgIdCode(id, vtime)
299
+	if tcode != vcode {
300
+		c.Data["msg"] = "无效的vcode"
301
+		c.TplName = "openwechat/errorauth.html"
302
+		return
303
+	}
304
+
305
+	authorizationCode := c.GetString("auth_code")
306
+
307
+	redisClient := service.RedisClient()
308
+
309
+	componentAccessToken, err := redisClient.Get("sgj_patient:component_access_token").Result()
310
+	if err != nil {
311
+		c.Data["msg"] = "需要component_access_token才能验证信息"
312
+		c.TplName = "openwechat/errorauth.html"
313
+		return
314
+	}
315
+
316
+	body, err := wechat_service.ComponentAPIQueryAuth(authorizationCode, componentAccessToken)
317
+	if err != nil {
318
+		c.Data["msg"] = "获取公众号授权信息失败"
319
+		c.TplName = "openwechat/errorauth.html"
320
+		return
321
+	}
322
+
323
+	var ai wechat_service.AuthorizationInfo
324
+	err = json.Unmarshal([]byte(body), &ai)
325
+	if err != nil {
326
+		c.Data["msg"] = "解析公众号授权信息失败"
327
+		c.TplName = "openwechat/errorauth.html"
328
+		return
329
+	}
330
+
331
+	body, err = wechat_service.ComponentAPIGetAuthorizerInfo(ai.AuthorizationInfo.AuthorizerAppid, componentAccessToken)
332
+	if err != nil {
333
+		c.Data["msg"] = "获取公众号信息失败"
334
+		c.TplName = "openwechat/errorauth.html"
335
+		return
336
+	}
337
+
338
+	var aui wechat_service.AuthorizerInfo
339
+	err = json.Unmarshal([]byte(body), &aui)
340
+	if err != nil {
341
+		c.Data["msg"] = "解析公众号信息失败"
342
+		c.TplName = "openwechat/errorauth.html"
343
+		return
344
+	}
345
+
346
+	var funcInfoItem []string
347
+	for _, valjue := range ai.AuthorizationInfo.FuncInfo {
348
+		funcInfoItem = append(funcInfoItem, strconv.FormatInt(valjue.FuncscopeCategory.ID, 10))
349
+	}
350
+
351
+	BusinessInfo, err := json.MarshalIndent(aui.AuthorizerInfo.BusinessInfo, "", " ")
352
+	//用json,功能的开通状况(0代表未开通,1代表已开通): open_store:是否开通微信门店功能 open_scan:是否开通微信扫商品功能 open_pay:是否开通微信支付功能 open_card:是否开通微信卡券功能 open_shake:是否开通微信摇一摇功能
353
+	if err != nil {
354
+		c.Data["msg"] = "解析公众号功能的开通状况失败"
355
+		c.TplName = "openwechat/errorauth.html"
356
+		return
357
+	}
358
+
359
+	authorizationsInfo, err := wechat_service.GetAuthorizationByOrgID(id)
360
+	if err != nil {
361
+		c.Data["msg"] = "读取公众号信息失败"
362
+		c.TplName = "openwechat/errorauth.html"
363
+		return
364
+	}
365
+	var authorizations models.PatientAuthorizations
366
+	if authorizationsInfo == nil {
367
+		authorizations.UserOrgId = id
368
+		authorizations.CreatedTime = time.Now().Unix()
369
+	} else {
370
+		authorizations = *authorizationsInfo
371
+	}
372
+	authorizations.UpdatedTime = time.Now().Unix()
373
+	authorizations.AuthorizerAccessToken = ai.AuthorizationInfo.AuthorizerAccessToken
374
+	authorizations.AuthorizerRefreshToken = ai.AuthorizationInfo.AuthorizerRefreshToken
375
+	authorizations.AuthorizerFuncscopeCategory = strings.Join(funcInfoItem, ",")
376
+	authorizations.AuthorizerAppid = ai.AuthorizationInfo.AuthorizerAppid
377
+	authorizations.AuthorizerNickName = aui.AuthorizerInfo.NickName
378
+	authorizations.AuthorizerHeadImg = aui.AuthorizerInfo.HeadImg
379
+	authorizations.AuthorizerServiceTypeInfo = aui.AuthorizerInfo.ServiceTypeInfo.ID
380
+	authorizations.AuthorizerVerifyTypeInfo = aui.AuthorizerInfo.VerifyTypeInfo.ID
381
+	authorizations.AuthorizerUserName = aui.AuthorizerInfo.UserName
382
+	authorizations.AuthorizerPrincipalName = aui.AuthorizerInfo.PrincipalName
383
+	authorizations.AuthorizerBusinessInfo = string(BusinessInfo)
384
+	authorizations.AuthorizerQrcodeUrl = aui.AuthorizerInfo.QrcodeURL
385
+	authorizations.AuthorizerStatus = 1
386
+
387
+	err = wechat_service.SaveAuthorizationInfo(&authorizations)
388
+	if err != nil {
389
+		c.Data["msg"] = "保存公众号信息失败"
390
+		c.TplName = "openwechat/errorauth.html"
391
+		return
392
+	}
393
+
394
+	c.TplName = "openwechat/successauth.html"
395
+	return
396
+}

+ 37 - 0
controllers/global/qiniu_controller.go View File

@@ -0,0 +1,37 @@
1
+package global
2
+
3
+import (
4
+	base_ctl "SCRM/controllers"
5
+	"SCRM/enums"
6
+	base_service "SCRM/service"
7
+	"fmt"
8
+
9
+	"github.com/astaxie/beego"
10
+)
11
+
12
+type QiNiuApiController struct {
13
+	base_ctl.BaseAPIController
14
+}
15
+
16
+func QiniuCtlRegistRouters() {
17
+	beego.Router("/api/qiniu/uptoken", &QiNiuApiController{}, "get:GetQNUpToken")
18
+}
19
+
20
+func (c *QiNiuApiController) GetQNUpToken() {
21
+
22
+	redisClient := base_service.RedisClient()
23
+	defer redisClient.Close()
24
+
25
+	token, err := redisClient.Get("qn_token").Result()
26
+	fmt.Println("token是什么", token)
27
+	if err != nil {
28
+		defer fmt.Println(err)
29
+		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeGetQiniuUpToken)
30
+		return
31
+	}
32
+
33
+	c.ServeSuccessJSON(map[string]interface{}{
34
+		"uptoken": token,
35
+	})
36
+	return
37
+}

+ 9 - 0
controllers/global/router_collector.go View File

@@ -0,0 +1,9 @@
1
+package global
2
+
3
+func RegisterRouters() {
4
+	ErrorCtlRegistRouters()
5
+	DistrictCtlRegistRouters()
6
+	QiniuCtlRegistRouters()
7
+	OpenWechatCtlRegistRouters()
8
+	SMSCBAPICtlRegistRouters()
9
+}

+ 50 - 0
controllers/global/sms_controller.go View File

@@ -0,0 +1,50 @@
1
+package global
2
+
3
+import (
4
+	base_ctl "SCRM/controllers"
5
+	"SCRM/service/sms_service"
6
+	"encoding/json"
7
+	"strconv"
8
+
9
+	"github.com/astaxie/beego"
10
+)
11
+
12
+func SMSCBAPICtlRegistRouters() {
13
+	beego.Router("/sms/callback", &SMSTplCallBackAPIController{}, "post:CallBack")
14
+}
15
+
16
+type SMSTplCallBackAPIController struct {
17
+	base_ctl.BaseAPIController
18
+}
19
+
20
+// /sms/callback [post]
21
+func (this *SMSTplCallBackAPIController) CallBack() {
22
+	var callbackParams map[string]string
23
+	json.Unmarshal(this.Ctx.Input.RequestBody, &callbackParams)
24
+	this.TraceLog("短信平台回调: params: %v", callbackParams)
25
+
26
+	code := callbackParams["code"]
27
+	templateIDStr := callbackParams["templateid"]
28
+
29
+	if len(templateIDStr) != 0 {
30
+		templateID, _ := strconv.Atoi(templateIDStr)
31
+		if code == "2" {
32
+			err := sms_service.SMSUCPaasTemplateApproved(int64(templateID))
33
+			if err != nil {
34
+				this.ErrorLog("短信平台回调(成功)——数据库操作失败: err: %v; templateID: %v", err, templateID)
35
+			}
36
+		} else if code == "3" {
37
+			err := sms_service.SMSUCPaasTemplateUnapproved(int64(templateID))
38
+			if err != nil {
39
+				this.ErrorLog("短信平台回调(失败)——数据库操作失败: err: %v; templateID: %v", err, templateID)
40
+			}
41
+		}
42
+
43
+	} else {
44
+		this.TraceLog("短信平台回调: %+v", this.Ctx.Request)
45
+	}
46
+
47
+	this.ServeSuccessJSON(map[string]interface{}{
48
+		"result": true,
49
+	})
50
+}

+ 5 - 0
controllers/kefu/router_collector.go View File

@@ -0,0 +1,5 @@
1
+package kefu
2
+
3
+func RegisterRouters() {
4
+	TencentUsersigApiRegistRouters()
5
+}

+ 63 - 0
controllers/kefu/tencent_usersig_api_controller.go View File

@@ -0,0 +1,63 @@
1
+package kefu
2
+
3
+import (
4
+	base_ctl "SCRM/controllers"
5
+	"SCRM/enums"
6
+	"SCRM/service/tencentim_service"
7
+	"SCRM/utils"
8
+	"strconv"
9
+
10
+	"github.com/astaxie/beego"
11
+)
12
+
13
+type TencentUsersigApiController struct {
14
+	base_ctl.BaseAuthAPIController
15
+}
16
+
17
+func TencentUsersigApiRegistRouters() {
18
+	beego.Router("/api/tencent/usersig", &TencentUsersigApiController{}, "get:GetUsersig")
19
+
20
+}
21
+
22
+//GetUsersig 签名
23
+func (c *TencentUsersigApiController) GetUsersig() {
24
+
25
+	adminUserInfo := c.GetAdminUserInfo()
26
+
27
+	adminId := adminUserInfo.AdminUser.Id
28
+	Indentifier := "Org_" + strconv.FormatInt(adminUserInfo.CurrentOrgId, 10)
29
+	appIDAt3rd := Indentifier
30
+	sig, err := tencentim_service.CreateUserSig(Indentifier, appIDAt3rd)
31
+	if err != nil {
32
+		utils.ErrorLog("usersig err : %v", err)
33
+		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
34
+		return
35
+	}
36
+
37
+	orgInfo := adminUserInfo.Orgs[adminUserInfo.CurrentOrgId]
38
+	IdentifierNick := ""
39
+	HeadURL := "http://jk.kuyicloud.com/static/images/ico_gjh.png"
40
+	if orgInfo != nil {
41
+		if len(orgInfo.OrgName) > 0 {
42
+			IdentifierNick = orgInfo.OrgName
43
+		}
44
+		if len(orgInfo.OrgLogo) > 0 {
45
+			HeadURL = orgInfo.OrgLogo
46
+		}
47
+	}
48
+
49
+	returnData := map[string]interface{}{
50
+		"sig":            sig,
51
+		"adminId":        adminId,
52
+		"Indentifier":    Indentifier,
53
+		"appIDAt3rd":     appIDAt3rd,
54
+		"IdentifierNick": IdentifierNick,
55
+		"HeadURL":        HeadURL,
56
+		"sdkAppID":       tencentim_service.ThisSDKAppId,
57
+		"accountType":    tencentim_service.ThisAccType,
58
+		"selToAdmin":     "AdminKeFu",
59
+	}
60
+
61
+	c.ServeSuccessJSON(returnData)
62
+	return
63
+}

+ 154 - 0
controllers/login/login_controller.go View File

@@ -0,0 +1,154 @@
1
+package login
2
+
3
+import (
4
+	base_ctl "SCRM/controllers"
5
+	"SCRM/enums"
6
+	"SCRM/service/admin_service"
7
+	"SCRM/service/org_service"
8
+	"SCRM/utils"
9
+	"fmt"
10
+	"net/url"
11
+
12
+	"github.com/astaxie/beego"
13
+)
14
+
15
+func LoginCtlRegistRouters() {
16
+	beego.Router("/login", &LoginViewController{}, "get:Login")
17
+	beego.Router("/logout", &LoginViewController{}, "get,post:Logout")
18
+	beego.Router("/api/token/verify", &VerifyUserLoginAPIController{}, "post:VerifyToken")
19
+}
20
+
21
+type LoginViewController struct {
22
+	base_ctl.BaseViewController
23
+}
24
+
25
+// /login [get]
26
+// @param token?:string
27
+// @param relogin?:bool
28
+func (this *LoginViewController) Login() {
29
+	token := this.Ctx.Input.Query("token")
30
+	if len(token) > 0 { // 带 token 参数的一般是从 SSO 回调回来的
31
+		utils.TraceLog("SSO Login 回调: token=%v", token)
32
+		xtFrontEndDomain := beego.AppConfig.String("front_end_domain") + "?lt=" + token
33
+		this.Redirect302(xtFrontEndDomain)
34
+
35
+	} else {
36
+		relogin, _ := this.GetBool("relogin", false)
37
+		returnURL := url.QueryEscape(fmt.Sprintf("%v%v", beego.AppConfig.String("httpdomain"), this.Ctx.Request.RequestURI))
38
+		ssoDomain := beego.AppConfig.String("sso_domain")
39
+		ssoLoginURL := fmt.Sprintf("%v/login?returnurl=%v&app_type=1&relogin=%v", ssoDomain, returnURL, relogin)
40
+		this.Redirect302(ssoLoginURL)
41
+	}
42
+}
43
+
44
+// /logout [get/post]
45
+func (this *LoginViewController) Logout() {
46
+	if this.Ctx.Request.Method == "GET" {
47
+		this.DelSession("admin_user_info")
48
+		this.Redirect302(fmt.Sprintf("%v/logout", beego.AppConfig.String("sso_domain")))
49
+	} else if this.Ctx.Request.Method == "POST" {
50
+		this.DelSession("admin_user_info")
51
+	}
52
+}
53
+
54
+type VerifyUserLoginAPIController struct {
55
+	base_ctl.BaseAPIController
56
+}
57
+
58
+// /api/token/verify [post]
59
+// @param token:string
60
+func (this *VerifyUserLoginAPIController) VerifyToken() {
61
+	if this.Ctx.Request.Method == "OPTIONS" {
62
+		this.Abort("200")
63
+
64
+	} else {
65
+		token := this.GetString("token")
66
+		utils.TraceLog("token: %v", token)
67
+		if len(token) == 0 {
68
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
69
+			return
70
+		}
71
+
72
+		ip := utils.GetIP(this.Ctx.Request)
73
+		sessionID := this.Ctx.GetCookie("s")
74
+		utils.TraceLog("cookie session id: %v %v", ip, sessionID)
75
+		adminUserInfo, err, errCode := admin_service.VerifyToken(token, ip, sessionID)
76
+		if err != nil {
77
+			if errCode == 903 { // 未创建应用
78
+				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNeverCreateTypeApp)
79
+
80
+			} else if errCode == 904 { // 联系超管来开通
81
+				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeContactSuperAdminCreateTypeApp)
82
+
83
+			} else {
84
+				utils.ErrorLog("令牌验证失败:%v", err)
85
+				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeInvalidToken)
86
+			}
87
+			return
88
+
89
+		} else {
90
+			this.SetSession("admin_user_info", adminUserInfo)
91
+
92
+			adminUser := adminUserInfo.AdminUser
93
+			appRole := adminUserInfo.AppRoles[adminUserInfo.CurrentAppId]
94
+			userInfo := map[string]interface{}{
95
+				"id":         adminUser.Id,
96
+				"mobile":     adminUser.Mobile,
97
+				"user_name":  appRole.UserName,
98
+				"avatar":     appRole.Avatar,
99
+				"intro":      appRole.Intro,
100
+				"user_type":  appRole.UserType,
101
+				"user_title": appRole.UserTitle,
102
+			}
103
+			curOrg := adminUserInfo.Orgs[adminUserInfo.CurrentOrgId]
104
+			org := map[string]interface{}{
105
+				"id":             curOrg.Id,
106
+				"org_name":       curOrg.OrgName,
107
+				"org_short_name": curOrg.OrgShortName,
108
+				"org_intro":      curOrg.OrgIntroduction,
109
+				"org_logo":       curOrg.OrgLogo,
110
+				"province":       curOrg.Province,
111
+				"city":           curOrg.City,
112
+				"district":       curOrg.District,
113
+				"address":        curOrg.Address,
114
+			}
115
+			curAppUrlfors := adminUserInfo.AppUrlfors[adminUserInfo.CurrentAppId]
116
+
117
+			subscibe := adminUserInfo.Subscibes[adminUserInfo.CurrentOrgId]
118
+			if err := org_service.GetOrgSubscibeState(subscibe); err != nil {
119
+				this.ErrorLog("没有机构订阅信息,数据有误")
120
+				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
121
+				return
122
+			}
123
+
124
+			orgApps := adminUserInfo.OrgApps[curOrg.Id]
125
+			didRegistedForXT := false
126
+			didRegistedForMall := false
127
+			didRegistedForCDM := false
128
+			for _, app := range orgApps {
129
+				if app.AppType == 3 && app.OpenStatus == 1 {
130
+					didRegistedForXT = true
131
+				}
132
+				if app.AppType == 4 && app.OpenStatus == 1 {
133
+					didRegistedForCDM = true
134
+				}
135
+				if app.AppType == 5 && app.OpenStatus == 1 {
136
+					didRegistedForMall = true
137
+				}
138
+			}
139
+
140
+			this.ServeSuccessJSON(map[string]interface{}{
141
+				"user":            userInfo,
142
+				"org":             org,
143
+				"urlfors":         curAppUrlfors,
144
+				"current_org_id":  adminUserInfo.CurrentOrgId,
145
+				"current_app_id":  adminUserInfo.CurrentAppId,
146
+				"subscibe":        subscibe,
147
+				"xt_role_exist":   didRegistedForXT,
148
+				"cdm_role_exist":  didRegistedForCDM,
149
+				"mall_role_exist": didRegistedForMall,
150
+			})
151
+			return
152
+		}
153
+	}
154
+}

+ 5 - 0
controllers/login/router_collector.go View File

@@ -0,0 +1,5 @@
1
+package login
2
+
3
+func RegisterRouters() {
4
+	LoginCtlRegistRouters()
5
+}

+ 519 - 0
controllers/marketing_tool/activity_controller.go View File

@@ -0,0 +1,519 @@
1
+package marketing_tool
2
+
3
+import (
4
+	"SCRM/controllers"
5
+	"SCRM/enums"
6
+	"SCRM/models"
7
+	"SCRM/service/marketing_tool_service"
8
+	"SCRM/utils"
9
+	"encoding/json"
10
+	"time"
11
+
12
+	"github.com/astaxie/beego"
13
+)
14
+
15
+func ActivityCtlRegistRouters() {
16
+	beego.Router("/api/activities", &ActivityAPIController{}, "get:Activities")
17
+	beego.Router("/api/activity", &ActivityAPIController{}, "get:GetActivity")
18
+	beego.Router("/api/activity/submit", &ActivityAPIController{}, "post:ActivitySubmit")
19
+	beego.Router("/api/activity/detailview", &ActivityAPIController{}, "get:GetActivityDetailView")
20
+	beego.Router("/api/activity/signups", &ActivityAPIController{}, "get:SignupUsers")
21
+	beego.Router("/api/activity/delete", &ActivityAPIController{}, "post:DeleteActivity")
22
+	beego.Router("/api/activity/publish", &ActivityAPIController{}, "post:PublishActivity")
23
+	beego.Router("/api/activity/shareinfo", &ActivityAPIController{}, "get:GetActivityShareInfo")
24
+}
25
+
26
+type ActivityAPIController struct {
27
+	controllers.BaseAuthAPIController
28
+}
29
+
30
+// /api/activities [get]
31
+// @param page?:int
32
+// @param keyword?:string
33
+// @param status?:int 1.已发布 2.待发布 3.未通过 4.已结束 其他取全部
34
+func (this *ActivityAPIController) Activities() {
35
+	page, _ := this.GetInt("page")
36
+	keyword := this.GetString("keyword")
37
+	status, _ := this.GetInt("status")
38
+	if page <= 0 {
39
+		page = 1
40
+	}
41
+	if status < 1 || status > 4 {
42
+		status = 0
43
+	}
44
+
45
+	adminUserInfo := this.GetAdminUserInfo()
46
+	var activities []*models.Activity
47
+	var totalCount int64
48
+	var getActivityErr error
49
+	if status == 1 {
50
+		activities, totalCount, getActivityErr = marketing_tool_service.GetActivitiesWithStatus(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, keyword, 1, page, 10)
51
+	} else if status == 2 {
52
+		activities, totalCount, getActivityErr = marketing_tool_service.GetActivitiesWithStatus(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, keyword, 4, page, 10)
53
+	} else if status == 3 {
54
+		activities, totalCount, getActivityErr = marketing_tool_service.GetActivitiesWithStatus(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, keyword, 3, page, 10)
55
+	} else if status == 4 {
56
+		activities, totalCount, getActivityErr = marketing_tool_service.GetDidEndedActivities(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, keyword, page, 10)
57
+	} else {
58
+		activities, totalCount, getActivityErr = marketing_tool_service.GetValidActivities(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, keyword, page, 10)
59
+	}
60
+
61
+	if getActivityErr != nil {
62
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
63
+		return
64
+	}
65
+
66
+	activityJSONList := make([]map[string]interface{}, 0, len(activities))
67
+	for _, activity := range activities {
68
+		var json map[string]interface{}
69
+		// 活动状态 1:已发布 2:待审核 3:未通过 4:草稿 9:已删除
70
+		if activity.Status == 1 { // 已发布/已结束
71
+			json = this._convertToPublishedActivityViewJSON(activity)
72
+		} else if activity.Status == 3 { // 未通过
73
+			json = this._convertToUnapprovedActivityViewJSON(activity)
74
+		} else if activity.Status == 4 { // 草稿
75
+			json = this._convertToActivityDraftsViewJSON(activity)
76
+		}
77
+		activityJSONList = append(activityJSONList, json)
78
+	}
79
+
80
+	this.ServeSuccessJSON(map[string]interface{}{
81
+		"activities": activityJSONList,
82
+		"total":      totalCount,
83
+	})
84
+}
85
+
86
+func (this *ActivityAPIController) _convertToPublishedActivityViewJSON(activity *models.Activity) map[string]interface{} {
87
+	json := make(map[string]interface{})
88
+	now := time.Now().Unix()
89
+	if activity.StartTime < now {
90
+		json["status"] = 4
91
+	} else {
92
+		json["status"] = 1
93
+	}
94
+	json["id"] = activity.Id
95
+	json["poster_photo"] = activity.PosterPhoto
96
+	json["title"] = activity.Title
97
+	json["is_recommend"] = activity.IsRecommend
98
+	json["read_num"] = activity.ReadNum
99
+	json["comment_num"] = activity.CommentNum
100
+	json["star_num"] = activity.StarNum
101
+	json["join_num"] = activity.JoinNum
102
+	json["limit_num"] = activity.LimitNum
103
+	json["start_time"] = activity.StartTime
104
+	return json
105
+}
106
+
107
+func (this *ActivityAPIController) _convertToActivityDraftsViewJSON(activity *models.Activity) map[string]interface{} {
108
+	json := make(map[string]interface{})
109
+	json["status"] = 2
110
+	json["id"] = activity.Id
111
+	json["poster_photo"] = activity.PosterPhoto
112
+	json["title"] = activity.Title
113
+	return json
114
+}
115
+
116
+func (this *ActivityAPIController) _convertToUnapprovedActivityViewJSON(activity *models.Activity) map[string]interface{} {
117
+	json := make(map[string]interface{})
118
+	json["status"] = 3
119
+	json["id"] = activity.Id
120
+	json["poster_photo"] = activity.PosterPhoto
121
+	json["title"] = activity.Title
122
+	json["reason"] = activity.Reason
123
+	json["start_time"] = activity.StartTime
124
+	return json
125
+}
126
+
127
+// /api/activity [get]
128
+// @param id:int
129
+func (this *ActivityAPIController) GetActivity() {
130
+	activityID, _ := this.GetInt64("id")
131
+	if activityID <= 0 {
132
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
133
+		return
134
+	}
135
+
136
+	adminUserInfo := this.GetAdminUserInfo()
137
+	activity, getActivityErr := marketing_tool_service.GetActivityWithID(adminUserInfo.CurrentOrgId, activityID)
138
+	if getActivityErr != nil {
139
+		this.ErrorLog("获取活动失败:%v", getActivityErr)
140
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
141
+		return
142
+	} else if activity == nil {
143
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeActivityNotExist)
144
+		return
145
+	}
146
+
147
+	paragraph, getParagraphErr := marketing_tool_service.GetActivityParagraphByActivityID(activity.Id)
148
+	if getParagraphErr != nil {
149
+		this.ErrorLog("获取活动段落失败:%v", getParagraphErr)
150
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
151
+		return
152
+	}
153
+
154
+	paragraphTitle := ""
155
+	paragraphContent := ""
156
+	if paragraph != nil {
157
+		paragraphTitle = paragraph.Title
158
+		paragraphContent = paragraph.Text
159
+	}
160
+
161
+	currentOrg := adminUserInfo.Orgs[adminUserInfo.CurrentOrgId]
162
+	this.ServeSuccessJSON(map[string]interface{}{
163
+		"activity": activity,
164
+		"paragraph": map[string]interface{}{
165
+			"title":   paragraphTitle,
166
+			"content": paragraphContent,
167
+		},
168
+		"org": map[string]interface{}{
169
+			"logo": currentOrg.OrgLogo,
170
+			"name": currentOrg.OrgName,
171
+		},
172
+	})
173
+}
174
+
175
+// /api/activity/submit [post]
176
+// @param publish:bool 是否发布
177
+// @data 如下格式
178
+/*
179
+{
180
+	id?:int
181
+	title:string
182
+	subtitle:string
183
+	poster_photo:string
184
+	address:string
185
+	limit_num?:int
186
+	sign_up_deadline:string ("yyyy-MM-dd HH:mm")
187
+	start_time:string ("yyyy-MM-dd HH:mm")
188
+	phone_number?:string
189
+	sign_up_notice?:string
190
+
191
+	paragraph: {
192
+		title:string
193
+		content:string
194
+	}
195
+}
196
+*/
197
+func (this *ActivityAPIController) ActivitySubmit() {
198
+	publish, _ := this.GetBool("publish")
199
+
200
+	var activityForm ActivityForm
201
+	parseErr := json.Unmarshal(this.Ctx.Input.RequestBody, &activityForm)
202
+	if parseErr != nil {
203
+		this.ErrorLog("解析 activity form 失败:%v", parseErr)
204
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamFormatWrong)
205
+		return
206
+	}
207
+
208
+	adminUserInfo := this.GetAdminUserInfo()
209
+	var activity *models.Activity
210
+	if activityForm.ID > 0 {
211
+		var getActivityErr error
212
+		activity, getActivityErr = marketing_tool_service.GetActivityWithID(adminUserInfo.CurrentOrgId, activityForm.ID)
213
+		if getActivityErr != nil {
214
+			this.ErrorLog("获取活动失败:%v", getActivityErr)
215
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
216
+			return
217
+		} else if activity == nil || activity.Status == 9 {
218
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeActivityNotExist)
219
+			return
220
+		} else if activity.Status == 1 {
221
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeActivityPublishedCannotModify)
222
+			return
223
+		}
224
+	}
225
+
226
+	if len(activityForm.Title) == 0 || len(activityForm.Subtitle) == 0 || len(activityForm.PosterPhoto) == 0 || len(activityForm.Address) == 0 || len(activityForm.SignUpDeadline) == 0 || len(activityForm.StartTime) == 0 {
227
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
228
+		return
229
+	}
230
+	timeFmt := "2006-01-02 15:04"
231
+	signUpDeadlineTime, parseSUDErr := utils.ParseTimeStringToTime(timeFmt, activityForm.SignUpDeadline)
232
+	if parseSUDErr != nil {
233
+		this.ErrorLog("解析报名截止时间失败:%v", parseSUDErr)
234
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamFormatWrong)
235
+		return
236
+	}
237
+	activityTime, parseActivityTimeErr := utils.ParseTimeStringToTime(timeFmt, activityForm.StartTime)
238
+	if parseActivityTimeErr != nil {
239
+		this.ErrorLog("解析活动开始时间失败:%v", parseActivityTimeErr)
240
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamFormatWrong)
241
+		return
242
+	}
243
+
244
+	if len(activityForm.PhoneNumber) > 0 {
245
+		if utils.PhoneRegexp().MatchString(activityForm.PhoneNumber) == false {
246
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamFormatWrong)
247
+			return
248
+		}
249
+	}
250
+	if activityForm.LimitNum < 0 {
251
+		activityForm.LimitNum = 0
252
+	}
253
+
254
+	if activity == nil {
255
+		activity = &models.Activity{
256
+			UserOrgId:        adminUserInfo.CurrentOrgId,
257
+			UserAppId:        adminUserInfo.CurrentAppId,
258
+			Title:            activityForm.Title,
259
+			Subtitle:         activityForm.Subtitle,
260
+			Address:          activityForm.Address,
261
+			SignUpDeadline:   signUpDeadlineTime.Unix(),
262
+			SignUpNotice:     activityForm.SignUpNotice,
263
+			StartTime:        activityTime.Unix(),
264
+			PosterPhoto:      activityForm.PosterPhoto,
265
+			PosterPhotoThumb: activityForm.PosterPhoto,
266
+			LimitNum:         activityForm.LimitNum,
267
+			PhoneNumber:      activityForm.PhoneNumber,
268
+			CreateTime:       time.Now().Unix(),
269
+		}
270
+	} else {
271
+		activity.Title = activityForm.Title
272
+		activity.Subtitle = activityForm.Subtitle
273
+		activity.Address = activityForm.Address
274
+		activity.SignUpDeadline = signUpDeadlineTime.Unix()
275
+		activity.SignUpNotice = activityForm.SignUpNotice
276
+		activity.StartTime = activityTime.Unix()
277
+		activity.PosterPhoto = activityForm.PosterPhoto
278
+		activity.PosterPhotoThumb = activityForm.PosterPhoto
279
+		activity.LimitNum = activityForm.LimitNum
280
+		activity.PhoneNumber = activityForm.PhoneNumber
281
+	}
282
+	activity.ModifyTime = time.Now().Unix()
283
+	if publish {
284
+		activity.Status = 1
285
+	} else {
286
+		activity.Status = 4
287
+	}
288
+
289
+	var paragraph *models.ActivityParagraph
290
+	if activity.Id > 0 {
291
+		var getPErr error
292
+		paragraph, getPErr = marketing_tool_service.GetActivityParagraphByActivityID(activity.Id)
293
+		if getPErr != nil {
294
+			this.ErrorLog("获取活动段落失败:%v", getPErr)
295
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
296
+			return
297
+		}
298
+	}
299
+	if len(activityForm.Paragraph.Title) > 0 {
300
+		if paragraph == nil {
301
+			paragraph = &models.ActivityParagraph{
302
+				Title:      activityForm.Paragraph.Title,
303
+				Text:       activityForm.Paragraph.Content,
304
+				Status:     1,
305
+				CreateTime: time.Now().Unix(),
306
+				ModifyTime: time.Now().Unix(),
307
+			}
308
+		} else {
309
+			paragraph.Title = activityForm.Paragraph.Title
310
+			paragraph.Text = activityForm.Paragraph.Content
311
+			paragraph.ModifyTime = time.Now().Unix()
312
+		}
313
+	} else {
314
+		if paragraph != nil {
315
+			paragraph.Status = 0
316
+			paragraph.ModifyTime = time.Now().Unix()
317
+		}
318
+	}
319
+
320
+	saveErr := marketing_tool_service.SaveActivityAndParagraph(activity, paragraph)
321
+	if saveErr != nil {
322
+		this.ErrorLog("保存活动失败:%v", saveErr)
323
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
324
+		return
325
+	}
326
+
327
+	wxShareModel, getWxShareErr := marketing_tool_service.GetActivityWxShareByActivityID(activity.Id)
328
+	if getWxShareErr != nil {
329
+		this.ErrorLog("获取活动微信分享信息失败:%v", getWxShareErr)
330
+	} else if wxShareModel != nil {
331
+		wxShareModel.ModifyTime = time.Now().Unix()
332
+		wxShareModel.Status = 1
333
+		wxShareModel.Title = activity.Title
334
+		wxShareModel.Subtitle = activity.Subtitle
335
+		wxShareModel.Image = activity.PosterPhoto
336
+		saveWxShareErr := marketing_tool_service.SaveActivityWxShare(wxShareModel)
337
+		if saveWxShareErr != nil {
338
+			this.ErrorLog("更新活动微信分享信息失败:%v", saveWxShareErr)
339
+		}
340
+	}
341
+
342
+	this.ServeSuccessJSON(map[string]interface{}{
343
+		"activity_id": activity.Id,
344
+	})
345
+}
346
+
347
+// /api/activity/detailview [get]
348
+// @param id:int
349
+func (this *ActivityAPIController) GetActivityDetailView() {
350
+	activityID, _ := this.GetInt64("id")
351
+	if activityID <= 0 {
352
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
353
+		return
354
+	}
355
+
356
+	adminUserInfo := this.GetAdminUserInfo()
357
+	activity, getActivityErr := marketing_tool_service.GetActivityWithID(adminUserInfo.CurrentOrgId, activityID)
358
+	if getActivityErr != nil {
359
+		this.ErrorLog("获取活动失败:%v", getActivityErr)
360
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
361
+		return
362
+	} else if activity == nil {
363
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeActivityNotExist)
364
+		return
365
+	}
366
+	if activity.Status != 1 && activity.Status != 4 {
367
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeActivityNotExist)
368
+		return
369
+	}
370
+
371
+	signupUsers, _, getUsersErr := marketing_tool_service.GetValidActivitySignupUsers(activityID, "", 1)
372
+	if getUsersErr != nil {
373
+		this.ErrorLog("获取活动报名客户失败:%v", getUsersErr)
374
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
375
+		return
376
+	}
377
+
378
+	this.ServeSuccessJSON(map[string]interface{}{
379
+		"activity": activity,
380
+		"users":    signupUsers,
381
+	})
382
+}
383
+
384
+// /api/activity/signups [get]
385
+// @param id:int
386
+// @param keyword?:string
387
+// @param page?:int
388
+func (this *ActivityAPIController) SignupUsers() {
389
+	activityID, _ := this.GetInt64("id")
390
+	if activityID <= 0 {
391
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
392
+		return
393
+	}
394
+	page, _ := this.GetInt("page")
395
+	if page <= 0 {
396
+		page = 1
397
+	}
398
+	keyword := this.GetString("keyword")
399
+
400
+	adminUserInfo := this.GetAdminUserInfo()
401
+	activity, getActivityErr := marketing_tool_service.GetActivityWithID(adminUserInfo.CurrentOrgId, activityID)
402
+	if getActivityErr != nil {
403
+		this.ErrorLog("获取活动失败:%v", getActivityErr)
404
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
405
+		return
406
+	} else if activity == nil {
407
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeActivityNotExist)
408
+		return
409
+	}
410
+
411
+	signupUsers, total, getUsersErr := marketing_tool_service.GetValidActivitySignupUsers(activityID, keyword, page)
412
+	if getUsersErr != nil {
413
+		this.ErrorLog("获取活动报名客户失败:%v", getUsersErr)
414
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
415
+		return
416
+	}
417
+	this.ServeSuccessJSON(map[string]interface{}{
418
+		"users": signupUsers,
419
+		"total": total,
420
+	})
421
+}
422
+
423
+// /api/activity/delete [post]
424
+// @param id:int
425
+func (this *ActivityAPIController) DeleteActivity() {
426
+	activityID, _ := this.GetInt64("id")
427
+	if activityID <= 0 {
428
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
429
+		return
430
+	}
431
+
432
+	adminUserInfo := this.GetAdminUserInfo()
433
+	activity, getActivityErr := marketing_tool_service.GetActivityWithID(adminUserInfo.CurrentOrgId, activityID)
434
+	if getActivityErr != nil {
435
+		this.ErrorLog("获取活动失败:%v", getActivityErr)
436
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
437
+		return
438
+	} else if activity == nil || activity.Status == 9 {
439
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeActivityNotExist)
440
+		return
441
+	}
442
+
443
+	deleteErr := marketing_tool_service.DeleteActivity(adminUserInfo.CurrentOrgId, activityID)
444
+	if deleteErr != nil {
445
+		this.ErrorLog("删除活动失败:%v", deleteErr)
446
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
447
+		return
448
+	}
449
+
450
+	this.ServeSuccessJSON(nil)
451
+}
452
+
453
+// /api/activity/publish [post]
454
+// @param id:int
455
+func (this *ActivityAPIController) PublishActivity() {
456
+	activityID, _ := this.GetInt64("id")
457
+	if activityID <= 0 {
458
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
459
+		return
460
+	}
461
+
462
+	adminUserInfo := this.GetAdminUserInfo()
463
+	activity, getActivityErr := marketing_tool_service.GetActivityWithID(adminUserInfo.CurrentOrgId, activityID)
464
+	if getActivityErr != nil {
465
+		this.ErrorLog("获取活动失败:%v", getActivityErr)
466
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
467
+		return
468
+	} else if activity == nil || activity.Status == 9 {
469
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeActivityNotExist)
470
+		return
471
+	}
472
+
473
+	if activity.Status == 1 {
474
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeActivityPublishRepeat)
475
+		return
476
+	}
477
+
478
+	activity.Status = 1
479
+	activity.ModifyTime = time.Now().Unix()
480
+	updateErr := marketing_tool_service.SaveActivityAndParagraph(activity, nil)
481
+	if updateErr != nil {
482
+		this.ErrorLog("发布活动失败:%v", updateErr)
483
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
484
+		return
485
+	}
486
+	this.ServeSuccessJSON(nil)
487
+}
488
+
489
+// /api/activity/shareinfo [get]
490
+// @param id:int
491
+func (this *ActivityAPIController) GetActivityShareInfo() {
492
+	activityID, _ := this.GetInt64("id")
493
+	if activityID <= 0 {
494
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
495
+		return
496
+	}
497
+
498
+	adminUserInfo := this.GetAdminUserInfo()
499
+	activity, getActivityErr := marketing_tool_service.GetActivityWithID(adminUserInfo.CurrentOrgId, activityID)
500
+	if getActivityErr != nil {
501
+		this.ErrorLog("获取活动失败:%v", getActivityErr)
502
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
503
+		return
504
+	} else if activity == nil {
505
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeActivityNotExist)
506
+		return
507
+	}
508
+
509
+	wxShareModel, getWxShareErr := marketing_tool_service.GetActivityWxShareByActivityID(activity.Id)
510
+	if getWxShareErr != nil || wxShareModel == nil {
511
+		this.ErrorLog("获取活动微信分享信息失败:%v", getWxShareErr)
512
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
513
+		return
514
+	}
515
+
516
+	this.ServeSuccessJSON(map[string]interface{}{
517
+		"url": wxShareModel.ShortURL,
518
+	})
519
+}

+ 19 - 0
controllers/marketing_tool/activity_vms.go View File

@@ -0,0 +1,19 @@
1
+package marketing_tool
2
+
3
+type ActivityForm struct {
4
+	ID             int64  `json:"id"`
5
+	Title          string `json:"title"`
6
+	Subtitle       string `json:"subtitle"`
7
+	PosterPhoto    string `json:"poster_photo"`
8
+	Address        string `json:"address"`
9
+	LimitNum       int    `json:"limit_num"`
10
+	SignUpDeadline string `json:"sign_up_deadline"`
11
+	StartTime      string `json:"start_time"`
12
+	PhoneNumber    string `json:"phone_number"`
13
+	SignUpNotice   string `json:"sign_up_notice"`
14
+
15
+	Paragraph struct {
16
+		Title   string `json:"title"`
17
+		Content string `json:"content"`
18
+	} `json:"paragraph"`
19
+}

+ 5 - 0
controllers/marketing_tool/router_collector.go View File

@@ -0,0 +1,5 @@
1
+package marketing_tool
2
+
3
+func RegisterRouters() {
4
+	ActivityCtlRegistRouters()
5
+}

+ 496 - 0
controllers/members/card_controller.go View File

@@ -0,0 +1,496 @@
1
+package members
2
+
3
+import (
4
+	base_ctl "SCRM/controllers"
5
+	"SCRM/enums"
6
+	"SCRM/models"
7
+	"SCRM/service/member_service"
8
+	"SCRM/utils"
9
+	"encoding/json"
10
+	"fmt"
11
+	"reflect"
12
+	"time"
13
+
14
+	"github.com/astaxie/beego"
15
+	"github.com/bwmarrin/snowflake"
16
+)
17
+
18
+func CardCtlRegistRouters() {
19
+	beego.Router("/api/member/card/edit", &CardAPIController{}, "Put:EditMemberCard")
20
+	beego.Router("/api/membercards", &CardAPIController{}, "Get:GetCards")
21
+	beego.Router("/api/membercard/create", &CardAPIController{}, "Post:CreateCard")
22
+	beego.Router("/api/membercard/edit", &CardAPIController{}, "Put:EditCard")
23
+	beego.Router("/api/membercard/right/edit", &CardAPIController{}, "Put:EditRight")
24
+	beego.Router("/api/membercards/delete", &CardAPIController{}, "Delete:DeleteCard")
25
+}
26
+
27
+type CardAPIController struct {
28
+	base_ctl.BaseAuthAPIController
29
+}
30
+
31
+func (c *CardAPIController) EditMemberCard() {
32
+	id, _ := c.GetInt64("id", 0)
33
+	if id <= 0 {
34
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误:id")
35
+		return
36
+	}
37
+	cardID, _ := c.GetInt64("card_id", 0)
38
+	if cardID <= 0 { //设置为无卡
39
+		cardID = 0
40
+	}
41
+	adminUserInfo := c.GetAdminUserInfo()
42
+	timeNow := time.Now().Unix()
43
+	member, err := member_service.GetOnlyMemberByID(adminUserInfo.CurrentOrgId, id)
44
+	if err != nil {
45
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "设置会员卡失败:("+err.Error()+")")
46
+		return
47
+	}
48
+	if member == nil {
49
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "设置会员卡失败:(会员记录不存在)")
50
+		return
51
+	}
52
+
53
+	returnData := make(map[string]interface{}, 0)
54
+	if cardID == 0 {
55
+		err = member_service.DeleteUserCard(adminUserInfo.CurrentOrgId, id)
56
+		if err != nil {
57
+			c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "设置会员卡失败:("+err.Error()+")")
58
+			return
59
+		}
60
+		returnData["user_card"] = nil
61
+	} else {
62
+
63
+		card, err := member_service.GetCardByID(adminUserInfo.CurrentOrgId, cardID)
64
+		if err != nil {
65
+			c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "设置会员卡失败:("+err.Error()+")")
66
+			return
67
+		}
68
+		if card == nil {
69
+			c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "设置会员卡失败:(会员卡不存在)")
70
+			return
71
+		}
72
+
73
+		oldUserCard, err := member_service.GetUserCardByID(adminUserInfo.CurrentOrgId, id)
74
+		if err != nil {
75
+			c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "设置会员卡失败:("+err.Error()+")")
76
+			return
77
+		}
78
+		var userCard models.UserCard
79
+		if oldUserCard != nil {
80
+			userCard = *oldUserCard
81
+		} else {
82
+			node, err := snowflake.NewNode(1)
83
+			if err != nil {
84
+				c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "设置会员卡失败:(生成卡号时出错)")
85
+				return
86
+			}
87
+			cardNo := node.Generate()
88
+
89
+			userCard.CustomerId = id
90
+			userCard.UserOrgId = adminUserInfo.CurrentOrgId
91
+			userCard.CreatedTime = timeNow
92
+			userCard.CardNo = fmt.Sprintf("%s", cardNo)
93
+		}
94
+
95
+		userCard.CardId = card.ID
96
+		userCard.CardName = card.CardName
97
+		userCard.UpdatedTime = timeNow
98
+		userCard.Status = 1
99
+		err = member_service.SaveUserCard(&userCard, member)
100
+		if err != nil {
101
+			c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "设置会员卡失败:("+err.Error()+")")
102
+			return
103
+		}
104
+		returnData["user_card"] = userCard
105
+		returnData["member"] = member
106
+	}
107
+
108
+	c.ServeSuccessJSON(returnData)
109
+	return
110
+}
111
+
112
+func (c *CardAPIController) GetCards() {
113
+
114
+	adminUserInfo := c.GetAdminUserInfo()
115
+	cards, _ := member_service.GetCardList(adminUserInfo.CurrentOrgId)
116
+
117
+	right, _ := member_service.GetMembershipRights(adminUserInfo.CurrentOrgId)
118
+	if right != nil && right.Status != 1 {
119
+		right = nil
120
+	}
121
+
122
+	returnData := make(map[string]interface{}, 0)
123
+	returnData["cards"] = cards
124
+	returnData["right"] = right
125
+	c.ServeSuccessJSON(returnData)
126
+	return
127
+}
128
+
129
+func (c *CardAPIController) CreateCard() {
130
+
131
+	adminUserInfo := c.GetAdminUserInfo()
132
+	timeNow := time.Now().Unix()
133
+
134
+	dataBody := make(map[string]interface{}, 0)
135
+	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
136
+	if err != nil {
137
+		utils.ErrorLog(err.Error())
138
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误")
139
+		return
140
+	}
141
+
142
+	var card models.UserMembershipCard
143
+
144
+	if dataBody["background_type"] == nil || reflect.TypeOf(dataBody["background_type"]).String() != "float64" {
145
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:background_type")
146
+		return
147
+	}
148
+	backgroundType := int64(dataBody["background_type"].(float64))
149
+	if backgroundType != 1 && backgroundType != 2 {
150
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "请选择正确的卡片封面模式")
151
+		return
152
+	}
153
+	card.BackgroundType = backgroundType
154
+
155
+	if dataBody["background"] == nil || reflect.TypeOf(dataBody["background"]).String() != "string" {
156
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:background")
157
+		return
158
+	}
159
+	background, _ := dataBody["background"].(string)
160
+	if len(background) == 0 {
161
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "卡片封面不能为空")
162
+		return
163
+	}
164
+	if backgroundType == 1 && !utils.CheckHexColor(background) {
165
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "背景色格式不正确")
166
+		return
167
+	}
168
+	card.Background = background
169
+
170
+	if dataBody["card_name"] == nil || reflect.TypeOf(dataBody["card_name"]).String() != "string" {
171
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:card_name")
172
+		return
173
+	}
174
+	cardName, _ := dataBody["card_name"].(string)
175
+	if len(cardName) == 0 {
176
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "会员卡名称不能为空")
177
+		return
178
+	}
179
+	card.CardName = cardName
180
+
181
+	if dataBody["use_notice"] != nil && reflect.TypeOf(dataBody["use_notice"]).String() == "string" {
182
+		useNotice, _ := dataBody["use_notice"].(string)
183
+		if len([]rune(useNotice)) > 300 {
184
+			c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "使用须知最多可输入300个字符")
185
+			return
186
+		}
187
+		card.UseNotice = useNotice
188
+	}
189
+
190
+	if dataBody["card_right"] != nil && reflect.TypeOf(dataBody["card_right"]).String() == "string" {
191
+		cardRight, _ := dataBody["card_right"].(string)
192
+		if len([]rune(cardRight)) > 300 {
193
+			c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "会员权益最多可输入300个字符")
194
+			return
195
+		}
196
+		card.CardRight = cardRight
197
+	}
198
+
199
+	if dataBody["service_phone"] != nil && reflect.TypeOf(dataBody["service_phone"]).String() == "string" {
200
+		servicePhone, _ := dataBody["service_phone"].(string)
201
+		if len(servicePhone) > 0 && (!utils.CheckMobile(servicePhone) && !utils.CheckPhone(servicePhone)) {
202
+			c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "客服电话格式不正确")
203
+			return
204
+		}
205
+		card.ServicePhone = servicePhone
206
+	}
207
+
208
+	if dataBody["upgrade_integral"] != nil && reflect.TypeOf(dataBody["upgrade_integral"]).String() == "float64" {
209
+		upgradeIntegral := int64(dataBody["upgrade_integral"].(float64))
210
+		if upgradeIntegral < 0 {
211
+			c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "累积积分不能小于0")
212
+			return
213
+		}
214
+		card.UpgradeIntegral = upgradeIntegral
215
+
216
+	}
217
+	card.UserOrgId = adminUserInfo.CurrentOrgId
218
+	card.Status = 1
219
+	card.CreatedTime = timeNow
220
+	card.UpdatedTime = timeNow
221
+
222
+	oldCard, err := member_service.FindMemberCardByName(adminUserInfo.CurrentOrgId, card.CardName)
223
+	if err != nil {
224
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "添加会员卡失败:("+err.Error()+")")
225
+		return
226
+	}
227
+	if oldCard != nil {
228
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "添加会员卡失败:(已经存在同名的会员卡)")
229
+		return
230
+	}
231
+
232
+	err = member_service.SaveMemberCard(&card)
233
+	if err != nil {
234
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "添加会员卡失败:("+err.Error()+")")
235
+		return
236
+	}
237
+
238
+	returnData := make(map[string]interface{}, 0)
239
+	returnData["card"] = card
240
+	c.ServeSuccessJSON(returnData)
241
+	return
242
+
243
+}
244
+
245
+func (c *CardAPIController) EditCard() {
246
+	id, _ := c.GetInt64("id", 0)
247
+	if id <= 0 {
248
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误:id")
249
+		return
250
+	}
251
+
252
+	adminUserInfo := c.GetAdminUserInfo()
253
+	timeNow := time.Now().Unix()
254
+
255
+	dataBody := make(map[string]interface{}, 0)
256
+	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
257
+	if err != nil {
258
+		utils.ErrorLog(err.Error())
259
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误")
260
+		return
261
+	}
262
+
263
+	card, err := member_service.FindOnlyMemberCardByID(adminUserInfo.CurrentOrgId, id)
264
+	if err != nil {
265
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "编辑会员卡失败:("+err.Error()+")")
266
+		return
267
+	}
268
+	if card == nil {
269
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "编辑会员卡失败:(会员卡不存在)")
270
+		return
271
+	}
272
+
273
+	if dataBody["background_type"] == nil || reflect.TypeOf(dataBody["background_type"]).String() != "float64" {
274
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:background_type")
275
+		return
276
+	}
277
+	backgroundType := int64(dataBody["background_type"].(float64))
278
+	if backgroundType != 1 && backgroundType != 2 {
279
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "请选择正确的卡片封面模式")
280
+		return
281
+	}
282
+	card.BackgroundType = backgroundType
283
+
284
+	if dataBody["background"] == nil || reflect.TypeOf(dataBody["background"]).String() != "string" {
285
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:background")
286
+		return
287
+	}
288
+	background, _ := dataBody["background"].(string)
289
+	if len(background) == 0 {
290
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "卡片封面不能为空")
291
+		return
292
+	}
293
+	if backgroundType == 1 && !utils.CheckHexColor(background) {
294
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "背景色格式不正确")
295
+		return
296
+	}
297
+	card.Background = background
298
+
299
+	if dataBody["card_name"] == nil || reflect.TypeOf(dataBody["card_name"]).String() != "string" {
300
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:card_name")
301
+		return
302
+	}
303
+	cardName, _ := dataBody["card_name"].(string)
304
+	if len(cardName) == 0 {
305
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "会员卡名称不能为空")
306
+		return
307
+	}
308
+	card.CardName = cardName
309
+
310
+	if dataBody["use_notice"] != nil && reflect.TypeOf(dataBody["use_notice"]).String() == "string" {
311
+		useNotice, _ := dataBody["use_notice"].(string)
312
+		if len([]rune(useNotice)) > 300 {
313
+			c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "使用须知最多可输入300个字符")
314
+			return
315
+		}
316
+		card.UseNotice = useNotice
317
+	}
318
+
319
+	if dataBody["card_right"] != nil && reflect.TypeOf(dataBody["card_right"]).String() == "string" {
320
+		cardRight, _ := dataBody["card_right"].(string)
321
+		if len([]rune(cardRight)) > 300 {
322
+			c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "会员权益最多可输入300个字符")
323
+			return
324
+		}
325
+		card.CardRight = cardRight
326
+	}
327
+
328
+	if dataBody["service_phone"] != nil && reflect.TypeOf(dataBody["service_phone"]).String() == "string" {
329
+		servicePhone, _ := dataBody["service_phone"].(string)
330
+		if len(servicePhone) > 0 && (!utils.CheckMobile(servicePhone) && !utils.CheckPhone(servicePhone)) {
331
+			c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "客服电话格式不正确")
332
+			return
333
+		}
334
+		card.ServicePhone = servicePhone
335
+	}
336
+
337
+	if dataBody["upgrade_integral"] != nil && reflect.TypeOf(dataBody["upgrade_integral"]).String() == "float64" {
338
+		upgradeIntegral := int64(dataBody["upgrade_integral"].(float64))
339
+		if upgradeIntegral < 0 {
340
+			c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "累积积分不能小于0")
341
+			return
342
+		}
343
+		card.UpgradeIntegral = upgradeIntegral
344
+
345
+	}
346
+	card.UpdatedTime = timeNow
347
+
348
+	oldCard, err := member_service.FindMemberCardByName(adminUserInfo.CurrentOrgId, card.CardName)
349
+	if err != nil {
350
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "编辑会员卡失败:("+err.Error()+")")
351
+		return
352
+	}
353
+	if oldCard != nil && oldCard.ID != card.ID {
354
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "编辑会员卡失败:(已经存在同名的会员卡)")
355
+		return
356
+	}
357
+
358
+	err = member_service.SaveMemberCard(card)
359
+	if err != nil {
360
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "编辑会员卡失败:("+err.Error()+")")
361
+		return
362
+	}
363
+
364
+	returnData := make(map[string]interface{}, 0)
365
+	returnData["card"] = card
366
+	c.ServeSuccessJSON(returnData)
367
+	return
368
+
369
+}
370
+
371
+func (c *CardAPIController) DeleteCard() {
372
+	adminUserInfo := c.GetAdminUserInfo()
373
+
374
+	dataBody := make(map[string]interface{}, 0)
375
+	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
376
+	if err != nil {
377
+		utils.ErrorLog(err.Error())
378
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误")
379
+		return
380
+	}
381
+
382
+	idsInters := dataBody["ids"].([]interface{})
383
+	if len(idsInters) == 0 {
384
+		if err != nil {
385
+			c.ServeFailJsonSend(enums.ErrorCodeDBDelete, "删除会员卡失败:(没有选择会员卡)")
386
+			return
387
+		}
388
+	}
389
+
390
+	ids := make([]int64, 0)
391
+	for _, idsInter := range idsInters {
392
+		id := int64(idsInter.(float64))
393
+		ids = append(ids, id)
394
+	}
395
+
396
+	count, err := member_service.GetMemebrCardCount(adminUserInfo.CurrentOrgId)
397
+	if err != nil {
398
+		c.ServeFailJsonSend(enums.ErrorCodeDBDelete, "删除会员卡失败:("+err.Error()+")")
399
+		return
400
+	}
401
+	if count <= 1 {
402
+		c.ServeFailJsonSend(enums.ErrorCodeDBDelete, "删除会员卡失败:(只有1张会员卡时不能删除)")
403
+		return
404
+	}
405
+	if count-int64(len(ids)) < 1 {
406
+		c.ServeFailJsonSend(enums.ErrorCodeDBDelete, "删除会员卡失败:(至少需要保留1张会员卡)")
407
+		return
408
+	}
409
+
410
+	ccs, err := member_service.GetCardsUserCount(adminUserInfo.CurrentOrgId, ids)
411
+	if err != nil {
412
+		c.ServeFailJsonSend(enums.ErrorCodeDBDelete, "删除会员卡失败:("+err.Error()+")")
413
+		return
414
+	}
415
+
416
+	hadUserIds := make([]int64, 0)
417
+	willIds := make([]int64, 0)
418
+	if len(ccs) > 0 {
419
+		ccsMap := make(map[int64]int64, 0)
420
+		for _, cc := range ccs {
421
+			if cc.MemberCount > 0 {
422
+				hadUserIds = append(hadUserIds, cc.CardID)
423
+				ccsMap[cc.CardID] = cc.MemberCount
424
+			}
425
+		}
426
+		for _, id := range ids {
427
+			if _, exist := ccsMap[id]; !exist {
428
+				willIds = append(willIds, id)
429
+			}
430
+		}
431
+		if len(willIds) == 0 {
432
+			c.ServeFailJsonSend(enums.ErrorCodeDBDelete, "删除会员卡失败:(不能删除有会员的会员卡)")
433
+			return
434
+		}
435
+	}
436
+
437
+	err = member_service.DeleteMemberShipCards(adminUserInfo.CurrentOrgId, ids)
438
+	if err != nil {
439
+		c.ServeFailJsonSend(enums.ErrorCodeDBDelete, "删除会员卡失败:("+err.Error()+")")
440
+		return
441
+	}
442
+
443
+	returnData := make(map[string]interface{}, 0)
444
+	returnData["delete_ids"] = willIds
445
+	returnData["delete_number"] = len(willIds)
446
+
447
+	c.ServeSuccessJSON(returnData)
448
+	return
449
+}
450
+
451
+func (c *CardAPIController) EditRight() {
452
+	adminUserInfo := c.GetAdminUserInfo()
453
+	timeNow := time.Now().Unix()
454
+
455
+	dataBody := make(map[string]interface{}, 0)
456
+	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
457
+	if err != nil {
458
+		utils.ErrorLog(err.Error())
459
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误")
460
+		return
461
+	}
462
+
463
+	var saveRight models.MembershipRights
464
+	right, err := member_service.GetMembershipRights(adminUserInfo.CurrentOrgId)
465
+	if err != nil {
466
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "编辑会员权益失败:("+err.Error()+")")
467
+		return
468
+	}
469
+	if right != nil {
470
+		saveRight = *right
471
+	} else {
472
+		saveRight.UserOrgId = adminUserInfo.CurrentOrgId
473
+		saveRight.Status = 1
474
+		saveRight.CreatedTime = timeNow
475
+	}
476
+
477
+	if dataBody["rights"] == nil || reflect.TypeOf(dataBody["rights"]).String() != "string" {
478
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:rights")
479
+		return
480
+	}
481
+	rights, _ := dataBody["rights"].(string)
482
+	saveRight.Rights = rights
483
+	saveRight.UpdatedTime = timeNow
484
+
485
+	err = member_service.SaveMembershipRight(&saveRight)
486
+	if err != nil {
487
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "编辑会员权益失败:("+err.Error()+")")
488
+		return
489
+	}
490
+
491
+	returnData := make(map[string]interface{}, 0)
492
+	returnData["right"] = saveRight
493
+	c.ServeSuccessJSON(returnData)
494
+	return
495
+
496
+}

+ 657 - 0
controllers/members/members_controller.go View File

@@ -0,0 +1,657 @@
1
+package members
2
+
3
+import (
4
+	base_ctl "SCRM/controllers"
5
+	"SCRM/enums"
6
+	"SCRM/models"
7
+	"SCRM/service/member_service"
8
+	"SCRM/utils"
9
+	"encoding/json"
10
+	"fmt"
11
+	"reflect"
12
+	"time"
13
+
14
+	"github.com/astaxie/beego"
15
+)
16
+
17
+func MemberCtlRegistRouters() {
18
+	beego.Router("/api/members", &MembersAPIController{}, "get:GetMembers")
19
+	beego.Router("/api/members/all", &MembersAPIController{}, "get:GetAllMembers")
20
+	beego.Router("/api/member/create", &MembersAPIController{}, "Post:CreateMember")
21
+	beego.Router("/api/member/edit", &MembersAPIController{}, "Put:EditMember")
22
+	beego.Router("/api/members/delete", &MembersAPIController{}, "Delete:DeleteMembers")
23
+}
24
+
25
+type MembersAPIController struct {
26
+	base_ctl.BaseAuthAPIController
27
+}
28
+
29
+func (c *MembersAPIController) GetMembers() {
30
+	page, _ := c.GetInt64("page", 1)
31
+	limit, _ := c.GetInt64("limit", 10)
32
+	startTime := c.GetString("start_time", "")
33
+	endTime := c.GetString("end_time", "")
34
+	searchKey := c.GetString("search", "")
35
+	level, _ := c.GetInt64("level", 0)
36
+	source, _ := c.GetInt64("source", 0)
37
+	tag, _ := c.GetInt64("tag", 0)
38
+	init, _ := c.GetInt64("init", 0)
39
+	fmt.Println("level", level, "source", source)
40
+	if page <= 0 {
41
+		page = 1
42
+	}
43
+	if limit <= 0 {
44
+		limit = 10
45
+	}
46
+
47
+	adminUserInfo := c.GetAdminUserInfo()
48
+
49
+	timeLayout := "2006-01-02 15:04:05"
50
+
51
+	var isStartTime bool
52
+	var theStartTIme int64
53
+	if len(startTime) > 0 {
54
+		theTime, err := utils.ParseTimeStringToTime(timeLayout, startTime+" 00:00:00")
55
+		if err != nil {
56
+			c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "开始时间错误")
57
+			return
58
+		}
59
+		isStartTime = true
60
+		theStartTIme = theTime.Unix()
61
+	}
62
+	var isEndTime bool
63
+	var theEndtTIme int64
64
+	if len(endTime) > 0 {
65
+		theTime, err := utils.ParseTimeStringToTime(timeLayout, endTime+" 23:59:59")
66
+		if err != nil {
67
+			c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "结束时间错误")
68
+			return
69
+		}
70
+		isEndTime = true
71
+		theEndtTIme = theTime.Unix()
72
+	}
73
+
74
+	members, total, err := member_service.GetMemberList(adminUserInfo.CurrentOrgId, page, limit, level, source, tag, theStartTIme, theEndtTIme, isStartTime, isEndTime, searchKey)
75
+
76
+	if err != nil {
77
+		c.ServeFailJsonSend(enums.ErrorCodeDataException, "获取会员列表失败")
78
+		return
79
+	}
80
+
81
+	returnData := make(map[string]interface{}, 0)
82
+	if init == 1 {
83
+		cards, err := member_service.GetCardList(adminUserInfo.CurrentOrgId)
84
+		if err != nil {
85
+			c.ServeFailJsonSend(enums.ErrorCodeDataException, "获取会员卡列表失败")
86
+			return
87
+		}
88
+		returnData["cards"] = cards
89
+
90
+		tags, err := member_service.GetTagList(adminUserInfo.CurrentOrgId)
91
+		if err != nil {
92
+			c.ServeFailJsonSend(enums.ErrorCodeDataException, "获取标签列表失败")
93
+			return
94
+		}
95
+		returnData["tags"] = tags
96
+
97
+		illness, err := member_service.GetIllnessList()
98
+		if err != nil {
99
+			c.ServeFailJsonSend(enums.ErrorCodeDataException, "获取病种列表失败")
100
+			return
101
+		}
102
+		returnData["illness"] = illness
103
+	}
104
+	returnData["members"] = members
105
+	returnData["total"] = total
106
+
107
+	c.ServeSuccessJSON(returnData)
108
+	return
109
+}
110
+
111
+func (c *MembersAPIController) GetAllMembers() {
112
+
113
+	adminUserInfo := c.GetAdminUserInfo()
114
+	members, err := member_service.GetAllMemberList(adminUserInfo.CurrentOrgId)
115
+	fmt.Println("members是什么", members)
116
+	fmt.Println("资讯管理错误是什么", err)
117
+	if err != nil {
118
+		c.ServeFailJsonSend(enums.ErrorCodeDataException, "获取列表失败")
119
+		return
120
+	}
121
+
122
+	returnData := make(map[string]interface{}, 0)
123
+	returnData["members"] = members
124
+
125
+	c.ServeSuccessJSON(returnData)
126
+	return
127
+}
128
+
129
+func (c *MembersAPIController) CreateMember() {
130
+
131
+	adminUserInfo := c.GetAdminUserInfo()
132
+	timeNow := time.Now().Unix()
133
+
134
+	dataBody := make(map[string]interface{}, 0)
135
+	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
136
+	if err != nil {
137
+		utils.ErrorLog(err.Error())
138
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误")
139
+		return
140
+	}
141
+
142
+	var member member_service.Members
143
+
144
+	if dataBody["name"] == nil || reflect.TypeOf(dataBody["name"]).String() != "string" {
145
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:姓名")
146
+		return
147
+	}
148
+	name, _ := dataBody["name"].(string)
149
+	if len(name) == 0 {
150
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "姓名不能为空")
151
+		return
152
+	}
153
+	member.Name = name
154
+
155
+	if dataBody["mobile"] == nil || reflect.TypeOf(dataBody["mobile"]).String() != "string" {
156
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:手机号")
157
+		return
158
+	}
159
+	mobile, _ := dataBody["mobile"].(string)
160
+	if len(mobile) == 0 {
161
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "手机号不能为空")
162
+		return
163
+	}
164
+	if !utils.CheckMobile(mobile) {
165
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "手机号格式不正确")
166
+		return
167
+	}
168
+	member.Mobile = mobile
169
+
170
+	if dataBody["gender"] == nil || reflect.TypeOf(dataBody["gender"]).String() != "float64" {
171
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:性别")
172
+		return
173
+	}
174
+	gender := int64(dataBody["gender"].(float64))
175
+
176
+	if gender != 1 && gender != 2 {
177
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "性别选择不正确")
178
+		return
179
+	}
180
+	member.Gender = gender
181
+
182
+	if dataBody["birthday"] == nil || reflect.TypeOf(dataBody["birthday"]).String() != "string" {
183
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:生日")
184
+		return
185
+	}
186
+	birthday, _ := dataBody["birthday"].(string)
187
+	if len(birthday) == 0 {
188
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "生日格式不正确")
189
+		return
190
+	}
191
+
192
+	timeLayout := "2006-01-02 15:04:05"
193
+	theTime, err := utils.ParseTimeStringToTime(timeLayout, birthday+" 00:00:00")
194
+	if err != nil {
195
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "生日格式不正确")
196
+		return
197
+	}
198
+	member.Birthday = theTime.Unix()
199
+
200
+	if dataBody["province_id"] == nil || reflect.TypeOf(dataBody["province_id"]).String() != "float64" {
201
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:地区(省)")
202
+		return
203
+	}
204
+	provinceID := int64(dataBody["province_id"].(float64))
205
+	if provinceID <= 0 {
206
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "请选择地区")
207
+		return
208
+	}
209
+	member.ProvinceId = provinceID
210
+
211
+	if dataBody["city_id"] == nil || reflect.TypeOf(dataBody["city_id"]).String() != "float64" {
212
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:地区(市)")
213
+		return
214
+	}
215
+	cityID := int64(dataBody["city_id"].(float64))
216
+	if cityID <= 0 {
217
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "请选择地区")
218
+		return
219
+	}
220
+	member.CityId = cityID
221
+
222
+	if dataBody["district_id"] == nil || reflect.TypeOf(dataBody["district_id"]).String() != "float64" {
223
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:地区(区/县)")
224
+		return
225
+	}
226
+	districtID := int64(dataBody["district_id"].(float64))
227
+	if districtID <= 0 {
228
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "请选择地区")
229
+		return
230
+	}
231
+	member.DistrictId = districtID
232
+
233
+	if dataBody["illness"] == nil || reflect.TypeOf(dataBody["illness"]).String() != "[]interface {}" {
234
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:病种")
235
+		return
236
+	}
237
+	illnessInters := dataBody["illness"].([]interface{})
238
+	if len(illnessInters) <= 0 {
239
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "请选择病种")
240
+		return
241
+	}
242
+	member.Illness = make([]*member_service.CustomerIllness, 0)
243
+	for _, illnessInter := range illnessInters {
244
+		id := int64(illnessInter.(float64))
245
+		var illItem member_service.CustomerIllness
246
+		illItem.UserOrgId = adminUserInfo.CurrentOrgId
247
+		illItem.IllnessId = id
248
+		illItem.Status = 1
249
+		illItem.UpdatedTime = timeNow
250
+		illItem.CreatedTime = timeNow
251
+		member.Illness = append(member.Illness, &illItem)
252
+	}
253
+
254
+	if dataBody["ill_date"] == nil || reflect.TypeOf(dataBody["ill_date"]).String() != "string" {
255
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:患病时间")
256
+		return
257
+	}
258
+	illDate, _ := dataBody["ill_date"].(string)
259
+	if len(illDate) == 0 {
260
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "患病时间格式不正确")
261
+		return
262
+	}
263
+
264
+	illDateTime, err := utils.ParseTimeStringToTime(timeLayout, illDate+" 00:00:00")
265
+	if err != nil {
266
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "患病时间格式不正确")
267
+		return
268
+	}
269
+	member.IllDate = illDateTime.Unix()
270
+
271
+	if dataBody["treat_type"] == nil || reflect.TypeOf(dataBody["treat_type"]).String() != "float64" {
272
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:治疗方式")
273
+		return
274
+	}
275
+	treatType := int64(dataBody["treat_type"].(float64))
276
+	if treatType <= 0 {
277
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "请选择治疗方式")
278
+		return
279
+	}
280
+	member.TreatType = treatType
281
+
282
+	if dataBody["tags"] != nil && reflect.TypeOf(dataBody["tags"]).String() == "[]interface {}" {
283
+		tagsInters := dataBody["tags"].([]interface{})
284
+		if len(tagsInters) > 0 {
285
+			member.UserTags = make([]*models.UserTagLinks, 0)
286
+			for _, tagsInter := range tagsInters {
287
+				id := int64(tagsInter.(float64))
288
+				var tagItem models.UserTagLinks
289
+				tagItem.TagId = id
290
+				tagItem.UserOrgId = adminUserInfo.CurrentOrgId
291
+				tagItem.Status = 1
292
+				tagItem.UpdatedTime = timeNow
293
+				tagItem.CreatedTime = timeNow
294
+				member.UserTags = append(member.UserTags, &tagItem)
295
+			}
296
+		}
297
+	}
298
+
299
+	if dataBody["remark"] != nil && reflect.TypeOf(dataBody["remark"]).String() == "string" {
300
+		remark, _ := dataBody["remark"].(string)
301
+		if len(remark) > 0 {
302
+			member.Remark = remark
303
+		}
304
+	}
305
+
306
+	if dataBody["avatar"] != nil && reflect.TypeOf(dataBody["avatar"]).String() == "string" {
307
+		avatar, _ := dataBody["avatar"].(string)
308
+		if len(avatar) > 0 {
309
+			member.Avatar = avatar
310
+		}
311
+	}
312
+
313
+	customer, err := member_service.GetCustomerByMobile(adminUserInfo.CurrentOrgId, member.Mobile)
314
+	if err != nil {
315
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "添加会员失败:("+err.Error()+")")
316
+		return
317
+	}
318
+	if customer != nil {
319
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "添加会员失败:(已经存在该手机号的客户)")
320
+		return
321
+	}
322
+
323
+	member.UserOrgId = adminUserInfo.CurrentOrgId
324
+	member.Status = 1
325
+	member.CreatedTime = timeNow
326
+	member.UpdatedTime = timeNow
327
+	member.Sources = 7
328
+
329
+	user, err := member_service.GetUserByMobile(member.Mobile)
330
+	if err != nil {
331
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "添加会员失败:("+err.Error()+")")
332
+		return
333
+	}
334
+	if user != nil {
335
+		member.UserId = user.ID
336
+		err = member_service.CreateMember(&member)
337
+		if err != nil {
338
+			c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "添加会员失败:("+err.Error()+")")
339
+			return
340
+		}
341
+	} else {
342
+		var userData models.User
343
+		userData.Avatar = member.Avatar
344
+		userData.AvatarThumb = member.Avatar
345
+		userData.Username = member.Name
346
+		userData.Remarkname = member.Name
347
+		userData.Mobile = member.Mobile
348
+		userData.Gender = member.Gender
349
+		userData.ProvinceId = member.ProvinceId
350
+		userData.CityId = member.CityId
351
+		userData.Address = member.Address
352
+		userData.Birthday = member.Birthday
353
+		userData.TreatType = member.TreatType
354
+		userData.Relationship = member.Relationship
355
+		userData.IllnessId = member.Illness[0].IllnessId
356
+		userData.Sources = member.Sources
357
+		userData.Status = 1
358
+		userData.CreatedTime = timeNow
359
+		userData.UpdatedTime = timeNow
360
+
361
+		err = member_service.CreateMemberWithUser(&member, &userData)
362
+		if err != nil {
363
+			c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "添加会员失败:("+err.Error()+")")
364
+			return
365
+		}
366
+	}
367
+
368
+	returnData := make(map[string]interface{}, 0)
369
+	returnData["member"] = member
370
+	c.ServeSuccessJSON(returnData)
371
+	return
372
+
373
+}
374
+
375
+func (c *MembersAPIController) EditMember() {
376
+	id, _ := c.GetInt64("id", 0)
377
+	if id <= 0 {
378
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误:id")
379
+		return
380
+	}
381
+	adminUserInfo := c.GetAdminUserInfo()
382
+
383
+	member, err := member_service.GetOnlyMemberByID(adminUserInfo.CurrentOrgId, id)
384
+	if err != nil {
385
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "编辑会员失败:("+err.Error()+")")
386
+		return
387
+	}
388
+	if member == nil {
389
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "编辑会员失败:(会员记录不存在)")
390
+		return
391
+	}
392
+
393
+	timeNow := time.Now().Unix()
394
+
395
+	dataBody := make(map[string]interface{}, 0)
396
+	err = json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
397
+	if err != nil {
398
+		utils.ErrorLog(err.Error())
399
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误")
400
+		return
401
+	}
402
+
403
+	if dataBody["name"] == nil || reflect.TypeOf(dataBody["name"]).String() != "string" {
404
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:姓名")
405
+		return
406
+	}
407
+	name, _ := dataBody["name"].(string)
408
+	if len(name) == 0 {
409
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "姓名不能为空")
410
+		return
411
+	}
412
+	member.Name = name
413
+
414
+	if dataBody["mobile"] == nil || reflect.TypeOf(dataBody["mobile"]).String() != "string" {
415
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:手机号")
416
+		return
417
+	}
418
+	mobile, _ := dataBody["mobile"].(string)
419
+	if len(mobile) == 0 {
420
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "手机号不能为空")
421
+		return
422
+	}
423
+	if !utils.CheckMobile(mobile) {
424
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "手机号格式不正确")
425
+		return
426
+	}
427
+	changeMobile := true
428
+	if member.Mobile == mobile {
429
+		changeMobile = false
430
+	}
431
+	member.Mobile = mobile
432
+
433
+	if dataBody["gender"] == nil || reflect.TypeOf(dataBody["gender"]).String() != "float64" {
434
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:性别")
435
+		return
436
+	}
437
+	gender := int64(dataBody["gender"].(float64))
438
+
439
+	if gender != 1 && gender != 2 {
440
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "性别选择不正确")
441
+		return
442
+	}
443
+	member.Gender = gender
444
+
445
+	if dataBody["birthday"] == nil || reflect.TypeOf(dataBody["birthday"]).String() != "string" {
446
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:生日")
447
+		return
448
+	}
449
+	birthday, _ := dataBody["birthday"].(string)
450
+	if len(birthday) == 0 {
451
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "生日格式不正确")
452
+		return
453
+	}
454
+
455
+	timeLayout := "2006-01-02 15:04:05"
456
+	theTime, err := utils.ParseTimeStringToTime(timeLayout, birthday+" 00:00:00")
457
+	if err != nil {
458
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "生日格式不正确")
459
+		return
460
+	}
461
+	member.Birthday = theTime.Unix()
462
+
463
+	if dataBody["province_id"] == nil || reflect.TypeOf(dataBody["province_id"]).String() != "float64" {
464
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:地区(省)")
465
+		return
466
+	}
467
+	provinceID := int64(dataBody["province_id"].(float64))
468
+	if provinceID <= 0 {
469
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "请选择地区")
470
+		return
471
+	}
472
+	member.ProvinceId = provinceID
473
+
474
+	if dataBody["city_id"] == nil || reflect.TypeOf(dataBody["city_id"]).String() != "float64" {
475
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:地区(市)")
476
+		return
477
+	}
478
+	cityID := int64(dataBody["city_id"].(float64))
479
+	if cityID <= 0 {
480
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "请选择地区")
481
+		return
482
+	}
483
+	member.CityId = cityID
484
+
485
+	if dataBody["district_id"] == nil || reflect.TypeOf(dataBody["district_id"]).String() != "float64" {
486
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:地区(区/县)")
487
+		return
488
+	}
489
+	districtID := int64(dataBody["district_id"].(float64))
490
+	if districtID <= 0 {
491
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "请选择地区")
492
+		return
493
+	}
494
+	member.DistrictId = districtID
495
+
496
+	if dataBody["illness"] == nil || reflect.TypeOf(dataBody["illness"]).String() != "[]interface {}" {
497
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:病种")
498
+		return
499
+	}
500
+	illnessInters := dataBody["illness"].([]interface{})
501
+	if len(illnessInters) <= 0 {
502
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "请选择病种")
503
+		return
504
+	}
505
+	member.Illness = make([]*member_service.CustomerIllness, 0)
506
+	illnessIDS := make([]int64, 0)
507
+	illnessIDMap := make(map[int64]int64, 0)
508
+	for _, illnessInter := range illnessInters {
509
+		id := int64(illnessInter.(float64))
510
+		illnessIDS = append(illnessIDS, id)
511
+		illnessIDMap[id] = id
512
+	}
513
+	allIllness, err := member_service.GetMemberAllIllness(adminUserInfo.CurrentOrgId, member.ID)
514
+	if err != nil {
515
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "编辑会员失败:("+err.Error()+")")
516
+		return
517
+	}
518
+	oldIllIDMap := make(map[int64]int64, 0)
519
+	for _, illItem := range allIllness {
520
+		item := *illItem
521
+		item.Status = 1
522
+		if _, exist := illnessIDMap[item.IllnessId]; !exist {
523
+			item.Status = 0
524
+			item.UpdatedTime = timeNow
525
+		}
526
+		member.Illness = append(member.Illness, &item)
527
+		oldIllIDMap[item.IllnessId] = item.IllnessId
528
+	}
529
+
530
+	for _, id := range illnessIDMap {
531
+		if _, exist := oldIllIDMap[id]; exist {
532
+			continue
533
+		}
534
+		var illItem member_service.CustomerIllness
535
+		illItem.UserOrgId = adminUserInfo.CurrentOrgId
536
+		illItem.IllnessId = id
537
+		illItem.Status = 1
538
+		illItem.UpdatedTime = timeNow
539
+		illItem.CreatedTime = timeNow
540
+		member.Illness = append(member.Illness, &illItem)
541
+	}
542
+
543
+	if dataBody["ill_date"] == nil || reflect.TypeOf(dataBody["ill_date"]).String() != "string" {
544
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:患病时间")
545
+		return
546
+	}
547
+	illDate, _ := dataBody["ill_date"].(string)
548
+	if len(illDate) == 0 {
549
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "患病时间格式不正确")
550
+		return
551
+	}
552
+
553
+	illDateTime, err := utils.ParseTimeStringToTime(timeLayout, illDate+" 00:00:00")
554
+	if err != nil {
555
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "患病时间格式不正确")
556
+		return
557
+	}
558
+	member.IllDate = illDateTime.Unix()
559
+
560
+	if dataBody["treat_type"] == nil || reflect.TypeOf(dataBody["treat_type"]).String() != "float64" {
561
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:治疗方式")
562
+		return
563
+	}
564
+	treatType := int64(dataBody["treat_type"].(float64))
565
+	if treatType <= 0 {
566
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "请选择治疗方式")
567
+		return
568
+	}
569
+	member.TreatType = treatType
570
+
571
+	if dataBody["remark"] != nil && reflect.TypeOf(dataBody["remark"]).String() == "string" {
572
+		remark, _ := dataBody["remark"].(string)
573
+		if len(remark) > 0 {
574
+			member.Remark = remark
575
+		}
576
+	}
577
+
578
+	if dataBody["avatar"] != nil && reflect.TypeOf(dataBody["avatar"]).String() == "string" {
579
+		avatar, _ := dataBody["avatar"].(string)
580
+		if len(avatar) > 0 {
581
+			member.Avatar = avatar
582
+		}
583
+	}
584
+
585
+	if changeMobile {
586
+		customer, err := member_service.GetCustomerByMobile(adminUserInfo.CurrentOrgId, member.Mobile)
587
+		if err != nil {
588
+			c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "编辑会员失败:("+err.Error()+")")
589
+			return
590
+		}
591
+		if customer != nil && customer.ID != member.ID {
592
+			c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "编辑会员失败:(已经存在该手机号的客户)")
593
+			return
594
+		}
595
+	}
596
+	member.UpdatedTime = timeNow
597
+
598
+	err = member_service.EditMember(member)
599
+	if err != nil {
600
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "编辑会员失败:("+err.Error()+")")
601
+		return
602
+	}
603
+
604
+	illness := member.Illness
605
+	member.Illness = make([]*member_service.CustomerIllness, 0)
606
+	for _, ill := range illness {
607
+		illItem := *ill
608
+		if illItem.Status == 0 {
609
+			continue
610
+		}
611
+		member.Illness = append(member.Illness, &illItem)
612
+	}
613
+
614
+	returnData := make(map[string]interface{}, 0)
615
+	returnData["member"] = member
616
+	c.ServeSuccessJSON(returnData)
617
+	return
618
+
619
+}
620
+
621
+func (c *MembersAPIController) DeleteMembers() {
622
+	adminUserInfo := c.GetAdminUserInfo()
623
+
624
+	dataBody := make(map[string]interface{}, 0)
625
+	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
626
+	if err != nil {
627
+		utils.ErrorLog(err.Error())
628
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误")
629
+		return
630
+	}
631
+
632
+	idsInters := dataBody["ids"].([]interface{})
633
+	if len(idsInters) == 0 {
634
+		if err != nil {
635
+			c.ServeFailJsonSend(enums.ErrorCodeDBDelete, "删除会员失败:(没有选择会员)")
636
+			return
637
+		}
638
+	}
639
+
640
+	ids := make([]int64, 0)
641
+	for _, idsInter := range idsInters {
642
+		id := int64(idsInter.(float64))
643
+		ids = append(ids, id)
644
+	}
645
+
646
+	err = member_service.DeleteMembers(adminUserInfo.CurrentOrgId, ids)
647
+	if err != nil {
648
+		c.ServeFailJsonSend(enums.ErrorCodeDBDelete, "删除会员失败:("+err.Error()+")")
649
+		return
650
+	}
651
+
652
+	returnData := make(map[string]interface{}, 0)
653
+	returnData["msg"] = "ok"
654
+
655
+	c.ServeSuccessJSON(returnData)
656
+	return
657
+}

+ 7 - 0
controllers/members/router_controller.go View File

@@ -0,0 +1,7 @@
1
+package members
2
+
3
+func RegisterRouters() {
4
+	MemberCtlRegistRouters()
5
+	TagCtlRegistRouters()
6
+	CardCtlRegistRouters()
7
+}

+ 395 - 0
controllers/members/tags_controller.go View File

@@ -0,0 +1,395 @@
1
+package members
2
+
3
+import (
4
+	base_ctl "SCRM/controllers"
5
+	"SCRM/enums"
6
+	"SCRM/models"
7
+	"SCRM/service/member_service"
8
+	"SCRM/utils"
9
+	"reflect"
10
+	"time"
11
+
12
+	"encoding/json"
13
+
14
+	"github.com/astaxie/beego"
15
+)
16
+
17
+func TagCtlRegistRouters() {
18
+	beego.Router("/api/member/tag/edit", &TagAPIController{}, "Post:EditMemberTags")
19
+	beego.Router("/api/members/tags/add", &TagAPIController{}, "Post:AddMembersTags")
20
+	beego.Router("/api/members/tags", &TagAPIController{}, "Get:GetTags")
21
+	beego.Router("/api/members/tag/create", &TagAPIController{}, "Post:CreateTag")
22
+	beego.Router("/api/members/tag/edit", &TagAPIController{}, "Put:EditTag")
23
+	beego.Router("/api/members/tags/delete", &TagAPIController{}, "Delete:DeleteTag")
24
+}
25
+
26
+type TagAPIController struct {
27
+	base_ctl.BaseAuthAPIController
28
+}
29
+
30
+func (c *TagAPIController) EditMemberTags() {
31
+	id, _ := c.GetInt64("id", 0)
32
+	if id <= 0 {
33
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误:id")
34
+		return
35
+	}
36
+	adminUserInfo := c.GetAdminUserInfo()
37
+	member, err := member_service.GetOnlyMemberByID(adminUserInfo.CurrentOrgId, id)
38
+	if err != nil {
39
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "编辑会员标签失败:("+err.Error()+")")
40
+		return
41
+	}
42
+	if member == nil {
43
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "编辑会员标签失败:(会员记录不存在)")
44
+		return
45
+	}
46
+
47
+	timeNow := time.Now().Unix()
48
+
49
+	dataBody := make(map[string]interface{}, 0)
50
+	err = json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
51
+	if err != nil {
52
+		utils.ErrorLog(err.Error())
53
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误")
54
+		return
55
+	}
56
+
57
+	if dataBody["tags"] == nil || reflect.TypeOf(dataBody["tags"]).String() != "[]interface {}" {
58
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:tags")
59
+		return
60
+	}
61
+
62
+	returnData := make(map[string]interface{}, 0)
63
+
64
+	tagsInters := dataBody["tags"].([]interface{})
65
+	if len(tagsInters) == 0 {
66
+		err = member_service.DeleteMemeberAllTags(adminUserInfo.CurrentOrgId, member.ID)
67
+		if err != nil {
68
+			c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "编辑会员标签失败:("+err.Error()+")")
69
+			return
70
+		}
71
+		returnData["tags"] = nil
72
+	} else {
73
+		userTags := make([]*models.UserTagLinks, 0)
74
+		tagIds := make([]int64, 0)
75
+		tagIDMap := make(map[int64]int64, 0)
76
+		for _, tagsInter := range tagsInters {
77
+			id := int64(tagsInter.(float64))
78
+			tagIds = append(tagIds, id)
79
+			tagIDMap[id] = id
80
+		}
81
+		allTags, err := member_service.GetMemberAllTags(adminUserInfo.CurrentOrgId, member.ID)
82
+		if err != nil {
83
+			c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "编辑会员标签失败:("+err.Error()+")")
84
+			return
85
+		}
86
+		oldTagIDMap := make(map[int64]int64, 0)
87
+		for _, tagItem := range allTags {
88
+			item := *tagItem
89
+			item.Status = 1
90
+			if _, exist := tagIDMap[item.TagId]; !exist {
91
+				item.Status = 0
92
+				item.UpdatedTime = timeNow
93
+			}
94
+			userTags = append(userTags, &item)
95
+			oldTagIDMap[item.TagId] = item.TagId
96
+		}
97
+
98
+		for _, id := range tagIDMap {
99
+			if _, exist := oldTagIDMap[id]; exist {
100
+				continue
101
+			}
102
+			var tagItem models.UserTagLinks
103
+			tagItem.UserOrgId = adminUserInfo.CurrentOrgId
104
+			tagItem.TagId = id
105
+			tagItem.UserLinkId = member.ID
106
+			tagItem.Status = 1
107
+			tagItem.UpdatedTime = timeNow
108
+			tagItem.CreatedTime = timeNow
109
+			userTags = append(userTags, &tagItem)
110
+		}
111
+		err = member_service.SaveMemberTags(userTags)
112
+
113
+		if err != nil {
114
+			c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "编辑会员标签失败:("+err.Error()+")")
115
+			return
116
+		}
117
+
118
+		returnData["tags"] = tagIds
119
+	}
120
+	c.ServeSuccessJSON(returnData)
121
+	return
122
+}
123
+
124
+func (c *TagAPIController) AddMembersTags() {
125
+	adminUserInfo := c.GetAdminUserInfo()
126
+	timeNow := time.Now().Unix()
127
+
128
+	dataBody := make(map[string]interface{}, 0)
129
+	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
130
+	if err != nil {
131
+		utils.ErrorLog(err.Error())
132
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误")
133
+		return
134
+	}
135
+
136
+	if dataBody["tags"] == nil || reflect.TypeOf(dataBody["tags"]).String() != "[]interface {}" {
137
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:tags")
138
+		return
139
+	}
140
+
141
+	idsInters := dataBody["ids"].([]interface{})
142
+	if len(idsInters) == 0 {
143
+		if err != nil {
144
+			c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "添加会员标签失败:(没有选择会员)")
145
+			return
146
+		}
147
+	}
148
+
149
+	ids := make([]int64, 0)
150
+	idsMap := make(map[int64]int64, 0)
151
+	for _, idsInter := range idsInters {
152
+		id := int64(idsInter.(float64))
153
+		ids = append(ids, id)
154
+		idsMap[id] = id
155
+	}
156
+
157
+	tagsInters := dataBody["tags"].([]interface{})
158
+	if len(tagsInters) == 0 {
159
+		if err != nil {
160
+			c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "添加会员标签失败:(没有选择标签)")
161
+			return
162
+		}
163
+	}
164
+	tagIds := make([]int64, 0)
165
+	tagIDMap := make(map[int64]int64, 0)
166
+	for _, tagsInter := range tagsInters {
167
+		id := int64(tagsInter.(float64))
168
+		tagIds = append(tagIds, id)
169
+		tagIDMap[id] = id
170
+	}
171
+
172
+	allTags, err := member_service.GetMembersAllTags(adminUserInfo.CurrentOrgId, ids)
173
+	if err != nil {
174
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "添加会员标签失败:("+err.Error()+")")
175
+		return
176
+	}
177
+
178
+	userTags := make([]*models.UserTagLinks, 0)
179
+	oldTagIDMap := make(map[int64]map[int64]int64, 0)
180
+	for _, tagItem := range allTags {
181
+		_, exist := tagIDMap[tagItem.TagId]
182
+		_, uexist := idsMap[tagItem.UserLinkId]
183
+		if exist && uexist {
184
+			item := *tagItem
185
+			item.Status = 1
186
+			item.UpdatedTime = timeNow
187
+			userTags = append(userTags, &item)
188
+			if _, oex := oldTagIDMap[item.UserLinkId]; !oex {
189
+				oldTagIDMap[item.UserLinkId] = make(map[int64]int64, 0)
190
+			}
191
+			oldTagIDMap[item.UserLinkId][item.TagId] = item.TagId
192
+		}
193
+	}
194
+
195
+	for _, userid := range idsMap {
196
+		for _, tagid := range tagIDMap {
197
+			if _, exist := oldTagIDMap[userid]; exist {
198
+				if _, exist := oldTagIDMap[userid][tagid]; exist {
199
+					continue
200
+				}
201
+			}
202
+			var tagItem models.UserTagLinks
203
+			tagItem.UserOrgId = adminUserInfo.CurrentOrgId
204
+			tagItem.TagId = tagid
205
+			tagItem.UserLinkId = userid
206
+			tagItem.Status = 1
207
+			tagItem.UpdatedTime = timeNow
208
+			tagItem.CreatedTime = timeNow
209
+			userTags = append(userTags, &tagItem)
210
+		}
211
+	}
212
+	err = member_service.SaveMemberTags(userTags)
213
+
214
+	if err != nil {
215
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "添加会员标签失败:("+err.Error()+")")
216
+		return
217
+	}
218
+
219
+	returnData := make(map[string]interface{}, 0)
220
+	returnData["msg"] = "ok"
221
+
222
+	c.ServeSuccessJSON(returnData)
223
+	return
224
+}
225
+
226
+func (c *TagAPIController) GetTags() {
227
+	page, _ := c.GetInt64("page", 1)
228
+	limit, _ := c.GetInt64("limit", 10)
229
+	searchKey := c.GetString("search", "")
230
+	if page <= 0 {
231
+		page = 1
232
+	}
233
+	if limit <= 0 {
234
+		limit = 10
235
+	}
236
+
237
+	adminUserInfo := c.GetAdminUserInfo()
238
+	tags, total, _ := member_service.GetPageTagList(adminUserInfo.CurrentOrgId, page, limit, searchKey)
239
+
240
+	returnData := make(map[string]interface{}, 0)
241
+	returnData["tags"] = tags
242
+	returnData["total"] = total
243
+	c.ServeSuccessJSON(returnData)
244
+	return
245
+}
246
+
247
+func (c *TagAPIController) CreateTag() {
248
+	adminUserInfo := c.GetAdminUserInfo()
249
+	timeNow := time.Now().Unix()
250
+
251
+	dataBody := make(map[string]interface{}, 0)
252
+	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
253
+	if err != nil {
254
+		utils.ErrorLog(err.Error())
255
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误")
256
+		return
257
+	}
258
+
259
+	var tag models.UserTags
260
+
261
+	if dataBody["tag_name"] == nil || reflect.TypeOf(dataBody["tag_name"]).String() != "string" {
262
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:标签名")
263
+		return
264
+	}
265
+	tagName, _ := dataBody["tag_name"].(string)
266
+	if len(tagName) == 0 {
267
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "标签名不能为空")
268
+		return
269
+	}
270
+	tag.TagName = tagName
271
+
272
+	oldTag, err := member_service.FindTagByName(adminUserInfo.CurrentOrgId, tagName)
273
+	if err != nil {
274
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "添加标签失败:("+err.Error()+")")
275
+		return
276
+	}
277
+	if oldTag != nil {
278
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "添加标签失败:(已经存在同名的标签)")
279
+		return
280
+	}
281
+	tag.Status = 1
282
+	tag.UserOrgId = adminUserInfo.CurrentOrgId
283
+	tag.CreatedTime = timeNow
284
+	tag.UpdatedTime = timeNow
285
+
286
+	err = member_service.SaveTag(&tag)
287
+	if err != nil {
288
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "添加标签失败:("+err.Error()+")")
289
+		return
290
+	}
291
+
292
+	returnData := make(map[string]interface{}, 0)
293
+	returnData["tag"] = tag
294
+	c.ServeSuccessJSON(returnData)
295
+	return
296
+}
297
+
298
+func (c *TagAPIController) EditTag() {
299
+	id, _ := c.GetInt64("id", 0)
300
+	if id <= 0 {
301
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误:id")
302
+		return
303
+	}
304
+	adminUserInfo := c.GetAdminUserInfo()
305
+	timeNow := time.Now().Unix()
306
+
307
+	dataBody := make(map[string]interface{}, 0)
308
+	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
309
+	if err != nil {
310
+		utils.ErrorLog(err.Error())
311
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误")
312
+		return
313
+	}
314
+
315
+	tag, err := member_service.FindOnlyTagByID(adminUserInfo.CurrentOrgId, id)
316
+	if err != nil {
317
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "编辑标签失败:("+err.Error()+")")
318
+		return
319
+	}
320
+	if tag == nil {
321
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "编辑标签失败:(标签不存在)")
322
+		return
323
+	}
324
+
325
+	if dataBody["tag_name"] == nil || reflect.TypeOf(dataBody["tag_name"]).String() != "string" {
326
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:标签名")
327
+		return
328
+	}
329
+	tagName, _ := dataBody["tag_name"].(string)
330
+	if len(tagName) == 0 {
331
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "标签名不能为空")
332
+		return
333
+	}
334
+	tag.TagName = tagName
335
+
336
+	oldTag, err := member_service.FindTagByName(adminUserInfo.CurrentOrgId, tagName)
337
+	if err != nil {
338
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "编辑标签失败:("+err.Error()+")")
339
+		return
340
+	}
341
+	if oldTag != nil && oldTag.ID != tag.ID {
342
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "编辑标签失败:(已经存在同名的标签)")
343
+		return
344
+	}
345
+	tag.UpdatedTime = timeNow
346
+
347
+	err = member_service.SaveTag(tag)
348
+	if err != nil {
349
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "编辑标签失败:("+err.Error()+")")
350
+		return
351
+	}
352
+
353
+	returnData := make(map[string]interface{}, 0)
354
+	returnData["tag"] = tag
355
+	c.ServeSuccessJSON(returnData)
356
+	return
357
+}
358
+
359
+func (c *TagAPIController) DeleteTag() {
360
+	adminUserInfo := c.GetAdminUserInfo()
361
+
362
+	dataBody := make(map[string]interface{}, 0)
363
+	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
364
+	if err != nil {
365
+		utils.ErrorLog(err.Error())
366
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误")
367
+		return
368
+	}
369
+
370
+	idsInters := dataBody["ids"].([]interface{})
371
+	if len(idsInters) == 0 {
372
+		if err != nil {
373
+			c.ServeFailJsonSend(enums.ErrorCodeDBDelete, "删除标签失败:(没有选择标签)")
374
+			return
375
+		}
376
+	}
377
+
378
+	ids := make([]int64, 0)
379
+	for _, idsInter := range idsInters {
380
+		id := int64(idsInter.(float64))
381
+		ids = append(ids, id)
382
+	}
383
+
384
+	err = member_service.DeleteTags(adminUserInfo.CurrentOrgId, ids)
385
+	if err != nil {
386
+		c.ServeFailJsonSend(enums.ErrorCodeDBDelete, "删除标签失败:("+err.Error()+")")
387
+		return
388
+	}
389
+
390
+	returnData := make(map[string]interface{}, 0)
391
+	returnData["msg"] = "ok"
392
+
393
+	c.ServeSuccessJSON(returnData)
394
+	return
395
+}

+ 351 - 0
controllers/micro/micro_controller.go View File

@@ -0,0 +1,351 @@
1
+package micro
2
+
3
+import (
4
+	"SCRM/enums"
5
+	"SCRM/service/micro_service"
6
+	"fmt"
7
+	"github.com/astaxie/beego"
8
+)
9
+
10
+func microRouters() {
11
+	beego.Router("/api/site/getdatabyorgid", &Micro{}, "Get:GetDataByOrgId")
12
+	beego.Router("/api/site/getdatatwo", &Micro{}, "Get:GetDatatwo")
13
+	beego.Router("/api/site/getdatathree", &Micro{}, "Get:GetOfficeDetail")
14
+	beego.Router("/api/site/getdatafour", &Micro{}, "Get:GetDoctorDetail")
15
+	beego.Router("/api/site/getdatafive", &Micro{}, "Get:GetOfficEnviromentDetail")
16
+	beego.Router("/api/site/getarticlelist", &Micro{}, "Get:GetArticlelist")
17
+	beego.Router("/api/site/getactivities", &Micro{}, "Get:GetActivities")
18
+	beego.Router("/api/site/getdatasix", &Micro{}, "Get:GetArticlistDetail")
19
+	beego.Router("/api/site/getdataseven", &Micro{}, "Get:GetActivitesDetail")
20
+	beego.Router("/api/site/getdefalutnavigationdata", &Micro{}, "Get:GetDefalutNavigationData")
21
+	beego.Router("/api/site/getdataeight", &Micro{}, "Get:GetOrderData")
22
+	beego.Router("/api/site/getdatanight", &Micro{}, "Get:GetContactWay")
23
+	beego.Router("/api/site/singleactivitinfo", &Micro{}, "Get:GetActivitDetail")
24
+	beego.Router("/api/site/singlearticleinfo", &Micro{}, "Get:GetArticlesDetail")
25
+	beego.Router("/api/site/singledoctorinfo", &Micro{}, "Get:GetDoctorInfo")
26
+	beego.Router("/api/site/getdata", &Micro{}, "Get:GetData")
27
+	beego.Router("/api/site/getenviromentimages", &Micro{}, "Get:GetEnviromentImages")
28
+	beego.Router("/api/site/getalldoctors", &Micro{}, "Get:GetAllDoctors")
29
+}
30
+
31
+type Micro struct {
32
+	beego.Controller
33
+	//controllers.BaseAPIController
34
+}
35
+
36
+func (this *Micro) ServeFailJsonSend(code int, msg string) {
37
+	this.Data["json"] = enums.MakeFailResponseJSON(msg, code)
38
+	this.ServeJSON()
39
+}
40
+
41
+func (this *Micro) ServeSuccessJSON(data map[string]interface{}) {
42
+	this.Data["json"] = enums.MakeSuccessResponseJSON(data)
43
+	this.ServeJSON()
44
+}
45
+
46
+func (this *Micro) GetDataByOrgId() {
47
+	fmt.Println("我的 ")
48
+	orgid, _ := this.GetInt64("orgid")
49
+	fmt.Println("小明id", orgid)
50
+	model, err := micro_service.GetData(orgid)
51
+	fmt.Println("model是什么", model)
52
+	fmt.Println("err", err)
53
+	if err != nil {
54
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "删除回复成功")
55
+		return
56
+	}
57
+	this.ServeSuccessJSON(map[string]interface{}{
58
+		"patientModels": model,
59
+	})
60
+}
61
+
62
+func (this *Micro) GetData() {
63
+	// fmt.Println("hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh")
64
+	fmt.Println("我的 ")
65
+	orgid, _ := this.GetInt64("orgid")
66
+	fmt.Println("小明id", orgid)
67
+	model, err := micro_service.GetData(orgid)
68
+	fmt.Println("model是什么", model)
69
+	fmt.Println("err", err)
70
+	if err != nil {
71
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "删除回复成功")
72
+		return
73
+	}
74
+	this.ServeSuccessJSON(map[string]interface{}{
75
+		"patientModels": model,
76
+	})
77
+}
78
+
79
+func (this *Micro) GetDatatwo() {
80
+	fmt.Println("获取医院详情")
81
+	id, err := this.GetInt64("id")
82
+	fmt.Println(err)
83
+	fmt.Println("id是什么", id)
84
+	orgid, _ := this.GetInt64("orgid")
85
+	fmt.Println("机构id", orgid)
86
+	hospital, err := micro_service.QueryHispitalDetail(orgid, id)
87
+	if err != nil {
88
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "删除回复成功")
89
+		return
90
+	}
91
+	this.ServeSuccessJSON(map[string]interface{}{
92
+		"hospital": hospital,
93
+	})
94
+}
95
+
96
+func (this *Micro) GetOfficeDetail() {
97
+	id, err := this.GetInt64("id")
98
+	fmt.Println(err)
99
+	fmt.Println("id是什么", id)
100
+	orgid, _ := this.GetInt64("orgid")
101
+	fmt.Println("机构id", orgid)
102
+	offices, err := micro_service.GetOfficeDetail(orgid, id)
103
+	if err != nil {
104
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "删除回复成功")
105
+		return
106
+	}
107
+	this.ServeSuccessJSON(map[string]interface{}{
108
+		"offices": offices,
109
+	})
110
+
111
+}
112
+
113
+func (this *Micro) GetDoctorDetail() {
114
+	id, err := this.GetInt64("id")
115
+	fmt.Println(err)
116
+	fmt.Println("id是什么", id)
117
+	orgid, _ := this.GetInt64("orgid")
118
+	fmt.Println("机构id", orgid)
119
+	editdoctor, err := micro_service.GetDoctorDetail(orgid, id)
120
+	if err != nil {
121
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "删除回复成功")
122
+		return
123
+	}
124
+	this.ServeSuccessJSON(map[string]interface{}{
125
+		"editdoctor": editdoctor,
126
+	})
127
+
128
+}
129
+
130
+func (this *Micro) GetOfficEnviromentDetail() {
131
+	id, err := this.GetInt64("id")
132
+	fmt.Println(err)
133
+	fmt.Println("id是什么", id)
134
+	orgid, _ := this.GetInt64("orgid")
135
+	fmt.Println("机构id", orgid)
136
+	offenvironment, err := micro_service.GetOfficEnviromentDetail(orgid, id)
137
+	fmt.Println("错误", err)
138
+	fmt.Println("offenvironment", offenvironment)
139
+	if err != nil {
140
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "删除回复成功")
141
+		return
142
+	}
143
+	this.ServeSuccessJSON(map[string]interface{}{
144
+		"offenvironment": offenvironment,
145
+	})
146
+}
147
+
148
+func (this *Micro) GetArticlelist() {
149
+	//adminUserInfo := this.GetAdminUserInfo()
150
+	//userOrgID := int64(adminUserInfo.CurrentOrgId)
151
+	//fmt.Println("机构id",userOrgID)
152
+	orgid, _ := this.GetInt64("orgid")
153
+	//micro_service.GetArticlelistlimit(orgid)
154
+	articlelist, err := micro_service.GetlastLimit(orgid)
155
+	articlelists, err := micro_service.GetAllArticeList(orgid, articlelist.Number)
156
+	fmt.Println("文章列表", articlelists)
157
+	fmt.Println("错误", err)
158
+	if err != nil {
159
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "更改数据失败")
160
+		return
161
+	}
162
+	this.ServeSuccessJSON(map[string]interface{}{
163
+		"articlelists": articlelists,
164
+	})
165
+}
166
+
167
+func (this *Micro) GetActivities() {
168
+	orgid, _ := this.GetInt64("orgid")
169
+	fmt.Println("活动id", orgid)
170
+	//addactivity, err := micro_service.GetActivitiesById(orgid)
171
+	addactivity, err := micro_service.GetLastActivitiesLast(orgid)
172
+	activity, err := micro_service.GetAllActivities(orgid, addactivity.Number)
173
+	if err != nil {
174
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "更改数据失败")
175
+		return
176
+	}
177
+	this.ServeSuccessJSON(map[string]interface{}{
178
+		"activity": activity,
179
+	})
180
+}
181
+
182
+func (this *Micro) GetArticlistDetail() {
183
+	id, _ := this.GetInt64("id")
184
+	fmt.Println("id是设么", id)
185
+	orgid, _ := this.GetInt64("orgid")
186
+	fmt.Println("文章id", orgid)
187
+	articlelist, err := micro_service.GetArticlelistById(id, orgid)
188
+	fmt.Println(articlelist, err)
189
+	//fmt.Println(err)
190
+	//articlelists, err := micro_service.GetAllArticles(orgid, articlelist.Number)
191
+	articleslist, err := micro_service.GetAllPushArticles(orgid)
192
+	fmt.Println("报错了么", err)
193
+	if err != nil {
194
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "删除回复成功")
195
+		return
196
+	}
197
+	this.ServeSuccessJSON(map[string]interface{}{
198
+		"articlelists": articleslist,
199
+	})
200
+}
201
+
202
+func (this *Micro) GetActivitesDetail() {
203
+	id, _ := this.GetInt64("id")
204
+	fmt.Println("id是设么", id)
205
+	orgid, _ := this.GetInt64("orgid")
206
+	fmt.Println("活动id", orgid)
207
+	//addactivity, err := micro_service.GetAllActivitiById(id, orgid)
208
+	//	fmt.Println("err",err)
209
+	//addactivity, err := micro_service.GetLastActivitiesLast(orgid)
210
+	//	//activity, err := micro_service.GetAllActivities(orgid,addactivity.Number)
211
+	activity, err := micro_service.GetAllActivitiestwo(orgid)
212
+	if err != nil {
213
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "删除回复成功")
214
+		return
215
+	}
216
+	this.ServeSuccessJSON(map[string]interface{}{
217
+		"activity": activity,
218
+	})
219
+}
220
+
221
+func (this *Micro) GetDefalutNavigationData() {
222
+	orgid, _ := this.GetInt64("orgid")
223
+	fmt.Println("活动id", orgid)
224
+	navigation, err := micro_service.GetDefalutNavigationData(orgid)
225
+	if err != nil {
226
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "删除回复成功")
227
+		return
228
+	}
229
+	this.ServeSuccessJSON(map[string]interface{}{
230
+		"navigation": navigation,
231
+	})
232
+}
233
+
234
+func (this *Micro) GetOrderData() {
235
+	orgid, _ := this.GetInt64("orgid")
236
+	fmt.Println("活动id", orgid)
237
+	ordmodel, err := micro_service.GetOrederModel(orgid)
238
+	fmt.Println("ordemodel是社没什么", ordmodel)
239
+	if err != nil {
240
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "删除回复成功")
241
+		return
242
+	}
243
+	this.ServeSuccessJSON(map[string]interface{}{
244
+		"ordmodel": ordmodel,
245
+	})
246
+}
247
+
248
+func (this *Micro) GetContactWay() {
249
+	orgid, _ := this.GetInt64("orgid")
250
+	fmt.Println("联系方式id", orgid)
251
+	connect, err := micro_service.GetAllConnecway(orgid)
252
+	if err != nil {
253
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "删除回复成功")
254
+		return
255
+	}
256
+	this.ServeSuccessJSON(map[string]interface{}{
257
+		"connect": connect,
258
+	})
259
+}
260
+
261
+func (this *Micro) GetActivitDetail() {
262
+	id, _ := this.GetInt64("id")
263
+	fmt.Println("活动id", id)
264
+	orgid, _ := this.GetInt64("orgid")
265
+	fmt.Println("机构id", orgid)
266
+	activity, err := micro_service.GetActivitDetail(id, orgid)
267
+	if err != nil {
268
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "删除回复成功")
269
+		return
270
+	}
271
+	this.ServeSuccessJSON(map[string]interface{}{
272
+		"activity": activity,
273
+	})
274
+}
275
+
276
+func (this *Micro) GetArticlesDetail() {
277
+	id, _ := this.GetInt64("id")
278
+	fmt.Println("文章id", id)
279
+	orgid, _ := this.GetInt64("orgid")
280
+	fmt.Println("机构id", orgid)
281
+	articles, err := micro_service.GetArticlesDetail(id, orgid)
282
+	if err != nil {
283
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "删除回复成功")
284
+		return
285
+	}
286
+	this.ServeSuccessJSON(map[string]interface{}{
287
+		"articles": articles,
288
+	})
289
+}
290
+
291
+func (this *Micro) GetDoctorInfo() {
292
+	id, _ := this.GetInt64("id")
293
+	fmt.Println("医生id", id)
294
+	orgid, _ := this.GetInt64("orgid")
295
+	fmt.Println("机构id", orgid)
296
+	editdoctor, err := micro_service.GetDoctorInfo(id, orgid)
297
+	fmt.Println("错误", err)
298
+	fmt.Println("editdoctor", editdoctor)
299
+	if err != nil {
300
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "删除回复成功")
301
+		return
302
+	}
303
+	this.ServeSuccessJSON(map[string]interface{}{
304
+		"editdoctor": editdoctor,
305
+	})
306
+}
307
+
308
+func (this *Micro) GetRotationLinkAddress() {
309
+	linkid, _ := this.GetInt64("linkid")
310
+	fmt.Println("linkid", linkid)
311
+	orgid, _ := this.GetInt64("orgid")
312
+	fmt.Println("机构id", orgid)
313
+	linkaddress, err := micro_service.GetRotationLinkAddress(orgid, linkid)
314
+	fmt.Println("错误是什么", err)
315
+	if err != nil {
316
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "删除回复成功")
317
+		return
318
+	}
319
+	this.ServeSuccessJSON(map[string]interface{}{
320
+		"linkaddress": linkaddress,
321
+	})
322
+}
323
+
324
+func (this *Micro) GetEnviromentImages() {
325
+	id, _ := this.GetInt64("id")
326
+	fmt.Println("id是设么", id)
327
+	orgid, _ := this.GetInt64("orgid")
328
+	enviro, err := micro_service.GetEnviromentImages(id, orgid)
329
+	if err != nil {
330
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "删除回复成功")
331
+		return
332
+	}
333
+	this.ServeSuccessJSON(map[string]interface{}{
334
+		"enviro": enviro,
335
+	})
336
+}
337
+
338
+func (this *Micro) GetAllDoctors() {
339
+	orgid, _ := this.GetInt64("orgid")
340
+	fmt.Println("orgid失身东西", orgid)
341
+	info, err := micro_service.GetAllDoctors(orgid)
342
+	fmt.Println("info是什么", info)
343
+	fmt.Println("err是什么", err)
344
+	if err != nil {
345
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "删除回复成功")
346
+		return
347
+	}
348
+	this.ServeSuccessJSON(map[string]interface{}{
349
+		"info": info,
350
+	})
351
+}

+ 5 - 0
controllers/micro/router_collector.go View File

@@ -0,0 +1,5 @@
1
+package micro
2
+
3
+func RegisterRouters() {
4
+	microRouters()
5
+}

+ 179 - 0
controllers/mpwechat/material_controller.go View File

@@ -0,0 +1,179 @@
1
+package mpwechat
2
+
3
+import (
4
+	base_ctl "SCRM/controllers"
5
+	"SCRM/enums"
6
+	"SCRM/models"
7
+	"SCRM/service/wechat_service"
8
+	"bytes"
9
+	"encoding/json"
10
+	"mime/multipart"
11
+	"sync"
12
+	"time"
13
+
14
+	"io"
15
+	"io/ioutil"
16
+
17
+	"github.com/astaxie/beego"
18
+	"github.com/astaxie/beego/httplib"
19
+)
20
+
21
+func MpMaterialCtlRegistRouters() {
22
+	beego.Router("/api/mpwechat/media/add_material", &MpMaterialAPIController{}, "Post:AddMaterial")
23
+	beego.Router("/api/mpwechat/media/material", &MpMaterialAPIController{}, "Get:GetMaterials")
24
+}
25
+
26
+type MpMaterialAPIController struct {
27
+	base_ctl.BaseAuthAPIController
28
+}
29
+
30
+type MultipartFormField struct {
31
+	IsFile   bool
32
+	Name     string
33
+	FileName string
34
+	Value    io.Reader
35
+}
36
+
37
+var mediaBufferPool = sync.Pool{
38
+	New: func() interface{} {
39
+		return bytes.NewBuffer(make([]byte, 0, 10<<20)) // 10MB
40
+	},
41
+}
42
+
43
+func (c MpMaterialAPIController) AddMaterial() {
44
+
45
+	adminUserInfo := c.GetAdminUserInfo()
46
+
47
+	authorization, err := wechat_service.GetAuthorizationByOrgID(adminUserInfo.CurrentOrgId)
48
+	if err != nil {
49
+		c.ServeFailJsonSend(enums.ErrorCodeDataException, "上传失败:("+err.Error()+")")
50
+		return
51
+	}
52
+	if authorization == nil || authorization.AuthorizerStatus != 1 {
53
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:(公众号未授权)")
54
+		return
55
+	}
56
+
57
+	file, head, err := c.GetFile("file")
58
+	if err != nil {
59
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:("+err.Error()+")")
60
+		return
61
+	}
62
+	defer file.Close()
63
+
64
+	var fields = []MultipartFormField{
65
+		{
66
+			IsFile:   true,
67
+			Name:     "media",
68
+			FileName: head.Filename,
69
+			Value:    file,
70
+		},
71
+	}
72
+
73
+	buffer := mediaBufferPool.Get().(*bytes.Buffer)
74
+	buffer.Reset()
75
+	defer mediaBufferPool.Put(buffer)
76
+
77
+	multipartWriter := multipart.NewWriter(buffer)
78
+	for i := 0; i < len(fields); i++ {
79
+		if field := &fields[i]; field.IsFile {
80
+			partWriter, err3 := multipartWriter.CreateFormFile(field.Name, field.FileName)
81
+			if err3 != nil {
82
+				c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:("+err3.Error()+")")
83
+				return
84
+			}
85
+			if _, err3 = io.Copy(partWriter, field.Value); err3 != nil {
86
+				c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:("+err3.Error()+")")
87
+				return
88
+			}
89
+		} else {
90
+			partWriter, err3 := multipartWriter.CreateFormField(field.Name)
91
+			if err3 != nil {
92
+				c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:("+err3.Error()+")")
93
+				return
94
+			}
95
+			if _, err3 = io.Copy(partWriter, field.Value); err3 != nil {
96
+				c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:("+err3.Error()+")")
97
+				return
98
+			}
99
+		}
100
+	}
101
+
102
+	if err = multipartWriter.Close(); err != nil {
103
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:("+err.Error()+")")
104
+		return
105
+	}
106
+	requestBodyBytes := buffer.Bytes()
107
+	requestBodyType := multipartWriter.FormDataContentType()
108
+	url := "https://api.weixin.qq.com/cgi-bin/material/add_material?type=image&access_token=" + authorization.AuthorizerAccessToken
109
+	res := httplib.Post(url)
110
+	res.Header("Content-Type", requestBodyType)
111
+	response, err := res.Body(requestBodyBytes).Response()
112
+	if err != nil {
113
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:("+err.Error()+")")
114
+		return
115
+	}
116
+	respBody, err := ioutil.ReadAll(response.Body)
117
+	if err != nil {
118
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:("+err.Error()+")")
119
+		return
120
+	}
121
+
122
+	var resMaterial wechat_service.ResAddMaterial
123
+	err = json.Unmarshal(respBody, &resMaterial)
124
+	if err != nil {
125
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:("+err.Error()+")")
126
+		return
127
+	}
128
+	if resMaterial.ErrCode != 0 {
129
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:("+resMaterial.ErrMsg+")")
130
+		return
131
+	}
132
+	mediaID := resMaterial.MediaID
133
+	mediaUrl := resMaterial.URL
134
+	var media models.WechatMedias
135
+	media.UserOrgId = adminUserInfo.CurrentOrgId
136
+	media.MediaId = mediaID
137
+	media.MediaUrl = mediaUrl
138
+	media.Msgtype = "image"
139
+	media.MediaTitle = head.Filename
140
+	media.CreatedTime = time.Now().Unix()
141
+	media.UpdatedTime = time.Now().Unix()
142
+	media.MediaStatus = 1
143
+
144
+	err = wechat_service.SaveMaterial(&media)
145
+	if err != nil {
146
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "上传失败:("+err.Error()+")")
147
+		return
148
+	}
149
+
150
+	returnData := make(map[string]interface{}, 0)
151
+	returnData["media"] = media
152
+	c.ServeSuccessJSON(returnData)
153
+	return
154
+}
155
+
156
+func (c *MpMaterialAPIController) GetMaterials() {
157
+	page, _ := c.GetInt64("page", 1)
158
+	limit, _ := c.GetInt64("limit", 10)
159
+	mediaType := c.GetString("media_type")
160
+	if page <= 0 {
161
+		page = 1
162
+	}
163
+	if limit <= 0 {
164
+		limit = 10
165
+	}
166
+
167
+	adminUserInfo := c.GetAdminUserInfo()
168
+	medias, total, err := wechat_service.GetPageMaterials(adminUserInfo.CurrentOrgId, page, limit, mediaType)
169
+	if err != nil {
170
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "拉取失败:("+err.Error()+")")
171
+		return
172
+	}
173
+
174
+	returnData := make(map[string]interface{}, 0)
175
+	returnData["medias"] = medias
176
+	returnData["total"] = total
177
+	c.ServeSuccessJSON(returnData)
178
+	return
179
+}

+ 280 - 0
controllers/mpwechat/menu_controller.go View File

@@ -0,0 +1,280 @@
1
+package mpwechat
2
+
3
+import (
4
+	base_ctl "SCRM/controllers"
5
+	"SCRM/enums"
6
+	"SCRM/models"
7
+	"SCRM/service/wechat_service"
8
+	"time"
9
+
10
+	"encoding/json"
11
+
12
+	"fmt"
13
+	"github.com/astaxie/beego"
14
+)
15
+
16
+func MpMenusCtlRegistRouters() {
17
+	beego.Router("/api/mpwechat/menus", &MpMenusAPIController{}, "Get:GetMenus")
18
+	beego.Router("/api/mpwechat/savemenus", &MpMenusAPIController{}, "Put:SaveMenus")
19
+	beego.Router("/api/mpwechat/deletemenus", &MpMenusAPIController{}, "Post:DeleteMenu")
20
+}
21
+
22
+type MpMenusAPIController struct {
23
+	base_ctl.BaseAuthAPIController
24
+}
25
+
26
+func (c *MpMenusAPIController) GetMenus() {
27
+
28
+	adminUserInfo := c.GetAdminUserInfo()
29
+
30
+	buttons, err := wechat_service.GetOrgMenusWithMsgs(adminUserInfo.CurrentOrgId)
31
+	if err != nil {
32
+		c.ServeFailJsonSend(enums.ErrorCodeDataException, "读取菜单配置信息失败:("+err.Error()+")")
33
+		return
34
+	}
35
+	if buttons != nil && buttons.ButtonStatus != 1 {
36
+		buttons = nil
37
+	}
38
+
39
+	mediaIDs := make([]string, 0)
40
+	var menus wechat_service.SelfMenuInfo
41
+	if buttons != nil {
42
+		err = json.Unmarshal([]byte(buttons.ButtonFileds), &menus)
43
+		if err != nil {
44
+			c.ServeFailJsonSend(enums.ErrorCodeDataException, "解析菜单配置信息失败:("+err.Error()+")")
45
+			return
46
+		}
47
+
48
+		msgMap := make(map[string]string, 0)
49
+		for _, msg := range buttons.Messages {
50
+			msgMap[msg.MessageKeyName] = msg.MessageContent
51
+		}
52
+
53
+		for index, menu := range menus.Button {
54
+			if menu.Type == "media_id" && len(menu.MediaId) > 0 {
55
+				mediaIDs = append(mediaIDs, menu.MediaId)
56
+			}
57
+			if _, exist := msgMap[menu.Key]; exist {
58
+				menus.Button[index].Message = msgMap[menu.Key]
59
+			}
60
+			for sindex, sub := range menus.Button[index].SubButton {
61
+				if sub.Type == "media_id" && len(sub.MediaId) > 0 {
62
+					mediaIDs = append(mediaIDs, sub.MediaId)
63
+				}
64
+
65
+				if _, exist := msgMap[sub.Key]; exist {
66
+					menus.Button[index].SubButton[sindex].Message = msgMap[sub.Key]
67
+				}
68
+			}
69
+		}
70
+		if len(mediaIDs) > 0 {
71
+			medias, err := wechat_service.FindMeterialsByMediaIDs(adminUserInfo.CurrentOrgId, "image", mediaIDs)
72
+			if err != nil {
73
+				c.ServeFailJsonSend(enums.ErrorCodeDataException, "获取菜单信息失败:("+err.Error()+")")
74
+				return
75
+			}
76
+			if len(medias) > 0 {
77
+				mediaMap := make(map[string]string, 0)
78
+				for _, media := range medias {
79
+					mediaMap[media.MediaId] = media.MediaUrl
80
+				}
81
+				for index, menu := range menus.Button {
82
+					if menu.Type == "media_id" && len(menu.MediaId) > 0 {
83
+						if _, exist := mediaMap[menu.MediaId]; exist {
84
+							menus.Button[index].MediaUrl = mediaMap[menu.MediaId]
85
+						}
86
+					}
87
+					for sindex, sub := range menus.Button[index].SubButton {
88
+						if sub.Type == "media_id" && len(sub.MediaId) > 0 {
89
+							if _, exist := mediaMap[sub.MediaId]; exist {
90
+								menus.Button[index].SubButton[sindex].MediaUrl = mediaMap[sub.MediaId]
91
+							}
92
+						}
93
+					}
94
+				}
95
+			}
96
+
97
+		}
98
+
99
+	}
100
+
101
+	returnData := make(map[string]interface{}, 0)
102
+	returnData["buttons"] = buttons
103
+	returnData["menus"] = menus
104
+	c.ServeSuccessJSON(returnData)
105
+	return
106
+}
107
+
108
+func (c *MpMenusAPIController) SaveMenus() {
109
+	adminUserInfo := c.GetAdminUserInfo()
110
+	authorization, err := wechat_service.GetAuthorizationByOrgID(adminUserInfo.CurrentOrgId)
111
+	fmt.Println("authorization是什么", authorization)
112
+	fmt.Println("错误", err)
113
+	if err != nil {
114
+		c.ServeFailJsonSend(enums.ErrorCodeDataException, "保存菜单失败:("+err.Error()+")")
115
+		return
116
+	}
117
+	if authorization == nil || authorization.AuthorizerStatus != 1 {
118
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "保存菜单失败:(未授权)")
119
+		return
120
+	}
121
+
122
+	// 授权方公众号类型,0代表订阅号,1代表由历史老帐号升级后的订阅号,2代表服务号
123
+	// 授权方认证类型,-1代表未认证,0代表微信认证,1代表新浪微博认证,2代表腾讯微博认证,3代表已资质认证通过但还未通过名称认证,4代表已资质认证通过、还未通过名称认证,但通过了新浪微博认证,5代表已资质认证通过、还未通过名称认证,但通过了腾讯微博认证
124
+	if (authorization.AuthorizerServiceTypeInfo == 0 || authorization.AuthorizerServiceTypeInfo == 1) && authorization.AuthorizerVerifyTypeInfo == -1 {
125
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "保存菜单失败:(未认证的订阅号没有自定义菜单的接口权限)")
126
+		return
127
+	}
128
+	var buttons wechat_service.SelfMenuInfo
129
+
130
+	err = json.Unmarshal(c.Ctx.Input.RequestBody, &buttons)
131
+	if err != nil {
132
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "解析菜单失败:("+err.Error()+")")
133
+		return
134
+	}
135
+
136
+	clickMap := make(map[string]string, 0)
137
+	for pindex, button := range buttons.Button {
138
+		if button.Type == "click" && len(button.Key) > 0 && len(button.SubButton) == 0 {
139
+			clickMap[button.Key] = button.Message
140
+		}
141
+		if button.Type != "click" {
142
+			buttons.Button[pindex].Key = ""
143
+		}
144
+		if len(button.SubButton) > 0 {
145
+			for sindex, child := range button.SubButton {
146
+				if child.Type == "click" && len(child.Key) > 0 {
147
+					clickMap[child.Key] = child.Message
148
+				}
149
+				buttons.Button[pindex].SubButton[sindex].Message = ""
150
+
151
+				if child.Type != "click" {
152
+					buttons.Button[pindex].SubButton[sindex].Key = ""
153
+				}
154
+			}
155
+		}
156
+		buttons.Button[pindex].Message = ""
157
+	}
158
+	messages, err := wechat_service.GetOrgAllClickMessages(adminUserInfo.CurrentOrgId)
159
+	if err != nil {
160
+		c.ServeFailJsonSend(enums.ErrorCodeDataException, "保存菜单失败:("+err.Error()+")")
161
+		return
162
+	}
163
+	oldMsgs := make(map[string]models.AuthorizationMessageManagements)
164
+	for _, message := range messages {
165
+		if _, exist := clickMap[message.MessageKeyName]; exist {
166
+			msg := *message
167
+			oldMsgs[message.MessageKeyName] = msg
168
+		}
169
+	}
170
+
171
+	buttonFileds, err := json.Marshal(buttons)
172
+	if err != nil {
173
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "解析菜单失败:("+err.Error()+")")
174
+		return
175
+	}
176
+
177
+	timeNow := time.Now().Unix()
178
+	var saveButton wechat_service.Buttons
179
+	saveButton.UserOrgID = adminUserInfo.CurrentOrgId
180
+	saveButton.UpdatedTime = timeNow
181
+	saveButton.ButtonStatus = 1
182
+	saveButton.SendStatus = 0
183
+	saveButton.ButtonFileds = string(buttonFileds)
184
+
185
+	button, err := wechat_service.GetMenusByOrgID(adminUserInfo.CurrentOrgId)
186
+	if err != nil {
187
+		c.ServeFailJsonSend(enums.ErrorCodeDataException, "保存菜单失败:("+err.Error()+")")
188
+		return
189
+	}
190
+	if button != nil {
191
+		saveButton.ID = button.ID
192
+		saveButton.CreatedTime = button.CreatedTime
193
+	}
194
+
195
+	saveButton.Messages = make([]*models.AuthorizationMessageManagements, 0)
196
+	for keyName, Content := range clickMap {
197
+		var msg models.AuthorizationMessageManagements
198
+		msg.MessageMsgType = "event"
199
+		msg.MessageMsgEvent = "click"
200
+		msg.MessageContent = Content
201
+		msg.UpdatedTime = timeNow
202
+		msg.MessageStatus = 1
203
+		msg.MessageKeyName = keyName
204
+		msg.UserOrgId = adminUserInfo.CurrentOrgId
205
+
206
+		if _, exist := oldMsgs[keyName]; exist {
207
+			msg.ID = oldMsgs[keyName].ID
208
+			msg.CreatedTime = oldMsgs[keyName].CreatedTime
209
+		} else {
210
+			msg.CreatedTime = timeNow
211
+		}
212
+		saveButton.Messages = append(saveButton.Messages, &msg)
213
+	}
214
+
215
+	err = wechat_service.SaveButtons(&saveButton)
216
+	if err != nil {
217
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "保存菜单失败:("+err.Error()+")")
218
+		return
219
+	}
220
+	err = wechat_service.SendMpWechatMenus(authorization.AuthorizerAccessToken, buttonFileds)
221
+	fmt.Println("公众号错误是什么", err)
222
+	if err != nil {
223
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "保存菜单成功,但发布菜单到公众号失败:("+err.Error()+")")
224
+		return
225
+	}
226
+
227
+	returnData := make(map[string]interface{}, 0)
228
+	returnData["buttons"] = buttons
229
+	c.ServeSuccessJSON(returnData)
230
+	return
231
+}
232
+
233
+func (c *MpMenusAPIController) DeleteMenu() {
234
+
235
+	adminUserInfo := c.GetAdminUserInfo()
236
+	authorization, err := wechat_service.GetAuthorizationByOrgID(adminUserInfo.CurrentOrgId)
237
+	if err != nil {
238
+		c.ServeFailJsonSend(enums.ErrorCodeDataException, "删除菜单失败:("+err.Error()+")")
239
+		return
240
+	}
241
+	if authorization == nil || authorization.AuthorizerStatus != 1 {
242
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "删除菜单失败:(未授权)")
243
+		return
244
+	}
245
+
246
+	// 授权方公众号类型,0代表订阅号,1代表由历史老帐号升级后的订阅号,2代表服务号
247
+	// 授权方认证类型,-1代表未认证,0代表微信认证,1代表新浪微博认证,2代表腾讯微博认证,3代表已资质认证通过但还未通过名称认证,4代表已资质认证通过、还未通过名称认证,但通过了新浪微博认证,5代表已资质认证通过、还未通过名称认证,但通过了腾讯微博认证
248
+	if (authorization.AuthorizerServiceTypeInfo == 0 || authorization.AuthorizerServiceTypeInfo == 1) && authorization.AuthorizerVerifyTypeInfo == -1 {
249
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "删除菜单失败:(未认证的订阅号没有自定义菜单相关接口的权限)")
250
+		return
251
+	}
252
+
253
+	button, err := wechat_service.GetMenusByOrgID(adminUserInfo.CurrentOrgId)
254
+	if err != nil {
255
+		c.ServeFailJsonSend(enums.ErrorCodeDataException, "删除菜单失败:("+err.Error()+")")
256
+		return
257
+	}
258
+	if button == nil || button.ButtonStatus != 1 {
259
+		c.ServeFailJsonSend(enums.ErrorCodeDataException, "删除菜单失败:(未设置菜单)")
260
+		return
261
+	}
262
+
263
+	err = wechat_service.DeleteMpWechatMenus(authorization.AuthorizerAccessToken)
264
+	if err != nil {
265
+		c.ServeFailJsonSend(enums.ErrorCodeDataException, "删除菜单失败:("+err.Error()+")")
266
+		return
267
+	}
268
+
269
+	err = wechat_service.DeleteButton(adminUserInfo.CurrentOrgId, button.ID)
270
+	if err != nil {
271
+		c.ServeFailJsonSend(enums.ErrorCodeDataException, "删除菜单失败:("+err.Error()+")")
272
+		return
273
+	}
274
+
275
+	returnData := make(map[string]interface{}, 0)
276
+	returnData["msg"] = "ok"
277
+	c.ServeSuccessJSON(returnData)
278
+	return
279
+
280
+}

+ 52 - 0
controllers/mpwechat/mpwechat_controller.go View File

@@ -0,0 +1,52 @@
1
+package mpwechat
2
+
3
+import (
4
+	base_ctl "SCRM/controllers"
5
+	"SCRM/enums"
6
+	"SCRM/service/wechat_service"
7
+	"SCRM/utils"
8
+	"fmt"
9
+
10
+	"github.com/astaxie/beego"
11
+)
12
+
13
+func MpWechatCtlRegistRouters() {
14
+	beego.Router("/api/mpwechat/authorization", &MpWechatAPIController{}, "Get:GetAuthorizationInfo")
15
+	beego.Router("/api/mpwechat/authurl", &MpWechatAPIController{}, "Get:GetAuthUrl")
16
+}
17
+
18
+type MpWechatAPIController struct {
19
+	base_ctl.BaseAuthAPIController
20
+}
21
+
22
+func (c *MpWechatAPIController) GetAuthorizationInfo() {
23
+
24
+	adminUserInfo := c.GetAdminUserInfo()
25
+
26
+	authorization, err := wechat_service.GetAuthorizationByOrgID(adminUserInfo.CurrentOrgId)
27
+	if err != nil {
28
+		c.ServeFailJsonSend(enums.ErrorCodeDataException, "获取授权信息失败:("+err.Error()+")")
29
+		return
30
+	}
31
+
32
+	returnData := make(map[string]interface{}, 0)
33
+	returnData["authorization"] = authorization
34
+
35
+	c.ServeSuccessJSON(returnData)
36
+	return
37
+
38
+}
39
+
40
+func (c *MpWechatAPIController) GetAuthUrl() {
41
+
42
+	adminUserInfo := c.GetAdminUserInfo()
43
+
44
+	vcode, vtime := utils.GetOrgIdCode(adminUserInfo.CurrentOrgId, 0)
45
+
46
+	url := fmt.Sprintf("%s%s?id=%d&vcode=%s&vtime=%d", beego.AppConfig.String("httpdomain"), "/openwechat/mp/authorization", adminUserInfo.CurrentOrgId, vtime, vcode)
47
+
48
+	returnData := make(map[string]interface{}, 0)
49
+	returnData["url"] = url
50
+	c.ServeSuccessJSON(returnData)
51
+	return
52
+}

+ 318 - 0
controllers/mpwechat/reply_controller.go View File

@@ -0,0 +1,318 @@
1
+package mpwechat
2
+
3
+import (
4
+	base_ctl "SCRM/controllers"
5
+	"SCRM/enums"
6
+	"SCRM/models"
7
+	"SCRM/service/wechat_service"
8
+	"encoding/json"
9
+	"reflect"
10
+
11
+	"SCRM/utils"
12
+	"time"
13
+
14
+	"github.com/astaxie/beego"
15
+)
16
+
17
+func MpReplyCtlRegistRouters() {
18
+	beego.Router("/api/mpwechat/reply/subscribe", &MpReplyAPIController{}, "Get:GetSubscribe")
19
+	beego.Router("/api/mpwechat/reply/subscribe", &MpReplyAPIController{}, "Put:SaveSubscribe")
20
+	beego.Router("/api/mpwechat/reply/kewords", &MpReplyAPIController{}, "Get:GetKeyWordReplys")
21
+	beego.Router("/api/mpwechat/reply/keword", &MpReplyAPIController{}, "Post:CreateKeyWordReply")
22
+	beego.Router("/api/mpwechat/reply/keword", &MpReplyAPIController{}, "Put:EditKeyWordReply")
23
+	beego.Router("/api/mpwechat/replys", &MpReplyAPIController{}, "Delete:DeleteReplys")
24
+}
25
+
26
+type MpReplyAPIController struct {
27
+	base_ctl.BaseAuthAPIController
28
+}
29
+
30
+func (c *MpReplyAPIController) GetSubscribe() {
31
+
32
+	adminUserInfo := c.GetAdminUserInfo()
33
+
34
+	message, err := wechat_service.GetOrgSubscribeReplyMessages(adminUserInfo.CurrentOrgId)
35
+	if err != nil {
36
+		c.ServeFailJsonSend(enums.ErrorCodeDataException, "读取关注回复数据失败:("+err.Error()+")")
37
+		return
38
+	}
39
+
40
+	returnData := make(map[string]interface{}, 0)
41
+	returnData["message"] = message
42
+	c.ServeSuccessJSON(returnData)
43
+	return
44
+}
45
+
46
+func (c *MpReplyAPIController) SaveSubscribe() {
47
+	adminUserInfo := c.GetAdminUserInfo()
48
+	timeNow := time.Now().Unix()
49
+
50
+	dataBody := make(map[string]interface{}, 0)
51
+	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
52
+	if err != nil {
53
+		utils.ErrorLog(err.Error())
54
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误")
55
+		return
56
+	}
57
+
58
+	var saveMessage models.AuthorizationMessageManagements
59
+	message, err := wechat_service.GetOrgSubscribeReplyMessages(adminUserInfo.CurrentOrgId)
60
+	if err != nil {
61
+		c.ServeFailJsonSend(enums.ErrorCodeDataException, "保存失败:("+err.Error()+")")
62
+		return
63
+	}
64
+	if message != nil {
65
+		saveMessage = *message
66
+	} else {
67
+		saveMessage.CreatedTime = timeNow
68
+		saveMessage.MessageMsgType = "event"
69
+		saveMessage.MessageMsgEvent = "subscribe"
70
+		saveMessage.MessageStatus = 1
71
+		saveMessage.UserOrgId = adminUserInfo.CurrentOrgId
72
+	}
73
+
74
+	if dataBody["message_content"] == nil || reflect.TypeOf(dataBody["message_content"]).String() != "string" {
75
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:message_content")
76
+		return
77
+	}
78
+	messageContent, _ := dataBody["message_content"].(string)
79
+	saveMessage.MessageContent = messageContent
80
+	saveMessage.UpdatedTime = timeNow
81
+
82
+	err = wechat_service.SaveMessage(&saveMessage)
83
+	if err != nil {
84
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "保存失败:("+err.Error()+")")
85
+		return
86
+	}
87
+
88
+	returnData := make(map[string]interface{}, 0)
89
+	returnData["message"] = saveMessage
90
+	c.ServeSuccessJSON(returnData)
91
+	return
92
+
93
+}
94
+
95
+func (c *MpReplyAPIController) GetKeyWordReplys() {
96
+	page, _ := c.GetInt64("page", 1)
97
+	limit, _ := c.GetInt64("limit", 10)
98
+	searchKey := c.GetString("search", "")
99
+	if page <= 0 {
100
+		page = 1
101
+	}
102
+	if limit <= 0 {
103
+		limit = 10
104
+	}
105
+
106
+	adminUserInfo := c.GetAdminUserInfo()
107
+	messages, total, err := wechat_service.GetPageKeyWordMessages(adminUserInfo.CurrentOrgId, page, limit, searchKey)
108
+	if err != nil {
109
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "拉取失败:("+err.Error()+")")
110
+		return
111
+	}
112
+
113
+	returnData := make(map[string]interface{}, 0)
114
+	returnData["messages"] = messages
115
+	returnData["total"] = total
116
+	c.ServeSuccessJSON(returnData)
117
+	return
118
+}
119
+
120
+func (c *MpReplyAPIController) CreateKeyWordReply() {
121
+	adminUserInfo := c.GetAdminUserInfo()
122
+	timeNow := time.Now().Unix()
123
+
124
+	dataBody := make(map[string]interface{}, 0)
125
+	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
126
+	if err != nil {
127
+		utils.ErrorLog(err.Error())
128
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误")
129
+		return
130
+	}
131
+
132
+	var message models.AuthorizationMessageManagements
133
+
134
+	if dataBody["message_regular_name"] == nil || reflect.TypeOf(dataBody["message_regular_name"]).String() != "string" {
135
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:message_regular_name")
136
+		return
137
+	}
138
+	messageRegularName, _ := dataBody["message_regular_name"].(string)
139
+	if len(messageRegularName) == 0 {
140
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "规则名称不能为空")
141
+		return
142
+	}
143
+	message.MessageRegularName = messageRegularName
144
+
145
+	if dataBody["message_key_type"] == nil || reflect.TypeOf(dataBody["message_key_type"]).String() != "float64" {
146
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:message_key_type")
147
+		return
148
+	}
149
+	messageKeyType := int64(dataBody["message_key_type"].(float64))
150
+	if messageKeyType != 1 && messageKeyType != 2 {
151
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "模式选择不正确")
152
+		return
153
+	}
154
+	message.MessageKeyType = messageKeyType
155
+
156
+	if dataBody["message_key_name"] == nil || reflect.TypeOf(dataBody["message_key_name"]).String() != "string" {
157
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:message_key_name")
158
+		return
159
+	}
160
+	messageKeyName, _ := dataBody["message_key_name"].(string)
161
+	if len(messageKeyName) == 0 {
162
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "关键字不能为空")
163
+		return
164
+	}
165
+	message.MessageKeyName = messageKeyName
166
+
167
+	if dataBody["message_content"] == nil || reflect.TypeOf(dataBody["message_content"]).String() != "string" {
168
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:message_content")
169
+		return
170
+	}
171
+	messageContent, _ := dataBody["message_content"].(string)
172
+	if len(messageKeyName) == 0 {
173
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "回复内容不能为空")
174
+		return
175
+	}
176
+	message.MessageContent = messageContent
177
+
178
+	message.MessageMsgType = "text"
179
+	message.UpdatedTime = timeNow
180
+	message.CreatedTime = timeNow
181
+	message.MessageStatus = 1
182
+	message.UserOrgId = adminUserInfo.CurrentOrgId
183
+
184
+	err = wechat_service.SaveMessage(&message)
185
+	if err != nil {
186
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "添加回复失败:("+err.Error()+")")
187
+		return
188
+	}
189
+
190
+	returnData := make(map[string]interface{}, 0)
191
+	returnData["message"] = message
192
+	c.ServeSuccessJSON(returnData)
193
+	return
194
+}
195
+
196
+func (c *MpReplyAPIController) EditKeyWordReply() {
197
+	id, _ := c.GetInt64("id", 0)
198
+	if id <= 0 {
199
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误:id")
200
+		return
201
+	}
202
+
203
+	adminUserInfo := c.GetAdminUserInfo()
204
+	timeNow := time.Now().Unix()
205
+
206
+	dataBody := make(map[string]interface{}, 0)
207
+	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
208
+	if err != nil {
209
+		utils.ErrorLog(err.Error())
210
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误")
211
+		return
212
+	}
213
+
214
+	message, err := wechat_service.GetMessageByID(adminUserInfo.CurrentOrgId, id)
215
+	if err != nil {
216
+		c.ServeFailJsonSend(enums.ErrorCodeDataException, "保存失败:("+err.Error()+")")
217
+		return
218
+	}
219
+	if message == nil {
220
+		c.ServeFailJsonSend(enums.ErrorCodeDBUpdate, "保存失败:(回复不存在)")
221
+		return
222
+	}
223
+
224
+	if dataBody["message_regular_name"] == nil || reflect.TypeOf(dataBody["message_regular_name"]).String() != "string" {
225
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:message_regular_name")
226
+		return
227
+	}
228
+	messageRegularName, _ := dataBody["message_regular_name"].(string)
229
+	if len(messageRegularName) == 0 {
230
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "规则名称不能为空")
231
+		return
232
+	}
233
+	message.MessageRegularName = messageRegularName
234
+
235
+	if dataBody["message_key_type"] == nil || reflect.TypeOf(dataBody["message_key_type"]).String() != "float64" {
236
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:message_key_type")
237
+		return
238
+	}
239
+	messageKeyType := int64(dataBody["message_key_type"].(float64))
240
+	if messageKeyType != 1 && messageKeyType != 2 {
241
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "模式选择不正确")
242
+		return
243
+	}
244
+	message.MessageKeyType = messageKeyType
245
+
246
+	if dataBody["message_key_name"] == nil || reflect.TypeOf(dataBody["message_key_name"]).String() != "string" {
247
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:message_key_name")
248
+		return
249
+	}
250
+	messageKeyName, _ := dataBody["message_key_name"].(string)
251
+	if len(messageKeyName) == 0 {
252
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "关键字不能为空")
253
+		return
254
+	}
255
+	message.MessageKeyName = messageKeyName
256
+
257
+	if dataBody["message_content"] == nil || reflect.TypeOf(dataBody["message_content"]).String() != "string" {
258
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "缺少参数:message_content")
259
+		return
260
+	}
261
+	messageContent, _ := dataBody["message_content"].(string)
262
+	if len(messageKeyName) == 0 {
263
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "回复内容不能为空")
264
+		return
265
+	}
266
+	message.MessageContent = messageContent
267
+
268
+	message.UpdatedTime = timeNow
269
+
270
+	err = wechat_service.SaveMessage(message)
271
+	if err != nil {
272
+		c.ServeFailJsonSend(enums.ErrorCodeDBCreate, "编辑回复失败:("+err.Error()+")")
273
+		return
274
+	}
275
+
276
+	returnData := make(map[string]interface{}, 0)
277
+	returnData["message"] = message
278
+	c.ServeSuccessJSON(returnData)
279
+	return
280
+}
281
+
282
+func (c *MpReplyAPIController) DeleteReplys() {
283
+	adminUserInfo := c.GetAdminUserInfo()
284
+
285
+	dataBody := make(map[string]interface{}, 0)
286
+	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
287
+	if err != nil {
288
+		utils.ErrorLog(err.Error())
289
+		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误")
290
+		return
291
+	}
292
+
293
+	idsInters := dataBody["ids"].([]interface{})
294
+	if len(idsInters) == 0 {
295
+		if err != nil {
296
+			c.ServeFailJsonSend(enums.ErrorCodeDBDelete, "删除失败:(没有选择回复)")
297
+			return
298
+		}
299
+	}
300
+
301
+	ids := make([]int64, 0)
302
+	for _, idsInter := range idsInters {
303
+		id := int64(idsInter.(float64))
304
+		ids = append(ids, id)
305
+	}
306
+
307
+	err = wechat_service.DeleteMessages(adminUserInfo.CurrentOrgId, ids)
308
+	if err != nil {
309
+		c.ServeFailJsonSend(enums.ErrorCodeDBDelete, "删除失败:("+err.Error()+")")
310
+		return
311
+	}
312
+
313
+	returnData := make(map[string]interface{}, 0)
314
+	returnData["msg"] = "ok"
315
+
316
+	c.ServeSuccessJSON(returnData)
317
+	return
318
+}

+ 8 - 0
controllers/mpwechat/router_controller.go View File

@@ -0,0 +1,8 @@
1
+package mpwechat
2
+
3
+func RegisterRouters() {
4
+	MpWechatCtlRegistRouters()
5
+	MpMenusCtlRegistRouters()
6
+	MpReplyCtlRegistRouters()
7
+	MpMaterialCtlRegistRouters()
8
+}

+ 43 - 0
controllers/register/reigster_contrller.go View File

@@ -0,0 +1,43 @@
1
+package register
2
+
3
+import (
4
+	"SCRM/enums"
5
+	"SCRM/service/login_service"
6
+	"fmt"
7
+	"github.com/astaxie/beego"
8
+)
9
+
10
+func LoginRouter() {
11
+
12
+	beego.Router("/api/site/gettologin", &LoginManagement{}, "Post:GetToLogin")
13
+}
14
+
15
+type LoginManagement struct {
16
+	beego.Controller
17
+}
18
+
19
+func (this *LoginManagement) ServeFailJsonSend(code int, msg string) {
20
+	this.Data["json"] = enums.MakeFailResponseJSON(msg, code)
21
+	this.ServeJSON()
22
+}
23
+
24
+func (this *LoginManagement) ServeSuccessJSON(data map[string]interface{}) {
25
+	this.Data["json"] = enums.MakeSuccessResponseJSON(data)
26
+	this.ServeJSON()
27
+}
28
+
29
+func (this *LoginManagement) GetToLogin() {
30
+	tel := this.GetString("tel")
31
+	fmt.Println("哈哈tel是设么", tel)
32
+	psd := this.GetString("psd")
33
+	fmt.Println("psd是设么", psd)
34
+	admin, err := login_service.QueryLogin(tel, psd)
35
+	fmt.Println("错误是设么", err)
36
+	if err != nil {
37
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "删除回复成功")
38
+		return
39
+	}
40
+	this.ServeSuccessJSON(map[string]interface{}{
41
+		"admin": admin,
42
+	})
43
+}

+ 5 - 0
controllers/register/router_collector.go View File

@@ -0,0 +1,5 @@
1
+package register
2
+
3
+func RegisterRouter() {
4
+	LoginRouter()
5
+}

+ 336 - 0
controllers/role/admin_controller.go View File

@@ -0,0 +1,336 @@
1
+package role
2
+
3
+import (
4
+	base_ctl "SCRM/controllers"
5
+	"SCRM/enums"
6
+	"SCRM/models"
7
+	"SCRM/service"
8
+	base_service "SCRM/service"
9
+	"SCRM/service/role_service"
10
+	"SCRM/service/sms_service"
11
+	"time"
12
+
13
+	"github.com/astaxie/beego"
14
+)
15
+
16
+func AdminCtlRegistRouters() {
17
+	beego.Router("/api/adminmain", &AdminAPIController{}, "get:AdminMainView")
18
+	beego.Router("/api/admins", &AdminAPIController{}, "get:Admins")
19
+	beego.Router("/api/admin/addinit", &AdminAPIController{}, "get:AddAdminInitData")
20
+	beego.Router("/api/admin/add", &AdminAPIController{}, "post:AddAdmin")
21
+	beego.Router("/api/admin/editinit", &AdminAPIController{}, "get:EditAdminInitData")
22
+	beego.Router("/api/admin/edit", &AdminAPIController{}, "post:EditAdmin")
23
+	beego.Router("/api/admin/setstatus", &AdminAPIController{}, "post:AdminSetStatus")
24
+}
25
+
26
+type AdminAPIController struct {
27
+	base_ctl.BaseAuthAPIController
28
+}
29
+
30
+// /api/adminmain [get]
31
+func (this *AdminAPIController) AdminMainView() {
32
+	adminUserInfo := this.GetAdminUserInfo()
33
+	if adminUserInfo.AdminUser.IsSuperAdmin == false {
34
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePermissionDenied)
35
+		return
36
+	}
37
+
38
+	viewModels, total, getAdminsErr := role_service.GetAdminUsersAndLoginInfo(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, 1, 10)
39
+	if getAdminsErr != nil {
40
+		this.ErrorLog("获取管理员列表失败:", getAdminsErr)
41
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
42
+		return
43
+	}
44
+
45
+	existRoleCount, _ := role_service.GetValidRoleCount(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, adminUserInfo.AdminUser.Id)
46
+
47
+	this.ServeSuccessJSON(map[string]interface{}{
48
+		"admins":        viewModels,
49
+		"total_count":   total,
50
+		"is_exist_role": existRoleCount > 0,
51
+	})
52
+}
53
+
54
+// /api/admins [get]
55
+// @param page?:int
56
+func (this *AdminAPIController) Admins() {
57
+	adminUserInfo := this.GetAdminUserInfo()
58
+	if adminUserInfo.AdminUser.IsSuperAdmin == false {
59
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePermissionDenied)
60
+		return
61
+	}
62
+
63
+	page, _ := this.GetInt("page")
64
+	viewModels, total, getAdminsErr := role_service.GetAdminUsersAndLoginInfo(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, page, 10)
65
+	if getAdminsErr != nil {
66
+		this.ErrorLog("获取管理员列表失败:", getAdminsErr)
67
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
68
+	} else {
69
+		this.ServeSuccessJSON(map[string]interface{}{
70
+			"admins":      viewModels,
71
+			"total_count": total,
72
+		})
73
+	}
74
+}
75
+
76
+// /api/admin/addinit [get]
77
+func (this *AdminAPIController) AddAdminInitData() {
78
+	adminUserInfo := this.GetAdminUserInfo()
79
+	if adminUserInfo.AdminUser.IsSuperAdmin == false {
80
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePermissionDenied)
81
+		return
82
+	}
83
+
84
+	roles, getRoleErr := role_service.GetAllValidRoles(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId)
85
+	if getRoleErr != nil {
86
+		this.ErrorLog("获取所有角色失败:", getRoleErr)
87
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
88
+		return
89
+	}
90
+
91
+	redisClient := service.RedisClient()
92
+	defer redisClient.Close()
93
+	qntoken, _ := redisClient.Get("qn_token").Result()
94
+
95
+	this.ServeSuccessJSON(map[string]interface{}{
96
+		"roles":   roles,
97
+		"qntoken": qntoken,
98
+	})
99
+}
100
+
101
+// /api/admin/add [post]
102
+// @param mobile:string
103
+// @param name:string
104
+// @param type:int 管理员类型:2.医生 3.护士 4.运营
105
+// @param title:int 用户职称(1.医士;2.医师;3.住院医师;4.主治医师;5.副主任医师;6.主任医师;7.护士;8.护师;9.主管护师;10.副主任护师;11.主任护师;12.运营专员;13.运营主管)
106
+// @param role:int
107
+// @param intro?:string
108
+func (this *AdminAPIController) AddAdmin() {
109
+	adminUserInfo := this.GetAdminUserInfo()
110
+	if adminUserInfo.AdminUser.IsSuperAdmin == false {
111
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePermissionDenied)
112
+		return
113
+	}
114
+
115
+	mobile := this.GetString("mobile")
116
+	name := this.GetString("name")
117
+	userType, _ := this.GetInt("type")
118
+	userTitle, _ := this.GetInt("title")
119
+	roleId, _ := this.GetInt64("role")
120
+	intro := this.GetString("intro")
121
+
122
+	_, titleExist := models.UserTitle[userTitle]
123
+	if len(mobile) == 0 || len(name) == 0 || (userType != 2 && userType != 3 && userType != 4) || !titleExist || roleId <= 0 {
124
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
125
+		return
126
+	}
127
+
128
+	isRoleExist, getRoleErr := role_service.IsRoleExist(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, roleId)
129
+	if getRoleErr != nil {
130
+		this.ErrorLog("查询角色是否存在时失败:", getRoleErr)
131
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
132
+		return
133
+	}
134
+	if !isRoleExist {
135
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeRoleNotExist)
136
+		return
137
+	}
138
+
139
+	// 判断该应用是否已存在该手机号
140
+	if isMobileDidUsed, err := role_service.IsMobileDidUsedAtApp(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, mobile); err != nil {
141
+		this.ErrorLog("查询用户是否已被添加为管理员时失败:", err)
142
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
143
+		return
144
+	} else {
145
+		if isMobileDidUsed {
146
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeMobileDidUsedInApp)
147
+			return
148
+		}
149
+	}
150
+
151
+	if isSuperAdmin, err := role_service.IsUserSuperAdminWithMobile(mobile); err != nil {
152
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeMobileNotExit)
153
+		return
154
+	} else {
155
+		if isSuperAdmin {
156
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeRoleMobileIsSuperAdmin)
157
+			return
158
+		}
159
+	}
160
+
161
+	_, password, createErr := role_service.CreateGeneralAdminUser(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, mobile, name, userType, userTitle, intro, roleId)
162
+	if createErr != nil {
163
+		this.ErrorLog("创建管理员失败:", createErr)
164
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBCreate)
165
+		return
166
+
167
+	} else {
168
+		this.TraceLog("%v", password)
169
+		// 发送短信通知这个手机号
170
+		sendSMSErr := sms_service.SMSSendInviteMobileToJoinOrgAdmin(name, mobile, password)
171
+		if sendSMSErr != nil {
172
+			this.ErrorLog("发送邀请短信失败:%v", sendSMSErr)
173
+		}
174
+
175
+		this.ServeSuccessJSON(nil)
176
+		return
177
+	}
178
+}
179
+
180
+// /api/admin/editinit [get]
181
+// @param uid:int
182
+func (this *AdminAPIController) EditAdminInitData() {
183
+	adminUserInfo := this.GetAdminUserInfo()
184
+	if adminUserInfo.AdminUser.IsSuperAdmin == false {
185
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePermissionDenied)
186
+		return
187
+	}
188
+
189
+	admin_user_id, _ := this.GetInt64("uid")
190
+	if admin_user_id <= 0 {
191
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
192
+		return
193
+	}
194
+
195
+	adminUserViewModel, getInfoErr := role_service.GetGeneralAdminUser(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, admin_user_id)
196
+	if getInfoErr != nil {
197
+		this.ErrorLog("获取管理员信息失败:", getInfoErr)
198
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
199
+		return
200
+	}
201
+	if adminUserViewModel == nil {
202
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAdminUserNotExist)
203
+		return
204
+	}
205
+
206
+	roles, getRoleErr := role_service.GetAllValidRoles(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId)
207
+	if getRoleErr != nil {
208
+		this.ErrorLog("获取所有角色失败:", getRoleErr)
209
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
210
+		return
211
+	}
212
+
213
+	redisClient := base_service.RedisClient()
214
+	defer redisClient.Close()
215
+	qntoken, _ := redisClient.Get("qn_token").Result()
216
+
217
+	this.ServeSuccessJSON(map[string]interface{}{
218
+		"admin":   adminUserViewModel,
219
+		"roles":   roles,
220
+		"qntoken": qntoken,
221
+	})
222
+}
223
+
224
+// /api/admin/edit [post]
225
+// @param uid:int
226
+// @param name:string
227
+// @param type:int
228
+// @param title:int
229
+// @param role:int
230
+// @param intro?:string
231
+func (this *AdminAPIController) EditAdmin() {
232
+	adminUserInfo := this.GetAdminUserInfo()
233
+	if adminUserInfo.AdminUser.IsSuperAdmin == false {
234
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePermissionDenied)
235
+		return
236
+	}
237
+
238
+	adminUserId, _ := this.GetInt64("uid")
239
+	name := this.GetString("name")
240
+	userType, _ := this.GetInt("type")
241
+	userTitle, _ := this.GetInt("title")
242
+	roleId, _ := this.GetInt64("role")
243
+	intro := this.GetString("intro")
244
+
245
+	_, titleExist := models.UserTitle[userTitle]
246
+	if adminUserId <= 0 || len(name) == 0 || (userType != 2 && userType != 3 && userType != 4) || !titleExist || roleId <= 0 {
247
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
248
+		return
249
+	}
250
+
251
+	appRole, getAppRoleErr := role_service.GetAppRole(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, adminUserId)
252
+	if getAppRoleErr != nil {
253
+		this.ErrorLog("查询管理员信息时失败:", getAppRoleErr)
254
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
255
+		return
256
+	}
257
+	if appRole == nil {
258
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAdminUserNotExist)
259
+		return
260
+	}
261
+
262
+	isRoleExist, getRoleErr := role_service.IsRoleExist(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, roleId)
263
+	if getRoleErr != nil {
264
+		this.ErrorLog("查询角色是否存在时失败:", getRoleErr)
265
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
266
+		return
267
+	}
268
+	if !isRoleExist {
269
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeRoleNotExist)
270
+		return
271
+	}
272
+
273
+	appRole.UserName = name
274
+	appRole.UserType = int8(userType)
275
+	appRole.UserTitle = int8(userTitle)
276
+	appRole.RoleId = roleId
277
+	appRole.Intro = intro
278
+	appRole.ModifyTime = time.Now().Unix()
279
+	saveErr := role_service.SaveAppRole(appRole)
280
+	if saveErr != nil {
281
+		this.ErrorLog("修改App_Role失败:", saveErr)
282
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
283
+
284
+	} else {
285
+		this.ServeSuccessJSON(nil)
286
+	}
287
+}
288
+
289
+// /api/admin/setstatus [post]
290
+// @param uid:int
291
+// @param enable:bool
292
+func (this *AdminAPIController) AdminSetStatus() {
293
+	adminUserInfo := this.GetAdminUserInfo()
294
+	if adminUserInfo.AdminUser.IsSuperAdmin == false {
295
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePermissionDenied)
296
+		return
297
+	}
298
+
299
+	userID, _ := this.GetInt64("uid")
300
+	if userID <= 0 {
301
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
302
+		return
303
+	}
304
+	appRole, getAppRoleErr := role_service.GetAppRole(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, userID)
305
+	if getAppRoleErr != nil {
306
+		this.ErrorLog("查询管理员信息失败:", getAppRoleErr)
307
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
308
+		return
309
+	} else if appRole == nil {
310
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAdminUserNotExist)
311
+		return
312
+	}
313
+
314
+	enable, _ := this.GetBool("enable")
315
+	if enable == true {
316
+		if roleEnable, _ := role_service.IsRoleExist(appRole.OrgId, appRole.AppId, appRole.RoleId); roleEnable == false {
317
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeRoleNotExist)
318
+			return
319
+		}
320
+	}
321
+
322
+	if enable {
323
+		appRole.Status = 1
324
+	} else {
325
+		appRole.Status = 0
326
+	}
327
+	appRole.ModifyTime = time.Now().Unix()
328
+	saveErr := role_service.SaveAppRole(appRole)
329
+	if saveErr != nil {
330
+		this.ErrorLog("保存AppRole失败:", saveErr)
331
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
332
+
333
+	} else {
334
+		this.ServeSuccessJSON(nil)
335
+	}
336
+}

+ 227 - 0
controllers/role/role_controller.go View File

@@ -0,0 +1,227 @@
1
+package role
2
+
3
+import (
4
+	base_ctl "SCRM/controllers"
5
+	"SCRM/enums"
6
+	"SCRM/service/role_service"
7
+	"time"
8
+
9
+	"github.com/astaxie/beego"
10
+)
11
+
12
+func RoleCtlRegistRouters() {
13
+	beego.Router("/api/roles", &RoleAPIController{}, "get:GetRoles")
14
+	beego.Router("/api/role/create", &RoleAPIController{}, "post:CreateRole")
15
+	beego.Router("/api/role/modify", &RoleAPIController{}, "post:ModifyRole")
16
+	beego.Router("/api/role/setstatus", &RoleAPIController{}, "post:ModifyRoleStatus")
17
+
18
+	beego.Router("/role/purview/editinit", &RoleAPIController{}, "get:EditPurviewInitData")
19
+	beego.Router("/role/purview/edit", &RoleAPIController{}, "post:EditPurview")
20
+}
21
+
22
+type RoleAPIController struct {
23
+	base_ctl.BaseAuthAPIController
24
+}
25
+
26
+// /api/roles [get]
27
+// @param page?:int
28
+func (this *RoleAPIController) GetRoles() {
29
+	page, _ := this.GetInt("page")
30
+	adminUserInfo := this.GetAdminUserInfo()
31
+	//beego.Alert(adminUserInfo.AdminUser)
32
+	if adminUserInfo.AdminUser.IsSuperAdmin == false {
33
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePermissionDenied)
34
+		return
35
+	}
36
+
37
+	if page <= 0 {
38
+		page = 1
39
+	}
40
+	roles, total, getRoleErr := role_service.GetRoles(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, page, 10)
41
+	if getRoleErr != nil {
42
+		//beego.Error("获取角色列表失败:", getRoleErr)
43
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
44
+	} else {
45
+		this.ServeSuccessJSON(map[string]interface{}{
46
+			"roles":       roles,
47
+			"total_count": total,
48
+		})
49
+	}
50
+}
51
+
52
+// /api/role/create [post]
53
+// @param name:string
54
+// @param intro:string
55
+func (this *RoleAPIController) CreateRole() {
56
+	name := this.GetString("name")
57
+	intro := this.GetString("intro")
58
+	if len(name) == 0 || len(intro) == 0 {
59
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
60
+		return
61
+	}
62
+	adminUserInfo := this.GetAdminUserInfo()
63
+	if adminUserInfo.AdminUser.IsSuperAdmin == false {
64
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePermissionDenied)
65
+		return
66
+	}
67
+
68
+	role, createErr := role_service.CreateRole(adminUserInfo.AdminUser.Id, adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, name, intro)
69
+	if createErr != nil {
70
+		//beego.Error("创建角色失败:", createErr)
71
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBCreate)
72
+	} else {
73
+		this.ServeSuccessJSON(map[string]interface{}{
74
+			"id":     role.Id,
75
+			"name":   role.RoleName,
76
+			"intro":  role.RoleIntro,
77
+			"status": role.Status,
78
+		})
79
+	}
80
+}
81
+
82
+// /api/role/modify
83
+// @param role_id:int
84
+// @param name:string
85
+// @param intro:string
86
+func (this *RoleAPIController) ModifyRole() {
87
+	roleID, _ := this.GetInt64("role_id")
88
+	name := this.GetString("name")
89
+	intro := this.GetString("intro")
90
+	if roleID <= 0 || len(name) == 0 || len(intro) == 0 {
91
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
92
+		return
93
+	}
94
+	adminUserInfo := this.GetAdminUserInfo()
95
+	if adminUserInfo.AdminUser.IsSuperAdmin == false {
96
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePermissionDenied)
97
+		return
98
+	}
99
+
100
+	role, getRoleErr := role_service.GetRoleByRoleID(roleID)
101
+	if getRoleErr != nil {
102
+		//beego.Error("获取角色失败:", getRoleErr)
103
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
104
+		return
105
+	} else if role == nil {
106
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeRoleNotExist)
107
+		return
108
+	}
109
+
110
+	role.RoleName = name
111
+	role.RoleIntro = intro
112
+	role.ModifyTime = time.Now().Unix()
113
+	saveErr := role_service.ModifyRole(role)
114
+	if saveErr != nil {
115
+		//beego.Error("修改角色失败:", role.Id, saveErr)
116
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
117
+	} else {
118
+		this.ServeSuccessJSON(nil)
119
+	}
120
+}
121
+
122
+// /api/role/setstatus
123
+// @param role_id:int
124
+// @param enable:bool
125
+func (this *RoleAPIController) ModifyRoleStatus() {
126
+	roleID, _ := this.GetInt64("role_id")
127
+	enable, _ := this.GetBool("enable")
128
+	if roleID <= 0 {
129
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
130
+		return
131
+	}
132
+
133
+	adminUserInfo := this.GetAdminUserInfo()
134
+	if adminUserInfo.AdminUser.IsSuperAdmin == false {
135
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePermissionDenied)
136
+		return
137
+	}
138
+
139
+	role, getRoleErr := role_service.GetRoleByRoleID(roleID)
140
+	if getRoleErr != nil {
141
+		//beego.Error("获取角色失败:", getRoleErr)
142
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
143
+		return
144
+	} else if role == nil {
145
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeRoleNotExist)
146
+		return
147
+	}
148
+
149
+	if enable == false {
150
+		if count, _ := role_service.RoleAdminUserCount(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, roleID); count != 0 {
151
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCannotRemoveRole)
152
+			return
153
+		}
154
+	}
155
+
156
+	if enable {
157
+		role.Status = 1
158
+	} else {
159
+		role.Status = 2
160
+	}
161
+	role.ModifyTime = time.Now().Unix()
162
+	saveErr := role_service.ModifyRole(role)
163
+	if saveErr != nil {
164
+		//beego.Error("修改角色失败:", role.Id, saveErr)
165
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
166
+	} else {
167
+		this.ServeSuccessJSON(nil)
168
+	}
169
+}
170
+
171
+// /role/purview/editinit [get]
172
+// @param role_id:int
173
+func (this *RoleAPIController) EditPurviewInitData() {
174
+	adminUserInfo := this.GetAdminUserInfo()
175
+	if adminUserInfo.AdminUser.IsSuperAdmin == false {
176
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePermissionDenied)
177
+		return
178
+	}
179
+
180
+	roleId, _ := this.GetInt64("role_id")
181
+	if roleId <= 0 {
182
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
183
+		return
184
+	}
185
+	purviews, getPurviewsErr := role_service.GetAllGeneralPurviewVMsProcessed()
186
+	if getPurviewsErr != nil {
187
+		//beego.Error("获取所有权限时出错:", getPurviewsErr)
188
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
189
+		return
190
+	}
191
+	rolePurviewIdStr, getRPIdsErr := role_service.GetRolePurviewIds(roleId)
192
+	if getRPIdsErr != nil {
193
+		//beego.Error("获取角色的权限时出错:", getRPIdsErr)
194
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
195
+		return
196
+	}
197
+
198
+	this.ServeSuccessJSON(map[string]interface{}{
199
+		"purviews":         purviews,
200
+		"role_purview_ids": rolePurviewIdStr,
201
+	})
202
+}
203
+
204
+// /role/purview/edit [post]
205
+// @param role_id:int
206
+// @param purview_ids:string
207
+func (this *RoleAPIController) EditPurview() {
208
+	adminUserInfo := this.GetAdminUserInfo()
209
+	if adminUserInfo.AdminUser.IsSuperAdmin == false {
210
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePermissionDenied)
211
+		return
212
+	}
213
+	roleId, _ := this.GetInt64("role_id")
214
+	purviewIds := this.GetString("purview_ids")
215
+	if roleId <= 0 {
216
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
217
+		return
218
+	}
219
+
220
+	err := role_service.SaveRolePurviewIds(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, roleId, purviewIds)
221
+	if err != nil {
222
+		//beego.Error("设置角色的权限时出错:", err)
223
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
224
+	} else {
225
+		this.ServeSuccessJSON(nil)
226
+	}
227
+}

+ 6 - 0
controllers/role/router_collector.go View File

@@ -0,0 +1,6 @@
1
+package role
2
+
3
+func RegisterRouters() {
4
+	RoleCtlRegistRouters()
5
+	AdminCtlRegistRouters()
6
+}

+ 5 - 0
controllers/site/router_collector.go View File

@@ -0,0 +1,5 @@
1
+package site
2
+
3
+func RegisterRouters() {
4
+	siteRouters()
5
+}

File diff suppressed because it is too large
+ 5484 - 0
controllers/site/site_controller.go


+ 5 - 0
controllers/sms/router_collector.go View File

@@ -0,0 +1,5 @@
1
+package sms
2
+
3
+func RegisterRouters() {
4
+	SMSCtlRegistRouters()
5
+}

+ 236 - 0
controllers/sms/sms_controller.go View File

@@ -0,0 +1,236 @@
1
+package sms
2
+
3
+import (
4
+	base_ctl "SCRM/controllers"
5
+	"SCRM/enums"
6
+	"SCRM/service/marketing_tool_service"
7
+	"SCRM/service/member_service"
8
+	"SCRM/service/sms_service"
9
+	"fmt"
10
+	"strings"
11
+
12
+	"github.com/astaxie/beego"
13
+)
14
+
15
+func SMSCtlRegistRouters() {
16
+	beego.Router("/api/sms/records", &SMSController{}, "get:GetSendRecords")
17
+	beego.Router("/api/sms/sendinit", &SMSController{}, "get:SendInitData")
18
+	beego.Router("/api/sms/tagfiltercount", &SMSController{}, "get:TagFilterCustomerCount")
19
+
20
+	beego.Router("/api/sms/send2all", &SMSController{}, "post:Send2AllCustomers")
21
+	beego.Router("/api/sms/send2tag", &SMSController{}, "post:Send2TagCustomers")
22
+	beego.Router("/api/sms/send2specific", &SMSController{}, "post:Send2SpecificCustomers")
23
+}
24
+
25
+type SMSController struct {
26
+	base_ctl.BaseAuthAPIController
27
+}
28
+
29
+// /api/sms/records [get]
30
+// @param page:int
31
+func (this *SMSController) GetSendRecords() {
32
+	page, _ := this.GetInt("page")
33
+	if page <= 0 {
34
+		page = 1
35
+	}
36
+
37
+	adminUserInfo := this.GetAdminUserInfo()
38
+	records, total, getRecordErr := sms_service.GetBatchSendRecords(adminUserInfo.CurrentOrgId, page, 10)
39
+	if getRecordErr != nil {
40
+		this.ErrorLog("获取短信批次记录失败:%v", getRecordErr)
41
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
42
+		return
43
+	}
44
+
45
+	this.ServeSuccessJSON(map[string]interface{}{
46
+		"records": records,
47
+		"total":   total,
48
+	})
49
+}
50
+
51
+// /api/sms/sendinit [get]
52
+// @param action?:int 事件类型 1.活动
53
+// @param id?:int 事件对应的id,如活动id
54
+func (this *SMSController) SendInitData() {
55
+	adminUserInfo := this.GetAdminUserInfo()
56
+	tags, getTagErr := member_service.GetTagList(adminUserInfo.CurrentOrgId)
57
+	if getTagErr != nil {
58
+		this.ErrorLog("获取标签失败:%v", getTagErr)
59
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
60
+		return
61
+	}
62
+
63
+	action, _ := this.GetInt("action")
64
+	id, _ := this.GetInt64("id")
65
+	defaultSMSContent := ""
66
+	if id > 0 {
67
+		if action == 1 {
68
+			activity, _ := marketing_tool_service.GetActivityWithID(adminUserInfo.CurrentOrgId, id)
69
+			if activity != nil { // 因为 defaultSMSContent 不是必须的,所以不理会出现的错误
70
+				shareObj, _ := marketing_tool_service.GetActivityWxShareByActivityID(id)
71
+				if shareObj != nil {
72
+					defaultSMSContent = fmt.Sprintf("给您分享一个活动,点击参与:%v", shareObj.ShortURL)
73
+				}
74
+			}
75
+		}
76
+	}
77
+
78
+	this.ServeSuccessJSON(map[string]interface{}{
79
+		"tags":            tags,
80
+		"default_content": defaultSMSContent,
81
+	})
82
+}
83
+
84
+// /api/sms/tagfiltercount [get]
85
+// @param tags:string tag_id 以逗号隔开 (1,2,4)
86
+func (this *SMSController) TagFilterCustomerCount() {
87
+	tagIDsStr := this.GetString("tags")
88
+	fmt.Println("tagIDsStr是什么", tagIDsStr)
89
+	if len(tagIDsStr) == 0 {
90
+		this.ServeSuccessJSON(map[string]interface{}{
91
+			"count": 0,
92
+		})
93
+		return
94
+	}
95
+	tagIDs := strings.Split(tagIDsStr, ",")
96
+	fmt.Println("tagIDs是什么", tagIDs)
97
+	count, getCountErr := member_service.GetTagUsersCountWithMobileByTagIDs(tagIDs)
98
+	fmt.Println("count是什么", count)
99
+	fmt.Println("getCountErr是什么", getCountErr)
100
+	if getCountErr != nil {
101
+		this.ErrorLog("获取标签人数失败:%v", getCountErr)
102
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
103
+		return
104
+	}
105
+	this.ServeSuccessJSON(map[string]interface{}{
106
+		"count": count,
107
+	})
108
+}
109
+
110
+// /api/sms/send2all [post]
111
+// @param content:string
112
+func (this *SMSController) Send2AllCustomers() {
113
+	content := this.GetString("content")
114
+	if len(content) == 0 || strings.Contains(content, "【") || strings.Contains(content, "】") {
115
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
116
+		return
117
+	}
118
+
119
+	adminUserInfo := this.GetAdminUserInfo()
120
+	customers, getCustomerErr := member_service.GetAllCustomersWithMobile(adminUserInfo.CurrentOrgId)
121
+	if getCustomerErr != nil {
122
+		this.ErrorLog("获取所有客户失败:%v", getCustomerErr)
123
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
124
+		return
125
+	} else if len(customers) == 0 {
126
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSMSNoCustomer)
127
+		return
128
+	}
129
+
130
+	mobiles := make([]string, 0, len(customers))
131
+	for _, customer := range customers {
132
+		mobiles = append(mobiles, customer.Mobile)
133
+	}
134
+
135
+	sendErr := sms_service.SMSOrgSendWithCustomContent(adminUserInfo.CurrentOrgId, content, mobiles)
136
+	if sendErr != nil {
137
+		if sendErr == sms_service.SMSErrorFreeLimitInsufficient {
138
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSMSLimitInsufficient)
139
+			return
140
+		} else {
141
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
142
+			return
143
+		}
144
+	} else {
145
+		this.ServeSuccessJSON(nil)
146
+	}
147
+}
148
+
149
+// /api/sms/send2tag [post]
150
+// @param content:string
151
+// @param tags:string 标签id以逗号隔开 (1,2,43)
152
+func (this *SMSController) Send2TagCustomers() {
153
+	content := this.GetString("content")
154
+	fmt.Println("内容", content)
155
+	tagIDsStr := this.GetString("tags")
156
+	fmt.Println("tagIDsStr是什么", tagIDsStr)
157
+	if len(content) == 0 || strings.Contains(content, "【") || strings.Contains(content, "】") || len(tagIDsStr) == 0 {
158
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
159
+		return
160
+	}
161
+
162
+	tagIDs := strings.Split(tagIDsStr, ",")
163
+	fmt.Println("tagIDS是什么", tagIDs)
164
+	adminUserInfo := this.GetAdminUserInfo()
165
+	customers, getCustomerErr := member_service.GetTagCustomersWithMobileByTagIDs(adminUserInfo.CurrentOrgId, tagIDs)
166
+	fmt.Println("customers是什么", customers)
167
+	fmt.Println("错误是什么", getCustomerErr)
168
+	if getCustomerErr != nil {
169
+		this.ErrorLog("获取标签指定客户失败:%v", getCustomerErr)
170
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
171
+		return
172
+	} else if len(customers) == 0 {
173
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSMSNoCustomer)
174
+		return
175
+	}
176
+
177
+	mobiles := make([]string, 0, len(customers))
178
+	for _, customer := range customers {
179
+		mobiles = append(mobiles, customer.Mobile)
180
+	}
181
+
182
+	sendErr := sms_service.SMSOrgSendWithCustomContent(adminUserInfo.CurrentOrgId, content, mobiles)
183
+	if sendErr != nil {
184
+		if sendErr == sms_service.SMSErrorFreeLimitInsufficient {
185
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSMSLimitInsufficient)
186
+			return
187
+		} else {
188
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
189
+			return
190
+		}
191
+	} else {
192
+		this.ServeSuccessJSON(nil)
193
+	}
194
+}
195
+
196
+// /api/sms/send2specific [post]
197
+// @param content:string
198
+// @param ids:string customer_id以逗号隔开 (4,11)
199
+func (this *SMSController) Send2SpecificCustomers() {
200
+	content := this.GetString("content")
201
+	customerIDsStr := this.GetString("ids")
202
+	if len(content) == 0 || strings.Contains(content, "【") || strings.Contains(content, "】") || len(customerIDsStr) == 0 {
203
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
204
+		return
205
+	}
206
+
207
+	customerIDs := strings.Split(customerIDsStr, ",")
208
+	adminUserInfo := this.GetAdminUserInfo()
209
+	customers, getCustomerErr := member_service.GetSpecificCustomersWithMobile(adminUserInfo.CurrentOrgId, customerIDs)
210
+	if getCustomerErr != nil {
211
+		this.ErrorLog("获取指定客户失败:%v", getCustomerErr)
212
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
213
+		return
214
+	} else if len(customers) == 0 {
215
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSMSNoCustomer)
216
+		return
217
+	}
218
+
219
+	mobiles := make([]string, 0, len(customers))
220
+	for _, customer := range customers {
221
+		mobiles = append(mobiles, customer.Mobile)
222
+	}
223
+
224
+	sendErr := sms_service.SMSOrgSendWithCustomContent(adminUserInfo.CurrentOrgId, content, mobiles)
225
+	if sendErr != nil {
226
+		if sendErr == sms_service.SMSErrorFreeLimitInsufficient {
227
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSMSLimitInsufficient)
228
+			return
229
+		} else {
230
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
231
+			return
232
+		}
233
+	} else {
234
+		this.ServeSuccessJSON(nil)
235
+	}
236
+}

+ 5 - 0
controllers/staff/router_collector.go View File

@@ -0,0 +1,5 @@
1
+package staff
2
+
3
+func RegisterRouters() {
4
+	staffRouters()
5
+}

+ 290 - 0
controllers/staff/staff_controller.go View File

@@ -0,0 +1,290 @@
1
+package staff
2
+
3
+import (
4
+	"SCRM/controllers"
5
+	"SCRM/enums"
6
+	"SCRM/models"
7
+	"SCRM/service/staff_service"
8
+	"SCRM/utils"
9
+	"encoding/json"
10
+	"fmt"
11
+	"github.com/astaxie/beego"
12
+	"time"
13
+)
14
+
15
+func staffRouters() {
16
+
17
+	beego.Router("/api/staff/addStaffInfo", &StaffManage{}, "Post:AddStaffInfo")
18
+	beego.Router("/api/staff/getAllStaffInfo", &StaffManage{}, "Get:GetAllStaffInfo")
19
+	beego.Router("/api/staff/EditStaffInfo", &StaffManage{}, "Post:EditStaffInfo")
20
+	beego.Router("/api/staff/DeleteStaffs", &StaffManage{}, "Delete:DeleteStaffs")
21
+}
22
+
23
+type StaffManage struct {
24
+	controllers.BaseAuthAPIController
25
+}
26
+
27
+func (this *StaffManage) AddStaffInfo() {
28
+	adminUserInfo := this.GetAdminUserInfo()
29
+	userOrgID := int64(adminUserInfo.CurrentOrgId)
30
+	fmt.Println("机构ID", userOrgID)
31
+	dataBody := make(map[string]interface{}, 0)
32
+
33
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
34
+	fmt.Println("视频发布是什么呢", err)
35
+
36
+	if err != nil {
37
+		utils.ErrorLog(err.Error())
38
+		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误")
39
+		return
40
+	}
41
+	fmt.Println("hhhhh")
42
+	staffname := dataBody["name"].(string)
43
+	if len(staffname) == 0 {
44
+		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "姓名不能为空")
45
+		return
46
+	}
47
+
48
+	phone := dataBody["phone"].(string)
49
+	if len(phone) == 0 {
50
+		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "手机不能为空")
51
+		return
52
+	}
53
+
54
+	gender := int64(dataBody["gender"].(float64))
55
+	if gender <= 0 {
56
+		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "性别不能为空")
57
+		return
58
+	}
59
+
60
+	birthday, _ := dataBody["birthday"].(string)
61
+	if len(birthday) == 0 {
62
+		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "生日格式不正确")
63
+		return
64
+	}
65
+
66
+	timeLayout := "2006-01-02 15:04:05"
67
+	theTime, err := utils.ParseTimeStringToTime(timeLayout, birthday+" 00:00:00")
68
+	if err != nil {
69
+		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "生日格式不正确")
70
+		return
71
+	}
72
+
73
+	var staffbirthday = theTime.Unix()
74
+	fmt.Println("生日", staffbirthday)
75
+
76
+	userType := int64(dataBody["user_type"].(float64))
77
+
78
+	if userType <= 0 {
79
+		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "职称类型不正确")
80
+		return
81
+	}
82
+	userTitle := int64(dataBody["user_title"].(float64))
83
+	if userTitle <= 0 {
84
+		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "职称名称不正确")
85
+		return
86
+	}
87
+	dochead := dataBody["dochead"].(string)
88
+	if len(dochead) == 0 {
89
+		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "头像不正确")
90
+		return
91
+	}
92
+	content := dataBody["content"].(string)
93
+	if len(content) == 0 {
94
+		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "头像不正确")
95
+		return
96
+	}
97
+
98
+	fmt.Println("姓名", staffname, "性别", gender, "生日", staffbirthday, "职称类型", userType, "职称名称", userTitle, "头像", dochead, "内容", content)
99
+
100
+	StaffInfo := models.SgjUserStaffInfo{
101
+		Name:      staffname,
102
+		Phone:     phone,
103
+		Birthday:  staffbirthday,
104
+		Gender:    gender,
105
+		Content:   content,
106
+		UserType:  userType,
107
+		UserTitle: userTitle,
108
+		Dochead:   dochead,
109
+		Status:    1,
110
+		UserOrgId: userOrgID,
111
+		Ctime:     time.Now().Unix(),
112
+	}
113
+
114
+	err = staff_service.AddStaffInfo(StaffInfo)
115
+	if err != nil {
116
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "插入文章失败")
117
+		return
118
+	}
119
+	this.ServeSuccessJSON(map[string]interface{}{
120
+		"staffInfo": StaffInfo,
121
+	})
122
+	return
123
+}
124
+
125
+func (this *StaffManage) GetAllStaffInfo() {
126
+	keyword := this.GetString("keyword")
127
+	page, _ := this.GetInt64("page", 1)
128
+	fmt.Println("页面", page)
129
+	limit, _ := this.GetInt64("limit", 10)
130
+
131
+	if page <= 0 {
132
+		page = 1
133
+	}
134
+	if limit <= 0 {
135
+		limit = 10
136
+	}
137
+	fmt.Println("限制", limit)
138
+	fmt.Println("关键字", keyword, "limit", limit, "page", page)
139
+
140
+	adminUserInfo := this.GetAdminUserInfo()
141
+	userOrgID := int64(adminUserInfo.CurrentOrgId)
142
+	userStaffInfo, total, err := staff_service.GetAllStaffInfo(userOrgID, page, limit, keyword)
143
+	fmt.Println("内容", userStaffInfo, "total", total, "err", err)
144
+	if err != nil {
145
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "获取文章分类列表失败")
146
+		return
147
+	}
148
+	this.ServeSuccessJSON(map[string]interface{}{
149
+		"userStaffInfo": userStaffInfo,
150
+		"total":         total,
151
+	})
152
+}
153
+
154
+func (this *StaffManage) EditStaffInfo() {
155
+	id, _ := this.GetInt64("id")
156
+	fmt.Println("ID是多少?", id)
157
+	adminUserInfo := this.GetAdminUserInfo()
158
+	userOrgID := int64(adminUserInfo.CurrentOrgId)
159
+	fmt.Println("机构ID", userOrgID)
160
+	dataBody := make(map[string]interface{}, 0)
161
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
162
+	fmt.Println("视频发布是什么呢", err)
163
+
164
+	if err != nil {
165
+		utils.ErrorLog(err.Error())
166
+		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误")
167
+		return
168
+	}
169
+	staffname := dataBody["name"].(string)
170
+	fmt.Println("staffname", staffname)
171
+	if len(staffname) == 0 {
172
+		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "姓名不能为空")
173
+		return
174
+	}
175
+
176
+	phone := dataBody["phone"].(string)
177
+	fmt.Println("phone", phone)
178
+	if len(phone) == 0 {
179
+		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "手机不能为空")
180
+		return
181
+	}
182
+
183
+	gender := int64(dataBody["gender"].(float64))
184
+	fmt.Println("gender", gender)
185
+	if gender <= 0 {
186
+		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "性别不能为空")
187
+		return
188
+	}
189
+
190
+	birthday, _ := dataBody["birthday"].(string)
191
+	fmt.Println("birthday", birthday)
192
+	if len(birthday) == 0 {
193
+		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "生日格式不正确")
194
+		return
195
+	}
196
+
197
+	timeLayout := "2006-01-02 15:04:05"
198
+	theTime, err := utils.ParseTimeStringToTime(timeLayout, birthday+" 00:00:00")
199
+	if err != nil {
200
+		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "生日格式不正确")
201
+		return
202
+	}
203
+
204
+	var staffbirthday = theTime.Unix()
205
+	fmt.Println("生日", staffbirthday)
206
+
207
+	userType := int64(dataBody["user_type"].(float64))
208
+	fmt.Println("userType", userType)
209
+	if userType <= 0 {
210
+		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "职称类型不正确")
211
+		return
212
+	}
213
+	userTitle := int64(dataBody["user_title"].(float64))
214
+	fmt.Println("userTitle", userTitle)
215
+	if userTitle <= 0 {
216
+		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "职称名称不正确")
217
+		return
218
+	}
219
+	dochead := dataBody["dochead"].(string)
220
+	fmt.Println("dochead", dochead)
221
+	if len(dochead) == 0 {
222
+		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "头像不正确")
223
+		return
224
+	}
225
+	content := dataBody["content"].(string)
226
+	fmt.Println("content", content)
227
+	if len(content) == 0 {
228
+		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "头像不正确")
229
+		return
230
+	}
231
+
232
+	fmt.Println("姓名", staffname, "性别", gender, "生日", staffbirthday, "职称类型", userType, "职称名称", userTitle, "头像", dochead, "内容", content)
233
+
234
+	StaffInfo := models.SgjUserStaffInfo{
235
+		Name:      staffname,
236
+		Phone:     phone,
237
+		Birthday:  staffbirthday,
238
+		Gender:    gender,
239
+		Content:   content,
240
+		UserType:  userType,
241
+		UserTitle: userTitle,
242
+		Dochead:   dochead,
243
+		Status:    1,
244
+		UserOrgId: userOrgID,
245
+		Mtime:     time.Now().Unix(),
246
+	}
247
+	fmt.Println(StaffInfo)
248
+	err = staff_service.UpdateStaffInfo(StaffInfo, userOrgID, id)
249
+	fmt.Println("err", err)
250
+	this.ServeSuccessJSON(map[string]interface{}{
251
+		"userStaffInfo": StaffInfo,
252
+	})
253
+}
254
+
255
+func (this *StaffManage) DeleteStaffs() {
256
+	adminUserInfo := this.GetAdminUserInfo()
257
+	OrgID := adminUserInfo.CurrentOrgId
258
+	dataBody := make(map[string]interface{}, 0)
259
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
260
+	if err != nil {
261
+		utils.ErrorLog(err.Error())
262
+		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误")
263
+		return
264
+	}
265
+
266
+	idsInters := dataBody["ids"].([]interface{})
267
+	if len(idsInters) == 0 {
268
+		if err != nil {
269
+			this.ServeFailJsonSend(enums.ErrorCodeDBDelete, "删除会员失败:(没有选择会员)")
270
+			return
271
+		}
272
+	}
273
+
274
+	ids := make([]int64, 0)
275
+	for _, idsInter := range idsInters {
276
+		id := int64(idsInter.(float64))
277
+		ids = append(ids, id)
278
+	}
279
+
280
+	err = staff_service.DeleteStaffs(OrgID, ids)
281
+	fmt.Println("错误", err)
282
+	if err != nil {
283
+		this.ServeFailJsonSend(enums.ErrorCodeDBDelete, "删除失败:("+err.Error()+")")
284
+		return
285
+	}
286
+	returnData := make(map[string]interface{}, 0)
287
+	returnData["msg"] = "ok"
288
+	this.ServeSuccessJSON(returnData)
289
+	return
290
+}

+ 171 - 0
enums/error_code.go View File

@@ -0,0 +1,171 @@
1
+package enums
2
+
3
+import "SCRM/utils"
4
+
5
+const ( // ErrorCode
6
+	// 登录注册错误 6000+
7
+	ErrorCodeLoginTimeout                   = 6001
8
+	ErrorCodeNotLogin                       = 6002
9
+	ErrorCodePermissionDenied               = 6003
10
+	ErrorCodeMobileRegistered               = 6004
11
+	ErrorCodePasswordEmpty                  = 6005
12
+	ErrorCodeVerificationCodeWrong          = 6006
13
+	ErrorCodeRegisterFail                   = 6007
14
+	ErrorCodeInvalidToken                   = 6008
15
+	ErrorCodeAccountOrPasswordWrong         = 6009
16
+	ErrorCodeMissingOrg                     = 6010
17
+	ErrorCodeMissingOrgApp                  = 6011
18
+	ErrorCodeAccountOrVerCodeWrong          = 6012
19
+	ErrorCodeMobileNotExit                  = 6013
20
+	ErrorCodeUserNotExist                   = 6014
21
+	ErrorCodeUserWasForbidden               = 6015
22
+	ErrorCodeNeverCreateTypeApp             = 6016
23
+	ErrorCodeContactSuperAdminCreateTypeApp = 6017
24
+	ErrorCodeVerificationCodeLimit          = 6018
25
+
26
+	// 数据验证错误 7000+
27
+	ErrorCodeMobileFormat     = 7001
28
+	ErrorCodeTelphoneFormat   = 7002
29
+	ErrorCodeParamWrong       = 7003
30
+	ErrorCodeParamFormatWrong = 7004
31
+
32
+	// 数据库操作错误 8000+
33
+	ErrorCodeDBCreate         = 8001
34
+	ErrorCodeDBUpdate         = 8002
35
+	ErrorCodeDBDelete         = 8003
36
+	ErrorCodeDBSelectNoResult = 8004
37
+	ErrorCodeDataException    = 8005
38
+
39
+	// 业务逻辑操作错误 9000+
40
+	ErrorCodeRoleNotExist           = 9001
41
+	ErrorCodeAdminUserNotExist      = 9002
42
+	ErrorCodeMobileDidUsedInApp     = 9003
43
+	ErrorCodeMissingUserName        = 9004
44
+	ErrorCodeOldPasswordWrong       = 9005
45
+	ErrorCodeCannotRemoveRole       = 9006
46
+	ErrorCodeRoleMobileIsSuperAdmin = 9007
47
+
48
+	ErrorCodeActivityNotExist              = 9100
49
+	ErrorCodeActivityPublishedCannotModify = 9101
50
+	ErrorCodeActivityPublishRepeat         = 9102
51
+
52
+	ErrorCodeGetQiniuUpToken = 1001
53
+
54
+	ErrorCodeNotSubscibe       = 4003
55
+	ErrorCodeServeNotExist     = 4004
56
+	ErrorCodeInvoiceExist      = 4005
57
+	ErrorCodeApplyInvoiceFail  = 4006
58
+	ErrorCodeHetongHad         = 4007
59
+	ErrorCodeCreateHetongFail  = 4008
60
+	ErrorCodePatientReachLimit = 4009
61
+
62
+	ErrorCodeSMSNoCustomer        = 10001
63
+	ErrorCodeSMSLimitInsufficient = 10002
64
+)
65
+
66
+var ErrCodeMsgs = map[int]string{
67
+	// 登录注册错误
68
+	ErrorCodeLoginTimeout:                   "登录超时",
69
+	ErrorCodeNotLogin:                       "未登录",
70
+	ErrorCodePermissionDenied:               "权限不足",
71
+	ErrorCodeMobileRegistered:               "手机号已被注册",
72
+	ErrorCodePasswordEmpty:                  "密码为空",
73
+	ErrorCodeVerificationCodeWrong:          "验证码错误",
74
+	ErrorCodeRegisterFail:                   "注册失败",
75
+	ErrorCodeInvalidToken:                   "令牌无效",
76
+	ErrorCodeAccountOrPasswordWrong:         "账号或密码错误",
77
+	ErrorCodeMissingOrg:                     "未创建机构",
78
+	ErrorCodeMissingOrgApp:                  "未创建任何应用",
79
+	ErrorCodeAccountOrVerCodeWrong:          "账号或验证码错误",
80
+	ErrorCodeMobileNotExit:                  "手机号不存在",
81
+	ErrorCodeUserNotExist:                   "用户不存在",
82
+	ErrorCodeUserWasForbidden:               "该用户被禁用",
83
+	ErrorCodeNeverCreateTypeApp:             "未创建此种应用",
84
+	ErrorCodeContactSuperAdminCreateTypeApp: "请联系超级管理员开通此种应用",
85
+	ErrorCodeVerificationCodeLimit:          "该号码今日验证码已超限",
86
+
87
+	// 数据验证错误
88
+	ErrorCodeMobileFormat:     "手机号格式错误",
89
+	ErrorCodeTelphoneFormat:   "电话格式错误",
90
+	ErrorCodeParamWrong:       "参数错误",
91
+	ErrorCodeParamFormatWrong: "参数格式错误",
92
+
93
+	// 数据库操作错误
94
+	ErrorCodeDBCreate:         "数据库创建出错",
95
+	ErrorCodeDBUpdate:         "数据库更新出错",
96
+	ErrorCodeDBDelete:         "数据库删除出错",
97
+	ErrorCodeDBSelectNoResult: "查询无结果",
98
+	ErrorCodeDataException:    "数据异常",
99
+
100
+	// 业务逻辑操作错误
101
+	ErrorCodeRoleNotExist:           "角色不存在",
102
+	ErrorCodeAdminUserNotExist:      "管理员不存在",
103
+	ErrorCodeMobileDidUsedInApp:     "该手机号已在该应用中被注册为管理员",
104
+	ErrorCodeMissingUserName:        "缺少用户名",
105
+	ErrorCodeOldPasswordWrong:       "原密码不正确",
106
+	ErrorCodeCannotRemoveRole:       "存在该角色的管理员,不能删除该角色",
107
+	ErrorCodeRoleMobileIsSuperAdmin: "该手机号已注册为超级管理员",
108
+
109
+	ErrorCodeActivityNotExist:              "活动不存在",
110
+	ErrorCodeActivityPublishedCannotModify: "已发布的活动不可更改",
111
+	ErrorCodeActivityPublishRepeat:         "该活动已发布",
112
+
113
+	ErrorCodeGetQiniuUpToken: "获取七牛uptoken失败",
114
+
115
+	ErrorCodeNotSubscibe:       "没有订阅服务或服务已过期,请先购买服务!",
116
+	ErrorCodeServeNotExist:     "服务订单不存在!",
117
+	ErrorCodeInvoiceExist:      "已经申请了发票!",
118
+	ErrorCodeApplyInvoiceFail:  "申请发票失败!",
119
+	ErrorCodeHetongHad:         "合同已经存在!",
120
+	ErrorCodeCreateHetongFail:  "合同创建失败",
121
+	ErrorCodePatientReachLimit: "患者数已达到当前服务版本病人数,需要升级到更高的版本",
122
+
123
+	ErrorCodeSMSNoCustomer:        "没有目标客户",
124
+	ErrorCodeSMSLimitInsufficient: "当月可用短信额度不足",
125
+}
126
+
127
+type SGJError struct {
128
+	Code int
129
+}
130
+
131
+func (e *SGJError) Error() string {
132
+	value, ok := ErrCodeMsgs[e.Code]
133
+	if ok {
134
+		return value
135
+	} else {
136
+		return "未知错误"
137
+	}
138
+}
139
+
140
+func MakeSuccessResponseJSON(data map[string]interface{}) map[string]interface{} {
141
+	json := make(map[string]interface{})
142
+	if data != nil {
143
+		json["data"] = data
144
+	} else {
145
+		json["data"] = make(map[string]interface{})
146
+	}
147
+	json["state"] = 1
148
+	json["code"] = 0
149
+	return json
150
+}
151
+
152
+func MakeFailResponseJSON(errMsg string, errCode int) map[string]interface{} {
153
+	json := make(map[string]interface{})
154
+	json["msg"] = errMsg
155
+	json["code"] = errCode
156
+	json["state"] = 0
157
+	return json
158
+}
159
+
160
+func MakeFailResponseJSONWithSGJError(err *SGJError) map[string]interface{} {
161
+	if err == nil {
162
+		utils.WarningLog("MakeFailResponseJSONWithSGJError 参数err 不能为空")
163
+		return nil
164
+	}
165
+	return MakeFailResponseJSON(err.Error(), err.Code)
166
+}
167
+
168
+func MakeFailResponseJSONWithSGJErrorCode(code int) map[string]interface{} {
169
+	err := &SGJError{Code: code}
170
+	return MakeFailResponseJSON(err.Error(), err.Code)
171
+}

+ 129 - 0
jobcron/activity_short_url_job.go View File

@@ -0,0 +1,129 @@
1
+package jobcron
2
+
3
+import (
4
+	"SCRM/service"
5
+	"SCRM/utils"
6
+	"encoding/json"
7
+	"fmt"
8
+	"io/ioutil"
9
+	"net/http"
10
+	"net/url"
11
+	"strings"
12
+	"time"
13
+
14
+	"github.com/astaxie/beego"
15
+	"github.com/robfig/cron"
16
+)
17
+
18
+// cron表达式 https://www.cnblogs.com/zuxingyu/p/6023919.html
19
+var activityShortUrlCronJob *cron.Cron
20
+
21
+func init() {
22
+	activityShortUrlCronJob = cron.New()
23
+	spec := "0 0 0 * * ?" // 每天晚上12点整检查活动短链接库存充不充足
24
+	activityShortUrlCronJob.AddFunc(spec, func() {
25
+		CreateActivityShortURLIfNeeded()
26
+	})
27
+}
28
+
29
+type CreateShortURLServiceMaxId struct {
30
+	Value int
31
+}
32
+
33
+func CreateActivityShortURLIfNeeded() {
34
+	var maxActivityId CreateShortURLServiceMaxId
35
+	service.PatientReadDB().Raw("SELECT MAX(id) AS value FROM sgj_patient_activity").Scan(&maxActivityId)
36
+	utils.TraceLog("当前最大的活动 ID 为:%v", maxActivityId)
37
+	var maxShortURLId CreateShortURLServiceMaxId
38
+	service.PatientReadDB().Raw("SELECT MAX(id) AS value FROM sgj_patient_activity_wx_share").Scan(&maxShortURLId)
39
+	utils.TraceLog("当前最大的活动短链接 ID 为:%v", maxShortURLId)
40
+
41
+	if maxShortURLId.Value-maxActivityId.Value <= 300 {
42
+		utils.TraceLog("即将生成更多活动短链接")
43
+		go CreateMoreActivityShortURL(maxShortURLId.Value)
44
+	} else {
45
+		utils.TraceLog("活动短链接充足,无需生成")
46
+	}
47
+}
48
+
49
+// 新浪短链接服务示例 https://www.cnblogs.com/azure/archive/2012/08/29/WeiboAPI.html
50
+func CreateMoreActivityShortURL(lastShortURLID int) {
51
+	var maxUrlCountPerRequest int = 20
52
+	createCount, _ := beego.AppConfig.Int("create_short_url_count_every_time")
53
+	pageCount := createCount / maxUrlCountPerRequest
54
+	tx := service.PatientWriteDB().Begin()
55
+	for i := 0; i < pageCount; i++ {
56
+		longURLParams := make([]string, 0, maxUrlCountPerRequest)
57
+		for longURLIndex := 1; longURLIndex < maxUrlCountPerRequest+1; longURLIndex++ {
58
+			id := lastShortURLID + i*maxUrlCountPerRequest + longURLIndex
59
+			param := fmt.Sprintf("url_long=%v", fmt.Sprintf("%v/weixin/activity/%v", beego.AppConfig.String("weixinwebdomain"), id))
60
+			longURLParams = append(longURLParams, param)
61
+		}
62
+
63
+		urlStr := fmt.Sprintf("http://api.weibo.com/2/short_url/shorten.json?source=2849184197&%v", strings.Join(longURLParams, "&"))
64
+		u, _ := url.Parse(urlStr)
65
+		u.RawQuery = u.Query().Encode()
66
+		// fmt.Println(u.String())
67
+
68
+		resp, requestErr := http.Get(u.String())
69
+		if requestErr != nil {
70
+			utils.ErrorLog("http.Get error: %v", requestErr)
71
+			continue
72
+		}
73
+		result, readErr := ioutil.ReadAll(resp.Body)
74
+		resp.Body.Close()
75
+		if readErr != nil {
76
+			utils.ErrorLog("ioutil.ReadAll error: %v", readErr)
77
+			continue
78
+		}
79
+		// fmt.Println(string(result))
80
+		var respJSON map[string]interface{}
81
+		if err := json.Unmarshal([]byte(string(result)), &respJSON); err != nil {
82
+			utils.ErrorLog("json.Unmarshal error: %v\n", err)
83
+			continue
84
+		}
85
+		// fmt.Printf("resp: %v\n", respJSON)
86
+		if respJSON["error"] != nil {
87
+			utils.ErrorLog("request error: %v\n", respJSON)
88
+			continue
89
+		}
90
+
91
+		urlJSONs := respJSON["urls"].([]interface{})
92
+		now := time.Now().Unix()
93
+		valueStrs := make([]string, 0, len(urlJSONs))
94
+		values := make([]interface{}, 0, len(urlJSONs)*9)
95
+
96
+		for index, url := range urlJSONs {
97
+			urlJSON := url.(map[string]interface{})
98
+			shortURL := urlJSON["url_short"].(string)
99
+			fmt.Println("shortURL是什么")
100
+			id := lastShortURLID + i*maxUrlCountPerRequest + (index + 1)
101
+			// CreateActivityWxShareWithShortURL(id, shortURL)
102
+
103
+			// (`id`,`activity_id`,`title`,`subtitle`,`image`,`status`,`ctime`,`mtime`,`short_url`)
104
+			valueStrs = append(valueStrs, "(?, ?, ?, ?, ?, ?, ?, ?, ?)")
105
+			values = append(values, id)
106
+			values = append(values, id)
107
+			values = append(values, "")
108
+			values = append(values, "")
109
+			values = append(values, "")
110
+			values = append(values, 1)
111
+			values = append(values, now)
112
+			values = append(values, now)
113
+			values = append(values, shortURL)
114
+		}
115
+
116
+		sql := fmt.Sprintf("INSERT INTO sgj_patient_activity_wx_share (id, activity_id, title, subtitle, image, status, ctime, mtime, short_url) VALUES %v;", strings.Join(valueStrs, ", "))
117
+		if err := tx.Exec(sql, values...).Error; err != nil {
118
+			utils.ErrorLog("插入活动短链接失败: %v", err)
119
+			tx.Rollback()
120
+			break
121
+		}
122
+	}
123
+	tx.Commit()
124
+	utils.TraceLog("完成生成更多活动短链接")
125
+}
126
+
127
+func BeginCreateActivityShortURLCronJob() {
128
+	activityShortUrlCronJob.Start()
129
+}

+ 201 - 0
jobcron/open_wechat_job.go View File

@@ -0,0 +1,201 @@
1
+package jobcron
2
+
3
+import (
4
+	"encoding/json"
5
+	"fmt"
6
+	"time"
7
+
8
+	"github.com/silenceper/wechat/util"
9
+
10
+	"SCRM/service"
11
+	"SCRM/service/wechat_service"
12
+	"SCRM/utils"
13
+
14
+	"github.com/astaxie/beego"
15
+	"github.com/robfig/cron"
16
+)
17
+
18
+var openWechatCron *cron.Cron
19
+
20
+func init() {
21
+	openWechatCron = cron.New()
22
+	openWechatCron.AddFunc("@every 1h30m", func() {
23
+		go func() {
24
+			RequestComponentAccessToken()
25
+		}()
26
+	})
27
+
28
+	openWechatCron.AddFunc("@every 1h30m", func() {
29
+		go func() {
30
+			RequestMpWechatAccessToken()
31
+		}()
32
+	})
33
+
34
+}
35
+
36
+func StartOpenWechatCron() {
37
+	openWechatCron.Start()
38
+}
39
+
40
+var (
41
+	token          = beego.AppConfig.String("openwechattoken")
42
+	appID          = beego.AppConfig.String("openwechatappid")
43
+	encodingAESKey = beego.AppConfig.String("openwechatencodingaeskey")
44
+	appSecret      = beego.AppConfig.String("openwechatsecret")
45
+)
46
+
47
+type ReqComponentAccessStruct struct {
48
+	ComponentAppid        string `json:"component_appid"`
49
+	ComponentAppSecret    string `json:"component_appsecret"`
50
+	ComponentVerifyTicket string `json:"component_verify_ticket"`
51
+}
52
+
53
+//请求第三方平台的accessToken
54
+func RequestComponentAccessToken() {
55
+	utils.InfoLog("Request ComponentAccessToken Start...")
56
+	redisClient := service.RedisClient()
57
+	defer redisClient.Close()
58
+
59
+	componentVerifyTicket, err := redisClient.Get("sgj_patient:ComponentVerifyTicket").Result()
60
+	if err != nil {
61
+		utils.ErrorLog("读取ComponentVerifyTicket失败:%s", err)
62
+		return
63
+	}
64
+
65
+	//假设 拿到了  component_verify_ticket ,开始通过接口 拿 component_access_token
66
+	//获取第三方平台component_access_token,POST数据
67
+	var ReqComponentAccess ReqComponentAccessStruct
68
+	ReqComponentAccess.ComponentAppid = appID
69
+	ReqComponentAccess.ComponentAppSecret = appSecret
70
+	ReqComponentAccess.ComponentVerifyTicket = componentVerifyTicket
71
+	fmt.Println(ReqComponentAccess)
72
+	//创建请求
73
+	uri := fmt.Sprintf("%s", "https://api.weixin.qq.com/cgi-bin/component/api_component_token")
74
+	var responseBytes []byte
75
+	responseBytes, err = util.PostJSON(uri, ReqComponentAccess)
76
+	if err != nil {
77
+		utils.ErrorLog("创建请求失败:%s", err)
78
+		return
79
+	}
80
+
81
+	var res wechat_service.MPResult
82
+	err = json.Unmarshal(responseBytes, &res)
83
+	if err != nil {
84
+		utils.ErrorLog("MPResult error:%s", err)
85
+		return
86
+	}
87
+
88
+	if res.ErrCode > 0 {
89
+		fmt.Println(res.ErrMsg)
90
+		return
91
+	}
92
+
93
+	//body 是上面请求返回的json数据
94
+	//{"component_access_token":"61W3mEpU66027wgNZ_MhGHNQDHnFATkDa9-2llqrMBjUwxRSNPbVsMmyD-yq8wZETSoE5NQgecigDrSHkPtIYA", "expires_in":7200}
95
+	var access_token wechat_service.ComponentAccessToken
96
+	// 将body的json解析成 access_token ComponentAccessToken
97
+	err = json.Unmarshal(responseBytes, &access_token)
98
+	if err != nil {
99
+		utils.ErrorLog("Unmarshal json error:%s", err)
100
+		return
101
+	}
102
+
103
+	err = redisClient.Set("sgj_patient:component_access_token", access_token.ComponentAccessToken, time.Second*7000).Err()
104
+	fmt.Println("err错误是哦", err)
105
+	if err != nil {
106
+		utils.ErrorLog("redis set failed:%s", err)
107
+		return
108
+	}
109
+
110
+	componentID, err := beego.AppConfig.Int64("openwechatcomponentid")
111
+	if err != nil {
112
+		utils.ErrorLog("get component id failed: %s", err)
113
+		return
114
+	}
115
+
116
+	info := make(map[string]interface{}, 0)
117
+	info["ComponentAccessToken"] = access_token.ComponentAccessToken
118
+	info["UpdatedTime"] = time.Now().Unix()
119
+	info["ComponentStatus"] = 1
120
+
121
+	err = wechat_service.SaveWechatComponentInfoByMap(componentID, info)
122
+
123
+	utils.InfoLog("Request ComponentAccessToken Finish.")
124
+}
125
+
126
+type ReqRefreshTokenStruct struct {
127
+	ComponentAppid         string `json:"component_appid"`
128
+	AuthorizerAppid        string `json:"authorizer_appid"`
129
+	AuthorizerRefreshToken string `json:"authorizer_refresh_token"`
130
+}
131
+
132
+func RequestMpWechatAccessToken() {
133
+	utils.InfoLog("Request MpWechatAccessToken start...")
134
+	mps, err := wechat_service.GetAuthorizations()
135
+	if err != nil {
136
+		utils.ErrorLog("get mps error: %s", err)
137
+		return
138
+	}
139
+
140
+	redisClient := service.RedisClient()
141
+	defer redisClient.Close()
142
+
143
+	componentAccessToken, err := redisClient.Get("sgj_patient:component_access_token").Result()
144
+	if err != nil {
145
+		utils.ErrorLog("get component_access_token error: %s", err)
146
+		return
147
+	}
148
+
149
+	for _, item := range mps {
150
+		var ReqRefreshToken ReqRefreshTokenStruct
151
+		ReqRefreshToken.ComponentAppid = appID
152
+		ReqRefreshToken.AuthorizerAppid = item.AuthorizerAppid
153
+		ReqRefreshToken.AuthorizerRefreshToken = item.AuthorizerRefreshToken
154
+
155
+		uri := fmt.Sprintf("%s?component_access_token=%s", "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token", componentAccessToken)
156
+		var responseBytes []byte
157
+		responseBytes, err = util.PostJSON(uri, ReqRefreshToken)
158
+		if err != nil {
159
+			utils.ErrorLog("error: %s", err)
160
+			continue
161
+		}
162
+
163
+		var res wechat_service.MPResult
164
+		err = json.Unmarshal(responseBytes, &res)
165
+		if err != nil {
166
+			utils.ErrorLog("%s, error: %s", item.AuthorizerAppid, err)
167
+			continue
168
+		}
169
+
170
+		if res.ErrCode > 0 {
171
+			utils.ErrorLog("%s, error: %s", item.AuthorizerAppid, res.ErrMsg)
172
+			continue
173
+		}
174
+
175
+		var accessToken wechat_service.RefreshToken
176
+		err = json.Unmarshal(responseBytes, &accessToken)
177
+		if err != nil {
178
+			utils.ErrorLog("%s, Unmarshal error: %s", item.AuthorizerAppid, err)
179
+			continue
180
+		}
181
+
182
+		info := *item
183
+		info.AuthorizerAccessToken = accessToken.AuthorizerAccessToken
184
+		info.AuthorizerRefreshToken = accessToken.AuthorizerRefreshToken
185
+		info.UpdatedTime = time.Now().Unix()
186
+		err = wechat_service.SaveAuthorizationInfo(&info)
187
+		if err != nil {
188
+			utils.ErrorLog("%s,Save error: %s", item.AuthorizerAppid, err)
189
+			continue
190
+		}
191
+
192
+		atKey := fmt.Sprintf("Patient:AccessToken[%s]", item.AuthorizerAppid)
193
+		_, err = redisClient.Set(atKey, accessToken.AuthorizerAccessToken, 0).Result()
194
+		if err != nil {
195
+			utils.ErrorLog("%s,Save redis error: %s", item.AuthorizerAppid, err)
196
+			continue
197
+		}
198
+	}
199
+	utils.InfoLog("Request MpWechatAccessToken END")
200
+
201
+}

+ 44 - 0
jobcron/qiniu_job.go View File

@@ -0,0 +1,44 @@
1
+package jobcron
2
+
3
+import (
4
+	"SCRM/service"
5
+	"fmt"
6
+
7
+	"github.com/astaxie/beego"
8
+	"github.com/qiniu/api.v7/auth/qbox"
9
+	"github.com/qiniu/api.v7/storage"
10
+	"github.com/robfig/cron"
11
+)
12
+
13
+var qnTokenCronJob *cron.Cron
14
+
15
+func init() {
16
+	qnTokenCronJob = cron.New()
17
+	qnTokenCronJob.AddFunc("@every 1h50m", func() {
18
+		go RequestQNToken()
19
+	})
20
+}
21
+
22
+func RequestQNToken() {
23
+	accessKey := beego.AppConfig.String("qiniu_accesskey")
24
+	secretKey := beego.AppConfig.String("qiniu_secretkey")
25
+	bucket := beego.AppConfig.String("qiniu_bucket")
26
+	fmt.Println("bucket", bucket)
27
+	putPolicy := storage.PutPolicy{
28
+		Scope:      bucket,
29
+		ReturnBody: `{"url":"$(key)","hash":"$(etag)","state":"SUCCESS"}`,
30
+	}
31
+	fmt.Println("putpolicy", putPolicy)
32
+	putPolicy.Expires = 7200
33
+	mac := qbox.NewMac(accessKey, secretKey)
34
+	upToken := putPolicy.UploadToken(mac)
35
+	fmt.Println("new qiniu token: ", upToken)
36
+
37
+	redisClient := service.RedisClient()
38
+	defer redisClient.Close()
39
+	redisClient.Set("qn_token", upToken, 0)
40
+}
41
+
42
+func BeginRerequestQNTokenCronJob() {
43
+	qnTokenCronJob.Start()
44
+}

+ 24 - 0
jobcron/sms_job.go View File

@@ -0,0 +1,24 @@
1
+package jobcron
2
+
3
+import (
4
+	"SCRM/service/sms_service"
5
+	"SCRM/utils"
6
+
7
+	"github.com/robfig/cron"
8
+)
9
+
10
+// cron表达式 https://www.cnblogs.com/zuxingyu/p/6023919.html
11
+var smsCronJob *cron.Cron
12
+
13
+func init() {
14
+	smsCronJob = cron.New()
15
+	spec := "0 */5 * * * ?" // 每五分钟检查一次
16
+	smsCronJob.AddFunc(spec, func() {
17
+		utils.TraceLog("定时发送未发送的短信")
18
+		sms_service.SMSSendUnsendBatchRealTime()
19
+	})
20
+}
21
+
22
+func BeginSendUnsendSMSCronJob() {
23
+	smsCronJob.Start()
24
+}

+ 35 - 0
main.go View File

@@ -0,0 +1,35 @@
1
+package main
2
+
3
+import (
4
+	"SCRM/jobcron"
5
+	_ "SCRM/routers"
6
+	"SCRM/service"
7
+
8
+	"SCRM/service/site_service"
9
+	"github.com/astaxie/beego"
10
+)
11
+
12
+func init() {
13
+	service.ConnectDB()
14
+}
15
+
16
+func main() {
17
+
18
+	//微信开放平台
19
+	go func() {
20
+		// jobcron.RequestComponentAccessToken()
21
+		// jobcron.RequestMpWechatAccessToken()
22
+		// jobcron.ReqJsapiTicket()
23
+	}()
24
+
25
+	jobcron.StartOpenWechatCron()
26
+	jobcron.BeginSendUnsendSMSCronJob()
27
+
28
+	jobcron.CreateActivityShortURLIfNeeded()
29
+	jobcron.BeginCreateActivityShortURLCronJob()
30
+
31
+	go jobcron.RequestQNToken()
32
+	jobcron.BeginRerequestQNTokenCronJob()
33
+	site_service.BeginAutoCreateDefalutData()
34
+	beego.Run()
35
+}

+ 3 - 0
models/Readme.md View File

@@ -0,0 +1,3 @@
1
+这个文件夹下只定义数据库相关的 model;  
2
+其他如 view model 则在具体的 controller 或 service 中定义;  
3
+避免因为 model 太多而导致混乱和难查;  

+ 100 - 0
models/activity_models.go View File

@@ -0,0 +1,100 @@
1
+package models
2
+
3
+// 表
4
+type Activity struct {
5
+	Id               int64  `gorm:"column:id" json:"id"`                                 // 活动 ID
6
+	Title            string `json:"title"`                                               // 活动标题
7
+	Subtitle         string `json:"subtitle"`                                            // 活动副标题
8
+	CityId           int    `gorm:"column:city_id" json:"city_id"`                       // 活动地点 ID
9
+	Address          string `json:"address"`                                             // 活动详细地址
10
+	Lng              string `gorm:"column:longitude" json:"lng"`                         // 活动位置的经度
11
+	Lat              string `gorm:"column:latitude" json:"lat"`                          // 活动位置的纬度
12
+	SignUpDeadline   int64  `gorm:"column:sign_up_deadline" json:"sign_up_deadline"`     // 报名截止时间戳
13
+	SignUpNotice     string `gorm:"column:sign_up_notice" json:"sign_up_notice"`         // 报名须知
14
+	StartTime        int64  `gorm:"column:start_time" json:"start_time"`                 // 活动开始时间戳
15
+	PosterPhoto      string `gorm:"column:poster_photo" json:"poster_photo"`             // 活动海报
16
+	PosterPhotoThumb string `gorm:"column:poster_photo_thumb" json:"poster_photo_thumb"` // 活动海报缩略图
17
+	LimitNum         int    `gorm:"column:limit_num;" json:"limit_num"`                  // 限制报名人数,0表示无限制
18
+	JoinNum          int    `gorm:"column:join_num" json:"join_num"`                     // 已报名人数
19
+	PhoneNumber      string `gorm:"column:phone_number" json:"phone_number"`             // 联系方式
20
+	Type             int8   `json:"type"`                                                // 活动形式
21
+	IsInsurance      int8   `gorm:"column:is_insurance;" json:"is_insurance"`            // 是否提供保险:报名不需要保险0:否;报名需要保险1:是;2不需要报名
22
+	Status           int    `json:"status"`                                              // 活动状态 1:已发布 2:待审核 3:未通过 4:草稿 9:已删除
23
+	Reason           string `json:"reason"`                                              // 审核原因
24
+	IsRecommend      int8   `gorm:"column:is_recommend;" json:"is_recommend"`            // 0:未推荐;1:已推荐
25
+	CreateTime       int64  `gorm:"column:ctime" json:"-"`                               // 创建时间
26
+	ModifyTime       int64  `gorm:"column:mtime" json:"-"`                               // 修改时间
27
+	UserOrgId        int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
28
+	UserAppId        int64  `gorm:"column:user_app_id" json:"-"`            // 所属发布应用 ID
29
+	CommentNum       int    `gorm:"column:comment_num;" json:"comment_num"` // 评论数
30
+	StarNum          int    `gorm:"column:star_num" json:"star_num"`        // 点赞书
31
+	ReadNum          int    `gorm:"column:read_num;" json:"read_num"`       // 阅读数
32
+}
33
+
34
+func (Activity) TableName() string {
35
+	return "sgj_patient_activity"
36
+}
37
+
38
+type ActivityParagraph struct {
39
+	Id         int64  `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id"`  // 记录 ID
40
+	ActivityId int64  `gorm:"column:activity_id" json:"activity_id"` // 活动 ID
41
+	Title      string `json:"title"`
42
+	Text       string `json:"text"`
43
+	// Image      string `json:"image"` // 该字段实际上已经没用了
44
+	Status     int8  `json:"-"`                     // 状态 0.无效 1.有效
45
+	CreateTime int64 `gorm:"column:ctime" json:"-"` // 创建时间
46
+	ModifyTime int64 `gorm:"column:mtime" json:"-"` // 修改时间
47
+}
48
+
49
+func (ActivityParagraph) TableName() string {
50
+	return "sgj_patient_activity_paragraph"
51
+}
52
+
53
+type ActivityUser struct {
54
+	Id          int    `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id"` // 记录 ID
55
+	ActivityId  int    `gorm:"column:activity_id" json:"-"`          // 活动 ID
56
+	UserId      int    `gorm:"column:user_id" json:"-"`              // 参与者 ID
57
+	IDCardNo    string `gorm:"column:idcard_no" json:"idcard_no"`    // 身份证号
58
+	Mobile      string `json:"mobile"`
59
+	Realname    string `json:"real_name"`
60
+	Avatar      string `json:"avatar"`
61
+	AvatarThumb string `json:"avatar_thumb"`
62
+	Status      int8   `json:"-"`                         // 状态 0.无效 1.有效
63
+	CreateTime  int64  `gorm:"column:ctime" json:"ctime"` // 报名时间
64
+	ModifyTime  int64  `gorm:"column:mtime" json:"-"`     // 修改时间
65
+}
66
+
67
+func (ActivityUser) TableName() string {
68
+	return "sgj_patient_activity_user"
69
+}
70
+
71
+type ActivityWxShare struct {
72
+	Id         int `gorm:"PRIMARY_KEY;AUTO_INCREMENT"` // 记录 ID
73
+	ActivityId int `gorm:"column:activity_id"`         // 活动 ID
74
+	Title      string
75
+	Subtitle   string
76
+	Image      string
77
+	Status     int8   // 状态 0.无效 1.有效
78
+	CreateTime int64  `gorm:"column:ctime"`     // 创建时间
79
+	ModifyTime int64  `gorm:"column:mtime"`     // 修改时间
80
+	ShortURL   string `gorm:"column:short_url"` // 短链接
81
+}
82
+
83
+func (ActivityWxShare) TableName() string {
84
+	return "sgj_patient_activity_wx_share"
85
+}
86
+
87
+type PatientOrdmodel struct {
88
+	ID        int64  `gorm:"column:id" json:"id" form:"id"`
89
+	Title     string `gorm:"column:title" json:"title" form:"title"`
90
+	Sort      int64  `gorm:"column:sort" json:"sort" form:"sort"`
91
+	Ctime     int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
92
+	Mtime     int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
93
+	UserOrgId int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
94
+	Status    int64  `gorm:"column:status" json:"status" form:"status"`
95
+	ModeType  int64  `gorm:"column:mode_type" json:"mode_type" form:"mode_type"`
96
+}
97
+
98
+func (PatientOrdmodel) TableName() string {
99
+	return "sgj_patient_ordmodel"
100
+}

+ 69 - 0
models/admin_user_models.go View File

@@ -0,0 +1,69 @@
1
+package models
2
+
3
+type AdminUser struct {
4
+	Id           int64  `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id"` // 管理员用户 ID
5
+	Mobile       string `json:"mobile"`
6
+	Password     string `json:"password"`
7
+	IsSuperAdmin bool   `gorm:"column:is_super_admin" json:"is_super_admin"` // 是否为超级管理员
8
+	Status       int8   `json:"status"`                                      // 状态 0.无效 1.有效
9
+	CreateTime   int64  `gorm:"column:ctime" json:"ctime"`                   // 创建时间
10
+	ModifyTime   int64  `gorm:"column:mtime" json:"mtime"`                   // 修改时间
11
+}
12
+
13
+func (AdminUser) TableName() string {
14
+	return "sgj_user_admin"
15
+}
16
+
17
+type AdminUserLoginLog struct {
18
+	Id          int64  `gorm:"PRIMARY_KEY;AUTO_INCREMENT"` // 记录 ID
19
+	AdminUserId int64  `gorm:"column:admin_user_id"`
20
+	OrgId       int64  `gorm:"column:org_id"`
21
+	AppId       int64  `gorm:"column:app_id"`
22
+	IP          string `gorm:"column:ip"`
23
+	OperateType int8   `gorm:"column:operate_type"` // 操作类型(1.登录;2.退出;3.切换机构)
24
+	AppType     int8   `gorm:"column:app_type"`     // 应用类型,与 OrgApp.AppType 一致
25
+	CreateTime  int64  `gorm:"column:ctime"`        // 创建时间
26
+}
27
+
28
+func (AdminUserLoginLog) TableName() string {
29
+	return "sgj_user_admin_login_log"
30
+}
31
+
32
+type AdminUserElectronicSignature struct {
33
+	ID      int64  `gorm:"column:id" json:"id" form:"id"`
34
+	Creator int64  `gorm:"column:creator" json:"creator" form:"creator"`
35
+	OrgId   int64  `gorm:"column:org_id" json:"org_id" form:"org_id"`
36
+	AppId   int64  `gorm:"column:app_id" json:"app_id" form:"app_id"`
37
+	Url     string `gorm:"column:url" json:"url" form:"url"`
38
+	Hash    string `gorm:"column:hash" json:"hash" form:"hash"`
39
+	Status  int64  `gorm:"column:status" json:"status" form:"status"`
40
+	Ctime   int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
41
+	Mtime   int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
42
+}
43
+
44
+func (AdminUserElectronicSignature) TableName() string {
45
+	return "sgj_user_admin_electronic_signature"
46
+}
47
+
48
+// 管理员用户特殊权限,详见表注释
49
+type AdminUserSpecialPermission struct {
50
+	ID          int64 `gorm:"column:id" json:"id"`
51
+	OrgID       int64 `gorm:"column:org_id" json:"org_id"`
52
+	AppID       int64 `gorm:"column:app_id" json:"app_id"`
53
+	AdminUserID int64 `gorm:"column:admin_user_id" json:"admin_user_id"`
54
+	Permission  int64 `gorm:"column:permission" json:"permission"`
55
+	Status      int64 `gorm:"column:status" json:"-"`
56
+	CreateTime  int64 `gorm:"column:ctime" json:"-"`
57
+	ModifyTime  int64 `gorm:"column:mtime" json:"-"`
58
+}
59
+
60
+func (AdminUserSpecialPermission) TableName() string {
61
+	return "xt_admin_user_special_permission"
62
+}
63
+
64
+type SpecialPermissionType int64
65
+
66
+const (
67
+	_                              SpecialPermissionType = iota
68
+	SpecialPermissionTypeHeadNurse                       // 护士长
69
+)

+ 123 - 0
models/article_models.go View File

@@ -0,0 +1,123 @@
1
+package models
2
+
3
+type ArticleCategory struct {
4
+	//对应数据库中的字段
5
+	IMenuId   int64  `gorm:"column:id" json:"id" form:"id"`
6
+	Name      string `gorm:"column:name" json:"name" form:"Name"`
7
+	Order     int64  `gorm:"column:order" json:"order" form:"order"`
8
+	Status    int64  `gorm:"column:status" json:"status" form:"status"`
9
+	Summary   string `gorm:"column:summary" json:"summary" form:"summary"`
10
+	Type      int64  `gorm:"column:type" json:"type" form:"type"`
11
+	UserOrgId int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
12
+	Mtime     int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
13
+	Ctime     int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
14
+	Num       int64  `gorm:"column:num" json:"num" form:"num"`
15
+}
16
+
17
+func (ArticleCategory) TableName() string {
18
+	return "sgj_patient_articles_menu"
19
+}
20
+
21
+//type Articles struct {
22
+//	ID            int64     `gorm:"column:id" json:"id"`
23
+//	Title         string    `gorm:"column:title" json:"title"`
24
+//	Summary       string    `gorm:"column:summary" json:"summary"`
25
+//	Content       string    `gorm:"column:content" json:"content"`
26
+//	Type          int       `gorm:"column:type" json:"type"`
27
+//	Num           int       `gorm:"column:num" json:"num"`
28
+//	Realreadnum   int64       `gorm:"column:real_read_num" json:"real_read_num"`
29
+//	Mtime         int64     `gorm:"column:mtime" json:"mtime"`
30
+//	Ctime         int64     `gorm:"column:ctime" json:"ctime"`
31
+//	ClassId       int64     `gorm:"column:class_id" json:"class_id"`
32
+//	Author        string    `gorm:"column:author" json:"author"`
33
+//	Status        int       `gorm:"column:status" json:"status"`
34
+//	Reason        string    `gorm:"column:reason" json:"reason"`
35
+//	StarNum       int       `gorm:"column:star_num" json:"star_num"`
36
+//	CommentNum    int       `gorm:"column:comment_num" json:"comment_num"`
37
+//	UserOrgId     int64     `gorm:"column:user_org_id" json:"user_org_id"`
38
+//	ArticleStatus int64     `gorm:"column:article_status" json:"article_status"`
39
+//	Imgs          string    `gorm:"column:imgs" json:"imgs"`
40
+//	VideoUrl      string    `gorm:"column:video_url" json:"video_url"`
41
+//	Cover         string    `gorm:"-" json:"cover"`
42
+//	PublicTime    string    `gorm:"-" json:"publicTime"`
43
+//	Comments      []Comment `gorm:"ForeignKey:ArticleId"`
44
+//	ArticleId	  int64		 `gorm:"-"`
45
+//}
46
+type Articles struct {
47
+	ID            int64     `gorm:"column:id" json:"id" form:"id"`
48
+	Title         string    `gorm:"column:title" json:"title" form:"title"`
49
+	Summary       string    `gorm:"column:summary" json:"summary" form:"summary"`
50
+	Content       string    `gorm:"column:content" json:"content" form:"content"`
51
+	Type          int64     `gorm:"column:type" json:"type" form:"type"`
52
+	Num           int64     `gorm:"column:num" json:"num" form:"num"`
53
+	Mtime         int64     `gorm:"column:mtime" json:"mtime" form:"mtime"`
54
+	RealReadNum   int64     `gorm:"column:real_read_num" json:"real_read_num" form:"real_read_num"`
55
+	Ctime         int64     `gorm:"column:ctime" json:"ctime" form:"ctime"`
56
+	ClassId       int64     `gorm:"column:class_id" json:"class_id" form:"class_id"`
57
+	Author        string    `gorm:"column:author" json:"author" form:"author"`
58
+	Status        int64     `gorm:"column:status" json:"status" form:"status"`
59
+	Reason        string    `gorm:"column:reason" json:"reason" form:"reason"`
60
+	StarNum       int64     `gorm:"column:star_num" json:"star_num" form:"star_num"`
61
+	CommentNum    int64     `gorm:"column:comment_num" json:"comment_num" form:"comment_num"`
62
+	UserOrgId     int64     `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
63
+	ArticleStatus int64     `gorm:"column:article_status" json:"article_status" form:"article_status"`
64
+	Imgs          string    `gorm:"column:imgs" json:"imgs" form:"imgs"`
65
+	VideoUrl      string    `gorm:"column:video_url" json:"video_url" form:"video_url"`
66
+	Source        int64     `gorm:"column:source" json:"source" form:"source"`
67
+	CategoryId    int64     `gorm:"column:category_id" json:"category_id" form:"category_id"`
68
+	Ttid          int64     `gorm:"column:ttid" json:"ttid" form:"ttid"`
69
+	Ttype         int64     `gorm:"column:ttype" json:"ttype" form:"ttype"`
70
+	Toid          int64     `gorm:"column:toid" json:"toid" form:"toid"`
71
+	Comments      []Comment `gorm:"ForeignKey:ArticleId"`
72
+	PublicTime    string    `gorm:"-" json:"publicTime"`
73
+	ArticleId     int64     `gorm:"-"`
74
+}
75
+
76
+func (Articles) TableName() string {
77
+	return "sgj_patient_articles"
78
+}
79
+
80
+type Comment struct {
81
+	ID                int64  `gorm:"column:id" json:"id"`
82
+	ArticleId         int64  `gorm:"column:article_id" json:"article_id"`
83
+	CommentUserId     int64  `gorm:"column:comment_user_id" json:"comment_user_id"`
84
+	ParentId          int64  `gorm:"column:parent_id" json:"parent_id"`
85
+	Content           string `gorm:"column:content" json:"content"`
86
+	Ctime             int64  `gorm:"column:ctime" json:"ctime"`
87
+	Mtime             int64  `gorm:"column:mtime" json:"mtime"`
88
+	Status            int64  `gorm:"column:status" json:"status"`
89
+	StarNum           int64  `gorm:"column:star_num" json:"star_num"`
90
+	CommentNum        int64  `gorm:"column:comment_num" json:"comment_num"`
91
+	CommentId         int64  `gorm:"column:comment_id" json:"comment_id"`
92
+	CommentUserName   string `gorm:"column:comment_user_name" json:"comment_user_name"`
93
+	CommentUserAvater string `gorm:"column:comment_user_avater" json:"comment_user_avater"`
94
+	CommentTime       string `gorm:"-" json:"commentTime"`
95
+	Article           Articles
96
+	Parent            Parents
97
+}
98
+
99
+type Parents struct {
100
+	ID                int64  `gorm:"column:id" json:"id" form:"id"`
101
+	ArticleId         int64  `gorm:"column:article_id" json:"article_id" form:"article_id"`
102
+	CommentUserId     int64  `gorm:"column:comment_user_id" json:"comment_user_id" form:"comment_user_id"`
103
+	ParentId          int64  `gorm:"column:parent_id" json:"parent_id" form:"parent_id"`
104
+	Content           string `gorm:"column:content" json:"content" form:"content"`
105
+	Ctime             int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
106
+	Mtime             int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
107
+	Status            int64  `gorm:"column:status" json:"status" form:"status"`
108
+	StarNum           int64  `gorm:"column:star_num" json:"star_num" form:"star_num"`
109
+	CommentNum        int64  `gorm:"column:comment_num" json:"comment_num" form:"comment_num"`
110
+	CommentId         int64  `gorm:"column:comment_id" json:"comment_id" form:"comment_id"`
111
+	CommentUserName   string `gorm:"column:comment_user_name" json:"comment_user_name" form:"comment_user_name"`
112
+	CommentUserAvater string `gorm:"column:comment_user_avater" json:"comment_user_avater" form:"comment_user_avater"`
113
+	Source            int64  `gorm:"column:source" json:"source" form:"source"`
114
+	Ttid              int64  `gorm:"column:ttid" json:"ttid" form:"ttid"`
115
+	TuserId           int64  `gorm:"column:tuser_id" json:"tuser_id" form:"tuser_id"`
116
+	Taid              int64  `gorm:"column:taid" json:"taid" form:"taid"`
117
+	Tpid              int64  `gorm:"column:tpid" json:"tpid" form:"tpid"`
118
+	Tcid              int64  `gorm:"column:tcid" json:"tcid" form:"tcid"`
119
+}
120
+
121
+func (Comment) TableName() string {
122
+	return "sgj_patient_articles_comment"
123
+}

+ 18 - 0
models/district_models.go View File

@@ -0,0 +1,18 @@
1
+package models
2
+
3
+type District struct {
4
+	ID        int64  `gorm:"column:id" json:"id" form:"id"`
5
+	Name      string `gorm:"column:name" json:"name" form:"name"`
6
+	Level     int64  `gorm:"column:level" json:"level" form:"level"`
7
+	Upid      int64  `gorm:"column:upid" json:"upid" form:"upid"`
8
+	Path      string `gorm:"column:path" json:"path" form:"path"`
9
+	Namepath  string `gorm:"column:namepath" json:"namepath" form:"namepath"`
10
+	Initial   string `gorm:"column:initial" json:"initial" form:"initial"`
11
+	Longitude string `gorm:"column:longitude" json:"longitude" form:"longitude"`
12
+	Latitude  string `gorm:"column:latitude" json:"latitude" form:"latitude"`
13
+	Adcode    int64  `gorm:"column:adcode" json:"adcode" form:"adcode"`
14
+}
15
+
16
+func (District) TableName() string {
17
+	return "sgj_user_district"
18
+}

+ 27 - 0
models/illness_models.go View File

@@ -0,0 +1,27 @@
1
+package models
2
+
3
+type Illness struct {
4
+	ID          int64  `gorm:"column:id" json:"id" form:"id"`
5
+	IllnessName string `gorm:"column:illness_name" json:"illness_name" form:"illness_name"`
6
+	Status      int64  `gorm:"column:status" json:"status" form:"status"`
7
+	CreatedTime int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
8
+	UpdatedTime int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
9
+}
10
+
11
+func (Illness) TableName() string {
12
+	return "sgj_user_illness"
13
+}
14
+
15
+type CustomerIllness struct {
16
+	ID          int64 `gorm:"column:id" json:"id" form:"id"`
17
+	CustomerId  int64 `gorm:"column:customer_id" json:"customer_id" form:"customer_id"`
18
+	IllnessId   int64 `gorm:"column:illness_id" json:"illness_id" form:"illness_id"`
19
+	Status      int64 `gorm:"column:status" json:"status" form:"status"`
20
+	CreatedTime int64 `gorm:"column:created_time" json:"created_time" form:"created_time"`
21
+	UpdatedTime int64 `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
22
+	UserOrgId   int64 `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
23
+}
24
+
25
+func (Illness) CustomerIllness() string {
26
+	return "sgj_user_customer_illness"
27
+}

+ 19 - 0
models/login_models.go View File

@@ -0,0 +1,19 @@
1
+package models
2
+
3
+type SgjUserAdmin struct {
4
+	ID           int64  `gorm:"column:id" json:"id" form:"id"`
5
+	Mobile       string `gorm:"column:mobile" json:"mobile" form:"mobile"`
6
+	Password     string `gorm:"column:password" json:"password" form:"password"`
7
+	IsSuperAdmin int64  `gorm:"column:is_super_admin" json:"is_super_admin" form:"is_super_admin"`
8
+	Status       int64  `gorm:"column:status" json:"status" form:"status"`
9
+	Ctime        int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
10
+	Mtime        int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
11
+	Source       int64  `gorm:"column:source" json:"source" form:"source"`
12
+	Ttype        int64  `gorm:"column:ttype" json:"ttype" form:"ttype"`
13
+	Ttid         int64  `gorm:"column:ttid" json:"ttid" form:"ttid"`
14
+	Tuid         int64  `gorm:"column:tuid" json:"tuid" form:"tuid"`
15
+}
16
+
17
+func (SgjUserAdmin) TableName() string {
18
+	return "sgj_user_admin"
19
+}

+ 29 - 0
models/org_fans_models.go View File

@@ -0,0 +1,29 @@
1
+package models
2
+
3
+type OrgFans struct {
4
+	ID          int64  `gorm:"column:id" json:"id" form:"id"`
5
+	UserOrgId   int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
6
+	UserId      int64  `gorm:"column:user_id" json:"user_id" form:"user_id"`
7
+	Mobile      string `gorm:"column:mobile" json:"mobile" form:"mobile"`
8
+	Name        string `gorm:"column:name" json:"name" form:"name"`
9
+	Gender      int64  `gorm:"column:gender" json:"gender" form:"gender"`
10
+	ProvinceId  int64  `gorm:"column:province_id" json:"province_id" form:"province_id"`
11
+	CityId      int64  `gorm:"column:city_id" json:"city_id" form:"city_id"`
12
+	Address     string `gorm:"column:address" json:"address" form:"address"`
13
+	Birthday    int64  `gorm:"column:birthday" json:"birthday" form:"birthday"`
14
+	Openid      string `gorm:"column:openid" json:"openid" form:"openid"`
15
+	Sources     int64  `gorm:"column:sources" json:"sources" form:"sources"`
16
+	Avatar      string `gorm:"column:avatar" json:"avatar" form:"avatar"`
17
+	Unionid     string `gorm:"column:unionid" json:"unionid" form:"unionid"`
18
+	Status      int64  `gorm:"column:status" json:"status" form:"status"`
19
+	CreatedTime int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
20
+	UpdatedTime int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
21
+	Ttid        int64  `gorm:"column:ttid" json:"ttid" form:"ttid"`
22
+	Tuid        int64  `gorm:"column:tuid" json:"tuid" form:"tuid"`
23
+	Taid        int64  `gorm:"column:taid" json:"taid" form:"taid"`
24
+	Ttype       int64  `gorm:"column:ttype" json:"ttype" form:"ttype"`
25
+}
26
+
27
+func (Org) OrgFans() string {
28
+	return "sgj_user_org_fans"
29
+}

+ 92 - 0
models/org_models.go View File

@@ -0,0 +1,92 @@
1
+package models
2
+
3
+type Org struct {
4
+	Id              int64  `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id"` // 机构 ID
5
+	Creator         int64  `json:"creator"`                              // 创建者,即管理员用户的 id
6
+	OrgName         string `gorm:"column:org_name" json:"org_name"`
7
+	OrgShortName    string `gorm:"column:org_short_name" json:"org_short_name"` // 简称
8
+	OrgLogo         string `gorm:"column:org_logo" json:"org_logo"`
9
+	OrgIntroduction string `gorm:"column:org_introduction" json:"org_introduction"`
10
+	Province        int64  `json:"province"` // 省,代号,下面的市、区也一样
11
+	City            int64  `json:"city"`
12
+	District        int64  `json:"district"`
13
+	Address         string `json:"address"`                   // 详细地址
14
+	Illness         string `json:"illness"`                   // 服务病种 多个并用“,”隔开
15
+	Status          int8   `json:"status"`                    // 状态 0.无效 1.有效 2.禁用
16
+	CreateTime      int64  `gorm:"column:ctime" json:"ctime"` // 创建时间
17
+	ModifyTime      int64  `gorm:"column:mtime" json:"mtime"` // 修改时间
18
+
19
+	OrgType        int64   `gorm:"column:org_type" json:"org_type"`
20
+	Evaluate       float64 `gorm:"column:evaluate" json:"evaluate"`
21
+	Comments       int64   `gorm:"column:comments" json:"comments"`
22
+	OperatingState int64   `gorm:"column:operating_state" json:"operating_state"`
23
+	Claim          int64   `gorm:"column:claim" json:"claim"`
24
+	Telephone      string  `gorm:"column:telephone" json:"telephone"`
25
+	BusinessWeek   string  `gorm:"column:business_week" json:"business_week"`
26
+	BusinessTime   string  `gorm:"column:business_time" json:"business_time"`
27
+	Gallery        string  `gorm:"column:gallery" json:"gallery"`
28
+	ContactName    string  `gorm:"column:contact_name" json:"contact_name"`
29
+}
30
+
31
+func (Org) TableName() string {
32
+	return "sgj_user_org"
33
+}
34
+
35
+type OrgGallery struct {
36
+	ID     int64  `gorm:"column:id" json:"id" form:"id"`
37
+	Url    string `gorm:"column:url" json:"url" form:"url"`
38
+	Type   int64  `gorm:"column:type" json:"type" form:"type"`
39
+	OrgId  int64  `gorm:"column:org_id" json:"org_id" form:"org_id"`
40
+	UserId int64  `gorm:"column:user_id" json:"user_id" form:"user_id"`
41
+	Status int64  `gorm:"column:status" json:"status" form:"status"`
42
+	Ctime  int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
43
+	Mtime  int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
44
+}
45
+
46
+func (OrgGallery) TableName() string {
47
+	return "sgj_user_org_gallery"
48
+}
49
+
50
+type OrgApp struct {
51
+	Id         int64 `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id"` // ID
52
+	AppType    int   `gorm:"column:app_type" json:"app_type"`      // 应用类型 1.病友经营;2.科普号;3.血透经营;4.慢病管理
53
+	Creator    int   `json:"creator"`                              // 创建者,即管理员用户的 id
54
+	OrgId      int   `gorm:"column:org_id" json:"org_id"`
55
+	OpenStatus int   `gorm:"column:open_status" json:"open_status"`
56
+	Status     int8  `json:"status"`                    // 状态 0.无效 1.有效 2.禁用
57
+	CreateTime int64 `gorm:"column:ctime" json:"ctime"` // 创建时间
58
+	ModifyTime int64 `gorm:"column:mtime" json:"mtime"` // 修改时间
59
+}
60
+
61
+func (OrgApp) TableName() string {
62
+	return "sgj_user_org_app"
63
+}
64
+
65
+type OrgBan struct {
66
+	ID      int64  `gorm:"column:id" json:"id"`
67
+	OrgId   int64  `gorm:"column:org_id" json:"org_id"`
68
+	Reason  string `gorm:"column:reason" json:"reason"`
69
+	Ctime   int64  `gorm:"column:ctime" json:"ctime"`
70
+	BanTime int64  `gorm:"column:ban_time" json:"ban_time"`
71
+	Status  int64  `gorm:"column:status" json:"status"`
72
+	Mtime   int64  `gorm:"column:mtime" json:"mtime"`
73
+}
74
+
75
+func (OrgBan) TableName() string {
76
+	return "sgj_user_admin_org_ban"
77
+}
78
+
79
+type OrgType struct {
80
+	ID          int64  `gorm:"column:id" json:"id" form:"id"`
81
+	Name        string `gorm:"column:name" json:"name" form:"name"`
82
+	ShortName   string `gorm:"column:short_name" json:"short_name" form:"short_name"`
83
+	Pid         int64  `gorm:"column:pid" json:"pid" form:"pid"`
84
+	Status      int64  `gorm:"column:status" json:"status" form:"status"`
85
+	CreatedTime int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
86
+	UpdatedTime int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
87
+	SortNo      int64  `gorm:"column:sort_no" json:"sort_no" form:"sort_no"`
88
+}
89
+
90
+func (OrgType) TableName() string {
91
+	return "sgj_user_org_type"
92
+}

+ 37 - 0
models/purview_models.go View File

@@ -0,0 +1,37 @@
1
+package models
2
+
3
+type Purview struct {
4
+	Id                  int64  `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id"`
5
+	Parentid            int64  `json:"pid"`                                                // 父级ID
6
+	Module              int8   `json:"module"`                                             // 所属应用类型 1.病友经营;2.科普号;3.血透经营;4.慢病管理;
7
+	Name                string `json:"name"`                                               // 规则名称(也是菜单名)
8
+	Urlfor              string `json:"urlfor"`                                             // 规则唯一英文标识,(Controller.Method)
9
+	MenuIconClass       string `gorm:"menu_icon_class" json:"menu_icon_class"`             // 菜单图标的 css 样式
10
+	SuperAdminExclusive int8   `gorm:"super_admin_exclusive" json:"super_admin_exclusive"` // 是否为超级管理员专属 0否1是
11
+	Listorder           int    `json:"-"`                                                  // 排序ID
12
+	Status              int8   `json:"status"`                                             // 状态 0.无效 1.有效 2.禁用
13
+	CreateTime          int64  `gorm:"column:ctime" json:"-"`                              // 创建时间
14
+	ModifyTime          int64  `gorm:"column:mtime" json:"-"`                              // 修改时间
15
+
16
+	Link   string     `gorm:"-" json:"link"`   // urlfor 解析后的链接
17
+	Childs []*Purview `gorm:"-" json:"childs"` // 子节点
18
+}
19
+
20
+func (Purview) TableName() string {
21
+	return "sgj_user_purview"
22
+}
23
+
24
+type RolePurview struct {
25
+	Id         int64 `gorm:"PRIMARY_KEY;AUTO_INCREMENT"`
26
+	RoleId     int64
27
+	OrgId      int64
28
+	AppId      int64
29
+	PurviewIds string
30
+	Status     int8  // 状态 0.无效 1.有效 2.禁用
31
+	CreateTime int64 `gorm:"column:ctime"` // 创建时间
32
+	ModifyTime int64 `gorm:"column:mtime"` // 修改时间
33
+}
34
+
35
+func (RolePurview) TableName() string {
36
+	return "sgj_user_role_purview"
37
+}

+ 61 - 0
models/role_models.go View File

@@ -0,0 +1,61 @@
1
+package models
2
+
3
+type Role struct {
4
+	Id           int64  `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id"`
5
+	RoleName     string `gorm:"column:role_name" json:"name"`
6
+	RoleIntro    string `gorm:"column:role_introduction" json:"intro"`
7
+	Creator      int64  `json:"-"`
8
+	OrgId        int64  `gorm:"column:org_id" json:"-"`
9
+	AppId        int64  `gorm:"column:app_id" json:"-"`
10
+	IsSuperAdmin bool   `gorm:"column:is_super_admin" json:"-"`
11
+	Status       int8   `json:"status"`                // 状态 0.无效 1.有效 2.禁用
12
+	CreateTime   int64  `gorm:"column:ctime" json:"-"` // 创建时间
13
+	ModifyTime   int64  `gorm:"column:mtime" json:"-"` // 修改时间
14
+}
15
+
16
+func (Role) TableName() string {
17
+	return "sgj_user_role"
18
+}
19
+
20
+type App_Role struct {
21
+	Id          int64  `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id"`
22
+	AdminUserId int64  `gorm:"column:admin_user_id" json:"admin_user_id"`
23
+	OrgId       int64  `gorm:"column:org_id" json:"org_id"`
24
+	AppId       int64  `gorm:"column:app_id" json:"app_id"`
25
+	RoleId      int64  `gorm:"column:role_id" json:"role_id"`
26
+	Avatar      string `json:"avatar" json:"avatar"`
27
+	UserName    string `gorm:"column:user_name" json:"user_name"`   // 用户名称
28
+	Intro       string `json:"intro"`                               // 简介
29
+	UserType    int8   `gorm:"column:user_type" json:"user_type"`   // 用户类型(1.管理员;2.医生;3.护士;4.运营)
30
+	UserTitle   int8   `gorm:"column:user_title" json:"user_title"` // 用户职称(1.医士;2.医师;3.住院医师;4.主治医师;5.副主任医师;6.主任医师;7.护士;8.护师;9.主管护师;10.副主任护师;11.主任护师;12.运营专员;13.运营主管)
31
+	Status      int8   `json:"status"`                              // 状态 0.无效 1.有效
32
+	CreateTime  int64  `gorm:"column:ctime" json:"ctime"`           // 创建时间
33
+	ModifyTime  int64  `gorm:"column:mtime" json:"mtime"`           // 修改时间
34
+}
35
+
36
+func (App_Role) TableName() string {
37
+	return "sgj_user_admin_role"
38
+}
39
+
40
+var UserType = map[int]string{
41
+	1: "管理员",
42
+	2: "医生",
43
+	3: "护士",
44
+	4: "运营",
45
+}
46
+
47
+var UserTitle = map[int]string{
48
+	1:  "医士",
49
+	2:  "医师",
50
+	3:  "住院医师",
51
+	4:  "主治医师",
52
+	5:  "副主任医师",
53
+	6:  "主任医师",
54
+	7:  "护士",
55
+	8:  "护师",
56
+	9:  "主管护师",
57
+	10: "副主任护师",
58
+	11: "主任护师",
59
+	12: "运营专员",
60
+	13: "运营主管",
61
+}

+ 130 - 0
models/service_models.go View File

@@ -0,0 +1,130 @@
1
+package models
2
+
3
+import "time"
4
+
5
+type ServeOrder struct {
6
+	ID                    int64     `gorm:"column:id" json:"id"`
7
+	OrgId                 int64     `gorm:"column:org_id" json:"org_id"`
8
+	Period                int64     `gorm:"column:period" json:"period"`
9
+	PeriodStart           int64     `gorm:"column:period_start" json:"period_start"`
10
+	PeriodEnd             int64     `gorm:"column:period_end" json:"period_end"`
11
+	PeriodStartTime       time.Time `gorm:"column:period_start_time" json:"period_start_time"`
12
+	PeriodEndTime         time.Time `gorm:"column:period_end_time" json:"period_end_time"`
13
+	Status                int64     `gorm:"column:status" json:"status"`
14
+	CreatedTime           int64     `gorm:"column:created_time" json:"created_time"`
15
+	UpdatedTime           int64     `gorm:"column:updated_time" json:"updated_time"`
16
+	OrderNumber           string    `gorm:"column:order_number" json:"order_number"`
17
+	OrderStatus           int64     `gorm:"column:order_status" json:"order_status"`
18
+	PayType               int64     `gorm:"column:pay_type" json:"pay_type"`
19
+	PayTime               int64     `gorm:"column:pay_time" json:"pay_time"`
20
+	PaymentAmount         float64   `gorm:"column:payment_amount" json:"payment_amount"`
21
+	PayableAmount         float64   `gorm:"column:payable_amount" json:"payable_amount"`
22
+	DiscountableAmount    float64   `gorm:"column:discountable_amount" json:"discountable_amount"`
23
+	PaymentTransactionId  string    `gorm:"column:payment_transaction_id" json:"payment_transaction_id"`
24
+	ServeName             string    `gorm:"column:serve_name" json:"serve_name"`
25
+	ServeDesc             string    `gorm:"column:serve_desc" json:"serve_desc"`
26
+	ServeDuration         string    `gorm:"column:serve_duration" json:"serve_duration"`
27
+	OrderExpireTime       int64     `gorm:"column:order_expire_time" json:"order_expire_time"`
28
+	Price                 float64   `gorm:"column:price" json:"price"`
29
+	Quantity              int64     `gorm:"column:quantity" json:"quantity"`
30
+	ServeId               int64     `gorm:"column:serve_id" json:"serve_id"`
31
+	OrderExpireTimeFormat string    `gorm:"-"`
32
+}
33
+
34
+func (ServeOrder) TableName() string {
35
+	return "sgj_serve_order"
36
+}
37
+
38
+type ServeOrderInfomation struct {
39
+	ID          int64   `gorm:"column:id" json:"id"`
40
+	OrgId       int64   `gorm:"column:org_id" json:"org_id"`
41
+	OrderNumber string  `gorm:"column:order_number" json:"order_number"`
42
+	ProductId   int64   `gorm:"column:product_id" json:"product_id"`
43
+	ProductName string  `gorm:"column:product_name" json:"product_name"`
44
+	ProductDesc string  `gorm:"column:product_desc" json:"product_desc"`
45
+	Price       float64 `gorm:"column:price" json:"price"`
46
+	Quantity    int64   `gorm:"column:quantity" json:"quantity"`
47
+	MarketPrice float64 `gorm:"column:market_price" json:"market_price"`
48
+	Status      int64   `gorm:"column:status" json:"status"`
49
+}
50
+
51
+func (ServeOrderInfomation) TableName() string {
52
+	return "sgj_serve_order_infomation"
53
+}
54
+
55
+type ServeProduct struct {
56
+	ID            int64   `gorm:"column:id" json:"id"`
57
+	ServeName     string  `gorm:"column:serve_name" json:"serve_name"`
58
+	ServeDesc     string  `gorm:"column:serve_desc" json:"serve_desc"`
59
+	OriginalPrice float64 `gorm:"column:original_price" json:"original_price"`
60
+	Price         float64 `gorm:"column:price" json:"price"`
61
+	Status        int64   `gorm:"column:status" json:"status"`
62
+	CreatedTime   int64   `gorm:"column:created_time" json:"created_time"`
63
+	UpdatedTime   int64   `gorm:"column:updated_time" json:"updated_time"`
64
+	ServeDuration int64   `gorm:"column:serve_duration" json:"serve_duration"`
65
+	Edition       int64   `gorm:"column:edition" json:"edition"`
66
+}
67
+
68
+func (ServeProduct) TableName() string {
69
+	return "sgj_serve_product"
70
+}
71
+
72
+type ServeSubscibe struct {
73
+	ID              int64     `gorm:"column:id" json:"id"`
74
+	OrgId           int64     `gorm:"column:org_id" json:"org_id"`
75
+	PeriodStart     int64     `gorm:"column:period_start" json:"period_start"`
76
+	PeriodEnd       int64     `gorm:"column:period_end" json:"period_end"`
77
+	PeriodStartTime time.Time `gorm:"column:period_start_time" json:"period_start_time"`
78
+	PeriodEndTime   time.Time `gorm:"column:period_end_time" json:"period_end_time"`
79
+	Status          int64     `gorm:"column:status" json:"status"`
80
+	CreatedTime     int64     `gorm:"column:created_time" json:"created_time"`
81
+	UpdatedTime     int64     `gorm:"column:updated_time" json:"updated_time"`
82
+	State           int64     `gorm:"column:state" json:"state" form:"statstateus"`
83
+	Org             Org       `gorm:"ForeignKey:OrgId"`
84
+
85
+	Patients int64 `gorm:"-" json:"patients"`
86
+}
87
+
88
+func (ServeSubscibe) TableName() string {
89
+	return "sgj_serve_subscibe"
90
+}
91
+
92
+type ServeInvoice struct {
93
+	ID                      int64   `gorm:"column:id" json:"id" form:"id"`
94
+	InvoiceType             int64   `gorm:"column:invoice_type" json:"invoice_type" form:"invoice_type"`
95
+	OrgId                   int64   `gorm:"column:org_id" json:"org_id" form:"org_id"`
96
+	InvoiceTitle            string  `gorm:"column:invoice_title" json:"invoice_title" form:"invoice_title"`
97
+	InvoiceAmountGross      float64 `gorm:"column:invoice_amount_gross" json:"invoice_amount_gross" form:"invoice_amount_gross"`
98
+	Recipient               string  `gorm:"column:recipient" json:"recipient" form:"recipient"`
99
+	ContactPhone            string  `gorm:"column:contact_phone" json:"contact_phone" form:"contact_phone"`
100
+	Address                 string  `gorm:"column:address" json:"address" form:"address"`
101
+	TaxIdentificationNumber string  `gorm:"column:tax_identification_number" json:"tax_identification_number" form:"tax_identification_number"`
102
+	Remark                  string  `gorm:"column:remark" json:"remark" form:"remark"`
103
+	Status                  int64   `gorm:"column:status" json:"status" form:"status"`
104
+	CreatedTime             int64   `gorm:"column:created_time" json:"created_time" form:"created_time"`
105
+	UpdatedTime             int64   `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
106
+	Orders                  string  `gorm:"column:orders" json:"orders" form:"orders"`
107
+	InvoiceStatus           int64   `gorm:"column:invoice_status" json:"invoice_status" form:"invoice_status"`
108
+}
109
+
110
+func (ServeInvoice) TableName() string {
111
+	return "sgj_serve_invoice"
112
+}
113
+
114
+type ServeOrderContract struct {
115
+	ID             int64  `gorm:"column:id" json:"id" form:"id"`
116
+	OrgId          int64  `gorm:"column:org_id" json:"org_id" form:"org_id"`
117
+	OrderId        int64  `gorm:"column:order_id" json:"order_id" form:"order_id"`
118
+	OrderNumber    string `gorm:"column:order_number" json:"order_number" form:"order_number"`
119
+	CompanyTitle   string `gorm:"column:company_title" json:"company_title" form:"company_title"`
120
+	CompanyAddress string `gorm:"column:company_address" json:"company_address" form:"company_address"`
121
+	ContactPhone   string `gorm:"column:contact_phone" json:"contact_phone" form:"contact_phone"`
122
+	Contact        string `gorm:"column:contact" json:"contact" form:"contact"`
123
+	Status         int64  `gorm:"column:status" json:"status" form:"status"`
124
+	CreatedTime    int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
125
+	UpdatedTime    int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
126
+}
127
+
128
+func (ServeOrderContract) TableName() string {
129
+	return "sgj_serve_order_contract"
130
+}

+ 557 - 0
models/site_models.go View File

@@ -0,0 +1,557 @@
1
+package models
2
+
3
+//轮播图
4
+type SgjPatientRotation struct {
5
+	ID             int64  `gorm:"column:id" json:"id" form:"id"`
6
+	Title          string `gorm:"column:title" json:"title" form:"title"`
7
+	Sort           int64  `gorm:"column:sort" json:"sort" form:"sort"`
8
+	RotationImages string `gorm:"column:rotation_images" json:"rotation_images" form:"rotation_images"`
9
+	UserOrgId      int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
10
+	Ctime          int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
11
+	Mtime          int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
12
+	Status         int64  `gorm:"column:status" json:"status" form:"status"`
13
+	ModelId        int64  `gorm:"column:model_id" json:"model_id" form:"model_id"`
14
+}
15
+
16
+func (SgjPatientRotation) TableName() string {
17
+	return "sgj_patient_rotation"
18
+}
19
+
20
+type SgjPatientModel struct {
21
+	ID        int64              `gorm:"column:id" json:"id" form:"id"`
22
+	Title     string             `gorm:"column:title" json:"title" form:"title"`
23
+	Sort      int64              `gorm:"column:sort" json:"sort" form:"sort"`
24
+	Ctime     int64              `gorm:"column:ctime" json:"ctime" form:"ctime"`
25
+	Mtime     int64              `gorm:"column:mtime" json:"mtime" form:"mtime"`
26
+	Status    int64              `gorm:"column:status" json:"status" form:"status"`
27
+	UserOrgId int64              `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
28
+	ModeType  int64              `gorm:"column:mode_type" json:"mode_type" form:"mode_type"`
29
+	Hospitals SgjPatientHospital `gorm:"ForeignKey:Modleid"`
30
+	Offices   SgjPatientOffices  `gorm:"ForeignKey:Modleid"`
31
+	//Doctors     SgjPatientDocinfo `gorm:"ForeignKey:Modelid"`
32
+	OfficeEnviroment SgjPatientOffenvironment `gorm:"ForeignKey:Modelid"`
33
+	Editdoctor       []SgjPatientEditdoctor   `gorm:"ForeignKey:Modleid"`
34
+	//Rotation     SgjPatientRotation  `gorm:"ForeignKey:ModelId"`
35
+	//Macnavigation  SgjPatientMacnavigation `gorm:"ForeignKey:Modeid"`
36
+	Addactivity        SgjPatientAddactivity    `gorm:"ForeignKey:Modeid"`
37
+	Articlelist        SgjPatientArticlelist    `gorm:"ForeignKey:Modeid"`
38
+	Editmargin         []SgjPatientEditmargin   `gorm:"ForeignKey:Modeid"`
39
+	Enviroimages       []SgjPatientEnviroimages `gorm:"ForeignKey:Modeid"`
40
+	PatientEditpiclink []SgjPatientEditpiclink  `gorm:"ForeignKey:Modeid"`
41
+}
42
+
43
+func (SgjPatientModel) TableName() string {
44
+	return "sgj_patient_model"
45
+}
46
+
47
+type PatientModel struct {
48
+	ID        int64  `gorm:"column:id" json:"id" form:"id"`
49
+	Title     string `gorm:"column:title" json:"title" form:"title"`
50
+	Sort      int64  `gorm:"column:sort" json:"sort" form:"sort"`
51
+	Ctime     int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
52
+	Mtime     int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
53
+	Status    int64  `gorm:"column:status" json:"status" form:"status"`
54
+	UserOrgId int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
55
+	ModeType  int64  `gorm:"column:mode_type" json:"mode_type" form:"mode_type"`
56
+}
57
+
58
+func (PatientModel) TableName() string {
59
+	return "sgj_patient_model"
60
+}
61
+
62
+//医院介绍
63
+type SgjPatientHospital struct {
64
+	ID           int64  `gorm:"column:id" json:"id" form:"id"`
65
+	Title        string `gorm:"column:title" json:"title" form:"title"`
66
+	Sort         int64  `gorm:"column:sort" json:"sort" form:"sort"`
67
+	Introduction string `gorm:"column:introduction" json:"introduction" form:"introduction"`
68
+	Ctime        int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
69
+	Mtime        int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
70
+	UserOrgId    int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
71
+	Status       int64  `gorm:"column:status" json:"status" form:"status"`
72
+	Modleid      int64  `gorm:"column:modleid" json:"modleid" form:"modleid"`
73
+}
74
+
75
+func (SgjPatientHospital) TableName() string {
76
+	return "sgj_patient_hospital"
77
+}
78
+
79
+type SgjPatientEnviroimages struct {
80
+	ID           int64  `gorm:"column:id" json:"id" form:"id"`
81
+	Enviroimages string `gorm:"column:enviroimages" json:"enviroimages" form:"enviroimages"`
82
+	Sort         int64  `gorm:"column:sort" json:"sort" form:"sort"`
83
+	UserOrgId    int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
84
+	Status       int64  `gorm:"column:status" json:"status" form:"status"`
85
+	Ctime        int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
86
+	Mtime        int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
87
+	Modeid       int64  `gorm:"column:modeid" json:"modeid" form:"modeid"`
88
+	Imgshow      int64  `gorm:"column:imgshow" json:"imgshow" form:"imgshow"`
89
+}
90
+
91
+func (SgjPatientEnviroimages) TableName() string {
92
+
93
+	return "sgj_patient_enviroimages"
94
+}
95
+
96
+//科室介绍
97
+type SgjPatientOffices struct {
98
+	ID           int64  `gorm:"column:id" json:"id" form:"id"`
99
+	Title        string `gorm:"column:title" json:"title" form:"title"`
100
+	Sort         int64  `gorm:"column:sort" json:"sort" form:"sort"`
101
+	Introduction string `gorm:"column:introduction" json:"introduction" form:"introduction"`
102
+	Mtime        int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
103
+	Ctime        int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
104
+	UserOrgId    int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
105
+	Status       int64  `gorm:"column:status" json:"status" form:"status"`
106
+	Modleid      int64  `gorm:"column:modleid" json:"modelid" form:"modelid"`
107
+}
108
+
109
+func (SgjPatientOffices) TableName() string {
110
+	return "sgj_patient_offices"
111
+}
112
+
113
+//名医介绍
114
+type SgjPatientDocinfo struct {
115
+	ID        int64  `gorm:"column:id" json:"id" form:"id"`
116
+	Title     string `gorm:"column:title" json:"title" form:"title"`
117
+	Sort      int64  `gorm:"column:sort" json:"sort" form:"sort"`
118
+	Docimages string `gorm:"column:docimages" json:"docimages" form:"docimages"`
119
+	Ctime     int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
120
+	Mtime     int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
121
+	Status    int64  `gorm:"column:status" json:"status" form:"status"`
122
+	UserOrgId int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
123
+	Modelid   int64  `gorm:"column:modelid" json:"modelid" form:"modelid"`
124
+}
125
+
126
+func (SgjPatientDocinfo) TableName() string {
127
+
128
+	return "sgj_patient_docinfo"
129
+}
130
+
131
+//编辑名医介绍
132
+type SgjPatientEditdoctor struct {
133
+	ID              int64  `gorm:"column:id" json:"id" form:"id"`
134
+	DocPostion      int64  `gorm:"column:doc_postion" json:"doc_postion" form:"doc_postion"`
135
+	Dochead         string `gorm:"column:dochead" json:"dochead" form:"dochead"`
136
+	DocSort         int64  `gorm:"column:doc_sort" json:"doc_sort" form:"doc_sort"`
137
+	Docintroduction string `gorm:"column:docintroduction" json:"docintroduction" form:"docintroduction"`
138
+	UserOrgId       int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
139
+	Ctime           int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
140
+	Mtime           int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
141
+	Status          int64  `gorm:"column:status" json:"status" form:"status"`
142
+	DocName         string `gorm:"column:doc_name" json:"doc_name" form:"doc_name"`
143
+	Modleid         int64  `gorm:"column:modleid" json:"modleid" form:"modleid"`
144
+	ImgShow         int64  `gorm:"column:img_show" json:"img_show" form:"img_show"`
145
+}
146
+
147
+func (SgjPatientEditdoctor) TableName() string {
148
+
149
+	return "sgj_patient_editdoctor"
150
+}
151
+
152
+// 科室环境
153
+type SgjPatientOffenvironment struct {
154
+	ID        int64  `gorm:"column:id" json:"id" form:"id"`
155
+	Title     string `gorm:"column:title" json:"title" form:"title"`
156
+	Sort      int64  `gorm:"column:sort" json:"sort" form:"sort"`
157
+	Keimages  string `gorm:"column:keimages" json:"keimages" form:"keimages"`
158
+	UserOrgId int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
159
+	Ctime     int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
160
+	Mtime     int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
161
+	Status    int64  `gorm:"column:status" json:"status" form:"status"`
162
+	Modelid   int64  `gorm:"column:modelid" json:"modelid" form:"modelid"`
163
+}
164
+
165
+func (SgjPatientOffenvironment) TableName() string {
166
+	return "sgj_patient_offenvironment"
167
+}
168
+
169
+type SgjPatientConnection struct {
170
+	ID        int64  `gorm:"column:id" json:"id" form:"id"`
171
+	Title     string `gorm:"column:title" json:"title" form:"title"`
172
+	Connecway int64  `gorm:"column:connecway" json:"connecway" form:"connecway"`
173
+	Content   string `gorm:"column:content" json:"content" form:"content"`
174
+	Status    int64  `gorm:"column:status" json:"status" form:"status"`
175
+	Ctime     int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
176
+	Mtime     int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
177
+	UserOrgId int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
178
+}
179
+
180
+func (SgjPatientConnection) TableName() string {
181
+
182
+	return "sgj_patient_connection"
183
+}
184
+
185
+type SgjPatientConnecmodel struct {
186
+	ID              int64  `gorm:"column:id" json:"id" form:"id"`
187
+	Title           string `gorm:"column:title" json:"title" form:"title"`
188
+	Sort            int64  `gorm:"column:sort" json:"sort" form:"sort"`
189
+	RotationImages  string `gorm:"column:rotation_images" json:"rotation_images" form:"rotation_images"`
190
+	HospitalAddress string `gorm:"column:hospital_address" json:"hospital_address" form:"hospital_address"`
191
+	HospitalMap     string `gorm:"column:hospital_map" json:"hospital_map" form:"hospital_map"`
192
+	ConnectionWay   string `gorm:"column:connection_way" json:"connection_way" form:"connection_way"`
193
+	Worktime        string `gorm:"column:worktime" json:"worktime" form:"worktime"`
194
+	Rideway         string `gorm:"column:rideway" json:"rideway" form:"rideway"`
195
+	UserOrgId       int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
196
+	Status          int64  `gorm:"column:status" json:"status" form:"status"`
197
+	Ctime           int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
198
+	Mtime           int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
199
+	ModeType        int64  `gorm:"column:mode_type" json:"mode_type" form:"mode_type"`
200
+}
201
+
202
+func (SgjPatientConnecmodel) TableName() string {
203
+
204
+	return "sgj_patient_connecmodel"
205
+}
206
+
207
+type SgjPatientNewmodel struct {
208
+	ID                   int64  `gorm:"column:id" json:"id" form:"id"`
209
+	Title                string `gorm:"column:title" json:"title" form:"title"`
210
+	Sort                 int64  `gorm:"column:sort" json:"sort" form:"sort"`
211
+	RotationImages       string `gorm:"column:rotation_images" json:"rotation_images" form:"rotation_images"`
212
+	HospitalIntroduction string `gorm:"column:hospital_introduction" json:"hospital_introduction" form:"hospital_introduction"`
213
+	OfficeIntroduction   string `gorm:"column:office_introduction" json:"office_introduction" form:"office_introduction"`
214
+	DoctorImages         string `gorm:"column:doctor_images" json:"doctor_images" form:"doctor_images"`
215
+	OfficeImages         string `gorm:"column:office_images" json:"office_images" form:"office_images"`
216
+	UserOrgId            int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
217
+	Status               int64  `gorm:"column:status" json:"status" form:"status"`
218
+	Ctime                int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
219
+	Mtime                int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
220
+	Docname              string `gorm:"column:docname" json:"docname" form:"docname"`
221
+	Dochead              string `gorm:"column:dochead" json:"dochead" form:"dochead"`
222
+	DocPositional        string `gorm:"column:doc_positional" json:"doc_positional" form:"doc_positional"`
223
+	DocIntroduction      string `gorm:"column:doc_introduction" json:"doc_introduction" form:"doc_introduction"`
224
+}
225
+
226
+func (SgjPatientNewmodel) TableName() string {
227
+
228
+	return "sgj_patient_newmodel"
229
+
230
+}
231
+
232
+type SgjPatientNavigation struct {
233
+	ID          int64  `gorm:"column:id" json:"id" form:"id"`
234
+	Navtitle    string `gorm:"column:navtitle" json:"navtitle" form:"navtitle"`
235
+	Navimages   string `gorm:"column:navimages" json:"navimages" form:"navimages"`
236
+	Jumpset     int64  `gorm:"column:jumpset" json:"jumpset" form:"jumpset"`
237
+	Navaddress  string `gorm:"column:navaddress" json:"navaddress" form:"navaddress"`
238
+	Ctime       int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
239
+	Mtime       int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
240
+	Status      int64  `gorm:"column:status" json:"status" form:"status"`
241
+	UserOrgId   int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
242
+	Linkid      int64  `gorm:"column:linkid" json:"linkid" form:"linkid"`
243
+	Nonavimages string `gorm:"column:nonavimages" json:"nonavimages" form:"nonavimages"`
244
+	Linktype    int64  `gorm:"column:linktype" json:"linktype" form:"linktype"`
245
+}
246
+
247
+func (SgjPatientNavigation) TableName() string {
248
+
249
+	return "sgj_patient_navigation"
250
+}
251
+
252
+type SgjPatientShare struct {
253
+	ID                int64  `gorm:"column:id" json:"id" form:"id"`
254
+	ShareTitle        string `gorm:"column:share_title" json:"share_title" form:"share_title"`
255
+	ShareIntroduction string `gorm:"column:share_introduction" json:"share_introduction" form:"share_introduction"`
256
+	ShareImages       string `gorm:"column:share_images" json:"share_images" form:"share_images"`
257
+	UserOrgId         int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
258
+	Ctime             int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
259
+	Mtime             int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
260
+	Status            int64  `gorm:"column:status" json:"status" form:"status"`
261
+}
262
+
263
+func (SgjPatientShare) TableName() string {
264
+
265
+	return "sgj_patient_share"
266
+}
267
+
268
+type SgjPatientOrdmodel struct {
269
+	ID          int64                   `gorm:"column:id" json:"id" form:"id"`
270
+	Title       string                  `gorm:"column:title" json:"title" form:"title"`
271
+	Sort        int64                   `gorm:"column:sort" json:"sort" form:"sort"`
272
+	Ctime       int64                   `gorm:"column:ctime" json:"ctime" form:"ctime"`
273
+	Mtime       int64                   `gorm:"column:mtime" json:"mtime" form:"mtime"`
274
+	UserOrgId   int64                   `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
275
+	Status      int64                   `gorm:"column:status" json:"status" form:"status"`
276
+	ModeType    int64                   `gorm:"column:mode_type" json:"mode_type" form:"mode_type"`
277
+	Hosaddress  SgjPatientHosaddress    `gorm:"ForeignKey:Modeid"`
278
+	Connectway  SgjPatientConnectway    `gorm:"ForeignKey:ModeId"`
279
+	Worktime    SgjPatientWorktime      `gorm:"ForeignKey:ModeId"`
280
+	Rideway     SgjPatientRideway       `gorm:"ForeignKey:ModeId"`
281
+	Oldration   SgjPatientOldrotation   `gorm:"ForeignKey:ModeId"`
282
+	Conrotation []SgjPatientConrotation `gorm:"ForeignKey:Modeid"`
283
+}
284
+
285
+func (SgjPatientOrdmodel) TableName() string {
286
+
287
+	return "sgj_patient_ordmodel"
288
+}
289
+
290
+type SgjPatientConnectway struct {
291
+	ID        int64  `gorm:"column:id" json:"id" form:"id"`
292
+	Title     string `gorm:"column:title" json:"title" form:"title"`
293
+	UserOrgId int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
294
+	Ctime     int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
295
+	Mtime     int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
296
+	Status    int64  `gorm:"column:status" json:"status" form:"status"`
297
+	Sort      int64  `gorm:"column:sort" json:"sort" form:"sort"`
298
+	ModeId    int64  `gorm:"column:mode_id" json:"mode_id" form:"mode_id"`
299
+}
300
+
301
+func (SgjPatientConnectway) TableName() string {
302
+
303
+	return "sgj_patient_connectway"
304
+}
305
+
306
+type SgjPatientWorktime struct {
307
+	ID        int64  `gorm:"column:id" json:"id" form:"id"`
308
+	Title     string `gorm:"column:title" json:"title" form:"title"`
309
+	Sort      int64  `gorm:"column:sort" json:"sort" form:"sort"`
310
+	Worktime  string `gorm:"column:worktime" json:"worktime" form:"worktime"`
311
+	UserOrgId int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
312
+	ModeId    int64  `gorm:"column:mode_id" json:"mode_id" form:"mode_id"`
313
+	Status    int64  `gorm:"column:status" json:"status" form:"status"`
314
+	Ctime     int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
315
+	Mtime     int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
316
+}
317
+
318
+func (SgjPatientWorktime) TableName() string {
319
+
320
+	return "sgj_patient_worktime"
321
+}
322
+
323
+type SgjPatientRideway struct {
324
+	ID        int64  `gorm:"column:id" json:"id" form:"id"`
325
+	Title     string `gorm:"column:title" json:"title" form:"title"`
326
+	Sort      int64  `gorm:"column:sort" json:"sort" form:"sort"`
327
+	RideWay   string `gorm:"column:ride_way" json:"ride_way" form:"ride_way"`
328
+	Ctime     int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
329
+	Mtime     int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
330
+	Status    int64  `gorm:"column:status" json:"status" form:"status"`
331
+	UserOrgId int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
332
+	ModeId    int64  `gorm:"column:mode_id" json:"mode_id" form:"mode_id"`
333
+}
334
+
335
+func (SgjPatientRideway) TableName() string {
336
+
337
+	return "sgj_patient_rideway"
338
+}
339
+
340
+type SgjPatientConrotation struct {
341
+	ID          int64  `gorm:"column:id" json:"id" form:"id"`
342
+	Images      string `gorm:"column:images" json:"images" form:"images"`
343
+	Sort        int64  `gorm:"column:sort" json:"sort" form:"sort"`
344
+	Piclink     int64  `gorm:"column:piclink" json:"piclink" form:"piclink"`
345
+	Linkaddress string `gorm:"column:linkaddress" json:"linkaddress" form:"linkaddress"`
346
+	Status      int64  `gorm:"column:status" json:"status" form:"status"`
347
+	UserOrgId   int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
348
+	Ctime       int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
349
+	Mtime       int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
350
+	Modeid      int64  `gorm:"column:modeid" json:"modeid" form:"modeid"`
351
+	ImgShow     int64  `gorm:"column:img_show" json:"img_show" form:"img_show"`
352
+	Linkid      int64  `gorm:"column:linkid" json:"linkid" form:"linkid"`
353
+}
354
+
355
+func (SgjPatientConrotation) TableName() string {
356
+
357
+	return "sgj_patient_conrotation"
358
+}
359
+
360
+type SgjPatientOldrotation struct {
361
+	ID             int64  `gorm:"column:id" json:"id" form:"id"`
362
+	Title          string `gorm:"column:title" json:"title" form:"title"`
363
+	Sort           int64  `gorm:"column:sort" json:"sort" form:"sort"`
364
+	RotationImages string `gorm:"column:rotation_images" json:"rotation_images" form:"rotation_images"`
365
+	UserOrgId      int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
366
+	ModeId         int64  `gorm:"column:mode_id" json:"mode_id" form:"mode_id"`
367
+	Status         int64  `gorm:"column:status" json:"status" form:"status"`
368
+	Ctime          int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
369
+	Mtime          int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
370
+}
371
+
372
+func (SgjPatientOldrotation) TableName() string {
373
+
374
+	return "sgj_patient_oldrotation"
375
+}
376
+
377
+type SgjPatientEditpiclink struct {
378
+	ID          int64  `gorm:"column:id" json:"id" form:"id"`
379
+	Images      string `gorm:"column:images" json:"images" form:"images"`
380
+	Sort        int64  `gorm:"column:sort" json:"sort" form:"sort"`
381
+	Piclink     int64  `gorm:"column:piclink" json:"piclink" form:"piclink"`
382
+	Linkaddress string `gorm:"column:linkaddress" json:"linkaddress" form:"linkaddress"`
383
+	UserOrgId   int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
384
+	Status      int64  `gorm:"column:status" json:"status" form:"status"`
385
+	Ctime       int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
386
+	Mtime       int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
387
+	Modeid      int64  `gorm:"column:modeid" json:"modeid" form:"modeid"`
388
+	ImgShow     int64  `gorm:"column:img_show" json:"img_show" form:"img_show"`
389
+	Linkid      int64  `gorm:"column:linkid" json:"linkid" form:"linkid"`
390
+}
391
+
392
+func (SgjPatientEditpiclink) TableName() string {
393
+
394
+	return "sgj_patient_editpiclink"
395
+}
396
+
397
+type SgjPatientEditmargin struct {
398
+	ID            int64  `gorm:"column:id" json:"id" form:"id"`
399
+	Margtitle     string `gorm:"column:margtitle" json:"margtitle" form:"margtitle"`
400
+	Margimage     string `gorm:"column:margimage" json:"margimage" form:"margimage"`
401
+	Marginaddress string `gorm:"column:marginaddress" json:"marginaddress" form:"marginaddress"`
402
+	Jumpset       int64  `gorm:"column:jumpset" json:"jumpset" form:"jumpset"`
403
+	UserOrgId     int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
404
+	Status        int64  `gorm:"column:status" json:"status" form:"status"`
405
+	Ctime         int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
406
+	Mtime         int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
407
+	ImgShow       int64  `gorm:"column:img_show" json:"img_show" form:"img_show"`
408
+	Modeid        int64  `gorm:"column:modeid" json:"modeid" form:"modeid"`
409
+	Linkid        int64  `gorm:"column:linkid" json:"linkid" form:"linkid"`
410
+}
411
+
412
+func (SgjPatientEditmargin) TableName() string {
413
+
414
+	return "sgj_patient_editmargin"
415
+}
416
+
417
+type SgjPatientMacnavigation struct {
418
+	ID        int64  `gorm:"column:id" json:"id" form:"id"`
419
+	Title     string `gorm:"column:title" json:"title" form:"title"`
420
+	Sort      int64  `gorm:"column:sort" json:"sort" form:"sort"`
421
+	MacImages string `gorm:"column:mac_images" json:"mac_images" form:"mac_images"`
422
+	Modeid    int64  `gorm:"column:modeid" json:"modeid" form:"modeid"`
423
+	Ctime     int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
424
+	Mtime     int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
425
+	Status    int64  `gorm:"column:status" json:"status" form:"status"`
426
+	UserOrgId int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
427
+	MacTitles string `gorm:"column:mac_titles" json:"mac_titles" form:"mac_titles"`
428
+}
429
+
430
+func (SgjPatientMacnavigation) TableName() string {
431
+
432
+	return "sgj_patient_macnavigation"
433
+}
434
+
435
+type SgjPatientHosaddress struct {
436
+	ID        int64  `gorm:"column:id" json:"id" form:"id"`
437
+	Title     string `gorm:"column:title" json:"title" form:"title"`
438
+	Sort      int64  `gorm:"column:sort" json:"sort" form:"sort"`
439
+	Address   string `gorm:"column:address" json:"address" form:"address"`
440
+	UserOrgId int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
441
+	Status    int64  `gorm:"column:status" json:"status" form:"status"`
442
+	Ctime     int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
443
+	Mtime     int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
444
+	Modeid    int64  `gorm:"column:modeid" json:"modeid" form:"modeid"`
445
+}
446
+
447
+func (SgjPatientHosaddress) TableName() string {
448
+
449
+	return "sgj_patient_hosaddress"
450
+}
451
+
452
+type SgjPatientAddactivity struct {
453
+	ID        int64  `gorm:"column:id" json:"id" form:"id"`
454
+	Title     string `gorm:"column:title" json:"title" form:"title"`
455
+	Sort      int64  `gorm:"column:sort" json:"sort" form:"sort"`
456
+	Number    int64  `gorm:"column:number" json:"number" form:"number"`
457
+	UserOrgId int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
458
+	Status    int64  `gorm:"column:status" json:"status" form:"status"`
459
+	Ctime     int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
460
+	Mtime     int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
461
+	Modeid    int64  `gorm:"column:modeid" json:"modeid" form:"modeid"`
462
+}
463
+
464
+func (SgjPatientAddactivity) TableName() string {
465
+
466
+	return "sgj_patient_addactivity"
467
+}
468
+
469
+type SgjPatientArticlelist struct {
470
+	ID          int64  `gorm:"column:id" json:"id" form:"id"`
471
+	Title       string `gorm:"column:title" json:"title" form:"title"`
472
+	Sort        int64  `gorm:"column:sort" json:"sort" form:"sort"`
473
+	Category    int64  `gorm:"column:category" json:"category" form:"category"`
474
+	Categoryone int64  `gorm:"column:categoryone" json:"categoryone" form:"categoryone"`
475
+	Number      int64  `gorm:"column:number" json:"number" form:"number"`
476
+	Status      int64  `gorm:"column:status" json:"status" form:"status"`
477
+	UserOrgId   int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
478
+	Ctime       int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
479
+	Mtime       int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
480
+	Modeid      int64  `gorm:"column:modeid" json:"modeid" form:"modeid"`
481
+}
482
+
483
+func (SgjPatientArticlelist) TableName() string {
484
+
485
+	return "sgj_patient_articlelist"
486
+}
487
+
488
+type SgjPatientLinkaddress struct {
489
+	ID            int64  `gorm:"column:id" json:"id" form:"id"`
490
+	Defineaddress string `gorm:"column:defineaddress" json:"defineaddress" form:"defineaddress"`
491
+	UserOrgId     int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
492
+	Status        int64  `gorm:"column:status" json:"status" form:"status"`
493
+	Ctime         int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
494
+	Mtime         int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
495
+}
496
+
497
+func (SgjPatientLinkaddress) TableName() string {
498
+
499
+	return "sgj_patient_linkaddress"
500
+}
501
+
502
+type SgjPatientConlinkaddress struct {
503
+	ID            int64  `gorm:"column:id" json:"id" form:"id"`
504
+	UserOrgId     int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
505
+	Defineaddress string `gorm:"column:defineaddress" json:"defineaddress" form:"defineaddress"`
506
+	Ctime         int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
507
+	Mtime         int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
508
+	Status        int64  `gorm:"column:status" json:"status" form:"status"`
509
+}
510
+
511
+func (SgjPatientConlinkaddress) TableName() string {
512
+
513
+	return "sgj_patient_conlinkaddress"
514
+}
515
+
516
+type SgjPatientMagiclink struct {
517
+	ID             int64  `gorm:"column:id" json:"id" form:"id"`
518
+	UserOrgId      int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
519
+	Linktype       int64  `gorm:"column:linktype" json:"linktype" form:"linktype"`
520
+	Instationlink  int64  `gorm:"column:instationlink" json:"instationlink" form:"instationlink"`
521
+	Phone          string `gorm:"column:phone" json:"phone" form:"phone"`
522
+	Outstationlink string `gorm:"column:outstationlink" json:"outstationlink" form:"outstationlink"`
523
+	Ctime          int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
524
+	Mtime          int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
525
+	Status         int64  `gorm:"column:status" json:"status" form:"status"`
526
+	Linkaddress    string `gorm:"column:linkaddress" json:"linkaddress" form:"linkaddress"`
527
+}
528
+
529
+func (SgjPatientMagiclink) TableName() string {
530
+
531
+	return "sgj_patient_magiclink"
532
+}
533
+
534
+type PatientNavgationlink struct {
535
+	ID               int64  `gorm:"column:id" json:"id" form:"id"`
536
+	Phone            string `gorm:"column:phone" json:"phone" form:"phone"`
537
+	Outstationlink   string `gorm:"column:outstationlink" json:"outstationlink" form:"outstationlink"`
538
+	UserOrgId        int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
539
+	Status           int64  `gorm:"column:status" json:"status" form:"status"`
540
+	Ctime            int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
541
+	Mtime            int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
542
+	Linkaddress      string `gorm:"column:linkaddress" json:"linkaddress" form:"linkaddress"`
543
+	Instationlink    int64  `gorm:"column:instationlink" json:"instationlink" form:"instationlink"`
544
+	Linktype         int64  `gorm:"column:linktype" json:"linktype" form:"linktype"`
545
+	Navitionlinktype int64  `gorm:"column:navitionlinktype" json:"navitionlinktype" form:"navitionlinktype"`
546
+}
547
+
548
+func (PatientNavgationlink) TableName() string {
549
+	return "sgj_patient_navgationlink"
550
+}
551
+
552
+type OrgInfo struct {
553
+	ID              int64
554
+	OrgIntroduction string
555
+	Telephone       string
556
+	Address         string
557
+}

+ 77 - 0
models/sms_models.go View File

@@ -0,0 +1,77 @@
1
+package models
2
+
3
+type SMSTemplate struct {
4
+	ID           int64  `gorm:"column:id"`
5
+	TemplateType int8   `gorm:"column:template_type"` // 模板类型 1.默认模板 2.自定义模板
6
+	TemplateID   int64  `gorm:"column:template_id"`   // 短信平台上的模板 id
7
+	MessageType  int8   `gorm:"column:message_type"`  // 短信类型 1.通知短信 2.服务短信
8
+	Content      string // 模板内容
9
+	// ParamTypes   string `gorm:"column:param_types"` // 字段因业务没有采用默认模板的方式而弃用了!!!! 模板内容里的参数类型:1,2,3 。参数类型以逗号隔开,位置代表了参数‘{n+1}’,类型暂时有:1.用户名 2.商家简称 3.链接 4.商品名称 5.活动名称 6.验证码。(自定义模板是没有值的,因为它没有参数)
10
+	Autograph  string // 短信签名
11
+	OrgID      int64  `gorm:"column:org_id"` // 模板所属机构(自定义模板才有值)
12
+	Status     int8   // 模板状态 0.无效 1.有效 2.审核中
13
+	CreateTime int64  `gorm:"column:ctime"` // 创建时间
14
+	ModifyTime int64  `gorm:"column:mtime"` // 修改时间
15
+}
16
+
17
+func (SMSTemplate) TableName() string {
18
+	return "sgj_patient_sms_template"
19
+}
20
+
21
+type UserSMSFreeLimit struct {
22
+	ID         int64  `gorm:"column:id"`
23
+	OrgID      int64  `gorm:"column:org_id"`      // 机构 ID
24
+	TotalCount int    `gorm:"column:total_count"` // 免费额度,单位:条,下同
25
+	UsedCount  int    `gorm:"column:used_count"`  // 已用额度
26
+	ValidMonth string `gorm:"column:valid_month"` // 生效月份,格式:201804
27
+	Status     int8   // 状态 0.无效 1.有效
28
+	CreateTime int64  `gorm:"column:ctime"` // 创建时间
29
+	ModifyTime int64  `gorm:"column:mtime"` // 修改时间
30
+}
31
+
32
+func (UserSMSFreeLimit) TableName() string {
33
+	return "sgj_patient_user_sms_free_limit"
34
+}
35
+
36
+type SMSBatch struct {
37
+	ID          int64  `gorm:"column:id"`
38
+	OrgID       int64  `gorm:"column:org_id"`          // 机构 ID
39
+	TemplateID  int64  `gorm:"column:sms_template_id"` // 对应短信平台上的模板 ID
40
+	Autograph   string // 短信签名
41
+	Params      string // 模板参数,以“,”隔开
42
+	FullContent string `gorm:"column:full_content"` // 完整短信内容
43
+	Mobiles     string // 接收手机号,以“,”隔开
44
+	SendTime    int64  `gorm:"column:send_time"` // 发送时间
45
+	Status      int8   // 状态: 1.待审核 2.审核未通过 3.未发送 4.已发送 5.发送失败
46
+	CreateTime  int64  `gorm:"column:ctime"` // 创建时间
47
+	ModifyTime  int64  `gorm:"column:mtime"` // 修改时间
48
+}
49
+
50
+func (SMSBatch) TableName() string {
51
+	return "sgj_patient_sms_batch"
52
+}
53
+
54
+type SMSSendStatus struct {
55
+	ID         int64  `gorm:"column:id"`
56
+	BatchID    int64  `gorm:"batch_id"` // 批次 ID,对应 SMSBatch.ID
57
+	Mobile     string // 接收手机号
58
+	Status     int8   // 发送结果状态: 0.失败 1.成功
59
+	Code       string // 短信平台返回的错误码
60
+	Msg        string // 短信平台返回的错误信息
61
+	CreateTime int64  `gorm:"column:ctime"` // 创建时间
62
+	ModifyTime int64  `gorm:"column:mtime"` // 修改时间
63
+}
64
+
65
+func (SMSSendStatus) TableName() string {
66
+	return "sgj_patient_sms_send_status"
67
+}
68
+
69
+// 1.待审核 2.审核未通过 3.未发送 4.已发送 5.发送失败
70
+const (
71
+	SMSBatchStatusInReview   = int8(1)
72
+	SMSBatchStatusUnapproved = int8(2)
73
+	SMSBatchStatusUnsend     = int8(3)
74
+	SMSBatchStatusDidSend    = int8(4)
75
+	SMSBatchStatusSendFailed = int8(5)
76
+	SMSBatchStatusSending    = int8(6)
77
+)

+ 11 - 0
models/subscibe_state_models.go View File

@@ -0,0 +1,11 @@
1
+package models
2
+
3
+type ServeSubscibeState struct {
4
+	ServeSubscibe
5
+
6
+	State int64 `gorm:"-" json:"state"`
7
+}
8
+
9
+func (ServeSubscibeState) TableName() string {
10
+	return "sgj_serve_subscibe"
11
+}

+ 35 - 0
models/user_customer_models.go View File

@@ -0,0 +1,35 @@
1
+package models
2
+
3
+type UserCustomer struct {
4
+	ID              int64  `gorm:"column:id" json:"id" form:"id"`
5
+	UserOrgId       int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
6
+	UserId          int64  `gorm:"column:user_id" json:"user_id" form:"user_id"`
7
+	Mobile          string `gorm:"column:mobile" json:"mobile" form:"mobile"`
8
+	Name            string `gorm:"column:name" json:"name" form:"name"`
9
+	Gender          int64  `gorm:"column:gender" json:"gender" form:"gender"`
10
+	ProvinceId      int64  `gorm:"column:province_id" json:"province_id" form:"province_id"`
11
+	CityId          int64  `gorm:"column:city_id" json:"city_id" form:"city_id"`
12
+	Address         string `gorm:"column:address" json:"address" form:"address"`
13
+	Birthday        int64  `gorm:"column:birthday" json:"birthday" form:"birthday"`
14
+	TreatType       int64  `gorm:"column:treat_type" json:"treat_type" form:"treat_type"`
15
+	Relationship    int64  `gorm:"column:relationship" json:"relationship" form:"relationship"`
16
+	IllnessId       int64  `gorm:"column:illness_id" json:"illness_id" form:"illness_id"`
17
+	WechatOpenid    string `gorm:"column:wechat_openid" json:"wechat_openid" form:"wechat_openid"`
18
+	Membership      int64  `gorm:"column:membership" json:"membership" form:"membership"`
19
+	Sources         int64  `gorm:"column:sources" json:"sources" form:"sources"`
20
+	Status          int64  `gorm:"column:status" json:"status" form:"status"`
21
+	CreatedTime     int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
22
+	UpdatedTime     int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
23
+	Avatar          string `gorm:"column:avatar" json:"avatar" form:"avatar"`
24
+	WechatUnionid   string `gorm:"column:wechat_unionid" json:"wechat_unionid" form:"wechat_unionid"`
25
+	Remark          string `gorm:"column:remark" json:"remark" form:"remark"`
26
+	MedicalDiagnose string `gorm:"column:medical_diagnose" json:"medical_diagnose" form:"medical_diagnose"`
27
+	YzUid           int64  `gorm:"column:yz_uid" json:"yz_uid" form:"yz_uid"`
28
+	Tttime          int64  `gorm:"column:tttime" json:"tttime" form:"tttime"`
29
+	IllDate         int64  `gorm:"column:ill_date" json:"ill_date" form:"ill_date"`
30
+	DistrictId      int64  `gorm:"column:district_id" json:"district_id" form:"district_id"`
31
+}
32
+
33
+func (UserCustomer) TableName() string {
34
+	return "sgj_user_customer"
35
+}

+ 51 - 0
models/user_membership_card_models.go View File

@@ -0,0 +1,51 @@
1
+package models
2
+
3
+type UserMembershipCard struct {
4
+	ID              int64  `gorm:"column:id" json:"id" form:"id"`
5
+	UserOrgId       int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
6
+	CardName        string `gorm:"column:card_name" json:"card_name" form:"card_name"`
7
+	CardLevel       int64  `gorm:"column:card_level" json:"card_level" form:"card_level"`
8
+	UpgradeIntegral int64  `gorm:"column:upgrade_integral" json:"upgrade_integral" form:"upgrade_integral"`
9
+	CardRight       string `gorm:"column:card_right" json:"card_right" form:"card_right"`
10
+	UseNotice       string `gorm:"column:use_notice" json:"use_notice" form:"use_notice"`
11
+	BackgroundType  int64  `gorm:"column:background_type" json:"background_type" form:"background_type"`
12
+	Background      string `gorm:"column:background" json:"background" form:"background"`
13
+	ServicePhone    string `gorm:"column:service_phone" json:"service_phone" form:"service_phone"`
14
+	Status          int64  `gorm:"column:status" json:"status" form:"status"`
15
+	CreatedTime     int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
16
+	UpdatedTime     int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
17
+}
18
+
19
+func (UserMembershipCard) TableName() string {
20
+	return "sgj_user_membership_card"
21
+}
22
+
23
+type UserCard struct {
24
+	ID           int64  `gorm:"column:id" json:"id" form:"id"`
25
+	UserOrgId    int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
26
+	CustomerId   int64  `gorm:"column:customer_id" json:"customer_id" form:"customer_id"`
27
+	CardId       int64  `gorm:"column:card_id" json:"card_id" form:"card_id"`
28
+	CardNo       string `gorm:"column:card_no" json:"card_no" form:"card_no"`
29
+	CardName     string `gorm:"column:card_name" json:"card_name" form:"card_name"`
30
+	CardIntegral int64  `gorm:"column:card_integral" json:"card_integral" form:"card_integral"`
31
+	Status       int64  `gorm:"column:status" json:"status" form:"status"`
32
+	CreatedTime  int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
33
+	UpdatedTime  int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
34
+}
35
+
36
+func (UserCard) TableName() string {
37
+	return "sgj_user_user_card"
38
+}
39
+
40
+type MembershipRights struct {
41
+	ID          int64  `gorm:"column:id" json:"id" form:"id"`
42
+	UserOrgId   int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
43
+	Rights      string `gorm:"column:rights" json:"rights" form:"rights"`
44
+	Status      int64  `gorm:"column:status" json:"status" form:"status"`
45
+	CreatedTime int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
46
+	UpdatedTime int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
47
+}
48
+
49
+func (MembershipRights) TableName() string {
50
+	return "sgj_user_membership_rights"
51
+}

+ 57 - 0
models/user_models.go View File

@@ -0,0 +1,57 @@
1
+package models
2
+
3
+type User struct {
4
+	ID              int64  `gorm:"column:id" json:"id" form:"id"`
5
+	Password        string `gorm:"column:password" json:"password" form:"password"`
6
+	Mobile          string `gorm:"column:mobile" json:"mobile" form:"mobile"`
7
+	Username        string `gorm:"column:username" json:"username" form:"username"`
8
+	Remarkname      string `gorm:"column:remarkname" json:"remarkname" form:"remarkname"`
9
+	Realname        string `gorm:"column:realname" json:"realname" form:"realname"`
10
+	Introduce       string `gorm:"column:introduce" json:"introduce" form:"introduce"`
11
+	Avatar          string `gorm:"column:avatar" json:"avatar" form:"avatar"`
12
+	AvatarThumb     string `gorm:"column:avatar_thumb" json:"avatar_thumb" form:"avatar_thumb"`
13
+	Gender          int64  `gorm:"column:gender" json:"gender" form:"gender"`
14
+	ReceivingPhone  string `gorm:"column:receiving_phone" json:"receiving_phone" form:"receiving_phone"`
15
+	ProvinceId      int64  `gorm:"column:province_id" json:"province_id" form:"province_id"`
16
+	CityId          int64  `gorm:"column:city_id" json:"city_id" form:"city_id"`
17
+	DistrictId      int64  `gorm:"column:district_id" json:"district_id" form:"district_id"`
18
+	Birthday        int64  `gorm:"column:birthday" json:"birthday" form:"birthday"`
19
+	Address         string `gorm:"column:address" json:"address" form:"address"`
20
+	Recipient       string `gorm:"column:recipient" json:"recipient" form:"recipient"`
21
+	TreatType       int64  `gorm:"column:treat_type" json:"treat_type" form:"treat_type"`
22
+	Token           string `gorm:"column:token" json:"token" form:"token"`
23
+	Imei            string `gorm:"column:imei" json:"imei" form:"imei"`
24
+	Relationship    int64  `gorm:"column:relationship" json:"relationship" form:"relationship"`
25
+	Platform        string `gorm:"column:platform" json:"platform" form:"platform"`
26
+	IllnessId       int64  `gorm:"column:illness_id" json:"illness_id" form:"illness_id"`
27
+	Sources         int64  `gorm:"column:sources" json:"sources" form:"sources"`
28
+	Status          int64  `gorm:"column:status" json:"status" form:"status"`
29
+	CreatedTime     int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
30
+	UpdatedTime     int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
31
+	WechatOpenid    string `gorm:"column:wechat_openid" json:"wechat_openid" form:"wechat_openid"`
32
+	MedicalDiagnose string `gorm:"column:medical_diagnose" json:"medical_diagnose" form:"medical_diagnose"`
33
+}
34
+
35
+func (User) TableName() string {
36
+	return "sgj_user_user"
37
+}
38
+
39
+type SgjUserStaffInfo struct {
40
+	ID        int64  `gorm:"column:id" json:"id" form:"id"`
41
+	Name      string `gorm:"column:name" json:"name" form:"name"`
42
+	Phone     string `gorm:"column:phone" json:"phone" form:"phone"`
43
+	Birthday  int64  `gorm:"column:birthday" json:"birthday" form:"birthday"`
44
+	Gender    int64  `gorm:"column:gender" json:"gender" form:"gender"`
45
+	UserType  int64  `gorm:"column:user_type" json:"user_type" form:"user_type"`
46
+	UserTitle int64  `gorm:"column:user_title" json:"user_title" form:"user_title"`
47
+	Dochead   string `gorm:"column:dochead" json:"dochead" form:"dochead"`
48
+	Content   string `gorm:"column:content" json:"content" form:"content"`
49
+	Ctime     int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
50
+	Mtime     int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
51
+	Status    int64  `gorm:"column:status" json:"status" form:"status"`
52
+	UserOrgId int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
53
+}
54
+
55
+func (SgjUserStaffInfo) TableName() string {
56
+	return "sgj_user_staff_info"
57
+}

+ 28 - 0
models/user_tag_models.go View File

@@ -0,0 +1,28 @@
1
+package models
2
+
3
+type UserTags struct {
4
+	ID          int64  `gorm:"column:id" json:"id" form:"id"`
5
+	TagName     string `gorm:"column:tag_name" json:"tag_name" form:"tag_name"`
6
+	UserOrgId   int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
7
+	Status      int64  `gorm:"column:status" json:"status" form:"status"`
8
+	CreatedTime int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
9
+	UpdatedTime int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
10
+}
11
+
12
+func (UserTags) TableName() string {
13
+	return "sgj_user_tags"
14
+}
15
+
16
+type UserTagLinks struct {
17
+	ID          int64 `gorm:"column:id" json:"id" form:"id"`
18
+	TagId       int64 `gorm:"column:tag_id" json:"tag_id" form:"tag_id"`
19
+	UserLinkId  int64 `gorm:"column:user_link_id" json:"user_link_id" form:"user_link_id"`
20
+	Status      int64 `gorm:"column:status" json:"status" form:"status"`
21
+	CreatedTime int64 `gorm:"column:created_time" json:"created_time" form:"created_time"`
22
+	UpdatedTime int64 `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
23
+	UserOrgId   int64 `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
24
+}
25
+
26
+func (UserTagLinks) TableName() string {
27
+	return "sgj_user_tag_links"
28
+}

+ 104 - 0
models/wechat_models.go View File

@@ -0,0 +1,104 @@
1
+package models
2
+
3
+type WechatComponents struct {
4
+	ID                    int64  `gorm:"column:id" json:"id" form:"id"`
5
+	ComponentAppid        string `gorm:"column:component_appid" json:"component_appid" form:"component_appid"`
6
+	ComponentAppsecret    string `gorm:"column:component_appsecret" json:"component_appsecret" form:"component_appsecret"`
7
+	ComponentVerifyTicket string `gorm:"column:component_verify_ticket" json:"component_verify_ticket" form:"component_verify_ticket"`
8
+	ComponentAccessToken  string `gorm:"column:component_access_token" json:"component_access_token" form:"component_access_token"`
9
+	PreAuthCode           string `gorm:"column:pre_auth_code" json:"pre_auth_code" form:"pre_auth_code"`
10
+	CreatedTime           int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
11
+	UpdatedTime           int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
12
+	ComponentStatus       int64  `gorm:"column:component_status" json:"component_status" form:"component_status"`
13
+}
14
+
15
+func (WechatComponents) TableName() string {
16
+	return "sgj_patient_wechat_components"
17
+}
18
+
19
+type PatientAuthorizations struct {
20
+	ID                          int64  `gorm:"column:id" json:"id" form:"id"`
21
+	UserOrgId                   int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
22
+	AuthorizerAppid             string `gorm:"column:authorizer_appid" json:"authorizer_appid" form:"authorizer_appid"`
23
+	AuthorizerAccessToken       string `gorm:"column:authorizer_access_token" json:"authorizer_access_token" form:"authorizer_access_token"`
24
+	AuthorizerRefreshToken      string `gorm:"column:authorizer_refresh_token" json:"authorizer_refresh_token" form:"authorizer_refresh_token"`
25
+	AuthorizerJsapiTicket       string `gorm:"column:authorizer_jsapi_ticket" json:"authorizer_jsapi_ticket" form:"authorizer_jsapi_ticket"`
26
+	AuthorizerFuncscopeCategory string `gorm:"column:authorizer_funcscope_category" json:"authorizer_funcscope_category" form:"authorizer_funcscope_category"`
27
+	AuthorizerNickName          string `gorm:"column:authorizer_nick_name" json:"authorizer_nick_name" form:"authorizer_nick_name"`
28
+	AuthorizerHeadImg           string `gorm:"column:authorizer_head_img" json:"authorizer_head_img" form:"authorizer_head_img"`
29
+	AuthorizerServiceTypeInfo   int64  `gorm:"column:authorizer_service_type_info" json:"authorizer_service_type_info" form:"authorizer_service_type_info"`
30
+	AuthorizerVerifyTypeInfo    int64  `gorm:"column:authorizer_verify_type_info" json:"authorizer_verify_type_info" form:"authorizer_verify_type_info"`
31
+	AuthorizerUserName          string `gorm:"column:authorizer_user_name" json:"authorizer_user_name" form:"authorizer_user_name"`
32
+	AuthorizerPrincipalName     string `gorm:"column:authorizer_principal_name" json:"authorizer_principal_name" form:"authorizer_principal_name"`
33
+	AuthorizerBusinessInfo      string `gorm:"column:authorizer_business_info" json:"authorizer_business_info" form:"authorizer_business_info"`
34
+	AuthorizerQrcodeUrl         string `gorm:"column:authorizer_qrcode_url" json:"authorizer_qrcode_url" form:"authorizer_qrcode_url"`
35
+	CreatedTime                 int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
36
+	UpdatedTime                 int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
37
+	AuthorizerStatus            int64  `gorm:"column:authorizer_status" json:"authorizer_status" form:"authorizer_status"`
38
+}
39
+
40
+func (PatientAuthorizations) TableName() string {
41
+	return "sgj_patient_authorizations"
42
+}
43
+
44
+//type AuthorizationMessageManagements struct {
45
+//	ID                 int64  `gorm:"column:id" json:"id" form:"id"`
46
+//	UserOrgId          int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
47
+//	MessageMsgEvent    string `gorm:"column:message_msg_event" json:"message_msg_event" form:"message_msg_event"`
48
+//	MessageMsgType     string `gorm:"column:message_msg_type" json:"message_msg_type" form:"message_msg_type"`
49
+//	MessageKeyType     int64  `gorm:"column:message_key_type" json:"message_key_type" form:"message_key_type"`
50
+//	MessageRegularName string `gorm:"column:message_regular_name" json:"message_regular_name" form:"message_regular_name"`
51
+//	MessageKeyName     string `gorm:"column:message_key_name" json:"message_key_name" form:"message_key_name"`
52
+//	MessageContent     string `gorm:"column:message_content" json:"message_content" form:"message_content"`
53
+//	CreatedTime        int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
54
+//	UpdatedTime        int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
55
+//	MessageStatus      int64  `gorm:"column:message_status" json:"message_status" form:"message_status"`
56
+//}
57
+type AuthorizationMessageManagements struct {
58
+	ID                 int64  `gorm:"column:id" json:"id" form:"id"`
59
+	UserOrgId          int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
60
+	MessageMsgEvent    string `gorm:"column:message_msg_event" json:"message_msg_event" form:"message_msg_event"`
61
+	MessageMsgType     string `gorm:"column:message_msg_type" json:"message_msg_type" form:"message_msg_type"`
62
+	MessageKeyType     int64  `gorm:"column:message_key_type" json:"message_key_type" form:"message_key_type"`
63
+	MessageRegularName string `gorm:"column:message_regular_name" json:"message_regular_name" form:"message_regular_name"`
64
+	MessageKeyName     string `gorm:"column:message_key_name" json:"message_key_name" form:"message_key_name"`
65
+	MessageContent     string `gorm:"column:message_content" json:"message_content" form:"message_content"`
66
+	CreatedTime        int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
67
+	UpdatedTime        int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
68
+	MessageStatus      int64  `gorm:"column:message_status" json:"message_status" form:"message_status"`
69
+}
70
+
71
+func (AuthorizationMessageManagements) TableName() string {
72
+	return "sgj_patient_authorization_message_managements"
73
+}
74
+
75
+type AuthorizationButtons struct {
76
+	ID           int64  `gorm:"column:id" json:"id"`
77
+	UserOrgID    int64  `gorm:"column:user_org_id" json:"user_org_id"`
78
+	ButtonFileds string `gorm:"column:button_fileds" json:"button_fileds"`
79
+	CreatedTime  int64  `gorm:"column:created_time" json:"created_time"`
80
+	UpdatedTime  int64  `gorm:"column:updated_time" json:"updated_time"`
81
+	ButtonStatus int64  `gorm:"column:button_status" json:"button_status"`
82
+	SendStatus   int64  `gorm:"column:send_status" json:"send_status"`
83
+}
84
+
85
+func (AuthorizationButtons) TableName() string {
86
+	return "sgj_patient_authorization_buttons"
87
+}
88
+
89
+type WechatMedias struct {
90
+	ID               int64  `gorm:"column:id" json:"id" form:"id"`
91
+	UserOrgId        int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
92
+	Msgtype          string `gorm:"column:msgtype" json:"msgtype" form:"msgtype"`
93
+	MediaId          string `gorm:"column:media_id" json:"media_id" form:"media_id"`
94
+	MediaTitle       string `gorm:"column:media_title" json:"media_title" form:"media_title"`
95
+	MediaDescription string `gorm:"column:media_description" json:"media_description" form:"media_description"`
96
+	MediaUrl         string `gorm:"column:media_url" json:"media_url" form:"media_url"`
97
+	UpdatedTime      int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
98
+	MediaStatus      int64  `gorm:"column:media_status" json:"media_status" form:"media_status"`
99
+	CreatedTime      int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
100
+}
101
+
102
+func (WechatMedias) TableName() string {
103
+	return "sgj_patient_wechat_medias"
104
+}

+ 49 - 0
routers/router.go View File

@@ -0,0 +1,49 @@
1
+package routers
2
+
3
+import (
4
+	"SCRM/controllers/admin_user"
5
+	"SCRM/controllers/article"
6
+	"SCRM/controllers/global"
7
+	"SCRM/controllers/kefu"
8
+	"SCRM/controllers/login"
9
+	"SCRM/controllers/marketing_tool"
10
+	"SCRM/controllers/members"
11
+	"SCRM/controllers/mpwechat"
12
+	"SCRM/controllers/role"
13
+	"SCRM/controllers/sms"
14
+	"SCRM/controllers/staff"
15
+
16
+	"SCRM/controllers/micro"
17
+	"SCRM/controllers/register"
18
+	"SCRM/controllers/site"
19
+	"github.com/astaxie/beego"
20
+	"github.com/astaxie/beego/context"
21
+	"github.com/astaxie/beego/plugins/cors"
22
+)
23
+
24
+func init() {
25
+	beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
26
+		AllowOrigins:     []string{"http://jk.kuyicloud.com", "http://localhost:8090", "http://localhost:8091", "http://test1.sgjyun.com", "https://www.ucpaas.com", "http://microweb.kuyicloud.com", "http://jk.test.sgjyun.com"},
27
+		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
28
+		AllowHeaders:     []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
29
+		ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
30
+		AllowCredentials: true,
31
+	}))
32
+	beego.Get("/MP_verify_JiWyx0d2U4nzjGX5.txt", func(ctx *context.Context) {
33
+		ctx.Output.Body([]byte("JiWyx0d2U4nzjGX5"))
34
+	})
35
+	global.RegisterRouters()
36
+	admin_user.RegisterRouters()
37
+	login.RegisterRouters()
38
+	role.RegisterRouters()
39
+	members.RegisterRouters()
40
+	marketing_tool.RegisterRouters()
41
+	article.RegisterRouters()
42
+	mpwechat.RegisterRouters()
43
+	sms.RegisterRouters()
44
+	staff.RegisterRouters()
45
+	kefu.RegisterRouters()
46
+	site.RegisterRouters()
47
+	micro.RegisterRouters()
48
+	register.RegisterRouter()
49
+}

+ 5 - 0
service/Readme.md View File

@@ -0,0 +1,5 @@
1
+将 service 模块化;  
2
+通用的 redis 和 db 配置处在最外层;  
3
+具体的业务 service 按业务分模块(包);  
4
+在具体的模块包里定义 service 方法和 view model;  
5
+如果某个模块比较复杂,service 代码很多,则再将其业务细分,拆分为多个文件;  

+ 383 - 0
service/admin_service/verify_login_token_service.go View File

@@ -0,0 +1,383 @@
1
+package admin_service
2
+
3
+import (
4
+	"encoding/json"
5
+	"io/ioutil"
6
+	"net/http"
7
+	"net/url"
8
+	"strconv"
9
+	"time"
10
+
11
+	"SCRM/models"
12
+	"SCRM/service"
13
+	"SCRM/service/org_service"
14
+	"SCRM/utils"
15
+
16
+	"github.com/astaxie/beego"
17
+)
18
+
19
+type AdminUserInfo struct {
20
+	AdminUser    *models.AdminUser                    `json:"user"`
21
+	CurrentOrgId int64                                `json:"current_org_id"`
22
+	CurrentAppId int64                                `json:"current_app_id"`
23
+	OrgIds       []int64                              `json:"org_ids"`
24
+	Orgs         map[int64]*org_service.Org           `json:"orgs"`
25
+	OrgAppIds    map[int64][]int64                    `json:"org_app_ids"`
26
+	OrgApps      map[int64](map[int64]*models.OrgApp) `json:"org_apps"`
27
+	App2OrgIds   map[int64]int64                      `json:"app_to_org_ids"`
28
+	AppRoles     map[int64]*models.App_Role           `json:"app_roles"`
29
+	AppPurviews  map[int64][]*models.Purview          `json:"app_purviews"`
30
+	AppUrlfors   map[int64][]string                   `json:"app_urlfors"`
31
+	Subscibes    map[int64]*models.ServeSubscibe      `json:"org_subscibes"`
32
+}
33
+
34
+type verifyTokenError struct {
35
+	Msg string
36
+}
37
+
38
+func (e *verifyTokenError) Error() string {
39
+	return e.Msg
40
+}
41
+
42
+// 验证 token 成功后返回的管理员用户的所有信息,包括:基本用户信息,所属的所有机构,机构下的所有应用,应用的用户权限
43
+// map 的数据格式为
44
+/*
45
+"admin_user": { AdminUser's json },
46
+current_org_id: 1,
47
+current_app_id: 11,
48
+"org_ids": [1, 2, 3],
49
+"orgs": { (org_id: Org_Obj)
50
+	1: { Org's json },
51
+	2: { Org's json },
52
+},
53
+"org_app_ids": { (org_id: org_app_ids)
54
+	1: [11, 12, 13],
55
+	2: [21, 22, 23],
56
+},
57
+"org_apps": { (org_id: {app_id: OrgApp_Obj})
58
+	1: {
59
+		11: { OrgApp's json },
60
+		12: { OrgApp's json },
61
+	},
62
+	2: {
63
+		21: { OrgApp's json },
64
+		22: { OrgApp's json },
65
+	},
66
+},
67
+"app_to_org_ids": { (app_id: org_id)
68
+	11: 1,
69
+	12: 1,
70
+	21: 2,
71
+	22: 2,
72
+},
73
+"app_roles": { (app_id: App_Role Obj)
74
+	11: {App_Role's json},
75
+	12: {App_Role's json},
76
+	21: {App_Role's json},
77
+},
78
+"purviews": { (app_id: [processed Purviews' json])
79
+	11: [
80
+		{Purview's json .childs[
81
+			{Purview's json},
82
+			{Purview's json},
83
+		]},
84
+		{Purview's json},
85
+	],
86
+	12: [
87
+		{Purview's json},
88
+		{Purview's json},
89
+	],
90
+},
91
+"purview_urlfors": { (app_id: [url_for])
92
+	11: [
93
+		"Controller1.Action1",
94
+		"Controller1.Action2",
95
+		"Controller2.Action1",
96
+		"Controller2.Action2",
97
+	],
98
+}
99
+应当注意的是,屈服于 Golang 令人恶心的类型机制,这里将所有数值型的 key 或 value 全部转成了 string
100
+*/
101
+// 解析用户信息,并返回
102
+func VerifyToken(token string, ip string, sessionID string) (*AdminUserInfo, error, int) {
103
+	// if len(sessionID) == 0 {
104
+	// 	return nil, &verifyTokenError{"sessionID 为空"}
105
+	// }
106
+	ssoDomain := beego.AppConfig.String("sso_domain")
107
+	api := ssoDomain + "/verifytoken"
108
+	values := make(url.Values)
109
+	values.Set("token", token)
110
+	values.Set("app_type", "1")
111
+	values.Set("ip", ip)
112
+	values.Set("session_id", sessionID)
113
+	resp, requestErr := http.PostForm(api, values)
114
+
115
+	if requestErr != nil {
116
+		utils.ErrorLog("请求验证 sso token 接口失败: %v", requestErr)
117
+		return nil, requestErr, 0
118
+	}
119
+	defer resp.Body.Close()
120
+	body, ioErr := ioutil.ReadAll(resp.Body)
121
+	if ioErr != nil {
122
+		utils.ErrorLog("验证 sso token 接口返回数据读取失败: %v", ioErr)
123
+		return nil, ioErr, 0
124
+	}
125
+	var respJSON map[string]interface{}
126
+	utils.InfoLog(string(body))
127
+	if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
128
+		utils.ErrorLog("验证 sso token 接口返回数据解析JSON失败: %v", err)
129
+		return nil, err, 0
130
+	}
131
+
132
+	if respJSON["state"].(float64) != 1 {
133
+		msg := respJSON["msg"].(string)
134
+		utils.ErrorLog("验证 sso token 接口请求失败: %v", msg)
135
+		return nil, &verifyTokenError{"验证 sso token 接口请求失败"}, int(respJSON["code"].(float64))
136
+	} else {
137
+		utils.SuccessLog("验证 sso token 成功")
138
+		return processAdminUserInfo(respJSON["data"].(map[string]interface{})), nil, 0
139
+	}
140
+}
141
+
142
+func processAdminUserInfo(data map[string]interface{}) *AdminUserInfo {
143
+	adminUser := processAdminUser(data)
144
+	currentOrgId, currentAppId := processCurrentOrgIDAndAppID(data)
145
+	orgIds := processOrgIds(data)
146
+	orgs := processOrgs(data)
147
+	orgAppIds := processOrgAppIds(data)
148
+	orgApps := processOrgApps(data)
149
+	app2OrgIds := processApp2OrgIds(data)
150
+	appRoles := processAppRoles(data)
151
+	appPurviews := processPurviews(data)
152
+	appUrlfors := processPurviewUrlfors(data)
153
+	orgSubscibes := processOrgSubscibes(data)
154
+	sessionAdminUserInfo := &AdminUserInfo{
155
+		AdminUser:    adminUser,
156
+		CurrentOrgId: currentOrgId,
157
+		CurrentAppId: currentAppId,
158
+		OrgIds:       orgIds,
159
+		Orgs:         orgs,
160
+		OrgAppIds:    orgAppIds,
161
+		OrgApps:      orgApps,
162
+		App2OrgIds:   app2OrgIds,
163
+		AppRoles:     appRoles,
164
+		AppPurviews:  appPurviews,
165
+		AppUrlfors:   appUrlfors,
166
+		Subscibes:    orgSubscibes,
167
+	}
168
+	return sessionAdminUserInfo
169
+}
170
+
171
+// "admin_user": { AdminUser's json },
172
+func processAdminUser(data map[string]interface{}) *models.AdminUser {
173
+	userJSONStr := data["admin_user"].(string)
174
+	var adminUser models.AdminUser
175
+	if err := json.Unmarshal([]byte(userJSONStr), &adminUser); err != nil {
176
+		utils.ErrorLog("解析用户信息失败:%v", err)
177
+		return nil
178
+	} else {
179
+		return &adminUser
180
+	}
181
+}
182
+
183
+// current_org_id: 1,
184
+// current_app_id: 11,
185
+func processCurrentOrgIDAndAppID(data map[string]interface{}) (int64, int64) {
186
+	orgIDStr := data["current_org_id"].(string)
187
+	appIDStr := data["current_app_id"].(string)
188
+	orgID, _ := strconv.Atoi(orgIDStr)
189
+	appID, _ := strconv.Atoi(appIDStr)
190
+	return int64(orgID), int64(appID)
191
+}
192
+
193
+// "org_ids": [1, 2, 3],
194
+func processOrgIds(data map[string]interface{}) []int64 {
195
+	orgIdStrs := data["org_ids"].([]interface{})
196
+	orgIds := make([]int64, 0, len(orgIdStrs))
197
+	for _, idstr := range orgIdStrs {
198
+		id, _ := strconv.Atoi(idstr.(string))
199
+		orgIds = append(orgIds, int64(id))
200
+	}
201
+	return orgIds
202
+}
203
+
204
+// "orgs": { (org_id: Org_Obj)
205
+// 	1: { Org's json },
206
+// 	2: { Org's json },
207
+// },
208
+func processOrgs(data map[string]interface{}) map[int64]*org_service.Org {
209
+	orgJSONs := data["orgs"].(map[string]interface{})
210
+	orgs := make(map[int64]*org_service.Org)
211
+	for orgIdStr, orgJSON := range orgJSONs {
212
+		orgId, _ := strconv.Atoi(orgIdStr)
213
+		var org org_service.Org
214
+		json.Unmarshal([]byte(orgJSON.(string)), &org)
215
+		orgs[int64(orgId)] = &org
216
+	}
217
+	return orgs
218
+}
219
+
220
+// "org_app_ids": { (org_id: org_app_ids)
221
+// 	1: [11, 12, 13],
222
+// 	2: [21, 22, 23],
223
+// },
224
+func processOrgAppIds(data map[string]interface{}) map[int64][]int64 {
225
+	orgAppIdStrs := data["org_app_ids"].(map[string]interface{})
226
+	orgAppIds := make(map[int64][]int64)
227
+	for orgIdStr, appIdStrs := range orgAppIdStrs {
228
+		orgId, _ := strconv.Atoi(orgIdStr)
229
+		appIds := make([]int64, 0, len(appIdStrs.([]interface{})))
230
+		for _, appIdStr := range appIdStrs.([]interface{}) {
231
+			appId, _ := strconv.Atoi(appIdStr.(string))
232
+			appIds = append(appIds, int64(appId))
233
+		}
234
+		orgAppIds[int64(orgId)] = appIds
235
+	}
236
+	return orgAppIds
237
+}
238
+
239
+// "org_apps": { (org_id: {app_id: OrgApp_Obj})
240
+// 	1: {
241
+// 		11: { OrgApp's json },
242
+// 		12: { OrgApp's json },
243
+// 	},
244
+// 	2: {
245
+// 		21: { OrgApp's json },
246
+// 		22: { OrgApp's json },
247
+// 	},
248
+// },
249
+func processOrgApps(data map[string]interface{}) map[int64]map[int64]*models.OrgApp {
250
+	orgAppJSONs := data["org_apps"].(map[string]interface{})
251
+	orgApps := make(map[int64]map[int64]*models.OrgApp)
252
+	for orgIdStr, appJSONStrMap := range orgAppJSONs {
253
+		orgId, _ := strconv.Atoi(orgIdStr)
254
+
255
+		apps := make(map[int64]*models.OrgApp)
256
+		for appIdStr, appJSONStr := range appJSONStrMap.(map[string]interface{}) {
257
+			appId, _ := strconv.Atoi(appIdStr)
258
+
259
+			var app models.OrgApp
260
+			json.Unmarshal([]byte(appJSONStr.(string)), &app)
261
+			apps[int64(appId)] = &app
262
+		}
263
+
264
+		orgApps[int64(orgId)] = apps
265
+	}
266
+	return orgApps
267
+}
268
+
269
+// "app_to_org_ids": { (app_id: org_id)
270
+// 	11: 1,
271
+// 	12: 1,
272
+// 	21: 2,
273
+// 	22: 2,
274
+// },
275
+func processApp2OrgIds(data map[string]interface{}) map[int64]int64 {
276
+	app2OrgIdStrs := data["app_to_org_ids"].(map[string]interface{})
277
+	app2OrgIds := make(map[int64]int64)
278
+	for appIdStr, orgIdStr := range app2OrgIdStrs {
279
+		orgId, _ := strconv.Atoi(orgIdStr.(string))
280
+		appId, _ := strconv.Atoi(appIdStr)
281
+		app2OrgIds[int64(appId)] = int64(orgId)
282
+	}
283
+	return app2OrgIds
284
+}
285
+
286
+// "app_roles": { (app_id: App_Role Obj)
287
+// 	11: {App_Role's json},
288
+// 	12: {App_Role's json},
289
+// 	21: {App_Role's json},
290
+// },
291
+func processAppRoles(data map[string]interface{}) map[int64]*models.App_Role {
292
+	appRoleJSONs := data["app_roles"].(map[string]interface{})
293
+	appRoles := make(map[int64]*models.App_Role)
294
+	for appIDStr, appRoleJSON := range appRoleJSONs {
295
+		appID, _ := strconv.Atoi(appIDStr)
296
+		var appRole models.App_Role
297
+		json.Unmarshal([]byte(appRoleJSON.(string)), &appRole)
298
+		appRoles[int64(appID)] = &appRole
299
+	}
300
+	return appRoles
301
+}
302
+
303
+// "purviews": { (app_id: [processed Purviews' json])
304
+// 	11: [
305
+// 		{Purview's json .childs[
306
+// 			{Purview's json},
307
+// 			{Purview's json},
308
+// 		]},
309
+// 		{Purview's json},
310
+// 	],
311
+// 	12: [
312
+// 		{Purview's json},
313
+// 		{Purview's json},
314
+// 	],
315
+// },
316
+func processPurviews(data map[string]interface{}) map[int64][]*models.Purview {
317
+	appPurviewJSONsStrs := data["purviews"].(map[string]interface{})
318
+	appPurviews := make(map[int64][]*models.Purview)
319
+	for appIdStr, purviewJSONsStr := range appPurviewJSONsStrs {
320
+		appId, _ := strconv.Atoi(appIdStr)
321
+		var purviews []*models.Purview
322
+		json.Unmarshal([]byte(purviewJSONsStr.(string)), &purviews)
323
+		// setLinkForPurviews(purviews)
324
+		appPurviews[int64(appId)] = purviews
325
+	}
326
+	return appPurviews
327
+}
328
+
329
+// func setLinkForPurviews(purviews []*models.Purview) {
330
+// 	for _, purview := range purviews {
331
+// 		if len(purview.Urlfor) == 0 {
332
+// 			purview.Link = ""
333
+// 		} else {
334
+// 			purview.Link = beego.URLFor(purview.Urlfor)
335
+// 		}
336
+// 		if purview.Childs == nil {
337
+// 			purview.Childs = make([]*models.Purview, 0)
338
+// 		} else {
339
+// 			setLinkForPurviews(purview.Childs)
340
+// 		}
341
+// 		// utils.TraceLog("%+v", purview)
342
+// 	}
343
+// }
344
+
345
+// "purview_urlfors": { (app_id: [url_for])
346
+// 	11: [
347
+// 		"Controller1.Action1",
348
+// 		"Controller1.Action2",
349
+// 		"Controller2.Action1",
350
+// 		"Controller2.Action2",
351
+// 	],
352
+// }
353
+func processPurviewUrlfors(data map[string]interface{}) map[int64][]string {
354
+	appUrlforsStrs := data["purview_urlfors"].(map[string]interface{})
355
+	appUrlfors := make(map[int64][]string)
356
+	for appIdStr, urlforsStr := range appUrlforsStrs {
357
+		appId, _ := strconv.Atoi(appIdStr)
358
+		var urlfors []string
359
+		json.Unmarshal([]byte(urlforsStr.(string)), &urlfors)
360
+		appUrlfors[int64(appId)] = urlfors
361
+	}
362
+	return appUrlfors
363
+}
364
+
365
+// "org_subscibes": { (org_id: ServeSubscibe)
366
+//  11: {ServeSubscibe's json}
367
+// },
368
+func processOrgSubscibes(data map[string]interface{}) map[int64]*models.ServeSubscibe {
369
+	subscibeJSONs := data["org_subscibes"].(map[string]interface{})
370
+	subscibes := make(map[int64]*models.ServeSubscibe)
371
+	for orgIDStr, subscibeJSON := range subscibeJSONs {
372
+		orgID, _ := strconv.Atoi(orgIDStr)
373
+		var subscibe models.ServeSubscibe
374
+		json.Unmarshal([]byte(subscibeJSON.(string)), &subscibe)
375
+		subscibes[int64(orgID)] = &subscibe
376
+	}
377
+	return subscibes
378
+}
379
+
380
+func ModifyPassword(adminID int64, password string) error {
381
+	err := service.UserWriteDB().Model(&models.AdminUser{}).Where("id = ? AND status = 1", adminID).Updates(map[string]interface{}{"password": password, "mtime": time.Now().Unix()}).Error
382
+	return err
383
+}

+ 372 - 0
service/article_service/article_category_service.go View File

@@ -0,0 +1,372 @@
1
+package article_service
2
+
3
+import (
4
+	"SCRM/models"
5
+	"SCRM/service"
6
+	"fmt"
7
+	"github.com/jinzhu/gorm"
8
+	"time"
9
+)
10
+
11
+func FindArticleCategoryType(userOrgId int64) (*[]models.ArticleCategory, error) {
12
+	cartegory := &[]models.ArticleCategory{}
13
+	err := service.PatientReadDB().Where("status = ? AND user_org_id = ? ", 1, userOrgId).Find(cartegory).Error
14
+	return cartegory, err
15
+}
16
+
17
+func FindCategoryList(orgID int64) (cate []*models.ArticleCategory, err error) {
18
+	err = service.PatientReadDB().Model(&models.ArticleCategory{}).Where("user_org_id =? AND status =?", orgID, 1).Order("id asc").Find(&cate).Error
19
+	return
20
+}
21
+
22
+func AddAritcle(articles models.Articles) error {
23
+	err := service.PatientWriteDB().Create(&articles).Error
24
+	return err
25
+}
26
+
27
+func FindAllArticle(orgID int64, page int64, limit int64, searchKey string, classId int64) (articles []*models.Articles, total int64, err error) {
28
+	fmt.Println("机构ID", orgID, "搜搜索", searchKey)
29
+	db := service.PatientReadDB().Table("sgj_patient_articles as a ").Where("a.status=1")
30
+	if orgID > 0 {
31
+		db = db.Where("a.user_org_id=?", orgID)
32
+	}
33
+
34
+	if classId > 0 {
35
+		db = db.Where("class_id = ?", classId)
36
+	}
37
+
38
+	if len(searchKey) > 0 {
39
+		searchKey = "%" + searchKey + "%"
40
+		db = db.Where("a.title LIKE ?", searchKey)
41
+	}
42
+
43
+	offset := (page - 1) * limit
44
+	err = db.Count(&total).Order("a.ctime desc").Offset(offset).Limit(limit).
45
+		Preload("Comments", func(db *gorm.DB) *gorm.DB {
46
+			return db.Where(" status = ?", 1)
47
+		}).Where("article_status <> ?", 3).
48
+		Select("a.id, a.title, a.summary, a.content, a.type, a.num, a.mtime, a.real_read_num, a.ctime, a.class_id, a.author, a.status, a.reason,a.star_num, a.comment_num,a.user_org_id, a.article_status, a.imgs, a.video_url, a.source, a.category_id, a.ttid, a.ttype, a.toid").Find(&articles).Error
49
+	fmt.Println("err是啥呢?", err)
50
+	if err != nil {
51
+		return
52
+	}
53
+	return
54
+}
55
+
56
+func AddCategory(name string) (*models.ArticleCategory, error) {
57
+	var art models.ArticleCategory
58
+	var err error
59
+	err = service.PatientReadDB().Model(&models.ArticleCategory{}).Where("name = ? AND status = ?", name, 1).Find(&art).Error
60
+	fmt.Println("错误", err)
61
+	if err == gorm.ErrRecordNotFound {
62
+		return nil, err
63
+	}
64
+	if err != nil {
65
+		return nil, err
66
+	}
67
+
68
+	return &art, err
69
+}
70
+
71
+func SaveCategory(category models.ArticleCategory) error {
72
+	err := service.PatientWriteDB().Create(&category).Error
73
+	return err
74
+}
75
+
76
+func GetCategorys(page int64, limit int64, orgID int64) (categorys []*models.ArticleCategory, total int64, err error) {
77
+	db := service.PatientReadDB().Table("sgj_patient_articles_menu as a").Where("a.status=1")
78
+	if orgID > 0 {
79
+		db = db.Where("a.user_org_id=?", orgID)
80
+	}
81
+	offset := (page - 1) * limit
82
+	err = db.Count(&total).Order("a.ctime desc").Offset(offset).Limit(limit).
83
+		Select("a.id,a.name,a.order,a.status,a.summary,a.type,a.user_org_id,a.mtime,a.ctime,a.num").Find(&categorys).Error
84
+	if err != nil {
85
+		return
86
+	}
87
+	//rows, err := db.Raw("SELECT t.name,(SELECT count(id) from sgj_patient_articles as a WHERE a.class_id = t.id) as count from sgj_patient_articles_menu as t").Rows()
88
+	//fmt.Println("错误",err)
89
+	//fmt.Println("rows是谁很忙",rows)
90
+	return
91
+}
92
+
93
+func GetCategorysByID(orgID int64, id int64) (categorys []*models.ArticleCategory, err error) {
94
+	err = service.PatientReadDB().Where("user_org_id = ? AND id =? AND status =1", orgID, id).Find(&categorys).Error
95
+	if err == gorm.ErrRecordNotFound {
96
+		return nil, nil
97
+	}
98
+	if err != nil {
99
+		return nil, err
100
+	}
101
+	return categorys, err
102
+}
103
+
104
+func EditCategory(cat *models.ArticleCategory, orgID int64, id int64) {
105
+	service.PatientWriteDB().Model(cat).Where("user_org_id =? AND id =? AND status = ?", orgID, id, 1).Update(map[string]interface{}{"Name": cat.Name, "Summary": cat.Summary, "Order": cat.Order, "mtime": cat.Mtime})
106
+}
107
+
108
+func DeleteCategorys(orgID int64, ids []int64) (err error) {
109
+	if len(ids) == 1 {
110
+		err = service.PatientWriteDB().Model(&models.ArticleCategory{}).Where("id=? and user_org_id = ?", ids[0], orgID).Update(map[string]interface{}{"Status": 0, "mtime": time.Now().Unix()}).Error
111
+	} else {
112
+		err = service.PatientWriteDB().Model(&models.ArticleCategory{}).Where("id IN (?) and user_org_id = ?", ids, orgID).Update(map[string]interface{}{"Status": 0, "mtime": time.Now().Unix()}).Error
113
+	}
114
+	return
115
+}
116
+
117
+func AddVido(articles models.Articles) error {
118
+	err := service.PatientWriteDB().Create(&articles).Error
119
+	return err
120
+}
121
+
122
+func AddPrviewArticle(articles models.Articles) (err error) {
123
+	err = service.PatientWriteDB().Create(&articles).Error
124
+	return err
125
+}
126
+
127
+func GetArtilcePreview(OrgID int64) (models.Articles, error) {
128
+	article := models.Articles{}
129
+	err := service.PatientReadDB().Where("user_org_id = ? AND article_status = ? AND type = ?", OrgID, 3, 1).Last(&article).Error
130
+	return article, err
131
+}
132
+
133
+func AddDraft(articles models.Articles) error {
134
+	err := service.PatientReadDB().Create(&articles).Error
135
+	return err
136
+}
137
+
138
+func GetPublished(orgID int64, page int64, limit int64, searchKey string) (articles []*models.Articles, total int64, err error) {
139
+	db := service.PatientReadDB().Table("sgj_patient_articles as a ").Where("a.status=1")
140
+	if orgID > 0 {
141
+		db = db.Where("a.user_org_id=? AND article_status = ?", orgID, 1)
142
+	}
143
+	if len(searchKey) > 0 {
144
+		searchKey = "%" + searchKey + "%"
145
+		db = db.Where("a.title LIKE ?", searchKey)
146
+	}
147
+	offset := (page - 1) * limit
148
+	err = db.Count(&total).Order("a.ctime desc").Offset(offset).Limit(limit).
149
+		Preload("Comments", func(db *gorm.DB) *gorm.DB {
150
+			return db.Where(" status = ?", 1)
151
+		}).Where("status = ?", 1).
152
+		Select("a.id, a.title, a.summary, a.content, a.type, a.num, a.mtime, a.real_read_num, a.ctime, a.class_id, a.author, a.status, a.reason,a.star_num, a.comment_num,a.user_org_id, a.article_status, a.imgs, a.video_url, a.source, a.category_id, a.ttid, a.ttype, a.toid").Find(&articles).Error
153
+	fmt.Println("err是啥呢?", err)
154
+	if err != nil {
155
+		return
156
+	}
157
+	return
158
+}
159
+
160
+//func GetAllartic(page int64,limit int64,orgID int64)(articles []*models.Articles,total int64, err error)  {
161
+//	db := service.PatientReadDB().Table("sgj_patient_articles as a ").Where("a.status=1")
162
+//	if (orgID > 0) {
163
+//		db = db.Where("a.user_org_id=? AND article_status = ?", orgID,1)
164
+//	}
165
+//	offset := (page - 1) * limit
166
+//	err = db.Count(&total).Order("a.ctime desc").Offset(offset).Limit(limit).
167
+//		Preload("Comments", func(db *gorm.DB) *gorm.DB {
168
+//		return  db.Where(" status = ?",1)
169
+//	}).Select("a.id, a.title, a.summary, a.content, a.type, a.num, a.mtime, a.real_read_num, a.ctime, a.class_id, a.author, a.status, a.reason,a.star_num, a.comment_num,a.user_org_id, a.article_status, a.imgs, a.video_url, a.source, a.category_id, a.ttid, a.ttype, a.toid").Find(&articles).Error
170
+//	fmt.Println("err是啥呢?",err)
171
+//	if err != nil {
172
+//		return
173
+//	}
174
+//	return
175
+//}
176
+
177
+func GetDraftbox(orgID int64, page int64, limit int64, searchKey string) (articles []*models.Articles, total int64, err error) {
178
+	db := service.PatientReadDB().Table("sgj_patient_articles as a ").Where("a.status=1")
179
+	if orgID > 0 {
180
+		db = db.Where("a.user_org_id=? AND article_status = ?", orgID, 2)
181
+	}
182
+	if len(searchKey) > 0 {
183
+		searchKey = "%" + searchKey + "%"
184
+		db = db.Where("a.title LIKE ?", searchKey)
185
+	}
186
+	offset := (page - 1) * limit
187
+	err = db.Count(&total).Order("a.ctime desc").Offset(offset).Limit(limit).
188
+		Preload("Comments", func(db *gorm.DB) *gorm.DB {
189
+			return db.Where(" status = ?", 1)
190
+		}).Where("article_status = ? AND status = ?", 2, 1).
191
+		Select("a.id, a.title, a.summary, a.content, a.type, a.num, a.mtime, a.real_read_num, a.ctime, a.class_id, a.author, a.status, a.reason,a.star_num, a.comment_num,a.user_org_id, a.article_status, a.imgs, a.video_url, a.source, a.category_id, a.ttid, a.ttype, a.toid").Find(&articles).Error
192
+	fmt.Println("err是啥呢?", err)
193
+	if err != nil {
194
+		return
195
+	}
196
+	return
197
+}
198
+
199
+func GetNoPass(orgID int64, page int64, limit int64, searchKey string) (articles []*models.Articles, total int64, err error) {
200
+	db := service.PatientReadDB().Table("sgj_patient_articles as a ").Where("a.status=1")
201
+	if orgID > 0 {
202
+		db = db.Where("a.user_org_id=? AND article_status = ?", orgID, 4)
203
+	}
204
+	if len(searchKey) > 0 {
205
+		searchKey = "%" + searchKey + "%"
206
+		db = db.Where("a.title LIKE ?", searchKey)
207
+	}
208
+	offset := (page - 1) * limit
209
+	err = db.Count(&total).Order("a.ctime desc").Offset(offset).Limit(limit).
210
+		Preload("Comments", func(db *gorm.DB) *gorm.DB {
211
+			return db.Where(" status = ?", 1)
212
+		}).Where("article_status = ? AND status = ?", 4, 1).
213
+		Select("a.id, a.title, a.summary, a.content, a.type, a.num, a.mtime, a.real_read_num, a.ctime, a.class_id, a.author, a.status, a.reason,a.star_num, a.comment_num,a.user_org_id, a.article_status, a.imgs, a.video_url, a.source, a.category_id, a.ttid, a.ttype, a.toid").Find(&articles).Error
214
+	fmt.Println("err是啥呢?", err)
215
+	if err != nil {
216
+		return
217
+	}
218
+	return
219
+}
220
+
221
+func GetArticleInfo(orgID int64, id int64) (articles models.Articles, err error) {
222
+	err = service.PatientReadDB().Where("user_org_id = ? AND id = ? AND status = ?", orgID, id, 1).Find(&articles).Error
223
+	return articles, err
224
+}
225
+
226
+func DeleteArticle(ids []int64, orgID int64) (err error) {
227
+	if len(ids) == 1 {
228
+		err = service.PatientWriteDB().Model(&models.Articles{}).Where("id=? and user_org_id = ?", ids[0], orgID).Update(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
229
+	} else {
230
+		err = service.PatientWriteDB().Model(&models.Articles{}).Where("id IN (?) and user_org_id = ?", ids, orgID).Update(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
231
+	}
232
+	return
233
+}
234
+
235
+func DeleteArticles(id int64, orgID int64) (err error) {
236
+	err = service.PatientWriteDB().Model(&models.Articles{}).Where("id = ? and user_org_id = ?", id, orgID).Update(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
237
+	return
238
+}
239
+
240
+func GetMenus(OrgID int64) (categorys []*models.ArticleCategory, err error) {
241
+	err = service.PatientReadDB().Where("user_org_id = ? AND status = ?", OrgID, 1).Find(&categorys).Error
242
+	return categorys, err
243
+}
244
+
245
+func UpdataArticleInfo(art *models.Articles, orgID int64, id int64) {
246
+	service.PatientWriteDB().Model(art).Where("user_org_id = ? AND id = ? AND status = ?", orgID, id, 1).Update(map[string]interface{}{"title": art.Title, "content": art.Content, "imgs": art.Imgs, "video_url": art.VideoUrl, "class_id": art.ClassId, "mtime": art.Mtime, "article_status": art.ArticleStatus})
247
+
248
+}
249
+
250
+func SaveVidoDraft(art *models.Articles, orgID int64, id int64) {
251
+	service.PatientWriteDB().Model(art).Where("user_org_id =? AND id = ? AND status = ?", orgID, id, 1).Update(map[string]interface{}{"title": art.Title, "imgs": art.Imgs, "class_id": art.ClassId, "mtime": art.Mtime, "article_status": art.ArticleStatus})
252
+}
253
+
254
+func PreviewEditArticle(art models.Articles, orgID int64, id int64) {
255
+	service.PatientWriteDB().Model(art).Where("user_org_id = ? AND id = ? AND status = ?", orgID, id, 1).Update(map[string]interface{}{"title": art.Title, "content": art.Content, "imgs": art.Imgs, "class_id": art.ClassId, "mtime": art.Mtime, "article_status": art.ArticleStatus})
256
+}
257
+
258
+//func GetPreviewInfo(orgID int64)(models.Articles,error)  {
259
+//	article := models.Articles{}
260
+//	err := service.PatientReadDB().Where("user_org_id = ? AND article_status = ? AND type = ?", orgID, 3, 1).Last(&article).Error
261
+//	return article, err
262
+//}
263
+
264
+func GetPreviewInfoById(id int64, orgid int64) (models.Articles, error) {
265
+	articles := models.Articles{}
266
+	err := service.PatientReadDB().Model(articles).Where("id = ? AND user_org_id = ?", id, orgid).Find(&articles).Error
267
+	return articles, err
268
+}
269
+
270
+func GetAllComment(page int64, limit int64, orgID int64) (articles []*models.Articles, total int64, err error) {
271
+	db := service.PatientReadDB().Table("sgj_patient_articles as a ").Where("a.status=1")
272
+	if orgID > 0 {
273
+		db = db.Where("a.user_org_id=? AND article_status = ?", orgID, 1)
274
+	}
275
+	offset := (page - 1) * limit
276
+	err = db.Count(&total).Order("a.ctime desc").Offset(offset).Limit(limit).
277
+		Preload("Comments", func(db *gorm.DB) *gorm.DB {
278
+			return db.Where(" status = ?", 1)
279
+		}).
280
+		Select("a.id, a.title, a.summary, a.content, a.type, a.num, a.mtime, a.real_read_num, a.ctime, a.class_id, a.author, a.status, a.reason,a.star_num, a.comment_num,a.user_org_id, a.article_status, a.imgs, a.video_url, a.source, a.category_id, a.ttid, a.ttype, a.toid").Find(&articles).Error
281
+	fmt.Println("err是啥呢?", err)
282
+	if err != nil {
283
+		return
284
+	}
285
+	return
286
+}
287
+
288
+func GetArticleCommentDetail(articleId int64, orgID int64) (*models.Articles, error) {
289
+	article := &models.Articles{}
290
+	err := service.PatientReadDB().Where("id = ? AND user_org_id = ? AND status = ?", articleId, orgID, 1).Find(article).Error
291
+	tm := time.Unix(article.Ctime, 0)
292
+	article.PublicTime = tm.Format("2006-01-02 15:04:05")
293
+	return article, err
294
+}
295
+
296
+func FindAllComments(page int64, limit int64, articleId int64) (comment []*models.Comment, total int64, err error) {
297
+	db := service.PatientReadDB().Table("sgj_patient_articles_comment as a").Where("a.status = 1")
298
+	offset := (page - 1) * limit
299
+	err = db.Where("article_id = ? AND parent_id = ?", articleId, 0).Count(&total).Order("a.ctime desc").Offset(offset).Limit(limit).
300
+		Select("a.id,a.article_id,a.comment_user_id,a.parent_id,a.content,a.ctime,a.status,a.star_num,a.comment_num,a.comment_id,a.comment_user_name,a.comment_user_avater,a.source,a.ttid,a.tuser_id,a.taid,a.tpid,a.tcid").Find(&comment).Error
301
+	fmt.Println("err是啥呢?", err)
302
+	if err != nil {
303
+		return
304
+	}
305
+	return
306
+}
307
+
308
+func AddComment(comment *models.Comment) error {
309
+	err := service.PatientReadDB().Create(comment).Error
310
+	return err
311
+}
312
+
313
+func GetReplyAllComents(orgid int64, page int64, limit int64) (comment []*models.Comment, total int64, err error) {
314
+	db := service.PatientReadDB().Table("sgj_patient_articles_comment as a").Where("a.status = ? AND a.user_org_id = ?", 1, orgid)
315
+	offset := (page - 1) * limit
316
+	err = db.Where("parent_id = ?", 0).Count(&total).Order("a.ctime desc").Offset(offset).Limit(limit).
317
+		Select("a.id,a.article_id,a.comment_user_id,a.parent_id,a.content,a.ctime,a.status,a.star_num,a.comment_num,a.comment_id,a.comment_user_name,a.comment_user_avater,a.source,a.ttid,a.tuser_id,a.taid,a.tpid,a.tcid").Find(&comment).Error
318
+	fmt.Println("err是啥呢?", err)
319
+	if err != nil {
320
+		return
321
+	}
322
+	return
323
+}
324
+
325
+func GetAllReplyFormId(articleID int64, commentId int64) ([]models.Comment, error) {
326
+	var comments []models.Comment
327
+	errs := service.PatientReadDB().Model(&models.Comment{}).
328
+		Where("article_id = ? AND parent_id = ? AND status = ?", articleID, commentId, 1).
329
+		Find(&comments).Error
330
+
331
+	return comments, errs
332
+}
333
+
334
+func ClearReplyInfo(id int64) error {
335
+	err := service.PatientWriteDB().Model(&models.Comment{}).Where("id = ?", id).Update(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
336
+	return err
337
+}
338
+
339
+func DeleteReply(id int64) error {
340
+	err := service.PatientWriteDB().Model(&models.Comment{}).Where("id = ?", id).Update(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
341
+	return err
342
+}
343
+func GetQueryReplyInfo(parentid int64, articleID int64) ([]models.Comment, error) {
344
+	var comments []models.Comment
345
+	errs := service.PatientWriteDB().Model(&models.Comment{}).
346
+		Where("article_id = ? AND parent_id = ? AND status = ?", articleID, parentid, 1).Find(&comments).Error
347
+	return comments, errs
348
+}
349
+
350
+func DeleteAllReply(ids []int64) (err error) {
351
+	if len(ids) == 1 {
352
+		err = service.PatientWriteDB().Model(&models.Comment{}).Where("id=?", ids[0]).Update(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
353
+	} else {
354
+		err = service.PatientWriteDB().Model(&models.Comment{}).Where("id IN (?)", ids).Update(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
355
+	}
356
+	return
357
+}
358
+
359
+func DeleteAllArticles(ids []int64) (err error) {
360
+	if len(ids) == 1 {
361
+		err = service.PatientWriteDB().Model(&models.Articles{}).Where("id=?", ids[0]).Update(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
362
+	} else {
363
+		err = service.PatientWriteDB().Model(&models.Articles{}).Where("id IN (?)", ids).Update(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
364
+	}
365
+	return
366
+}
367
+
368
+func GetArticleDetailById(id int64, orgid int64) (models.Articles, error) {
369
+	articles := models.Articles{}
370
+	err := service.PatientReadDB().Model(articles).Where("id = ? AND user_org_id = ? AND status = ?", id, orgid, 1).Find(&articles).Error
371
+	return articles, err
372
+}

+ 10 - 0
service/article_service/models.go View File

@@ -0,0 +1,10 @@
1
+package article_service
2
+
3
+import (
4
+	"SCRM/models"
5
+)
6
+
7
+type Articles struct {
8
+	models.Articles
9
+	ArticleCategory []*models.ArticleCategory `gorm:"foreignkey:class_id" json:"id"`
10
+}

+ 108 - 0
service/db.go View File

@@ -0,0 +1,108 @@
1
+// Pipe - A small and beautiful blogging platform written in golang.
2
+// Copyright (C) 2017-2018, b3log.org
3
+//
4
+// This program is free software: you can redistribute it and/or modify
5
+// it under the terms of the GNU General Public License as published by
6
+// the Free Software Foundation, either version 3 of the License, or
7
+// (at your option) any later version.
8
+//
9
+// This program is distributed in the hope that it will be useful,
10
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
+// GNU General Public License for more details.
13
+//
14
+// You should have received a copy of the GNU General Public License
15
+// along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
+
17
+package service
18
+
19
+import (
20
+	"fmt"
21
+
22
+	"github.com/astaxie/beego"
23
+	"github.com/jinzhu/gorm"
24
+	_ "github.com/jinzhu/gorm/dialects/mysql" // mysql
25
+)
26
+
27
+var readDb *gorm.DB
28
+var writeDb *gorm.DB
29
+var readUserDb *gorm.DB
30
+var writeUserDb *gorm.DB
31
+var err error
32
+
33
+func ConnectDB() {
34
+	readHost := beego.AppConfig.String("readmysqlhost")
35
+	readPort := beego.AppConfig.String("readmysqlport")
36
+	readUser := beego.AppConfig.String("readmysqluser")
37
+	readPass := beego.AppConfig.String("readmysqlpass")
38
+	readName := beego.AppConfig.String("readmysqlname")
39
+
40
+	writeHost := beego.AppConfig.String("writemysqlhost")
41
+	writePort := beego.AppConfig.String("writemysqlport")
42
+	writeUser := beego.AppConfig.String("writemysqluser")
43
+	writePass := beego.AppConfig.String("writemysqlpass")
44
+	writeName := beego.AppConfig.String("writemysqlname")
45
+
46
+	readUserHost := beego.AppConfig.String("readuserhost")
47
+	readUserPort := beego.AppConfig.String("readuserport")
48
+	readUserUser := beego.AppConfig.String("readuseruser")
49
+	readUserPass := beego.AppConfig.String("readuserpass")
50
+	readUserName := beego.AppConfig.String("readusername")
51
+
52
+	writeUserHost := beego.AppConfig.String("writeuserhost")
53
+	writeUserPort := beego.AppConfig.String("writeuserport")
54
+	writeUserUser := beego.AppConfig.String("writeuseruser")
55
+	writeUserPass := beego.AppConfig.String("writeuserpass")
56
+	writeUserName := beego.AppConfig.String("writeusername")
57
+
58
+	rdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readUser, readPass, readHost, readPort, readName)
59
+	wdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writeUser, writePass, writeHost, writePort, writeName)
60
+
61
+	rudsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readUserUser, readUserPass, readUserHost, readUserPort, readUserName)
62
+	wudsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writeUserUser, writeUserPass, writeUserHost, writeUserPort, writeUserName)
63
+
64
+	readDb, err = gorm.Open("mysql", rdsn)
65
+	if err != nil {
66
+		//beego.Error(err)
67
+	}
68
+	readDb.DB().SetMaxIdleConns(10)
69
+	readDb.DB().SetMaxOpenConns(100)
70
+	readDb.LogMode(true)
71
+
72
+	writeDb, err = gorm.Open("mysql", wdsn)
73
+	if err != nil {
74
+		//beego.Error(err)
75
+	}
76
+	writeDb.DB().SetMaxIdleConns(10)
77
+	writeDb.DB().SetMaxOpenConns(100)
78
+	writeDb.LogMode(true)
79
+
80
+	readUserDb, err = gorm.Open("mysql", rudsn)
81
+	if err != nil {
82
+		//beego.Error(err)
83
+	}
84
+	readUserDb.DB().SetMaxIdleConns(10)
85
+	readUserDb.DB().SetMaxOpenConns(100)
86
+	readUserDb.LogMode(true)
87
+
88
+	writeUserDb, err = gorm.Open("mysql", wudsn)
89
+	if err != nil {
90
+		//beego.Error(err)
91
+	}
92
+	writeUserDb.DB().SetMaxIdleConns(10)
93
+	writeUserDb.DB().SetMaxOpenConns(100)
94
+	writeUserDb.LogMode(true)
95
+}
96
+
97
+func PatientReadDB() *gorm.DB {
98
+	return readDb
99
+}
100
+func PatientWriteDB() *gorm.DB {
101
+	return writeDb
102
+}
103
+func UserReadDB() *gorm.DB {
104
+	return readUserDb
105
+}
106
+func UserWriteDB() *gorm.DB {
107
+	return writeUserDb
108
+}

+ 11 - 0
service/district_service/district_service.go View File

@@ -0,0 +1,11 @@
1
+package district_service
2
+
3
+import (
4
+	"SCRM/models"
5
+	"SCRM/service"
6
+)
7
+
8
+func GetDistrictsByUpid(id int64) (dis []*models.District, err error) {
9
+	err = service.UserReadDB().Model(&models.District{}).Where("upid=?", id).Find(&dis).Error
10
+	return
11
+}

+ 14 - 0
service/login_service/login_service.go View File

@@ -0,0 +1,14 @@
1
+package login_service
2
+
3
+import (
4
+	"SCRM/models"
5
+	"SCRM/service"
6
+	"fmt"
7
+)
8
+
9
+func QueryLogin(tel string, psd string) (models.SgjUserAdmin, error) {
10
+	fmt.Println("bbbbbbbbbbbbbbbbbbbb")
11
+	admin := models.SgjUserAdmin{}
12
+	err := service.UserReadDB().Where("mobile = ? AND password = ? AND status = ?", tel, psd, 1).Find(&admin).Error
13
+	return admin, err
14
+}

+ 221 - 0
service/marketing_tool_service/activity_service.go View File

@@ -0,0 +1,221 @@
1
+package marketing_tool_service
2
+
3
+import (
4
+	"SCRM/models"
5
+	"SCRM/service"
6
+	"time"
7
+
8
+	"github.com/jinzhu/gorm"
9
+)
10
+
11
+func GetValidActivities(orgID int64, appID int64, keyWord string, page int, count int) ([]*models.Activity, int64, error) {
12
+	if count <= 0 {
13
+		return []*models.Activity{}, 0, nil
14
+	}
15
+	if page < 1 {
16
+		page = 1
17
+	}
18
+
19
+	var activities []*models.Activity
20
+	var totalCount int64
21
+	db := service.PatientReadDB().Model(&models.Activity{}).Where("user_org_id = ? AND user_app_id = ? AND status <> 9", orgID, appID)
22
+	if len(keyWord) > 0 {
23
+		likeParam := "%" + keyWord + "%"
24
+		db = db.Where("title LIKE ?", likeParam)
25
+	}
26
+
27
+	err := db.
28
+		Count(&totalCount).
29
+		Order("ctime desc").Limit(count).Offset((page - 1) * count).Find(&activities).
30
+		Error
31
+
32
+	if err == nil {
33
+		return activities, totalCount, nil
34
+	} else {
35
+		return nil, 0, err
36
+	}
37
+}
38
+
39
+func GetActivitiesWithStatus(orgID int64, appID int64, keyWord string, status int, page int, count int) ([]*models.Activity, int64, error) {
40
+	if count <= 0 {
41
+		return []*models.Activity{}, 0, nil
42
+	}
43
+	if page < 1 {
44
+		page = 1
45
+	}
46
+
47
+	var activities []*models.Activity
48
+	var totalCount int64
49
+	db := service.PatientReadDB().Model(&models.Activity{}).Where("user_org_id = ? AND user_app_id = ? AND status = ?", orgID, appID, status)
50
+	if len(keyWord) > 0 {
51
+		likeParam := "%" + keyWord + "%"
52
+		db = db.Where("title LIKE ?", likeParam)
53
+	}
54
+	err := db.
55
+		Count(&totalCount).
56
+		Order("ctime desc").Limit(count).Offset((page - 1) * count).Find(&activities).
57
+		Error
58
+
59
+	if err == nil {
60
+		return activities, totalCount, nil
61
+	} else {
62
+		return nil, 0, err
63
+	}
64
+}
65
+
66
+func GetDidEndedActivities(orgID int64, appID int64, keyWord string, page int, count int) ([]*models.Activity, int64, error) {
67
+	if count <= 0 {
68
+		return []*models.Activity{}, 0, nil
69
+	}
70
+	if page < 1 {
71
+		page = 1
72
+	}
73
+
74
+	var activities []*models.Activity
75
+	var totalCount int64
76
+	now := time.Now().Unix()
77
+	db := service.PatientReadDB().Model(&models.Activity{}).Where("user_org_id = ? AND user_app_id = ? AND status = 1 AND start_time < ?", orgID, appID, now)
78
+	if len(keyWord) > 0 {
79
+		likeParam := "%" + keyWord + "%"
80
+		db = db.Where("title LIKE ?", likeParam)
81
+	}
82
+	err := db.
83
+		Count(&totalCount).
84
+		Order("ctime desc").Limit(count).Offset((page - 1) * count).Find(&activities).
85
+		Error
86
+
87
+	if err == nil {
88
+		return activities, totalCount, nil
89
+	} else {
90
+		return nil, 0, err
91
+	}
92
+}
93
+
94
+func GetActivityWithID(orgID int64, activityID int64) (*models.Activity, error) {
95
+	var activity models.Activity
96
+	err := service.PatientReadDB().Model(&models.Activity{}).Where("user_org_id = ? and id = ?", orgID, activityID).First(&activity).Error
97
+	if err != nil {
98
+		if err == gorm.ErrRecordNotFound {
99
+			return nil, nil
100
+		} else {
101
+			return nil, err
102
+		}
103
+	}
104
+	return &activity, nil
105
+}
106
+
107
+func GetActivityParagraphByActivityID(activityID int64) (*models.ActivityParagraph, error) {
108
+	var paragraph models.ActivityParagraph
109
+	err :=
110
+		service.PatientReadDB().Model(&models.ActivityParagraph{}).
111
+			Where("activity_id = ? and status = 1", activityID).
112
+			First(&paragraph).
113
+			Error
114
+	if err != nil {
115
+		if err == gorm.ErrRecordNotFound {
116
+			return nil, nil
117
+		} else {
118
+			return nil, err
119
+		}
120
+	}
121
+	return &paragraph, nil
122
+}
123
+
124
+func GetActivityWxShareByActivityID(activityID int64) (*models.ActivityWxShare, error) {
125
+	var model models.ActivityWxShare
126
+	err :=
127
+		service.PatientReadDB().Model(&models.ActivityWxShare{}).
128
+			Where("activity_id = ?", activityID).
129
+			First(&model).
130
+			Error
131
+	if err != nil {
132
+		if err == gorm.ErrRecordNotFound {
133
+			return nil, nil
134
+		} else {
135
+			return nil, err
136
+		}
137
+	}
138
+	return &model, nil
139
+}
140
+
141
+func SaveActivityAndParagraph(activity *models.Activity, paragraph *models.ActivityParagraph) error {
142
+	tx := service.PatientWriteDB().Begin()
143
+	saveActivityErr := tx.Save(activity).Error
144
+	if saveActivityErr != nil {
145
+		tx.Rollback()
146
+		return saveActivityErr
147
+	}
148
+	if paragraph != nil {
149
+		if paragraph.Id == 0 {
150
+			paragraph.ActivityId = activity.Id
151
+		}
152
+
153
+		saveParagraphErr := tx.Save(paragraph).Error
154
+		if saveParagraphErr != nil {
155
+			tx.Rollback()
156
+			return saveParagraphErr
157
+		}
158
+	}
159
+
160
+	tx.Commit()
161
+	return nil
162
+}
163
+
164
+func SaveActivityWxShare(model *models.ActivityWxShare) error {
165
+	return service.PatientWriteDB().Save(model).Error
166
+}
167
+
168
+func GetValidActivitySignupUsers(activityID int64, keyWord string, page int) ([]*models.ActivityUser, int, error) {
169
+	var users []*models.ActivityUser
170
+	countPerPage := 10
171
+	var totalCount int
172
+	db := service.PatientReadDB().Model(&models.ActivityUser{}).Where("activity_id = ? AND status = 1", activityID)
173
+	if len(keyWord) > 0 {
174
+		likeParam := "%" + keyWord + "%"
175
+		db = db.Where("mobile LIKE ? OR realname LIKE ?", likeParam, likeParam)
176
+	}
177
+	err := db.
178
+		Count(&totalCount).
179
+		Order("id asc").Limit(countPerPage).Offset((page - 1) * countPerPage).
180
+		Find(&users).
181
+		Error
182
+
183
+	if err == nil {
184
+		return users, totalCount, nil
185
+	} else {
186
+		return nil, 0, err
187
+	}
188
+}
189
+
190
+func DeleteActivity(orgID int64, activityID int64) error {
191
+	tx := service.PatientWriteDB().Begin()
192
+	deleteActivityErr := tx.Model(&models.Activity{}).Where("user_org_id = ? AND id = ?", orgID, activityID).Updates(map[string]interface{}{
193
+		"status": 9,
194
+		"mtime":  time.Now().Unix(),
195
+	}).Error
196
+	if deleteActivityErr != nil {
197
+		tx.Rollback()
198
+		return deleteActivityErr
199
+	}
200
+
201
+	// deletePErr := tx.Model(&models.ActivityParagraph{}).Where("activity_id = ?", activityID).Updates(map[string]interface{}{
202
+	// 	"status": 0,
203
+	// 	"mtime":  time.Now().Unix(),
204
+	// }).Error
205
+	// if deletePErr != nil {
206
+	// 	tx.Rollback()
207
+	// 	return deletePErr
208
+	// }
209
+
210
+	// deleteShareErr := tx.Model(&models.ActivityWxShare{}).Where("activity_id = ?", activityID).Updates(map[string]interface{}{
211
+	// 	"status": 0,
212
+	// 	"mtime":  time.Now().Unix(),
213
+	// }).Error
214
+	// if deleteShareErr != nil {
215
+	// 	tx.Rollback()
216
+	// 	return deleteShareErr
217
+	// }
218
+
219
+	tx.Commit()
220
+	return nil
221
+}

+ 141 - 0
service/member_service/cards_service.go View File

@@ -0,0 +1,141 @@
1
+package member_service
2
+
3
+import (
4
+	"SCRM/models"
5
+	"SCRM/service"
6
+	"time"
7
+
8
+	"github.com/jinzhu/gorm"
9
+)
10
+
11
+func GetCardList(orgID int64) (cards []*models.UserMembershipCard, err error) {
12
+	err = service.UserReadDB().Model(&models.UserMembershipCard{}).Where("status=1 and user_org_id=?", orgID).Find(&cards).Error
13
+	return
14
+}
15
+
16
+func GetCardByID(orgID, cardID int64) (*models.UserMembershipCard, error) {
17
+	var card models.UserMembershipCard
18
+	var err error
19
+	err = service.UserReadDB().Model(&models.UserMembershipCard{}).Where("id=? and user_org_id=? and status=1", cardID, orgID).First(&card).Error
20
+	if err == gorm.ErrRecordNotFound {
21
+		return nil, nil
22
+	}
23
+	if err != nil {
24
+		return nil, err
25
+	}
26
+	return &card, nil
27
+}
28
+
29
+func GetUserCardByID(orgID, customerID int64) (*models.UserCard, error) {
30
+	var card models.UserCard
31
+	var err error
32
+	err = service.UserReadDB().Model(&models.UserCard{}).Where("user_org_id=? and customer_id=? and status=1", orgID, customerID).First(&card).Error
33
+	if err == gorm.ErrRecordNotFound {
34
+		return nil, nil
35
+	}
36
+	if err != nil {
37
+		return nil, err
38
+	}
39
+	return &card, nil
40
+}
41
+
42
+func DeleteUserCard(orgID, customerID int64) (err error) {
43
+	err = service.UserWriteDB().Model(&models.UserCard{}).Where("user_org_id=? and customer_id=? ", orgID, customerID).Update(map[string]interface{}{"Status": 0, "UpdatedTime": time.Now().Unix()}).Error
44
+	return
45
+}
46
+
47
+func SaveUserCard(card *models.UserCard, member *Members) (err error) {
48
+	if member.Membership == 1 {
49
+		err = service.UserWriteDB().Save(card).Error
50
+	} else {
51
+		tx := service.UserWriteDB().Begin()
52
+		err = service.UserWriteDB().Save(card).Error
53
+		if err != nil {
54
+			tx.Rollback()
55
+			return
56
+		}
57
+
58
+		err = service.UserWriteDB().Model(&models.UserCustomer{}).Where("id=? and user_org_id=? ", member.ID, member.UserOrgId).Update(map[string]interface{}{"Membership": 1, "UpdatedTime": time.Now().Unix()}).Error
59
+		if err != nil {
60
+			tx.Rollback()
61
+			return
62
+		}
63
+		tx.Commit()
64
+	}
65
+
66
+	return
67
+}
68
+
69
+func FindMemberCardByName(orgID int64, name string) (*models.UserMembershipCard, error) {
70
+	var card models.UserMembershipCard
71
+	var err error
72
+	err = service.UserReadDB().Model(&models.UserMembershipCard{}).Where("card_name = ? AND user_org_id=? AND status=1", name, orgID).First(&card).Error
73
+	if err == gorm.ErrRecordNotFound {
74
+		return nil, nil
75
+	}
76
+	if err != nil {
77
+		return nil, err
78
+	}
79
+	return &card, nil
80
+}
81
+
82
+func SaveMemberCard(card *models.UserMembershipCard) (err error) {
83
+	err = service.UserWriteDB().Save(card).Error
84
+	return
85
+}
86
+
87
+func FindOnlyMemberCardByID(orgID, id int64) (*models.UserMembershipCard, error) {
88
+	var card models.UserMembershipCard
89
+	var err error
90
+	err = service.UserReadDB().Model(&models.UserMembershipCard{}).Where("id = ? AND user_org_id=? AND status=1", id, orgID).First(&card).Error
91
+	if err == gorm.ErrRecordNotFound {
92
+		return nil, nil
93
+	}
94
+	if err != nil {
95
+		return nil, err
96
+	}
97
+	return &card, nil
98
+}
99
+
100
+func GetMemebrCardCount(orgID int64) (count int64, err error) {
101
+	err = service.UserReadDB().Model(&models.UserMembershipCard{}).Where("user_org_id=? AND status=1", orgID).Count(&count).Error
102
+	return
103
+}
104
+
105
+func GetCardUserCount(orgID, id int64) (count int64, err error) {
106
+	err = service.UserReadDB().Table("sgj_user_user_card as uc").Joins("JOIN sgj_user_customer as c ON c.id=uc.customer_id AND uc.user_org_id=? AND c.user_org_id=? AND uc.card_id=?", orgID, orgID, id).Where("uc.card_id=? AND uc.status=1 AND c.status=1", id).Count(&count).Error
107
+
108
+	return
109
+}
110
+
111
+func GetCardsUserCount(orgID int64, ids []int64) (counts []*CardsMemberCount, err error) {
112
+	err = service.UserReadDB().Table("sgj_user_user_card as uc").Joins("JOIN sgj_user_customer as c ON c.id=uc.customer_id AND uc.user_org_id=? AND c.user_org_id=?", orgID, orgID).Where("uc.card_id IN (?) AND uc.status=1 AND c.status=1", ids).Select("uc.card_id, COUNT(uc.card_id) AS member_count").Group("uc.card_id").Scan(&counts).Error
113
+
114
+	return
115
+}
116
+
117
+func DeleteMemberShipCards(orgID int64, ids []int64) (err error) {
118
+	if len(ids) == 1 {
119
+		err = service.UserWriteDB().Model(&models.UserMembershipCard{}).Where("id =? and user_org_id =?", ids[0], orgID).Update(map[string]interface{}{"Status": 0, "UpdatedTime": time.Now().Unix()}).Error
120
+	} else {
121
+		err = service.UserWriteDB().Model(&models.UserMembershipCard{}).Where("id IN (?) and user_org_id =?", ids, orgID).Update(map[string]interface{}{"Status": 0, "UpdatedTime": time.Now().Unix()}).Error
122
+	}
123
+	return
124
+}
125
+
126
+func GetMembershipRights(orgID int64) (*models.MembershipRights, error) {
127
+	var right models.MembershipRights
128
+	err := service.UserReadDB().Model(&models.MembershipRights{}).Where("user_org_id=?", orgID).First(&right).Error
129
+	if err == gorm.ErrRecordNotFound {
130
+		return nil, nil
131
+	}
132
+	if err != nil {
133
+		return nil, err
134
+	}
135
+	return &right, nil
136
+}
137
+
138
+func SaveMembershipRight(right *models.MembershipRights) (err error) {
139
+	err = service.UserWriteDB().Save(right).Error
140
+	return
141
+}

+ 22 - 0
service/member_service/illness_service.go View File

@@ -0,0 +1,22 @@
1
+package member_service
2
+
3
+import (
4
+	"SCRM/models"
5
+	"SCRM/service"
6
+)
7
+
8
+func GetIllnessList() (ills []*models.Illness, err error) {
9
+	err = service.UserReadDB().Where("status=1").Find(&ills).Error
10
+	return
11
+}
12
+
13
+func GetMemberAllIllnessByIllIDs(orgID, customerID int64, ids []int64) (ills []*CustomerIllness, err error) {
14
+	err = service.UserReadDB().Where("user_org_id = ? and customer_id =? and illness_id IN (?) ", orgID, customerID, ids).Find(&ills).Error
15
+	return
16
+}
17
+
18
+//GetMemberAllIllness 取所有(包括已经软删除的记录)
19
+func GetMemberAllIllness(orgID, customerID int64) (ills []*CustomerIllness, err error) {
20
+	err = service.UserReadDB().Where("user_org_id = ? and customer_id =? ", orgID, customerID).Find(&ills).Error
21
+	return
22
+}

+ 201 - 0
service/member_service/member_service.go View File

@@ -0,0 +1,201 @@
1
+package member_service
2
+
3
+import (
4
+	"SCRM/models"
5
+	"SCRM/service"
6
+	"strings"
7
+
8
+	"time"
9
+
10
+	"fmt"
11
+	"github.com/jinzhu/gorm"
12
+)
13
+
14
+func GetMemberList(orgID, page, limit, level, source, tag, startTime, endTime int64, isStartTime, isEndTime bool, searchKey string) (members []*Members, total int64, err error) {
15
+	db := service.UserReadDB().Table("sgj_user_customer as c").Where("c.status=1")
16
+	if orgID > 0 {
17
+		db = db.Where("c.user_org_id=?", orgID)
18
+	}
19
+	if source > 0 {
20
+		db = db.Where("c.sources=?", source)
21
+	}
22
+	if isStartTime {
23
+		db = db.Where("c.created_time>=?", startTime)
24
+	}
25
+	if isEndTime {
26
+		db = db.Where("c.created_time<=?", endTime)
27
+	}
28
+	if len(searchKey) > 0 {
29
+		searchKey = "%" + searchKey + "%"
30
+		db = db.Where("c.name LIKE ? OR c.mobile LIKE ? ", searchKey, searchKey)
31
+	}
32
+	if level > 0 {
33
+		db = db.Joins("JOIN sgj_user_user_card as uc ON uc.customer_id = c.id and uc.user_org_id = ? and uc.status=1 and uc.card_id=? ", orgID, level)
34
+	}
35
+	if tag > 0 {
36
+		db = db.Joins("JOIN sgj_user_tag_links as ut ON ut.user_link_id = c.id and ut.user_org_id = ? and ut.status=1 and ut.tag_id=? ", orgID, tag)
37
+	}
38
+
39
+	offset := (page - 1) * limit
40
+	err = db.Count(&total).Order("c.created_time desc").Offset(offset).Limit(limit).
41
+		Preload("Tags", func(db *gorm.DB) *gorm.DB {
42
+			return db.Where("sgj_user_tag_links.user_org_id=? and sgj_user_tags.user_org_id=? and sgj_user_tags.status=1 and sgj_user_tag_links.status=1", orgID, orgID).Order("sgj_user_tag_links.id desc")
43
+		}).
44
+		Preload("UserCard", func(db *gorm.DB) *gorm.DB {
45
+			return db.Where("user_org_id=? and status=1", orgID)
46
+		}).
47
+		Preload("UserCard.Card", "user_org_id=? and status=1", orgID).
48
+		Preload("Illness", "user_org_id=? and status=1", orgID).
49
+		Select("c.id, c.user_org_id, c.user_id, c.mobile, c.name, c.gender, c.province_id, c.city_id, c.address, c.birthday, c.treat_type, c.relationship, c.illness_id, c.wechat_openid, c.membership, c.sources, c.status, c.created_time, c.updated_time, c.avatar, c.wechat_unionid, c.remark, c.medical_diagnose, c.yz_uid, c.ill_date, c.district_id").Find(&members).Error
50
+	if err != nil {
51
+		return
52
+	}
53
+	if len(members) > 0 {
54
+		for _, member := range members {
55
+			member.Avatar = strings.Replace(member.Avatar, "http://7xkofe.com1.z0.glb.clouddn.com", "https://images.shengws.com", 1)
56
+		}
57
+	}
58
+
59
+	return
60
+}
61
+
62
+func GetCustomerByMobile(orgID int64, mobile string) (*models.UserCustomer, error) {
63
+	var customer models.UserCustomer
64
+	var err error
65
+	err = service.UserReadDB().Where("user_org_id=? and mobile=? and status=1", orgID, mobile).Find(&customer).Error
66
+	if err == gorm.ErrRecordNotFound {
67
+		return nil, nil
68
+	}
69
+	if err != nil {
70
+		return nil, err
71
+	}
72
+	return &customer, nil
73
+}
74
+
75
+func GetUserByMobile(mobile string) (*models.User, error) {
76
+	var user models.User
77
+	var err error
78
+	err = service.UserReadDB().Where("mobile=?", mobile).Find(&user).Error
79
+	if err == gorm.ErrRecordNotFound {
80
+		return nil, nil
81
+	}
82
+	if err != nil {
83
+		return nil, err
84
+	}
85
+	return &user, nil
86
+}
87
+
88
+func GetOnlyMemberByID(orgID, id int64) (*Members, error) {
89
+	var member Members
90
+	var err error
91
+	err = service.UserReadDB().Where("id =? and user_org_id=? and status=1", id, orgID).Find(&member).Error
92
+	if err == gorm.ErrRecordNotFound {
93
+		return nil, nil
94
+	}
95
+	if err != nil {
96
+		return nil, err
97
+	}
98
+	return &member, nil
99
+}
100
+
101
+func CreateMember(member *Members) (err error) {
102
+	err = service.UserWriteDB().Create(member).Error
103
+	return
104
+}
105
+
106
+func EditMember(member *Members) (err error) {
107
+	err = service.UserWriteDB().Save(member).Error
108
+	return
109
+}
110
+
111
+func CreateMemberWithUser(member *Members, user *models.User) (err error) {
112
+	tx := service.UserWriteDB().Begin()
113
+	err = tx.Create(user).Error
114
+	if err != nil {
115
+		tx.Rollback()
116
+		return
117
+	}
118
+	member.UserId = user.ID
119
+	err = tx.Create(member).Error
120
+	if err != nil {
121
+		tx.Rollback()
122
+		return
123
+	}
124
+
125
+	tx.Commit()
126
+
127
+	return
128
+}
129
+
130
+func DeleteMembers(orgID int64, ids []int64) (err error) {
131
+	if len(ids) == 1 {
132
+		err = service.UserWriteDB().Model(&models.UserCustomer{}).Where("id =? and user_org_id =?", ids[0], orgID).Update(map[string]interface{}{"Status": 0, "UpdatedTime": time.Now().Unix()}).Error
133
+	} else {
134
+		err = service.UserWriteDB().Model(&models.UserCustomer{}).Where("id IN (?) and user_org_id =?", ids, orgID).Update(map[string]interface{}{"Status": 0, "UpdatedTime": time.Now().Unix()}).Error
135
+	}
136
+	return
137
+}
138
+
139
+func FindCustomerInfoByOpenid(orgID int64, openid string) (*models.UserCustomer, error) {
140
+	var cusotmer models.UserCustomer
141
+	err := service.UserReadDB().Where("user_org_id = ? and wechat_openid =? and status=1", orgID, openid).First(&cusotmer).Error
142
+	if err == gorm.ErrRecordNotFound {
143
+		return nil, nil
144
+	}
145
+	if err != nil {
146
+		return nil, err
147
+	}
148
+	return &cusotmer, nil
149
+}
150
+
151
+// 获取所有有手机号的客户(仅取部分信息!)
152
+func GetAllCustomersWithMobile(orgUserID int64) ([]*models.UserCustomer, error) {
153
+	var customer []*models.UserCustomer
154
+	err := service.UserReadDB().Table("sgj_user_customer AS uc").
155
+		Where("uc.user_org_id = ? AND uc.status=1 and uc.mobile <>'' ", orgUserID).
156
+		Select("uc.id, uc.name, uc.mobile").
157
+		Scan(&customer).
158
+		Error
159
+	return customer, err
160
+}
161
+
162
+// 获取指定标签下有手机号的客户(仅取部分信息!)
163
+func GetTagCustomersWithMobileByTagIDs(orgID int64, tagIDs []string) ([]*models.UserCustomer, error) {
164
+	var customer []*models.UserCustomer
165
+	err := service.UserReadDB().Table("sgj_user_customer AS uc").
166
+		Joins("JOIN sgj_user_tag_links AS tl on uc.id = tl.user_link_id").
167
+		Where("tl.tag_id IN (?) and tl.status = 1 and uc.user_org_id = ? and uc.status=1 and uc.mobile <>'' ", tagIDs, orgID).
168
+		Group("uc.id").
169
+		Select("uc.id, uc.name, uc.mobile").
170
+		Scan(&customer).
171
+		Error
172
+	return customer, err
173
+}
174
+
175
+// 获取指定客户ID的且有手机号的客户(仅取部分信息!)
176
+func GetSpecificCustomersWithMobile(orgID int64, customerIDs []string) ([]*models.UserCustomer, error) {
177
+	var customer []*models.UserCustomer
178
+	err := service.UserReadDB().Table("sgj_user_customer AS uc").
179
+		Where("uc.user_org_id = ? AND uc.status=1 and uc.mobile <>'' and id in (?)", orgID, customerIDs).
180
+		Select("uc.id, uc.name, uc.mobile").
181
+		Scan(&customer).
182
+		Error
183
+	return customer, err
184
+}
185
+
186
+func GetAllMemberList(orgID int64) (members []*Members, err error) {
187
+	db := service.UserReadDB().Table("sgj_user_customer as c").Where("c.user_org_id=? and c.status=1", orgID)
188
+
189
+	err = db.Order("c.created_time desc").
190
+		Select("c.id, c.user_org_id, c.user_id, c.mobile, c.name, c.gender, c.province_id, c.city_id, c.address, c.birthday, c.treat_type, c.relationship, c.illness_id, c.wechat_openid, c.membership, c.sources, c.status, c.created_time, c.updated_time, c.avatar, c.wechat_unionid, c.remark, c.medical_diagnose, c.yz_uid, c.ill_date, c.district_id").Find(&members).Error
191
+	fmt.Println("错误是什么", err)
192
+	if err != nil {
193
+		return
194
+	}
195
+	if len(members) > 0 {
196
+		for _, member := range members {
197
+			member.Avatar = strings.Replace(member.Avatar, "http://7xkofe.com1.z0.glb.clouddn.com", "https://images.shengws.com", 1)
198
+		}
199
+	}
200
+	return
201
+}

+ 56 - 0
service/member_service/models.go View File

@@ -0,0 +1,56 @@
1
+package member_service
2
+
3
+import (
4
+	"SCRM/models"
5
+)
6
+
7
+type Members struct {
8
+	models.UserCustomer
9
+
10
+	Tags     []*models.UserTags     `gorm:"many2many:sgj_user_tag_links;association_jointable_foreignkey:tag_id;jointable_foreignkey:user_link_id;" json:"tags"`
11
+	UserCard *UserCard              `gorm:"foreignkey:customer_id" json:"user_card"`
12
+	Illness  []*CustomerIllness     `gorm:"foreignkey:customer_id" json:"illness"`
13
+	UserTags []*models.UserTagLinks `gorm:"foreignkey:user_link_id" json:"user_tags"`
14
+}
15
+
16
+func (Members) TableName() string {
17
+	return "sgj_user_customer"
18
+}
19
+
20
+type UserCard struct {
21
+	models.UserCard
22
+
23
+	Card *models.UserMembershipCard `gorm:"ForeignKey:CardId" json:"card"`
24
+}
25
+
26
+func (UserCard) TableName() string {
27
+	return "sgj_user_user_card"
28
+}
29
+
30
+type CustomerIllness struct {
31
+	models.CustomerIllness
32
+}
33
+
34
+func (CustomerIllness) TableName() string {
35
+	return "sgj_user_customer_illness"
36
+}
37
+
38
+type Tags struct {
39
+	models.UserTags
40
+
41
+	MemberCount int64 `json:"member_count"`
42
+}
43
+
44
+func (Tags) TableName() string {
45
+	return "sgj_user_tags"
46
+}
47
+
48
+type TagsMemberCount struct {
49
+	MemberCount int64 `gorm:"member_count"`
50
+	TagID       int64 `gorm:"tag_id"`
51
+}
52
+
53
+type CardsMemberCount struct {
54
+	MemberCount int64 `gorm:"member_count"`
55
+	CardID      int64 `gorm:"card_id"`
56
+}

+ 184 - 0
service/member_service/tags_service.go View File

@@ -0,0 +1,184 @@
1
+package member_service
2
+
3
+import (
4
+	"SCRM/models"
5
+	"SCRM/service"
6
+	"errors"
7
+	"strings"
8
+	"time"
9
+
10
+	"github.com/jinzhu/gorm"
11
+)
12
+
13
+func GetTagList(orgID int64) (tags []*models.UserTags, err error) {
14
+	err = service.UserReadDB().Model(&models.UserTags{}).Where("user_org_id=? and status=1", orgID).Order("id asc").Find(&tags).Error
15
+
16
+	return
17
+}
18
+
19
+//GetMemberAllTags 取所有(包括已经软删除的记录)
20
+func GetMemberAllTags(orgID, customerID int64) (tags []*models.UserTagLinks, err error) {
21
+	err = service.UserReadDB().Where("user_org_id = ? and user_link_id =? ", orgID, customerID).Find(&tags).Error
22
+	return
23
+}
24
+
25
+//GetMembersAllTags 取所有(包括已经软删除的记录)
26
+func GetMembersAllTags(orgID int64, customerIDs []int64) (tags []*models.UserTagLinks, err error) {
27
+	err = service.UserReadDB().Where("user_org_id = ? and user_link_id in (?) ", orgID, customerIDs).Find(&tags).Error
28
+	return
29
+}
30
+
31
+//DeleteMemeberAllTags 删除会员所有标签
32
+func DeleteMemeberAllTags(orgID, customerID int64) (err error) {
33
+	err = service.UserWriteDB().Model(&models.UserTagLinks{}).Where("user_org_id = ? and user_link_id =? ", orgID, customerID).Update(map[string]interface{}{"Status": 0, "UpdatedTime": time.Now().Unix()}).Error
34
+	return
35
+}
36
+
37
+func SaveMemberTags(tags []*models.UserTagLinks) (err error) {
38
+	if len(tags) == 0 {
39
+		err = errors.New("NotRecordToUpdate")
40
+		return
41
+	}
42
+
43
+	insertSql := "INSERT INTO sgj_user_tag_links (tag_id, user_link_id, status, created_time, updated_time, user_org_id) VALUES "
44
+	insertParams := make([]string, 0)
45
+	insertData := make([]interface{}, 0)
46
+	updateIds := make([]int64, 0)
47
+	deleteIds := make([]int64, 0)
48
+	for _, tag := range tags {
49
+		if tag.ID == 0 {
50
+			insertParams = append(insertParams, "(?,?,?,?,?,?)")
51
+			insertData = append(insertData, tag.TagId)
52
+			insertData = append(insertData, tag.UserLinkId)
53
+			insertData = append(insertData, tag.Status)
54
+			insertData = append(insertData, tag.CreatedTime)
55
+			insertData = append(insertData, tag.UpdatedTime)
56
+			insertData = append(insertData, tag.UserOrgId)
57
+		} else {
58
+			if tag.Status == 1 {
59
+				updateIds = append(updateIds, tag.ID)
60
+			} else {
61
+				deleteIds = append(deleteIds, tag.ID)
62
+			}
63
+		}
64
+	}
65
+
66
+	tx := service.UserWriteDB().Begin()
67
+	if len(insertParams) > 0 {
68
+		insertSql += strings.Join(insertParams, ", ")
69
+		err = tx.Exec(insertSql, insertData...).Error
70
+		if err != nil {
71
+			tx.Rollback()
72
+			return
73
+		}
74
+	}
75
+
76
+	if len(updateIds) > 0 {
77
+		err = service.UserWriteDB().Model(&models.UserTagLinks{}).Where("id IN (?)", updateIds).Update(map[string]interface{}{"Status": 1, "UpdatedTime": time.Now().Unix()}).Error
78
+		if err != nil {
79
+			tx.Rollback()
80
+			return
81
+		}
82
+	}
83
+	if len(deleteIds) > 0 {
84
+		err = service.UserWriteDB().Model(&models.UserTagLinks{}).Where("id IN (?)", deleteIds).Update(map[string]interface{}{"Status": 0, "UpdatedTime": time.Now().Unix()}).Error
85
+		if err != nil {
86
+			tx.Rollback()
87
+			return
88
+		}
89
+	}
90
+
91
+	tx.Commit()
92
+	return
93
+}
94
+
95
+func GetPageTagList(orgID, page, limit int64, search string) (tags []*Tags, total int64, err error) {
96
+	db := service.UserReadDB().Model(&models.UserTags{}).Where("user_org_id=? and status=1", orgID)
97
+
98
+	if len(search) > 0 {
99
+		searchKey := "%" + search + "%"
100
+		db = db.Where("tag_name LIKE ?", searchKey)
101
+	}
102
+	offset := (page - 1) * limit
103
+
104
+	err = db.Count(&total).Order("id desc").Offset(offset).Limit(limit).Find(&tags).Error
105
+
106
+	if len(tags) > 0 {
107
+		var tmcs []*TagsMemberCount
108
+		tagIDs := make([]int64, 0)
109
+		for _, tag := range tags {
110
+			tagIDs = append(tagIDs, tag.ID)
111
+		}
112
+		err = service.UserReadDB().Table("sgj_user_tag_links as utl").Joins("JOIN sgj_user_tags AS ut ON ut.id=utl.tag_id and utl.user_org_id=? and ut.user_org_id=?", orgID, orgID).Select("utl.tag_id, COUNT(utl.tag_id) AS member_count").Where("utl.tag_id IN (?)", tagIDs).Group("utl.tag_id").Scan(&tmcs).Error
113
+		if err != nil {
114
+			return
115
+		}
116
+		if len(tmcs) > 0 {
117
+			tmcsMap := make(map[int64]int64, 0)
118
+			for _, tmc := range tmcs {
119
+				tmcsMap[tmc.TagID] = tmc.MemberCount
120
+			}
121
+
122
+			for index, tag := range tags {
123
+				if _, exist := tmcsMap[tag.ID]; exist {
124
+					tags[index].MemberCount = tmcsMap[tag.ID]
125
+				}
126
+			}
127
+
128
+		}
129
+
130
+	}
131
+	return
132
+}
133
+
134
+func FindTagByName(orgID int64, name string) (*models.UserTags, error) {
135
+	var tag models.UserTags
136
+	var err error
137
+	err = service.UserReadDB().Model(&models.UserTags{}).Where("tag_name=? and user_org_id=? and status=1", name, orgID).First(&tag).Error
138
+	if err == gorm.ErrRecordNotFound {
139
+		return nil, nil
140
+	}
141
+	if err != nil {
142
+		return nil, err
143
+	}
144
+	return &tag, nil
145
+}
146
+
147
+func SaveTag(tag *models.UserTags) (err error) {
148
+	err = service.UserWriteDB().Save(tag).Error
149
+	return
150
+}
151
+
152
+func FindOnlyTagByID(orgID, id int64) (*models.UserTags, error) {
153
+	var tag models.UserTags
154
+	var err error
155
+	err = service.UserReadDB().Model(&models.UserTags{}).Where("id=? and user_org_id=? and status=1", id, orgID).First(&tag).Error
156
+	if err == gorm.ErrRecordNotFound {
157
+		return nil, nil
158
+	}
159
+	if err != nil {
160
+		return nil, err
161
+	}
162
+	return &tag, nil
163
+}
164
+
165
+func DeleteTags(orgID int64, ids []int64) (err error) {
166
+	if len(ids) == 1 {
167
+		err = service.UserWriteDB().Model(&models.UserTags{}).Where("id =? and user_org_id =?", ids[0], orgID).Update(map[string]interface{}{"Status": 0, "UpdatedTime": time.Now().Unix()}).Error
168
+	} else {
169
+		err = service.UserWriteDB().Model(&models.UserTags{}).Where("id IN (?) and user_org_id =?", ids, orgID).Update(map[string]interface{}{"Status": 0, "UpdatedTime": time.Now().Unix()}).Error
170
+	}
171
+	return
172
+}
173
+
174
+// 获取 tag ids 下有手机号的客户的数量
175
+func GetTagUsersCountWithMobileByTagIDs(tagIDs []string) (int, error) {
176
+	var count int
177
+	err := service.UserReadDB().Table("sgj_user_customer AS uc").
178
+		Joins("JOIN sgj_user_tag_links AS tl on uc.id = tl.user_link_id").
179
+		Where("tl.tag_id IN (?) and tl.status = 1 and uc.status=1 and uc.mobile <>'' ", tagIDs).
180
+		Group("uc.id").
181
+		Count(&count).
182
+		Error
183
+	return count, err
184
+}

+ 179 - 0
service/micro_service/micro_service.go View File

@@ -0,0 +1,179 @@
1
+package micro_service
2
+
3
+import (
4
+	"SCRM/models"
5
+	"SCRM/service"
6
+	"fmt"
7
+	"github.com/jinzhu/gorm"
8
+)
9
+
10
+func GetData(orgid int64) (model []*models.SgjPatientModel, err error) {
11
+	db := service.PatientReadDB().Table("sgj_patient_model as m").Where(" m.status = ?", 1)
12
+	dbs := service.PatientReadDB().Table("sgj_patient_editpiclink as s")
13
+	fmt.Println("db是什么?", db)
14
+
15
+	if orgid > 0 {
16
+		db = db.Where("user_org_id = ? ", orgid)
17
+	}
18
+	err = db.Preload("Hospitals").Preload("Offices").Preload("OfficeEnviroment").
19
+		Preload("Editdoctor").Preload("Editmargin").Preload("Enviroimages").Preload("PatientEditpiclink", func(db *gorm.DB) *gorm.DB {
20
+		return dbs.Select("s.id,s.images,s.sort,s.piclink,s.linkaddress,s.user_org_id,s.status,s.ctime,s.mtime,s.modeid,s.img_show,s.linkid").Order("sort")
21
+	}).Select("m.id,m.title,m.sort,m.ctime,m.mtime,m.user_org_id,m.status,m.mode_type").Order("sort").Find(&model).Error
22
+	return
23
+}
24
+
25
+func GetArticlelist(orgid int64) (models.SgjPatientArticlelist, error) {
26
+	articlelist := models.SgjPatientArticlelist{}
27
+	err := service.PatientReadDB().Where("user_org_id = ? AND Status = ?", orgid, 1).Last(&articlelist).Error
28
+	fmt.Println("错误", err)
29
+	return articlelist, err
30
+}
31
+
32
+//func GetArticlelistlimit(orgid int64)(models.SgjPatientArticlelist,error)  {
33
+//	articlelist := models.SgjPatientArticlelist{}
34
+//	service.PatientReadDB().Model(&articlelist).Where("")
35
+//}
36
+
37
+func GetlastLimit(orgid int64) (models.SgjPatientArticlelist, error) {
38
+	articlelist := models.SgjPatientArticlelist{}
39
+	err := service.PatientReadDB().Model(&articlelist).Where("user_org_id = ? AND status = ?", orgid, 1).Last(&articlelist).Error
40
+	return articlelist, err
41
+}
42
+
43
+func GetAllArticeList(orgid int64, limit int64) (articles []models.Articles, err error) {
44
+	err = service.PatientReadDB().Model(&articles).Where("user_org_id = ? AND status = ? AND article_status = ?", orgid, 1, 1).Limit(limit).Order("ctime desc").Find(&articles).Error
45
+	return articles, err
46
+}
47
+
48
+func GetActivitiesById(orgid int64) (models.SgjPatientAddactivity, error) {
49
+	addactivity := models.SgjPatientAddactivity{}
50
+	err := service.PatientReadDB().Where("user_org_id = ? AND status = ?", orgid, 1).Last(&addactivity).Error
51
+	fmt.Println("查询活动列表错误", err)
52
+	return addactivity, err
53
+}
54
+
55
+func GetLastActivitiesLast(orgid int64) (models.SgjPatientAddactivity, error) {
56
+	addactivity := models.SgjPatientAddactivity{}
57
+	err := service.PatientReadDB().Model(&addactivity).Where("user_org_id = ? AND status = ?", orgid, 1).Last(&addactivity).Error
58
+	return addactivity, err
59
+}
60
+
61
+func GetAllActivities(orgid int64, limit int64) (activity []models.Activity, err error) {
62
+	err = service.PatientReadDB().Model(activity).Where("user_org_id = ? AND status = ?", orgid, 1).Limit(limit).Find(&activity).Error
63
+	return
64
+}
65
+
66
+func GetAllActivitiestwo(orgid int64) (activity []models.Activity, err error) {
67
+	err = service.PatientReadDB().Model(activity).Where("user_org_id = ? AND status = ?", orgid, 1).Order("ctime desc").Find(&activity).Error
68
+	return activity, err
69
+}
70
+
71
+func QueryHispitalDetail(orgid int64, id int64) (models.SgjPatientHospital, error) {
72
+	hospital := models.SgjPatientHospital{}
73
+	err := service.PatientReadDB().Model(&hospital).Where("user_org_id = ?  AND modleid = ? AND status = ?", orgid, id, 1).Find(&hospital).Error
74
+	return hospital, err
75
+}
76
+
77
+func GetOfficeDetail(orgid int64, id int64) (models.SgjPatientOffices, error) {
78
+	offices := models.SgjPatientOffices{}
79
+	err := service.PatientReadDB().Model(&offices).Where("user_org_id = ? AND modleid = ? AND status = ?", orgid, id, 1).Find(&offices).Error
80
+	return offices, err
81
+}
82
+
83
+func GetDoctorDetail(orgid int64, id int64) (editdoctor []*models.SgjPatientEditdoctor, err error) {
84
+	err = service.PatientReadDB().Model(&editdoctor).Where("user_org_id = ? AND modleid = ? AND status = ?", orgid, id, 1).Order("doc_sort").Find(&editdoctor).Error
85
+	return
86
+}
87
+
88
+func GetOfficEnviromentDetail(orgid int64, id int64) (offenvironment []models.SgjPatientEnviroimages, err error) {
89
+	err = service.PatientReadDB().Model(&offenvironment).Where("user_org_id = ? AND modeid = ? AND status = ?", orgid, id, 1).Order("sort").Find(&offenvironment).Error
90
+	return offenvironment, err
91
+}
92
+func GetArticlelistById(modeid int64, orgID int64) (models.SgjPatientArticlelist, error) {
93
+	articlelist := models.SgjPatientArticlelist{}
94
+	err := service.PatientReadDB().Model(articlelist).Where("modeid = ? AND user_org_id = ? AND Status = ?", modeid, orgID, 1).Find(&articlelist).Error
95
+	return articlelist, err
96
+}
97
+
98
+func GetAllArticles(orgid int64, limit int64) (articlelist []models.Articles, err error) {
99
+	err = service.PatientReadDB().Model(articlelist).Where("user_org_id = ? AND Status = ?", orgid, 1).Limit(limit).Find(&articlelist).Error
100
+	return
101
+}
102
+
103
+func GetAllPushArticles(orgid int64) (articleslist []models.Articles, err error) {
104
+
105
+	err = service.PatientReadDB().Model(articleslist).Where("user_org_id = ? AND article_status = ? AND status = ?", orgid, 1, 1).Order("ctime desc").Find(&articleslist).Error
106
+	return
107
+}
108
+
109
+func GetAllActivitiById(modeid int64, orgID int64) (models.SgjPatientAddactivity, error) {
110
+	addactivity := models.SgjPatientAddactivity{}
111
+	err := service.PatientReadDB().Model(addactivity).Where("modeid = ? AND user_org_id = ? AND Status = ?", modeid, orgID, 1).Find(&addactivity).Error
112
+	return addactivity, err
113
+}
114
+
115
+func GetDefalutNavigationData(orgid int64) (navigation []models.SgjPatientNavigation, err error) {
116
+	err = service.PatientReadDB().Where("user_org_id = ? AND status = ?", orgid, 1).Find(&navigation).Error
117
+	return navigation, err
118
+}
119
+func GetOrederModel(orgid int64) (model []*models.SgjPatientOrdmodel, err error) {
120
+	db := service.PatientReadDB().Table("sgj_patient_ordmodel as o").Where("o.status = ?", 1)
121
+	if orgid > 0 {
122
+		db = db.Where("user_org_id = ?", orgid)
123
+	}
124
+	err = db.Preload("Hosaddress").Preload("Connectway").Preload("Worktime").Preload("Rideway").Preload("Oldration").Preload("Conrotation").
125
+		Select("o.id,o.title,o.sort,o.ctime,o.mtime,o.mode_type").Order("sort").Find(&model).Error
126
+	fmt.Println("sql错误是什么", err)
127
+	return
128
+
129
+}
130
+
131
+func GetAllConnecway(orgid int64) (connect []models.SgjPatientConnection, err error) {
132
+	err = service.PatientReadDB().Model(&connect).Where("user_org_id = ? AND status = ?", orgid, 1).Find(&connect).Error
133
+	return
134
+}
135
+
136
+func GetActivitDetail(id int64, orgid int64) (models.Activity, error) {
137
+	activity := models.Activity{}
138
+	err := service.PatientReadDB().Model(&activity).Where(" id = ? AND user_org_id = ?", id, orgid).Find(&activity).Error
139
+	return activity, err
140
+}
141
+
142
+func GetArticlesDetail(id int64, orgid int64) (models.Articles, error) {
143
+	articles := models.Articles{}
144
+	err := service.PatientReadDB().Model(&articles).Where("id = ? AND user_org_id = ?", id, orgid).Find(&articles).Error
145
+	return articles, err
146
+}
147
+
148
+//func GetDoctorInfo(id int64,orgid int64)(models.SgjPatientEditdoctor,error)  {
149
+//	editdoctor := models.SgjPatientEditdoctor{}
150
+//	err := service.PatientReadDB().Model(&editdoctor).Where("id = ? AND user_org_id = ?", id, orgid).Find(&editdoctor).Error
151
+//	return editdoctor,err
152
+//}
153
+func GetDoctorInfo(id int64, orgid int64) (models.SgjUserStaffInfo, error) {
154
+	info := models.SgjUserStaffInfo{}
155
+	err := service.UserReadDB().Model(&info).Where("id = ? AND user_org_id = ?", id, orgid).Find(&info).Error
156
+	return info, err
157
+}
158
+
159
+func GetRotationLinkAddress(orgid int64, linkid int64) (models.SgjPatientLinkaddress, error) {
160
+	linkaddress := models.SgjPatientLinkaddress{}
161
+	err := service.PatientReadDB().Model(&linkaddress).Where("user_org_id = ? AND id = ? AND status = ?", orgid, linkid, 1).Find(&linkaddress).Error
162
+	return linkaddress, err
163
+}
164
+
165
+func GetNavigationLinkAddressById(id int64, orgid int64) (models.SgjPatientEditmargin, error) {
166
+	editmargin := models.SgjPatientEditmargin{}
167
+	err := service.PatientReadDB().Model(&editmargin).Where("id=? and user_org_id = ?", id, orgid).Find(&editmargin).Error
168
+	return editmargin, err
169
+}
170
+
171
+func GetEnviromentImages(mid int64, orgid int64) (enviro []models.SgjPatientEnviroimages, err error) {
172
+	err = service.PatientReadDB().Model(&enviro).Where(" modeid = ? AND user_org_id = ?", mid, orgid).Find(&enviro).Error
173
+	return
174
+}
175
+
176
+func GetAllDoctors(orgid int64) (staff []models.SgjUserStaffInfo, err error) {
177
+	err = service.UserReadDB().Model(&staff).Where("user_org_id = ? AND status = ? AND user_type <> ? AND user_title <> ? AND user_title <> ?", orgid, 1, 3, 12, 13).Find(&staff).Error
178
+	return staff, err
179
+}

+ 14 - 0
service/org_service/org_fans_service.go View File

@@ -0,0 +1,14 @@
1
+package org_service
2
+
3
+import (
4
+	"SCRM/models"
5
+	"SCRM/service"
6
+	"time"
7
+)
8
+
9
+func SetFansUnsubscribe(orgID int64, openid string) (err error) {
10
+
11
+	err = service.UserWriteDB().Model(&models.OrgFans{}).Where("user_org_id=? and openid=?", orgID, openid).Update(map[string]interface{}{"UpdatedTime": time.Now().Unix(), "Status": 2}).Error
12
+	return
13
+
14
+}

+ 14 - 0
service/org_service/org_info_models.go View File

@@ -0,0 +1,14 @@
1
+package org_service
2
+
3
+import (
4
+	"SCRM/models"
5
+)
6
+
7
+type Org struct {
8
+	models.Org
9
+	OrgGallery []*models.OrgGallery `gorm:"ForeignKey:OrgId" json:"org_gallery"`
10
+}
11
+
12
+func (Org) TableName() string {
13
+	return "sgj_user_org"
14
+}

+ 32 - 0
service/org_service/org_info_service.go View File

@@ -0,0 +1,32 @@
1
+package org_service
2
+
3
+import (
4
+	"SCRM/models"
5
+	"SCRM/service"
6
+	"time"
7
+)
8
+
9
+func GetOrgTypes() (ots []*models.OrgType, err error) {
10
+	err = service.UserReadDB().Model(&models.OrgType{}).Where("status=1").Order("sort_no").Find(&ots).Error
11
+	return
12
+}
13
+
14
+func UpdateOrgInfo(org *Org) (err error) {
15
+	err = service.UserWriteDB().Model(&models.Org{}).Where("id=?", org.Id).Update(org).Error
16
+	return
17
+}
18
+
19
+func GetIllnessList() (ills []*models.Illness, err error) {
20
+	err = service.UserReadDB().Where("status=1").Find(&ills).Error
21
+	return
22
+}
23
+
24
+func CreateOrgGalleryItem(item *models.OrgGallery) (err error) {
25
+	err = service.UserWriteDB().Create(item).Error
26
+	return
27
+}
28
+
29
+func DeleteOrgGalleryItem(id int64) (err error) {
30
+	err = service.UserWriteDB().Model(&models.OrgGallery{}).Where("id=?", id).Update(map[string]interface{}{"Status": 0, "Mtime": time.Now().Unix()}).Error
31
+	return
32
+}

+ 29 - 0
service/org_service/subscibe_service.go View File

@@ -0,0 +1,29 @@
1
+package org_service
2
+
3
+import (
4
+	"SCRM/models"
5
+	"errors"
6
+	"time"
7
+)
8
+
9
+func GetOrgSubscibeState(subscibe *models.ServeSubscibe) (err error) {
10
+	if subscibe == nil {
11
+		err = errors.New("没有订阅信息")
12
+		return
13
+	}
14
+
15
+	//免费试用版2,永久免费版9 不过期
16
+	if subscibe.State == 9 || subscibe.State == 2 {
17
+		return
18
+	}
19
+
20
+	timeNow := time.Now().Unix()
21
+	if timeNow < subscibe.PeriodStart || timeNow > subscibe.PeriodEnd {
22
+		subscibe.State = 3
23
+	}
24
+	if subscibe.State != 1 && subscibe.State != 8 {
25
+		subscibe.State = 3
26
+	}
27
+	return
28
+
29
+}

+ 21 - 0
service/redis.go View File

@@ -0,0 +1,21 @@
1
+package service
2
+
3
+import (
4
+	"fmt"
5
+
6
+	"github.com/astaxie/beego"
7
+	"github.com/go-redis/redis"
8
+)
9
+
10
+func RedisClient() *redis.Client {
11
+	address := fmt.Sprintf("%s:%s", beego.AppConfig.String("redishost"), beego.AppConfig.String("redisport"))
12
+	client := redis.NewClient(&redis.Options{
13
+		Addr:     address,
14
+		Password: beego.AppConfig.String("redispasswrod"), // no password set
15
+		DB:       0,                                       // use default DB
16
+	})
17
+
18
+	pong, err := client.Ping().Result()
19
+	fmt.Println(pong, err)
20
+	return client
21
+}

+ 407 - 0
service/role_service/role_service.go View File

@@ -0,0 +1,407 @@
1
+package role_service
2
+
3
+import (
4
+	"time"
5
+
6
+	"SCRM/models"
7
+	"SCRM/service"
8
+	"SCRM/utils"
9
+
10
+	"github.com/jinzhu/gorm"
11
+)
12
+
13
+func GetRoles(orgID int64, appID int64, page int, count int) ([]*models.Role, int, error) {
14
+	var roles []*models.Role
15
+	var totalCount int
16
+	err := service.UserReadDB().Model(&models.Role{}).
17
+		Where("org_id = ? AND app_id = ?", orgID, appID).
18
+		Count(&totalCount).
19
+		Order("ctime asc").Limit(count).Offset((page - 1) * count).
20
+		Find(&roles).
21
+		Error
22
+	if err != nil {
23
+		if err == gorm.ErrRecordNotFound {
24
+			return make([]*models.Role, 0), 0, nil
25
+		} else {
26
+			return nil, 0, err
27
+		}
28
+	}
29
+	return roles, totalCount, nil
30
+}
31
+
32
+func GetAppRole(orgID int64, appID int64, adminUserID int64) (*models.App_Role, error) {
33
+	var appRole models.App_Role
34
+	err := service.UserReadDB().Model(models.App_Role{}).Where("org_id = ? and app_id = ? and admin_user_id = ?", orgID, appID, adminUserID).First(&appRole).Error
35
+	if err != nil {
36
+		if err == gorm.ErrRecordNotFound {
37
+			return nil, nil
38
+		} else {
39
+			return nil, err
40
+		}
41
+	}
42
+	return &appRole, nil
43
+}
44
+
45
+func CreateRole(adminUserID int64, orgID int64, appID int64, name string, intro string) (*models.Role, error) {
46
+	role := models.Role{
47
+		RoleName:     name,
48
+		RoleIntro:    intro,
49
+		Creator:      adminUserID,
50
+		OrgId:        orgID,
51
+		AppId:        appID,
52
+		IsSuperAdmin: false,
53
+		Status:       1,
54
+		CreateTime:   time.Now().Unix(),
55
+		ModifyTime:   time.Now().Unix(),
56
+	}
57
+	tx := service.UserWriteDB().Begin()
58
+	if err := tx.Create(&role).Error; err != nil {
59
+		tx.Rollback()
60
+		return nil, err
61
+	}
62
+	tx.Commit()
63
+	return &role, nil
64
+}
65
+
66
+func GetRoleByRoleID(roleID int64) (*models.Role, error) {
67
+	var role models.Role
68
+	err := service.UserReadDB().Model(&models.Role{}).Where("id = ?", roleID).First(&role).Error
69
+	if err != nil {
70
+		if err == gorm.ErrRecordNotFound {
71
+			return nil, nil
72
+		}
73
+		return nil, err
74
+	} else {
75
+		return &role, nil
76
+	}
77
+}
78
+
79
+func ModifyRole(role *models.Role) error {
80
+	tx := service.UserWriteDB().Begin()
81
+	if err := tx.Save(role).Error; err != nil {
82
+		tx.Rollback()
83
+		return err
84
+	}
85
+	return tx.Commit().Error
86
+}
87
+
88
+// 拥有xx角色的管理员的数量
89
+func RoleAdminUserCount(orgID int64, appID int64, roleID int64) (int, error) {
90
+	var count int
91
+	err := service.UserReadDB().Model(models.App_Role{}).
92
+		Where("org_id = ? AND app_id = ? AND role_id = ? AND status = 1", orgID, appID, roleID).
93
+		Count(&count).
94
+		Error
95
+	if err != nil {
96
+		return 0, err
97
+	} else {
98
+		return count, nil
99
+	}
100
+}
101
+
102
+type AdminUserManageViewModel struct {
103
+	AdminUserId int    `gorm:"admin_user_id" json:"user_id"`
104
+	UserName    string `gorm:"user_name" json:"user_name"`
105
+	RoleName    string `gorm:"role_name" json:"role_name"`
106
+	UserTitle   int    `gorm:"user_title" json:"user_title"`
107
+	Ip          string `gorm:"ip" json:"ip"`
108
+	Ctime       int64  `gorm:"ctime" json:"last_login_time"`
109
+	Status      int    `gorm:"status" json:"status"`
110
+
111
+	// LastLoginTimeStr string `gorm:"-" json:"last_login_time_formatted"`
112
+	TitleName string `gorm:"-" json:"title_name"`
113
+}
114
+
115
+func GetAdminUsersAndLoginInfo(orgID int64, appID int64, page int, count int) ([]*AdminUserManageViewModel, int, error) {
116
+	if count <= 0 {
117
+		return []*AdminUserManageViewModel{}, 0, nil
118
+	}
119
+	if page < 1 {
120
+		page = 1
121
+	}
122
+	var viewModels []*AdminUserManageViewModel = make([]*AdminUserManageViewModel, 0)
123
+	userReadDB := service.UserReadDB()
124
+	rows, err := userReadDB.Raw("SELECT u_a_r.admin_user_id, u_a_r.user_name, u_r.role_name, u_a_r.user_title, u_l.ip, u_l.ctime, u_a_r.status FROM sgj_user_admin_role AS u_a_r INNER JOIN sgj_user_role AS u_r ON u_a_r.org_id = u_r.org_id AND u_a_r.app_id = u_r.app_id AND u_r.id = u_a_r.role_id LEFT JOIN (SELECT * FROM (SELECT admin_user_id, org_id, app_id, ip, ctime FROM sgj_user_admin_login_log WHERE org_id = ? AND app_id = ? ORDER BY ctime DESC) AS t GROUP BY admin_user_id) AS u_l ON u_a_r.org_id = u_l.org_id AND u_a_r.app_id = u_l.app_id AND u_a_r.admin_user_id = u_l.admin_user_id WHERE u_a_r.org_id = ? AND u_a_r.app_id = ? GROUP BY u_a_r.admin_user_id LIMIT ? OFFSET ?;", orgID, appID, orgID, appID, count, (page-1)*count).Rows()
125
+	defer rows.Close()
126
+	if err != nil {
127
+		if err == gorm.ErrRecordNotFound {
128
+			return viewModels, 0, nil
129
+		} else {
130
+			return nil, 0, err
131
+		}
132
+	}
133
+	for rows.Next() {
134
+		var viewModel AdminUserManageViewModel
135
+		userReadDB.ScanRows(rows, &viewModel)
136
+		title, _ := models.UserTitle[viewModel.UserTitle]
137
+		viewModel.TitleName = title
138
+		// if viewModel.Ctime == 0 {
139
+		// 	viewModel.LastLoginTimeStr = ""
140
+		// } else {
141
+		// 	loginTime := time.Unix(viewModel.Ctime, 0)
142
+		// 	viewModel.LastLoginTimeStr = loginTime.Format("2006-01-02 15:04")
143
+		// }
144
+		viewModels = append(viewModels, &viewModel)
145
+	}
146
+	total := 0
147
+	userReadDB.Table("sgj_user_admin_role as u_a_r").Joins("join sgj_user_role as u_r on u_r.org_id = u_a_r.org_id AND u_r.app_id = u_a_r.app_id AND u_r.id = u_a_r.role_id").Where("u_a_r.org_id = ? AND u_a_r.app_id = ?", orgID, appID).Count(&total)
148
+	return viewModels, total, nil
149
+}
150
+
151
+func GetValidRoleCount(orgID int64, appID int64, superAdminUserID int64) (int, error) {
152
+	var count int
153
+	err := service.UserReadDB().Model(models.Role{}).
154
+		Where("org_id = ? AND app_id = ? AND creator = ? AND is_super_admin = 0 AND status = 1", orgID, appID, superAdminUserID).
155
+		Count(&count).
156
+		Error
157
+	if err != nil {
158
+		return 0, err
159
+	} else {
160
+		return count, nil
161
+	}
162
+}
163
+
164
+func GetAllValidRoles(orgID int64, appID int64) ([]*models.Role, error) {
165
+	var roles []*models.Role
166
+	err := service.UserReadDB().Model(models.Role{}).
167
+		Where("org_id = ? AND app_id = ? AND status = 1", orgID, appID).
168
+		Order("ctime asc").
169
+		Find(&roles).
170
+		Error
171
+	if err != nil {
172
+		if err == gorm.ErrRecordNotFound {
173
+			return make([]*models.Role, 0), nil
174
+		} else {
175
+			return nil, err
176
+		}
177
+	}
178
+	return roles, nil
179
+}
180
+
181
+func IsRoleExist(orgID int64, appID int64, roleID int64) (bool, error) {
182
+	var count int
183
+	err := service.UserReadDB().Model(models.Role{}).Where("org_id = ? AND app_id = ? AND id = ? AND status = 1", orgID, appID, roleID).Count(&count).Error
184
+	if err != nil {
185
+		return false, err
186
+	} else {
187
+		return count > 0, nil
188
+	}
189
+}
190
+
191
+type AdminUserEditViewModel struct {
192
+	AdminUserId int64  `gorm:"admin_user_id" json:"user_id"`
193
+	UserName    string `gorm:"user_name" json:"user_name"`
194
+	Mobile      string `gorm:"mobile" json:"mobile"`
195
+	UserType    int    `gorm:"user_type" json:"user_type"`
196
+	UserTitle   int    `gorm:"user_title" json:"user_title"`
197
+	Intro       string `gorm:"intro" json:"intro"`
198
+	RoleId      int64  `gorm:"role_id" json:"role_id"`
199
+}
200
+
201
+func GetGeneralAdminUser(orgID int64, appID int64, user_id int64) (*AdminUserEditViewModel, error) {
202
+	rows, err := service.UserReadDB().Raw("SELECT u_a.mobile, u_a_r.admin_user_id, u_a_r.user_name, u_a_r.user_type, u_a_r.user_title, u_a_r.intro, u_a_r.role_id FROM sgj_user_admin AS u_a, sgj_user_admin_role AS u_a_r WHERE u_a.id = u_a_r.admin_user_id AND u_a.id = ? AND u_a_r.status = 1 AND u_a_r.org_id = ? AND u_a_r.app_id = ?;", user_id, orgID, appID).Rows()
203
+	defer rows.Close()
204
+	if err != nil {
205
+		if err == gorm.ErrRecordNotFound {
206
+			return nil, nil
207
+		} else {
208
+			return nil, err
209
+		}
210
+	}
211
+	if rows.Next() {
212
+		var viewModel AdminUserEditViewModel
213
+		err := service.UserReadDB().ScanRows(rows, &viewModel)
214
+		if err != nil {
215
+			return nil, err
216
+		} else {
217
+			return &viewModel, nil
218
+		}
219
+	}
220
+	return nil, nil
221
+}
222
+
223
+func SaveAppRole(appRole *models.App_Role) error {
224
+	tx := service.UserWriteDB().Begin()
225
+	if err := tx.Model(&models.App_Role{}).Save(appRole).Error; err != nil {
226
+		tx.Rollback()
227
+		return err
228
+	}
229
+	return tx.Commit().Error
230
+}
231
+
232
+func IsMobileDidUsedAtApp(orgID int64, appID int64, mobile string) (bool, error) {
233
+	var count int
234
+	rows, err := service.UserReadDB().Raw("select count(u_a.id) as count from sgj_user_admin as u_a, sgj_user_admin_role as u_a_r where u_a_r.org_id = ? and u_a_r.app_id = ? and u_a.mobile = ? and u_a.id = u_a_r.admin_user_id;", orgID, appID, mobile).Rows()
235
+	defer rows.Close()
236
+	if err != nil {
237
+		if err == gorm.ErrRecordNotFound {
238
+			return false, nil
239
+		} else {
240
+			return true, err
241
+		}
242
+	}
243
+	if rows.Next() {
244
+		rows.Scan(&count)
245
+		return count > 0, nil
246
+	}
247
+	return true, nil
248
+}
249
+
250
+func IsUserSuperAdminWithMobile(mobile string) (bool, error) {
251
+	var user models.AdminUser
252
+	err := service.UserReadDB().Where("mobile = ?", mobile).First(&user).Error
253
+	if err != nil {
254
+		if err == gorm.ErrRecordNotFound {
255
+			return false, nil
256
+		} else {
257
+			return false, err
258
+		}
259
+	}
260
+	return user.IsSuperAdmin, nil
261
+}
262
+
263
+func CreateGeneralAdminUser(orgID int64, appID int64, mobile string, name string, userType int, userTitle int, intro string, roleID int64) (*models.AdminUser, string, error) {
264
+	now := time.Now().Unix()
265
+	tx := service.UserWriteDB().Begin()
266
+	var adminUser models.AdminUser
267
+	err := service.UserReadDB().Where("mobile = ? AND status = 1", mobile).First(&adminUser).Error
268
+	password := ""
269
+	if err != nil {
270
+		if err != gorm.ErrRecordNotFound {
271
+			return nil, "", err
272
+		} else {
273
+			password = utils.RandomNumberString(6)
274
+			adminUser.Mobile = mobile
275
+			adminUser.Password = utils.String2md5(password)
276
+			adminUser.IsSuperAdmin = false
277
+			adminUser.Status = 1
278
+			adminUser.CreateTime = now
279
+			adminUser.ModifyTime = now
280
+			if createErr := tx.Create(&adminUser).Error; createErr != nil {
281
+				tx.Rollback()
282
+				return nil, "", createErr
283
+			}
284
+		}
285
+	}
286
+	app_role := models.App_Role{
287
+		AdminUserId: adminUser.Id,
288
+		OrgId:       orgID,
289
+		AppId:       appID,
290
+		RoleId:      roleID,
291
+		Avatar:      "",
292
+		UserName:    name,
293
+		Intro:       intro,
294
+		UserType:    int8(userType),
295
+		UserTitle:   int8(userTitle),
296
+		Status:      1,
297
+		CreateTime:  now,
298
+		ModifyTime:  now,
299
+	}
300
+	if createApp_RoleErr := tx.Create(&app_role).Error; createApp_RoleErr != nil {
301
+		tx.Rollback()
302
+		return nil, "", createApp_RoleErr
303
+	}
304
+
305
+	tx.Commit()
306
+	return &adminUser, password, nil
307
+}
308
+
309
+type PurviewTreeViewModel struct {
310
+	ID     int64                   `json:"id"`
311
+	PID    int64                   `json:"pid"`
312
+	Name   string                  `json:"name"`
313
+	Childs []*PurviewTreeViewModel `json:"childs"`
314
+}
315
+
316
+func GetAllGeneralPurviewVMsProcessed() ([]*PurviewTreeViewModel, error) {
317
+	var originPurviews []*models.Purview
318
+	getPurviewErr := service.UserReadDB().Model(models.Purview{}).Where("module = 6 AND status = 1 AND super_admin_exclusive = 0").Order("listorder asc").Order("id asc").Find(&originPurviews).Error
319
+	if getPurviewErr != nil {
320
+		return nil, getPurviewErr
321
+	}
322
+	// 加工这些规则:树形化
323
+	purviewVMs := make([]*PurviewTreeViewModel, 0)
324
+	pid_childs := make(map[int64][]*PurviewTreeViewModel)
325
+	for _, purview := range originPurviews {
326
+		// warning:下面这个算法只适用最多两层树形结构的菜单,对于两层以上的会丢失掉第三层及其以下的节点
327
+		// 因为取出 originPurviews 的时候已经排过序了,所以顶级节点肯定最先处理,不需要担心子节点比父节点先处理
328
+		pvm := &PurviewTreeViewModel{
329
+			ID:   purview.Id,
330
+			PID:  purview.Parentid,
331
+			Name: purview.Name,
332
+		}
333
+		if purview.Parentid == 0 {
334
+			purviewVMs = append(purviewVMs, pvm)
335
+		} else {
336
+			childs := pid_childs[purview.Parentid]
337
+			if childs == nil {
338
+				childs = make([]*PurviewTreeViewModel, 0)
339
+			}
340
+			childs = append(childs, pvm)
341
+			pid_childs[purview.Parentid] = childs
342
+		}
343
+	}
344
+
345
+	for _, vm := range purviewVMs {
346
+		vm.Childs = pid_childs[vm.ID]
347
+	}
348
+
349
+	return purviewVMs, nil
350
+}
351
+
352
+func GetRolePurviewIds(roleID int64) (string, error) {
353
+	var rolePurview models.RolePurview
354
+	err := service.UserReadDB().Where("role_id = ?", roleID).First(&rolePurview).Error
355
+	if err != nil {
356
+		if err == gorm.ErrRecordNotFound {
357
+			return "", nil
358
+		} else {
359
+			return "", err
360
+		}
361
+	}
362
+	return rolePurview.PurviewIds, nil
363
+}
364
+
365
+func SaveRolePurviewIds(orgID int64, appID int64, roleID int64, purviewIds string) error {
366
+	var rolePurview models.RolePurview
367
+	getRPErr := service.UserReadDB().Where("org_id = ? AND app_id = ? AND role_id = ?", orgID, appID, roleID).First(&rolePurview).Error
368
+	if getRPErr != nil {
369
+		if getRPErr == gorm.ErrRecordNotFound {
370
+			rolePurview = models.RolePurview{
371
+				RoleId:     roleID,
372
+				OrgId:      orgID,
373
+				AppId:      appID,
374
+				Status:     1,
375
+				CreateTime: time.Now().Unix(),
376
+			}
377
+		} else {
378
+			return getRPErr
379
+		}
380
+	}
381
+	rolePurview.PurviewIds = purviewIds
382
+	rolePurview.ModifyTime = time.Now().Unix()
383
+	tx := service.UserWriteDB().Begin()
384
+	if err := tx.Save(&rolePurview).Error; err != nil {
385
+		tx.Rollback()
386
+		return err
387
+	}
388
+	return tx.Commit().Error
389
+}
390
+
391
+func ModifyAdminUserInfo(adminUserID int64, orgID int64, appID int64, name string, avatar string, newPassword string) error {
392
+	tx := service.UserWriteDB().Begin()
393
+	editInfoErr := tx.Exec("update sgj_user_admin_role set user_name = ?, avatar = ?, mtime = ? where admin_user_id = ? and org_id = ?", name, avatar, time.Now().Unix(), adminUserID, orgID).Error
394
+	if editInfoErr != nil {
395
+		tx.Rollback()
396
+		return editInfoErr
397
+	}
398
+	if len(newPassword) > 0 {
399
+		editPwdErr := tx.Exec("update sgj_user_admin set password = ?, mtime = ? where id = ?", newPassword, time.Now().Unix(), adminUserID).Error
400
+		if editPwdErr != nil {
401
+			tx.Rollback()
402
+			return editPwdErr
403
+		}
404
+	}
405
+	tx.Commit()
406
+	return nil
407
+}

File diff suppressed because it is too large
+ 1913 - 0
service/site_service/site_microwebsite_service.go


+ 116 - 0
service/sms_service/sms_db_service.go View File

@@ -0,0 +1,116 @@
1
+package sms_service
2
+
3
+import (
4
+	"SCRM/models"
5
+	"SCRM/service"
6
+	"SCRM/utils"
7
+	"time"
8
+
9
+	"github.com/jinzhu/gorm"
10
+)
11
+
12
+func GetBatchSendRecords(orgID int64, page int, count int) ([]*SMSBatchListViewModel, int, error) {
13
+	if count <= 0 {
14
+		return []*SMSBatchListViewModel{}, 0, nil
15
+	}
16
+	var viewModels []*SMSBatchListViewModel = make([]*SMSBatchListViewModel, 0)
17
+	readDB := service.PatientReadDB()
18
+	var total int
19
+	getTotalErr := readDB.Model(&models.SMSBatch{}).Where("org_id = ?", orgID).Count(&total).Error
20
+	if getTotalErr != nil {
21
+		return nil, 0, getTotalErr
22
+	}
23
+
24
+	rows, err := readDB.Raw("SELECT b.full_content, b.status, (SELECT COUNT(id) AS c FROM sgj_patient_sms_send_status WHERE batch_id = b.id) AS total_count, (SELECT COUNT(id) AS c FROM sgj_patient_sms_send_status WHERE batch_id = b.id AND STATUS = '1') AS success_count FROM sgj_patient_sms_batch AS b WHERE b.org_id = ? ORDER BY  b.id DESC LIMIT ? OFFSET ?;", orgID, count, (page-1)*count).Rows()
25
+	defer rows.Close()
26
+	if err != nil {
27
+		return nil, 0, err
28
+	}
29
+	for rows.Next() {
30
+		var viewModel SMSBatchListViewModel
31
+		readDB.ScanRows(rows, &viewModel)
32
+		viewModels = append(viewModels, &viewModel)
33
+	}
34
+	return viewModels, total, nil
35
+}
36
+
37
+// 获取指定模板id的模板
38
+func GetSMSTemplateWithTemplateID(templateID int64) (*models.SMSTemplate, error) {
39
+	var template models.SMSTemplate
40
+	err := service.PatientReadDB().Where("template_id = ? AND (status = 1 OR status = 2)", templateID).First(&template).Error
41
+	if err != nil {
42
+		if err == gorm.ErrRecordNotFound {
43
+			return nil, nil
44
+		} else {
45
+			return nil, err
46
+		}
47
+	}
48
+	return &template, nil
49
+}
50
+
51
+// 获取审核中的短信批次
52
+func getInReviewSMSBatchWithTemplateID(templateID int) ([]*models.SMSBatch, error) {
53
+	var batchs []*models.SMSBatch
54
+	err := service.PatientReadDB().Where("sms_template_id = ? AND status = ?", templateID, models.SMSBatchStatusInReview).Find(&batchs).Error
55
+	if err != nil {
56
+		return nil, err
57
+	} else {
58
+		return batchs, nil
59
+	}
60
+}
61
+
62
+// 获取用户的免费短信额度
63
+func GetUserSMSFreeLimit(orgID int64, date time.Time) (*models.UserSMSFreeLimit, error) {
64
+	month := date.Format("200601")
65
+	var freeLimit models.UserSMSFreeLimit
66
+	if readErr := service.PatientReadDB().Where("org_id = ? AND valid_month = ?", orgID, month).First(&freeLimit).Error; readErr == gorm.ErrRecordNotFound {
67
+		// 创建
68
+		now := time.Now().Unix()
69
+		freeLimit = models.UserSMSFreeLimit{
70
+			OrgID:      orgID,
71
+			TotalCount: 200,
72
+			UsedCount:  0,
73
+			ValidMonth: month,
74
+			Status:     1,
75
+			CreateTime: now,
76
+			ModifyTime: now,
77
+		}
78
+
79
+		if createErr := service.PatientWriteDB().Create(&freeLimit).Error; createErr != nil {
80
+			utils.ErrorLog("用户短信免费额度创建失败: %v", createErr)
81
+			return nil, createErr
82
+		} else {
83
+			return &freeLimit, nil
84
+		}
85
+
86
+	} else if readErr != nil {
87
+		utils.ErrorLog("获取用户短信免费额度信息失败: %v", readErr)
88
+		return nil, readErr
89
+
90
+	} else {
91
+		return &freeLimit, nil
92
+	}
93
+}
94
+
95
+// 获取未发送的短信批次
96
+func GetUnsendSMSBatch() ([]*models.SMSBatch, error) {
97
+	var batchs []*models.SMSBatch
98
+	err := service.PatientReadDB().Where("status = ?", models.SMSBatchStatusUnsend).Find(&batchs).Error
99
+	if err != nil {
100
+		if err == gorm.ErrRecordNotFound {
101
+			return nil, nil
102
+		} else {
103
+			return nil, err
104
+		}
105
+	} else {
106
+		return batchs, nil
107
+	}
108
+}
109
+
110
+func DisableTemplate(templateID int64) error {
111
+	err := service.PatientWriteDB().Model(&models.SMSTemplate{}).Where("template_id = ?", templateID).Updates(map[string]interface{}{
112
+		"status": 0,
113
+		"mtime":  time.Now().Unix(),
114
+	}).Error
115
+	return err
116
+}

+ 325 - 0
service/sms_service/sms_service.go View File

@@ -0,0 +1,325 @@
1
+package sms_service
2
+
3
+import (
4
+	"SCRM/models"
5
+	base "SCRM/service"
6
+	"SCRM/utils"
7
+	"errors"
8
+	"fmt"
9
+	"math"
10
+	"strings"
11
+	"time"
12
+
13
+	"github.com/astaxie/beego"
14
+	"github.com/jinzhu/gorm"
15
+)
16
+
17
+// 发送验证码短信
18
+func SMSSendVerificationCode(mobile string) (string, error) {
19
+	if len(mobile) == 0 {
20
+		return "", errors.New("手机号为空")
21
+	}
22
+
23
+	code_str := utils.RandomNumberString(6)
24
+	templateID, _ := beego.AppConfig.Int("sms_verification_code_templateid")
25
+	_, _, _, err := singleSendMessageUseUCPaas(templateID, []string{code_str}, mobile)
26
+	return code_str, err
27
+}
28
+
29
+// 成为机构管理员的邀请短信
30
+func SMSSendInviteMobileToJoinOrgAdmin(name string, mobile string, password string) error {
31
+	if len(mobile) == 0 {
32
+		return errors.New("手机号为空")
33
+	}
34
+	if len(password) == 0 {
35
+		_, _, _, err := singleSendMessageUseUCPaas(332784, []string{name, mobile}, mobile)
36
+		return err
37
+	} else {
38
+		_, _, _, err := singleSendMessageUseUCPaas(332783, []string{name, mobile, password}, mobile)
39
+		return err
40
+	}
41
+}
42
+
43
+var (
44
+	SMSErrorFreeLimitInsufficient = errors.New("短信额度不足")
45
+)
46
+
47
+// 发送自定义内容短信,content 不需要包括签名及“退订请回复TD”字样
48
+/* 流程说明:
49
+检查额度 -> 创建短信平台模板 -> 创建数据库短信模板(待审核状态) -> 创建发送批次(待审核状态) -> 扣除额度 -> finish
50
+*/
51
+func SMSOrgSendWithCustomContent(orgID int64, originContent string, mobiles []string) error {
52
+	if len(mobiles) == 0 {
53
+		return nil
54
+	}
55
+
56
+	autograph := "酷医聚客"
57
+	content := fmt.Sprintf("%v退订请回复TD", originContent)
58
+	fullContent := fmt.Sprintf("【%v】%v", autograph, content)
59
+	if len(fullContent) > 500 {
60
+		return errors.New("短信太长")
61
+	}
62
+
63
+	willConsumeLimit := GetWillConsumeLimit(fullContent, len(mobiles))
64
+	freeLimit, getFreeLimitErr := GetUserSMSFreeLimit(orgID, time.Now())
65
+	if getFreeLimitErr != nil {
66
+		return getFreeLimitErr
67
+	}
68
+	if willConsumeLimit+freeLimit.UsedCount > freeLimit.TotalCount {
69
+		return SMSErrorFreeLimitInsufficient
70
+	}
71
+
72
+	smsTplID, createSMSTplErr := createTemplate2UCPaas(autograph, content, 5)
73
+	if createSMSTplErr != nil {
74
+		return createSMSTplErr
75
+	}
76
+
77
+	template := models.SMSTemplate{
78
+		TemplateType: 2,
79
+		TemplateID:   int64(smsTplID),
80
+		MessageType:  2,
81
+		Content:      content,
82
+		Autograph:    autograph,
83
+		OrgID:        orgID,
84
+		Status:       2,
85
+		CreateTime:   time.Now().Unix(),
86
+		ModifyTime:   time.Now().Unix(),
87
+	}
88
+
89
+	tx := base.PatientWriteDB().Begin()
90
+	if createTplErr := tx.Save(&template).Error; createTplErr != nil {
91
+		tx.Rollback()
92
+		return createTplErr
93
+	}
94
+
95
+	sendTime := time.Now()
96
+	batch := &models.SMSBatch{
97
+		OrgID:       orgID,
98
+		Autograph:   autograph,
99
+		FullContent: fullContent,
100
+		Mobiles:     strings.Join(mobiles, ","),
101
+		TemplateID:  int64(smsTplID),
102
+		SendTime:    sendTime.Unix(),
103
+		Status:      models.SMSBatchStatusInReview,
104
+		CreateTime:  time.Now().Unix(),
105
+		ModifyTime:  time.Now().Unix(),
106
+	}
107
+	if createBatchErr := tx.Save(batch).Error; createBatchErr != nil {
108
+		tx.Rollback()
109
+		return createBatchErr
110
+	}
111
+
112
+	freeLimit.UsedCount += willConsumeLimit
113
+	freeLimit.ModifyTime = time.Now().Unix()
114
+	updateLimitErr := tx.Save(freeLimit).Error
115
+	if updateLimitErr != nil {
116
+		tx.Rollback()
117
+		return updateLimitErr
118
+	}
119
+
120
+	tx.Commit()
121
+	return nil
122
+}
123
+
124
+// 计算即将消耗的额度 (smsFullContent 包含签名在内)
125
+func GetWillConsumeLimit(smsFullContent string, mobileCount int) int {
126
+	limitEachMessage := math.Ceil(float64(len(smsFullContent)) / 67.0)
127
+	return int(limitEachMessage) * mobileCount
128
+}
129
+
130
+// 短信平台模板审核成功
131
+/* 流程说明
132
+更新数据库模板状态(有效) -> 更新对应发送批次状态(待发送) -> finish
133
+*/
134
+func SMSUCPaasTemplateApproved(templateID int64) error {
135
+	tx := base.PatientWriteDB().Begin()
136
+
137
+	updateTplErr := tx.Model(&models.SMSTemplate{}).Where("template_id = ?", templateID).Updates(map[string]interface{}{
138
+		"status": 1,
139
+		"mtime":  time.Now().Unix(),
140
+	}).Error
141
+	if updateTplErr != nil {
142
+		tx.Rollback()
143
+		return updateTplErr
144
+	}
145
+
146
+	updateBatchErr := tx.Model(&models.SMSBatch{}).Where("sms_template_id = ?", templateID).Updates(map[string]interface{}{
147
+		"status": models.SMSBatchStatusUnsend,
148
+		"mtime":  time.Now().Unix(),
149
+	}).Error
150
+	if updateBatchErr != nil {
151
+		tx.Rollback()
152
+		return updateBatchErr
153
+	}
154
+
155
+	tx.Commit()
156
+	return nil
157
+}
158
+
159
+// 短信平台模板审核失败
160
+/* 流程说明
161
+更新数据库模板状态(无效) -> 更新对应发送批次状态(审核未通过) -> 返回发送当月的额度 -> finish
162
+*/
163
+func SMSUCPaasTemplateUnapproved(templateID int64) error {
164
+	var batch models.SMSBatch
165
+	getBatchErr := base.PatientReadDB().Model(&models.SMSBatch{}).Where("sms_template_id = ?", templateID).First(&batch).Error
166
+	if getBatchErr != nil {
167
+		if getBatchErr != gorm.ErrRecordNotFound {
168
+			return getBatchErr
169
+		}
170
+	}
171
+
172
+	tx := base.PatientWriteDB().Begin()
173
+
174
+	updateTplErr := tx.Model(&models.SMSTemplate{}).Where("template_id = ?", templateID).Updates(map[string]interface{}{
175
+		"status": 0,
176
+		"mtime":  time.Now().Unix(),
177
+	}).Error
178
+	if updateTplErr != nil {
179
+		tx.Rollback()
180
+		return updateTplErr
181
+	}
182
+
183
+	if batch.ID > 0 {
184
+		batch.Status = models.SMSBatchStatusUnapproved
185
+		batch.ModifyTime = time.Now().Unix()
186
+		updateBatchErr := tx.Save(&batch).Error
187
+		if updateBatchErr != nil {
188
+			tx.Rollback()
189
+			return updateBatchErr
190
+		}
191
+
192
+		freeLimit, getFreeLimitErr := GetUserSMSFreeLimit(batch.OrgID, time.Unix(batch.SendTime, 0))
193
+		if getFreeLimitErr != nil {
194
+			tx.Rollback()
195
+			return getFreeLimitErr
196
+		}
197
+
198
+		mobiles := strings.Split(batch.Mobiles, ",")
199
+		consumedLimit := GetWillConsumeLimit(batch.FullContent, len(mobiles))
200
+		freeLimit.UsedCount -= consumedLimit
201
+		freeLimit.ModifyTime = time.Now().Unix()
202
+		updateFreeLimitErr := tx.Save(freeLimit).Error
203
+		if updateFreeLimitErr != nil {
204
+			tx.Rollback()
205
+			return updateFreeLimitErr
206
+		}
207
+	}
208
+
209
+	tx.Commit()
210
+	return nil
211
+}
212
+
213
+// 发送“未发送”批次的短信
214
+// 备注:因短信平台每次群发限制 100 个号码,所以同一个批次可能需要分成多次发送
215
+func SMSSendUnsendBatchRealTime() {
216
+	batchs, getBatchErr := GetUnsendSMSBatch()
217
+	if getBatchErr != nil {
218
+		return
219
+	}
220
+
221
+	for _, batch := range batchs {
222
+		tx := base.PatientWriteDB().Begin()
223
+
224
+		isSendSuccess := false
225
+		failMobileCount := 0
226
+		reports := []interface{}{}
227
+
228
+		mobiles := strings.Split(batch.Mobiles, ",")
229
+		subbatchCount := int(math.Ceil(float64(len(mobiles)) / 100.0))
230
+		for index := 0; index < subbatchCount; index++ {
231
+			var subMobiles []string
232
+			if len(mobiles)-index*100 >= 100 {
233
+				subMobiles = mobiles[index*100 : 100]
234
+			} else {
235
+				subMobiles = mobiles[index*100:]
236
+			}
237
+
238
+			sendCount, report, sendErr := batchSendMessageUseUCPaas(int(batch.TemplateID), nil, subMobiles)
239
+			if sendErr != nil {
240
+				utils.ErrorLog("%v", sendErr)
241
+				failMobileCount += len(subMobiles)
242
+
243
+			} else {
244
+				isSendSuccess = true // 只要子批次有一次发送成功,就认为这个批次发送成功
245
+				reports = append(reports, report)
246
+				failMobileCount += len(subMobiles) - sendCount
247
+			}
248
+		}
249
+
250
+		if isSendSuccess {
251
+			batch.Status = models.SMSBatchStatusDidSend
252
+			batch.ModifyTime = time.Now().Unix()
253
+			updateBatchErr := tx.Save(batch).Error
254
+			if updateBatchErr != nil {
255
+				utils.ErrorLog("群发短信成功后 更新批次状态失败:%v", updateBatchErr)
256
+				tx.Rollback()
257
+				continue
258
+			}
259
+
260
+			valueStrs := make([]string, 0, len(reports))
261
+			values := make([]interface{}, 0, len(reports))
262
+			for _, item := range reports {
263
+				json := item.(map[string]interface{})
264
+				valueStrs = append(valueStrs, "(?, ?, ?, ?, ?, ?, ?)")
265
+
266
+				values = append(values, batch.ID)
267
+				values = append(values, json["mobile"])
268
+				if json["code"].(string) == "000000" {
269
+					values = append(values, 1)
270
+				} else {
271
+					values = append(values, 0)
272
+				}
273
+				values = append(values, json["code"])
274
+				values = append(values, json["msg"])
275
+				values = append(values, time.Now().Unix())
276
+				values = append(values, time.Now().Unix())
277
+			}
278
+			sql := fmt.Sprintf("INSERT INTO sgj_patient_sms_send_status (batch_id, mobile, status, code, msg, ctime, mtime) VALUES %v;", strings.Join(valueStrs, ", "))
279
+			if insertReportErr := tx.Exec(sql, values...).Error; insertReportErr != nil {
280
+				utils.ErrorLog("群发短信成功后 插入短信发送状态失败: %v", insertReportErr)
281
+				tx.Rollback()
282
+				continue
283
+			}
284
+
285
+			if failMobileCount > 0 {
286
+				freeLimit, getFreeLimitErr := GetUserSMSFreeLimit(batch.OrgID, time.Unix(batch.SendTime, 0))
287
+				if getFreeLimitErr == nil {
288
+					freeLimit.UsedCount -= GetWillConsumeLimit(batch.FullContent, failMobileCount)
289
+					freeLimit.ModifyTime = time.Now().Unix()
290
+					updateLimitErr := tx.Save(freeLimit).Error
291
+					if updateLimitErr != nil {
292
+						utils.ErrorLog("群发短信成功后 返回额度失败: %v", updateLimitErr)
293
+						tx.Rollback()
294
+						continue
295
+					}
296
+				}
297
+			}
298
+			tx.Commit()
299
+
300
+		} else {
301
+			batch.Status = models.SMSBatchStatusSendFailed
302
+			batch.ModifyTime = time.Now().Unix()
303
+			updateBatchErr := tx.Save(batch).Error
304
+			if updateBatchErr != nil {
305
+				utils.ErrorLog("群发短信成功后 更新批次状态失败:%v", updateBatchErr)
306
+				tx.Rollback()
307
+				continue
308
+			}
309
+
310
+			freeLimit, getFreeLimitErr := GetUserSMSFreeLimit(batch.OrgID, time.Unix(batch.SendTime, 0))
311
+			if getFreeLimitErr == nil {
312
+				freeLimit.UsedCount -= GetWillConsumeLimit(batch.FullContent, len(mobiles))
313
+				freeLimit.ModifyTime = time.Now().Unix()
314
+				updateLimitErr := tx.Save(freeLimit).Error
315
+				if updateLimitErr != nil {
316
+					utils.ErrorLog("群发短信成功后 返回额度失败: %v", updateLimitErr)
317
+					tx.Rollback()
318
+					continue
319
+				}
320
+			}
321
+
322
+			tx.Commit()
323
+		}
324
+	}
325
+}

+ 8 - 0
service/sms_service/sms_vms.go View File

@@ -0,0 +1,8 @@
1
+package sms_service
2
+
3
+type SMSBatchListViewModel struct {
4
+	FullContent  string `json:"full_content"`  // 发送内容
5
+	Status       int8   `json:"status"`        // 批次状态 (值同 sms_models 中的 SMSBatchStatuss)
6
+	TotalCount   int    `json:"total_count"`   // 发送人数
7
+	SuccessCount int    `json:"success_count"` // 到达条数
8
+}

+ 164 - 0
service/sms_service/ucpaas.go View File

@@ -0,0 +1,164 @@
1
+package sms_service
2
+
3
+import (
4
+	"SCRM/utils"
5
+	"bytes"
6
+	"encoding/json"
7
+	"errors"
8
+	"io/ioutil"
9
+	"net/http"
10
+	"strconv"
11
+	"strings"
12
+
13
+	"github.com/astaxie/beego"
14
+)
15
+
16
+// 获取短信平台信息
17
+func getUCPaasConfig() (string, string, string) {
18
+	return beego.AppConfig.String("sms_appId"),
19
+		beego.AppConfig.String("sms_sid"),
20
+		beego.AppConfig.String("sms_token")
21
+}
22
+
23
+// 向云之讯短信平台创建模板,返回新模板的 ID
24
+// autograph: 签名,即为机构简称
25
+// content: 模板内容
26
+// type_: 短信类型:0:通知短信 5:会员服务短信
27
+func createTemplate2UCPaas(autograph string, content string, type_ int) (int, error) {
28
+	sms_api := beego.AppConfig.String("sms_baseUrl") + "addsmstemplate"
29
+	appID, sid, token := getUCPaasConfig()
30
+	params := make(map[string]interface{})
31
+	params["appid"] = appID
32
+	params["sid"] = sid
33
+	params["token"] = token
34
+	params["type"] = type_
35
+	params["autograph"] = autograph
36
+	params["content"] = content
37
+
38
+	paramsBytes, _ := json.Marshal(params)
39
+	resp, requestErr := http.Post(sms_api, "application/json", bytes.NewBuffer(paramsBytes))
40
+
41
+	if requestErr != nil {
42
+		utils.ErrorLog("短信平台增加模板接口调用失败: %v", requestErr)
43
+		return 0, requestErr
44
+	}
45
+	defer resp.Body.Close()
46
+	body, ioErr := ioutil.ReadAll(resp.Body)
47
+	if ioErr != nil {
48
+		utils.ErrorLog("短信平台增加模板接口返回数据读取失败: %v", ioErr)
49
+		return 0, ioErr
50
+	}
51
+	var respJSON map[string]interface{}
52
+	utils.InfoLog(string(body))
53
+	if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
54
+		utils.ErrorLog("短信平台增加模板接口返回数据解析JSON失败: %v", err)
55
+		return 0, err
56
+	}
57
+	if respJSON["code"].(string) != "000000" {
58
+		msg := respJSON["msg"].(string)
59
+		utils.ErrorLog("短信平台增加模板接口请求失败: %v", msg)
60
+		return 0, errors.New("短信平台增加模板接口请求失败")
61
+	}
62
+
63
+	templateID, _ := strconv.Atoi(respJSON["templateid"].(string))
64
+	utils.SuccessLog("新短信模板 ID: %v", templateID)
65
+	return templateID, nil
66
+}
67
+
68
+// 用云之讯群发模板短信
69
+// 返回值为发送了 n 条短信
70
+func batchSendMessageUseUCPaas(templateID int, params []string, mobiles []string) (int, []interface{}, error) {
71
+	sms_api := beego.AppConfig.String("sms_baseUrl") + "sendsms_batch"
72
+	mobileStr := strings.Join(mobiles, ",")
73
+	appID, sid, token := getUCPaasConfig()
74
+	requestParams := make(map[string]interface{})
75
+	requestParams["appid"] = appID
76
+	requestParams["sid"] = sid
77
+	requestParams["token"] = token
78
+	requestParams["templateid"] = strconv.Itoa(templateID)
79
+	requestParams["mobile"] = mobileStr
80
+	if params != nil && len(params) != 0 {
81
+		paramStr := strings.Join(params, ",")
82
+		requestParams["param"] = paramStr
83
+	}
84
+
85
+	paramsBytes, _ := json.Marshal(requestParams)
86
+	resp, requestErr := http.Post(sms_api, "application/json", bytes.NewBuffer(paramsBytes))
87
+
88
+	if requestErr != nil {
89
+		utils.ErrorLog("短信平台模板群发接口调用失败: %v", requestErr)
90
+		return 0, nil, requestErr
91
+	}
92
+	defer resp.Body.Close()
93
+	body, ioErr := ioutil.ReadAll(resp.Body)
94
+	if ioErr != nil {
95
+		utils.ErrorLog("短信平台模板群发接口返回数据读取失败: %v", ioErr)
96
+		return 0, nil, ioErr
97
+	}
98
+	var respJSON map[string]interface{}
99
+	utils.InfoLog(string(body))
100
+	if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
101
+		utils.ErrorLog("短信平台模板群发接口返回数据解析JSON失败: %v", err)
102
+		return 0, nil, err
103
+	}
104
+	if respJSON["code"].(string) != "000000" {
105
+		msg := respJSON["msg"].(string)
106
+		utils.ErrorLog("短信平台模板群发接口请求失败: %v", msg)
107
+		return 0, nil, errors.New("短信平台模板群发接口请求失败")
108
+
109
+	} else {
110
+		utils.SuccessLog("短信发送成功 report: %v", respJSON["report"])
111
+		if len(mobiles) > 1 {
112
+			count, _ := strconv.Atoi(respJSON["count_sum"].(string))
113
+			return count, respJSON["report"].([]interface{}), nil
114
+		} else {
115
+			return 1, nil, nil
116
+		}
117
+	}
118
+}
119
+
120
+// 用云之讯单发模板短信
121
+// 返回值分别是 是否成功,code,msg,error
122
+func singleSendMessageUseUCPaas(templateID int, params []string, mobile string) (bool, string, string, error) {
123
+	sms_api := beego.AppConfig.String("sms_baseUrl") + "sendsms"
124
+	appID, sid, token := getUCPaasConfig()
125
+	requestParams := make(map[string]interface{})
126
+	requestParams["appid"] = appID
127
+	requestParams["sid"] = sid
128
+	requestParams["token"] = token
129
+	requestParams["templateid"] = strconv.Itoa(templateID)
130
+	requestParams["mobile"] = mobile
131
+	if params != nil && len(params) != 0 {
132
+		paramStr := strings.Join(params, ",")
133
+		requestParams["param"] = paramStr
134
+	}
135
+
136
+	paramsBytes, _ := json.Marshal(requestParams)
137
+	resp, requestErr := http.Post(sms_api, "application/json", bytes.NewBuffer(paramsBytes))
138
+
139
+	if requestErr != nil {
140
+		utils.ErrorLog("短信平台模板群发接口调用失败: %v", requestErr)
141
+		return false, "", "", requestErr
142
+	}
143
+	defer resp.Body.Close()
144
+	body, ioErr := ioutil.ReadAll(resp.Body)
145
+	if ioErr != nil {
146
+		utils.ErrorLog("短信平台模板群发接口返回数据读取失败: %v", ioErr)
147
+		return false, "", "", ioErr
148
+	}
149
+	var respJSON map[string]interface{}
150
+	utils.InfoLog(string(body))
151
+	if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
152
+		utils.ErrorLog("短信平台模板群发接口返回数据解析JSON失败: %v", err)
153
+		return false, "", "", err
154
+	}
155
+	if respJSON["code"].(string) != "000000" {
156
+		msg := respJSON["msg"].(string)
157
+		utils.ErrorLog("短信平台模板群发接口请求失败: %v", msg)
158
+		return false, "", "", errors.New("短信平台模板群发接口请求失败")
159
+
160
+	} else {
161
+		utils.SuccessLog("短信发送成功")
162
+		return true, respJSON["code"].(string), respJSON["msg"].(string), nil
163
+	}
164
+}

+ 48 - 0
service/staff_service/staff_manager_service.go View File

@@ -0,0 +1,48 @@
1
+package staff_service
2
+
3
+import (
4
+	"SCRM/models"
5
+	"SCRM/service"
6
+	"time"
7
+)
8
+
9
+func AddStaffInfo(info models.SgjUserStaffInfo) error {
10
+	err := service.UserWriteDB().Create(&info).Error
11
+	return err
12
+}
13
+
14
+func GetAllStaffInfo(orgID int64, page int64, limit int64, keyword string) (userStaffInfo []*models.SgjUserStaffInfo, total int64, err error) {
15
+
16
+	db := service.UserReadDB().Table("sgj_user_staff_info as s").Where("s.status = 1")
17
+	if orgID > 0 {
18
+		db = db.Where("s.user_org_id = ?", orgID)
19
+	}
20
+
21
+	if len(keyword) > 0 {
22
+		keyword = "%" + keyword + "%"
23
+		db = db.Where("s.name LIKE ?", keyword)
24
+	}
25
+
26
+	offset := (page - 1) * limit
27
+	err = db.Count(&total).Order("s.ctime desc").Offset(offset).Limit(limit).
28
+		Select("s.id,s.name,s.phone,s.birthday,s.gender,s.user_type,s.user_title,s.dochead,s.content,s.ctime,s.mtime,s.status,s.user_org_id").Find(&userStaffInfo).Error
29
+
30
+	if err != nil {
31
+		return
32
+	}
33
+	return
34
+}
35
+
36
+func UpdateStaffInfo(info models.SgjUserStaffInfo, OrgID int64, id int64) error {
37
+	err := service.UserWriteDB().Model(&info).Where("user_org_id = ? AND id =? AND status = ?", OrgID, id, 1).Update(map[string]interface{}{"Name": info.Name, "phone": info.Phone, "birthday": info.Birthday, "gender": info.Gender, "user_type": info.UserType, "user_title": info.UserTitle, "dochead": info.Dochead, "content": info.Content, "mtime": info.Mtime}).Error
38
+	return err
39
+}
40
+
41
+func DeleteStaffs(orgID int64, ids []int64) (err error) {
42
+	if len(ids) == 1 {
43
+		err = service.UserWriteDB().Model(&models.SgjUserStaffInfo{}).Where("id=? and user_org_id = ?", ids[0], orgID).Update(map[string]interface{}{"Status": 0, "mtime": time.Now().Unix()}).Error
44
+	} else {
45
+		err = service.UserWriteDB().Model(&models.SgjUserStaffInfo{}).Where("id IN (?) and user_org_id = ?", ids, orgID).Update(map[string]interface{}{"Status": 0, "mtime": time.Now().Unix()}).Error
46
+	}
47
+	return
48
+}

+ 28 - 0
service/tencentim_service/tencent_im_service.go View File

@@ -0,0 +1,28 @@
1
+package tencentim_service
2
+
3
+import (
4
+	"SCRM/utils/tencentsig"
5
+)
6
+
7
+//正式
8
+const (
9
+	ThisAccType    = 29296
10
+	ThisSDKAppId   = "1400103109"
11
+	ThisIdentifier = "kuyiyun" //  admin
12
+	ThisPriKey     = `-----BEGIN PRIVATE KEY-----
13
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgpM/saduI49IF+DeL
14
+jEjyU1ryKIEKTyRLekw4w4qeC7ShRANCAAQHinjtGLt6WF2wOfEKA1xomfcS19/i
15
+ZyymFHJlKR49WASx/9XEbm2/TNZUn/qbe5jc4HhujQR7IUVKVFtEU6Oa
16
+-----END PRIVATE KEY-----`
17
+	ThisPubKey = `-----BEGIN PUBLIC KEY-----
18
+MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEB4p47Ri7elhdsDnxCgNcaJn3Etff
19
+4mcsphRyZSkePVgEsf/VxG5tv0zWVJ/6m3uY3OB4bo0EeyFFSlRbRFOjmg==
20
+-----END PUBLIC KEY-----`
21
+)
22
+
23
+func CreateUserSig(Identifier, AppId3rd string) (userSig string, err error) {
24
+	conf := tencentsig.NewConf(ThisSDKAppId, Identifier, AppId3rd).WithExpire(86400)
25
+	userSig, err = conf.GenUserSig(ThisPriKey)
26
+
27
+	return
28
+}

+ 0 - 0
service/tencentim_service/user_service.go View File


Some files were not shown because too many files changed in this diff