Pārlūkot izejas kodu

第一次提交

XMLWAN 4 gadus atpakaļ
revīzija
98154d6dfb

+ 143 - 0
conf/app.conf Parādīt failu

@@ -0,0 +1,143 @@
1
+appname = KYA
2
+httpport = 9536
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
+[prod]
42
+httpdomain = http://api.scrm.kuyicloud.com
43
+sso_domain = https://sso.kuyicloud.com
44
+front_end_domain = "http://jk.kuyicloud.com/#"
45
+
46
+openwechattoken = dwqofqon2e12en2o
47
+openwechatappid = wx9c877a6fc2acc742
48
+openwechatencodingaeskey = jiowefjw9pfjw9pfcw9pewjfow9huwgihg23hfwi8t4
49
+openwechatsecret = 5ac9ed5c6e3e8eee230befc7a7d04d37
50
+
51
+openwechatcomponentid = 1
52
+
53
+readmysqlhost = shengws1.mysql.rds.aliyuncs.com
54
+readmysqlport = 3306
55
+readmysqluser = syh
56
+readmysqlpass = xhPECP2nFObR8aUK
57
+readmysqlname = sgj_patient
58
+
59
+writemysqlhost = shengws1.mysql.rds.aliyuncs.com
60
+writemysqlport = 3306
61
+writemysqluser = syh
62
+writemysqlpass = xhPECP2nFObR8aUK
63
+writemysqlname = sgj_patient
64
+
65
+readuserhost = shengws1.mysql.rds.aliyuncs.com
66
+readuserport = 3306
67
+readuseruser = syh
68
+readuserpass = xhPECP2nFObR8aUK
69
+readusername = sgj_users
70
+
71
+writeuserhost = shengws1.mysql.rds.aliyuncs.com
72
+writeuserport = 3306
73
+writeuseruser = syh
74
+writeuserpass = xhPECP2nFObR8aUK
75
+writeusername = sgj_users
76
+
77
+redishost = 349e580b2a524290.redis.rds.aliyuncs.com
78
+redisport = 6379
79
+redispasswrod = TZtBW098WId3i27clkpj3q8dnUaVFP
80
+redisdb = 0
81
+
82
+
83
+
84
+
85
+[dev]
86
+httpdomain = http://api.test1.sgjyun.com
87
+sso_domain = https://testsso.sgjyun.com
88
+front_end_domain = "http://test1.sgjyun.com/#"
89
+
90
+openwechattoken = dwqofqon2e12en2o
91
+openwechatappid = wx710ed9839d337b2a
92
+openwechatencodingaeskey = jiowefjw9pfjw9pfcw9pewjfow9huwgihg23hfwi8t4
93
+openwechatsecret = bbce950b9404ed80a6727f2f3c2ec729
94
+
95
+openwechatcomponentid = 1
96
+
97
+readmysqlhost = rm-wz9rg531npf61q03tro.mysql.rds.aliyuncs.com
98
+readmysqlport = 3306
99
+readmysqluser = root
100
+readmysqlpass = 1Q2W3e4r!@#$
101
+readmysqlname = sgj_patient
102
+
103
+writemysqlhost = rm-wz9rg531npf61q03tro.mysql.rds.aliyuncs.com
104
+writemysqlport = 3306
105
+writemysqluser = root
106
+writemysqlpass = 1Q2W3e4r!@#$
107
+writemysqlname = sgj_patient
108
+
109
+readuserhost = rm-wz9rg531npf61q03tro.mysql.rds.aliyuncs.com
110
+readuserport = 3306
111
+readuseruser = root
112
+readuserpass = 1Q2W3e4r!@#$
113
+readusername = sgj_users
114
+
115
+writeuserhost = rm-wz9rg531npf61q03tro.mysql.rds.aliyuncs.com
116
+writeuserport = 3306
117
+writeuseruser = root
118
+writeuserpass = 1Q2W3e4r!@#$
119
+writeusername = sgj_users
120
+
121
+
122
+readmysqlhosts = rm-wz9rg531npf61q03tro.mysql.rds.aliyuncs.com
123
+readmysqlports = 3306
124
+readmysqlusers = root
125
+readmysqlpasss = 1Q2W3e4r!@#$
126
+readmysqlnames = sgj_xt
127
+
128
+writemysqlhosts = rm-wz9rg531npf61q03tro.mysql.rds.aliyuncs.com
129
+writemysqlports = 3306
130
+writemysqlusers = root
131
+writemysqlpasss = 1Q2W3e4r!@#$
132
+writemysqlnames = sgj_xt
133
+
134
+redishost = 127.0.0.1
135
+redisport = 6379
136
+redispasswrod = syh@#$%123456!
137
+redisdb = 0
138
+
139
+
140
+
141
+
142
+
143
+

+ 44 - 0
controllers/base_api_controller.go Parādīt failu

@@ -0,0 +1,44 @@
1
+package controllers
2
+
3
+import (
4
+	"KYA/enums"
5
+	"fmt"
6
+)
7
+
8
+type BaseAPIController struct {
9
+	BaseController
10
+}
11
+
12
+func (this *BaseAPIController) ServeSuccessJSON(data map[string]interface{}) {
13
+	this.Data["json"] = enums.MakeSuccessResponseJSON(data)
14
+	this.ServeJSON()
15
+}
16
+
17
+func (this *BaseAPIController) ServeFailJSONWithSGJErrorCode(code int) {
18
+	this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(code)
19
+	this.ServeJSON()
20
+}
21
+
22
+func (this *BaseAPIController) ServeFailJSONWithSGJError(err *enums.SGJError) {
23
+	this.Data["json"] = enums.MakeFailResponseJSONWithSGJError(err)
24
+	this.ServeJSON()
25
+}
26
+
27
+func (this *BaseAPIController) ServeFailJsonSend(code int, msg string) {
28
+	fmt.Println("code", code)
29
+	this.Data["json"] = enums.MakeFailResponseJSON(msg, code)
30
+	this.ServeJSON()
31
+}
32
+
33
+type BaseAuthAPIController struct {
34
+	BaseAPIController
35
+}
36
+
37
+type BaseServeAPIController struct {
38
+	BaseAPIController
39
+}
40
+
41
+func (this *BaseServeAPIController) Prepare() {
42
+	this.BaseAPIController.Prepare()
43
+
44
+}

+ 7 - 0
controllers/base_controller.go Parādīt failu

@@ -0,0 +1,7 @@
1
+package controllers
2
+
3
+import "github.com/astaxie/beego"
4
+
5
+type BaseController struct {
6
+	beego.Controller
7
+}

+ 687 - 0
controllers/login/login_controller.go Parādīt failu

@@ -0,0 +1,687 @@
1
+package login
2
+
3
+import (
4
+	"KYA/controllers"
5
+	"KYA/enums"
6
+	"KYA/models"
7
+	"KYA/service/login_service"
8
+	"KYA/service/patient_service"
9
+	"KYA/sms_service"
10
+	"KYA/utils"
11
+	"encoding/json"
12
+	"fmt"
13
+	"github.com/astaxie/beego"
14
+	"github.com/jinzhu/gorm"
15
+	"strconv"
16
+	"strings"
17
+	"time"
18
+)
19
+
20
+func LoginRouter() {
21
+	beego.Router("/api/qiniu/uptoken", &LoginManagement{}, "Get:GetQNUpToken")
22
+	beego.Router("/api/site/gettologin", &LoginManagement{}, "Post:GetToLogin")
23
+	beego.Router("/api/password/code", &LoginManagement{}, "Post:CodeOfModifyPwd")
24
+	beego.Router("/api/save/register", &LoginManagement{}, "Post:SaveRegisterData")
25
+	beego.Router("/api/login/getallprovince", &LoginManagement{}, "Get:GetAllProvince")
26
+	beego.Router("/api/login/nopasslogin", &LoginManagement{}, "Get:NoPassLogin")
27
+	beego.Router("/api/login/getcode", &LoginManagement{}, "Post:GetCode")
28
+	beego.Router("/api/login/nextstep", &LoginManagement{}, "Get:NextStep")
29
+	beego.Router("/api/login/accomplish", &LoginManagement{}, "Post:Accomplish")
30
+	beego.Router("/api/login/getallorgname", &LoginManagement{}, "Get:GetAllOrgName")
31
+	beego.Router("/api/login/getcitybyid", &LoginManagement{}, "Get:GetCityById")
32
+	beego.Router("/api/login/getallorgtype", &LoginManagement{}, "Get:GetAllOrgType")
33
+	beego.Router("/api/login/saveorginformation", &LoginManagement{}, "Post:SaveOrginInformation")
34
+	beego.Router("/api/patient/getneratedialysisno", &LoginManagement{}, "Get:GetneratedDialysisNo")
35
+	beego.Router("/api/login/getblooddialysispatient", &LoginManagement{}, "Get:GetBloodDialysisPatient")
36
+	beego.Router("/api/site/getdoctoradvice", &LoginManagement{}, "Get:GetDoctorAdvice")
37
+	beego.Router("/api/site/savesearch", &LoginManagement{}, "Get:SaveSearch")
38
+	beego.Router("/api/site/toseacherdoctoradvice", &LoginManagement{}, "Get:ToSeacherDoctorAdvice")
39
+	beego.Router("/api/site/deleteDoctorAdvice", &LoginManagement{}, "Get:DeleteDoctorAdvice")
40
+}
41
+
42
+type LoginManagement struct {
43
+	controllers.BaseAPIController
44
+}
45
+
46
+func (this *LoginManagement) GetQNUpToken() {
47
+	redisClient := login_service.RedisClient()
48
+	fmt.Println("redisClient", redisClient)
49
+	defer redisClient.Close()
50
+	token, err := redisClient.Get("qn_token").Result()
51
+	fmt.Println("token是什么", token)
52
+	fmt.Println("错误", err)
53
+	fmt.Println("token", token)
54
+	if err != nil {
55
+		defer fmt.Println(err)
56
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeGetQiniuUpToken)
57
+		return
58
+	}
59
+	this.ServeSuccessJSON(map[string]interface{}{
60
+		"uptoken": token,
61
+	})
62
+	return
63
+}
64
+
65
+func (this *LoginManagement) ServeFailJsonSend(code int, msg string) {
66
+	fmt.Println("code", code)
67
+	this.Data["json"] = enums.MakeFailResponseJSON(msg, code)
68
+	this.ServeJSON()
69
+}
70
+
71
+func (this *LoginManagement) ServeSuccessJSON(data map[string]interface{}) {
72
+	this.Data["json"] = enums.MakeSuccessResponseJSON(data)
73
+	this.ServeJSON()
74
+}
75
+
76
+func (this *LoginManagement) GetToLogin() {
77
+	tel := this.GetString("tel")
78
+	fmt.Println("账号啊", tel)
79
+	psd := this.GetString("psd")
80
+	fmt.Println("密码哈", psd)
81
+	admin, err := login_service.QueryLogin(tel, psd)
82
+	fmt.Println("admin", admin)
83
+	fmt.Println("err", err)
84
+	if err != nil {
85
+		fmt.Println("代码进来了没哟u")
86
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "账号密码错误")
87
+		return
88
+	} else {
89
+		fmt.Println("admin", admin.ID)
90
+		org, error := login_service.GetQueryUserOrgId(admin.ID)
91
+		fmt.Println("error", error)
92
+		if error == gorm.ErrRecordNotFound {
93
+			this.ServeSuccessJSON(map[string]interface{}{
94
+				"org":  org,
95
+				"info": admin,
96
+			})
97
+		} else if error == nil {
98
+			fmt.Println("heeeee")
99
+			this.ServeSuccessJSON(map[string]interface{}{
100
+				"admin": admin,
101
+			})
102
+		}
103
+	}
104
+
105
+	//fmt.Println("==============================================",admin.ID)
106
+	//org, errcode := login_service.GetQueryUserOrgId(admin.ID)
107
+	//fmt.Println("org是什么",org)
108
+	//fmt.Println("errcode",errcode)
109
+	//fmt.Println("org",org)
110
+
111
+	//if err == gorm.ErrRecordNotFound{
112
+	//	this.ServeSuccessJSON(map[string]interface{}{
113
+	//		"Userorg":admin,
114
+	//	})
115
+	//}else if err == nil {
116
+	//	if(admin.Mobile != tel && admin.Mobile != psd){
117
+	//		this.ServeFailJsonSend(enums.ErrorCodeDataException, "登录失败")
118
+	//		return
119
+	//	}
120
+	//	this.ServeSuccessJSON(map[string]interface{}{
121
+	//		"admin":admin,
122
+	//	})
123
+	//}
124
+
125
+}
126
+
127
+func (this *LoginManagement) CodeOfModifyPwd() {
128
+
129
+	redisClient := login_service.RedisClient()
130
+	defer redisClient.Close()
131
+	mobile := this.GetString("phone")
132
+	fmt.Println("错误错误错误错误错误错误错误错误错误错误错误错误错误错误错误错误错误错误错误错误错误错误", mobile)
133
+	//var  mobile = "13318464642"
134
+	admin, errcode := login_service.GetQueryMobileData(mobile)
135
+	fmt.Println("admin是设么", admin)
136
+	fmt.Println("errcode是设么", errcode)
137
+	if errcode == gorm.ErrRecordNotFound {
138
+		cur_date := time.Now().Format("2006-01-02")
139
+		moblie_count, _ := redisClient.Get("scrm_verification_code_" + mobile + "_" + cur_date).Result()
140
+		fmt.Println("moblie_count", moblie_count)
141
+		moblie_count_int, _ := strconv.Atoi(moblie_count)
142
+		if moblie_max := 5; moblie_count_int >= moblie_max {
143
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeVerificationCodeLimit)
144
+			return
145
+		}
146
+
147
+		if code, err := sms_service.SMSSendVerificationCode(mobile); err != nil {
148
+			//this.ErrorLog("修改密码发送验证码失败:%v", err)
149
+			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
150
+			return
151
+
152
+		} else {
153
+			cur_date := time.Now().Format("2006-01-02")
154
+			set := redisClient.Set("scrm_verification_code_"+mobile, code, time.Minute*10)
155
+			fmt.Println("set", set)
156
+			Incr, _ := redisClient.Incr("scrm_verification_code_" + mobile + "_" + cur_date).Result()
157
+			fmt.Println("Incr", Incr)
158
+
159
+			this.ServeSuccessJSON(map[string]interface{}{
160
+				"msg": "短信发送成功,有效期为10分钟",
161
+			})
162
+		}
163
+		returnData := make(map[string]interface{}, 0)
164
+		returnData["admin"] = admin
165
+		this.ServeSuccessJSON(returnData)
166
+	} else if errcode == nil {
167
+		returnData := make(map[string]interface{}, 0)
168
+		returnData["admin"] = admin
169
+		this.ServeSuccessJSON(returnData)
170
+	}
171
+}
172
+
173
+func (this *LoginManagement) SaveRegisterData() {
174
+	phone := this.GetString("phone")
175
+	fmt.Println("电话是多少", phone)
176
+	password := this.GetString("password")
177
+	fmt.Println("密码是多少", password)
178
+	code := this.GetString("code")
179
+	fmt.Println("code", code)
180
+	redisClient := login_service.RedisClient()
181
+	fmt.Println("redisClient", redisClient)
182
+	defer redisClient.Close()
183
+	cachedCode, err := redisClient.Get("scrm_verification_code_" + phone).Result()
184
+	fmt.Println("错误是设么", err)
185
+	fmt.Println("cachedCode", cachedCode)
186
+
187
+	//admin := models.SgjUserAdmin{
188
+	//	Mobile:       phone,
189
+	//	Password:     password,
190
+	//	Status:       1,
191
+	//	IsSuperAdmin: 1,
192
+	//	Ctime:        time.Now().Unix(),
193
+	//}
194
+	//err := login_service.AddAdmin(&admin)
195
+	//fmt.Println("错误",err)
196
+	//returnData := make(map[string]interface{}, 0)
197
+	//returnData["admin"] = admin
198
+	//this.ServeSuccessJSON(returnData)
199
+	//if err != nil {
200
+	//	this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAccountOrVerCodeWrong)
201
+	//	return
202
+	//}
203
+	if code != cachedCode {
204
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAccountOrVerCodeWrong)
205
+		return
206
+	} else {
207
+		admin := models.SgjUserAdmin{
208
+			Mobile:       phone,
209
+			Password:     password,
210
+			Status:       1,
211
+			IsSuperAdmin: 1,
212
+			Ctime:        time.Now().Unix(),
213
+		}
214
+		err = login_service.AddAdmin(&admin)
215
+		fmt.Println("错误", err)
216
+		returnData := make(map[string]interface{}, 0)
217
+		returnData["admin"] = admin
218
+		this.ServeSuccessJSON(returnData)
219
+	}
220
+
221
+}
222
+
223
+func (this *LoginManagement) GetAllProvince() {
224
+	provice, err := login_service.GetAllProvince(0)
225
+	fmt.Println("错误", err)
226
+	//returnData := make(map[string]interface{}, 0)
227
+	//returnData["provice"] = provice
228
+	//this.ServeSuccessJSON(returnData)
229
+
230
+	this.ServeSuccessJSON(map[string]interface{}{
231
+		"provice": provice,
232
+	})
233
+}
234
+
235
+func (this *LoginManagement) NoPassLogin() {
236
+	phone := this.GetString("phone")
237
+	fmt.Println("phone是什么", phone)
238
+	code := this.GetString("code")
239
+	fmt.Println("code是什么", code)
240
+	admin, err := login_service.GetQueryPhoneData(phone)
241
+	fmt.Println("admin", admin)
242
+	if err != nil {
243
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAccountOrVerCodeWrong)
244
+		return
245
+	}
246
+	redisClient := login_service.RedisClient()
247
+	defer redisClient.Close()
248
+	cachedCode, err := redisClient.Get("scrm_verification_code_" + phone).Result()
249
+	fmt.Println("cachedCode", cachedCode)
250
+	if err != nil {
251
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAccountOrVerCodeWrong)
252
+		return
253
+	}
254
+	if code == cachedCode {
255
+		returnData := make(map[string]interface{}, 0)
256
+		returnData["msg"] = "ok"
257
+		this.ServeSuccessJSON(returnData)
258
+	}
259
+
260
+	if code != cachedCode {
261
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAccountOrVerCodeWrong)
262
+		return
263
+	}
264
+}
265
+
266
+func (this *LoginManagement) GetCode() {
267
+	phone := this.GetString("phone")
268
+	fmt.Println("phone", phone)
269
+	redisClient := login_service.RedisClient()
270
+	defer redisClient.Close()
271
+	cur_date := time.Now().Format("2006-01-02")
272
+	moblie_count, _ := redisClient.Get("scrm_verification_code_" + phone + "_" + cur_date).Result()
273
+	moblie_count_int, _ := strconv.Atoi(moblie_count)
274
+	if moblie_max := 5; moblie_count_int >= moblie_max {
275
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeVerificationCodeLimit)
276
+		return
277
+	}
278
+	if code, err := sms_service.SMSSendVerificationCode(phone); err != nil {
279
+		//this.ErrorLog("修改密码发送验证码失败:%v", err)
280
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
281
+		return
282
+
283
+	} else {
284
+		cur_date := time.Now().Format("2006-01-02")
285
+		redisClient.Set("scrm_verification_code_"+phone, code, time.Minute*10)
286
+		redisClient.Incr("scrm_verification_code_" + phone + "_" + cur_date).Result()
287
+
288
+		this.ServeSuccessJSON(map[string]interface{}{
289
+			"msg": "短信发送成功,有效期为10分钟",
290
+		})
291
+	}
292
+}
293
+
294
+func (this *LoginManagement) NextStep() {
295
+	phone := this.GetString("phone")
296
+	fmt.Println("电话", phone)
297
+	code := this.GetString("code")
298
+	fmt.Println("code", code)
299
+	redisClient := login_service.RedisClient()
300
+	defer redisClient.Close()
301
+	cachedCode, err := redisClient.Get("scrm_verification_code_" + phone).Result()
302
+	fmt.Println("cachedCode", cachedCode)
303
+	if err != nil {
304
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAccountOrVerCodeWrong)
305
+		return
306
+	}
307
+	if code == cachedCode {
308
+		returnData := make(map[string]interface{}, 0)
309
+		returnData["msg"] = "ok"
310
+		this.ServeSuccessJSON(returnData)
311
+	}
312
+
313
+	if code != cachedCode {
314
+		fmt.Println("hehehhhhhhhhhheheh")
315
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAccountOrVerCodeWrong)
316
+		return
317
+	}
318
+}
319
+
320
+func (this *LoginManagement) Accomplish() {
321
+	phone := this.GetString("phone")
322
+	fmt.Println("phone", phone)
323
+	newpassword := this.GetString("newpassword")
324
+	fmt.Println("newpassword", newpassword)
325
+	confirmpassword := this.GetString("confirmpassword")
326
+	fmt.Println("confirmpassword", confirmpassword)
327
+	if newpassword != confirmpassword {
328
+		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAccountOrVerCodeWrong)
329
+		return
330
+	}
331
+	if newpassword == confirmpassword {
332
+		admin := models.SgjUserAdmin{
333
+			Password: newpassword,
334
+		}
335
+		err := login_service.UpdatedPassword(phone, &admin)
336
+		fmt.Println("错误", err)
337
+		returnData := make(map[string]interface{}, 0)
338
+		returnData["admin"] = admin
339
+		this.ServeSuccessJSON(returnData)
340
+	}
341
+}
342
+
343
+func (this *LoginManagement) GetAllOrgName() {
344
+	id, _ := this.GetInt64("id")
345
+	org, err := login_service.GetAllOrgName(id)
346
+	fmt.Println("错误", err)
347
+	returnData := make(map[string]interface{}, 0)
348
+	returnData["org"] = org
349
+	this.ServeSuccessJSON(returnData)
350
+}
351
+func (this *LoginManagement) GetCityById() {
352
+	id, _ := this.GetInt64("id")
353
+	//fmt.Println("id是什么",id)
354
+	ids, err := login_service.GetCityById(id)
355
+	fmt.Println("err是设么", err)
356
+	returnData := make(map[string]interface{}, 0)
357
+	returnData["ids"] = ids
358
+	this.ServeSuccessJSON(returnData)
359
+}
360
+
361
+func (this *LoginManagement) GetAllOrgType() {
362
+	orgtypes, err := login_service.GetAllOrgType()
363
+	fmt.Println("err是什么", err)
364
+	fmt.Println("orgtypes", orgtypes)
365
+	returnData := make(map[string]interface{}, 0)
366
+	returnData["orgtypes"] = orgtypes
367
+	this.ServeSuccessJSON(returnData)
368
+}
369
+
370
+func (this *LoginManagement) SaveOrginInformation() {
371
+	id, _ := this.GetInt64("id")
372
+	fmt.Println("id", id)
373
+	dataBody := make(map[string]interface{}, 0)
374
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
375
+	fmt.Println("视频发布是什么呢", err)
376
+	//orgname := this.GetString("org_name")
377
+	orgname := dataBody["org_name"].(string)
378
+	fmt.Println("orgname", orgname)
379
+	address := dataBody["address"].(string)
380
+	fmt.Println("address", address)
381
+	contactname := dataBody["contact_name"].(string)
382
+	fmt.Println("contactname", contactname)
383
+	telephone := dataBody["telephone"].(string)
384
+	fmt.Println("telephone", telephone)
385
+	provincesName := dataBody["provinces_name"].(string)
386
+	fmt.Println("provincesName", provincesName)
387
+	district, err := login_service.GetProvinceByName(provincesName)
388
+	fmt.Println("district", district)
389
+	cityname := dataBody["city_name"].(string)
390
+	fmt.Println("cityname", cityname)
391
+	cityDistrict, err := login_service.GetCityByName(cityname, district.ID)
392
+	fmt.Println("err", err)
393
+	fmt.Println("cityDistrict", cityDistrict)
394
+	countname := dataBody["count_name"].(string)
395
+	fmt.Println("countname", countname)
396
+	orgtype := dataBody["org_type"].(string)
397
+	fmt.Println("orgtype", orgtype)
398
+	Orgtype, err := login_service.GetOrgTypeByName(orgtype)
399
+	userDistrict, err := login_service.GetCountByName(countname, cityDistrict.ID)
400
+	fmt.Println("错误", err)
401
+	fmt.Println("userDistrict", userDistrict)
402
+	org := models.SgjUserOrg{
403
+		OrgName:     orgname,
404
+		Address:     address,
405
+		ContactName: contactname,
406
+		Telephone:   telephone,
407
+		Ctime:       time.Now().Unix(),
408
+		Status:      1,
409
+		Province:    district.ID,
410
+		City:        cityDistrict.ID,
411
+		District:    userDistrict.ID,
412
+		OrgType:     Orgtype.ID,
413
+		Creator:     id,
414
+	}
415
+
416
+	fmt.Println("org", org)
417
+	err = login_service.AddUserOrgInfo(&org)
418
+	userOrg, err := login_service.GeLastUserOrgLastData(id)
419
+	fmt.Println("uerOrg", userOrg)
420
+	fmt.Println("heeeeeeeeeeeeeeee", userOrg.ID)
421
+	fmt.Println("err", err)
422
+	nextMonthDate := time.Now().AddDate(0, 0, 30)
423
+	subscibe := models.ServeSubscibe{
424
+		OrgId:       userOrg.ID,
425
+		PeriodStart: time.Now().Unix(),
426
+		PeriodEnd:   nextMonthDate.Unix(),
427
+		Status:      1,
428
+		State:       9,
429
+		CreatedTime: time.Now().Unix(),
430
+		UpdatedTime: time.Now().Unix(),
431
+	}
432
+	err = login_service.CreateSubscibe(&subscibe)
433
+
434
+	fmt.Println("err", err)
435
+	role := models.UserRole{
436
+		RoleName:     "超级管理员",
437
+		Creator:      id,
438
+		OrgId:        userOrg.ID,
439
+		IsSuperAdmin: 1,
440
+		Status:       1,
441
+		Ctime:        time.Now().Unix(),
442
+		Mtime:        time.Now().Unix(),
443
+	}
444
+
445
+	err = login_service.AddRole(&role)
446
+	userRole, err := login_service.GetRoleLastDate(userOrg.ID)
447
+	fmt.Println("添加权限", err)
448
+	orgApp := models.UserOrgApp{
449
+		AppType:    1,
450
+		Creator:    id,
451
+		OrgId:      userOrg.ID,
452
+		OpenStatus: 0,
453
+		Status:     1,
454
+		Ctime:      time.Now().Unix(),
455
+		Mtime:      time.Now().Unix(),
456
+	}
457
+	errcode := login_service.AddUserOrgApp(&orgApp)
458
+	fmt.Println("addUserOrgApp", errcode)
459
+
460
+	orgApp, _ = login_service.GetLastData(userOrg.ID)
461
+	fmt.Println("oooooooooooooooooooooooooooooooooooooooooo")
462
+	fmt.Println("orgApp是什么东西", orgApp)
463
+	fmt.Println("orgapp", orgApp.ID)
464
+	adminRole := models.UserAdminRole{
465
+		AdminUserId: id,
466
+		OrgId:       userOrg.ID,
467
+		AppId:       orgApp.ID,
468
+		RoleId:      userRole.ID,
469
+		UserType:    1,
470
+		UserTitle:   1,
471
+		Status:      1,
472
+		UserName:    telephone,
473
+		Ctime:       time.Now().Unix(),
474
+	}
475
+	err = login_service.AddAdimnRole(&adminRole)
476
+
477
+	app := models.UserOrgApp{
478
+		AppType:    3,
479
+		Creator:    id,
480
+		OrgId:      userOrg.ID,
481
+		OpenStatus: 1,
482
+		Status:     1,
483
+		Ctime:      time.Now().Unix(),
484
+		Mtime:      time.Now().Unix(),
485
+	}
486
+	err = login_service.AddUserOrgApp(&app)
487
+
488
+	getLastDatas, _ := login_service.GetLastData(userOrg.ID)
489
+	adminRolethee := models.UserAdminRole{
490
+		AdminUserId: id,
491
+		OrgId:       userOrg.ID,
492
+		AppId:       getLastDatas.ID,
493
+		RoleId:      userRole.ID,
494
+		UserType:    1,
495
+		UserTitle:   1,
496
+		Status:      1,
497
+		UserName:    telephone,
498
+		Ctime:       time.Now().Unix(),
499
+	}
500
+	err = login_service.AddAdimnRole(&adminRolethee)
501
+
502
+	userOrgApp := models.UserOrgApp{
503
+		AppType:    4,
504
+		Creator:    id,
505
+		OrgId:      userOrg.ID,
506
+		OpenStatus: 0,
507
+		Status:     1,
508
+		Ctime:      time.Now().Unix(),
509
+		Mtime:      time.Now().Unix(),
510
+	}
511
+	err = login_service.AddUserOrgApp(&userOrgApp)
512
+	data, _ := login_service.GetLastData(userOrg.ID)
513
+	adminRoleone := models.UserAdminRole{
514
+		AdminUserId: id,
515
+		OrgId:       userOrg.ID,
516
+		AppId:       data.ID,
517
+		RoleId:      userRole.ID,
518
+		UserType:    1,
519
+		UserTitle:   1,
520
+		Status:      1,
521
+		UserName:    telephone,
522
+		Ctime:       time.Now().Unix(),
523
+	}
524
+	err = login_service.AddAdimnRole(&adminRoleone)
525
+
526
+	iuser := models.UserOrgApp{
527
+		AppType:    5,
528
+		Creator:    id,
529
+		OrgId:      userOrg.ID,
530
+		OpenStatus: 0,
531
+		Status:     1,
532
+		Ctime:      time.Now().Unix(),
533
+		Mtime:      time.Now().Unix(),
534
+	}
535
+	err = login_service.AddUserOrgApp(&iuser)
536
+	fmt.Println("错误", err)
537
+	lastData, _ := login_service.GetLastData(userOrg.ID)
538
+	adminRoletwo := models.UserAdminRole{
539
+		AdminUserId: id,
540
+		OrgId:       userOrg.ID,
541
+		AppId:       lastData.ID,
542
+		RoleId:      userRole.ID,
543
+		UserType:    1,
544
+		UserTitle:   1,
545
+		Status:      1,
546
+		UserName:    telephone,
547
+		Ctime:       time.Now().Unix(),
548
+	}
549
+	err = login_service.AddAdimnRole(&adminRoletwo)
550
+	returnData := make(map[string]interface{}, 0)
551
+	returnData["org"] = org
552
+	this.ServeSuccessJSON(returnData)
553
+}
554
+
555
+func (this *LoginManagement) GetneratedDialysisNo() {
556
+	phone := this.GetString("phone")
557
+	fmt.Println("phone是什么", phone)
558
+	admin, err := patient_service.GetCreatorId(phone)
559
+	fmt.Println("获取注册id错误", err)
560
+	org, err := patient_service.GetOrgId(admin.ID)
561
+	fmt.Println("获取机构id错误", err)
562
+	fmt.Println("机构id", org.ID)
563
+	dialysisNo := patient_service.GetneratedDialysisNo(org.ID)
564
+	fmt.Println("dialysisNo是什么", dialysisNo)
565
+	if dialysisNo == 0 {
566
+		dialysisNo = 1
567
+	} else {
568
+		dialysisNo++
569
+	}
570
+	no := strconv.FormatInt(dialysisNo, 10)
571
+	fmt.Println("no", no)
572
+	rep := 3 - len(no)
573
+	if rep > 0 {
574
+		no = strings.Repeat("0", rep) + no
575
+	}
576
+	this.ServeSuccessJSON(map[string]interface{}{
577
+		"no": no,
578
+	})
579
+	returnData := make(map[string]interface{}, 0)
580
+	returnData["no"] = no
581
+	this.ServeSuccessJSON(returnData)
582
+}
583
+
584
+func (this *LoginManagement) GetBloodDialysisPatient() {
585
+	page, _ := this.GetInt64("page")
586
+	fmt.Println("page", page)
587
+	limit, _ := this.GetInt64("limit")
588
+	fmt.Println("limit", limit)
589
+	id, _ := this.GetInt64("id")
590
+	org, _ := patient_service.GetOrgId(id)
591
+	fmt.Println("org是什么", org.ID)
592
+	patients, total, err := login_service.GetBloodDialysisPatient(org.ID, page, limit)
593
+	fmt.Println("patients", patients)
594
+	fmt.Println("err", err)
595
+	returnData := make(map[string]interface{}, 0)
596
+	returnData["patients"] = patients
597
+	returnData["total"] = total
598
+	this.ServeSuccessJSON(returnData)
599
+	if err != nil {
600
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加医院失败")
601
+		return
602
+	}
603
+	this.ServeSuccessJSON(map[string]interface{}{
604
+		"patients": patients,
605
+		"total":    total,
606
+	})
607
+
608
+}
609
+
610
+func (this *LoginManagement) GetDoctorAdvice() {
611
+	patientid, _ := this.GetInt64("patientid")
612
+	fmt.Println("patientid", patientid)
613
+	starttime := this.GetString("starttime")
614
+	fmt.Println("starttime", starttime)
615
+	timeLayout := "2006-01-02 15:04:05"
616
+	theTime, _ := utils.ParseTimeStringToTime(timeLayout, starttime+" 00:00:00")
617
+	fmt.Println("err")
618
+	star := theTime.Unix()
619
+	fmt.Println("star", star)
620
+	orgid, _ := this.GetInt64("orgid")
621
+	fmt.Println("orgid是什么", orgid)
622
+	endtime := this.GetString("endtime")
623
+	fmt.Println("endtime", endtime)
624
+	toTime, _ := utils.ParseTimeStringToTime(timeLayout, endtime+" 00:00:00")
625
+	end := toTime.Unix()
626
+	fmt.Println("end", end)
627
+	searchval := this.GetString("searchval")
628
+	fmt.Println("searchval", searchval)
629
+	patients, err := login_service.GetPatintsInfo(patientid, orgid)
630
+	diseases, err := login_service.GetPatientInfectious(patientid)
631
+	fmt.Println("徐欧文", err)
632
+	//根据机构id获取创建者id
633
+	org, _ := login_service.GetCreatorId(orgid)
634
+	fmt.Println("创建者", org)
635
+	//根据创建者id获取apptype id
636
+	app, _ := login_service.GetOrgAppId(org.Creator, orgid)
637
+	fmt.Println("appid", app.ID)
638
+	//获取开嘱医生
639
+	role, _ := login_service.GetAdvceDoctor(org.Creator, orgid, app.ID)
640
+	doctoradvice, total, err := login_service.GetDoctorAdvice(patientid, orgid, star, end, searchval)
641
+	fmt.Println("err", err)
642
+	fmt.Println("doctorradvice", doctoradvice)
643
+	if err != nil {
644
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加医院失败")
645
+		return
646
+	}
647
+	this.ServeSuccessJSON(map[string]interface{}{
648
+		"doctoradvice": doctoradvice,
649
+		"patients":     patients,
650
+		"diseases":     diseases,
651
+		"role":         role,
652
+		"total":        total,
653
+	})
654
+}
655
+
656
+func (this *LoginManagement) SaveSearch() {
657
+	searchval := this.GetString("searchval")
658
+	fmt.Println("searchval", searchval)
659
+}
660
+
661
+func (this *LoginManagement) ToSeacherDoctorAdvice() {
662
+	patientid, _ := this.GetInt64("patientid")
663
+	fmt.Println("patientid", patientid)
664
+	orgid, _ := this.GetInt64("orgid")
665
+	fmt.Println("orgid", orgid)
666
+	searchval := this.GetString("searchval")
667
+	fmt.Println("searchval", searchval)
668
+	doctoradvice, err := login_service.SeacherDoctorAdviceByAdviceName(patientid, orgid, searchval)
669
+	if err != nil {
670
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加医院失败")
671
+		return
672
+	}
673
+	this.ServeSuccessJSON(map[string]interface{}{
674
+		"doctoradvice": doctoradvice,
675
+	})
676
+}
677
+
678
+func (this *LoginManagement) DeleteDoctorAdvice() {
679
+	id, _ := this.GetInt64("id")
680
+	fmt.Println("id是什么", id)
681
+	err := login_service.DeleteDoctorAdvice(id)
682
+	fmt.Println("err", err)
683
+	returnData := make(map[string]interface{}, 0)
684
+	returnData["msg"] = "ok"
685
+	this.ServeSuccessJSON(returnData)
686
+	return
687
+}

+ 6 - 0
controllers/login/router_conllector.go Parādīt failu

@@ -0,0 +1,6 @@
1
+package login
2
+
3
+func LoginRegisterRouter() {
4
+
5
+	LoginRouter()
6
+}

+ 569 - 0
controllers/manage/manage_controller.go Parādīt failu

@@ -0,0 +1,569 @@
1
+package manage
2
+
3
+import (
4
+	"KYA/controllers"
5
+	"KYA/enums"
6
+	"KYA/models"
7
+	"KYA/service/login_service"
8
+	"KYA/service/manage_service"
9
+	"KYA/service/patient_service"
10
+	"KYA/utils"
11
+	"encoding/json"
12
+	"fmt"
13
+	"github.com/astaxie/beego"
14
+	"github.com/jinzhu/gorm"
15
+	"strconv"
16
+	"strings"
17
+	"time"
18
+)
19
+
20
+func ManageRouter() {
21
+
22
+	beego.Router("/api/patient/getcoursemanagement", &Manage{}, "Post:GetCourseManagement")
23
+	beego.Router("/api/patient/savepatient", &Manage{}, "Post:SavePatient")
24
+	beego.Router("/api/patient/todeletecousemanage", &Manage{}, "Get:DeleteCouseManage")
25
+	beego.Router("/api/patient/getmissioninformation", &Manage{}, "Get:GetMissionInformation")
26
+	beego.Router("/api/patient/getrecordsave", &Manage{}, "Get:GetRecordSave")
27
+	beego.Router("/api/patient/getcheckpatientdata", &Manage{}, "Get:GetCheckPatientData")
28
+	beego.Router("/api/patient/getlongdialysis", &Manage{}, "Get:GetLongDialysis")
29
+	beego.Router("/api/patient/getdialysrecord", &Manage{}, "Get:GetDialysRecord")
30
+	beego.Router("/api/site/toseacherCourseManagement", &Manage{}, "Get:ToSeacherCourseManagement")
31
+	beego.Router("/api/site/todeletesaverecord", &Manage{}, "Get:ToDeleteSaveRecord")
32
+	beego.Router("/api/site/toSeacherRecord", &Manage{}, "Get:ToSeacherRecord")
33
+	beego.Router("/api/site/deletemissioninformation", &Manage{}, "Get:DeleteMissionInformation")
34
+	beego.Router("/api/patient/toseachermissioninformation", &Manage{}, "Get:ToSeacherMissionInformation")
35
+	beego.Router("/api/patient/getpatientschedules", &Manage{}, "Get:GetPatientSchedules")
36
+	beego.Router("/api/patient/deletescheduleinformation", &Manage{}, "Get:DeleteScheduleinformation")
37
+	beego.Router("/api/patient/toseacherscheduleinformation", &Manage{}, "Get:ToSeacherScheduleInformation")
38
+	beego.Router("/api/patient/getpatienttype", &Manage{}, "Get:GetPatientType")
39
+	beego.Router("/api/patient/checkall", &Manage{}, "Get:GetCheckall")
40
+}
41
+
42
+type Manage struct {
43
+	controllers.BaseAPIController
44
+}
45
+
46
+func (this *Manage) ServeFailJsonSend(code int, msg string) {
47
+	fmt.Println("code", code)
48
+	this.Data["json"] = enums.MakeFailResponseJSON(msg, code)
49
+	this.ServeJSON()
50
+}
51
+
52
+func (this *Manage) ServeSuccessJSON(data map[string]interface{}) {
53
+	this.Data["json"] = enums.MakeSuccessResponseJSON(data)
54
+	this.ServeJSON()
55
+}
56
+
57
+func (this *Manage) GetCourseManagement() {
58
+
59
+	patienid, _ := this.GetInt64("patientid")
60
+	fmt.Println("patientid", patienid)
61
+	orgid, _ := this.GetInt64("orgid")
62
+	fmt.Println("orgid", orgid)
63
+	startime := this.GetString("startime")
64
+	fmt.Println("startime", startime)
65
+	endtime := this.GetString("endtime")
66
+	endTimeYMDHmsStr := endtime + " 23:59:59"
67
+	endTime, _ := utils.ParseTimeStringToTime("2006-01-02 15:04:05", endTimeYMDHmsStr)
68
+	fmt.Println("endtime", endtime)
69
+	timeLayout := "2006-01-02 15:04:05"
70
+	theTime, _ := utils.ParseTimeStringToTime(timeLayout, startime+" 00:00:00")
71
+	star := theTime.Unix()
72
+	patients, _ := login_service.GetPatintsInfo(patienid, orgid)
73
+
74
+	patientCourse, err := patient_service.GetCourseManagementData(patienid, orgid, star, endTime.Unix())
75
+	fmt.Print("报错----------------------", err)
76
+	infectious, err := patient_service.GetPatientInfectious(patienid)
77
+	fmt.Println("错误是设么", err)
78
+	fmt.Println("patietnCourse", patientCourse)
79
+	if err != nil {
80
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加医院失败")
81
+		return
82
+	}
83
+	this.ServeSuccessJSON(map[string]interface{}{
84
+		"patientCourse": patientCourse,
85
+		"patients":      patients,
86
+		"infectious":    infectious,
87
+	})
88
+}
89
+
90
+func (this *Manage) SavePatient() {
91
+
92
+	dataBody := make(map[string]interface{}, 0)
93
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
94
+	if err != nil {
95
+		utils.ErrorLog(err.Error())
96
+		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数错误")
97
+		return
98
+	}
99
+
100
+	mobile := this.GetString("telephone")
101
+	fmt.Println("phone", mobile)
102
+	admin, _ := patient_service.GetCreatorId(mobile)
103
+	org, _ := patient_service.GetOrgId(admin.ID)
104
+	var orgID = org.ID
105
+	fmt.Println("orgID是什么", orgID)
106
+	//基本信息
107
+	name := dataBody["name"].(string)
108
+	fmt.Println("病人姓名", name)
109
+	sex := int64(dataBody["sex"].(float64))
110
+	fmt.Println("性别", sex)
111
+	idcard := dataBody["idCard"].(string)
112
+	fmt.Println("idcard", idcard)
113
+
114
+	//manage_service.GetIdCardInfo(idcard)
115
+	birthday := dataBody["birthday"].(string)
116
+	births := strings.Split(birthday, "-")
117
+	birYear, _ := strconv.Atoi(births[0])
118
+	age := time.Now().Year() - birYear
119
+	ages := int64(age)
120
+	fmt.Println("age是多少", ages)
121
+	fmt.Println("birthday", birthday)
122
+	timeLayout := "2006-01-02 15:04:05"
123
+	theTime, err := utils.ParseTimeStringToTime(timeLayout, birthday+" 00:00:00")
124
+	birth := theTime.Unix()
125
+	fmt.Println("出生日期", birth)
126
+	phone := dataBody["phone"].(string)
127
+	fmt.Println("手机号", phone)
128
+	patientType := dataBody["patient_type"].([]interface{})
129
+	fmt.Println("病人类型", patientType)
130
+
131
+	//血透信息
132
+	dialysis := dataBody["dialysis"].(string)
133
+	fmt.Println("透析号", dialysis)
134
+	admissionNumber := dataBody["admissionNumber"].(string)
135
+	fmt.Println("住院门诊号", admissionNumber)
136
+	patientsoure := int64(dataBody["patientsoure"].(float64))
137
+	fmt.Println("患者来源", patientsoure)
138
+	lapseto := int64(dataBody["lapseto"].(float64))
139
+	fmt.Println("留置状态", lapseto)
140
+	contagions := dataBody["contagions"].([]interface{})
141
+	ids := make([]int64, 0)
142
+	for _, contagion := range contagions {
143
+		id := int64(contagion.(float64))
144
+		ids = append(ids, id)
145
+	}
146
+
147
+	fmt.Println("传染病", contagions)
148
+	fistdata := dataBody["fistDate"].(string)
149
+	fmt.Println("首次透析日期", fistdata)
150
+	times, err := utils.ParseTimeStringToTime(timeLayout, fistdata+"00:00:00")
151
+	fisttime := times.Unix()
152
+	fmt.Println("第一透析日期", fisttime)
153
+	diagnose := dataBody["diagnose"].(string)
154
+	fmt.Println("诊断", diagnose)
155
+	patientHead := dataBody["patientHead"].(string)
156
+	fmt.Println("患者头像", patientHead)
157
+
158
+	//慢病信息
159
+	requipmentid := dataBody["requipmentId"].(string)
160
+	fmt.Println("设备id", requipmentid)
161
+	slowcontagions := dataBody["slowcontagions"].([]interface{})
162
+	fmt.Println("传染病", slowcontagions)
163
+	slowPatients := dataBody["slowPatients"].([]interface{})
164
+	fmt.Println("slowPatients", slowPatients)
165
+
166
+	//会员信息
167
+	memberIllnessTime := dataBody["memberIllnessTime"].(string)
168
+	fmt.Println("会员患病时间", memberIllnessTime)
169
+
170
+	memberTime, err := utils.ParseTimeStringToTime(timeLayout, memberIllnessTime+" 00:00:00")
171
+	memberdata := memberTime.Unix()
172
+	fmt.Println("会员患病时间", memberdata)
173
+	memberlapseto := int64(dataBody["memberlapseto"].(float64))
174
+	fmt.Println("留治转台", memberlapseto)
175
+	treatementmethod := int64(dataBody["TreatmentMethod"].(float64))
176
+	fmt.Println("治疗方式", treatementmethod)
177
+
178
+	patients, errcode := manage_service.GetPatientInfoByIdCard(idcard, orgID)
179
+	fmt.Println("errcode", errcode)
180
+	fmt.Println("patients", patients)
181
+	if errcode == gorm.ErrRecordNotFound {
182
+		byPhone, err := manage_service.GetPatientInfoByPhone(phone, orgID)
183
+		fmt.Println("byphone", byPhone)
184
+		if err == gorm.ErrRecordNotFound {
185
+			bloodPatients := models.Patients{
186
+				Name:              name,
187
+				Gender:            sex,
188
+				IdCardNo:          idcard,
189
+				Birthday:          birth,
190
+				Phone:             phone,
191
+				DialysisNo:        dialysis,
192
+				Source:            patientsoure,
193
+				PatientType:       1,
194
+				Lapseto:           lapseto,
195
+				FirstDialysisDate: fisttime,
196
+				Diagnose:          diagnose,
197
+				Avatar:            patientHead,
198
+				Status:            1,
199
+				CreatedTime:       time.Now().Unix(),
200
+				UserOrgId:         orgID,
201
+				Age:               ages,
202
+			}
203
+			idtrs := make([]int64, 0)
204
+			for _, patienttype := range patientType {
205
+				id := int64(patienttype.(float64))
206
+				idtrs = append(idtrs, id)
207
+			}
208
+			err := manage_service.AddPatients(&bloodPatients)
209
+			patientss, _ := manage_service.GetLastData(orgID)
210
+			err = manage_service.AddPatientType(orgID, patientss.ID, idtrs)
211
+			fmt.Println("添加患者类型")
212
+			fmt.Println("错误是什么", err)
213
+			patients, err := manage_service.GetPatientLastData(orgID)
214
+			fmt.Println("错误", err)
215
+			fmt.Println("获取新增病人信息", patients)
216
+			err = manage_service.AddContagions(patients.ID, patients.CreatedTime, patients.UpdatedTime, ids)
217
+			fmt.Println("添加传染病失败", err)
218
+			this.ServeSuccessJSON(map[string]interface{}{
219
+				"bloodPatients": bloodPatients,
220
+				"patientss":     patientss,
221
+			})
222
+			fmt.Println("bloodPatients", bloodPatients)
223
+			fmt.Println("数据为空")
224
+		} else if errcode == nil {
225
+
226
+			this.ServeSuccessJSON(map[string]interface{}{
227
+				"msg": "ok",
228
+			})
229
+
230
+			return
231
+		}
232
+	} else if errcode == nil {
233
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加医院失败")
234
+		return
235
+
236
+	}
237
+
238
+}
239
+
240
+func (this *Manage) DeleteCouseManage() {
241
+	id, _ := this.GetInt64("id")
242
+	fmt.Println("id", id)
243
+	orgid, _ := this.GetInt64("orgid")
244
+	fmt.Println("orgid", orgid)
245
+	err := manage_service.DeleteCouseManage(id, orgid)
246
+	fmt.Println("错误是什么", err)
247
+	returnData := make(map[string]interface{}, 0)
248
+	returnData["msg"] = "ok"
249
+	this.ServeSuccessJSON(returnData)
250
+	return
251
+
252
+}
253
+
254
+func (this *Manage) GetMissionInformation() {
255
+	patientid, _ := this.GetInt64("patientid")
256
+	fmt.Println("patientid", patientid)
257
+	orgid, _ := this.GetInt64("orgid")
258
+	fmt.Println("orgid是什么", orgid)
259
+	startime := this.GetString("startime")
260
+	fmt.Println("startime", startime)
261
+	endtime := this.GetString("endtime")
262
+	fmt.Println("endtime", endtime)
263
+	timeLayout := "2006-01-02 15:04:05"
264
+	theTime, _ := utils.ParseTimeStringToTime(timeLayout, startime+" 00:00:00")
265
+	star := theTime.Unix()
266
+	fmt.Println("star", star)
267
+	toTime, _ := utils.ParseTimeStringToTime(timeLayout, endtime+" 00:00:00")
268
+	end := toTime.Unix()
269
+	fmt.Println("end", end)
270
+	treatment, err := manage_service.GetMissionInforMation(patientid, orgid, star, end)
271
+	patients, _ := login_service.GetPatintsInfo(patientid, orgid)
272
+	fmt.Println("patients", patients)
273
+	infectious, err := patient_service.GetPatientInfectious(patientid)
274
+	if err != nil {
275
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加医院失败")
276
+		return
277
+	}
278
+	this.ServeSuccessJSON(map[string]interface{}{
279
+		"treatment":  treatment,
280
+		"patients":   patients,
281
+		"infectious": infectious,
282
+	})
283
+}
284
+
285
+func (this *Manage) GetRecordSave() {
286
+	patientid, _ := this.GetInt64("patientid")
287
+	fmt.Println("patientid", patientid)
288
+	orgid, _ := this.GetInt64("orgid")
289
+	fmt.Println("orgid", orgid)
290
+	startime := this.GetString("startime")
291
+	fmt.Println("startime", startime)
292
+	timeLayout := "2006-01-02 15:04:05"
293
+	theTime, _ := utils.ParseTimeStringToTime(timeLayout, startime+" 00:00:00")
294
+	startimes := theTime.Unix()
295
+	fmt.Println("startimes", startimes)
296
+	endtime := this.GetString("endtime")
297
+	endTimeYMDHmsStr := endtime + " 23:59:59"
298
+	endTime, _ := utils.ParseTimeStringToTime("2006-01-02 15:04:05", endTimeYMDHmsStr)
299
+	patients, _ := login_service.GetPatintsInfo(patientid, orgid)
300
+	fmt.Println("paptients", patients)
301
+	infectious, err := patient_service.GetPatientInfectious(patientid)
302
+	record, err := manage_service.GetRecordServe(patientid, orgid, startimes, endTime.Unix())
303
+	if err != nil {
304
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加医院失败")
305
+		return
306
+	}
307
+	this.ServeSuccessJSON(map[string]interface{}{
308
+		"record":     record,
309
+		"patients":   patients,
310
+		"infectious": infectious,
311
+	})
312
+}
313
+
314
+func (this *Manage) GetCheckPatientData() {
315
+	patientid, _ := this.GetInt64("patientid")
316
+	fmt.Println("patientid", patientid)
317
+	orgid, _ := this.GetInt64("orgid")
318
+	fmt.Println("orgid", orgid)
319
+	startime := this.GetString("startime")
320
+	fmt.Println("startime", startime)
321
+	timeLayout := "2006-01-02 15:04:05"
322
+	theTime, _ := utils.ParseTimeStringToTime(timeLayout, startime+" 00:00:00")
323
+	startimes := theTime.Unix()
324
+	fmt.Println("startimes", startimes)
325
+	endtime := this.GetString("endtime")
326
+	fmt.Println("endtime是什么", endtime)
327
+	theTimes, _ := utils.ParseTimeStringToTime(timeLayout, endtime+" 00:00:00")
328
+	endtimes := theTimes.Unix()
329
+	fmt.Println("endtime", endtimes)
330
+	checkpatientdata, err := patient_service.GetCheckPatientData(patientid, orgid, startimes, endtimes)
331
+	//for _, check := range checkpatientdata {
332
+	//  Checkdata, _ := patient_service.GetCheckData(check.InspectDate, patientid, orgid)
333
+	//  this.ServeSuccessJSON(map[string]interface{}{
334
+	//    "checkdata":Checkdata,
335
+	//  })
336
+	//}
337
+	if err != nil {
338
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加医院失败")
339
+		return
340
+	}
341
+	this.ServeSuccessJSON(map[string]interface{}{
342
+		"checkpatientdata": checkpatientdata,
343
+	})
344
+}
345
+
346
+func (this *Manage) GetLongDialysis() {
347
+	patientid, _ := this.GetInt64("patientid")
348
+	fmt.Println("patientid", patientid)
349
+	orgid, _ := this.GetInt64("orgid")
350
+	fmt.Println("orgid", orgid)
351
+	startime := this.GetString("startime")
352
+	fmt.Println("startime", startime)
353
+	timeLayout := "2006-01-02 15:04:05"
354
+	theTime, _ := utils.ParseTimeStringToTime(timeLayout, startime+" 00:00:00")
355
+	startimes := theTime.Unix()
356
+	fmt.Println("startimes", startimes)
357
+	endtime := this.GetString("endtime")
358
+	fmt.Println("endtime是什么", endtime)
359
+	theTimes, _ := utils.ParseTimeStringToTime(timeLayout, endtime+" 00:00:00")
360
+	endtimes := theTimes.Unix()
361
+	fmt.Println("endtime", endtimes)
362
+	patients, err := login_service.GetPatintsInfo(patientid, orgid)
363
+	dialysis, err := manage_service.GetLongDialysisData(patientid, orgid, startimes, endtimes)
364
+	if err != nil {
365
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加医院失败")
366
+		return
367
+	}
368
+	this.ServeSuccessJSON(map[string]interface{}{
369
+		"patients": patients,
370
+		"dialysis": dialysis,
371
+	})
372
+}
373
+
374
+func (this *Manage) GetDialysRecord() {
375
+	patientid, _ := this.GetInt64("patientid")
376
+	fmt.Println("patientid", patientid)
377
+	orgid, _ := this.GetInt64("orgid")
378
+	fmt.Println("orgid", orgid)
379
+	startime := this.GetString("startime")
380
+	fmt.Println("startime", startime)
381
+	timeLayout := "2006-01-02 15:04:05"
382
+	theTime, _ := utils.ParseTimeStringToTime(timeLayout, startime+" 00:00:00")
383
+	startimes := theTime.Unix()
384
+	fmt.Println("startimes", startimes)
385
+	endtime := this.GetString("endtime")
386
+	fmt.Println("endtime是什么", endtime)
387
+	theTimes, _ := utils.ParseTimeStringToTime(timeLayout, endtime+" 00:00:00")
388
+	endtimes := theTimes.Unix()
389
+	fmt.Println("endtime", endtimes)
390
+	patients, err := login_service.GetPatintsInfo(patientid, orgid)
391
+	dialysisOrder, err := manage_service.GetDialysReCord(patientid, orgid, startimes, endtimes)
392
+	if err != nil {
393
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加医院失败")
394
+		return
395
+	}
396
+	this.ServeSuccessJSON(map[string]interface{}{
397
+		"dialysisOrder": dialysisOrder,
398
+		"patients":      patients,
399
+	})
400
+}
401
+
402
+func (this *Manage) ToSeacherCourseManagement() {
403
+	patientid, _ := this.GetInt64("patientid")
404
+	fmt.Println("patientid", patientid)
405
+	orgid, _ := this.GetInt64("orgid")
406
+	fmt.Println("orgid是什么", orgid)
407
+	seacherval := this.GetString("seacherVal")
408
+	fmt.Println("seacherval", seacherval)
409
+	patientCourse, err := manage_service.ToSeacherCourseManagement(patientid, orgid, seacherval)
410
+	fmt.Println("patientCousrse是什么", patientCourse)
411
+	if err != nil {
412
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加医院失败")
413
+		return
414
+	}
415
+	this.ServeSuccessJSON(map[string]interface{}{
416
+		"patientCourse": patientCourse,
417
+	})
418
+}
419
+
420
+func (this *Manage) ToDeleteSaveRecord() {
421
+	id, _ := this.GetInt64("id")
422
+	fmt.Println("id", id)
423
+	err := manage_service.ToDeleteSaveRecord(id)
424
+	fmt.Println("错误", err)
425
+	returnData := make(map[string]interface{}, 0)
426
+	returnData["msg"] = "ok"
427
+	this.ServeSuccessJSON(returnData)
428
+	return
429
+}
430
+
431
+func (this *Manage) ToSeacherRecord() {
432
+	patientid, _ := this.GetInt64("patientid")
433
+	orgid, _ := this.GetInt64("orgid")
434
+	seacherVal := this.GetString("seacherVal")
435
+	record, err := manage_service.ToSeacherRecord(patientid, orgid, seacherVal)
436
+	if err != nil {
437
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "查询失败")
438
+		return
439
+	}
440
+	this.ServeSuccessJSON(map[string]interface{}{
441
+		"record": record,
442
+	})
443
+}
444
+
445
+func (this *Manage) DeleteMissionInformation() {
446
+	id, _ := this.GetInt64("id")
447
+	fmt.Println("id", id)
448
+	orgid, _ := this.GetInt64("orgid")
449
+	fmt.Println("orgid", orgid)
450
+	err := manage_service.DeletMissionInformation(id)
451
+	fmt.Println("err", err)
452
+	returnData := make(map[string]interface{}, 0)
453
+	returnData["msg"] = "ok"
454
+	this.ServeSuccessJSON(returnData)
455
+	return
456
+
457
+}
458
+
459
+func (this *Manage) ToSeacherMissionInformation() {
460
+	patientid, _ := this.GetInt64("patientid")
461
+	fmt.Println("patientid", patientid)
462
+	orgid, _ := this.GetInt64("orgid")
463
+	fmt.Println("orgid", orgid)
464
+	seacherval := this.GetString("seacherVal")
465
+	fmt.Println("seacherval", seacherval)
466
+	treat, err := manage_service.ToSeacherMissionInformation(patientid, orgid, seacherval)
467
+	if err != nil {
468
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加医院失败")
469
+		return
470
+	}
471
+	this.ServeSuccessJSON(map[string]interface{}{
472
+		"treat": treat,
473
+	})
474
+}
475
+
476
+func (this *Manage) GetPatientSchedules() {
477
+	patientid, _ := this.GetInt64("patientid")
478
+	fmt.Println("patientid", patientid)
479
+	orgid, _ := this.GetInt64("orgid")
480
+	fmt.Println("orgid", orgid)
481
+	startime := this.GetString("startime")
482
+	fmt.Println("startime", startime)
483
+	timeLayout := "2006-01-02 15:04:05"
484
+	theTime, _ := utils.ParseTimeStringToTime(timeLayout, startime+" 00:00:00")
485
+	startimes := theTime.Unix()
486
+	fmt.Println("startimes", startimes)
487
+	endtime := this.GetString("endtime")
488
+	toTime, _ := utils.ParseTimeStringToTime(timeLayout, endtime+" 00:00:00")
489
+	endtimes := toTime.Unix()
490
+	fmt.Println("endtimes", endtimes)
491
+	schedules, err := manage_service.GetPatientSchedules(patientid, orgid, startimes, endtimes)
492
+	patients, _ := login_service.GetPatintsInfo(patientid, orgid)
493
+	infectious, err := patient_service.GetPatientInfectious(patientid)
494
+	fmt.Println("err", err)
495
+	fmt.Println("schedules", schedules)
496
+	if err != nil {
497
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加医院失败")
498
+		return
499
+	}
500
+	this.ServeSuccessJSON(map[string]interface{}{
501
+		"schedules":  schedules,
502
+		"patients":   patients,
503
+		"infectious": infectious,
504
+	})
505
+}
506
+
507
+func (this *Manage) DeleteScheduleinformation() {
508
+	id, _ := this.GetInt64("id")
509
+	err := manage_service.DeleteScheduleinformationById(id)
510
+	fmt.Println("错误是什么", err)
511
+	if err != nil {
512
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "删除排班失败")
513
+		return
514
+	}
515
+	returnData := make(map[string]interface{}, 0)
516
+	returnData["msg"] = "ok"
517
+	this.ServeSuccessJSON(returnData)
518
+	return
519
+}
520
+
521
+func (this *Manage) ToSeacherScheduleInformation() {
522
+	patientid, _ := this.GetInt64("patientid")
523
+	fmt.Println("patientid", patientid)
524
+	orgid, _ := this.GetInt64("orgid")
525
+	fmt.Println("orgid", orgid)
526
+	seacherval := this.GetString("seacherVal")
527
+	fmt.Println("seacherval", seacherval)
528
+	schedules, err := manage_service.ToSeacherSheduleinformation(patientid, orgid, seacherval)
529
+	if err != nil {
530
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加医院失败")
531
+		return
532
+	}
533
+	this.ServeSuccessJSON(map[string]interface{}{
534
+		"schedules": schedules,
535
+	})
536
+}
537
+
538
+func (this *Manage) GetPatientType() {
539
+	patientid, _ := this.GetInt64("patientid")
540
+	fmt.Println("paitentid", patientid)
541
+	orgid, _ := this.GetInt64("orgid")
542
+	fmt.Println("orgid", orgid)
543
+	patientType, err := manage_service.GetPaitentType(patientid, orgid)
544
+	if err != nil {
545
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "添加医院失败")
546
+		return
547
+	}
548
+	this.ServeSuccessJSON(map[string]interface{}{
549
+		"patientType": patientType,
550
+	})
551
+}
552
+
553
+func (this *Manage) GetCheckall() {
554
+	checkdate, _ := this.GetInt64("checkdate")
555
+	fmt.Print("checkdate", checkdate)
556
+	patientid, _ := this.GetInt64("patientid")
557
+	fmt.Print("patientid", patientid)
558
+	orgid, _ := this.GetInt64("orgid")
559
+	fmt.Print("org", orgid)
560
+	checkdata, err := patient_service.GetCheckData(checkdate, patientid, orgid)
561
+	if err != nil {
562
+		this.ServeFailJsonSend(enums.ErrorCodeDataException, "查询失败")
563
+		return
564
+	}
565
+	this.ServeSuccessJSON(map[string]interface{}{
566
+		"checkdata": checkdata,
567
+	})
568
+
569
+}

+ 6 - 0
controllers/manage/router_conllector.go Parādīt failu

@@ -0,0 +1,6 @@
1
+package manage
2
+
3
+func ManageRegisterRouter() {
4
+
5
+	ManageRouter()
6
+}

+ 24 - 0
controllers/patient/patient_controller.go Parādīt failu

@@ -0,0 +1,24 @@
1
+package patient
2
+
3
+import (
4
+	"KYA/controllers"
5
+	"KYA/enums"
6
+)
7
+
8
+func PatientRouter() {
9
+
10
+}
11
+
12
+type PatientMangement struct {
13
+	controllers.BaseAPIController
14
+}
15
+
16
+func (this *PatientMangement) ServeFailJsonSend(code int, msg string) {
17
+	this.Data["json"] = enums.MakeFailResponseJSON(msg, code)
18
+	this.ServeJSON()
19
+}
20
+
21
+func (this *PatientMangement) ServeSuccessJSON(data map[string]interface{}) {
22
+	this.Data["json"] = enums.MakeSuccessResponseJSON(data)
23
+	this.ServeJSONP()
24
+}

+ 6 - 0
controllers/patient/router_conllector.go Parādīt failu

@@ -0,0 +1,6 @@
1
+package patient
2
+
3
+func PatientRegisterRouter() {
4
+
5
+	PatientRouter()
6
+}

+ 171 - 0
enums/error_code.go Parādīt failu

@@ -0,0 +1,171 @@
1
+package enums
2
+
3
+import "KYA/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
+}

+ 45 - 0
jobcron/qiliu_job.go Parādīt failu

@@ -0,0 +1,45 @@
1
+package jobcron
2
+
3
+import (
4
+	"KYA/service/login_service"
5
+	"fmt"
6
+	"github.com/astaxie/beego"
7
+	"github.com/qiniu/api.v7/auth/qbox"
8
+	"github.com/qiniu/api.v7/storage"
9
+	"github.com/robfig/cron"
10
+)
11
+
12
+var qnTokenCronJob *cron.Cron
13
+
14
+func init() {
15
+	qnTokenCronJob := cron.New()
16
+	qnTokenCronJob.AddFunc("@every 1h50m", func() {
17
+		go RequestQNToken()
18
+	})
19
+}
20
+func RequestQNToken() {
21
+	accessKey := beego.AppConfig.String("qiniu_accesskey")
22
+	fmt.Println("accessKey", accessKey)
23
+	secretKey := beego.AppConfig.String("qiniu_secretkey")
24
+	fmt.Println("secretKey", 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
+	fmt.Println("mac", mac)
35
+	upToken := putPolicy.UploadToken(mac)
36
+	fmt.Println("new qiniu upToken", upToken)
37
+	redisClient := login_service.RedisClient()
38
+	defer redisClient.Close()
39
+	redisClient.Set("qn_token", upToken, 0)
40
+}
41
+
42
+func BeginRerequestTwoQNTokenCronJob() {
43
+	fmt.Println("七牛开始啦")
44
+	//qnTokenCronJob.Start()
45
+}

+ 22 - 0
main.go Parādīt failu

@@ -0,0 +1,22 @@
1
+package main
2
+
3
+import (
4
+	"KYA/jobcron"
5
+	_ "KYA/routers"
6
+	"KYA/service"
7
+	"github.com/astaxie/beego"
8
+)
9
+
10
+func init() {
11
+	service.ConnectDB()
12
+}
13
+
14
+func main() {
15
+	go func() {
16
+
17
+	}()
18
+	go jobcron.RequestQNToken()
19
+	jobcron.BeginRerequestTwoQNTokenCronJob()
20
+	beego.Run()
21
+
22
+}

+ 69 - 0
models/admin_user_model.go Parādīt failu

@@ -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
+)

+ 734 - 0
models/login_model.go Parādīt failu

@@ -0,0 +1,734 @@
1
+package models
2
+
3
+import "time"
4
+
5
+type SgjUserAdmin struct {
6
+	ID           int64  `gorm:"column:id" json:"id" form:"id"`
7
+	Mobile       string `gorm:"column:mobile" json:"mobile" form:"mobile"`
8
+	Password     string `gorm:"column:password" json:"password" form:"password"`
9
+	IsSuperAdmin int64  `gorm:"column:is_super_admin" json:"is_super_admin" form:"is_super_admin"`
10
+	Status       int64  `gorm:"column:status" json:"status" form:"status"`
11
+	Ctime        int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
12
+	Mtime        int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
13
+	Source       int64  `gorm:"column:source" json:"source" form:"source"`
14
+	Ttype        int64  `gorm:"column:ttype" json:"ttype" form:"ttype"`
15
+	Ttid         int64  `gorm:"column:ttid" json:"ttid" form:"ttid"`
16
+	Tuid         int64  `gorm:"column:tuid" json:"tuid" form:"tuid"`
17
+}
18
+
19
+func (SgjUserAdmin) TableName() string {
20
+	return "sgj_user_admin"
21
+}
22
+
23
+type SgjPatientArticles struct {
24
+	ID            int64  `gorm:"column:id" json:"id" form:"id"`
25
+	Title         string `gorm:"column:title" json:"title" form:"title"`
26
+	Summary       string `gorm:"column:summary" json:"summary" form:"summary"`
27
+	Content       string `gorm:"column:content" json:"content" form:"content"`
28
+	Type          int64  `gorm:"column:type" json:"type" form:"type"`
29
+	Num           int64  `gorm:"column:num" json:"num" form:"num"`
30
+	Mtime         int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
31
+	RealReadNum   int64  `gorm:"column:real_read_num" json:"real_read_num" form:"real_read_num"`
32
+	Ctime         int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
33
+	ClassId       int64  `gorm:"column:class_id" json:"class_id" form:"class_id"`
34
+	Author        string `gorm:"column:author" json:"author" form:"author"`
35
+	Status        int64  `gorm:"column:status" json:"status" form:"status"`
36
+	Reason        string `gorm:"column:reason" json:"reason" form:"reason"`
37
+	StarNum       int64  `gorm:"column:star_num" json:"star_num" form:"star_num"`
38
+	CommentNum    int64  `gorm:"column:comment_num" json:"comment_num" form:"comment_num"`
39
+	UserOrgId     int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
40
+	ArticleStatus int64  `gorm:"column:article_status" json:"article_status" form:"article_status"`
41
+	Imgs          string `gorm:"column:imgs" json:"imgs" form:"imgs"`
42
+	VideoUrl      string `gorm:"column:video_url" json:"video_url" form:"video_url"`
43
+	Source        int64  `gorm:"column:source" json:"source" form:"source"`
44
+	CategoryId    int64  `gorm:"column:category_id" json:"category_id" form:"category_id"`
45
+	Ttid          int64  `gorm:"column:ttid" json:"ttid" form:"ttid"`
46
+	Ttype         int64  `gorm:"column:ttype" json:"ttype" form:"ttype"`
47
+	Toid          int64  `gorm:"column:toid" json:"toid" form:"toid"`
48
+}
49
+
50
+func (SgjPatientArticles) TableName() string {
51
+	return "sgj_patient_articles"
52
+}
53
+
54
+type SgjUserDistrict struct {
55
+	ID        int64  `gorm:"column:id" json:"id" form:"id"`
56
+	Name      string `gorm:"column:name" json:"name" form:"name"`
57
+	Level     int64  `gorm:"column:level" json:"level" form:"level"`
58
+	Upid      int64  `gorm:"column:upid" json:"upid" form:"upid"`
59
+	Path      string `gorm:"column:path" json:"path" form:"path"`
60
+	Namepath  string `gorm:"column:namepath" json:"namepath" form:"namepath"`
61
+	Initial   string `gorm:"column:initial" json:"initial" form:"initial"`
62
+	Longitude string `gorm:"column:longitude" json:"longitude" form:"longitude"`
63
+	Latitude  string `gorm:"column:latitude" json:"latitude" form:"latitude"`
64
+	Adcode    int64  `gorm:"column:adcode" json:"adcode" form:"adcode"`
65
+}
66
+
67
+func (SgjUserDistrict) TableName() string {
68
+
69
+	return "sgj_user_district"
70
+
71
+}
72
+
73
+type SgjUserOrg struct {
74
+	ID              int64   `gorm:"column:id" json:"id" form:"id"`
75
+	Creator         int64   `gorm:"column:creator" json:"creator" form:"creator"`
76
+	OrgName         string  `gorm:"column:org_name" json:"org_name" form:"org_name"`
77
+	OrgShortName    string  `gorm:"column:org_short_name" json:"org_short_name" form:"org_short_name"`
78
+	OrgLogo         string  `gorm:"column:org_logo" json:"org_logo" form:"org_logo"`
79
+	OrgIntroduction string  `gorm:"column:org_introduction" json:"org_introduction" form:"org_introduction"`
80
+	Illness         string  `gorm:"column:illness" json:"illness" form:"illness"`
81
+	Province        int64   `gorm:"column:province" json:"province" form:"province"`
82
+	City            int64   `gorm:"column:city" json:"city" form:"city"`
83
+	District        int64   `gorm:"column:district" json:"district" form:"district"`
84
+	Address         string  `gorm:"column:address" json:"address" form:"address"`
85
+	Longitude       string  `gorm:"column:longitude" json:"longitude" form:"longitude"`
86
+	Latitude        string  `gorm:"column:latitude" json:"latitude" form:"latitude"`
87
+	OrgType         int64   `gorm:"column:org_type" json:"org_type" form:"org_type"`
88
+	Comments        int64   `gorm:"column:comments" json:"comments" form:"comments"`
89
+	Evaluate        float64 `gorm:"column:evaluate" json:"evaluate" form:"evaluate"`
90
+	Gallery         string  `gorm:"column:gallery" json:"gallery" form:"gallery"`
91
+	BusinessWeek    string  `gorm:"column:business_week" json:"business_week" form:"business_week"`
92
+	BusinessTime    string  `gorm:"column:business_time" json:"business_time" form:"business_time"`
93
+	ContactName     string  `gorm:"column:contact_name" json:"contact_name" form:"contact_name"`
94
+	Telephone       string  `gorm:"column:telephone" json:"telephone" form:"telephone"`
95
+	Claim           int64   `gorm:"column:claim" json:"claim" form:"claim"`
96
+	OperatingState  int64   `gorm:"column:operating_state" json:"operating_state" form:"operating_state"`
97
+	Status          int64   `gorm:"column:status" json:"status" form:"status"`
98
+	Ctime           int64   `gorm:"column:ctime" json:"ctime" form:"ctime"`
99
+	Mtime           int64   `gorm:"column:mtime" json:"mtime" form:"mtime"`
100
+	Source          int64   `gorm:"column:source" json:"source" form:"source"`
101
+	Ttype           int64   `gorm:"column:ttype" json:"ttype" form:"ttype"`
102
+	Ttid            int64   `gorm:"column:ttid" json:"ttid" form:"ttid"`
103
+	Tuid            int64   `gorm:"column:tuid" json:"tuid" form:"tuid"`
104
+	Reason          string  `gorm:"column:reason" json:"reason" form:"reason"`
105
+	Level           int64   `gorm:"column:level" json:"level" form:"level"`
106
+	Website         string  `gorm:"column:website" json:"website" form:"website"`
107
+	Import          int64   `gorm:"column:import" json:"import" form:"import"`
108
+	Sortno          int64   `gorm:"column:sortno" json:"sortno" form:"sortno"`
109
+}
110
+
111
+func (SgjUserOrg) TableName() string {
112
+
113
+	return "sgj_user_org"
114
+
115
+}
116
+
117
+type SgjUserOrgType struct {
118
+	ID          int64  `gorm:"column:id" json:"id" form:"id"`
119
+	Name        string `gorm:"column:name" json:"name" form:"name"`
120
+	ShortName   string `gorm:"column:short_name" json:"short_name" form:"short_name"`
121
+	Pid         int64  `gorm:"column:pid" json:"pid" form:"pid"`
122
+	Status      int64  `gorm:"column:status" json:"status" form:"status"`
123
+	CreatedTime int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
124
+	UpdatedTime int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
125
+	SortNo      int64  `gorm:"column:sort_no" json:"sort_no" form:"sort_no"`
126
+}
127
+
128
+func (SgjUserOrgType) TableName() string {
129
+
130
+	return "sgj_user_org_type"
131
+}
132
+
133
+type Patients struct {
134
+	ID                           int64   `gorm:"column:id" json:"id" form:"id"`
135
+	UserOrgId                    int64   `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
136
+	UserId                       int64   `gorm:"column:user_id" json:"user_id" form:"user_id"`
137
+	Avatar                       string  `gorm:"column:avatar" json:"avatar" form:"avatar"`
138
+	PatientType                  int64   `gorm:"column:patient_type" json:"patient_type" form:"patient_type"`
139
+	DialysisNo                   string  `gorm:"column:dialysis_no" json:"dialysis_no" form:"dialysis_no"`
140
+	AdmissionNumber              string  `gorm:"column:admission_number" json:"admission_number" form:"admission_number"`
141
+	Source                       int64   `gorm:"column:source" json:"source" form:"source"`
142
+	Lapseto                      int64   `gorm:"column:lapseto" json:"lapseto" form:"lapseto"`
143
+	PartitionId                  int64   `gorm:"column:partition_id" json:"partition_id" form:"partition_id"`
144
+	BedId                        int64   `gorm:"column:bed_id" json:"bed_id" form:"bed_id"`
145
+	Name                         string  `gorm:"column:name" json:"name" form:"name"`
146
+	Alias                        string  `gorm:"column:alias" json:"alias" form:"alias"`
147
+	Gender                       int64   `gorm:"column:gender" json:"gender" form:"gender"`
148
+	MaritalStatus                int64   `gorm:"column:marital_status" json:"marital_status" form:"marital_status"`
149
+	IdCardNo                     string  `gorm:"column:id_card_no" json:"id_card_no" form:"id_card_no"`
150
+	Birthday                     int64   `gorm:"column:birthday" json:"birthday" form:"birthday"`
151
+	ReimbursementWayId           int64   `gorm:"column:reimbursement_way_id" json:"reimbursement_way_id" form:"reimbursement_way_id"`
152
+	HealthCareType               int64   `gorm:"column:health_care_type" json:"health_care_type" form:"health_care_type"`
153
+	HealthCareNo                 string  `gorm:"column:health_care_no" json:"health_care_no" form:"health_care_no"`
154
+	HealthCareDueDate            int64   `gorm:"column:health_care_due_date" json:"health_care_due_date" form:"health_care_due_date"`
155
+	Height                       int64   `gorm:"column:height" json:"height" form:"height"`
156
+	BloodType                    int64   `gorm:"column:blood_type" json:"blood_type" form:"blood_type"`
157
+	Rh                           int64   `gorm:"column:rh" json:"rh" form:"rh"`
158
+	HealthCareDueAlertDate       int64   `gorm:"column:health_care_due_alert_date" json:"health_care_due_alert_date" form:"health_care_due_alert_date"`
159
+	EducationLevel               int64   `gorm:"column:education_level" json:"education_level" form:"education_level"`
160
+	Profession                   int64   `gorm:"column:profession" json:"profession" form:"profession"`
161
+	Phone                        string  `gorm:"column:phone" json:"phone" form:"phone"`
162
+	HomeTelephone                string  `gorm:"column:home_telephone" json:"home_telephone" form:"home_telephone"`
163
+	RelativePhone                string  `gorm:"column:relative_phone" json:"relative_phone" form:"relative_phone"`
164
+	RelativeRelations            string  `gorm:"column:relative_relations" json:"relative_relations" form:"relative_relations"`
165
+	HomeAddress                  string  `gorm:"column:home_address" json:"home_address" form:"home_address"`
166
+	WorkUnit                     string  `gorm:"column:work_unit" json:"work_unit" form:"work_unit"`
167
+	UnitAddress                  string  `gorm:"column:unit_address" json:"unit_address" form:"unit_address"`
168
+	Children                     int64   `gorm:"column:children" json:"children" form:"children"`
169
+	ReceivingDate                int64   `gorm:"column:receiving_date" json:"receiving_date" form:"receiving_date"`
170
+	IsHospitalFirstDialysis      int64   `gorm:"column:is_hospital_first_dialysis" json:"is_hospital_first_dialysis" form:"is_hospital_first_dialysis"`
171
+	FirstDialysisDate            int64   `gorm:"column:first_dialysis_date" json:"first_dialysis_date" form:"first_dialysis_date"`
172
+	FirstDialysisHospital        string  `gorm:"column:first_dialysis_hospital" json:"first_dialysis_hospital" form:"first_dialysis_hospital"`
173
+	PredialysisCondition         string  `gorm:"column:predialysis_condition" json:"predialysis_condition" form:"predialysis_condition"`
174
+	PreHospitalDialysisFrequency string  `gorm:"column:pre_hospital_dialysis_frequency" json:"pre_hospital_dialysis_frequency" form:"pre_hospital_dialysis_frequency"`
175
+	PreHospitalDialysisTimes     int64   `gorm:"column:pre_hospital_dialysis_times" json:"pre_hospital_dialysis_times" form:"pre_hospital_dialysis_times"`
176
+	HospitalFirstDialysisDate    int64   `gorm:"column:hospital_first_dialysis_date" json:"hospital_first_dialysis_date" form:"hospital_first_dialysis_date"`
177
+	InductionPeriod              int64   `gorm:"column:induction_period" json:"induction_period" form:"induction_period"`
178
+	InitialDialysis              int64   `gorm:"column:initial_dialysis" json:"initial_dialysis" form:"initial_dialysis"`
179
+	TotalDialysis                int64   `gorm:"column:total_dialysis" json:"total_dialysis" form:"total_dialysis"`
180
+	AttendingDoctorId            int64   `gorm:"column:attending_doctor_id" json:"attending_doctor_id" form:"attending_doctor_id"`
181
+	HeadNurseId                  int64   `gorm:"column:head_nurse_id" json:"head_nurse_id" form:"head_nurse_id"`
182
+	Evaluate                     string  `gorm:"column:evaluate" json:"evaluate" form:"evaluate"`
183
+	Diagnose                     string  `gorm:"column:diagnose" json:"diagnose" form:"diagnose"`
184
+	Remark                       string  `gorm:"column:remark" json:"remark" form:"remark"`
185
+	RegistrarsId                 int64   `gorm:"column:registrars_id" json:"registrars_id" form:"registrars_id"`
186
+	Registrars                   string  `gorm:"column:registrars" json:"registrars" form:"registrars"`
187
+	QrCode                       string  `gorm:"column:qr_code" json:"qr_code" form:"qr_code"`
188
+	BindingState                 int64   `gorm:"column:binding_state" json:"binding_state" form:"binding_state"`
189
+	PatientComplains             string  `gorm:"column:patient_complains" json:"patient_complains" form:"patient_complains"`
190
+	PresentHistory               string  `gorm:"column:present_history" json:"present_history" form:"present_history"`
191
+	PastHistory                  string  `gorm:"column:past_history" json:"past_history" form:"past_history"`
192
+	Temperature                  float64 `gorm:"column:temperature" json:"temperature" form:"temperature"`
193
+	Pulse                        int64   `gorm:"column:pulse" json:"pulse" form:"pulse"`
194
+	Respiratory                  int64   `gorm:"column:respiratory" json:"respiratory" form:"respiratory"`
195
+	Sbp                          int64   `gorm:"column:sbp" json:"sbp" form:"sbp"`
196
+	Dbp                          int64   `gorm:"column:dbp" json:"dbp" form:"dbp"`
197
+	Status                       int64   `gorm:"column:status" json:"status" form:"status"`
198
+	CreatedTime                  int64   `gorm:"column:created_time" json:"created_time" form:"created_time"`
199
+	UpdatedTime                  int64   `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
200
+	Nation                       string  `gorm:"column:nation" json:"nation" form:"nation"`
201
+	NativePlace                  string  `gorm:"column:native_place" json:"native_place" form:"native_place"`
202
+	Age                          int64   `gorm:"column:age" json:"age" form:"age"`
203
+}
204
+
205
+func (Patients) TableName() string {
206
+
207
+	return "xt_patients"
208
+}
209
+
210
+type DoctorAdvice struct {
211
+	ID                    int64   `gorm:"column:id" json:"id" form:"id"`
212
+	UserOrgId             int64   `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
213
+	PatientId             int64   `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
214
+	AdviceType            int64   `gorm:"column:advice_type" json:"advice_type" form:"advice_type"`
215
+	AdviceDate            int64   `gorm:"column:advice_date" json:"advice_date" form:"advice_date"`
216
+	StartTime             int64   `gorm:"column:start_time" json:"start_time" form:"start_time"`
217
+	AdviceName            string  `gorm:"column:advice_name" json:"advice_name" form:"advice_name"`
218
+	AdviceDesc            string  `gorm:"column:advice_desc" json:"advice_desc" form:"advice_desc"`
219
+	ReminderDate          int64   `gorm:"column:reminder_date" json:"reminder_date" form:"reminder_date"`
220
+	SingleDose            float64 `gorm:"column:single_dose" json:"single_dose" form:"single_dose"`
221
+	SingleDoseUnit        string  `gorm:"column:single_dose_unit" json:"single_dose_unit" form:"single_dose_unit"`
222
+	PrescribingNumber     float64 `gorm:"column:prescribing_number" json:"prescribing_number" form:"prescribing_number"`
223
+	PrescribingNumberUnit string  `gorm:"column:prescribing_number_unit" json:"prescribing_number_unit" form:"prescribing_number_unit"`
224
+	DeliveryWay           string  `gorm:"column:delivery_way" json:"delivery_way" form:"delivery_way"`
225
+	ExecutionFrequency    string  `gorm:"column:execution_frequency" json:"execution_frequency" form:"execution_frequency"`
226
+	AdviceDoctor          int64   `gorm:"column:advice_doctor" json:"advice_doctor" form:"advice_doctor"`
227
+	Status                int64   `gorm:"column:status" json:"status" form:"status"`
228
+	CreatedTime           int64   `gorm:"column:created_time" json:"created_time" form:"created_time"`
229
+	UpdatedTime           int64   `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
230
+	AdviceAffirm          string  `gorm:"column:advice_affirm" json:"advice_affirm" form:"advice_affirm"`
231
+	Remark                string  `gorm:"column:remark" json:"remark" form:"remark"`
232
+	StopTime              int64   `gorm:"column:stop_time" json:"stop_time" form:"stop_time"`
233
+	StopReason            string  `gorm:"column:stop_reason" json:"stop_reason" form:"stop_reason"`
234
+	StopDoctor            int64   `gorm:"column:stop_doctor" json:"stop_doctor" form:"stop_doctor"`
235
+	StopState             int64   `gorm:"column:stop_state" json:"stop_state" form:"stop_state"`
236
+	ParentId              int64   `gorm:"column:parent_id" json:"parent_id" form:"parent_id"`
237
+	ExecutionTime         int64   `gorm:"column:execution_time" json:"execution_time" form:"execution_time"`
238
+	ExecutionStaff        int64   `gorm:"column:execution_staff" json:"execution_staff" form:"execution_staff"`
239
+	ExecutionState        int64   `gorm:"column:execution_state" json:"execution_state" form:"execution_state"`
240
+	Checker               int64   `gorm:"column:checker" json:"checker" form:"checker"`
241
+	RecordDate            int64   `gorm:"column:record_date" json:"record_date" form:"record_date"`
242
+	DialysisOrderId       int64   `gorm:"column:dialysis_order_id" json:"dialysis_order_id" form:"dialysis_order_id"`
243
+	CheckTime             int64   `gorm:"column:check_time" json:"check_time" form:"check_time"`
244
+	CheckState            int64   `gorm:"column:check_state" json:"check_state" form:"check_state"`
245
+	DrugSpec              float64 `gorm:"column:drug_spec" json:"drug_spec" form:"drug_spec"`
246
+	DrugSpecUnit          string  `gorm:"column:drug_spec_unit" json:"drug_spec_unit" form:"drug_spec_unit"`
247
+	Groupno               int64   `gorm:"column:groupno" json:"groupno" form:"groupno"`
248
+}
249
+
250
+func (DoctorAdvice) TableName() string {
251
+
252
+	return "xt_doctor_advice"
253
+}
254
+
255
+type SMSBatch struct {
256
+	ID          int64  `gorm:"column:id"`
257
+	OrgID       int64  `gorm:"column:org_id"`          // 机构 ID
258
+	TemplateID  int64  `gorm:"column:sms_template_id"` // 对应短信平台上的模板 ID
259
+	Autograph   string // 短信签名
260
+	Params      string // 模板参数,以“,”隔开
261
+	FullContent string `gorm:"column:full_content"` // 完整短信内容
262
+	Mobiles     string // 接收手机号,以“,”隔开
263
+	SendTime    int64  `gorm:"column:send_time"` // 发送时间
264
+	Status      int8   // 状态: 1.待审核 2.审核未通过 3.未发送 4.已发送 5.发送失败
265
+	CreateTime  int64  `gorm:"column:ctime"` // 创建时间
266
+	ModifyTime  int64  `gorm:"column:mtime"` // 修改时间
267
+}
268
+
269
+func (SMSBatch) TableName() string {
270
+	return "sgj_patient_sms_batch"
271
+}
272
+
273
+type SMSSendStatus struct {
274
+	ID         int64  `gorm:"column:id"`
275
+	BatchID    int64  `gorm:"batch_id"` // 批次 ID,对应 SMSBatch.ID
276
+	Mobile     string // 接收手机号
277
+	Status     int8   // 发送结果状态: 0.失败 1.成功
278
+	Code       string // 短信平台返回的错误码
279
+	Msg        string // 短信平台返回的错误信息
280
+	CreateTime int64  `gorm:"column:ctime"` // 创建时间
281
+	ModifyTime int64  `gorm:"column:mtime"` // 修改时间
282
+}
283
+
284
+func (SMSSendStatus) TableName() string {
285
+	return "sgj_patient_sms_send_status"
286
+}
287
+
288
+type SMSTemplate struct {
289
+	ID           int64  `gorm:"column:id"`
290
+	TemplateType int8   `gorm:"column:template_type"` // 模板类型 1.默认模板 2.自定义模板
291
+	TemplateID   int64  `gorm:"column:template_id"`   // 短信平台上的模板 id
292
+	MessageType  int8   `gorm:"column:message_type"`  // 短信类型 1.通知短信 2.服务短信
293
+	Content      string // 模板内容
294
+	// ParamTypes   string `gorm:"column:param_types"` // 字段因业务没有采用默认模板的方式而弃用了!!!! 模板内容里的参数类型:1,2,3 。参数类型以逗号隔开,位置代表了参数‘{n+1}’,类型暂时有:1.用户名 2.商家简称 3.链接 4.商品名称 5.活动名称 6.验证码。(自定义模板是没有值的,因为它没有参数)
295
+	Autograph  string // 短信签名
296
+	OrgID      int64  `gorm:"column:org_id"` // 模板所属机构(自定义模板才有值)
297
+	Status     int8   // 模板状态 0.无效 1.有效 2.审核中
298
+	CreateTime int64  `gorm:"column:ctime"` // 创建时间
299
+	ModifyTime int64  `gorm:"column:mtime"` // 修改时间
300
+}
301
+
302
+func (SMSTemplate) TableName() string {
303
+	return "sgj_patient_sms_template"
304
+}
305
+
306
+const (
307
+	SMSBatchStatusInReview   = int8(1)
308
+	SMSBatchStatusUnapproved = int8(2)
309
+	SMSBatchStatusUnsend     = int8(3)
310
+	SMSBatchStatusDidSend    = int8(4)
311
+	SMSBatchStatusSendFailed = int8(5)
312
+	SMSBatchStatusSending    = int8(6)
313
+)
314
+
315
+type UserSMSFreeLimit struct {
316
+	ID         int64  `gorm:"column:id"`
317
+	OrgID      int64  `gorm:"column:org_id"`      // 机构 ID
318
+	TotalCount int    `gorm:"column:total_count"` // 免费额度,单位:条,下同
319
+	UsedCount  int    `gorm:"column:used_count"`  // 已用额度
320
+	ValidMonth string `gorm:"column:valid_month"` // 生效月份,格式:201804
321
+	Status     int8   // 状态 0.无效 1.有效
322
+	CreateTime int64  `gorm:"column:ctime"` // 创建时间
323
+	ModifyTime int64  `gorm:"column:mtime"` // 修改时间
324
+}
325
+
326
+func (UserSMSFreeLimit) TableName() string {
327
+	return "sgj_patient_user_sms_free_limit"
328
+}
329
+
330
+type PatientCourseOfDiseases struct {
331
+	ID         int64  `gorm:"column:id" json:"id" form:"id"`
332
+	OrgId      int64  `gorm:"column:org_id" json:"org_id" form:"org_id"`
333
+	PatientId  int64  `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
334
+	Recorder   int64  `gorm:"column:recorder" json:"recorder" form:"recorder"`
335
+	RecordTime int64  `gorm:"column:record_time" json:"record_time" form:"record_time"`
336
+	Content    string `gorm:"column:content" json:"content" form:"content"`
337
+	Status     int64  `gorm:"column:status" json:"status" form:"status"`
338
+	Ctime      int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
339
+	Mtime      int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
340
+	Title      string `gorm:"column:title" json:"title" form:"title"`
341
+	UserName   string `gorm:"column:user_name" json:"user_name" form:"user_name"`
342
+}
343
+
344
+type PatientCourseOfDisease struct {
345
+	ID         int64  `gorm:"column:id" json:"id" form:"id"`
346
+	OrgId      int64  `gorm:"column:org_id" json:"org_id" form:"org_id"`
347
+	PatientId  int64  `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
348
+	Recorder   int64  `gorm:"column:recorder" json:"recorder" form:"recorder"`
349
+	RecordTime int64  `gorm:"column:record_time" json:"record_time" form:"record_time"`
350
+	Content    string `gorm:"column:content" json:"content" form:"content"`
351
+	Status     int64  `gorm:"column:status" json:"status" form:"status"`
352
+	Ctime      int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
353
+	Mtime      int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
354
+	Title      string `gorm:"column:title" json:"title" form:"title"`
355
+}
356
+
357
+func (PatientCourseOfDisease) TableName() string {
358
+
359
+	return "xt_patient_course_of_disease"
360
+}
361
+
362
+//宣教信息
363
+type TreatmentSummary struct {
364
+	ID                int64  `gorm:"column:id" json:"id" form:"id"`
365
+	UserOrgId         int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
366
+	PatientId         int64  `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
367
+	AssessmentDate    int64  `gorm:"column:assessment_date" json:"assessment_date" form:"assessment_date"`
368
+	DialysisOrderId   int64  `gorm:"column:dialysis_order_id" json:"dialysis_order_id" form:"dialysis_order_id"`
369
+	Mission           string `gorm:"column:mission" json:"mission" form:"mission"`
370
+	DialysisSummary   string `gorm:"column:dialysis_summary" json:"dialysis_summary" form:"dialysis_summary"`
371
+	Change            int64  `gorm:"column:change" json:"change" form:"change"`
372
+	SjNurse           int64  `gorm:"column:sj_nurse" json:"sj_nurse" form:"sj_nurse"`
373
+	ZlNurse           int64  `gorm:"column:zl_nurse" json:"zl_nurse" form:"zl_nurse"`
374
+	HdNurse           int64  `gorm:"column:hd_nurse" json:"hd_nurse" form:"hd_nurse"`
375
+	XjNurse           int64  `gorm:"column:xj_nurse" json:"xj_nurse" form:"xj_nurse"`
376
+	ZlDoctor          int64  `gorm:"column:zl_doctor" json:"zl_doctor" form:"zl_doctor"`
377
+	ChannelImage      string `gorm:"column:channel_image" json:"channel_image" form:"channel_image"`
378
+	Puncture          string `gorm:"column:puncture" json:"puncture" form:"puncture"`
379
+	PunctureNeedle    string `gorm:"column:puncture_needle" json:"puncture_needle" form:"puncture_needle"`
380
+	PunctureDirection string `gorm:"column:puncture_direction" json:"puncture_direction" form:"puncture_direction"`
381
+	Status            int64  `gorm:"column:status" json:"status" form:"status"`
382
+	CreatedTime       int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
383
+	UpdatedTime       int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
384
+	Creater           int64  `gorm:"column:creater" json:"creater" form:"creater"`
385
+	Modifier          int64  `gorm:"column:modifier" json:"modifier" form:"modifier"`
386
+}
387
+
388
+func (TreatmentSummary) TableName() string {
389
+
390
+	return "xt_treatment_summary"
391
+}
392
+
393
+type UserOrgApp struct {
394
+	ID         int64 `gorm:"column:id" json:"id" form:"id"`
395
+	AppType    int64 `gorm:"column:app_type" json:"app_type" form:"app_type"`
396
+	Creator    int64 `gorm:"column:creator" json:"creator" form:"creator"`
397
+	OrgId      int64 `gorm:"column:org_id" json:"org_id" form:"org_id"`
398
+	OpenStatus int64 `gorm:"column:open_status" json:"open_status" form:"open_status"`
399
+	Status     int64 `gorm:"column:status" json:"status" form:"status"`
400
+	Ctime      int64 `gorm:"column:ctime" json:"ctime" form:"ctime"`
401
+	Mtime      int64 `gorm:"column:mtime" json:"mtime" form:"mtime"`
402
+}
403
+
404
+func (UserOrgApp) TableName() string {
405
+
406
+	return "sgj_user_org_app"
407
+}
408
+
409
+type UserRole struct {
410
+	ID               int64  `gorm:"column:id" json:"id" form:"id"`
411
+	RoleName         string `gorm:"column:role_name" json:"role_name" form:"role_name"`
412
+	RoleIntroduction string `gorm:"column:role_introduction" json:"role_introduction" form:"role_introduction"`
413
+	Creator          int64  `gorm:"column:creator" json:"creator" form:"creator"`
414
+	OrgId            int64  `gorm:"column:org_id" json:"org_id" form:"org_id"`
415
+	AppId            int64  `gorm:"column:app_id" json:"app_id" form:"app_id"`
416
+	IsSuperAdmin     int64  `gorm:"column:is_super_admin" json:"is_super_admin" form:"is_super_admin"`
417
+	Status           int64  `gorm:"column:status" json:"status" form:"status"`
418
+	Ctime            int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
419
+	Mtime            int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
420
+}
421
+
422
+func (UserRole) TableName() string {
423
+
424
+	return "sgj_user_role"
425
+}
426
+
427
+type UserAdminRole struct {
428
+	ID          int64  `gorm:"column:id" json:"id" form:"id"`
429
+	AdminUserId int64  `gorm:"column:admin_user_id" json:"admin_user_id" form:"admin_user_id"`
430
+	OrgId       int64  `gorm:"column:org_id" json:"org_id" form:"org_id"`
431
+	AppId       int64  `gorm:"column:app_id" json:"app_id" form:"app_id"`
432
+	RoleId      int64  `gorm:"column:role_id" json:"role_id" form:"role_id"`
433
+	UserName    string `gorm:"column:user_name" json:"user_name" form:"user_name"`
434
+	Avatar      string `gorm:"column:avatar" json:"avatar" form:"avatar"`
435
+	UserType    int64  `gorm:"column:user_type" json:"user_type" form:"user_type"`
436
+	UserTitle   int64  `gorm:"column:user_title" json:"user_title" form:"user_title"`
437
+	Intro       string `gorm:"column:intro" json:"intro" form:"intro"`
438
+	Status      int64  `gorm:"column:status" json:"status" form:"status"`
439
+	Ctime       int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
440
+	Mtime       int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
441
+}
442
+
443
+func (UserAdminRole) TableName() string {
444
+
445
+	return "sgj_user_admin_role"
446
+}
447
+
448
+type PatientRescueRecords struct {
449
+	ID         int64  `gorm:"column:id" json:"id" form:"id"`
450
+	OrgId      int64  `gorm:"column:org_id" json:"org_id" form:"org_id"`
451
+	PatientId  int64  `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
452
+	Recorder   int64  `gorm:"column:recorder" json:"recorder" form:"recorder"`
453
+	RecordTime int64  `gorm:"column:record_time" json:"record_time" form:"record_time"`
454
+	Content    string `gorm:"column:content" json:"content" form:"content"`
455
+	Status     int64  `gorm:"column:status" json:"status" form:"status"`
456
+	Ctime      int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
457
+	Mtime      int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
458
+	UserName   string `gorm:"column:user_name" json:"user_name" form:"user_name"`
459
+}
460
+
461
+type PatientRescueRecord struct {
462
+	ID         int64  `gorm:"column:id" json:"id" form:"id"`
463
+	OrgId      int64  `gorm:"column:org_id" json:"org_id" form:"org_id"`
464
+	PatientId  int64  `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
465
+	Recorder   int64  `gorm:"column:recorder" json:"recorder" form:"recorder"`
466
+	RecordTime int64  `gorm:"column:record_time" json:"record_time" form:"record_time"`
467
+	Content    string `gorm:"column:content" json:"content" form:"content"`
468
+	Status     int64  `gorm:"column:status" json:"status" form:"status"`
469
+	Ctime      int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
470
+	Mtime      int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
471
+}
472
+
473
+func (PatientRescueRecord) TableName() string {
474
+
475
+	return "xt_patient_rescue_record"
476
+}
477
+
478
+//长期处方
479
+type DialysisPrescription struct {
480
+	ID                         int64   `gorm:"column:id" json:"id" form:"id"`
481
+	UserOrgId                  int64   `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
482
+	PatientId                  int64   `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
483
+	Dialyzer                   int64   `gorm:"column:dialyzer" json:"dialyzer" form:"dialyzer"`
484
+	MachineType                string  `gorm:"column:machine_type" json:"machine_type" form:"machine_type"`
485
+	DewaterAmount              float64 `gorm:"column:dewater_amount" json:"dewater_amount" form:"dewater_amount"`
486
+	DialyzerPerfusionApparatus string  `gorm:"column:dialyzer_perfusion_apparatus" json:"dialyzer_perfusion_apparatus" form:"dialyzer_perfusion_apparatus"`
487
+	PrescriptionDewatering     float64 `gorm:"column:prescription_dewatering" json:"prescription_dewatering" form:"prescription_dewatering"`
488
+	Anticoagulant              int64   `gorm:"column:anticoagulant" json:"anticoagulant" form:"anticoagulant"`
489
+	AnticoagulantShouji        float64 `gorm:"column:anticoagulant_shouji" json:"anticoagulant_shouji" form:"anticoagulant_shouji"`
490
+	AnticoagulantWeichi        float64 `gorm:"column:anticoagulant_weichi" json:"anticoagulant_weichi" form:"anticoagulant_weichi"`
491
+	AnticoagulantZongliang     float64 `gorm:"column:anticoagulant_zongliang" json:"anticoagulant_zongliang" form:"anticoagulant_zongliang"`
492
+	AnticoagulantGaimingcheng  string  `gorm:"column:anticoagulant_gaimingcheng" json:"anticoagulant_gaimingcheng" form:"anticoagulant_gaimingcheng"`
493
+	AnticoagulantGaijiliang    string  `gorm:"column:anticoagulant_gaijiliang" json:"anticoagulant_gaijiliang" form:"anticoagulant_gaijiliang"`
494
+	ModeId                     int64   `gorm:"column:mode_id" json:"mode_id" form:"mode_id"`
495
+	DialysisDurationHour       int64   `gorm:"column:dialysis_duration_hour" json:"dialysis_duration_hour" form:"dialysis_duration_hour"`
496
+	DialysisDurationMinute     int64   `gorm:"column:dialysis_duration_minute" json:"dialysis_duration_minute" form:"dialysis_duration_minute"`
497
+	DialysisDuration           float64 `gorm:"column:dialysis_duration" json:"dialysis_duration" form:"dialysis_duration"`
498
+	ReplacementTotal           float64 `gorm:"column:replacement_total" json:"replacement_total" form:"replacement_total"`
499
+	ReplacementWay             int64   `gorm:"column:replacement_way" json:"replacement_way" form:"replacement_way"`
500
+	HemodialysisMachine        int64   `gorm:"column:hemodialysis_machine" json:"hemodialysis_machine" form:"hemodialysis_machine"`
501
+	BloodFilter                int64   `gorm:"column:blood_filter" json:"blood_filter" form:"blood_filter"`
502
+	PerfusionApparatus         int64   `gorm:"column:perfusion_apparatus" json:"perfusion_apparatus" form:"perfusion_apparatus"`
503
+	DryWeight                  float64 `gorm:"column:dry_weight" json:"dry_weight" form:"dry_weight"`
504
+	VascularAccessMode         int64   `gorm:"column:vascular_access_mode" json:"vascular_access_mode" form:"vascular_access_mode"`
505
+	VascularAccess             int64   `gorm:"column:vascular_access" json:"vascular_access" form:"vascular_access"`
506
+	BloodFlowVolume            float64 `gorm:"column:blood_flow_volume" json:"blood_flow_volume" form:"blood_flow_volume"`
507
+	DialysateFlow              float64 `gorm:"column:dialysate_flow" json:"dialysate_flow" form:"dialysate_flow"`
508
+	DisplaceLiqui              float64 `gorm:"column:displace_liqui" json:"displace_liqui" form:"displace_liqui"`
509
+	Kalium                     float64 `gorm:"column:kalium" json:"kalium" form:"kalium"`
510
+	Sodium                     float64 `gorm:"column:sodium" json:"sodium" form:"sodium"`
511
+	Calcium                    float64 `gorm:"column:calcium" json:"calcium" form:"calcium"`
512
+	Bicarbonate                float64 `gorm:"column:bicarbonate" json:"bicarbonate" form:"bicarbonate"`
513
+	Glucose                    float64 `gorm:"column:glucose" json:"glucose" form:"glucose"`
514
+	DialysateTemperature       float64 `gorm:"column:dialysate_temperature" json:"dialysate_temperature" form:"dialysate_temperature"`
515
+	Conductivity               float64 `gorm:"column:conductivity" json:"conductivity" form:"conductivity"`
516
+	PrescriptionDoctor         int64   `gorm:"column:prescription_doctor" json:"prescription_doctor" form:"prescription_doctor"`
517
+	Creater                    int64   `gorm:"column:creater" json:"creater" form:"creater"`
518
+	Modifier                   int64   `gorm:"column:modifier" json:"modifier" form:"modifier"`
519
+	Remark                     string  `gorm:"column:remark" json:"remark" form:"remark"`
520
+	Status                     int64   `gorm:"column:status" json:"status" form:"status"`
521
+	CreatedTime                int64   `gorm:"column:created_time" json:"created_time" form:"created_time"`
522
+	UpdatedTime                int64   `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
523
+	RecordDate                 int64   `gorm:"column:record_date" json:"record_date" form:"record_date"`
524
+	RecordId                   int64   `gorm:"column:record_id" json:"record_id" form:"record_id"`
525
+	TargetUltrafiltration      float64 `gorm:"column:target_ultrafiltration" json:"target_ultrafiltration" form:"target_ultrafiltration"`
526
+	DialysateFormulation       int64   `gorm:"column:dialysate_formulation" json:"dialysate_formulation" form:"dialysate_formulation"`
527
+	BodyFluid                  int64   `gorm:"column:body_fluid" json:"body_fluid" form:"body_fluid"`
528
+	SpecialMedicine            int64   `gorm:"column:special_medicine" json:"special_medicine" form:"special_medicine"`
529
+	SpecialMedicineOther       string  `gorm:"column:special_medicine_other" json:"special_medicine_other" form:"special_medicine_other"`
530
+	DisplaceLiquiPart          int64   `gorm:"column:displace_liqui_part" json:"displace_liqui_part" form:"displace_liqui_part"`
531
+	BloodAccess                int64   `gorm:"column:blood_access" json:"blood_access" form:"blood_access"`
532
+	DisplaceLiquiValue         float64 `gorm:"column:displace_liqui_value" json:"displace_liqui_value" form:"displace_liqui_value"`
533
+	Ultrafiltration            float64 `gorm:"column:ultrafiltration" json:"ultrafiltration" form:"ultrafiltration"`
534
+	BodyFluidOther             string  `gorm:"column:body_fluid_other" json:"body_fluid_other" form:"body_fluid_other"`
535
+	Niprocart                  int64   `gorm:"column:niprocart" json:"niprocart" form:"niprocart"`
536
+	Jms                        int64   `gorm:"column:jms" json:"jms" form:"jms"`
537
+	FistulaNeedleSet           int64   `gorm:"column:fistula_needle_set" json:"fistula_needle_set" form:"fistula_needle_set"`
538
+	FistulaNeedleSet16         int64   `gorm:"column:fistula_needle_set_16" json:"fistula_needle_set_16" form:"fistula_needle_set_16"`
539
+	Hemoperfusion              int64   `gorm:"column:hemoperfusion" json:"hemoperfusion" form:"hemoperfusion"`
540
+	DialyserSterilised         int64   `gorm:"column:dialyser_sterilised" json:"dialyser_sterilised" form:"dialyser_sterilised"`
541
+	Filtryzer                  int64   `gorm:"column:filtryzer" json:"filtryzer" form:"filtryzer"`
542
+	TargetKtv                  float64 `gorm:"column:target_ktv" json:"target_ktv" form:"target_ktv"`
543
+	Dialyzers                  int64   `gorm:"column:dialyzers" json:"dialyzers" form:"dialyzers"`
544
+	Injector                   int64   `gorm:"column:injector" json:"injector" form:"injector"`
545
+	Bloodlines                 int64   `gorm:"column:bloodlines" json:"bloodlines" form:"bloodlines"`
546
+	TubingHemodialysis         int64   `gorm:"column:tubing_hemodialysis" json:"tubing_hemodialysis" form:"tubing_hemodialysis"`
547
+	Package                    int64   `gorm:"column:package" json:"package" form:"package"`
548
+	ALiquid                    int64   `gorm:"column:a_liquid" json:"a_liquid" form:"a_liquid"`
549
+}
550
+
551
+func (DialysisPrescription) TableName() string {
552
+
553
+	return "xt_dialysis_prescription"
554
+}
555
+
556
+type DialysisOrder struct {
557
+	ID             int64  `gorm:"column:id" json:"id" form:"id"`
558
+	DialysisDate   int64  `gorm:"column:dialysis_date" json:"dialysis_date" form:"dialysis_date"`
559
+	UserOrgId      int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
560
+	PatientId      int64  `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
561
+	PrescriptionId int64  `gorm:"column:prescription_id" json:"prescription_id" form:"prescription_id"`
562
+	Stage          int64  `gorm:"column:stage" json:"stage" form:"stage"`
563
+	Remark         string `gorm:"column:remark" json:"remark" form:"remark"`
564
+	BedId          int64  `gorm:"column:bed_id" json:"bed_id" form:"bed_id"`
565
+	StartNurse     int64  `gorm:"column:start_nurse" json:"start_nurse" form:"start_nurse"`
566
+	FinishNurse    int64  `gorm:"column:finish_nurse" json:"finish_nurse" form:"finish_nurse"`
567
+	Status         int64  `gorm:"column:status" json:"status" form:"status"`
568
+	CreatedTime    int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
569
+	UpdatedTime    int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
570
+	StartTime      int64  `gorm:"column:start_time" json:"start_time" form:"start_time"`
571
+	EndTime        int64  `gorm:"column:end_time" json:"end_time" form:"end_time"`
572
+	PunctureNurse  int64  `gorm:"column:puncture_nurse" json:"puncture_nurse" form:"puncture_nurse"`
573
+	Creator        int64  `gorm:"column:creator" json:"creator" form:"creator"`
574
+	Modifier       int64  `gorm:"column:modifier" json:"modifier" form:"modifier"`
575
+	FinishCreator  int64  `gorm:"column:finish_creator" json:"finish_creator" form:"finish_creator"`
576
+	FinishModifier int64  `gorm:"column:finish_modifier" json:"finish_modifier" form:"finish_modifier"`
577
+}
578
+
579
+func (DialysisOrder) TableName() string {
580
+
581
+	return "xt_dialysis_order"
582
+}
583
+
584
+type PatientsInfectiousDiseases struct {
585
+	ID          int64 `gorm:"column:id" json:"id" form:"id"`
586
+	PatientId   int64 `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
587
+	DiseaseId   int64 `gorm:"column:disease_id" json:"disease_id" form:"disease_id"`
588
+	Status      int64 `gorm:"column:status" json:"status" form:"status"`
589
+	CreatedTime int64 `gorm:"column:created_time" json:"created_time" form:"created_time"`
590
+	UpdatedTime int64 `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
591
+}
592
+
593
+func (PatientsInfectiousDiseases) TableName() string {
594
+
595
+	return "xt_patients_infectious_diseases"
596
+}
597
+
598
+type PatientsType struct {
599
+	ID          int64 `gorm:"column:id" json:"id" form:"id"`
600
+	UserOrgId   int64 `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
601
+	Text        int64 `gorm:"column:text" json:"text" form:"text"`
602
+	Status      int64 `gorm:"column:status" json:"status" form:"status"`
603
+	CreatedTime int64 `gorm:"column:created_time" json:"created_time" form:"created_time"`
604
+	UpdatedTime int64 `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
605
+	PatientId   int64 `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
606
+}
607
+
608
+func (PatientsType) TableName() string {
609
+
610
+	return "xt_patients_type"
611
+}
612
+
613
+type Schedule struct {
614
+	ID           int64 `gorm:"column:id" json:"id" form:"id"`
615
+	UserOrgId    int64 `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
616
+	PartitionId  int64 `gorm:"column:partition_id" json:"partition_id" form:"partition_id"`
617
+	BedId        int64 `gorm:"column:bed_id" json:"bed_id" form:"bed_id"`
618
+	PatientId    int64 `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
619
+	ScheduleDate int64 `gorm:"column:schedule_date" json:"schedule_date" form:"schedule_date"`
620
+	ScheduleType int64 `gorm:"column:schedule_type" json:"schedule_type" form:"schedule_type"`
621
+	ScheduleWeek int64 `gorm:"column:schedule_week" json:"schedule_week" form:"schedule_week"`
622
+	ModeId       int64 `gorm:"column:mode_id" json:"mode_id" form:"mode_id"`
623
+	Status       int64 `gorm:"column:status" json:"status" form:"status"`
624
+	CreatedTime  int64 `gorm:"column:created_time" json:"created_time" form:"created_time"`
625
+	UpdatedTime  int64 `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
626
+}
627
+
628
+func (Schedule) TableName() string {
629
+
630
+	return "xt_schedule"
631
+}
632
+
633
+type DeviceZone struct {
634
+	ID         int64  `gorm:"column:id" json:"id"`
635
+	OrgID      int64  `gorm:"column:org_id" json:"-"`
636
+	Name       string `json:"name"`
637
+	Type       int    `json:"type"`
638
+	Status     int8   `json:"-"`
639
+	CreateTime int64  `gorm:"column:ctime" json:"-"`
640
+	ModifyTime int64  `gorm:"column:mtime" json:"-"`
641
+}
642
+
643
+func (DeviceZone) TableName() string {
644
+	return "xt_device_zone"
645
+}
646
+
647
+type DeviceNumber struct {
648
+	ID         int64  `gorm:"column:id" json:"id"`
649
+	OrgID      int64  `gorm:"column:org_id" json:"-"`
650
+	Number     string `json:"number"`
651
+	GroupID    int64  `gorm:"column:group_id" json:"group_id"`
652
+	ZoneID     int64  `gorm:"column:zone_id" json:"zone_id"`
653
+	Status     int8   `json:"-"`
654
+	CreateTime int64  `gorm:"column:ctime" json:"-"`
655
+	ModifyTime int64  `gorm:"column:mtime" json:"-"`
656
+}
657
+
658
+func (DeviceNumber) TableName() string {
659
+	return "xt_device_number"
660
+}
661
+
662
+type TreatmentMode struct {
663
+	ID                  int64  `gorm:"column:id" json:"id" form:"id"`
664
+	Name                string `gorm:"column:name" json:"name" form:"name"`
665
+	DialysisDuration    int64  `gorm:"column:dialysis_duration" json:"dialysis_duration" form:"dialysis_duration"`
666
+	ReplacementWay      int64  `gorm:"column:replacement_way" json:"replacement_way" form:"replacement_way"`
667
+	HemodialysisMachine int64  `gorm:"column:hemodialysis_machine" json:"hemodialysis_machine" form:"hemodialysis_machine"`
668
+	BloodFilter         int64  `gorm:"column:blood_filter" json:"blood_filter" form:"blood_filter"`
669
+	PerfusionApparatus  int64  `gorm:"column:perfusion_apparatus" json:"perfusion_apparatus" form:"perfusion_apparatus"`
670
+	BloodFlowVolume     int64  `gorm:"column:blood_flow_volume" json:"blood_flow_volume" form:"blood_flow_volume"`
671
+	DialysateFlow       int64  `gorm:"column:dialysate_flow" json:"dialysate_flow" form:"dialysate_flow"`
672
+	Kalium              int64  `gorm:"column:kalium" json:"kalium" form:"kalium"`
673
+	Sodium              int64  `gorm:"column:sodium" json:"sodium" form:"sodium"`
674
+	Calcium             int64  `gorm:"column:calcium" json:"calcium" form:"calcium"`
675
+	Bicarbonate         int64  `gorm:"column:bicarbonate" json:"bicarbonate" form:"bicarbonate"`
676
+	Remark              string `gorm:"column:remark" json:"remark" form:"remark"`
677
+	Status              int64  `gorm:"column:status" json:"status" form:"status"`
678
+	CreatedTime         int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
679
+	UpdatedTime         int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
680
+}
681
+
682
+func (TreatmentMode) TableName() string {
683
+
684
+	return "xt_treatment_mode"
685
+}
686
+
687
+type PatientSchedule struct {
688
+	Schedule
689
+	DeviceZone   DeviceZone   `json:"zone" gorm:"foreignkey:PartitionId"`
690
+	DeviceNumber DeviceNumber `json:"bed" gorm:"foreignkey:BedId"`
691
+
692
+	Week int64 `gorm:"-" json:"week" form:"week"`
693
+
694
+	TreatmentMode TreatmentMode `json:"mode" gorm:"foreignkey:ModeId"`
695
+}
696
+
697
+type ServeSubscibe struct {
698
+	ID              int64     `gorm:"column:id" json:"id" form:"id"`
699
+	OrgId           int64     `gorm:"column:org_id" json:"org_id" form:"org_id"`
700
+	PeriodStart     int64     `gorm:"column:period_start" json:"period_start" form:"period_start"`
701
+	PeriodEnd       int64     `gorm:"column:period_end" json:"period_end" form:"period_end"`
702
+	PeriodStartTime time.Time `gorm:"column:period_start_time" json:"period_start_time" form:"period_start_time"`
703
+	PeriodEndTime   time.Time `gorm:"column:period_end_time" json:"period_end_time" form:"period_end_time"`
704
+	Status          int64     `gorm:"column:status" json:"status" form:"status"`
705
+	CreatedTime     int64     `gorm:"column:created_time" json:"created_time" form:"created_time"`
706
+	UpdatedTime     int64     `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
707
+	State           int64     `gorm:"column:state" json:"state" form:"state"`
708
+}
709
+
710
+func (ServeSubscibe) TableName() string {
711
+
712
+	return "sgj_serve_subscibe"
713
+}
714
+
715
+type Inspection struct {
716
+	ID           int64  `gorm:"column:id" json:"id" form:"id"`
717
+	PatientId    int64  `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
718
+	OrgId        int64  `gorm:"column:org_id" json:"org_id" form:"org_id"`
719
+	ProjectId    int64  `gorm:"column:project_id" json:"project_id" form:"project_id"`
720
+	ItemId       int64  `gorm:"column:item_id" json:"item_id" form:"item_id"`
721
+	ItemName     string `gorm:"column:item_name" json:"item_name" form:"item_name"`
722
+	ProjectName  string `gorm:"column:project_name" json:"project_name" form:"project_name"`
723
+	InspectType  int64  `gorm:"column:inspect_type" json:"inspect_type" form:"inspect_type"`
724
+	InspectValue string `gorm:"column:inspect_value" json:"inspect_value" form:"inspect_value"`
725
+	InspectDate  int64  `gorm:"column:inspect_date" json:"inspect_date" form:"inspect_date"`
726
+	Status       int64  `gorm:"column:status" json:"status" form:"status"`
727
+	CreatedTime  int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
728
+	UpdatedTime  int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
729
+}
730
+
731
+func (Inspection) TableName() string {
732
+
733
+	return "xt_inspection"
734
+}

+ 24 - 0
routers/router.go Parādīt failu

@@ -0,0 +1,24 @@
1
+package routers
2
+
3
+import (
4
+	"KYA/controllers/login"
5
+	"KYA/controllers/manage"
6
+	"KYA/controllers/patient"
7
+	"github.com/astaxie/beego"
8
+	"github.com/astaxie/beego/plugins/cors"
9
+)
10
+
11
+func init() {
12
+	//beego.Router("/", &controllers.MainController{})
13
+	beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
14
+		AllowOrigins:     []string{"http://localhost:8090", "http://localhost:8091", "http://mt.sgjyun.com"},
15
+		AllowMethods:     []string{"Get", "Post", "PUT", "DELETE", "OPTIONS"},
16
+		AllowHeaders:     []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
17
+		ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
18
+		AllowCredentials: true,
19
+	}))
20
+
21
+	login.LoginRegisterRouter()
22
+	patient.PatientRegisterRouter()
23
+	manage.ManageRegisterRouter()
24
+}

+ 149 - 0
service/db.go Parādīt failu

@@ -0,0 +1,149 @@
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
+	"github.com/astaxie/beego"
22
+	"github.com/jinzhu/gorm"
23
+	_ "github.com/jinzhu/gorm/dialects/mysql" // mysql
24
+)
25
+
26
+var readDb *gorm.DB
27
+var writeDb *gorm.DB
28
+var readUserDb *gorm.DB
29
+var writeUserDb *gorm.DB
30
+var readDbs *gorm.DB
31
+var writeDbs *gorm.DB
32
+var err error
33
+
34
+func ConnectDB() {
35
+	readHost := beego.AppConfig.String("readmysqlhost")
36
+	readPort := beego.AppConfig.String("readmysqlport")
37
+	readUser := beego.AppConfig.String("readmysqluser")
38
+	readPass := beego.AppConfig.String("readmysqlpass")
39
+	readName := beego.AppConfig.String("readmysqlname")
40
+
41
+	writeHost := beego.AppConfig.String("writemysqlhost")
42
+	writePort := beego.AppConfig.String("writemysqlport")
43
+	writeUser := beego.AppConfig.String("writemysqluser")
44
+	writePass := beego.AppConfig.String("writemysqlpass")
45
+	writeName := beego.AppConfig.String("writemysqlname")
46
+
47
+	readUserHost := beego.AppConfig.String("readuserhost")
48
+	readUserPort := beego.AppConfig.String("readuserport")
49
+	readUserUser := beego.AppConfig.String("readuseruser")
50
+	readUserPass := beego.AppConfig.String("readuserpass")
51
+	readUserName := beego.AppConfig.String("readusername")
52
+
53
+	writeUserHost := beego.AppConfig.String("writeuserhost")
54
+	writeUserPort := beego.AppConfig.String("writeuserport")
55
+	writeUserUser := beego.AppConfig.String("writeuseruser")
56
+	writeUserPass := beego.AppConfig.String("writeuserpass")
57
+	writeUserName := beego.AppConfig.String("writeusername")
58
+
59
+	readHosts := beego.AppConfig.String("readmysqlhosts")
60
+	readPorts := beego.AppConfig.String("readmysqlports")
61
+	readUsers := beego.AppConfig.String("readmysqlusers")
62
+	readPasss := beego.AppConfig.String("readmysqlpasss")
63
+	readNames := beego.AppConfig.String("readmysqlnames")
64
+
65
+	writeHosts := beego.AppConfig.String("writemysqlhosts")
66
+	writePorts := beego.AppConfig.String("writemysqlports")
67
+	writeUsers := beego.AppConfig.String("writemysqlusers")
68
+	writePasss := beego.AppConfig.String("writemysqlpasss")
69
+	writeNames := beego.AppConfig.String("writemysqlnames")
70
+
71
+	rdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readUser, readPass, readHost, readPort, readName)
72
+	wdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writeUser, writePass, writeHost, writePort, writeName)
73
+
74
+	rudsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readUserUser, readUserPass, readUserHost, readUserPort, readUserName)
75
+	wudsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writeUserUser, writeUserPass, writeUserHost, writeUserPort, writeUserName)
76
+
77
+	rdsns := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readUsers, readPasss, readHosts, readPorts, readNames)
78
+	wdsns := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writeUsers, writePasss, writeHosts, writePorts, writeNames)
79
+
80
+	readDb, err = gorm.Open("mysql", rdsn)
81
+	if err != nil {
82
+		//beego.Error(err)
83
+	}
84
+	readDb.DB().SetMaxIdleConns(10)
85
+	readDb.DB().SetMaxOpenConns(100)
86
+	readDb.LogMode(true)
87
+
88
+	writeDb, err = gorm.Open("mysql", wdsn)
89
+	if err != nil {
90
+		//beego.Error(err)
91
+	}
92
+	writeDb.DB().SetMaxIdleConns(10)
93
+	writeDb.DB().SetMaxOpenConns(100)
94
+	writeDb.LogMode(true)
95
+
96
+	readUserDb, err = gorm.Open("mysql", rudsn)
97
+	if err != nil {
98
+		//beego.Error(err)
99
+	}
100
+	readUserDb.DB().SetMaxIdleConns(10)
101
+	readUserDb.DB().SetMaxOpenConns(100)
102
+	readUserDb.LogMode(true)
103
+
104
+	writeUserDb, err = gorm.Open("mysql", wudsn)
105
+	if err != nil {
106
+		//beego.Error(err)
107
+	}
108
+	writeUserDb.DB().SetMaxIdleConns(10)
109
+	writeUserDb.DB().SetMaxOpenConns(100)
110
+	writeUserDb.LogMode(true)
111
+
112
+	readDbs, err = gorm.Open("mysql", rdsns)
113
+	fmt.Println("错误", err)
114
+	if err != nil {
115
+		//beego.Error(err)
116
+	}
117
+	readDbs.DB().SetMaxIdleConns(10)
118
+	readDbs.DB().SetMaxOpenConns(100)
119
+	readDbs.LogMode(true)
120
+
121
+	writeDbs, err = gorm.Open("mysql", wdsns)
122
+	fmt.Println("错误", err)
123
+	if err != nil {
124
+		//beego.Error(err)
125
+	}
126
+	writeDbs.DB().SetMaxIdleConns(10)
127
+	writeDbs.DB().SetMaxOpenConns(100)
128
+	writeDbs.LogMode(true)
129
+}
130
+
131
+func PatientReadDB() *gorm.DB {
132
+	return readDb
133
+}
134
+func PatientWriteDB() *gorm.DB {
135
+	return writeDb
136
+}
137
+func UserReadDB() *gorm.DB {
138
+	return readUserDb
139
+}
140
+func UserWriteDB() *gorm.DB {
141
+	return writeUserDb
142
+}
143
+
144
+func XTReadDB() *gorm.DB {
145
+	return readDbs
146
+}
147
+func XTWriteDB() *gorm.DB {
148
+	return writeDbs
149
+}

+ 275 - 0
service/login_service/login_service.go Parādīt failu

@@ -0,0 +1,275 @@
1
+package login_service
2
+
3
+import (
4
+	"KYA/models"
5
+	"KYA/service"
6
+	"KYA/utils"
7
+	"fmt"
8
+	"github.com/astaxie/beego"
9
+	"github.com/go-redis/redis"
10
+	"github.com/jinzhu/gorm"
11
+	"github.com/robfig/cron"
12
+	"time"
13
+)
14
+
15
+func QueryLogin(tel string, psd string) (admin models.SgjUserAdmin, err error) {
16
+	fmt.Println(service.UserReadDB())
17
+	err = service.UserReadDB().Model(&models.SgjUserAdmin{}).Where("mobile = ? AND password = ? AND status = ?", tel, psd, 1).First(&admin).Error
18
+	return
19
+}
20
+
21
+func GetQueryUserOrgId(creator int64) (*models.SgjUserOrg, error) {
22
+	var org models.SgjUserOrg
23
+	var err error
24
+	err = service.UserReadDB().Where("creator = ? AND status = ?", creator, 1).Find(&org).Error
25
+	if err == gorm.ErrRecordNotFound {
26
+		return nil, err
27
+	}
28
+	if err != nil {
29
+		return nil, err
30
+	}
31
+	return &org, nil
32
+}
33
+
34
+func init() {
35
+	utils.InfoLog("开启更新数据")
36
+	updateDefalutData := cron.New()
37
+	spec := "*/1 * * * * ?"
38
+	updateDefalutData.AddFunc(spec, func() {
39
+
40
+	})
41
+}
42
+
43
+func GetQueryPhoneData(phone string) (models.SgjUserAdmin, error) {
44
+	admin := models.SgjUserAdmin{}
45
+	err := service.UserReadDB().Where("mobile = ? AND status = ?", phone, 1).Find(&admin).Error
46
+	return admin, err
47
+}
48
+
49
+func RedisClient() *redis.Client {
50
+	address := fmt.Sprintf("%s:%s", beego.AppConfig.String("redishost"), beego.AppConfig.String("redisport"))
51
+	client := redis.NewClient(&redis.Options{
52
+		Addr:     address,
53
+		Password: beego.AppConfig.String("redispasswrod"), // no password set
54
+		DB:       0,                                       // use default DB
55
+	})
56
+
57
+	pong, err := client.Ping().Result()
58
+	fmt.Println(pong, err)
59
+	return client
60
+}
61
+
62
+func GetQueryMobileData(phone string) (*models.SgjUserAdmin, error) {
63
+
64
+	var user models.SgjUserAdmin
65
+	var err error
66
+	err = service.UserReadDB().Model(&models.SgjUserAdmin{}).Where("mobile = ? AND status = 1", phone).Find(&user).Error
67
+	if err == gorm.ErrRecordNotFound {
68
+		return nil, err
69
+	}
70
+	if err != nil {
71
+		return nil, err
72
+	}
73
+	return &user, nil
74
+
75
+}
76
+
77
+func AddAdmin(admin *models.SgjUserAdmin) error {
78
+
79
+	err := service.UserWriteDB().Create(&admin).Error
80
+	return err
81
+}
82
+
83
+func GetAllProvince(id int64) (dist []*models.SgjUserDistrict, err error) {
84
+
85
+	err = service.UserReadDB().Model(&models.SgjUserDistrict{}).Where("upid = ?", id).Find(&dist).Error
86
+	return dist, err
87
+}
88
+
89
+func UpdatedPassword(phone string, admin *models.SgjUserAdmin) error {
90
+	err := service.UserWriteDB().Model(&admin).Where("mobile = ?", phone).Update(map[string]interface{}{"password": admin.Password, "mtime": time.Now().Unix()}).Error
91
+	return err
92
+}
93
+
94
+func GetAllOrgName(id int64) (orgs []*models.SgjUserOrg, err error) {
95
+	fmt.Println("id是什么", id)
96
+	err = service.UserReadDB().Model(&models.SgjUserOrg{}).Where("creator = ? AND status = ?", id, 1).Find(&orgs).Error
97
+	fmt.Println("错误", err)
98
+	fmt.Println("orgs", orgs)
99
+	return orgs, err
100
+}
101
+
102
+func GetCityById(id int64) (ids []*models.SgjUserDistrict, err error) {
103
+	err = service.UserReadDB().Model(&models.SgjUserDistrict{}).Where("upid = ?", id).Find(&ids).Error
104
+	return ids, err
105
+}
106
+
107
+func GetAllOrgType() (orgType []*models.SgjUserOrgType, err error) {
108
+
109
+	err = service.UserReadDB().Model(&models.SgjUserOrgType{}).Where("status= ? AND id = ? OR id = ? OR id = ? OR id = ? OR id = ? OR id = ?", 1, 1, 7, 12, 16, 21, 26).Order("sort_no").Find(&orgType).Error
110
+	return
111
+}
112
+
113
+func AddUserOrgInfo(org *models.SgjUserOrg) error {
114
+
115
+	err := service.UserWriteDB().Create(&org).Error
116
+	return err
117
+}
118
+
119
+func CreateSubscibe(subscibe *models.ServeSubscibe) error {
120
+
121
+	err := service.UserWriteDB().Create(&subscibe).Error
122
+	return err
123
+}
124
+
125
+func GeLastUserOrgLastData(id int64) (models.SgjUserOrg, error) {
126
+	userOrg := models.SgjUserOrg{}
127
+	err := service.UserReadDB().Where("creator = ? AND status = ?", id, 1).Find(&userOrg).Error
128
+	return userOrg, err
129
+}
130
+
131
+func AddRole(role *models.UserRole) error {
132
+
133
+	err := service.UserWriteDB().Create(&role).Error
134
+	return err
135
+}
136
+
137
+func GetRoleLastDate(orgid int64) (models.UserRole, error) {
138
+	role := models.UserRole{}
139
+	err := service.UserReadDB().Where("org_id = ? AND status = ?", orgid, 1).Last(&role).Error
140
+	return role, err
141
+}
142
+
143
+func AddUserOrgApp(app *models.UserOrgApp) error {
144
+
145
+	err := service.UserWriteDB().Create(&app).Error
146
+	return err
147
+}
148
+
149
+func GetLastData(orgid int64) (models.UserOrgApp, error) {
150
+	app := models.UserOrgApp{}
151
+	err := service.UserReadDB().Where("org_id = ? AND status = 1", orgid).Last(&app).Error
152
+	return app, err
153
+}
154
+
155
+func AddAdimnRole(role *models.UserAdminRole) error {
156
+
157
+	err := service.UserWriteDB().Create(&role).Error
158
+	return err
159
+}
160
+
161
+func GetProvinceByName(orgname string) (models.SgjUserDistrict, error) {
162
+	dis := models.SgjUserDistrict{}
163
+	err := service.UserReadDB().Where("name = ? AND upid = ? ", orgname, 0).Find(&dis).Error
164
+	return dis, err
165
+}
166
+
167
+func GetCityByName(cityname string, proviceid int64) (models.SgjUserDistrict, error) {
168
+	district := models.SgjUserDistrict{}
169
+	err := service.UserReadDB().Where("name = ? AND upid = ?", cityname, proviceid).Find(&district).Error
170
+	return district, err
171
+}
172
+
173
+func GetCountByName(countname string, cityid int64) (models.SgjUserDistrict, error) {
174
+	district := models.SgjUserDistrict{}
175
+	err := service.UserReadDB().Where("name = ? AND upid = ?", countname, cityid).Find(&district).Error
176
+	return district, err
177
+}
178
+
179
+func GetOrgTypeByName(orgname string) (models.SgjUserOrgType, error) {
180
+	org := models.SgjUserOrgType{}
181
+	err := service.UserReadDB().Where("name = ? AND status = ?", orgname, 1).Find(&org).Error
182
+	return org, err
183
+}
184
+
185
+func GetBloodDialysisPatient(orgid int64, page int64, limit int64) (patients []*models.Patients, total int64, err error) {
186
+	db := service.XTReadDB().Table("xt_patients as x").Where("x.status = 1")
187
+	if orgid > 0 {
188
+		db = db.Where("x.user_org_id = ?", orgid)
189
+	}
190
+	offset := (page - 1) * limit
191
+	err = db.Count(&total).Order("x.created_time desc").Offset(offset).Limit(limit).
192
+		Select("x.id,x.user_org_id,x.user_id,x.avatar,x.patient_type,x.dialysis_no,x.admission_number,x.source,x.lapseto,x.partition_id,x.bed_id,x.name,x.alias,x.gender,x.marital_status,x.id_card_no,x.birthday,x.reimbursement_way_id,x.health_care_type,x.health_care_no,x.health_care_due_date,x.height,x.blood_type,x.rh,x.health_care_due_alert_date,x.education_level,x.profession,x.phone,x.home_telephone,x.relative_phone,x.relative_relations,x.home_address,x.work_unit,x.unit_address,x.children,x.receiving_date,x.is_hospital_first_dialysis,x.first_dialysis_date,x.first_dialysis_hospital,x.predialysis_condition,x.pre_hospital_dialysis_frequency,x.pre_hospital_dialysis_times,x.hospital_first_dialysis_date,x.induction_period,x.initial_dialysis,x.total_dialysis,x.attending_doctor_id,x.head_nurse_id,x.evaluate,x.diagnose,x.remark,x.registrars_id,x.registrars,x.qr_code,x.binding_state,x.patient_complains,x.present_history,x.past_history,x.temperature,x.pulse,x.respiratory,x.sbp,x.dbp,x.status,x.created_time,x.updated_time,x.nation,x.native_place,x.age").Find(&patients).Error
193
+	fmt.Println("err是什么", err)
194
+	return
195
+}
196
+
197
+func GetPatintsInfo(id int64, orgid int64) (models.Patients, error) {
198
+	patients := models.Patients{}
199
+	err := service.XTReadDB().Where("id = ? AND user_org_id = ? AND status = ?", id, orgid, 1).Find(&patients).Error
200
+	return patients, err
201
+}
202
+
203
+func GetPatientInfectious(patientid int64) (patients []*models.PatientsInfectiousDiseases, err error) {
204
+
205
+	err = service.XTReadDB().Where("patient_id = ? AND status = ?", patientid, 1).Find(&patients).Error
206
+	return patients, err
207
+}
208
+
209
+func GetCreatorId(orgid int64) (models.SgjUserOrg, error) {
210
+	org := models.SgjUserOrg{}
211
+	err := service.UserReadDB().Where("id = ? AND status = ? ", orgid, 1).Find(&org).Error
212
+	return org, err
213
+}
214
+
215
+func GetOrgAppId(creatorid int64, orgid int64) (models.UserOrgApp, error) {
216
+	app := models.UserOrgApp{}
217
+	err := service.UserReadDB().Where("creator = ? AND org_id = ? AND app_type = ?", creatorid, orgid, 3).Find(&app).Error
218
+	return app, err
219
+}
220
+
221
+func GetAdvceDoctor(creatorid int64, orgid int64, appid int64) (models.UserAdminRole, error) {
222
+	role := models.UserAdminRole{}
223
+	err := service.UserReadDB().Where("admin_user_id = ? and org_id = ? and app_id = ?", creatorid, orgid, appid).Find(&role).Error
224
+	return role, err
225
+}
226
+
227
+func GetDoctorAdvice(patientid int64, orgId int64, startime int64, endtime int64, keywords string) (doctoradvice []*models.DoctorAdvice, total int64, err error) {
228
+
229
+	db := service.XTReadDB().Model(&models.DoctorAdvice{}).Where("status = 1")
230
+	if orgId > 0 {
231
+		db = db.Where("user_org_id = ?", orgId)
232
+	}
233
+
234
+	if patientid > 0 {
235
+		db = db.Where("patient_id = ?", patientid)
236
+	}
237
+	if startime != 0 {
238
+		db = db.Where("start_time>= ?", startime)
239
+	}
240
+	if endtime != 0 {
241
+		db = db.Where("start_time<=?", endtime)
242
+	}
243
+
244
+	if len(keywords) > 0 {
245
+		likeKey := "%" + keywords + "%"
246
+		db = db.Where("advice_name LIKE ?", likeKey)
247
+	}
248
+	err = db.Count(&total).Select("id, user_org_id, patient_id, advice_type, advice_date, record_date, start_time, advice_name,advice_desc, reminder_date, drug_spec, drug_spec_unit, single_dose, single_dose_unit, prescribing_number, prescribing_number_unit, delivery_way, execution_frequency, advice_doctor, status, created_time,updated_time, advice_affirm, remark, stop_time, stop_reason, stop_doctor, stop_state, parent_id, execution_time, execution_staff, execution_state, checker, check_state, check_time, groupno,remind_type,frequency_type,day_count,week_day, IF(parent_id > 0, parent_id, id) as advice_order").Order("start_time desc, groupno desc, advice_order desc, id asc").Scan(&doctoradvice).Error
249
+	return
250
+
251
+	//	db := service.XTReadDB().Model(&models.DoctorAdvice{}).Where("status = 1")
252
+	//	if orgId>0 {
253
+	//		db = db.Where("user_org_id = ?", orgId)
254
+	//	}
255
+	//	if patientid > 0 {
256
+	//		db = db.Where("patient_id = ?", patientid)
257
+	//	}
258
+	//	db = db.Where("advice_date >= ?", startime)
259
+	//	db = db.Where("advice_date <=?", endtime)
260
+	//	//db = db.Where("advice_type int (?)", []int{1, 3})
261
+	//	err = db.Find(&doctoradvice).Error
262
+	//	return doctoradvice,err
263
+}
264
+
265
+func SeacherDoctorAdviceByAdviceName(patientid int64, orgid int64, serchval string) (doctoradvice []*models.DoctorAdvice, err error) {
266
+
267
+	err = service.XTReadDB().Where("patient_id = ? AND user_org_id = ? AND advice_name = ?", patientid, orgid, serchval).Find(&doctoradvice).Error
268
+	return doctoradvice, err
269
+}
270
+
271
+func DeleteDoctorAdvice(id int64) error {
272
+
273
+	err := service.XTWriteDB().Model(models.DoctorAdvice{}).Where("id= ?", id).Update(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
274
+	return err
275
+}

+ 197 - 0
service/manage_service/manage_service.go Parādīt failu

@@ -0,0 +1,197 @@
1
+package manage_service
2
+
3
+import (
4
+	"KYA/models"
5
+	"KYA/service"
6
+	"fmt"
7
+	"github.com/jinzhu/gorm"
8
+	"strings"
9
+	"time"
10
+)
11
+
12
+func GetPatientInfoByIdCard(idcard string, orgid int64) (*models.Patients, error) {
13
+	var patients models.Patients
14
+	var err error
15
+	err = service.XTReadDB().Model(&models.Patients{}).Where("id_card_no = ?  AND user_org_id = ? AND status = ?", idcard, orgid, 1).Find(&patients).Error
16
+	if err == gorm.ErrRecordNotFound {
17
+		return nil, err
18
+	}
19
+	if err != nil {
20
+		return nil, err
21
+	}
22
+	return &patients, nil
23
+}
24
+
25
+func GetPatientInfoByPhone(phone string, orgid int64) (*models.Patients, error) {
26
+	var patients models.Patients
27
+	var err error
28
+	err = service.XTReadDB().Model(&models.Patients{}).Where("id_card_no = ?  AND user_org_id = ? AND status = ?", phone, orgid, 1).Find(&patients).Error
29
+	if err == gorm.ErrRecordNotFound {
30
+		return nil, err
31
+	}
32
+	if err != nil {
33
+		return nil, err
34
+	}
35
+	return &patients, nil
36
+}
37
+
38
+func AddPatients(patients *models.Patients) error {
39
+
40
+	err := service.XTWriteDB().Create(&patients).Error
41
+	return err
42
+}
43
+
44
+func GetLastData(orgid int64) (models.Patients, error) {
45
+	patients := models.Patients{}
46
+	err := service.XTReadDB().Where("user_org_id = ? AND status = ?", orgid, 1).Last(&patients).Error
47
+	return patients, err
48
+}
49
+
50
+func GetPatientLastData(orgid int64) (models.Patients, error) {
51
+	patients := models.Patients{}
52
+	err := service.XTReadDB().Where("user_org_id = ? AND status = ?", orgid, 1).Find(&patients).Error
53
+	return patients, err
54
+}
55
+
56
+func AddContagions(patienid int64, createdtime int64, updatedtime int64, contagions []int64) (err error) {
57
+	utx := service.XTWriteDB()
58
+	if len(contagions) > 0 {
59
+		thisSQL := "INSERT INTO xt_patients_infectious_diseases (patient_id, disease_id, status, created_time, updated_time) VALUES "
60
+		insertParams := make([]string, 0)
61
+		insertData := make([]interface{}, 0)
62
+		for _, contagion := range contagions {
63
+			insertParams = append(insertParams, "(?, ?, ?, ?, ?)")
64
+			insertData = append(insertData, patienid)
65
+			insertData = append(insertData, contagion)
66
+			insertData = append(insertData, 1)
67
+			insertData = append(insertData, createdtime)
68
+			insertData = append(insertData, updatedtime)
69
+		}
70
+		thisSQL += strings.Join(insertParams, ",")
71
+		err = utx.Exec(thisSQL, insertData...).Error
72
+		fmt.Println("这个错误err", err)
73
+	}
74
+	utx.Commit()
75
+	return
76
+}
77
+
78
+func AddPatientType(orgid int64, patientid int64, patientType []int64) (err error) {
79
+	utx := service.XTWriteDB()
80
+	if len(patientType) > 0 {
81
+		thisSQL := "INSERT INTO xt_patients_type(user_org_id,patient_id,created_time,status,text) VALUES"
82
+		insertParams := make([]string, 0)
83
+		insertData := make([]interface{}, 0)
84
+		for _, patientype := range patientType {
85
+			insertParams = append(insertParams, "(?, ?, ?, ?, ?)")
86
+			insertData = append(insertData, orgid)
87
+			insertData = append(insertData, patientid)
88
+			insertData = append(insertData, time.Now().Unix())
89
+			insertData = append(insertData, 1)
90
+			insertData = append(insertData, patientype)
91
+		}
92
+		thisSQL += strings.Join(insertParams, ",")
93
+		err = utx.Exec(thisSQL, insertData...).Error
94
+		fmt.Println("这个错误err", err)
95
+	}
96
+	utx.Commit()
97
+	return
98
+}
99
+
100
+func DeleteCouseManage(patientid int64, orgid int64) error {
101
+
102
+	err := service.XTWriteDB().Model(models.PatientCourseOfDisease{}).Where("id = ? AND org_id = ?", patientid, orgid).Update(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
103
+	return err
104
+}
105
+
106
+func GetRecordServe(patientid int64, orgid int64, startime int64, endtime int64) (record []*models.PatientRescueRecords, err error) {
107
+	db := service.XTReadDB().Table("xt_patient_rescue_record as x").Where("x.status = 1")
108
+	err = db.Group("x.id").Select("x.id,x.org_id,x.patient_id,x.recorder,x.record_time,x.content,x.status,r.user_name").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.recorder").Where("x.patient_id = ? AND x.org_id = ? AND x.record_time >= ? AND x.record_time <= ?", patientid, orgid, startime, endtime).Scan(&record).Error
109
+	return record, err
110
+}
111
+
112
+func GetLongDialysisData(patientid int64, orgid int64, startime int64, endtime int64) (dialysis []*models.DialysisPrescription, err error) {
113
+
114
+	err = service.XTReadDB().Where("patient_id = ? AND user_org_id = ? AND record_date >= ? AND record_date <=?", patientid, orgid, startime, endtime).Find(&dialysis).Error
115
+	return dialysis, err
116
+}
117
+
118
+func GetDialysReCord(patientid int64, orgid int64, startime int64, endtime int64) (dialysisOrder []*models.DialysisOrder, err error) {
119
+
120
+	err = service.XTReadDB().Where("patient_id = ? AND user_org_id = ? AND dialysis_date >=? AND dialysis_date <= ?", patientid, orgid, startime, endtime).Find(&dialysisOrder).Error
121
+	return dialysisOrder, err
122
+}
123
+
124
+func GetMissionInforMation(patientid int64, orgid int64, startime int64, endtime int64) (treatment []*models.TreatmentSummary, err error) {
125
+	err = service.XTReadDB().Where("patient_id = ? AND user_org_id = ? AND assessment_date >=? AND assessment_date <= ?", patientid, orgid, startime, endtime).Find(&treatment).Error
126
+	return treatment, err
127
+}
128
+
129
+func ToSeacherCourseManagement(patientid int64, orgid int64, content string) (patient []*models.PatientCourseOfDiseases, err error) {
130
+	likekey := "%" + content + "%"
131
+	db := service.XTReadDB().Table("xt_patient_course_of_disease as x").Where("x.status = 1")
132
+	err = db.Group("x.id").Select("x.id,x.org_id,x.patient_id,x.recorder,x.record_time,x.content,x.title,r.user_name").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.recorder").Where("x.patient_id = ? and x.org_id = ? and x.title like ?", patientid, orgid, likekey).Scan(&patient).Error
133
+	return patient, err
134
+}
135
+
136
+func ToDeleteSaveRecord(id int64) error {
137
+	err := service.XTWriteDB().Model(models.PatientRescueRecord{}).Where("id = ?", id).Update(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
138
+	return err
139
+}
140
+
141
+func ToSeacherRecord(patientid int64, orgid int64, content string) (record []*models.PatientRescueRecords, err error) {
142
+	likekey := "%" + content + "%"
143
+	db := service.XTReadDB().Table("xt_patient_rescue_record as x").Where("x.status = 1")
144
+	err = db.Group("x.id").Select("x.id,x.org_id,x.patient_id,x.recorder,x.record_time,x.content,r.user_name").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.recorder").Where("x.patient_id = ? and x.org_id = ? and x.content like ?", patientid, orgid, likekey).Scan(&record).Error
145
+	return record, err
146
+}
147
+
148
+func DeletMissionInformation(id int64) error {
149
+
150
+	err := service.XTWriteDB().Model(models.TreatmentSummary{}).Where("id = ?", id).Update(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
151
+	return err
152
+}
153
+
154
+func ToSeacherMissionInformation(patientid int64, orgid int64, seachval string) (treat []*models.TreatmentSummary, err error) {
155
+
156
+	db := service.XTReadDB().Table("xt_treatment_summary as x")
157
+	//if len(keywords) > 0 {
158
+	//	likeKey := "%" + keywords + "%"
159
+	//	db = db.Where("p.name LIKE ?", likeKey)
160
+	//}
161
+	if len(seachval) > 0 {
162
+		likeKe := seachval + "%"
163
+		db = db.Where("x.patient_id = ? AND x.user_org_id = ? AND x.mission LIKE ?", patientid, orgid, likeKe)
164
+	}
165
+
166
+	err = db.Find(&treat).Error
167
+
168
+	return treat, err
169
+}
170
+
171
+func GetPatientSchedules(patientid int64, orgid int64, startime int64, endtime int64) (schedules []*models.PatientSchedule, err error) {
172
+	err = service.XTReadDB().Table("xt_schedule as s").
173
+		Preload("DeviceZone", "org_id = ? and status =1", orgid).
174
+		Preload("DeviceNumber", "org_id = ? and status =1", orgid).
175
+		Where("s.patient_id = ? and s.user_org_id = ? and s.schedule_date >= ? and s.schedule_date <= ? and status = 1", patientid, orgid, startime, endtime).
176
+		Find(&schedules).Error
177
+	return
178
+}
179
+
180
+func ToSeacherSheduleinformation(patientid int64, orgid int64, seachval string) (schedules []*models.PatientSchedule, err error) {
181
+	db := service.XTReadDB().Table("xt_schedule as s")
182
+	err = db.Preload("DeviceZone", "org_id = ? and status =1", orgid).
183
+		Preload("DeviceNumber", "org_id = ? and status =1", orgid).
184
+		Where("s.patient_id = ? and s.user_org_id = ? and s.bed_id = ?", patientid, orgid, seachval).Find(&schedules).Error
185
+	return schedules, err
186
+}
187
+
188
+func DeleteScheduleinformationById(id int64) error {
189
+	err := service.XTWriteDB().Model(models.Schedule{}).Where("id = ? ", id).Update(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
190
+	return err
191
+}
192
+
193
+func GetPaitentType(patientid int64, orgid int64) (patientType []*models.PatientsType, err error) {
194
+
195
+	err = service.XTReadDB().Where("patient_id = ? AND user_org_id = ?", patientid, orgid).Find(&patientType).Error
196
+	return patientType, err
197
+}

+ 94 - 0
service/patient_service/patient_service.go Parādīt failu

@@ -0,0 +1,94 @@
1
+package patient_service
2
+
3
+import (
4
+	"KYA/models"
5
+	"KYA/service"
6
+	"fmt"
7
+	"strconv"
8
+	"strings"
9
+)
10
+
11
+func GetCreatorId(phone string) (models.SgjUserAdmin, error) {
12
+	admin := models.SgjUserAdmin{}
13
+	err := service.UserReadDB().Where("mobile = ? AND status = ?", phone, 1).Find(&admin).Error
14
+	return admin, err
15
+}
16
+
17
+func GetOrgId(id int64) (models.SgjUserOrg, error) {
18
+	org := models.SgjUserOrg{}
19
+	err := service.UserReadDB().Where("creator = ? AND status = ?", id, 1).Find(&org).Error
20
+	return org, err
21
+}
22
+func GetneratedDialysisNo(orgID int64) (dialysisNo int64) {
23
+	fmt.Println("orgid", orgID)
24
+	var patient models.Patients
25
+	err := service.XTReadDB().Model(&models.Patients{}).Where("status = 1 AND user_org_id = ?", orgID).Order("dialysis_no desc").First(&patient).Error
26
+	fmt.Println("自动生成透析号错误", err)
27
+	if err != nil {
28
+		return
29
+	}
30
+
31
+	if patient.ID == 0 {
32
+		return
33
+	}
34
+	dialysisNo, _ = strconv.ParseInt(patient.DialysisNo, 10, 64)
35
+	return
36
+}
37
+
38
+func AddPatients(patients *models.Patients) error {
39
+
40
+	err := service.XTWriteDB().Create(&patients).Error
41
+	return err
42
+}
43
+
44
+func GetPatientsLastData(orgid int64) (models.Patients, error) {
45
+	patients := models.Patients{}
46
+	err := service.XTReadDB().Where("user_org_id = ? AND status = ?", orgid, 1).Find(&patients).Error
47
+	return patients, err
48
+}
49
+
50
+func AddContagions(patienid int64, createdtime int64, updatedtime int64, contagions []int64) (err error) {
51
+	utx := service.XTWriteDB().Begin()
52
+	//btx := service.UserWriteDB().Begin()
53
+	if len(contagions) > 0 {
54
+		thisSQL := "INSERT INTO xt_patients_infectious_diseases (patient_id, disease_id, status, created_time, updated_time) VALUES "
55
+		insertParams := make([]string, 0)
56
+		insertData := make([]interface{}, 0)
57
+		for _, contagion := range contagions {
58
+			insertParams = append(insertParams, "(?, ?, ?, ?, ?)")
59
+			insertData = append(insertData, patienid)
60
+			insertData = append(insertData, contagion)
61
+			insertData = append(insertData, 1)
62
+			insertData = append(insertData, createdtime)
63
+			insertData = append(insertData, updatedtime)
64
+		}
65
+		thisSQL += strings.Join(insertParams, ",")
66
+		err = utx.Exec(thisSQL, insertData...).Error
67
+		fmt.Println("这个错误err", err)
68
+	}
69
+	return
70
+}
71
+
72
+func GetCourseManagementData(patientid int64, orgid int64, startime int64, endtime int64) (patientCourse []*models.PatientCourseOfDiseases, err error) {
73
+	db := service.XTReadDB().Table("xt_patient_course_of_disease as x").Where("x.status = 1")
74
+	err = db.Group("x.id").Select("x.id,x.org_id,x.patient_id,x.recorder,x.record_time,x.content,x.title,r.user_name").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.recorder").Where("x.patient_id = ? and x.org_id = ? and x.record_time >=? and x.record_time <=?", patientid, orgid, startime, endtime).Scan(&patientCourse).Error
75
+	return patientCourse, err
76
+
77
+}
78
+
79
+func GetCheckPatientData(patientid int64, orgid int64, stattime int64, endtime int64) (inspection []*models.Inspection, err error) {
80
+
81
+	err = service.XTReadDB().Group("inspect_date").Where("patient_id = ? and org_id = ? and inspect_date >=? and inspect_date <= ? and status = 1", patientid, orgid, stattime, endtime).Find(&inspection).Error
82
+	return inspection, err
83
+}
84
+
85
+func GetCheckData(time int64, patientid int64, orgid int64) (inspection []*models.Inspection, err error) {
86
+
87
+	err = service.XTReadDB().Group("project_name").Where("patient_id = ? and org_id = ? and inspect_date = ?", patientid, orgid, time).Order("id asc").Find(&inspection).Error
88
+	return inspection, err
89
+}
90
+func GetPatientInfectious(patientid int64) (infectious []*models.PatientsInfectiousDiseases, err error) {
91
+
92
+	err = service.XTReadDB().Model(&models.PatientsInfectiousDiseases{}).Where("patient_id = ?", patientid).Find(&infectious).Error
93
+	return infectious, err
94
+}

+ 21 - 0
service/redis.go Parādīt failu

@@ -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
+}

+ 116 - 0
sms_service/sms_db_service.go Parādīt failu

@@ -0,0 +1,116 @@
1
+package sms_service
2
+
3
+import (
4
+	"time"
5
+
6
+	"KYA/models"
7
+	"KYA/service"
8
+	"KYA/utils"
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
sms_service/sms_service.go Parādīt failu

@@ -0,0 +1,325 @@
1
+package sms_service
2
+
3
+import (
4
+	"KYA/models"
5
+	base "KYA/service"
6
+	"KYA/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
+	code_str := utils.RandomNumberString(6)
23
+	templateID, _ := beego.AppConfig.Int("sms_verification_code_templateid")
24
+	fmt.Println("templateID", 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
sms_service/sms_vms.go Parādīt failu

@@ -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
sms_service/ucpaas.go Parādīt failu

@@ -0,0 +1,164 @@
1
+package sms_service
2
+
3
+import (
4
+	"KYA/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
+}

+ 1 - 0
static/js/reload.min.js Parādīt failu

@@ -0,0 +1 @@
1
+function b(a){var c=new WebSocket(a);c.onclose=function(){setTimeout(function(){b(a)},2E3)};c.onmessage=function(){location.reload()}}try{if(window.WebSocket)try{b("ws://localhost:12450/reload")}catch(a){console.error(a)}else console.log("Your browser does not support WebSockets.")}catch(a){console.error("Exception during connecting to Reload:",a)};

+ 37 - 0
tests/default_test.go Parādīt failu

@@ -0,0 +1,37 @@
1
+package test
2
+
3
+import (
4
+	_ "KYA/routers"
5
+	"net/http"
6
+	"net/http/httptest"
7
+	"path/filepath"
8
+	"runtime"
9
+	"testing"
10
+
11
+	"github.com/astaxie/beego"
12
+	. "github.com/smartystreets/goconvey/convey"
13
+)
14
+
15
+func init() {
16
+	_, file, _, _ := runtime.Caller(0)
17
+	apppath, _ := filepath.Abs(filepath.Dir(filepath.Join(file, ".."+string(filepath.Separator))))
18
+	beego.TestBeegoInit(apppath)
19
+}
20
+
21
+// TestBeego is a sample to run an endpoint test
22
+func TestBeego(t *testing.T) {
23
+	r, _ := http.NewRequest("GET", "/", nil)
24
+	w := httptest.NewRecorder()
25
+	beego.BeeApp.Handlers.ServeHTTP(w, r)
26
+
27
+	beego.Trace("testing", "TestBeego", "Code[%d]\n%s", w.Code, w.Body.String())
28
+
29
+	Convey("Subject: Test Station Endpoint\n", t, func() {
30
+		Convey("Status Code Should Be 200", func() {
31
+			So(w.Code, ShouldEqual, 200)
32
+		})
33
+		Convey("The Result Should Not Be Empty", func() {
34
+			So(w.Body.Len(), ShouldBeGreaterThan, 0)
35
+		})
36
+	})
37
+}

+ 13 - 0
utils/ip_helper.go Parādīt failu

@@ -0,0 +1,13 @@
1
+package utils
2
+
3
+import (
4
+	"net/http"
5
+)
6
+
7
+func GetIP(r *http.Request) string {
8
+	ip := r.Header.Get("X-Forwarded-For")
9
+	if ip == "" {
10
+		ip = r.RemoteAddr
11
+	}
12
+	return ip
13
+}

+ 66 - 0
utils/log.go Parādīt failu

@@ -0,0 +1,66 @@
1
+package utils
2
+
3
+import (
4
+	"fmt"
5
+	"time"
6
+)
7
+
8
+const (
9
+	color_red = uint8(iota + 91)
10
+	color_green
11
+	color_yellow
12
+	color_blue
13
+	color_magenta //洋红
14
+
15
+	// info = "[INFO]"
16
+	// trac = "[TRAC]"
17
+	// erro = "[ERRO]"
18
+	// warn = "[WARN]"
19
+	// succ = "[SUCC]"
20
+)
21
+
22
+// 根据 https://github.com/liyu4/chill 修改的
23
+// see complete color rules in document in https://en.wikipedia.org/wiki/ANSI_escape_code#cite_note-ecma48-13
24
+func TraceLog(format string, a ...interface{}) {
25
+	fmt.Println(formatLog(yellow(fmt.Sprintf(format, a...))))
26
+}
27
+
28
+func InfoLog(format string, a ...interface{}) {
29
+	fmt.Println(formatLog(blue(fmt.Sprintf(format, a...))))
30
+}
31
+
32
+func SuccessLog(format string, a ...interface{}) {
33
+	fmt.Println(formatLog(green(fmt.Sprintf(format, a...))))
34
+}
35
+
36
+func WarningLog(format string, a ...interface{}) {
37
+	fmt.Println(formatLog(magenta(fmt.Sprintf(format, a...))))
38
+}
39
+
40
+func ErrorLog(format string, a ...interface{}) {
41
+	fmt.Println(formatLog(red(fmt.Sprintf(format, a...))))
42
+}
43
+
44
+func red(s string) string {
45
+	return fmt.Sprintf("\x1b[%dm%s\x1b[0m", color_red, s)
46
+}
47
+
48
+func green(s string) string {
49
+	return fmt.Sprintf("\x1b[%dm%s\x1b[0m", color_green, s)
50
+}
51
+
52
+func yellow(s string) string {
53
+	return fmt.Sprintf("\x1b[%dm%s\x1b[0m", color_yellow, s)
54
+}
55
+
56
+func blue(s string) string {
57
+	return fmt.Sprintf("\x1b[%dm%s\x1b[0m", color_blue, s)
58
+}
59
+
60
+func magenta(s string) string {
61
+	return fmt.Sprintf("\x1b[%dm%s\x1b[0m", color_magenta, s)
62
+}
63
+
64
+func formatLog(prefix string) string {
65
+	return time.Now().Format("[2006/01/02 15:04:05]") + " " + prefix + " "
66
+}

+ 191 - 0
utils/paginator.go Parādīt failu

@@ -0,0 +1,191 @@
1
+// Copyright 2013 wetalk authors
2
+//
3
+// Licensed under the Apache License, Version 2.0 (the "License"): you may
4
+// not use this file except in compliance with the License. You may obtain
5
+// a copy of the License at
6
+//
7
+//     http://www.apache.org/licenses/LICENSE-2.0
8
+//
9
+// Unless required by applicable law or agreed to in writing, software
10
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
+// License for the specific language governing permissions and limitations
13
+// under the License.
14
+
15
+package utils
16
+
17
+import (
18
+	"math"
19
+	"net/http"
20
+	"net/url"
21
+	"strconv"
22
+)
23
+
24
+type Paginator struct {
25
+	Request     *http.Request
26
+	PerPageNums int
27
+	MaxPages    int
28
+
29
+	nums      int64
30
+	pageRange []int
31
+	pageNums  int
32
+	page      int
33
+}
34
+
35
+func (p *Paginator) PageNums() int {
36
+	if p.pageNums != 0 {
37
+		return p.pageNums
38
+	}
39
+	pageNums := math.Ceil(float64(p.nums) / float64(p.PerPageNums))
40
+	if p.MaxPages > 0 {
41
+		pageNums = math.Min(pageNums, float64(p.MaxPages))
42
+	}
43
+	p.pageNums = int(pageNums)
44
+	return p.pageNums
45
+}
46
+
47
+func (p *Paginator) Nums() int64 {
48
+	return p.nums
49
+}
50
+
51
+func (p *Paginator) SetNums(nums int64) {
52
+	p.nums = nums
53
+}
54
+
55
+func (p *Paginator) Page() int {
56
+	if p.page != 0 {
57
+		return p.page
58
+	}
59
+	if p.Request.Form == nil {
60
+		p.Request.ParseForm()
61
+	}
62
+	p.page, _ = strconv.Atoi(p.Request.Form.Get("page"))
63
+	if p.page > p.PageNums() {
64
+		p.page = p.PageNums()
65
+	}
66
+	if p.page <= 0 {
67
+		p.page = 1
68
+	}
69
+	return p.page
70
+}
71
+
72
+func (p *Paginator) Pages() []int {
73
+	if p.pageRange == nil && p.nums > 0 {
74
+		var pages []int
75
+		pageNums := p.PageNums()
76
+		page := p.Page()
77
+		switch {
78
+		case page >= pageNums-4 && pageNums > 9:
79
+			start := pageNums - 9 + 1
80
+			pages = make([]int, 9)
81
+			for i, _ := range pages {
82
+				pages[i] = start + i
83
+			}
84
+		case page >= 5 && pageNums > 9:
85
+			start := page - 5 + 1
86
+			pages = make([]int, int(math.Min(9, float64(page+4+1))))
87
+			for i, _ := range pages {
88
+				pages[i] = start + i
89
+			}
90
+		default:
91
+			pages = make([]int, int(math.Min(9, float64(pageNums))))
92
+			for i, _ := range pages {
93
+				pages[i] = i + 1
94
+			}
95
+		}
96
+		p.pageRange = pages
97
+	}
98
+	return p.pageRange
99
+}
100
+
101
+func (p *Paginator) PageLink(page int) string {
102
+	link, _ := url.ParseRequestURI(p.Request.RequestURI)
103
+	values := link.Query()
104
+	if page == 1 {
105
+		values.Del("page")
106
+	} else {
107
+		values.Set("page", strconv.Itoa(page))
108
+	}
109
+	link.RawQuery = values.Encode()
110
+	return link.String()
111
+}
112
+
113
+func (p *Paginator) PageParams() url.Values {
114
+	link, _ := url.ParseRequestURI(p.Request.RequestURI)
115
+	values := link.Query()
116
+	values.Del("page")
117
+	return values
118
+}
119
+
120
+func (p *Paginator) BasePageLink() string {
121
+	link, _ := url.ParseRequestURI(p.Request.RequestURI)
122
+	values := link.Query()
123
+	values.Del("page")
124
+	link.RawQuery = values.Encode()
125
+	return link.String()
126
+}
127
+
128
+func (p *Paginator) PageLinkPrev() (link string) {
129
+	if p.HasPrev() {
130
+		link = p.PageLink(p.Page() - 1)
131
+	}
132
+	return
133
+}
134
+
135
+func (p *Paginator) PageLinkNext() (link string) {
136
+	if p.HasNext() {
137
+		link = p.PageLink(p.Page() + 1)
138
+	}
139
+	return
140
+}
141
+
142
+func (p *Paginator) PageLinkFirst() (link string) {
143
+	return p.PageLink(1)
144
+}
145
+
146
+func (p *Paginator) PageLinkLast() (link string) {
147
+	return p.PageLink(p.PageNums())
148
+}
149
+
150
+func (p *Paginator) HasPrev() bool {
151
+	return p.Page() > 1
152
+}
153
+
154
+func (p *Paginator) HasNext() bool {
155
+	return p.Page() < p.PageNums()
156
+}
157
+
158
+func (p *Paginator) IsActive(page int) bool {
159
+	return p.Page() == page
160
+}
161
+
162
+func (p *Paginator) Offset() int {
163
+	return (p.Page() - 1) * p.PerPageNums
164
+}
165
+
166
+func (p *Paginator) HasPages() bool {
167
+	return p.PageNums() > 1
168
+}
169
+
170
+func (p *Paginator) Total() int {
171
+	return p.PageNums()
172
+}
173
+func (p *Paginator) TotalSubOne() int {
174
+	return p.PageNums() - 1
175
+}
176
+
177
+func NewPaginator(req *http.Request, per int, nums int64) *Paginator {
178
+	p := Paginator{}
179
+	p.Request = req
180
+	if per <= 0 {
181
+		per = 10
182
+	}
183
+	p.PerPageNums = per
184
+	p.SetNums(nums)
185
+	return &p
186
+}
187
+
188
+func FakePaginator(currentPage int, per int, nums int64) *Paginator {
189
+	fakeReq, _ := http.NewRequest("GET", "/?page="+strconv.Itoa(currentPage), nil)
190
+	return NewPaginator(fakeReq, per, nums)
191
+}

+ 75 - 0
utils/regex_helper.go Parādīt failu

@@ -0,0 +1,75 @@
1
+package utils
2
+
3
+import (
4
+	"fmt"
5
+	"regexp"
6
+)
7
+
8
+// 正整数正则
9
+func PositiveIntegerRegexp() *regexp.Regexp {
10
+	reg, _ := regexp.Compile("^[1-9][0-9]*$")
11
+	return reg
12
+}
13
+
14
+// 手机号正则 不那么严谨的
15
+func CellPhoneRegexp() *regexp.Regexp {
16
+	reg, _ := regexp.Compile("^1\\d{10}$")
17
+	return reg
18
+}
19
+
20
+// 固话正则
21
+func TelPhoneRegexp() *regexp.Regexp {
22
+	// reg, _ := regexp.Compile("^0\\d{2,3}-?\\d{7,8}$")
23
+	reg, _ := regexp.Compile("^0\\d{2,3}-?\\d{7,8}$")
24
+	return reg
25
+}
26
+
27
+// 手机号或固话正则
28
+func PhoneRegexp() *regexp.Regexp {
29
+	reg, _ := regexp.Compile("^(0\\d{2,3}-?\\d{7,8}$)|(1\\d{10}$)")
30
+	return reg
31
+}
32
+
33
+// tests
34
+func PositiveIntegerRegexpTest() {
35
+	reg := PositiveIntegerRegexp()
36
+	fmt.Println("12 是否匹配:", reg.MatchString("12"))
37
+	fmt.Println("1 是否匹配:", reg.MatchString("1"))
38
+	fmt.Println("980030 是否匹配:", reg.MatchString("980030"))
39
+	fmt.Println("01 是否匹配:", reg.MatchString("01"))
40
+	fmt.Println("asd1asd 是否匹配:", reg.MatchString("asd1asd"))
41
+	fmt.Println("a12 是否匹配:", reg.MatchString("a12"))
42
+	fmt.Println("12a 是否匹配:", reg.MatchString("12a"))
43
+	fmt.Println("-12 是否匹配:", reg.MatchString("-12"))
44
+	fmt.Println("12.1 是否匹配:", reg.MatchString("12.1"))
45
+	fmt.Println("14j2a 是否匹配:", reg.MatchString("14j2a"))
46
+}
47
+
48
+func CellPhoneRegexpTest() {
49
+	reg := CellPhoneRegexp()
50
+	fmt.Println("13632250447 是否匹配:", reg.MatchString("13632250447"))
51
+	fmt.Println("12000000000 是否匹配:", reg.MatchString("12000000000"))
52
+	fmt.Println("30001212325 是否匹配:", reg.MatchString("30001212325"))
53
+	fmt.Println("1233123 是否匹配:", reg.MatchString("1233123"))
54
+	fmt.Println("123312312344 是否匹配:", reg.MatchString("123312312344"))
55
+	fmt.Println("13345678a12 是否匹配:", reg.MatchString("13345678a12"))
56
+	fmt.Println("a13345678a1 是否匹配:", reg.MatchString("a13345678a1"))
57
+	fmt.Println("1334a678a12 是否匹配:", reg.MatchString("1334a678a12"))
58
+	fmt.Println("1345678a12a 是否匹配:", reg.MatchString("1345678a12a"))
59
+	fmt.Println("aqwertyuioo 是否匹配:", reg.MatchString("aqwertyuioo"))
60
+}
61
+
62
+func TelPhoneRegexpTest() {
63
+	reg := TelPhoneRegexp()
64
+	fmt.Println("020-39006917 是否匹配:", reg.MatchString("020-39006917"))
65
+	fmt.Println("02039006917 是否匹配:", reg.MatchString("02039006917"))
66
+	fmt.Println("0754-5916612 是否匹配:", reg.MatchString("0754-5916612"))
67
+	fmt.Println("07545916612 是否匹配:", reg.MatchString("07545916612"))
68
+	fmt.Println("123-39006917 是否匹配:", reg.MatchString("123-39006917"))
69
+	fmt.Println("1754-5916612 是否匹配:", reg.MatchString("1754-5916612"))
70
+	fmt.Println("0a0-39006917 是否匹配:", reg.MatchString("0a0-39006917"))
71
+	fmt.Println("0a039006917 是否匹配:", reg.MatchString("0a039006917"))
72
+	fmt.Println("010-39s06917 是否匹配:", reg.MatchString("010-39s06917"))
73
+	fmt.Println("020-390069171 是否匹配:", reg.MatchString("020-390069171"))
74
+	fmt.Println("020-3900691 是否匹配:", reg.MatchString("020-3900691"))
75
+}

+ 115 - 0
utils/stringtool.go Parādīt failu

@@ -0,0 +1,115 @@
1
+package utils
2
+
3
+import (
4
+	"bytes"
5
+	"crypto/aes"
6
+	"crypto/cipher"
7
+	"crypto/md5"
8
+	"encoding/base64"
9
+	"fmt"
10
+	"math/rand"
11
+	"strconv"
12
+	"strings"
13
+	"time"
14
+
15
+	"github.com/astaxie/beego"
16
+)
17
+
18
+// 将字符串加密成 md5
19
+func String2md5(str string) string {
20
+	data := []byte(str)
21
+	has := md5.Sum(data)
22
+	return fmt.Sprintf("%x", has) //将[]byte转成16进制
23
+}
24
+
25
+// RandomString 在数字、大写字母、小写字母范围内生成num位的随机字符串
26
+func RandomString(length int) string {
27
+	// 48 ~ 57 数字
28
+	// 65 ~ 90 A ~ Z
29
+	// 97 ~ 122 a ~ z
30
+	// 一共62个字符,在0~61进行随机,小于10时,在数字范围随机,
31
+	// 小于36在大写范围内随机,其他在小写范围随机
32
+	rand.Seed(time.Now().UnixNano())
33
+	result := make([]string, 0, length)
34
+	for i := 0; i < length; i++ {
35
+		t := rand.Intn(62)
36
+		if t < 10 {
37
+			result = append(result, strconv.Itoa(rand.Intn(10)))
38
+		} else if t < 36 {
39
+			result = append(result, string(rand.Intn(26)+65))
40
+		} else {
41
+			result = append(result, string(rand.Intn(26)+97))
42
+		}
43
+	}
44
+	return strings.Join(result, "")
45
+}
46
+
47
+func RandomNumberString(length int) string {
48
+	var str string
49
+	for i := 0; i < length; i++ {
50
+		rand.Seed(time.Now().UnixNano())
51
+		str += strconv.Itoa(rand.Intn(10))
52
+	}
53
+	return str
54
+}
55
+
56
+// AES加密
57
+func AESEncrypt(origin string) string {
58
+	aes_key := beego.AppConfig.String("aes_key")
59
+	fmt.Println(aes_key)
60
+	xpass, _ := _aesEncrypt([]byte(origin), []byte(aes_key))
61
+	fmt.Println(_aesEncrypt([]byte(origin), []byte(aes_key)))
62
+	fmt.Println(xpass)
63
+	pass64 := base64.StdEncoding.EncodeToString(xpass)
64
+	fmt.Println(pass64)
65
+	return pass64
66
+}
67
+
68
+func AESDecrypt(crypted []byte) string {
69
+	aes_key := beego.AppConfig.String("aes_key")
70
+	origData, err := _aesDecrypt(crypted, []byte(aes_key))
71
+	if err != nil {
72
+		return ""
73
+	}
74
+	return string(origData)
75
+}
76
+
77
+func _PKCS5Padding(ciphertext []byte, blockSize int) []byte {
78
+	padding := blockSize - len(ciphertext)%blockSize
79
+	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
80
+	return append(ciphertext, padtext...)
81
+}
82
+
83
+func _PKCS5UnPadding(origData []byte) []byte {
84
+	length := len(origData)
85
+	unpadding := int(origData[length-1])
86
+	return origData[:(length - unpadding)]
87
+}
88
+
89
+func _aesEncrypt(origData, key []byte) ([]byte, error) {
90
+	block, err := aes.NewCipher(key)
91
+	if err != nil {
92
+		return nil, err
93
+	}
94
+
95
+	blockSize := block.BlockSize()
96
+	origData = _PKCS5Padding(origData, blockSize)
97
+	blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
98
+	crypted := make([]byte, len(origData))
99
+	blockMode.CryptBlocks(crypted, origData)
100
+	return crypted, nil
101
+}
102
+
103
+func _aesDecrypt(crypted, key []byte) ([]byte, error) {
104
+	block, err := aes.NewCipher(key)
105
+	if err != nil {
106
+		return nil, err
107
+	}
108
+
109
+	blockSize := block.BlockSize()
110
+	blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
111
+	origData := make([]byte, len(crypted))
112
+	blockMode.CryptBlocks(origData, crypted)
113
+	origData = _PKCS5UnPadding(origData)
114
+	return origData, nil
115
+}

+ 350 - 0
utils/tencentsig/bitelliptic.go Parādīt failu

@@ -0,0 +1,350 @@
1
+package tencentsig
2
+
3
+// @see https://github.com/ThePiachu/Golang-Koblitz-elliptic-curve-DSA-library/blob/master/bitelliptic/bitelliptic.go
4
+
5
+import (
6
+	"crypto/elliptic"
7
+	"io"
8
+	"math/big"
9
+	"sync"
10
+)
11
+
12
+// A BitCurve represents a Koblitz Curve with a=0.
13
+// See http://www.hyperelliptic.org/EFD/g1p/auto-shortw.html
14
+type BitCurve struct {
15
+	P       *big.Int // the order of the underlying field
16
+	N       *big.Int // the order of the base point
17
+	B       *big.Int // the constant of the BitCurve equation
18
+	Gx, Gy  *big.Int // (x,y) of the base point
19
+	BitSize int      // the size of the underlying field
20
+}
21
+
22
+func (BitCurve *BitCurve) Params() *elliptic.CurveParams {
23
+	return &elliptic.CurveParams{P: BitCurve.P, N: BitCurve.N, B: BitCurve.B, Gx: BitCurve.Gx, Gy: BitCurve.Gy, BitSize: BitCurve.BitSize}
24
+}
25
+
26
+// IsOnBitCurve returns true if the given (x,y) lies on the BitCurve.
27
+func (BitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool {
28
+	// y² = x³ + b
29
+	y2 := new(big.Int).Mul(y, y) //y²
30
+	y2.Mod(y2, BitCurve.P)       //y²%P
31
+
32
+	x3 := new(big.Int).Mul(x, x) //x²
33
+	x3.Mul(x3, x)                //x³
34
+
35
+	x3.Add(x3, BitCurve.B) //x³+B
36
+	x3.Mod(x3, BitCurve.P) //(x³+B)%P
37
+
38
+	return x3.Cmp(y2) == 0
39
+}
40
+
41
+//TODO: double check if the function is okay
42
+// affineFromJacobian reverses the Jacobian transform. See the comment at the
43
+// top of the file.
44
+func (BitCurve *BitCurve) affineFromJacobian(x, y, z *big.Int) (xOut, yOut *big.Int) {
45
+	zinv := new(big.Int).ModInverse(z, BitCurve.P)
46
+	zinvsq := new(big.Int).Mul(zinv, zinv)
47
+
48
+	xOut = new(big.Int).Mul(x, zinvsq)
49
+	xOut.Mod(xOut, BitCurve.P)
50
+	zinvsq.Mul(zinvsq, zinv)
51
+	yOut = new(big.Int).Mul(y, zinvsq)
52
+	yOut.Mod(yOut, BitCurve.P)
53
+	return
54
+}
55
+
56
+// Add returns the sum of (x1,y1) and (x2,y2)
57
+func (BitCurve *BitCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) {
58
+	z := new(big.Int).SetInt64(1)
59
+	return BitCurve.affineFromJacobian(BitCurve.addJacobian(x1, y1, z, x2, y2, z))
60
+}
61
+
62
+// addJacobian takes two points in Jacobian coordinates, (x1, y1, z1) and
63
+// (x2, y2, z2) and returns their sum, also in Jacobian form.
64
+func (BitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int) {
65
+	// See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl
66
+	z1z1 := new(big.Int).Mul(z1, z1)
67
+	z1z1.Mod(z1z1, BitCurve.P)
68
+	z2z2 := new(big.Int).Mul(z2, z2)
69
+	z2z2.Mod(z2z2, BitCurve.P)
70
+
71
+	u1 := new(big.Int).Mul(x1, z2z2)
72
+	u1.Mod(u1, BitCurve.P)
73
+	u2 := new(big.Int).Mul(x2, z1z1)
74
+	u2.Mod(u2, BitCurve.P)
75
+	h := new(big.Int).Sub(u2, u1)
76
+	if h.Sign() == -1 {
77
+		h.Add(h, BitCurve.P)
78
+	}
79
+	i := new(big.Int).Lsh(h, 1)
80
+	i.Mul(i, i)
81
+	j := new(big.Int).Mul(h, i)
82
+
83
+	s1 := new(big.Int).Mul(y1, z2)
84
+	s1.Mul(s1, z2z2)
85
+	s1.Mod(s1, BitCurve.P)
86
+	s2 := new(big.Int).Mul(y2, z1)
87
+	s2.Mul(s2, z1z1)
88
+	s2.Mod(s2, BitCurve.P)
89
+	r := new(big.Int).Sub(s2, s1)
90
+	if r.Sign() == -1 {
91
+		r.Add(r, BitCurve.P)
92
+	}
93
+	r.Lsh(r, 1)
94
+	v := new(big.Int).Mul(u1, i)
95
+
96
+	x3 := new(big.Int).Set(r)
97
+	x3.Mul(x3, x3)
98
+	x3.Sub(x3, j)
99
+	x3.Sub(x3, v)
100
+	x3.Sub(x3, v)
101
+	x3.Mod(x3, BitCurve.P)
102
+
103
+	y3 := new(big.Int).Set(r)
104
+	v.Sub(v, x3)
105
+	y3.Mul(y3, v)
106
+	s1.Mul(s1, j)
107
+	s1.Lsh(s1, 1)
108
+	y3.Sub(y3, s1)
109
+	y3.Mod(y3, BitCurve.P)
110
+
111
+	z3 := new(big.Int).Add(z1, z2)
112
+	z3.Mul(z3, z3)
113
+	z3.Sub(z3, z1z1)
114
+	if z3.Sign() == -1 {
115
+		z3.Add(z3, BitCurve.P)
116
+	}
117
+	z3.Sub(z3, z2z2)
118
+	if z3.Sign() == -1 {
119
+		z3.Add(z3, BitCurve.P)
120
+	}
121
+	z3.Mul(z3, h)
122
+	z3.Mod(z3, BitCurve.P)
123
+
124
+	return x3, y3, z3
125
+}
126
+
127
+// Double returns 2*(x,y)
128
+func (BitCurve *BitCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) {
129
+	z1 := new(big.Int).SetInt64(1)
130
+	return BitCurve.affineFromJacobian(BitCurve.doubleJacobian(x1, y1, z1))
131
+}
132
+
133
+// doubleJacobian takes a point in Jacobian coordinates, (x, y, z), and
134
+// returns its double, also in Jacobian form.
135
+func (BitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) {
136
+	// See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l
137
+
138
+	a := new(big.Int).Mul(x, x) //X1²
139
+	b := new(big.Int).Mul(y, y) //Y1²
140
+	c := new(big.Int).Mul(b, b) //B²
141
+
142
+	d := new(big.Int).Add(x, b) //X1+B
143
+	d.Mul(d, d)                 //(X1+B)²
144
+	d.Sub(d, a)                 //(X1+B)²-A
145
+	d.Sub(d, c)                 //(X1+B)²-A-C
146
+	d.Mul(d, big.NewInt(2))     //2*((X1+B)²-A-C)
147
+
148
+	e := new(big.Int).Mul(big.NewInt(3), a) //3*A
149
+	f := new(big.Int).Mul(e, e)             //E²
150
+
151
+	x3 := new(big.Int).Mul(big.NewInt(2), d) //2*D
152
+	x3.Sub(f, x3)                            //F-2*D
153
+	x3.Mod(x3, BitCurve.P)
154
+
155
+	y3 := new(big.Int).Sub(d, x3)                  //D-X3
156
+	y3.Mul(e, y3)                                  //E*(D-X3)
157
+	y3.Sub(y3, new(big.Int).Mul(big.NewInt(8), c)) //E*(D-X3)-8*C
158
+	y3.Mod(y3, BitCurve.P)
159
+
160
+	z3 := new(big.Int).Mul(y, z) //Y1*Z1
161
+	z3.Mul(big.NewInt(2), z3)    //3*Y1*Z1
162
+	z3.Mod(z3, BitCurve.P)
163
+
164
+	return x3, y3, z3
165
+}
166
+
167
+//TODO: double check if it is okay
168
+// ScalarMult returns k*(Bx,By) where k is a number in big-endian form.
169
+func (BitCurve *BitCurve) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int) {
170
+	// We have a slight problem in that the identity of the group (the
171
+	// point at infinity) cannot be represented in (x, y) form on a finite
172
+	// machine. Thus the standard add/double algorithm has to be tweaked
173
+	// slightly: our initial state is not the identity, but x, and we
174
+	// ignore the first true bit in |k|.  If we don't find any true bits in
175
+	// |k|, then we return nil, nil, because we cannot return the identity
176
+	// element.
177
+
178
+	Bz := new(big.Int).SetInt64(1)
179
+	x := Bx
180
+	y := By
181
+	z := Bz
182
+
183
+	seenFirstTrue := false
184
+	for _, b := range k {
185
+		for bitNum := 0; bitNum < 8; bitNum++ {
186
+			if seenFirstTrue {
187
+				x, y, z = BitCurve.doubleJacobian(x, y, z)
188
+			}
189
+			if b&0x80 == 0x80 {
190
+				if !seenFirstTrue {
191
+					seenFirstTrue = true
192
+				} else {
193
+					x, y, z = BitCurve.addJacobian(Bx, By, Bz, x, y, z)
194
+				}
195
+			}
196
+			b <<= 1
197
+		}
198
+	}
199
+
200
+	if !seenFirstTrue {
201
+		return nil, nil
202
+	}
203
+
204
+	return BitCurve.affineFromJacobian(x, y, z)
205
+}
206
+
207
+// ScalarBaseMult returns k*G, where G is the base point of the group and k is
208
+// an integer in big-endian form.
209
+func (BitCurve *BitCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) {
210
+	return BitCurve.ScalarMult(BitCurve.Gx, BitCurve.Gy, k)
211
+}
212
+
213
+var mask = []byte{0xff, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f}
214
+
215
+//TODO: double check if it is okay
216
+// GenerateKey returns a public/private key pair. The private key is generated
217
+// using the given reader, which must return random data.
218
+func (BitCurve *BitCurve) GenerateKey(rand io.Reader) (priv []byte, x, y *big.Int, err error) {
219
+	byteLen := (BitCurve.BitSize + 7) >> 3
220
+	priv = make([]byte, byteLen)
221
+
222
+	for x == nil {
223
+		_, err = io.ReadFull(rand, priv)
224
+		if err != nil {
225
+			return
226
+		}
227
+		// We have to mask off any excess bits in the case that the size of the
228
+		// underlying field is not a whole number of bytes.
229
+		priv[0] &= mask[BitCurve.BitSize%8]
230
+		// This is because, in tests, rand will return all zeros and we don't
231
+		// want to get the point at infinity and loop forever.
232
+		priv[1] ^= 0x42
233
+		x, y = BitCurve.ScalarBaseMult(priv)
234
+	}
235
+	return
236
+}
237
+
238
+// Marshal converts a point into the form specified in section 4.3.6 of ANSI
239
+// X9.62.
240
+func (BitCurve *BitCurve) Marshal(x, y *big.Int) []byte {
241
+	byteLen := (BitCurve.BitSize + 7) >> 3
242
+
243
+	ret := make([]byte, 1+2*byteLen)
244
+	ret[0] = 4 // uncompressed point
245
+
246
+	xBytes := x.Bytes()
247
+	copy(ret[1+byteLen-len(xBytes):], xBytes)
248
+	yBytes := y.Bytes()
249
+	copy(ret[1+2*byteLen-len(yBytes):], yBytes)
250
+	return ret
251
+}
252
+
253
+// Unmarshal converts a point, serialised by Marshal, into an x, y pair. On
254
+// error, x = nil.
255
+func (BitCurve *BitCurve) Unmarshal(data []byte) (x, y *big.Int) {
256
+	byteLen := (BitCurve.BitSize + 7) >> 3
257
+	if len(data) != 1+2*byteLen {
258
+		return
259
+	}
260
+	if data[0] != 4 { // uncompressed form
261
+		return
262
+	}
263
+	x = new(big.Int).SetBytes(data[1 : 1+byteLen])
264
+	y = new(big.Int).SetBytes(data[1+byteLen:])
265
+	return
266
+}
267
+
268
+//curve parameters taken from:
269
+//http://www.secg.org/collateral/sec2_final.pdf
270
+
271
+var initonce sync.Once
272
+var secp160k1 *BitCurve
273
+var secp192k1 *BitCurve
274
+var secp224k1 *BitCurve
275
+var secp256k1 *BitCurve
276
+
277
+func initAll() {
278
+	initS160()
279
+	initS192()
280
+	initS224()
281
+	initS256()
282
+}
283
+
284
+func initS160() {
285
+	// See SEC 2 section 2.4.1
286
+	secp160k1 = new(BitCurve)
287
+	secp160k1.P, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73", 16)
288
+	secp160k1.N, _ = new(big.Int).SetString("0100000000000000000001B8FA16DFAB9ACA16B6B3", 16)
289
+	secp160k1.B, _ = new(big.Int).SetString("0000000000000000000000000000000000000007", 16)
290
+	secp160k1.Gx, _ = new(big.Int).SetString("3B4C382CE37AA192A4019E763036F4F5DD4D7EBB", 16)
291
+	secp160k1.Gy, _ = new(big.Int).SetString("938CF935318FDCED6BC28286531733C3F03C4FEE", 16)
292
+	secp160k1.BitSize = 160
293
+}
294
+
295
+func initS192() {
296
+	// See SEC 2 section 2.5.1
297
+	secp192k1 = new(BitCurve)
298
+	secp192k1.P, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37", 16)
299
+	secp192k1.N, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D", 16)
300
+	secp192k1.B, _ = new(big.Int).SetString("000000000000000000000000000000000000000000000003", 16)
301
+	secp192k1.Gx, _ = new(big.Int).SetString("DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D", 16)
302
+	secp192k1.Gy, _ = new(big.Int).SetString("9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D", 16)
303
+	secp192k1.BitSize = 192
304
+}
305
+
306
+func initS224() {
307
+	// See SEC 2 section 2.6.1
308
+	secp224k1 = new(BitCurve)
309
+	secp224k1.P, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFE56D", 16)
310
+	secp224k1.N, _ = new(big.Int).SetString("010000000000000000000000000001DCE8D2EC6184CAF0A971769FB1F7", 16)
311
+	secp224k1.B, _ = new(big.Int).SetString("00000000000000000000000000000000000000000000000000000005", 16)
312
+	secp224k1.Gx, _ = new(big.Int).SetString("A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C", 16)
313
+	secp224k1.Gy, _ = new(big.Int).SetString("7E089FED7FBA344282CAFBD6F7E319F7C0B0BD59E2CA4BDB556D61A5", 16)
314
+	secp224k1.BitSize = 224
315
+}
316
+
317
+func initS256() {
318
+	// See SEC 2 section 2.7.1
319
+	secp256k1 = new(BitCurve)
320
+	secp256k1.P, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16)
321
+	secp256k1.N, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 16)
322
+	secp256k1.B, _ = new(big.Int).SetString("0000000000000000000000000000000000000000000000000000000000000007", 16)
323
+	secp256k1.Gx, _ = new(big.Int).SetString("79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", 16)
324
+	secp256k1.Gy, _ = new(big.Int).SetString("483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", 16)
325
+	secp256k1.BitSize = 256
326
+}
327
+
328
+// S160 returns a BitCurve which implements secp160k1 (see SEC 2 section 2.4.1)
329
+func S160() *BitCurve {
330
+	initonce.Do(initAll)
331
+	return secp160k1
332
+}
333
+
334
+// S192 returns a BitCurve which implements secp192k1 (see SEC 2 section 2.5.1)
335
+func S192() *BitCurve {
336
+	initonce.Do(initAll)
337
+	return secp192k1
338
+}
339
+
340
+// S224 returns a BitCurve which implements secp224k1 (see SEC 2 section 2.6.1)
341
+func S224() *BitCurve {
342
+	initonce.Do(initAll)
343
+	return secp224k1
344
+}
345
+
346
+// S256 returns a BitCurve which implements secp256k1 (see SEC 2 section 2.7.1)
347
+func S256() *BitCurve {
348
+	initonce.Do(initAll)
349
+	return secp256k1
350
+}

+ 27 - 0
utils/time_helper.go Parādīt failu

@@ -0,0 +1,27 @@
1
+package utils
2
+
3
+import (
4
+	"time"
5
+)
6
+
7
+// day 当天凌晨0点
8
+func ZeroHourTimeOfDay(day time.Time) time.Time {
9
+	dayStr := day.Format("2006-01-02")
10
+	zeroHourTime, _ := ParseTimeStringToTime("2006-01-02", dayStr)
11
+	return *zeroHourTime
12
+}
13
+
14
+// day 当月一号凌晨0点
15
+func BeginningOfMonth(day time.Time) time.Time {
16
+	dayStr := day.Format("2006-01")
17
+	monthTime, _ := ParseTimeStringToTime("2006-01", dayStr)
18
+	return *monthTime
19
+}
20
+
21
+// 指定年月的月份的月初凌晨0点和月末23点59分59秒
22
+func MonthBeginningToEnd(year int, month int) (time.Time, time.Time) {
23
+	beginningOfMonth := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.Local)
24
+	beginningOfNextMonth := beginningOfMonth.AddDate(0, 1, 0)
25
+	endOfMonth := beginningOfNextMonth.Add(time.Duration(-1))
26
+	return beginningOfMonth, endOfMonth
27
+}

+ 258 - 0
utils/tools.go Parādīt failu

@@ -0,0 +1,258 @@
1
+package utils
2
+
3
+import (
4
+	"crypto/sha1"
5
+	"encoding/base64"
6
+	"errors"
7
+	"fmt"
8
+	"io"
9
+	"math/rand"
10
+	"regexp"
11
+	"sort"
12
+	"strconv"
13
+	"strings"
14
+	"time"
15
+
16
+	"crypto/md5"
17
+	"encoding/hex"
18
+
19
+	"github.com/astaxie/beego"
20
+)
21
+
22
+func TimeSub(t1, t2 time.Time) int {
23
+	t1 = time.Date(t1.Year(), t1.Month(), t1.Day(), 0, 0, 0, 0, time.Local)
24
+	t2 = time.Date(t2.Year(), t2.Month(), t2.Day(), 0, 0, 0, 0, time.Local)
25
+
26
+	return int(t1.Sub(t2).Hours() / 24)
27
+}
28
+
29
+func MarkBackUrl(backUrl, defaultUrl string) string {
30
+	if len(backUrl) == 0 {
31
+		backUrl = defaultUrl
32
+	} else {
33
+		backURLByte, err := base64.URLEncoding.DecodeString(backUrl)
34
+		if err != nil {
35
+			backUrl = backUrl
36
+		} else {
37
+			backUrl = string(backURLByte)
38
+		}
39
+	}
40
+	return backUrl
41
+}
42
+
43
+func CheckMobile(mobile string) (match bool) {
44
+	//过滤手机
45
+	match, _ = regexp.MatchString("^1([2358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$", mobile)
46
+	return
47
+}
48
+
49
+func CheckPhone(phone string) (match bool) {
50
+	reg, _ := regexp.MatchString("^0[0-9]{2,3}-?[0-9]{7,8}$", phone)
51
+	return reg
52
+}
53
+
54
+func CheckHexColor(color string) (match bool) {
55
+	reg, _ := regexp.MatchString("^#([0-9a-fA-F]{6})$", color)
56
+	return reg
57
+}
58
+
59
+func RandCode(min, max int64) string {
60
+	if min >= max || min == 0 || max == 0 {
61
+		return strconv.FormatInt(max, 10)
62
+	}
63
+	rand.Seed(time.Now().UnixNano())
64
+	randNum := rand.Int63n(max-min) + min
65
+	return strconv.FormatInt(randNum, 10)
66
+}
67
+
68
+func TimeAgo(timeUnix int64) string {
69
+	timeUnixS := time.Unix(timeUnix, 0)
70
+	timeNow := time.Now()
71
+	timeSub := timeNow.Sub(timeUnixS)
72
+
73
+	if timeSub < time.Minute*1 {
74
+		return "刚刚"
75
+	} else if timeSub < time.Hour*1 {
76
+		return strconv.Itoa(int(timeSub.Minutes())) + "分钟前"
77
+	} else if timeSub < time.Hour*24 {
78
+		return strconv.Itoa(int(timeSub.Hours())) + "小时前"
79
+	} else if timeSub < time.Hour*24*7 {
80
+		return strconv.Itoa(int(timeSub.Hours()/24)) + "天前"
81
+	} else {
82
+		return timeUnixS.Format("2006-01-02 15:04")
83
+	}
84
+	return ""
85
+}
86
+
87
+//Signature sha1签名
88
+func Signature(params ...string) string {
89
+	sort.Strings(params)
90
+	h := sha1.New()
91
+	for _, s := range params {
92
+		io.WriteString(h, s)
93
+	}
94
+	return fmt.Sprintf("%x", h.Sum(nil))
95
+}
96
+
97
+//RandomStr 随机生成字符串
98
+func RandomStr(length int) string {
99
+	str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
100
+	bytes := []byte(str)
101
+	result := []byte{}
102
+	r := rand.New(rand.NewSource(time.Now().UnixNano()))
103
+	for i := 0; i < length; i++ {
104
+		result = append(result, bytes[r.Intn(len(bytes))])
105
+	}
106
+	return string(result)
107
+}
108
+
109
+//GetCurrTs return current timestamps
110
+func GetCurrTs() int64 {
111
+	return time.Now().Unix()
112
+}
113
+
114
+func SetThisRequestURI(uri string) string {
115
+	return fmt.Sprintf("%v%v", beego.AppConfig.String("httpdomain"), uri)
116
+}
117
+
118
+func SetThisBasr64RequestURI(uri string) string {
119
+	backUrl := fmt.Sprintf("%v%v", beego.AppConfig.String("httpdomain"), uri)
120
+	backUrl = base64.URLEncoding.EncodeToString([]byte(backUrl))
121
+
122
+	return backUrl
123
+}
124
+
125
+func TransNum2Str(read int64) (transRead string) {
126
+	if read < 0 {
127
+		transRead = "0"
128
+	} else if read < 10000 {
129
+		transRead = fmt.Sprintf("%v", read)
130
+	} else {
131
+		var c float64 = 10000
132
+		var rc float64 = float64(read)
133
+		transRead = fmt.Sprintf("%.2f万", rc/c)
134
+	}
135
+
136
+	return
137
+}
138
+
139
+func GenMobileToken(mobile string) (token string) {
140
+	st := strings.Split(mobile, "")
141
+
142
+	s := fmt.Sprintf("%s%v%v%v%v%v%v", mobile, st[0], st[1], st[3], st[7], st[6], st[9])
143
+
144
+	h := sha1.New()
145
+	h.Write([]byte(s))
146
+	bs := h.Sum(nil)
147
+
148
+	token = fmt.Sprintf("%x", bs)
149
+
150
+	return
151
+}
152
+
153
+func CheckMobileToken(mobile, token string) bool {
154
+	o := GenMobileToken(mobile)
155
+	if token == o {
156
+		return true
157
+	}
158
+
159
+	return false
160
+}
161
+
162
+type jSapiConfig struct {
163
+	AppID     string `json:"app_id"`
164
+	Timestamp int64  `json:"timestamp"`
165
+	NonceStr  string `json:"nonce_str"`
166
+	Signature string `json:"signature"`
167
+}
168
+
169
+//GetAJTConfig jsapi_ticket config
170
+func GetAJTConfig(jsapiTicket, uri string) (jSapiConfig, error) {
171
+	var config jSapiConfig
172
+	nonceStr := RandomStr(16)
173
+	timestamp := GetCurrTs()
174
+	str := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s&timestamp=%d&url=%s", jsapiTicket, nonceStr, timestamp, uri)
175
+	sigStr := Signature(str)
176
+
177
+	config.AppID = beego.AppConfig.String("wxappId")
178
+	config.NonceStr = nonceStr
179
+	config.Timestamp = timestamp
180
+	config.Signature = sigStr
181
+	return config, nil
182
+}
183
+
184
+func TrimHtml(src string) string {
185
+	//将HTML标签全转换成小写
186
+	re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
187
+	src = re.ReplaceAllStringFunc(src, strings.ToLower)
188
+	//去除STYLE
189
+	re, _ = regexp.Compile("\\<style[\\S\\s]+?\\</style\\>")
190
+	src = re.ReplaceAllString(src, "")
191
+	//去除SCRIPT
192
+	re, _ = regexp.Compile("\\<script[\\S\\s]+?\\</script\\>")
193
+	src = re.ReplaceAllString(src, "")
194
+	//去除所有尖括号内的HTML代码,并换成换行符
195
+	re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
196
+	src = re.ReplaceAllString(src, "\n")
197
+	//去除连续的换行符
198
+	re, _ = regexp.Compile("\\s{2,}")
199
+	src = re.ReplaceAllString(src, "\n")
200
+	return strings.TrimSpace(src)
201
+}
202
+
203
+func SubString(str string, begin, length int) string {
204
+	rs := []rune(str)
205
+	lth := len(rs)
206
+	if begin < 0 {
207
+		begin = 0
208
+	}
209
+	if begin >= lth {
210
+		begin = lth
211
+	}
212
+	end := begin + length
213
+
214
+	if end > lth {
215
+		end = lth
216
+	}
217
+	return string(rs[begin:end])
218
+}
219
+
220
+func ParseTimeStringToTime(layout string, timeStr string) (*time.Time, error) {
221
+	if len(layout) == 0 || len(timeStr) == 0 {
222
+		return nil, errors.New("layout 或 日期字符串 为空,无法解析")
223
+	}
224
+	loc, _ := time.LoadLocation("Local")
225
+	date, parseDateErr := time.ParseInLocation(layout, timeStr, loc)
226
+	return &date, parseDateErr
227
+}
228
+
229
+// 获取 date 所在周的周一和周日,以周一0点为一周的开始,周日24点为一周的结束
230
+func GetMondayAndSundayOfWeekDate(date *time.Time) (time.Time, time.Time) {
231
+	if date == nil {
232
+		now := time.Now()
233
+		date = &now
234
+	}
235
+	weekday := int(date.Weekday())
236
+	if weekday == 0 {
237
+		weekday = 7
238
+	}
239
+	loc, _ := time.LoadLocation("Local")
240
+	monday, _ := time.ParseInLocation("2006-01-02 15:04:05", date.AddDate(0, 0, 1-weekday).Format("2006-01-02")+" 00:00:00", loc)
241
+	sunday, _ := time.ParseInLocation("2006-01-02 15:04:05", date.AddDate(0, 0, 7-weekday).Format("2006-01-02")+" 23:59:59", loc)
242
+	return monday, sunday
243
+}
244
+
245
+func GetOrgIdCode(orgID int64, timestamps int64) (int64, string) {
246
+	if timestamps == 0 {
247
+		timestamps = time.Now().Unix()
248
+	}
249
+
250
+	key := "47&hsq5wjfHXy%m&"
251
+	stringA := fmt.Sprintf("org_id=%d&time=%d&key=%s", orgID, timestamps, key)
252
+
253
+	md5 := md5.New()
254
+	md5.Write([]byte(stringA))
255
+	md5Data := md5.Sum([]byte(nil))
256
+	md5A := hex.EncodeToString(md5Data)
257
+	return timestamps, md5A
258
+}