张保健 3 年前
当前提交
fa8ba00aa6

+ 186 - 0
conf/app.conf 查看文件

@@ -0,0 +1,186 @@
1
+appname = IC
2
+httpport = 9818
3
+runmode = prod
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
+sms_appId = dcabb3aa7afd402794046ebbbf652bce
16
+sms_sid = a26cb0ceb3a811ca82143972f4ef38a4
17
+sms_token = ea475ed8d3de6c54c2b3f9d78db76d1e
18
+sms_baseUrl = https://open.ucpaas.com/ol/sms/
19
+ip_max_send_count = 20
20
+moblie_max_send_count = 5
21
+sms_verification_code_templateid = 329532
22
+
23
+appid = "wx43ad410d9eef426e"
24
+mchid = "1509573721"
25
+key = "e4SHrkiZu0pQEwVoGBapDBTf9N1Q6MxV"
26
+appsecret="61ee2e6268497d5aa9de0b0187c39aea"
27
+
28
+[prod]
29
+httpdomain = https://api.xt.kuyicloud.com
30
+sso_domain = https://sso.kuyicloud.com
31
+front_end_domain = "https://xt.kuyicloud.com/#"
32
+
33
+readmysqlhost = shengws1.mysql.rds.aliyuncs.com
34
+readmysqlport = 3306
35
+readmysqluser = syh
36
+readmysqlpass = xhPECP2nFObR8aUK
37
+readmysqlname = sgj_xt
38
+
39
+writemysqlhost = shengws1.mysql.rds.aliyuncs.com
40
+writemysqlport = 3306
41
+writemysqluser = syh
42
+writemysqlpass = xhPECP2nFObR8aUK
43
+writemysqlname = sgj_xt
44
+
45
+readremotehost = 219.135.207.166
46
+readremoteport = 1433
47
+readremoteuser = lis_xt
48
+readremotepass = xt2020
49
+readremotename = digitlab
50
+
51
+
52
+readuserhost = shengws1.mysql.rds.aliyuncs.com
53
+readuserport = 3306
54
+readuseruser = syh
55
+readuserpass = xhPECP2nFObR8aUK
56
+readusername = sgj_users
57
+
58
+writeuserhost = shengws1.mysql.rds.aliyuncs.com
59
+writeuserport = 3306
60
+writeuseruser = syh
61
+writeuserpass = xhPECP2nFObR8aUK
62
+writeusername = sgj_users
63
+
64
+readmiddlehost = shengws1.mysql.rds.aliyuncs.com
65
+readmiddleport = 3306
66
+readmiddleuser = syh
67
+readmiddlepass = xhPECP2nFObR8aUK
68
+readmiddlename = ky_xt_middle
69
+
70
+writemiddlehost = shengws1.mysql.rds.aliyuncs.com
71
+writemiddleport = 3306
72
+writemiddleuser = syh
73
+writemiddlepass = xhPECP2nFObR8aUK
74
+writemiddlename = ky_xt_middle
75
+
76
+backuphost = 120.76.159.131
77
+backupport = 3306
78
+backupuser = syh
79
+backuppass = xhPECP2nFObR8aUK
80
+backupname = sgj_xt
81
+
82
+
83
+redishost = kuyi6666.redis.rds.aliyuncs.com
84
+redisport = 6379
85
+redispasswrod = TZtBW098WId3i27clkpj3q8dnUaVFP
86
+redisdb = 2
87
+
88
+
89
+
90
+
91
+niprocart =  63
92
+jms = 58
93
+fistula_needle_set = 65
94
+fistula_needle_set_16 = 64
95
+hemoperfusion = 55
96
+dialyser_sterilised = 12
97
+filtryzer = 53
98
+dialyzers = 8
99
+injector = 81
100
+bloodlines = 42
101
+tubingHemodialysis = 30
102
+package = 82
103
+aliquid = 83
104
+
105
+
106
+
107
+[dev]
108
+httpdomain = http://api.xt.test.sgjyun.com
109
+sso_domain = https://testsso.sgjyun.com
110
+front_end_domain = "http://xt.test.sgjyun.com/#"
111
+
112
+readmysqlhost = rm-wz9rg531npf61q03tro.mysql.rds.aliyuncs.com
113
+readmysqlport = 3306
114
+readmysqluser = root
115
+readmysqlpass = 1Q2W3e4r!@#$
116
+readmysqlname = sgj_xt
117
+
118
+writemysqlhost = rm-wz9rg531npf61q03tro.mysql.rds.aliyuncs.com
119
+writemysqlport = 3306
120
+writemysqluser = root
121
+writemysqlpass = 1Q2W3e4r!@#$
122
+writemysqlname = sgj_xt
123
+
124
+readremotehost = 219.135.207.166
125
+readremoteport = 1433
126
+readremoteuser = lis_xt
127
+readremotepass = xt2020
128
+readremotename = digitlab
129
+
130
+
131
+readuserhost = rm-wz9rg531npf61q03tro.mysql.rds.aliyuncs.com
132
+readuserport = 3306
133
+readuseruser = root
134
+readuserpass = 1Q2W3e4r!@#$
135
+readusername = sgj_users
136
+
137
+writeuserhost = rm-wz9rg531npf61q03tro.mysql.rds.aliyuncs.com
138
+writeuserport = 3306
139
+writeuseruser = root
140
+writeuserpass = 1Q2W3e4r!@#$
141
+writeusername = sgj_users
142
+
143
+
144
+readmiddlehost = rm-wz9rg531npf61q03tro.mysql.rds.aliyuncs.com
145
+readmiddleport = 3306
146
+readmiddleuser = root
147
+readmiddlepass = 1Q2W3e4r!@#$
148
+readmiddlename = ky_xt_middle
149
+
150
+writemiddlehost = rm-wz9rg531npf61q03tro.mysql.rds.aliyuncs.com
151
+writemiddleport = 3306
152
+writemiddleuser = root
153
+writemiddlepass = 1Q2W3e4r!@#$
154
+writemiddlename = ky_xt_middle
155
+
156
+# backuphost = 120.76.159.131
157
+# backupport = 3306
158
+# backupuser = syh
159
+# backuppass = xhPECP2nFObR8aUK
160
+# backupname = sgj_xt
161
+
162
+
163
+
164
+
165
+#redishost = 120.77.235.13
166
+# redishost = 112.74.16.180
167
+redishost = 112.74.16.180
168
+redisport = 6379
169
+redispasswrod = syh@#$%123456!
170
+redisdb = 0
171
+
172
+
173
+
174
+niprocart =  83
175
+jms = 80
176
+fistula_needle_set = 81
177
+fistula_needle_set_16 = 82
178
+hemoperfusion = 85
179
+dialyser_sterilised = 84
180
+filtryzer = 79
181
+dialyzers = 10000
182
+injector = 10001
183
+bloodlines = 10002
184
+tubingHemodialysis = 10003
185
+package = 10004
186
+aliquid = 10005

+ 56 - 0
controllers/base_api_controller.go 查看文件

@@ -0,0 +1,56 @@
1
+package controllers
2
+
3
+import (
4
+	_"IC/service"
5
+	"IC/enums"
6
+	"github.com/astaxie/beego"
7
+)
8
+
9
+type BaseAPIController struct {
10
+	beego.Controller
11
+}
12
+
13
+// func (this *BaseAPIController) Prepare() {
14
+// 	this.BaseController.Prepare()
15
+// 	beego.Trace("============================================================")
16
+// 	beego.Trace("session ID: %v", this.Ctx.Input.Cookie("beegosessionID"))
17
+// 	beego.Trace("session : %v", this.GetSession("info"))
18
+// 	this.SetSession("info", time.Now().Format("2006/01/02 15:04:05"))
19
+// 	beego.Trace("============================================================")
20
+// }
21
+
22
+// 输出数据格式化
23
+/*
24
+	success json:
25
+	{
26
+		"state": 1,
27
+		"code": 0,
28
+		"data": json,
29
+	}
30
+
31
+	fail json:
32
+	{
33
+		"state": 0,
34
+		"code": int,
35
+		"msg": string,
36
+	}
37
+*/
38
+func (this *BaseAPIController) ServeSuccessJSON(data map[string]interface{}) {
39
+	this.Data["json"] = enums.MakeSuccessResponseJSON(data)
40
+	this.ServeJSON()
41
+}
42
+
43
+func (this *BaseAPIController) ServeFailJSONWithSGJErrorCode(code int) {
44
+	this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(code)
45
+	this.ServeJSON()
46
+}
47
+
48
+func (this *BaseAPIController) ServeFailJSONWithSGJError(err *enums.SGJError) {
49
+	this.Data["json"] = enums.MakeFailResponseJSONWithSGJError(err)
50
+	this.ServeJSON()
51
+}
52
+
53
+func (this *BaseAPIController) ServeFailJsonSend(code int, msg string) {
54
+	this.Data["json"] = enums.MakeFailResponseJSON(msg, code)
55
+	this.ServeJSON()
56
+}

+ 15 - 0
controllers/default.go 查看文件

@@ -0,0 +1,15 @@
1
+package controllers
2
+
3
+import (
4
+	"github.com/astaxie/beego"
5
+)
6
+
7
+type MainController struct {
8
+	beego.Controller
9
+}
10
+
11
+func (c *MainController) Get() {
12
+	c.Data["Website"] = "beego.me"
13
+	c.Data["Email"] = "astaxie@gmail.com"
14
+	c.TplName = "index.tpl"
15
+}

+ 398 - 0
controllers/lis.go 查看文件

@@ -0,0 +1,398 @@
1
+package controllers
2
+
3
+import (
4
+	"IC/service"
5
+	"IC/enums"
6
+	_"strconv"
7
+	"encoding/json"
8
+	"IC/models"
9
+	"IC/utils"
10
+	"time"
11
+	_"fmt"
12
+	_"github.com/jinzhu/gorm"
13
+	_"github.com/astaxie/beego"
14
+)
15
+
16
+// LisController operations for Lis
17
+type LisController struct {
18
+	BaseAPIController
19
+}
20
+
21
+func (c *LisController) SyncAdvice(){
22
+	// 获取备份库里所有的医嘱信息
23
+	advices,_ := service.GetAllAdvice()
24
+	for _,advice := range advices {
25
+		// if index > 50 {
26
+		// 	break
27
+		// }
28
+		tempAdvice := models.DoctorAdvice{
29
+			ID			: advice.ID,
30
+			Checker		: advice.Checker,
31
+			CheckTime	: advice.CheckTime,
32
+			CheckState	: advice.CheckState,
33
+		}
34
+		service.SyncAdvice(&tempAdvice)
35
+	}
36
+
37
+	c.ServeSuccessJSON(map[string]interface{}{
38
+		"resultList": "12345",
39
+	})
40
+	return
41
+
42
+}
43
+
44
+func (c *LisController) FiledConfigSys(){
45
+	orgs,_ := service.GetfiledConfigOrg()
46
+	sysFiledConfig,_ := service.GetfiledConfigSys()
47
+
48
+	if len(orgs) > 0 {
49
+		for _,org := range orgs {
50
+			for _,filed := range sysFiledConfig {
51
+				filedConfig,_ := service.GetfiledConfigByOrgId(org.OrgId,filed.Module,filed.FiledName)	
52
+				if filedConfig.ID > 0 {
53
+					continue
54
+				} else {
55
+					tempfiled := models.FiledConfig {
56
+						OrgId       : org.OrgId,
57
+						Module      : filed.Module,
58
+						FiledName   : filed.FiledName,
59
+						FiledNameCn : filed.FiledNameCn,
60
+						IsShow      : 2,
61
+					}
62
+					service.CreatefiledConfig(&tempfiled)
63
+				}
64
+			}
65
+		}
66
+	}
67
+
68
+	c.ServeSuccessJSON(map[string]interface{}{
69
+		"resultList": "12345",
70
+	})
71
+	return
72
+}
73
+
74
+func (c *LisController) SyncToBase() {
75
+	org_id, _:= c.GetInt64("org_id",0) 
76
+	if org_id <= 0 {
77
+		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
78
+		return
79
+	}
80
+	
81
+	// 第一步:跟进org_id 去中间库查出需要同步的数据
82
+	inspection_references,_ := service.GetSyncInspectionReferenceByOrgId(org_id)
83
+	inspections,_ := service.GetSyncInspectionByOrgId(org_id)
84
+
85
+	// 第二步:将数据同步到业务库
86
+	if len(inspection_references) > 0 {
87
+		for _,inspection_reference := range inspection_references {
88
+			service.SyncInspectionReference(&inspection_reference)
89
+		}
90
+	}
91
+
92
+	if len(inspections) > 0 {
93
+		for _,inspection := range inspections {
94
+			service.SyncInspection(&inspection)
95
+		}
96
+	}
97
+
98
+	c.ServeSuccessJSON(map[string]interface{}{
99
+		"resultList": "12345",
100
+	})
101
+	return
102
+}
103
+
104
+func (c *LisController) GetList() {
105
+	org_id, _ := c.GetInt64("org_id", 0)
106
+	if org_id <= 0 {
107
+		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
108
+		return
109
+	}
110
+
111
+	// 第一步:根据机构id获取对应机构所有病人的his_user_id
112
+	patients,patientError := service.GetHisUserIdByOrgID(org_id)
113
+	if patientError != nil {
114
+		utils.ErrorLog("获取用户His_user_id信息失败:%v", patientError)
115
+		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
116
+		return
117
+	}
118
+
119
+	patientStr:= make([]interface{},0)
120
+	if len(patients) > 0 {
121
+	// 第二步:根据病人的his_user_id来查询上次同步时间	
122
+		for _ , patient := range patients {
123
+			if len(patient.HisUserId) <= 0 {
124
+				continue
125
+			}
126
+			// if patient.SelectType != 1 {
127
+			// 	continue
128
+			// }
129
+
130
+			syncLastInfo,_ := service.GetSyncTimeByOrgID(org_id,patient.HisUserId)
131
+			var sync_time int64
132
+			if syncLastInfo.ID > 0 {
133
+				sync_time = syncLastInfo.SyncTime
134
+			} else {
135
+				inspectionLastInfo,_ := service.GetInspectionLastInfoByOrgID(org_id,patient.HisUserId)
136
+				if inspectionLastInfo.ID > 0 {
137
+					sync_time = inspectionLastInfo.CreatedTime
138
+				} else {
139
+					sync_time = 1609430400
140
+				}
141
+			}
142
+
143
+			syncTimes := time.Unix(sync_time,0).Format("2006-01-02 15:04")
144
+			utils.InfoLog("syncTimes:%v",syncTimes)
145
+
146
+			// 第三步:跟进上次同步时间和指定的his_user_id,获取上次同步到现在指定人的检验检查记录
147
+			resultList, _ := service.GetListByHisUserID(patient.HisUserId,syncTimes,patient.SelectType)
148
+			var syncInfo models.MiddleSyncInfo
149
+	
150
+			if len(resultList) > 0 {
151
+				// 如果有数据,则把同步过来的详情插入一条数据到同步详情表中
152
+				syncInfo.OrgId = org_id
153
+				syncInfo.HisUserId = patient.HisUserId
154
+				syncInfo.SyncTime = time.Now().Unix()
155
+				syncInfo.SyncResultType = 1
156
+				syncInfo.SyncRsultRemark = "同步成功"
157
+				syncInfo.SyncTotalNum = int64(len(resultList))
158
+				syncInfo.SyncSuccessNum = 0
159
+				SyncInfos,_ := json.Marshal(resultList)
160
+				syncInfo.SyncInfo = string(SyncInfos)
161
+				syncInfo.CreateTime = time.Now().Unix()
162
+				syncInfo.UpdateTime = time.Now().Unix()
163
+
164
+				err := service.CreateSyncInfo(&syncInfo)
165
+				if err != nil {
166
+					utils.ErrorLog("创建同步信息失败:%v", err)
167
+					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
168
+					return
169
+				}
170
+			} else {
171
+				// 如果没有数据,则插入一条数据到同步详情表中
172
+				syncInfo.OrgId = org_id
173
+				syncInfo.HisUserId = patient.HisUserId
174
+				syncInfo.SyncTime = time.Now().Unix()
175
+				syncInfo.SyncResultType = 1
176
+				syncInfo.SyncRsultRemark = "该患者这个时间段没有任何检验检查数据"
177
+				syncInfo.CreateTime = time.Now().Unix()
178
+				syncInfo.UpdateTime = time.Now().Unix()
179
+
180
+				err := service.CreateSyncInfo(&syncInfo)
181
+				if err != nil {
182
+					utils.ErrorLog("创建同步信息失败:%v", err)
183
+					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
184
+					return
185
+				}
186
+				// utils.InfoLog("同步信息详情:%v",syncInfo)
187
+				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
188
+				continue 
189
+			}
190
+
191
+			// 第四部:将同步过来的数据插入到中间库对应的表
192
+			syncSuccessNum := 0
193
+			for _, result := range resultList {
194
+				utils.ErrorLog("result:%v", result)
195
+				if (result.HisUserId == patient.HisUserId) || (result.PatientName ==  patient.HisUserId) {
196
+					patientId := patient.XtPatientId
197
+					if patientId > 0 {
198
+						inspection_reference,inspection,_ := service.Sync(result,org_id,patientId)
199
+						if (inspection_reference.ID > 0 || inspection.ID > 0 ) {
200
+							syncSuccessNum++
201
+						}
202
+					}
203
+				}
204
+			}
205
+			syncInfo.SyncSuccessNum = int64(syncSuccessNum)
206
+			service.UpdateSyncInfo(&syncInfo)
207
+
208
+			// patientStr = append(patientStr,patient.HisUserId)
209
+			// utils.InfoLog("patientStr:%v",patientStr)	
210
+		}
211
+	} else {
212
+		var syncInfo models.MiddleSyncInfo
213
+		// 如果没有数据,则插入一条数据到同步详情表中
214
+		syncInfo.OrgId = org_id
215
+		syncInfo.SyncTime = time.Now().Unix()
216
+		syncInfo.SyncResultType = 0
217
+		syncInfo.SyncRsultRemark = "该机构没有对应的his_user_id"
218
+		syncInfo.CreateTime = time.Now().Unix()
219
+		syncInfo.UpdateTime = time.Now().Unix()
220
+
221
+		err := service.CreateSyncInfo(&syncInfo)
222
+		if err != nil {
223
+			utils.ErrorLog("创建同步信息失败:%v", err)
224
+			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
225
+			return
226
+		}
227
+		utils.InfoLog("同步信息详情:%v",syncInfo)
228
+		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
229
+		return 
230
+	}
231
+
232
+	utils.InfoLog("patientStr:%v",patientStr) 
233
+
234
+
235
+	// // 第一步:根据机构id获取上次同步时间
236
+	// syncLastInfo,_ := service.GetSyncTimeByOrgID(org_id)
237
+	// var sync_time int64
238
+	// if syncLastInfo.ID > 0 {
239
+	// 	sync_time = syncLastInfo.SyncTime
240
+	// } else {
241
+	// 	sync_time = 0
242
+	// }
243
+
244
+	// syncTimes := time.Unix(sync_time,0).Format("2006-01-02 15:04")
245
+	// utils.InfoLog("syncTimes:%v",syncTimes)
246
+
247
+	// // 第二步:根据机构id获取对应机构所有病人的his_user_id
248
+	// patients,patientError := service.GetHisUserIdByOrgID(org_id)
249
+	// if patientError != nil {
250
+	// 	utils.ErrorLog("获取用户His_user_id信息失败:%v", patientError)
251
+	// 	c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
252
+	// 	return
253
+	// }
254
+
255
+	// patientStr:= make([]interface{},0)
256
+	// if len(patients) > 0 {
257
+	// 	for _ , patient := range patients {
258
+	// 		patientStr = append(patientStr,patient.HisUserId)
259
+	// 		utils.InfoLog("patientStr:%v",patientStr)	
260
+	// 	}
261
+	// } else {
262
+	// 	// 如果没有数据,则插入一条数据到同步详情表中
263
+	// 	syncInfo.OrgId = org_id
264
+	// 	syncInfo.SyncTime = time.Now().Unix()
265
+	// 	syncInfo.SyncResultType = 0
266
+	// 	syncInfo.SyncRsultRemark = "该机构没有对应的his_user_id"
267
+	// 	syncInfo.CreateTime = time.Now().Unix()
268
+	// 	syncInfo.UpdateTime = time.Now().Unix()
269
+
270
+	// 	err := service.CreateSyncInfo(&syncInfo)
271
+	// 	if err != nil {
272
+	// 		utils.ErrorLog("创建同步信息失败:%v", err)
273
+	// 		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
274
+	// 		return
275
+	// 	}
276
+	// 	utils.InfoLog("同步信息详情:%v",syncInfo)
277
+	// 	c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
278
+	// 	return 
279
+	// }
280
+
281
+	// utils.InfoLog("patientStr:%v",patientStr) 
282
+
283
+	// // 第三步:跟进上次同步时间和指定的his_user_id,获取上次同步到现在指定人的检验检查记录
284
+	// resultList, _ := service.GetList(patientStr,syncTimes)
285
+	
286
+	// if len(resultList) > 0 {
287
+	// 	// 如果有数据,则把同步过来的详情插入一条数据到同步详情表中
288
+	// 	syncInfo.OrgId = org_id
289
+	// 	syncInfo.SyncTime = time.Now().Unix()
290
+	// 	syncInfo.SyncResultType = 1
291
+	// 	syncInfo.SyncRsultRemark = "同步成功"
292
+	// 	syncInfo.SyncTotalNum = int64(len(resultList))
293
+	// 	syncInfo.SyncSuccessNum = 0
294
+	// 	SyncInfos,_ := json.Marshal(resultList)
295
+	// 	syncInfo.SyncInfo = string(SyncInfos)
296
+	// 	syncInfo.CreateTime = time.Now().Unix()
297
+	// 	syncInfo.UpdateTime = time.Now().Unix()
298
+
299
+	// 	err := service.CreateSyncInfo(&syncInfo)
300
+	// 	if err != nil {
301
+	// 		utils.ErrorLog("创建同步信息失败:%v", err)
302
+	// 		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
303
+	// 		return
304
+	// 	}
305
+	// } else {
306
+	// 	// 如果没有数据,则插入一条数据到同步详情表中
307
+	// 	syncInfo.OrgId = org_id
308
+	// 	syncInfo.SyncTime = time.Now().Unix()
309
+	// 	syncInfo.SyncResultType = 1
310
+	// 	syncInfo.SyncRsultRemark = "该机构这个时间段没有任何检验检查数据"
311
+	// 	syncInfo.CreateTime = time.Now().Unix()
312
+	// 	syncInfo.UpdateTime = time.Now().Unix()
313
+
314
+	// 	err := service.CreateSyncInfo(&syncInfo)
315
+	// 	if err != nil {
316
+	// 		utils.ErrorLog("创建同步信息失败:%v", err)
317
+	// 		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
318
+	// 		return
319
+	// 	}
320
+	// 	// utils.InfoLog("同步信息详情:%v",syncInfo)
321
+	// 	c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
322
+	// 	return 
323
+	// }
324
+
325
+	// // 第四部:将同步过来的数据插入到中间库对应的表
326
+	// syncSuccessNum := 0
327
+	// for _, result := range resultList {
328
+	// 	patientId := int64(0)
329
+	// 	for _ , patientInfo := range patients {
330
+	// 		if result.HisUserId == patientInfo.HisUserId {
331
+	// 			patientId = patientInfo.XtPatientId
332
+	// 			break
333
+	// 		}
334
+	// 	}
335
+	// 	if patientId > 0 {
336
+	// 		inspection_reference,inspection,_ := service.Sync(result,org_id,patientId)
337
+	// 		if (inspection_reference.ID > 0 || inspection.ID > 0 ) {
338
+	// 			syncSuccessNum++
339
+	// 		}
340
+	// 	}
341
+	// }
342
+	// syncInfo.SyncSuccessNum = int64(syncSuccessNum)
343
+	// service.UpdateSyncInfo(&syncInfo)
344
+
345
+	c.ServeSuccessJSON(map[string]interface{}{
346
+		"resultList": patients,
347
+	})
348
+	return
349
+
350
+}
351
+
352
+func (c *LisController) SyncLgth(){
353
+	service.SyncLisLgty()
354
+	c.ServeSuccessJSON(map[string]interface{}{
355
+		"resultList": "12345",
356
+	})
357
+	return
358
+}
359
+
360
+func (c *LisController) SyncYstx(){
361
+	service.SyncLisYstx()
362
+	c.ServeSuccessJSON(map[string]interface{}{
363
+		"resultList": "12345",
364
+	})
365
+	return
366
+}
367
+
368
+func (c *LisController) SyncGzjhyz(){
369
+	service.SyncGzjhyz()
370
+	c.ServeSuccessJSON(map[string]interface{}{
371
+		"resultList": "12345",
372
+	})
373
+	return
374
+}
375
+
376
+func (c *LisController) SyncGzjhLis(){
377
+	service.SyncGzjhLis()
378
+	c.ServeSuccessJSON(map[string]interface{}{
379
+		"resultList": "12345",
380
+	})
381
+	return
382
+}
383
+
384
+func (c *LisController) SyncHbJldyyz(){
385
+	service.SyncHbJldyyz()
386
+	c.ServeSuccessJSON(map[string]interface{}{
387
+		"resultList": "12345",
388
+	})
389
+	return
390
+}
391
+
392
+func (c *LisController) SyncHbJldyLis(){
393
+	service.SyncHbdyLis()
394
+	c.ServeSuccessJSON(map[string]interface{}{
395
+		"resultList": "12345",
396
+	})
397
+	return
398
+}

+ 401 - 0
enums/error_code.go 查看文件

@@ -0,0 +1,401 @@
1
+package enums
2
+
3
+import "IC/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
+
25
+	// 数据验证错误 7000+
26
+	ErrorCodeMobileFormat     = 7001
27
+	ErrorCodeTelphoneFormat   = 7002
28
+	ErrorCodeParamWrong       = 7003
29
+	ErrorCodeParamFormatWrong = 7004
30
+
31
+	// 数据库操作错误 8000+
32
+	ErrorCodeDBCreate         = 8001
33
+	ErrorCodeDBUpdate         = 8002
34
+	ErrorCodeDBDelete         = 8003
35
+	ErrorCodeDBSelectNoResult = 8004
36
+	ErrorCodeDataException    = 8005
37
+
38
+	// 业务逻辑操作错误 9000+
39
+	ErrorCodeRoleNotExist           = 9001
40
+	ErrorCodeAdminUserNotExist      = 9002
41
+	ErrorCodeMobileDidUsedInApp     = 9003
42
+	ErrorCodeMissingUserName        = 9004
43
+	ErrorCodeOldPasswordWrong       = 9005
44
+	ErrorCodeCannotRemoveRole       = 9006
45
+	ErrorCodeRoleMobileIsSuperAdmin = 9007
46
+
47
+	ErrorCodeGetQiniuUpToken                = 1001
48
+	ErrorCodeCreatePatient                  = 1002
49
+	ErrorCodeDialysisNoExist                = 1003
50
+	ErrorCodeIdCardNoExist                  = 1004
51
+	ErrorCodePatientNoExist                 = 1005
52
+	ErrorCodeUpdatePatient                  = 1006
53
+	ErrorCodeDialysisSolutionExist          = 1007
54
+	ErrorCodeDialysisSolutionCreate         = 1008
55
+	ErrorCodeDialysisSolutionUpdate         = 1009
56
+	ErrorCodeDialysisSolutionNotExist       = 1010
57
+	ErrorCodeParentDialysisSolutionNotExist = 1011
58
+	ErrorCodeAlReadyHadChildSolution        = 1012
59
+	ErrorCodeCanntCreateChildChildSolution  = 1013
60
+	ErrorCodeDialysisSolutionUsed           = 1014
61
+	ErrorCodeCreateDryWeightFail            = 1015
62
+	ErrorCodeCreateDoctorAdviceFail         = 1016
63
+	ErrorCodeDoctorAdviceNotExist           = 1017
64
+	ErrorCodeUpdateDoctorAdviceFail         = 1018
65
+	ErrorCodeLongTimeAdviceNotCanntEdit     = 1019
66
+	ErrorCodeAdviceStoped                   = 1020
67
+	ErrorCodeParentAdviceNotExist           = 1021
68
+	ErrorCodeStopAdviceFail                 = 1022
69
+	ErrorCodeDeleteAdviceFail               = 1023
70
+	ErrorCodeDialysisSolutionDelete         = 1024
71
+	ErrorCodeDeviceNumberNotTheZone         = 1025
72
+	ErrorCodeCreateScheduleFail             = 1026
73
+	ErrorCodeCantSetScheduleAgainOneDay     = 1027
74
+	ErrorCodeCantSetScheduleBeforeNow       = 1028
75
+	ErrorCodeScheduleNotExist               = 1029
76
+	ErrorCodeDeleteScheduleFail             = 1030
77
+	ErrorCodeChangeScheduleFail             = 1031
78
+	ErrorCodePatientPhoneUsed               = 1032
79
+	ErrorCodeAdviceExced                    = 1033
80
+	ErrorCodeAdviceChecked                  = 1034
81
+	ErrorCodePointScheduleExist             = 1035
82
+	ErrorCodeExceAndCheckNotOneUser         = 1036
83
+	ErrorCodeCanotEditOtherAdvice           = 1037
84
+	ErrorCodeEditLapsetoFail                = 1038
85
+	ErrorCodeAdviceCheckBeforeExce          = 1039
86
+	ErrorCodeAdviceExceBeforeStart          = 1040
87
+	ErrorCodeDelScheduleFailByDialysis      = 1041
88
+	ErrorCodeNotSelectLapsetoType           = 1042
89
+	ErrorCodeNotSelectLapsetoTime           = 1043
90
+
91
+	ErrorCodeInspectionDateExit    = 1201
92
+	ErrorCodeInspectionAddFail     = 1202
93
+	ErrorCodeInspectionEditFail    = 1204
94
+	ErrorCodeInspectionDateNotExit = 1203
95
+	ErrorCodeInspectionDeleteFail  = 1205
96
+
97
+	ErrorCodeMonitorCreate                  = 1128
98
+	ErrorCodeMonitorNotExist                = 1129
99
+	ErrorCodeMonitorUpdate                  = 1130
100
+	ErrorDialysisOrderNoStart               = 1132
101
+	ErrorDialysisOrderNoEND                 = 1133
102
+	ErrorDialysisOrderRepeatStart           = 1134
103
+	ErrorDialysisOrderRepeatBed             = 1136
104
+	ErrorCodeDialysisPermissionDeniedModify = 1135
105
+
106
+	ErrorCodeNotSubscibe       = 4003
107
+	ErrorCodeServeNotExist     = 4004
108
+	ErrorCodeInvoiceExist      = 4005
109
+	ErrorCodeApplyInvoiceFail  = 4006
110
+	ErrorCodeHetongHad         = 4007
111
+	ErrorCodeCreateHetongFail  = 4008
112
+	ErrorCodePatientReachLimit = 4009
113
+
114
+	ErrorCodeDeviceZoneNotExist                      = 9021
115
+	ErrorCodeDeviceZoneNameRepeat                    = 9022
116
+	ErrorCodeDeviceGroupNotExist                     = 9023
117
+	ErrorCodeDeviceGroupNameRepeat                   = 9024
118
+	ErrorCodeDeviceNumberNotExist                    = 9025
119
+	ErrorCodeDeviceNumberRepeat                      = 9026
120
+	ErrorCodeDeviceNotExist                          = 9027
121
+	ErrorCodeDeviceZoneCannotDisable                 = 9028
122
+	ErrorCodeDeviceNumberCannotDisableCuzDevice      = 9029
123
+	ErrorCodeDeviceNumberCannotDisableCuzSchedule    = 9030
124
+	ErrorCodeDeviceNumberCannotDisableCuzSchTemplate = 9031
125
+
126
+	ErrorCommitFail = 90000
127
+
128
+	ErrorCodeCreateStockInFail = 20001
129
+
130
+	ErrorCodeScheduleTemplateNotExist = 10001
131
+
132
+	ErrorCodeSystemError  = 6666
133
+	ErrorCodeProductError = 6667
134
+	ErrorCodeFieldExist   = 100001
135
+	ErrorCodeCreateConfig = 100002
136
+	ErrorCodeUpdateConfig = 100003
137
+
138
+	ErrorCodeDoubleCheckWrong     = 200003
139
+	ErrorCodeDoubleCheckUserWrong = 200004
140
+	ErrorCodeGoodNoStockInError   = 200005
141
+	ErrorCodeCancelStockFail      = 200006
142
+	ErrorCodeDeleteGoodTypeFail   = 200007
143
+	ErrorCodeDeleteGoodInfoFail   = 200008
144
+	ErrorCodeDeleteFail           = 200009
145
+
146
+	ErrorCodeKeyFail                 = 200010
147
+	ErrorCodeDeleteStockInRecordFail = 200011
148
+	ErrorCodeNameWrong               = 200012
149
+
150
+	ErrorCodeParamEmptyWrong       = 200013
151
+	ErrorCodeParamAdviceEmptyWrong = 200014
152
+
153
+	ErrorCodeParamTemplateNOEXISTWrong = 200015
154
+
155
+	ErrorCodeDeleteDealerWrong       = 200016
156
+	ErrorCodeDeleteManufacturerWrong = 200017
157
+	ErrorCodeGoodTypeNameExistError  = 200018
158
+	ErrorCodeGoodInfoNameExistError  = 200019
159
+
160
+	ErrorCodePrescriptionPermissionDeniedModify = 200020
161
+
162
+	ErrorCodeAdvicePermissionDeniedModify = 200021
163
+	ErrorCodePrescriptionException        = 200022
164
+
165
+	ErrorCodeNotDocking = 200023
166
+
167
+	ErrorCodeAdviceTypeWrong = 200024
168
+
169
+	ErrorCodeCreateAdvice = 200025
170
+
171
+	ErrorCodePatientDialysisOrder = 20026
172
+	ErrorSchedualcRepeatBed       = 20027
173
+
174
+	ErrorCodeChangeMode         = 20028
175
+	ErrorCodeChangeDeviceNumber = 20029
176
+
177
+	ErrorCodeHisIdExist = 20030
178
+
179
+	ErrorCodePreExist = 20031
180
+)
181
+
182
+var ErrCodeMsgs = map[int]string{
183
+	// 登录注册错误
184
+	ErrorCodeLoginTimeout:                   "登录超时",
185
+	ErrorCodeNotLogin:                       "未登录",
186
+	ErrorCodePermissionDenied:               "权限不足",
187
+	ErrorCodeMobileRegistered:               "手机号已被注册",
188
+	ErrorCodePasswordEmpty:                  "密码为空",
189
+	ErrorCodeVerificationCodeWrong:          "验证码错误",
190
+	ErrorCodeRegisterFail:                   "注册失败",
191
+	ErrorCodeInvalidToken:                   "令牌无效",
192
+	ErrorCodeAccountOrPasswordWrong:         "账号或密码错误",
193
+	ErrorCodeMissingOrg:                     "未创建机构",
194
+	ErrorCodeMissingOrgApp:                  "未创建任何应用",
195
+	ErrorCodeAccountOrVerCodeWrong:          "账号或验证码错误",
196
+	ErrorCodeMobileNotExit:                  "手机号不存在",
197
+	ErrorCodeUserNotExist:                   "用户不存在",
198
+	ErrorCodeUserWasForbidden:               "该用户被禁用",
199
+	ErrorCodeNeverCreateTypeApp:             "未创建此种应用",
200
+	ErrorCodeContactSuperAdminCreateTypeApp: "请联系超级管理员开通此种应用",
201
+
202
+	// 数据验证错误
203
+	ErrorCodeMobileFormat:     "手机号格式错误",
204
+	ErrorCodeTelphoneFormat:   "电话格式错误",
205
+	ErrorCodeParamWrong:       "参数错误",
206
+	ErrorCodeParamFormatWrong: "参数格式错误",
207
+
208
+	// 数据库操作错误
209
+	ErrorCodeDBCreate:         "数据库创建出错",
210
+	ErrorCodeDBUpdate:         "数据库更新出错",
211
+	ErrorCodeDBDelete:         "数据库删除出错",
212
+	ErrorCodeDBSelectNoResult: "查询无结果",
213
+	ErrorCodeDataException:    "数据异常",
214
+
215
+	// 业务逻辑操作错误
216
+	ErrorCodeRoleNotExist:           "角色不存在",
217
+	ErrorCodeAdminUserNotExist:      "管理员不存在",
218
+	ErrorCodeMobileDidUsedInApp:     "该手机号已在该应用中被注册为管理员",
219
+	ErrorCodeMissingUserName:        "缺少用户名",
220
+	ErrorCodeOldPasswordWrong:       "原密码不正确",
221
+	ErrorCodeCannotRemoveRole:       "该角色下存在用户,不能删除该角色",
222
+	ErrorCodeRoleMobileIsSuperAdmin: "该手机号已注册为超级管理员",
223
+
224
+	ErrorCodeGetQiniuUpToken: "获取七牛uptoken失败",
225
+	ErrorCodeCreatePatient:   "创建患者失败",
226
+	ErrorCodeDialysisNoExist: "患者透析号重复!",
227
+	ErrorCodeIdCardNoExist:   "身份证号重复!",
228
+	ErrorCodePatientNoExist:  "患者信息不存在!",
229
+	ErrorCodeUpdatePatient:   "修改患者信息失败",
230
+
231
+	ErrorCodeDialysisSolutionExist:          "该处方已经存在",
232
+	ErrorCodeDialysisSolutionCreate:         "创建处方失败",
233
+	ErrorCodeDialysisSolutionUpdate:         "修改处方失败",
234
+	ErrorCodeDialysisSolutionNotExist:       "该处方不存在",
235
+	ErrorCodeParentDialysisSolutionNotExist: "上级处方不存在",
236
+	ErrorCodeAlReadyHadChildSolution:        "所选处方已经存在子方案",
237
+	ErrorCodeCanntCreateChildChildSolution:  "子方案不能添加子方案",
238
+	ErrorCodeDialysisSolutionUsed:           "处方已被使用,不能删除",
239
+	ErrorCodeCreateDryWeightFail:            "添加干体重失败",
240
+	ErrorCodeCreateDoctorAdviceFail:         "添加医嘱失败",
241
+	ErrorCodeUpdateDoctorAdviceFail:         "修改医嘱信息失败",
242
+	ErrorCodeDoctorAdviceNotExist:           "医嘱不存在",
243
+	ErrorCodeLongTimeAdviceNotCanntEdit:     "长期医嘱不能修改!",
244
+	ErrorCodeAdviceStoped:                   "所选医嘱已停止",
245
+	ErrorCodeParentAdviceNotExist:           "上级医嘱不存在",
246
+	ErrorCodeDeleteAdviceFail:               "删除医嘱失败",
247
+	ErrorCodeStopAdviceFail:                 "停止医嘱失败",
248
+	ErrorCodeDialysisSolutionDelete:         "删除方案失败",
249
+	ErrorCodeDeviceNumberNotTheZone:         "所选机号不在选择分区中",
250
+	ErrorCodeCreateScheduleFail:             "添加排班失败",
251
+	ErrorCodeCantSetScheduleAgainOneDay:     "同一天不可有两次排班",
252
+	ErrorCodeCantSetScheduleBeforeNow:       "不能给今天之前的日期排班",
253
+	ErrorCodeScheduleNotExist:               "排班不存在",
254
+	ErrorCodePointScheduleExist:             "所先位置排班已经存在",
255
+	ErrorCodeDeleteScheduleFail:             "取消排班失败",
256
+	ErrorCodeChangeScheduleFail:             "修改排班失败",
257
+	ErrorCodePatientPhoneUsed:               "手机号已经存在",
258
+	ErrorCodeAdviceExced:                    "医嘱已经执行",
259
+	ErrorCodeAdviceCheckBeforeExce:          "核对医嘱不能在执行医嘱之前",
260
+	ErrorCodeAdviceExceBeforeStart:          "执行医嘱不能在开始之前",
261
+	ErrorCodeAdviceChecked:                  "医嘱已经核对",
262
+	ErrorCodeExceAndCheckNotOneUser:         "核对与执行不能是同一人",
263
+	ErrorCodeCanotEditOtherAdvice:           "不能修改非本人添加的医嘱",
264
+	ErrorCodeEditLapsetoFail:                "转归失败",
265
+	ErrorCodeDelScheduleFailByDialysis:      "已经上机透析,不能取消排班",
266
+	ErrorCodeNotSelectLapsetoType:           "请选择转归状态",
267
+	ErrorCodeNotSelectLapsetoTime:           "请选择转归时间",
268
+
269
+	ErrorCodeInspectionDateExit:    "当天已经存在检验检查记录",
270
+	ErrorCodeInspectionAddFail:     "添加记录失败",
271
+	ErrorCodeInspectionDateNotExit: "当天不存在检验检查记录",
272
+	ErrorCodeInspectionEditFail:    "修改记录失败",
273
+	ErrorCodeInspectionDeleteFail:  "删除记录失败",
274
+
275
+	ErrorCodeDeviceZoneNotExist:                      "设备分区不存在",
276
+	ErrorCodeDeviceZoneNameRepeat:                    "该分区名已存在",
277
+	ErrorCodeDeviceGroupNotExist:                     "设备分组不存在",
278
+	ErrorCodeDeviceGroupNameRepeat:                   "该分组名已存在",
279
+	ErrorCodeDeviceNumberNotExist:                    "机号不存在",
280
+	ErrorCodeDeviceNumberRepeat:                      "该机号已存在",
281
+	ErrorCodeDeviceNotExist:                          "该设备不存在",
282
+	ErrorCodeDeviceZoneCannotDisable:                 "该分区存在床位号,不能删除",
283
+	ErrorCodeDeviceNumberCannotDisableCuzDevice:      "该床位存在设备,不能删除",
284
+	ErrorCodeDeviceNumberCannotDisableCuzSchedule:    "该床位尚有排班安排,不能删除",
285
+	ErrorCodeDeviceNumberCannotDisableCuzSchTemplate: "排班模板在该床位尚有排班安排,不能删除",
286
+
287
+	ErrorCodeNotSubscibe:       "没有订阅服务或服务已过期,请先购买服务!",
288
+	ErrorCodeServeNotExist:     "服务订单不存在!",
289
+	ErrorCodeInvoiceExist:      "已经申请了发票!",
290
+	ErrorCodeApplyInvoiceFail:  "申请发票失败!",
291
+	ErrorCodeHetongHad:         "合同已经存在!",
292
+	ErrorCodeCreateHetongFail:  "合同创建失败",
293
+	ErrorCodePatientReachLimit: "患者数已达到当前服务版本病人数,需要升级到更高的版本",
294
+
295
+	ErrorCodeMonitorCreate:                  "创建监测失败",
296
+	ErrorCodeMonitorNotExist:                "监测记录不存在",
297
+	ErrorCodeMonitorUpdate:                  "修改监测失败",
298
+	ErrorCodeDialysisPermissionDeniedModify: "您没有权限修改其他医护的数据!",
299
+
300
+	ErrorDialysisOrderNoStart:     "尚未上机,无法执行下机操作",
301
+	ErrorDialysisOrderNoEND:       "已处于下机状态",
302
+	ErrorDialysisOrderRepeatStart: "已上机",
303
+	ErrorDialysisOrderRepeatBed:   "该床位已有患者上机,请选择其他床位",
304
+	//ErrorCodeScheduleTemplateNotExist: "排班模板不存在",
305
+
306
+	ErrorCodeSystemError:              "系统异常",
307
+	ErrorCodeProductError:             "该服务商品已丢失",
308
+	ErrorCodeScheduleTemplateNotExist: "排班模板不存在",
309
+
310
+	ErrorCodeCreateStockInFail: "入库失败",
311
+	//ErrorCodeSystemError:  "系统异常",
312
+	//ErrorCodeProductError: "该服务商品已丢失",
313
+	ErrorCodeFieldExist:   "配置字段已存在",
314
+	ErrorCodeCreateConfig: "创建配置失败",
315
+	ErrorCodeUpdateConfig: "修改配置失败",
316
+
317
+	ErrorCommitFail:               "提交失败",
318
+	ErrorCodeDoubleCheckWrong:     "核对已完成, 无法再次提交",
319
+	ErrorCodeDoubleCheckUserWrong: "你已完成核对,不能重复核对",
320
+	ErrorCodeGoodNoStockInError:   "该商品尚未入库",
321
+
322
+	ErrorCodeCancelStockFail:    "出库退库失败",
323
+	ErrorCodeDeleteGoodTypeFail: "该类型存在商品信息,无法删除",
324
+	ErrorCodeDeleteGoodInfoFail: "该商品已经入库无法删除",
325
+
326
+	ErrorCodeDeleteFail: "删除失败",
327
+
328
+	ErrorCodeKeyFail:                 "关键字不能为空",
329
+	ErrorCodeDeleteStockInRecordFail: "该记录已经有出库或退货操作,无法删除",
330
+	ErrorCodeNameWrong:               "该模版名字已存在",
331
+	ErrorCodeParamEmptyWrong:         "模版名称不能为空",
332
+	ErrorCodeParamAdviceEmptyWrong:   "医嘱名称不能为空",
333
+
334
+	ErrorCodeDeleteDealerWrong:       "该经销商所属商品已入库无法删除",
335
+	ErrorCodeDeleteManufacturerWrong: "该厂商所属商品已入库无法删除",
336
+	ErrorCodeGoodTypeNameExistError:  "该商品类型名字已存在",
337
+	ErrorCodeGoodInfoNameExistError:  "该规格名称名字已存在",
338
+
339
+	ErrorCodePrescriptionPermissionDeniedModify: "您没有权限修改透析处方数据",
340
+	ErrorCodeAdvicePermissionDeniedModify:       "您没有权限添加医嘱",
341
+	ErrorCodePrescriptionException:              "上机失败,请先开处方",
342
+	ErrorCodeNotDocking:                         "该地区尚未对接",
343
+
344
+	ErrorCodeAdviceTypeWrong:      "请选择医嘱模版类型",
345
+	ErrorCodeCreateAdvice:         "你没有权限开医嘱",
346
+	ErrorCodePatientDialysisOrder: "该病人已经上机,无法临时排班",
347
+	ErrorSchedualcRepeatBed:       "该床位已经有人排班,无法临时排班",
348
+
349
+	ErrorCodeChangeMode:         "该患者今天已上机治疗,请在透析记录中进行调整透析模式",
350
+	ErrorCodeChangeDeviceNumber: "该患者今天已上机治疗,请在透析记录中进行调整机号",
351
+
352
+	ErrorCodeHisIdExist: "该his_id已被占用,请重新输入",
353
+
354
+	ErrorCodePreExist: "没有该权限",
355
+}
356
+
357
+type SGJError struct {
358
+	Code int
359
+}
360
+
361
+func (e *SGJError) Error() string {
362
+	value, ok := ErrCodeMsgs[e.Code]
363
+	if ok {
364
+		return value
365
+	} else {
366
+		return "未知错误"
367
+	}
368
+}
369
+
370
+func MakeSuccessResponseJSON(data map[string]interface{}) map[string]interface{} {
371
+	json := make(map[string]interface{})
372
+	if data != nil {
373
+		json["data"] = data
374
+	} else {
375
+		json["data"] = make(map[string]interface{})
376
+	}
377
+	json["state"] = 1
378
+	json["code"] = 0
379
+	return json
380
+}
381
+
382
+func MakeFailResponseJSON(errMsg string, errCode int) map[string]interface{} {
383
+	json := make(map[string]interface{})
384
+	json["msg"] = errMsg
385
+	json["code"] = errCode
386
+	json["state"] = 0
387
+	return json
388
+}
389
+
390
+func MakeFailResponseJSONWithSGJError(err *SGJError) map[string]interface{} {
391
+	if err == nil {
392
+		utils.WarningLog("MakeFailResponseJSONWithSGJError 参数err 不能为空")
393
+		return nil
394
+	}
395
+	return MakeFailResponseJSON(err.Error(), err.Code)
396
+}
397
+
398
+func MakeFailResponseJSONWithSGJErrorCode(code int) map[string]interface{} {
399
+	err := &SGJError{Code: code}
400
+	return MakeFailResponseJSON(err.Error(), err.Code)
401
+}

+ 17 - 0
main.go 查看文件

@@ -0,0 +1,17 @@
1
+package main
2
+
3
+import (
4
+	_ "IC/routers"
5
+	"IC/service"
6
+	"github.com/astaxie/beego"
7
+)
8
+
9
+func init() {
10
+	service.ConnectDB()
11
+}
12
+
13
+func main() {
14
+	service.BeginAutoSyncLis()
15
+	beego.Run()
16
+}
17
+

+ 367 - 0
models/lis_model.go 查看文件

@@ -0,0 +1,367 @@
1
+package models
2
+
3
+type DoctorAdvice struct {
4
+	ID                    int64           `gorm:"column:id" json:"id" form:"id"`
5
+	GroupNo               int64           `gorm:"column:groupno" json:"groupno" form:"groupno"`
6
+	UserOrgId             int64           `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
7
+	PatientId             int64           `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
8
+	AdviceType            int64           `gorm:"column:advice_type" json:"advice_type" form:"advice_type"`
9
+	AdviceDate            int64           `gorm:"column:advice_date" json:"advice_date" form:"advice_date"`
10
+	StartTime             int64           `gorm:"column:start_time" json:"start_time" form:"start_time"`
11
+	AdviceName            string          `gorm:"column:advice_name" json:"advice_name" form:"advice_name"`
12
+	AdviceDesc            string          `gorm:"column:advice_desc" json:"advice_desc" form:"advice_desc"`
13
+	ReminderDate          int64           `gorm:"column:reminder_date" json:"reminder_date" form:"reminder_date"`
14
+	SingleDose            float64         `gorm:"column:single_dose" json:"single_dose" form:"single_dose"`
15
+	SingleDoseUnit        string          `gorm:"column:single_dose_unit" json:"single_dose_unit" form:"single_dose_unit"`
16
+	DrugSpec              float64         `gorm:"column:drug_spec" json:"drug_spec" form:"drug_spec"`
17
+	DrugSpecUnit          string          `gorm:"column:drug_spec_unit" json:"drug_spec_unit" form:"drug_spec_unit"`
18
+	PrescribingNumber     float64         `gorm:"column:prescribing_number" json:"prescribing_number" form:"prescribing_number"`
19
+	PrescribingNumberUnit string          `gorm:"column:prescribing_number_unit" json:"prescribing_number_unit" form:"prescribing_number_unit"`
20
+	DeliveryWay           string          `gorm:"column:delivery_way" json:"delivery_way" form:"delivery_way"`
21
+	ExecutionFrequency    string          `gorm:"column:execution_frequency" json:"execution_frequency" form:"execution_frequency"`
22
+	AdviceDoctor          int64           `gorm:"column:advice_doctor" json:"advice_doctor" form:"advice_doctor"`
23
+	Status                int64           `gorm:"column:status" json:"status" form:"status"`
24
+	CreatedTime           int64           `gorm:"column:created_time" json:"created_time" form:"created_time"`
25
+	UpdatedTime           int64           `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
26
+	AdviceAffirm          string          `gorm:"column:advice_affirm" json:"advice_affirm" form:"advice_affirm"`
27
+	Remark                string          `gorm:"column:remark" json:"remark" form:"remark"`
28
+	StopTime              int64           `gorm:"column:stop_time" json:"stop_time" form:"stop_time"`
29
+	StopReason            string          `gorm:"column:stop_reason" json:"stop_reason" form:"stop_reason"`
30
+	StopDoctor            int64           `gorm:"column:stop_doctor" json:"stop_doctor" form:"stop_doctor"`
31
+	StopState             int64           `gorm:"column:stop_state" json:"stop_state" form:"stop_state"`
32
+	ParentId              int64           `gorm:"column:parent_id" json:"parent_id" form:"parent_id"`
33
+	ExecutionTime         int64           `gorm:"column:execution_time" json:"execution_time" form:"execution_time"`
34
+	ExecutionStaff        int64           `gorm:"column:execution_staff" json:"execution_staff" form:"execution_staff"`
35
+	ExecutionState        int64           `gorm:"column:execution_state" json:"execution_state" form:"execution_state"`
36
+	Checker               int64           `gorm:"column:checker" json:"checker" form:"checker"`
37
+	RecordDate            int64           `gorm:"column:record_date" json:"record_date"`
38
+	DialysisOrderId       int64           `gorm:"column:dialysis_order_id" json:"dialysis_order_id"`
39
+	CheckTime             int64           `gorm:"column:check_time" json:"check_time" form:"check_time"`
40
+	CheckState            int64           `gorm:"column:check_state" json:"check_state" form:"check_state"`
41
+	AdviceId              int64           `gorm:"-"`
42
+	RemindType            int64           `gorm:"column:remind_type" json:"remind_type"`
43
+	FrequencyType         int64           `gorm:"column:frequency_type" json:"frequency_type"`
44
+	DayCount              int64           `gorm:"column:day_count" json:"day_count"`
45
+	WeekDay               string          `gorm:"column:week_day" json:"week_day"`
46
+	ChildDoctorAdvice     []*DoctorAdvice `gorm:"ForeignKey:ParentId;AssociationForeignKey:ID" json:"child"`
47
+	TemplateId            string          `gorm:"column:template_id" json:"template_id"`
48
+	Modifier              int64           `gorm:"column:modifier" json:"modifier" form:"modifier"`
49
+	IsCheck               int64           `gorm:"-" json:"is_check" form:"is_check"`
50
+}
51
+
52
+func (DoctorAdvice) TableName() string {
53
+	return "xt_doctor_advice"
54
+}
55
+
56
+type FiledConfig struct {
57
+	ID          int64  `gorm:"column:id" json:"id"`
58
+	OrgId       int64  `gorm:"column:org_id" json:"org_id"`
59
+	Module      int64  `gorm:"column:module" json:"module"`
60
+	FiledName   string `gorm:"column:filed_name" json:"filed_name"`
61
+	FiledNameCn string `gorm:"column:filed_name_cn" json:"filed_name_cn"`
62
+	IsShow      int64  `gorm:"column:is_show" json:"is_show"`
63
+	CreateTime  int64  `gorm:"column:create_time" json:"create_time"`
64
+	UpdateTime  int64  `gorm:"column:update_time" json:"update_time"`
65
+	SysModule   int64  `gorm:"column:sys_module" json:"sys_module" form:"sys_module"`
66
+}
67
+
68
+func (FiledConfig) TableName() string {
69
+	return "xt_filed_config"
70
+}
71
+
72
+type MiddlePatients struct {
73
+	ID             	int64 `gorm:"column:id" json:"id" form:"id"`
74
+	UserOrgId		int64 `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
75
+	UserId       	int64 `gorm:"column:user_id" json:"user_id" form:"user_id"`
76
+	HisUserId  		string `gorm:"column:his_user_id" json:"his_user_id" form:"his_user_id"`
77
+	XtPatientId  	int64 `gorm:"column:xt_patient_id" json:"xt_patient_id" form:"xt_patient_id"`
78
+	SelectType  	int64 `gorm:"column:select_type" json:"select_type" form:"select_type"`
79
+	Status 			int	  `gorm:"column:status" json:"status" form:"status"`
80
+
81
+}
82
+
83
+func (MiddlePatients) TableName() string {
84
+	return "xt_middle_patients"
85
+}
86
+
87
+type Patients struct {
88
+	ID				int64	`gorm:"column:id" json:"id" form:"id"`
89
+	UserOrgId		int64	`gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
90
+	UserId			int64	`gorm:"column:user_id" json:"user_id" form:"user_id"`
91
+	AdmissionNumber	string	`gorm:"column:admission_number" json:"admission_number" form:"admission_number"`
92
+	DialysisNo		string	`gorm:"column:dialysis_no" json:"dialysis_no" form:"dialysis_no"`
93
+	IdCardNo		string	`gorm:"column:id_card_no" json:"id_card_no" form:"id_card_no"`
94
+	Name			string	`gorm:"column:name" json:"name" form:"name"`
95
+	ContactName		string	`gorm:"column:contact_name" json:"contact_name" form:"contact_name"`
96
+}
97
+
98
+func (Patients) TableName() string {
99
+	return "xt_patients"
100
+}
101
+
102
+type DialysisSchedule struct {
103
+	ID           int64 `gorm:"column:id" json:"id" form:"id"`
104
+	UserOrgId    int64 `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
105
+	PartitionId  int64 `gorm:"column:partition_id" json:"partition_id" form:"partition_id"`
106
+	BedId        int64 `gorm:"column:bed_id" json:"bed_id" form:"bed_id"`
107
+	PatientId    int64 `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
108
+	ScheduleDate int64 `gorm:"column:schedule_date" json:"schedule_date" form:"schedule_date"`
109
+	ScheduleType int64 `gorm:"column:schedule_type" json:"schedule_type" form:"schedule_type"`
110
+	ScheduleWeek int64 `gorm:"column:schedule_week" json:"schedule_week" form:"schedule_week"`
111
+	ModeId       int64 `gorm:"column:mode_id" json:"mode_id" form:"mode_id"`
112
+	Status       int64 `gorm:"column:status" json:"status" form:"status"`
113
+	CreatedTime  int64 `gorm:"column:created_time" json:"created_time" form:"created_time"`
114
+	UpdatedTime  int64 `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
115
+	Patients Patients `gorm:"ForeignKey:PatientId" json:"patient"`
116
+}
117
+
118
+func (DialysisSchedule) TableName() string {
119
+	return "xt_schedule"
120
+}
121
+
122
+
123
+type MiddleSyncInfo struct {
124
+	ID             	int64 `gorm:"column:id" json:"id" form:"id"`
125
+	OrgId       	int64 `gorm:"column:org_id" json:"org_id" form:"org_id"`
126
+	HisUserId       string `gorm:"column:his_user_id" json:"his_user_id" form:"his_user_id"`
127
+	SyncTime       	int64 `gorm:"column:sync_time" json:"sync_time" form:"sync_time"`
128
+	SyncResultType  int	  `gorm:"column:sync_result_type" json:"sync_result_type" form:"sync_result_type"`
129
+	SyncRsultRemark string `gorm:"column:sync_result_remark" json:"sync_result_remark" form:"sync_result_remark"`
130
+	SyncTotalNum    int64 `gorm:"column:sync_total_num" json:"sync_total_num" form:"sync_total_num"`
131
+	SyncSuccessNum  int64 `gorm:"column:sync_success_num" json:"sync_success_num" form:"sync_success_num"`
132
+	SyncInfo      	string `gorm:"column:sync_info" json:"sync_info" form:"sync_info"`
133
+	CreateTime      int64 `gorm:"column:create_time" json:"create_time" form:"create_time"`
134
+	UpdateTime    	int64 `gorm:"column:update_time" json:"update_time" form:"update_time"`
135
+}
136
+
137
+func (MiddleSyncInfo) TableName() string {
138
+	return "xt_middle_sync_info"
139
+}
140
+
141
+type TBLISItem struct {
142
+	HisUserId             	string  `gorm:"column:his_user_id" json:"his_user_id" form:"his_user_id"`
143
+	ProjectId       		int64  `gorm:"column:project_id" json:"project_id" form:"project_id"`
144
+	ProjectName         	string `gorm:"column:project_name" json:"project_name" form:"project_name"`
145
+	PatientName         	string `gorm:"column:patient_name" json:"patient_name" form:"patient_name"`
146
+	InspectDate          	string  `gorm:"column:inspect_date" json:"inspect_date" form:"inspect_date"`
147
+	ItemId           		int64 `gorm:"column:item_id" json:"item_id" form:"item_id"`
148
+	ItemName      			string `gorm:"column:item_name" json:"item_name" form:"item_name"`
149
+	ItemType          		int    `gorm:"column:item_type" json:"item_type" form:"item_type"`
150
+	ItemValue    			string `gorm:"column:item_value" json:"item_value" form:"item_value"`
151
+	RangeMin    			string `gorm:"column:range_min" json:"range_min" form:"range_min"`
152
+	RangeMax    			string `gorm:"column:range_max" json:"range_max" form:"range_max"`
153
+	RangeValue   			string  `gorm:"column:range_value" json:"range_value" form:"range_value"`
154
+	RangeOptions         	string  `gorm:"column:range_options" json:"range_options" form:"range_options"`
155
+	Unit         			string `gorm:"column:unit" json:"unit" form:"unit"`
156
+	UTime 					string  `gorm:"column:u_time" json:"u_time" form:"u_time"`
157
+}
158
+
159
+func (TBLISItem) TableName() string {
160
+	return "TB_LIS_Item"
161
+}
162
+
163
+type Inspection struct {
164
+	ID int64 `gorm:"column:id" json:"id" form:"id"`
165
+	PatientId int64 `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
166
+	OrgId int64 `gorm:"column:org_id" json:"org_id" form:"org_id"`
167
+	ProjectId int64 `gorm:"column:project_id" json:"project_id" form:"project_id"`
168
+	ItemId int64 `gorm:"column:item_id" json:"item_id" form:"item_id"`
169
+	ItemName string `gorm:"column:item_name" json:"item_name" form:"item_name"`
170
+	ProjectName string `gorm:"column:project_name" json:"project_name" form:"project_name"`
171
+	InspectType int64 `gorm:"column:inspect_type" json:"inspect_type" form:"inspect_type"`
172
+	InspectValue string `gorm:"column:inspect_value" json:"inspect_value" form:"inspect_value"`
173
+	InspectTips string `gorm:"column:inspect_tips" json:"inspect_tips" form:"inspect_tips"`
174
+	InspectDate int64 `gorm:"column:inspect_date" json:"inspect_date" form:"inspect_date"`
175
+	Status int64 `gorm:"column:status" json:"status" form:"status"`
176
+	CreatedTime int64 `gorm:"column:created_time" json:"created_time" form:"created_time"`
177
+	UpdatedTime int64 `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
178
+}
179
+
180
+
181
+func (Inspection) TableName() string {
182
+	return "xt_inspection"
183
+}
184
+
185
+type InspectionReference struct {
186
+	ID int64 `gorm:"column:id" json:"id" form:"id"`
187
+	OrgId int64 `gorm:"column:org_id" json:"org_id" form:"org_id"`
188
+	ProjectName string `gorm:"column:project_name" json:"project_name" form:"project_name"`
189
+	Project string `gorm:"column:project" json:"project" form:"project"`
190
+	ProjectId int64 `gorm:"column:project_id" json:"project_id" form:"project_id"`
191
+	ItemName string `gorm:"column:item_name" json:"item_name" form:"item_name"`
192
+	ItemNameAddition string `gorm:"column:item_name_addition" json:"item_name_addition" form:"item_name_addition"`
193
+	Item string `gorm:"column:item" json:"item" form:"item"`
194
+	ItemId int64 `gorm:"column:item_id" json:"item_id" form:"item_id"`
195
+	RangeType int `gorm:"column:range_type" json:"range_type" form:"range_type"`
196
+	RangeMin string `gorm:"column:range_min" json:"range_min" form:"range_min"`
197
+	RangeMax string `gorm:"column:range_max" json:"range_max" form:"range_max"`
198
+	RangeValue string `gorm:"column:range_value" json:"range_value" form:"range_value"`
199
+	RangeOptions string `gorm:"column:range_options" json:"range_options" form:"range_options"`
200
+	Unit string `gorm:"column:unit" json:"unit" form:"unit"`
201
+	Status int64 `gorm:"column:status" json:"status" form:"status"`
202
+	CreatedTime int64 `gorm:"column:created_time" json:"created_time" form:"created_time"`
203
+	UpdatedTime int64 `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
204
+}
205
+
206
+func (InspectionReference) TableName() string {
207
+	return "xt_inspection_reference"
208
+}
209
+
210
+type MiddleReportHandle struct {
211
+	ID int64 `gorm:"column:id" json:"id" form:"id"`
212
+	OrgId int64 `gorm:"column:org_id" json:"org_id" form:"org_id"`
213
+	HisUserId string `gorm:"column:his_user_id" json:"his_user_id" form:"his_user_id"`
214
+	ApplyNo string `gorm:"column:apply_no" json:"apply_no" form:"apply_no"`
215
+	ReportId string `gorm:"column:report_id" json:"report_id" form:"report_id"`
216
+	Name string `gorm:"column:name" json:"name" form:"name"`
217
+	Sex string `gorm:"column:sex" json:"sex" form:"sex"`
218
+	Age string `gorm:"column:age" json:"age" form:"age"`
219
+	Dept string `gorm:"column:dept" json:"dept" form:"dept"`
220
+	PatientId string `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
221
+	RequestTime string `gorm:"column:request_time" json:"request_time" form:"request_time"`
222
+	ExecuteTime string `gorm:"column:execute_time" json:"execute_time" form:"execute_time"`
223
+	ReceiveTime string `gorm:"column:receive_time" json:"receive_time" form:"receive_time"`
224
+	Item string `gorm:"column:item" json:"item" form:"item"`
225
+	CheckTime string `gorm:"column:check_time" json:"check_time" form:"check_time"`
226
+	PatientType string `gorm:"column:patient_type" json:"patient_type" form:"patient_type"`
227
+	ReportInfo string `gorm:"column:report_info" json:"report_info" form:"report_info"`
228
+	ReportInfoItemNum int64 `gorm:"column:report_info_item_num" json:"report_info_item_num" form:"report_info_item_num"`
229
+	ReportInfoItemHandleNum int64 `gorm:"column:report_info_item_handle_num" json:"report_info_item_handle_num" form:"report_info_item_handle_num"`
230
+	HandleType int64 `gorm:"column:handle_type" json:"handle_type" form:"handle_type"`
231
+	CreatedTime int64 `gorm:"column:created_time" json:"created_time" form:"created_time"`
232
+	UpdatedTime int64 `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
233
+}
234
+
235
+
236
+func (MiddleReportHandle) TableName() string {
237
+	return "xt_middle_report_handle"
238
+}
239
+
240
+type MiddleInspection struct {
241
+	ID int64 `gorm:"column:id" json:"id" form:"id"`
242
+	PatientId int64 `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
243
+	OrgId int64 `gorm:"column:org_id" json:"org_id" form:"org_id"`
244
+	ProjectId int64 `gorm:"column:project_id" json:"project_id" form:"project_id"`
245
+	ItemId int64 `gorm:"column:item_id" json:"item_id" form:"item_id"`
246
+	ItemName string `gorm:"column:item_name" json:"item_name" form:"item_name"`
247
+	ProjectName string `gorm:"column:project_name" json:"project_name" form:"project_name"`
248
+	InspectType int `gorm:"column:inspect_type" json:"inspect_type" form:"inspect_type"`
249
+	InspectValue string `gorm:"column:inspect_value" json:"inspect_value" form:"inspect_value"`
250
+	InspectTips string `gorm:"column:inspect_tips" json:"inspect_tips" form:"inspect_tips"`
251
+	RecordDate int64 `gorm:"column:record_date" json:"record_date" form:"record_date"`
252
+	InspectDate string `gorm:"column:inspect_date" json:"inspect_date" form:"inspect_date"`
253
+	Status int64 `gorm:"column:status" json:"status" form:"status"`
254
+	CreatedTime int64 `gorm:"column:created_time" json:"created_time" form:"created_time"`
255
+	UpdatedTime int64 `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
256
+	UTime string `gorm:"column:u_time" json:"u_time" form:"u_time"`
257
+	IsSync int `gorm:"column:is_sync" json:"is_sync" form:"is_sync"`
258
+	// SyncItemId int64 `gorm:"column:sync_item_id" json:"sync_item_id" form:"sync_item_id"`
259
+	HisUserId string `gorm:"column:his_user_id" json:"his_user_id" form:"his_user_id"`
260
+	SyncId			int64 `gorm:"column:sync_id" json:"sync_id" form:"sync_id"`
261
+}
262
+
263
+
264
+func (MiddleInspection) TableName() string {
265
+	return "xt_middle_inspection"
266
+}
267
+
268
+type MiddleInspectionReference struct {
269
+	ID 					int64 `gorm:"column:id" json:"id" form:"id"`
270
+	OrgId 				int64 `gorm:"column:org_id" json:"org_id" form:"org_id"`
271
+	ProjectName 		string `gorm:"column:project_name" json:"project_name" form:"project_name"`
272
+	Project 			string `gorm:"column:project" json:"project" form:"project"`
273
+	ProjectId 			int64 `gorm:"column:project_id" json:"project_id" form:"project_id"`
274
+	ItemName 			string `gorm:"column:item_name" json:"item_name" form:"item_name"`
275
+	ItemId 				int64 `gorm:"column:item_id" json:"item_id" form:"item_id"`
276
+	ItemNameAddition 	string `gorm:"column:item_name_addition" json:"item_name_addition" form:"item_name_addition"`
277
+	Item 				string `gorm:"column:item" json:"item" form:"item"`
278
+	RangeType 			int `gorm:"column:range_type" json:"range_type" form:"range_type"`
279
+	RangeMin 			string `gorm:"column:range_min" json:"range_min" form:"range_min"`
280
+	RangeMax 			string `gorm:"column:range_max" json:"range_max" form:"range_max"`
281
+	RangeValue 			string `gorm:"column:range_value" json:"range_value" form:"range_value"`
282
+	RangeOptions 		string `gorm:"column:range_options" json:"range_options" form:"range_options"`
283
+	Unit 				string `gorm:"column:unit" json:"unit" form:"unit"`
284
+	Status 				int64 `gorm:"column:status" json:"status" form:"status"`
285
+	CreatedTime 		int64 `gorm:"column:created_time" json:"created_time" form:"created_time"`
286
+	UpdatedTime 		int64 `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
287
+	InspectDate 		string `gorm:"column:inspect_date" json:"inspect_date" form:"inspect_date"`
288
+	IsSync 				int `gorm:"column:is_sync" json:"is_sync" form:"is_sync"`
289
+	UTime 				string `gorm:"column:u_time" json:"u_time" form:"u_time"`
290
+	SyncId				int64 `gorm:"column:sync_id" json:"sync_id" form:"sync_id"`
291
+}
292
+
293
+func (MiddleInspectionReference) TableName() string {
294
+	return "xt_middle_inspection_reference"
295
+}
296
+
297
+type XtDoctorAdvice struct {
298
+	ID                    int64   `gorm:"column:id" json:"id" form:"id"`
299
+	UserOrgId             int64   `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
300
+	PatientId             int64   `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
301
+	AdviceType            int64   `gorm:"column:advice_type" json:"advice_type" form:"advice_type"`
302
+	AdviceDate            int64   `gorm:"column:advice_date" json:"advice_date" form:"advice_date"`
303
+	StartTime             int64   `gorm:"column:start_time" json:"start_time" form:"start_time"`
304
+	AdviceName            string  `gorm:"column:advice_name" json:"advice_name" form:"advice_name"`
305
+	AdviceDesc            string  `gorm:"column:advice_desc" json:"advice_desc" form:"advice_desc"`
306
+	ReminderDate          int64   `gorm:"column:reminder_date" json:"reminder_date" form:"reminder_date"`
307
+	SingleDose            float64 `gorm:"column:single_dose" json:"single_dose" form:"single_dose"`
308
+	SingleDoseUnit        string  `gorm:"column:single_dose_unit" json:"single_dose_unit" form:"single_dose_unit"`
309
+	PrescribingNumber     float64 `gorm:"column:prescribing_number" json:"prescribing_number" form:"prescribing_number"`
310
+	PrescribingNumberUnit string  `gorm:"column:prescribing_number_unit" json:"prescribing_number_unit" form:"prescribing_number_unit"`
311
+	DeliveryWay           string  `gorm:"column:delivery_way" json:"delivery_way" form:"delivery_way"`
312
+	ExecutionFrequency    string  `gorm:"column:execution_frequency" json:"execution_frequency" form:"execution_frequency"`
313
+	AdviceDoctor          int64   `gorm:"column:advice_doctor" json:"advice_doctor" form:"advice_doctor"`
314
+	Status                int64   `gorm:"column:status" json:"status" form:"status"`
315
+	CreatedTime           int64   `gorm:"column:created_time" json:"created_time" form:"created_time"`
316
+	UpdatedTime           int64   `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
317
+	AdviceAffirm          string  `gorm:"column:advice_affirm" json:"advice_affirm" form:"advice_affirm"`
318
+	Remark                string  `gorm:"column:remark" json:"remark" form:"remark"`
319
+	StopTime              int64   `gorm:"column:stop_time" json:"stop_time" form:"stop_time"`
320
+	StopReason            string  `gorm:"column:stop_reason" json:"stop_reason" form:"stop_reason"`
321
+	StopDoctor            int64   `gorm:"column:stop_doctor" json:"stop_doctor" form:"stop_doctor"`
322
+	StopState             int64   `gorm:"column:stop_state" json:"stop_state" form:"stop_state"`
323
+	ParentId              int64   `gorm:"column:parent_id" json:"parent_id" form:"parent_id"`
324
+	ExecutionTime         int64   `gorm:"column:execution_time" json:"execution_time" form:"execution_time"`
325
+	ExecutionStaff        int64   `gorm:"column:execution_staff" json:"execution_staff" form:"execution_staff"`
326
+	ExecutionState        int64   `gorm:"column:execution_state" json:"execution_state" form:"execution_state"`
327
+	Checker               int64   `gorm:"column:checker" json:"checker" form:"checker"`
328
+	RecordDate            int64   `gorm:"column:record_date" json:"record_date" form:"record_date"`
329
+	DialysisOrderId       int64   `gorm:"column:dialysis_order_id" json:"dialysis_order_id" form:"dialysis_order_id"`
330
+	CheckTime             int64   `gorm:"column:check_time" json:"check_time" form:"check_time"`
331
+	CheckState            int64   `gorm:"column:check_state" json:"check_state" form:"check_state"`
332
+	DrugSpec              float64 `gorm:"column:drug_spec" json:"drug_spec" form:"drug_spec"`
333
+	DrugSpecUnit          string  `gorm:"column:drug_spec_unit" json:"drug_spec_unit" form:"drug_spec_unit"`
334
+	Groupno               int64   `gorm:"column:groupno" json:"groupno" form:"groupno"`
335
+	RemindType            int64   `gorm:"column:remind_type" json:"remind_type" form:"remind_type"`
336
+	FrequencyType         int64   `gorm:"column:frequency_type" json:"frequency_type" form:"frequency_type"`
337
+	DayCount              int64   `gorm:"column:day_count" json:"day_count" form:"day_count"`
338
+	WeekDay               string  `gorm:"column:week_day" json:"week_day" form:"week_day"`
339
+	TemplateId            string  `gorm:"column:template_id" json:"template_id" form:"template_id"`
340
+	Modifier              int64   `gorm:"column:modifier" json:"modifier" form:"modifier"`
341
+	SyncAdviceId          int64   `gorm:"column:sync_advice_id" json:"sync_advice_id" form:"sync_advice_id"`
342
+	IsSync          	  int64   `gorm:"column:is_sync" json:"is_sync" form:"is_sync"`
343
+}
344
+
345
+func (XtDoctorAdvice) TableName() string {
346
+	return "xt_doctor_advice"
347
+}
348
+
349
+type UserAdminRole struct {
350
+	ID              int64           `gorm:"column:id" json:"id"`
351
+	AdminUserId     int64           `gorm:"column:admin_user_id" json:"admin_user_id"`
352
+	OrgId           int64           `gorm:"column:org_id" json:"org_id"`
353
+	AppId           int64           `gorm:"column:app_id" json:"app_id"`
354
+	RoleId          int64           `gorm:"column:role_id" json:"role_id"`
355
+	UserName        string          `gorm:"column:user_name" json:"user_name"`
356
+	Avatar          string          `gorm:"column:avatar" json:"avatar"`
357
+	UserType        int64           `gorm:"column:user_type" json:"user_type"`
358
+	UserTitle       int64           `gorm:"column:user_title" json:"user_title"`
359
+	Intro           string          `gorm:"column:intro" json:"intro"`
360
+	Status          int64           `gorm:"column:status" json:"status"`
361
+	Ctime           int64           `gorm:"column:ctime" json:"ctime"`
362
+	Mtime           int64           `gorm:"column:mtime" json:"mtime"`
363
+}
364
+
365
+func (UserAdminRole) TableName() string {
366
+	return "sgj_user_admin_role"
367
+}

+ 20 - 0
routers/router.go 查看文件

@@ -0,0 +1,20 @@
1
+package routers
2
+
3
+import (
4
+	"IC/controllers"
5
+	"github.com/astaxie/beego"
6
+)
7
+
8
+func init() {
9
+	beego.Router("/", &controllers.MainController{})
10
+	beego.Router("/api/lis/getlist", &controllers.LisController{}, "get:GetList")
11
+	beego.Router("/api/lis/synctobase", &controllers.LisController{}, "get:SyncToBase")
12
+	beego.Router("/api/lis/synfiled", &controllers.LisController{}, "get:FiledConfigSys")
13
+	beego.Router("/api/lis/syncadvice", &controllers.LisController{}, "get:SyncAdvice")
14
+	beego.Router("/api/lis/lgeysync", &controllers.LisController{}, "get:SyncLgth")
15
+	beego.Router("/api/lis/ystxsync", &controllers.LisController{}, "get:SyncYstx")
16
+	beego.Router("/api/lis/gzjhyzsync", &controllers.LisController{}, "get:SyncGzjhyz")
17
+	beego.Router("/api/lis/gzjhlissync", &controllers.LisController{}, "get:SyncGzjhLis")
18
+	beego.Router("/api/lis/hbdyyzsync", &controllers.LisController{}, "get:SyncHbJldyyz")
19
+	beego.Router("/api/lis/hbdylissync", &controllers.LisController{}, "get:SyncHbJldyLis")
20
+}

+ 190 - 0
service/cron.go 查看文件

@@ -0,0 +1,190 @@
1
+package service
2
+
3
+import (
4
+	_"fmt"
5
+	_"strings"
6
+	"time"
7
+	"IC/models"
8
+	"IC/utils"
9
+	"encoding/json"
10
+	_"github.com/jinzhu/gorm"
11
+	"github.com/robfig/cron"
12
+)
13
+
14
+// cron表达式 https://www.cnblogs.com/zuxingyu/p/6023919.html
15
+var createLisSyncCronJob *cron.Cron
16
+
17
+func init() {
18
+	utils.InfoLog("开启自动检验检查同步定时任务")
19
+	createLisSyncCronJob = cron.New()
20
+	spec := "0 0 1 * * ?" // 每天凌晨1点同步
21
+	createLisSyncCronJob.AddFunc(spec, func() {
22
+		AutoSyncLis()
23
+	})
24
+
25
+	speclg := "0 0 2 * * ?" // 每天凌晨2点同步 龙岗二院
26
+	createLisSyncCronJob.AddFunc(speclg, func() {
27
+		SyncLisLgty()
28
+	})
29
+
30
+	specys := "0 0 3 * * ?" // 每天凌晨3点同步 沅胜血透
31
+	createLisSyncCronJob.AddFunc(specys, func() {
32
+		SyncHbdyLis()
33
+	})
34
+
35
+	// specgzjh := "0 */1 7-20 * *  " // 每2分钟同步 广州暨华HIS医嘱
36
+	// createLisSyncCronJob.AddFunc(specgzjh, func() {
37
+	// 	SyncGzjhyz()
38
+	// })
39
+
40
+	specgzjhlis := "0 30 3 * * ?" // 每天凌晨3点30同步 广州暨华
41
+	createLisSyncCronJob.AddFunc(specgzjhlis, func() {
42
+		SyncGzjhLis()
43
+	})
44
+}
45
+
46
+func BeginAutoSyncLis() {
47
+	createLisSyncCronJob.Start()
48
+}
49
+
50
+func AutoSyncLis() {
51
+	utils.TraceLog("检验检查任务开始执行")
52
+	org_id := int64(9538)
53
+
54
+	// 第一步:根据机构id获取对应机构所有病人的his_user_id
55
+	patients,patientError := GetHisUserIdByOrgID(org_id)
56
+	if patientError != nil {
57
+		utils.ErrorLog("获取用户His_user_id信息失败:%v", patientError)
58
+		return
59
+	}
60
+
61
+	// patientStr:= make([]interface{},0)
62
+	if len(patients) > 0 {
63
+	// 第二步:根据病人的his_user_id来查询上次同步时间	
64
+		for _ , patient := range patients {
65
+			if len(patient.HisUserId) <= 0 {
66
+				continue
67
+			}
68
+			syncLastInfo,_ := GetSyncTimeByOrgID(org_id,patient.HisUserId)
69
+			var sync_time int64
70
+			if syncLastInfo.ID > 0 {
71
+				sync_time = syncLastInfo.SyncTime
72
+			} else {
73
+				inspectionLastInfo,_ := GetInspectionLastInfoByOrgID(org_id,patient.HisUserId)
74
+				if inspectionLastInfo.ID > 0 {
75
+					sync_time = inspectionLastInfo.CreatedTime
76
+				} else {
77
+					sync_time = 0
78
+				}
79
+			}
80
+
81
+			syncTimes := time.Unix(sync_time,0).Format("2006-01-02 15:04")
82
+			utils.InfoLog("syncTimes:%v",syncTimes)
83
+
84
+			// 第三步:跟进上次同步时间和指定的his_user_id,获取上次同步到现在指定人的检验检查记录
85
+			resultList, _ := GetListByHisUserID(patient.HisUserId,syncTimes,patient.SelectType)
86
+			var syncInfo models.MiddleSyncInfo
87
+	
88
+			if len(resultList) > 0 {
89
+				// 如果有数据,则把同步过来的详情插入一条数据到同步详情表中
90
+				syncInfo.OrgId = org_id
91
+				syncInfo.HisUserId = patient.HisUserId
92
+				syncInfo.SyncTime = time.Now().Unix()
93
+				syncInfo.SyncResultType = 1
94
+				syncInfo.SyncRsultRemark = "同步成功"
95
+				syncInfo.SyncTotalNum = int64(len(resultList))
96
+				syncInfo.SyncSuccessNum = 0
97
+				SyncInfos,_ := json.Marshal(resultList)
98
+				syncInfo.SyncInfo = string(SyncInfos)
99
+				syncInfo.CreateTime = time.Now().Unix()
100
+				syncInfo.UpdateTime = time.Now().Unix()
101
+
102
+				err := CreateSyncInfo(&syncInfo)
103
+				if err != nil {
104
+					utils.ErrorLog("创建同步信息失败:%v", err)
105
+					return
106
+				}
107
+			} else {
108
+				// 如果没有数据,则插入一条数据到同步详情表中
109
+				syncInfo.OrgId = org_id
110
+				syncInfo.HisUserId = patient.HisUserId
111
+				syncInfo.SyncTime = time.Now().Unix()
112
+				syncInfo.SyncResultType = 1
113
+				syncInfo.SyncRsultRemark = "该患者这个时间段没有任何检验检查数据"
114
+				syncInfo.CreateTime = time.Now().Unix()
115
+				syncInfo.UpdateTime = time.Now().Unix()
116
+
117
+				err := CreateSyncInfo(&syncInfo)
118
+				if err != nil {
119
+					utils.ErrorLog("创建同步信息失败:%v", err)
120
+					return
121
+				}
122
+				// utils.InfoLog("同步信息详情:%v",syncInfo)
123
+				continue 
124
+			}
125
+
126
+			// 第四部:将同步过来的数据插入到中间库对应的表
127
+			syncSuccessNum := 0
128
+			for _, result := range resultList {
129
+				if (result.HisUserId == patient.HisUserId) || (result.PatientName ==  patient.HisUserId) {
130
+					patientId := patient.XtPatientId
131
+					if patientId > 0 {
132
+						inspection_reference,inspection,_ := Sync(result,org_id,patientId)
133
+						if (inspection_reference.ID > 0 || inspection.ID > 0 ) {
134
+							syncSuccessNum++
135
+						}
136
+					}
137
+				}
138
+			}
139
+			syncInfo.SyncSuccessNum = int64(syncSuccessNum)
140
+			UpdateSyncInfo(&syncInfo)
141
+
142
+			// patientStr = append(patientStr,patient.HisUserId)
143
+			// utils.InfoLog("patientStr:%v",patientStr)	
144
+		}
145
+	} else {
146
+		var syncInfo models.MiddleSyncInfo
147
+		// 如果没有数据,则插入一条数据到同步详情表中
148
+		syncInfo.OrgId = org_id
149
+		syncInfo.SyncTime = time.Now().Unix()
150
+		syncInfo.SyncResultType = 0
151
+		syncInfo.SyncRsultRemark = "该机构没有对应的his_user_id"
152
+		syncInfo.CreateTime = time.Now().Unix()
153
+		syncInfo.UpdateTime = time.Now().Unix()
154
+
155
+		err := CreateSyncInfo(&syncInfo)
156
+		if err != nil {
157
+			utils.ErrorLog("创建同步信息失败:%v", err)
158
+			return
159
+		}
160
+		utils.InfoLog("同步信息详情:%v",syncInfo)
161
+		return 
162
+	}
163
+
164
+	SyncToBase()
165
+	utils.SuccessLog("检验检查任务完成")
166
+}
167
+
168
+
169
+func  SyncToBase() {
170
+	utils.TraceLog("检验检查同步任务开始执行")
171
+	org_id := int64(9538)
172
+
173
+	// 第一步:跟进org_id 去中间库查出需要同步的数据
174
+	inspection_references,_ := GetSyncInspectionReferenceByOrgId(org_id)
175
+	inspections,_ := GetSyncInspectionByOrgId(org_id)
176
+
177
+	// 第二步:将数据同步到业务库
178
+	if len(inspection_references) > 0 {
179
+		for _,inspection_reference := range inspection_references {
180
+			SyncInspectionReference(&inspection_reference)
181
+		}
182
+	}
183
+
184
+	if len(inspections) > 0 {
185
+		for _,inspection := range inspections {
186
+			SyncInspection(&inspection)
187
+		}
188
+	}
189
+	utils.SuccessLog("检验检查同步任务完成")
190
+}

+ 176 - 0
service/db.go 查看文件

@@ -0,0 +1,176 @@
1
+// Pipe - A small and beautiful blogging platform written in golang.
2
+// Copyright (C) 2017-2018, b3log.org
3
+//
4
+// This program is free software: you can redistribute it and/or modify
5
+// it under the terms of the GNU General Public License as published by
6
+// the Free Software Foundation, either version 3 of the License, or
7
+// (at your option) any later version.
8
+//
9
+// This program is distributed in the hope that it will be useful,
10
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
+// GNU General Public License for more details.
13
+//
14
+// You should have received a copy of the GNU General Public License
15
+// along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
+
17
+package service
18
+
19
+import (
20
+	"fmt"
21
+
22
+	"github.com/astaxie/beego"
23
+	"github.com/jinzhu/gorm"
24
+	_ "github.com/jinzhu/gorm/dialects/mysql" // mysql
25
+	_ "github.com/jinzhu/gorm/dialects/mssql" // mssql
26
+)
27
+
28
+var readDb *gorm.DB
29
+var writeDb *gorm.DB
30
+var readRemoteDb *gorm.DB
31
+var writeUserDb *gorm.DB
32
+
33
+var readMiddleDb *gorm.DB
34
+var writeMiddleDb *gorm.DB
35
+var backupDb *gorm.DB
36
+var err error
37
+
38
+func ConnectDB() {
39
+	readHost := beego.AppConfig.String("readmysqlhost")
40
+	readPort := beego.AppConfig.String("readmysqlport")
41
+	readUser := beego.AppConfig.String("readmysqluser")
42
+	readPass := beego.AppConfig.String("readmysqlpass")
43
+	readName := beego.AppConfig.String("readmysqlname")
44
+
45
+	writeHost := beego.AppConfig.String("writemysqlhost")
46
+	writePort := beego.AppConfig.String("writemysqlport")
47
+	writeUser := beego.AppConfig.String("writemysqluser")
48
+	writePass := beego.AppConfig.String("writemysqlpass")
49
+	writeName := beego.AppConfig.String("writemysqlname")
50
+
51
+	// readRemoteHost := beego.AppConfig.String("readremotehost")
52
+	// readRemotePort := beego.AppConfig.String("readremoteport")
53
+	// readRemoteUser := beego.AppConfig.String("readremoteuser")
54
+	// readRemotePass := beego.AppConfig.String("readremotepass")
55
+	// readRemoteName := beego.AppConfig.String("readremotename")
56
+
57
+	writeUserHost := beego.AppConfig.String("writeuserhost")
58
+	writeUserPort := beego.AppConfig.String("writeuserport")
59
+	writeUserUser := beego.AppConfig.String("writeuseruser")
60
+	writeUserPass := beego.AppConfig.String("writeuserpass")
61
+	writeUserName := beego.AppConfig.String("writeusername")
62
+
63
+	readMiddleHost := beego.AppConfig.String("readmiddlehost")
64
+	readMiddlePort := beego.AppConfig.String("readmiddleport")
65
+	readMiddleUser := beego.AppConfig.String("readmiddleuser")
66
+	readMiddlePass := beego.AppConfig.String("readmiddlepass")
67
+	readMiddleName := beego.AppConfig.String("readmiddlename")
68
+
69
+	writeMiddleHost := beego.AppConfig.String("writemiddlehost")
70
+	writeMiddlePort := beego.AppConfig.String("writemiddleport")
71
+	writeMiddleUser := beego.AppConfig.String("writemiddleuser")
72
+	writeMiddlePass := beego.AppConfig.String("writemiddlepass")
73
+	writeMiddleName := beego.AppConfig.String("writemiddlename")
74
+
75
+	// backupHost := beego.AppConfig.String("backuphost")
76
+	// backupPort := beego.AppConfig.String("backupport")
77
+	// backupUser := beego.AppConfig.String("backupuser")
78
+	// backupPass := beego.AppConfig.String("backuppass")
79
+	// backupName := beego.AppConfig.String("backupname")
80
+
81
+	rdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readUser, readPass, readHost, readPort, readName)
82
+	wdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writeUser, writePass, writeHost, writePort, writeName)
83
+
84
+	// rudsn := fmt.Sprintf("server=%s;port=%s;database=%s;user id=%s;password=%s", readRemoteHost, readRemotePort, readRemoteName, readRemoteUser, readRemotePass)
85
+	wudsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writeUserUser, writeUserPass, writeUserHost, writeUserPort, writeUserName)
86
+
87
+	rmdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readMiddleUser, readMiddlePass, readMiddleHost, readMiddlePort, readMiddleName)
88
+	wmdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writeMiddleUser, writeMiddlePass, writeMiddleHost, writeMiddlePort, writeMiddleName)
89
+
90
+	// bdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", backupUser, backupPass, backupHost, backupPort, backupName)
91
+
92
+	readDb, err = gorm.Open("mysql", rdsn)
93
+	if err != nil {
94
+		//beego.Error(err)
95
+	}
96
+	readDb.DB().SetMaxIdleConns(10)
97
+	readDb.DB().SetMaxOpenConns(100)
98
+	readDb.LogMode(true)
99
+
100
+	// backupDb, err = gorm.Open("mysql", bdsn)
101
+	// if err != nil {
102
+	// 	//beego.Error(err)
103
+	// }
104
+	// backupDb.DB().SetMaxIdleConns(10)
105
+	// backupDb.DB().SetMaxOpenConns(100)
106
+	// backupDb.LogMode(true)
107
+
108
+	writeDb, err = gorm.Open("mysql", wdsn)
109
+	if err != nil {
110
+		//beego.Error(err)
111
+	}
112
+	writeDb.DB().SetMaxIdleConns(10)
113
+	writeDb.DB().SetMaxOpenConns(100)
114
+	writeDb.LogMode(true)
115
+
116
+	// fmt.Println(rudsn)
117
+
118
+	// readRemoteDb, err = gorm.Open("mssql", rudsn)
119
+	// if err != nil {
120
+	// 	panic(err)
121
+	// }
122
+	// readRemoteDb.DB().SetMaxIdleConns(10)
123
+	// readRemoteDb.DB().SetMaxOpenConns(100)
124
+	// readRemoteDb.LogMode(true)
125
+
126
+	writeUserDb, err = gorm.Open("mysql", wudsn)
127
+	if err != nil {
128
+		//beego.Error(err)
129
+	}
130
+	writeUserDb.DB().SetMaxIdleConns(10)
131
+	writeUserDb.DB().SetMaxOpenConns(100)
132
+	writeUserDb.LogMode(true)
133
+
134
+	readMiddleDb, err = gorm.Open("mysql", rmdsn)
135
+	if err != nil {
136
+		//beego.Error(err)
137
+	}
138
+	readMiddleDb.DB().SetMaxIdleConns(10)
139
+	readMiddleDb.DB().SetMaxOpenConns(100)
140
+	readMiddleDb.LogMode(true)
141
+
142
+	writeMiddleDb, err = gorm.Open("mysql", wmdsn)
143
+	if err != nil {
144
+		//beego.Error(err)
145
+	}
146
+	writeMiddleDb.DB().SetMaxIdleConns(10)
147
+	writeMiddleDb.DB().SetMaxOpenConns(100)
148
+	writeMiddleDb.LogMode(true)
149
+
150
+}
151
+
152
+//func DisconnectDB() {
153
+//	if err := readDb.Close(); nil != err {
154
+//		beego.Error("Disconnect from database failed: " + err.Error())
155
+//	}
156
+//}
157
+
158
+func XTReadDB() *gorm.DB {
159
+	return readDb
160
+}
161
+func XTWriteDB() *gorm.DB {
162
+	return writeDb
163
+}
164
+// func RemoteReadDB() *gorm.DB {
165
+// 	return readRemoteDb
166
+// }
167
+func UserWriteDB() *gorm.DB {
168
+	return writeUserDb
169
+}
170
+
171
+func MiddleReadDB() *gorm.DB {
172
+	return readMiddleDb
173
+}
174
+func MiddleWriteDB() *gorm.DB {
175
+	return writeMiddleDb
176
+}

+ 439 - 0
service/lgty_service.go 查看文件

@@ -0,0 +1,439 @@
1
+package service
2
+
3
+import (
4
+	"IC/models"
5
+	"IC/utils"
6
+	_"strconv"
7
+	"strings"
8
+	"encoding/json"
9
+	"time"
10
+	"net/url"
11
+	_"IC/utils"
12
+	_"fmt"
13
+	_"encoding/json"
14
+	_"github.com/jinzhu/gorm"
15
+	"github.com/astaxie/beego/httplib"
16
+)
17
+
18
+
19
+// 龙岗二院Lis同步
20
+func SyncLisLgty() (err error) {
21
+	// 第一步:获取龙岗二院所有病人
22
+	org_id := int64(9598)
23
+	patientlist,patientError := GetUserInfoByOrgID(org_id)
24
+	if patientError != nil {
25
+		utils.ErrorLog("获取龙岗二院患者信息失败:%v", patientError)
26
+		return
27
+	}
28
+
29
+	if len(patientlist) > 0 {
30
+		// 第二步:根据病人的住院号来查询上次同步时间	
31
+		for _ , patient := range patientlist {
32
+			if len(patient.AdmissionNumber) <= 0 {
33
+				continue
34
+			}
35
+			syncLastInfo,_ := GetSyncTimeByOrgID(org_id,patient.AdmissionNumber)
36
+			var sync_time int64
37
+			if syncLastInfo.ID > 0 {
38
+				sync_time = syncLastInfo.SyncTime
39
+			} else {
40
+				inspectionLastInfo,_ := GetInspectionLastInfoByOrgID(org_id,patient.AdmissionNumber)
41
+				if inspectionLastInfo.ID > 0 {
42
+					sync_time = inspectionLastInfo.CreatedTime
43
+				} else {
44
+					sync_time = 0
45
+				}
46
+			}
47
+
48
+			syncTimes := time.Unix(sync_time,0).Format("2006-01-02 15:04")
49
+			utils.InfoLog("syncTimes:%v",syncTimes)
50
+			nowTimes := time.Now().Format("2006-01-02 15:04")
51
+			// 第三步:跟进上次同步时间和指定的门诊号,获取上次同步到现在指定人的检验检查记录
52
+			lisHead,HeadString := GetHead(patient.AdmissionNumber,syncTimes,nowTimes)
53
+			var resultCount int64
54
+			// 第四步,将同步过来的头部信息存到中间库的检验检查操作表中
55
+			if len(lisHead) > 0 {
56
+				resultCount = 0
57
+				for _ , head := range lisHead {
58
+					// if len(head.Item) <= 0  {
59
+					// 	continue
60
+					// }
61
+					if len(head.ReportId) > 1 {
62
+						if len(head.Item) == 0 {
63
+							head.Item = "肾功三项"
64
+						}
65
+						middleReportHandle := models.MiddleReportHandle{
66
+							OrgId:			org_id,
67
+							HisUserId:		patient.AdmissionNumber,
68
+							ApplyNo:		head.ApplyNo,
69
+							ReportId:		head.ReportId,	
70
+							Name:			head.Name,	
71
+							Sex:			head.Sex,
72
+							Age:			head.Age,
73
+							Dept:			head.Dept,
74
+							PatientId:		head.PatientId,
75
+							RequestTime:	head.RequestTime,
76
+							ExecuteTime:	head.ExecuteTime,
77
+							ReceiveTime:	head.ReceiveTime,
78
+							Item:			head.Item,
79
+							CheckTime:		head.CheckTime,
80
+							PatientType:	head.PatientType,
81
+							CreatedTime:	time.Now().Unix(),
82
+							UpdatedTime:	time.Now().Unix(),
83
+						}
84
+						handleerr := CreateReportHandle(&middleReportHandle)
85
+						if handleerr != nil {
86
+							utils.ErrorLog("创建检验检查操作数据失败:%v", handleerr)
87
+							return
88
+						} 
89
+						// // reportInfos,ReportString := GetReport(head.ReportId)
90
+						// HeadString = HeadString + " " + ReportString
91
+						// // 获取该项的检验检查project_id,如果没有,则创建一个
92
+						// project_id,_ := GetProjectID(org_id,head.Item)
93
+						// if len(reportInfos) > 2 {
94
+						// 	// 将同步过来的检验检查数据存到中间库
95
+						// 	for _,reportInfo := range reportInfos{
96
+						// 		if len(reportInfo.ItemName) <= 0 {
97
+						// 			continue
98
+						// 		}
99
+						// 		// 获取该小项的检验检查item_id,如果没有,则创建一个
100
+						// 		item_id,_ := GetItemID(org_id,head.Item,reportInfo.ItemName,project_id)
101
+						// 		_,_,syerr := LgthSync(head,reportInfo,project_id,item_id,org_id,patient.ID,patient.AdmissionNumber)
102
+						// 		if syerr == nil {
103
+						// 			resultCount = resultCount + 1
104
+						// 		}
105
+						// 	}
106
+						// }
107
+					}
108
+				}
109
+				var syncInfo models.MiddleSyncInfo
110
+				syncInfo.OrgId = org_id
111
+				syncInfo.HisUserId = patient.AdmissionNumber
112
+				syncInfo.SyncTime = time.Now().Unix()
113
+				syncInfo.SyncResultType = 1
114
+				syncInfo.SyncRsultRemark = "同步成功"
115
+				syncInfo.SyncTotalNum = resultCount
116
+				syncInfo.SyncSuccessNum = 0
117
+				syncInfo.SyncInfo = HeadString
118
+				syncInfo.CreateTime = time.Now().Unix()
119
+				syncInfo.UpdateTime = time.Now().Unix()
120
+
121
+				cwderr := CreateSyncInfo(&syncInfo)
122
+				if cwderr != nil {
123
+					utils.ErrorLog("创建同步信息失败:%v", cwderr)
124
+					return
125
+				}	
126
+			} else {
127
+				// 未同步到检验检查头部信息
128
+				var syncInfo models.MiddleSyncInfo
129
+				syncInfo.OrgId = org_id
130
+				syncInfo.HisUserId = patient.AdmissionNumber
131
+				syncInfo.SyncTime = time.Now().Unix()
132
+				syncInfo.SyncResultType = 1
133
+				syncInfo.SyncRsultRemark = "该患者这个时间段没有任何检验检查数据"
134
+				syncInfo.CreateTime = time.Now().Unix()
135
+				syncInfo.UpdateTime = time.Now().Unix()
136
+
137
+				serr := CreateSyncInfo(&syncInfo)
138
+				if serr != nil {
139
+					utils.ErrorLog("创建同步信息失败:%v", serr)
140
+					return
141
+				}
142
+				continue 
143
+			}
144
+			
145
+		}
146
+	}
147
+	// 第五步,查询检验检查操作表里状态为0的数据,并将该对应报告的检验检查详情数据请求回来并存入该条数据里的report_info字段
148
+	ReportInfoHandle(org_id)
149
+	return 
150
+}
151
+
152
+func ReportInfoHandle (org_id int64) {
153
+	// 1.从检验检查表中查询操作状态为0的数据 
154
+	report_handle_list,_ := GetReportHandleListyOrgID(org_id)
155
+	if len(report_handle_list) > 0 {
156
+		for _,report_handle := range report_handle_list {
157
+			// 2. 根据report_id获取报告详情并进行相关处理
158
+			reportInfos,ReportString := GetReport(report_handle.ReportId)
159
+			if len(reportInfos) > 0 {
160
+				report_info_item_num := len(reportInfos)
161
+				// 将检验检查详情,检验检查小项条数更新到操作表数据中
162
+				middleReportHandle := models.MiddleReportHandle{
163
+					ID:					report_handle.ID,
164
+					ReportInfo:			ReportString,
165
+					ReportInfoItemNum: 	int64(report_info_item_num),
166
+					UpdatedTime:		time.Now().Unix(),
167
+				}
168
+				err := UpdateReportHandleListyOrgID(&middleReportHandle)
169
+				if err != nil {
170
+					utils.ErrorLog("创建同步信息失败:%v", err)
171
+					return
172
+				}
173
+				report_handle.ReportInfoItemNum = int64(report_info_item_num)
174
+				project_id,_ := GetProjectID(org_id,report_handle.Item)
175
+				patient,perr := GetUserInfoByAdmission(report_handle.HisUserId,org_id)
176
+				if perr != nil {
177
+					utils.ErrorLog("查询病人信息失败:%v", perr)
178
+					return
179
+				}
180
+				if len(reportInfos) > 0 {
181
+				// 将同步过来的检验检查数据存到中间库
182
+					for _,reportInfo := range reportInfos{
183
+						if len(reportInfo.ItemName) <= 0 {
184
+							continue
185
+						}
186
+						// 获取该小项的检验检查item_id,如果没有,则创建一个
187
+						item_id,_ := GetItemID(org_id,report_handle.Item,reportInfo.ItemName,project_id)
188
+						_,_,syerr := LgthSync(&report_handle,reportInfo,project_id,item_id,org_id,patient.ID,patient.AdmissionNumber)
189
+						if syerr != nil {
190
+							utils.ErrorLog("创建同步信息失败:%v", syerr)
191
+							return
192
+						}
193
+					}
194
+				}
195
+			} 
196
+		}
197
+	}
198
+	SyncToLgey()
199
+}
200
+
201
+func  SyncToLgey() {
202
+	utils.TraceLog("检验检查同步任务开始执行")
203
+	org_id := int64(9598)
204
+
205
+	// 第一步:跟进org_id 去中间库查出需要同步的数据
206
+	inspection_references,_ := GetSyncInspectionReferenceByOrgId(org_id)
207
+	inspections,_ := GetSyncInspectionByOrgId(org_id)
208
+
209
+	// 第二步:将数据同步到业务库
210
+	if len(inspection_references) > 0 {
211
+		for _,inspection_reference := range inspection_references {
212
+			SyncInspectionReference(&inspection_reference)
213
+		}
214
+	}
215
+
216
+	if len(inspections) > 0 {
217
+		for _,inspection := range inspections {
218
+			SyncInspection(&inspection)
219
+		}
220
+	}
221
+	utils.SuccessLog("检验检查同步任务完成")
222
+}
223
+
224
+// 从机构将数据同步到中间库
225
+func LgthSync(Head *models.MiddleReportHandle,report ReportInfo,project_id int64,item_id int64,org_id int64,patient_id int64,his_user_id string)(*models.MiddleInspectionReference,*models.MiddleInspection,error) {
226
+	tx := writeMiddleDb.Begin()
227
+	var inspection models.MiddleInspection
228
+	var inspection_reference models.MiddleInspectionReference
229
+	recordDateStr := Head.CheckTime
230
+
231
+	if len(Head.CheckTime) == 0 { 
232
+		recordDateStr = time.Now().Format("2006-01-02 15:04")
233
+	} else {
234
+		dateTempArrOne := strings.Split(recordDateStr,"T")
235
+		dateTempArrTwo := strings.Split(dateTempArrOne[1],".")
236
+		recordDateStr = dateTempArrOne[0] + " " + dateTempArrTwo[0]
237
+	}
238
+
239
+	record_date_str, _ := utils.ParseTimeStringToTime("2006-01-02 15:04:05", recordDateStr)
240
+	record_date := record_date_str.Unix()
241
+	inspect_date := time.Unix(record_date,0).Format("2006-01-02 15:04")
242
+	// date, _ := utils.ParseTimeStringToTime("2006-01-02 15:04", recordDateStr)
243
+	// record_date,_ := utils.ParseTimeStringToTime("2006-01-02", date.Format("2006-01-02"))
244
+	var total int
245
+	var itotal int
246
+	var RangeOptions string 
247
+	var RangeMin string
248
+	var RangeMax string
249
+
250
+	// // 判断检查类型
251
+	ItemType := 1
252
+	Range := strings.Split(report.Reference,"~")
253
+	if len(Range) > 1   {
254
+		RangeMin = Range[0]
255
+		RangeMax = Range[1] 
256
+		ItemType = 1
257
+	} else {
258
+		ItemType = 2
259
+		RangeOptions = report.Reference
260
+	}
261
+
262
+
263
+
264
+	err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and project_id = ? and item_id = ? and status = 1", org_id, project_id,item_id).Find(&inspection_reference).Count(&total).Error
265
+	if inspection_reference.ID > 0 {
266
+		ItemType = inspection_reference.RangeType
267
+	}
268
+	if total <= 0 && len(Head.Item) > 0 {
269
+		inspection_reference.OrgId = org_id
270
+		inspection_reference.ProjectName = Head.Item
271
+		inspection_reference.Project = Head.Item
272
+		inspection_reference.ProjectId = project_id
273
+		inspection_reference.ItemName = report.ItemName
274
+		inspection_reference.ItemId = item_id
275
+		inspection_reference.RangeType = ItemType
276
+		inspection_reference.RangeMin = RangeMin
277
+		inspection_reference.RangeMax = RangeMax
278
+		// inspection_reference.RangeValue = RangeValue
279
+		inspection_reference.RangeOptions = RangeOptions
280
+		inspection_reference.Unit = report.Unit
281
+		inspection_reference.Status = 1
282
+		inspection_reference.CreatedTime = time.Now().Unix()
283
+		inspection_reference.UpdatedTime = time.Now().Unix()
284
+		inspection_reference.InspectDate = inspect_date
285
+		inspection_reference.UTime = inspect_date
286
+		err = tx.Model(&models.MiddleInspectionReference{}).Create(&inspection_reference).Error
287
+		if err != nil {
288
+			tx.Rollback()
289
+		}
290
+	}
291
+
292
+	err = readMiddleDb.Model(&models.MiddleInspection{}).Where("org_id = ? and project_id = ? and item_id = ? and record_date = ? and patient_id = ?  and status = 1", org_id, project_id,item_id,record_date,patient_id).Find(&inspection).Count(&itotal).Error
293
+	if itotal <= 0 {
294
+		inspection.PatientId = patient_id
295
+		inspection.OrgId = org_id
296
+		inspection.ProjectId = project_id
297
+		inspection.ItemName = report.ItemName
298
+		inspection.ProjectName = Head.Item
299
+		inspection.InspectType = ItemType
300
+		inspection.ItemId = item_id
301
+		inspection.InspectValue = report.Result
302
+		inspection.InspectDate = inspect_date
303
+		inspection.RecordDate = record_date
304
+		inspection.Status = 1
305
+		inspection.CreatedTime = time.Now().Unix()
306
+		inspection.UpdatedTime = time.Now().Unix()
307
+		inspection.UTime = inspect_date
308
+		inspection.HisUserId = his_user_id
309
+		err = tx.Model(&models.MiddleInspection{}).Create(&inspection).Error
310
+		if err != nil {
311
+			tx.Rollback()
312
+		}
313
+
314
+		//处理检验检查操作表里同步条数和状态
315
+		cur_num := Head.ReportInfoItemHandleNum + 1
316
+		Head.ReportInfoItemHandleNum = cur_num
317
+		handleType := 2 
318
+		if cur_num == Head.ReportInfoItemNum {
319
+			handleType = 1
320
+		}
321
+		middleReportHandle := models.MiddleReportHandle{
322
+			ID:							Head.ID,
323
+			ReportInfoItemHandleNum:	cur_num,
324
+			HandleType:					int64(handleType),
325
+			UpdatedTime:				time.Now().Unix(),
326
+		}
327
+		err = UpdateReportHandleListyOrgID(&middleReportHandle)
328
+		if err != nil {
329
+			tx.Rollback()
330
+		}
331
+	}
332
+
333
+	tx.Commit()
334
+	return nil,nil,err
335
+}
336
+
337
+// 根据机构ID和检验检查小项名称获取该检查的item_id,如没有,则创建一个
338
+func GetItemID(org_id int64,project_name string,item_name string,project_id int64) (item_id int64 ,err error) {
339
+	var inspection_reference models.MiddleInspectionReference
340
+	err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and status = 1 and project_name = ? and item_name = ?", org_id,project_name,item_name).First(&inspection_reference).Error
341
+	if inspection_reference.ID > 0 {
342
+		return inspection_reference.ItemId,err
343
+	} else {
344
+		err := readMiddleDb.Table("xt_middle_inspection_reference").Where("org_id = ? and project_id = ? ", org_id,project_id).Select("max(item_id) as item_id").First(&inspection_reference).Error
345
+		utils.InfoLog("inspection_reference: %v",inspection_reference)
346
+		if inspection_reference.ItemId > 0 {
347
+			return inspection_reference.ItemId + 1,err
348
+		} else {
349
+			return project_id * 1000 + 1 ,err
350
+		}
351
+	}
352
+}
353
+
354
+// 根据机构ID和检验检查名称获取该检查的project_id,如没有,则创建一个
355
+func GetProjectID(org_id int64,project_name string) (project_id int64 ,err error) {
356
+	var inspection_reference models.MiddleInspectionReference
357
+	err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and status = 1 and project_name = ?", org_id,project_name).First(&inspection_reference).Error
358
+	if inspection_reference.ID > 0 {
359
+		return inspection_reference.ProjectId,err
360
+	} else {
361
+		err := readMiddleDb.Table("xt_middle_inspection_reference").Where("org_id=? ", org_id).Select("max(project_id) as project_id").Scan(&inspection_reference).Error
362
+		utils.InfoLog("inspection_reference: %v",inspection_reference)
363
+		if inspection_reference.ProjectId > 0 {
364
+			return inspection_reference.ProjectId + 1,err
365
+		} else {
366
+			return 18001,err
367
+		}
368
+	}
369
+}
370
+
371
+// 根据机构ID获取该机构所有病人的admission_number (住院号)
372
+func GetUserInfoByOrgID(org_id int64) (patients []models.Patients ,err error) {
373
+	err = readDb.Model(&models.Patients{}).Where("user_org_id = ? and status = 1", org_id).Find(&patients).Error
374
+	return
375
+}
376
+
377
+// 根据机构ID获取该机构所有病人的admission_number (住院号)
378
+func GetUserInfoByAdmission(admission_number string,org_id int64) (patients models.Patients ,err error) {
379
+	err = readDb.Model(&models.Patients{}).Where("user_org_id = ? and admission_number = ?  and status = 1", org_id,admission_number).First(&patients).Error
380
+	return
381
+}
382
+
383
+type HeadInfo struct {
384
+	ApplyNo        	string  `json:"applyNo"`
385
+	ReportId        string	`json:"reportId"`
386
+	Name       		string	`json:"name"`
387
+	Sex       		string	`json:"sex"`
388
+	Age 			string	`json:"age"`
389
+	Dept 			string	`json:"dept"`
390
+	BedNo 			string	`json:"bedNo"`
391
+	PatientId 		string	`json:"patientId"`
392
+	PatientPid 		string	`json:"patientPid"`
393
+	SampleNo 		float64	`json:"sampleNo"`
394
+	RequestTime 	string	`json:"requestTime"`
395
+	ExecuteTime 	string	`json:"executeTime"`
396
+	ReceiveTime 	string	`json:"receiveTime"`
397
+	Item 			string	`json:"item"`
398
+	CheckTime 		string	`json:"checkTime"`
399
+	PatientType 	string	`json:"patientType"`
400
+	RequestTimes 	string	`json:"request_time"`
401
+}
402
+
403
+type ReportInfo struct {
404
+	ReportId    string  `json:"reportId"`
405
+	ItemCode    string	`json:"itemCode"`
406
+	ItemName    string	`json:"itemName"`
407
+	StdCode     string	`json:"stdCode"`
408
+	Result 		string	`json:"result"`
409
+	Unit 		string	`json:"unit"`
410
+	SampleNo 	float64	`json:"sampleNo"`
411
+	Reference 	string	`json:"reference"`
412
+	Prompt 		string	`json:"prompt"`
413
+}
414
+
415
+func GetHead(patient_id string,start_time string,end_time string)(head []HeadInfo,str string){
416
+	Domain := "http://www.szlg2h.cn:9991/xuetoushi/head/getHead?"
417
+	apiurl := "patient_id=" + patient_id + "&check_time_start=" + start_time + "&check_time_end=" + end_time
418
+	apiurl = url.PathEscape(apiurl)
419
+	apiurl = Domain + apiurl
420
+	utils.InfoLog("url: %v",apiurl)
421
+	var respJSON []HeadInfo
422
+	httplib.Get(apiurl).ToJSON(&respJSON)
423
+	jsonStr, _ := json.Marshal(respJSON)
424
+	utils.InfoLog("请求患者检查头部数据接口返回数据: %v",string(jsonStr))
425
+	return respJSON,string(jsonStr)
426
+}
427
+
428
+func GetReport(report_id string)(head  []ReportInfo,str string){
429
+	Domain := "http://www.szlg2h.cn:9991/xuetoushi/detail/getDetail?"
430
+	apiurl := "report_id=" + report_id 
431
+	apiurl = url.PathEscape(apiurl)
432
+	apiurl = Domain + apiurl
433
+	
434
+	var respJSON []ReportInfo
435
+	httplib.Get(apiurl).ToJSON(&respJSON)
436
+	jsonStr, _ := json.Marshal(respJSON)
437
+	utils.InfoLog("请求患者检查详情数据接口返回数据: %v",string(jsonStr))
438
+	return respJSON,string(jsonStr)
439
+}

+ 296 - 0
service/lis_service.go 查看文件

@@ -0,0 +1,296 @@
1
+package service
2
+
3
+import (
4
+	"IC/models"
5
+	"IC/utils"
6
+	_"strconv"
7
+	"strings"
8
+	"time"
9
+	_"IC/utils"
10
+	_"fmt"
11
+	_"github.com/jinzhu/gorm"
12
+)
13
+
14
+// 获取备份库所有的医嘱信息
15
+func GetAllAdvice() (Advice []models.DoctorAdvice,err error) {
16
+	err = backupDb.Model(&models.DoctorAdvice{}).Offset(100000).Limit(10000).Find(&Advice).Error
17
+	return
18
+}
19
+
20
+// 修改医嘱信息
21
+func SyncAdvice(Advice *models.DoctorAdvice) error {
22
+	err := writeDb.Model(&models.DoctorAdvice{}).Updates(&Advice).Error
23
+	return err
24
+}
25
+
26
+// 查找有字段的机构 
27
+func GetfiledConfigOrg() (FiledConfig []models.FiledConfig,err error) {
28
+	db := readDb.Begin()
29
+	err = db.Table("xt_filed_config").Group("org_id").Select("org_id,module,filed_name").Where("org_id > 0").Scan(&FiledConfig).Error
30
+	return
31
+}
32
+
33
+// 查询系统字段 
34
+func GetfiledConfigSys() (FiledConfig []models.FiledConfig,err error) {
35
+	err = readDb.Model(&models.FiledConfig{}).Where("org_id = 0").Find(&FiledConfig).Error
36
+	return 
37
+}
38
+
39
+// 跟进查询条件查询结果
40
+func GetfiledConfigByOrgId(org_id int64,module int64,filed_name string)(FiledConfig models.FiledConfig,err error) {
41
+	err = readDb.Model(&models.FiledConfig{}).Where("org_id = ? and module = ? and filed_name = ?",org_id,module,filed_name).First(&FiledConfig).Error
42
+	return 
43
+}
44
+
45
+// 创建一条字段数据详情
46
+func CreatefiledConfig(FiledConfig *models.FiledConfig) error {
47
+	err := writeDb.Create(&FiledConfig).Error
48
+	return err
49
+}
50
+
51
+// 从机构将数据同步到中间库
52
+func SyncInspectionReference(data *models.MiddleInspectionReference) error {
53
+	tx := writeDb.Begin()
54
+	var inspection_reference models.InspectionReference
55
+	var total int
56
+	err = readDb.Model(&models.InspectionReference{}).Where("org_id = ? and project_id = ? and item_id = ?  and status = 1", data.OrgId, data.ProjectId,data.ItemId).Find(&inspection_reference).Count(&total).Error
57
+	if total <= 0 {
58
+		inspection_reference.OrgId = data.OrgId
59
+		inspection_reference.ProjectName = data.ProjectName
60
+		inspection_reference.Project = data.ProjectName
61
+		inspection_reference.ProjectId = data.ProjectId
62
+		inspection_reference.ItemName = data.ItemName
63
+		inspection_reference.ItemId = data.ItemId
64
+		inspection_reference.RangeType = data.RangeType
65
+		inspection_reference.RangeMin = data.RangeMin
66
+		inspection_reference.RangeMax = data.RangeMax
67
+		inspection_reference.RangeValue = data.RangeValue
68
+		inspection_reference.RangeOptions = data.RangeOptions
69
+		inspection_reference.Unit = data.Unit
70
+		inspection_reference.Status = 1
71
+		inspection_reference.CreatedTime = time.Now().Unix()
72
+		inspection_reference.UpdatedTime = time.Now().Unix()
73
+
74
+		err := tx.Model(&models.InspectionReference{}).Create(&inspection_reference).Error
75
+		if err != nil {
76
+			tx.Rollback()
77
+		}
78
+
79
+		data.IsSync = 1
80
+		data.SyncId = inspection_reference.ID
81
+		data.UpdatedTime = time.Now().Unix()
82
+		ierr := writeMiddleDb.Save(&data).Error
83
+		if ierr != nil {
84
+			tx.Rollback()
85
+		}
86
+	}
87
+	tx.Commit()
88
+	return err
89
+}
90
+
91
+// 从机构将数据同步到中间库
92
+func SyncInspection(data *models.MiddleInspection) error {
93
+	tx := writeDb.Begin()
94
+	var inspection models.Inspection
95
+	var total int
96
+	err = readDb.Model(&models.Inspection{}).Where("org_id = ? and project_id = ? and item_id = ? and patient_id =? and inspect_date=?  and status = 1", data.OrgId, data.ProjectId,data.ItemId,data.PatientId,data.InspectDate).Find(&inspection).Count(&total).Error
97
+	if total <= 0 {
98
+		inspection.OrgId = data.OrgId
99
+		inspection.PatientId = data.PatientId
100
+		inspection.ProjectName = data.ProjectName
101
+		// inspection.Project = data.ProjectName
102
+		inspection.ProjectId = data.ProjectId
103
+		inspection.ItemName = data.ItemName
104
+		inspection.ItemId = data.ItemId
105
+		inspection.InspectType = int64(data.InspectType)
106
+		inspection.InspectValue = data.InspectValue
107
+		inspection.InspectTips = data.InspectTips
108
+		inspection.InspectDate = data.RecordDate
109
+		inspection.Status = 1
110
+		inspection.CreatedTime = time.Now().Unix()
111
+		inspection.UpdatedTime = time.Now().Unix()
112
+
113
+		err := tx.Model(&models.Inspection{}).Create(&inspection).Error
114
+		if err != nil {
115
+			tx.Rollback()
116
+		}
117
+
118
+		data.IsSync = 1
119
+		data.SyncId = inspection.ID
120
+		data.UpdatedTime = time.Now().Unix()
121
+		ierr := writeMiddleDb.Save(&data).Error
122
+		if ierr != nil {
123
+			tx.Rollback()
124
+		}
125
+	}
126
+	tx.Commit()
127
+	return err
128
+}
129
+
130
+// 跟进org_id获取未同步的检验检查选项信息
131
+func GetSyncInspectionReferenceByOrgId(org_id int64) (InspectionReferences []models.MiddleInspectionReference,err error) {
132
+	err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and status = 1 and is_sync = 0", org_id).Find(&InspectionReferences).Error
133
+	return
134
+}
135
+
136
+// 跟进org_id获取未同步的检验检查信息
137
+func GetSyncInspectionByOrgId(org_id int64) (Inspection []models.MiddleInspection,err error) {
138
+	err = readMiddleDb.Model(&models.MiddleInspection{}).Where("org_id = ? and status = 1 and is_sync = 0", org_id).Find(&Inspection).Error
139
+	return
140
+}
141
+
142
+// 修改一条同步数据详情
143
+func UpdateSyncInfo(syncInfo *models.MiddleSyncInfo) error {
144
+	err := writeMiddleDb.Save(&syncInfo).Error
145
+	return err
146
+}
147
+
148
+// 创建一条同步数据详情
149
+func CreateSyncInfo(syncInfo *models.MiddleSyncInfo) error {
150
+	err := writeMiddleDb.Create(&syncInfo).Error
151
+	return err
152
+}
153
+
154
+// 创建一条检验检查操作表数据
155
+func CreateReportHandle(report *models.MiddleReportHandle) error {
156
+	err := writeMiddleDb.Create(&report).Error
157
+	return err
158
+}
159
+
160
+// 根据机构ID获取该机构检验检查操作表里状态为0的数据
161
+func GetReportHandleListyOrgID(org_id int64) (report_handle_list []models.MiddleReportHandle ,err error){
162
+	err = readMiddleDb.Model(&models.MiddleReportHandle{}).Where("org_id = ?  and  handle_type = 0 ",  org_id).Find(&report_handle_list).Error
163
+	return
164
+}
165
+
166
+// 根据机构ID修改检验检查操作表里的数据
167
+func UpdateReportHandleListyOrgID(report_handle *models.MiddleReportHandle)  error{
168
+	err := writeMiddleDb.Model(&models.MiddleReportHandle{}).Updates(&report_handle).Error
169
+	return err
170
+}
171
+
172
+// 跟进机构ID获取该机构所有病人的his_user_id
173
+func GetHisUserIdByOrgID(org_id int64) (patients []models.MiddlePatients ,err error) {
174
+	err = readMiddleDb.Model(&models.MiddlePatients{}).Where("user_org_id = ? and status = 1", org_id).Find(&patients).Error
175
+	return
176
+}
177
+
178
+// 根据机构ID获取该机构上次同步信息
179
+func GetSyncTimeByOrgID(org_id int64,his_user_id string) (sync_info models.MiddleSyncInfo ,err error){
180
+	err = readMiddleDb.Model(&models.MiddleSyncInfo{}).Where("org_id = ?  and  his_user_id =? ",  org_id,his_user_id).Last(&sync_info).Error
181
+	return
182
+}
183
+
184
+// 根据机构ID获取该机构上次同步信息
185
+func GetSyncTimeByOrgIDForYs(org_id int64) (sync_info models.MiddleSyncInfo ,err error){
186
+	err = readMiddleDb.Model(&models.MiddleSyncInfo{}).Where("org_id = ? ",  org_id).Last(&sync_info).Error
187
+	return
188
+}
189
+
190
+// 根据机构ID和His_useer_id获取该患者最后一条同步检查数据
191
+func GetInspectionLastInfoByOrgID(org_id int64,his_user_id string) (inspectionLastInfo models.MiddleInspection ,err error){
192
+	err = readMiddleDb.Model(&models.MiddleInspection{}).Where("org_id = ?  and  his_user_id =? ",  org_id,his_user_id).Order("created_time desc").First(&inspectionLastInfo).Error
193
+	return
194
+}
195
+
196
+// 从机构将数据同步到中间库
197
+func Sync(data *models.TBLISItem,org_id int64,patient_id int64)(*models.MiddleInspectionReference,*models.MiddleInspection,error) {
198
+	tx := writeMiddleDb.Begin()
199
+	var inspection models.MiddleInspection
200
+	var inspection_reference models.MiddleInspectionReference
201
+	recordDateStr := data.UTime
202
+	if len(data.UTime) == 0 { 
203
+		recordDateStr = time.Now().Format("2006-01-02 15:04")
204
+	}
205
+	record_date, _ := utils.ParseTimeStringToTime("2006-01-02 15:04", recordDateStr)
206
+	// date, _ := utils.ParseTimeStringToTime("2006-01-02 15:04", recordDateStr)
207
+	// record_date,_ := utils.ParseTimeStringToTime("2006-01-02", date.Format("2006-01-02"))
208
+	var total int
209
+	var itotal int
210
+	if len(data.RangeOptions) > 0 {
211
+		data.ItemType = 2
212
+	} else {
213
+		data.ItemType = 1
214
+		if len(data.RangeMax) > 0 {
215
+			Range := strings.Split(data.RangeMax,"-")
216
+			if len(Range) > 1 {
217
+				data.RangeMin = Range[0]
218
+				data.RangeMax = Range[1] 
219
+			} else {
220
+				data.RangeMin = Range[0]
221
+			}
222
+		}
223
+	}
224
+
225
+	err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and project_id = ? and item_id = ? and status = 1", org_id, data.ProjectId,data.ItemId).Find(&inspection_reference).Count(&total).Error
226
+	if total <= 0 && len(data.ProjectName) > 0 {
227
+		inspection_reference.OrgId = org_id
228
+		inspection_reference.ProjectName = data.ProjectName
229
+		inspection_reference.Project = data.ProjectName
230
+		inspection_reference.ProjectId = data.ProjectId
231
+		inspection_reference.ItemName = data.ItemName
232
+		inspection_reference.ItemId = data.ItemId
233
+		inspection_reference.RangeType = data.ItemType
234
+		inspection_reference.RangeMin = data.RangeMin
235
+		inspection_reference.RangeMax = data.RangeMax
236
+		inspection_reference.RangeValue = data.RangeValue
237
+		inspection_reference.RangeOptions = data.RangeMax
238
+		inspection_reference.Unit = data.Unit
239
+		inspection_reference.Status = 1
240
+		inspection_reference.CreatedTime = time.Now().Unix()
241
+		inspection_reference.UpdatedTime = time.Now().Unix()
242
+		inspection_reference.InspectDate = data.InspectDate
243
+		inspection_reference.UTime = data.UTime
244
+		err := tx.Model(&models.MiddleInspectionReference{}).Create(&inspection_reference).Error
245
+		if err != nil {
246
+			tx.Rollback()
247
+		}
248
+	}
249
+
250
+	err = readMiddleDb.Model(&models.MiddleInspection{}).Where("org_id = ? and project_id = ? and item_id = ? and record_date = ? and patient_id = ?  and status = 1", org_id, data.ProjectId,data.ItemId,record_date.Unix(),patient_id).Find(&inspection).Count(&itotal).Error
251
+	if itotal <= 0 {
252
+		inspection.PatientId = patient_id
253
+		inspection.OrgId = org_id
254
+		inspection.ProjectId = data.ProjectId
255
+		inspection.ItemName = data.ItemName
256
+		inspection.ProjectName = data.ProjectName
257
+		inspection.InspectType = data.ItemType
258
+		inspection.ItemId = data.ItemId
259
+		if data.ItemType == 1 {
260
+			inspection.InspectValue = data.ItemValue
261
+		} else {
262
+			inspection.InspectValue = data.RangeValue
263
+		}
264
+		inspection.InspectDate = data.InspectDate
265
+		inspection.RecordDate = record_date.Unix()
266
+		inspection.Status = 1
267
+		inspection.CreatedTime = time.Now().Unix()
268
+		inspection.UpdatedTime = time.Now().Unix()
269
+		inspection.UTime = data.UTime
270
+		inspection.HisUserId = data.HisUserId
271
+		err := tx.Model(&models.MiddleInspection{}).Create(&inspection).Error
272
+		if err != nil {
273
+			tx.Rollback()
274
+		}
275
+	}
276
+
277
+	tx.Commit()
278
+	return &inspection_reference,&inspection,err
279
+}
280
+
281
+//GetPatientList 返回患者的列表
282
+func GetList(his_user_id []interface{},syncTimes string) (lis []*models.TBLISItem,  err error) {
283
+	err = readRemoteDb.Model(&models.TBLISItem{}).Where("u_time > ? AND his_user_id in (?)  ",syncTimes,his_user_id).Find(&lis).Error
284
+	return
285
+}
286
+
287
+//GetPatientList 返回患者的列表
288
+func GetListByHisUserID(his_user_id string,syncTimes string,selectType int64) (lis []*models.TBLISItem,err error) {
289
+	if selectType == 1 {
290
+	 	err = readRemoteDb.Model(&models.TBLISItem{}).Where("u_time > ? AND patient_name = ?  ",syncTimes,his_user_id).Find(&lis).Error
291
+	 } else {
292
+		err = readRemoteDb.Model(&models.TBLISItem{}).Where("u_time > ? AND his_user_id = ? ",syncTimes,his_user_id).Find(&lis).Error
293
+	 }
294
+	return
295
+}
296
+

+ 20 - 0
service/redis.go 查看文件

@@ -0,0 +1,20 @@
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
+	pong, err := client.Ping().Result()
18
+	fmt.Println(pong, err)
19
+	return client
20
+}

文件差异内容过多而无法显示
+ 1372 - 0
service/ystx_service.go


+ 1 - 0
static/js/reload.min.js 查看文件

@@ -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)};

+ 39 - 0
tests/default_test.go 查看文件

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

+ 13 - 0
utils/ip_helper.go 查看文件

@@ -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 查看文件

@@ -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 查看文件

@@ -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 查看文件

@@ -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 查看文件

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

+ 27 - 0
utils/time_helper.go 查看文件

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

+ 231 - 0
utils/tools.go 查看文件

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

文件差异内容过多而无法显示
+ 95 - 0
views/index.tpl