Kaynağa Gözat

check record

Rick.Lan 1 ay önce
ebeveyn
işleme
762c22ce60

+ 5 - 0
controllers/api_base_controller.go Dosyayı Görüntüle

@@ -43,10 +43,15 @@ func ApiControllersRegisterRouters() {
43 43
 	beego.Router("/xcx/api/sysdic/getdevicetypes", &SysDicApiController{}, "Get:GetDeviceTypes")
44 44
 
45 45
 	beego.Router("xcx/api/device/binddevice", &DeviceApiController{}, "Post:BindDevice")
46
+	beego.Router("/xcx/api/device/binddevicebyid", &DeviceApiController{}, "Post:BindDeviceById")
46 47
 	beego.Router("/xcx/api/device/getdevicedetail", &DeviceApiController{}, "Get:GetDeviceDetail")
47 48
 	beego.Router("/xcx/api/device/getmydevices", &DeviceApiController{}, "Get:GetMyDevices")
48 49
 	beego.Router("/xcx/api/device/unbinddevice", &DeviceApiController{}, "Post:UnbindDevice")
49 50
 
51
+	beego.Router("/xcx/api/checkrecord/getcheckrecorditembyid", &CheckRecordApiController{}, "Get:GetCheckRecordItemById")
52
+	beego.Router("/xcx/api/checkrecord/getcheckrecordlist", &CheckRecordApiController{}, "Get:GetCheckRecordList")
53
+	beego.Router("/xcx/api/checkrecord/qrcodecheckrecord", &CheckRecordApiController{}, "Get:QrCodeCheckRecord")
54
+
50 55
 }
51 56
 
52 57
 type BaseApiController struct {

+ 365 - 1
controllers/check_record_api_controller.go Dosyayı Görüntüle

@@ -1,21 +1,385 @@
1 1
 package controllers
2 2
 
3
+import (
4
+	"encoding/json"
5
+	"fmt"
6
+	"math"
7
+	"regexp"
8
+	"strconv"
9
+	"strings"
10
+	"sws_xcx/enums"
11
+	"sws_xcx/models"
12
+	"sws_xcx/service"
13
+	"sws_xcx/utils"
14
+	"time"
15
+	"unicode/utf8"
16
+)
17
+
3 18
 type CheckRecordApiController struct {
4 19
 	BaseApiAuthController
5 20
 }
6 21
 
22
+// @Title GetCheckRecordList
23
+// @Description 分页获取检测记录
24
+// @Param   pageNum query int true "当前页(从1开始)"
25
+// @Param   pageSize query int true "分页大小"
26
+// @Success 200 {array} models.AppCheckRecordVO success
27
+// @Failure 500 error
28
+// @Security token
29
+// @router /getcheckrecordlist [get]
7 30
 func (c *CheckRecordApiController) GetCheckRecordList() {
31
+	pageNum, _ := c.GetInt("pageNum", 1)
32
+	pageSize, _ := c.GetInt("pageSize", 10)
33
+
34
+	crs := service.NewCheckRecordService()
35
+	rs, total, err := crs.GetCheckRecordList(pageNum, pageSize, c.CurrentUser.Id)
36
+	if err != nil {
37
+		c.ServeDynamicFailJsonSend(fmt.Sprintf("GetCheckRecordList err:%v", err))
38
+		return
39
+	}
40
+
41
+	c.ServeSuccessPageJSON(rs, total)
8 42
 
9 43
 }
10 44
 
45
+/**********
46
+// @Title GetCheckRecordItemReport
47
+// @Description 获取检测报告
48
+// @Param   itemid query int true "项目ID"
49
+// @Param   daymun query int true "最近几天"
50
+// @Success 200 {object} models.AppCheckRecordItemReportVO success
51
+// @Failure 500 error
52
+// @Security token
53
+// @router /getcheckrecorditemreport [get]
11 54
 func (c *CheckRecordApiController) GetCheckRecordItemReport() {
12 55
 
13
-}
56
+}**/
14 57
 
58
+// @Title GetCheckRecordItemById
59
+// @Description 通过检测ID查看检测结果
60
+// @Param   checkid query int true "检测ID"
61
+// @Success 200 {object} models.AppCheckRecordItemVO success
62
+// @Failure 500 error
63
+// @Security token
64
+// @router /getcheckrecorditembyid [get]
15 65
 func (c *CheckRecordApiController) GetCheckRecordItemById() {
16 66
 
67
+	id, err := c.GetInt64("checkid")
68
+	if err != nil {
69
+		c.ServeDynamicFailJsonSend(err.Error())
70
+		return
71
+	}
72
+	crs := service.NewCheckRecordService()
73
+	record, err := crs.GetCheckRecordById(id)
74
+	if err != nil {
75
+		c.ServeDynamicFailJsonSend(fmt.Sprintf("GetCheckRecord err:%v", err))
76
+		return
77
+	}
78
+	recordItems, err := crs.GetCheckRecordItems(record.Id)
79
+	if err != nil {
80
+		c.ServeDynamicFailJsonSend(fmt.Sprintf("GetCheckRecordItems err:%v", err))
81
+		return
82
+	}
83
+	checkItems, err := service.NewCheckItemService().GetCheckItems("cn", "1")
84
+
85
+	if err != nil {
86
+		c.ServeDynamicFailJsonSend(fmt.Sprintf("GetCheckItems err:%v", err))
87
+		return
88
+	}
89
+
90
+	checkRecordItem, err := analyzeCheckRecord(recordItems, checkItems)
91
+	if err != nil {
92
+		c.ServeDynamicFailJsonSend(fmt.Sprintf("analyzeCheckRecord err:%v", err))
93
+		return
94
+	}
95
+	checkRecordItem.CheckDate = record.Ctime
96
+	checkRecordItem.UserID = int64(record.UserId)
97
+	checkRecordItem.Bind = checkRecordItem.UserID > 0
98
+	checkRecordItem.CheckRecordID = record.Id
99
+
100
+	c.ServeSuccessJSON(checkRecordItem)
101
+}
102
+
103
+var DIGITS = []rune{
104
+	'S', 'V', 'X', '5', '0', '8', '-', 'N',
105
+	'i', 'm', 'd', 'u', 'H', 'O', 'Q', 'E',
106
+	'D', 'v', 't', '2', 'c', 'p', '1', '3',
107
+	'z', 'R', 'a', 'W', 'l', 'G', 'k', 'A',
108
+	'9', 'o', 's', 'g', 'y', '4', 'w', 'L',
109
+	'T', 'Y', 'b', '+', 'J', 'x', '7', 'r',
110
+	'I', 'n', 'f', 'Z', 'e', 'M', 'C', 'P',
111
+	'U', 'B', 'j', '6', 'F', 'K', 'h', 'q',
17 112
 }
18 113
 
114
+// @Title QrCodeCheckRecord
115
+// @Description 通过扫描二维码查看检测结果
116
+// @Param   qrcode query int true "扫描二维码的内容"
117
+// @Success 200 {object} models.AppCheckRecordItemVO success
118
+// @Failure 500 error
119
+// @Security token
120
+// @router /qrcodecheckrecord [get]
19 121
 func (c *CheckRecordApiController) QrCodeCheckRecord() {
122
+	result := c.GetString("qrcode")
123
+	var userId uint64
124
+
125
+	if result != "" {
126
+
127
+		re := regexp.MustCompile(`(http.*/)?(.+)$`)
128
+		matches := re.FindStringSubmatch(result)
129
+
130
+		str := matches[2]
131
+
132
+		parity := str[len(str)-1:]
133
+		st := int8(0)
134
+		result1 := result[:len(result)-1]
135
+
136
+		for i := 0; i < utf8.RuneCountInString(result1); i++ {
137
+			r, _ := utf8.DecodeRuneInString(result1[i:])
138
+			st += int8(r)
139
+			st = int8(getUint8(int(st)))
140
+		}
141
+		digit := DIGITS[getUint8(int(^st))%64]
142
+		if string(digit) != parity {
143
+			c.ServeDynamicFailJsonSend("检测数据校验不通过")
144
+			return
145
+		}
146
+		item, err := strconv.ParseInt(str[:1], 16, 32)
147
+		if err != nil {
148
+			c.ServeDynamicFailJsonSend(fmt.Sprintf("无法解析检测结果: %v", err))
149
+			return
150
+		}
151
+		if item != 14 && item != 11 {
152
+			c.ServeDynamicFailJsonSend("无法解析检测结果")
153
+			return
154
+		}
155
+
156
+		strs := str[1 : len(str)-1]
157
+		strs = regexp.MustCompile(`[._&$|]`).ReplaceAllString(strs, " ")
158
+		strsArray := strings.Fields(strs)
159
+
160
+		if len(strsArray) < 5 {
161
+			c.ServeDynamicFailJsonSend("无法解析检测结果")
162
+			return
163
+		}
164
+
165
+		serialno := "09" + formatNumber(radixString(strsArray[0]), 8)
166
+		serialno += formatNumber(radixString(strsArray[1]), 7)
167
+
168
+		acc := int(radixString(strsArray[2]))
169
+
170
+		checkResultStr := formatNumber(radixString(strsArray[3]), 7)
171
+		if item == 14 {
172
+			checkResultStr += formatNumber(radixString(strsArray[4]), 7)
173
+		} else if item == 11 {
174
+			checkResultStr += formatNumber(radixString(strsArray[4]), 4)
175
+		}
176
+
177
+		// fmt.Println("Device Name:", serialno)
178
+		// fmt.Println("Acc:", acc)
179
+		// fmt.Println("Check Result String:", checkResultStr)
180
+
181
+		device, err := service.NewDeviceService().GetDeviceByNo(serialno)
182
+		if err != nil {
183
+			c.ServeDynamicFailJsonSend(fmt.Sprintf("GetDeviceByNo err:%v", err))
184
+			return
185
+		}
186
+		if device.Id == 0 {
187
+			c.ServeDynamicFailJsonSend("不是本系统中的设备,无法解析结果")
188
+			return
189
+		}
190
+		ds := service.NewDeviceService()
191
+		dr, err := ds.GetDeviceRelateByDeviceId(device.Id)
192
+		if err != nil {
193
+			c.ServeDynamicFailJsonSend(fmt.Sprintf("GetDeviceRelateByDeviceId err:%v", err))
194
+			return
195
+		}
196
+		var status int
197
+		if dr.Id == 0 {
198
+			//设备未绑定 提示绑定
199
+			status = 1
200
+
201
+		} else if dr.UserId != userId {
202
+			//别人已经绑定设备,返回结果 并提示
203
+			status = 2
204
+
205
+		} else {
206
+			//自己绑定的设备,返回结果不提示
207
+			status = 3
208
+		}
209
+		da := strings.Split(checkResultStr, "")
210
+		count := len(da)
211
+		checkItems, err := service.NewCheckItemService().GetCheckItems("cn", device.DeviceType)
212
+
213
+		if err != nil {
214
+			c.ServeDynamicFailJsonSend(fmt.Sprintf("GetCheckItems err:%v", err))
215
+			return
216
+		}
217
+		crs := service.NewCheckRecordService()
218
+		record, err := crs.GetCheckRecordByAcc(device.Id, acc)
219
+		if err != nil {
220
+			c.ServeDynamicFailJsonSend(fmt.Sprintf("GetCheckRecordByAcc err:%v", err))
221
+			return
222
+		}
223
+		if record.Id == 0 {
224
+			//创建记录
225
+			err = ds.CreateDeviceMessageLog(models.DeviceMessageLog{
226
+				DeviceName: device.DeviceName,
227
+				Content:    result,
228
+				EventType:  enums.EventTypeQrCode,
229
+			})
230
+			if err != nil {
231
+				c.ServeDynamicFailJsonSend(fmt.Sprintf("CreateDeviceMessageLog err:%v", err))
232
+				return
233
+			}
234
+			if len(checkItems) < count {
235
+				c.ServeDynamicFailJsonSend("接收的数据与检查项目配置不一致")
236
+				return
237
+			}
238
+			checkRecord := &models.CheckRecord{
239
+				Acc:          acc,
240
+				PutSources:   enums.EventTypeQrCode,
241
+				DeviceId:     device.Id,
242
+				UserId:       dr.UserId,
243
+				DeviceStatus: device.Status,
244
+				Ctime:        time.Now(),
245
+			}
246
+			if dr.UserId > 0 {
247
+
248
+				hp, err := service.NewUserHealthProfileService().GetUserHealthProfileByUserId(dr.UserId)
249
+				if err != nil {
250
+					c.ServeDynamicFailJsonSend(fmt.Sprintf("GetUserHealthProfileByUserId err:%v", err))
251
+					return
252
+				}
253
+				checkRecord.UserHealthProfileId = int64(hp.Id)
254
+			}
255
+			err = crs.CreateCheckRecord(checkRecord)
256
+			if err != nil {
257
+				c.ServeDynamicFailJsonSend(fmt.Sprintf("CreateCheckRecord err:%v", err))
258
+				return
259
+			}
260
+			alerts := make([]string, 0)
261
+			for i := 0; i < count; i++ {
262
+				vi, _ := strconv.Atoi(da[i])
263
+				err = createCheckRecordItem(checkItems, checkRecord.Id, &alerts, vi, i+1, crs)
264
+				if err != nil {
265
+					utils.ErrorLog("createCheckRecordItem valule:%v, err:%v:", vi, err)
266
+				}
267
+			}
268
+
269
+			if len(alerts) > 0 {
270
+				alertItemIds := strings.Join(alerts, ",")
271
+				err = crs.UpdateCheckRecordAlertItems(checkRecord.Id, alertItemIds)
272
+				if err != nil {
273
+					c.ServeDynamicFailJsonSend(fmt.Sprintf("UpdateCheckRecordAlertItems err:%v", err))
274
+					return
275
+				}
276
+
277
+			} else {
278
+				utils.TraceLog("无异常数据")
279
+			}
280
+			record = *checkRecord
281
+		}
282
+
283
+		recordItems, err := crs.GetCheckRecordItems(record.Id)
284
+		if err != nil {
285
+			c.ServeDynamicFailJsonSend(fmt.Sprintf("GetCheckRecordItems err:%v", err))
286
+			return
287
+		}
288
+		checkRecordItem, err := analyzeCheckRecord(recordItems, checkItems)
289
+		if err != nil {
290
+			c.ServeDynamicFailJsonSend(fmt.Sprintf("analyzeCheckRecord err:%v", err))
291
+			return
292
+		}
293
+		checkRecordItem.Status = status
294
+		checkRecordItem.CheckDate = record.Ctime
295
+		checkRecordItem.UserID = int64(record.UserId)
296
+		checkRecordItem.Bind = checkRecordItem.UserID > 0
297
+		checkRecordItem.CheckRecordID = record.Id
298
+
299
+		c.ServeSuccessJSON(checkRecordItem)
300
+
301
+	}
302
+}
303
+func analyzeCheckRecord(ritems []*models.CheckRecordItem, citems []*models.CheckItem) (models.AppCheckRecordItemVO, error) {
304
+	var result models.AppCheckRecordItemVO
305
+	var details []models.AppCheckRecordItemDetailsVO
306
+
307
+	for _, ri := range ritems {
308
+		detail := models.AppCheckRecordItemDetailsVO{}
309
+		item := findItem(citems, ri.CheckItemId)
310
+		if item == nil {
311
+			continue
312
+		}
313
+		if ri.CheckValue != "" && item.ScopeList != "" {
314
+			var scopes []*models.CheckItemScopeVO
315
+			err := json.Unmarshal([]byte(item.ScopeList), &scopes)
316
+			if err != nil {
317
+				return result, err
318
+			}
319
+			for _, scope := range scopes {
320
+				if ri.CheckValueIndex == scope.Index {
321
+					if scope.Type == 1 {
322
+						result.NormalCount += 1
323
+						detail.Alert = false
324
+
325
+					} else {
326
+						result.AlertCount += 1
327
+						detail.Alert = true
328
+					}
329
+					detail.ValueIndex = strconv.Itoa(ri.CheckValueIndex)
330
+					detail.ID = item.Id
331
+					detail.Value = scope.Value
332
+					detail.NameCn = item.NameCn
333
+					detail.NameEn = item.NameEn
334
+					detail.ReferenceValue = item.ReferenceValue
335
+					//detail.Describe = item.Details
336
+					detail.Unit = item.Unit
337
+					details = append(details, detail)
338
+					break
339
+				}
340
+			}
341
+			result.Items = details
342
+			if result.AlertCount > 1 {
343
+				result.AlertGrade = enums.AlertGradeHIGH
344
+			} else if result.AlertCount == 1 {
345
+				result.AlertGrade = enums.AlertGradeMEDIUM
346
+
347
+			} else {
348
+				result.AlertGrade = enums.AlertGradeNORMAL
349
+			}
350
+			result.Describe = enums.AlertGradeMap[result.AlertGrade]
351
+		}
352
+	}
353
+
354
+	return result, nil
355
+}
356
+
357
+func formatNumber(num int64, width int) string {
358
+	format := fmt.Sprintf("%%0%dd", width)
359
+	return fmt.Sprintf(format, num)
360
+}
361
+
362
+func getUint8(val int) uint8 {
363
+	return uint8(val & 0xFF)
364
+}
365
+
366
+func indexDigits(ch rune) int {
367
+	for i, digit := range DIGITS {
368
+		if ch == digit {
369
+			return i
370
+		}
371
+	}
372
+	return -1
373
+}
374
+
375
+func radixString(str string) int64 {
376
+	sum := int64(0)
377
+	len := len(str)
378
+
379
+	for i := 0; i < len; i++ {
380
+		index := indexDigits(rune(str[len-i-1]))
381
+		sum += int64(index) * int64(math.Pow(64, float64(i)))
382
+	}
20 383
 
384
+	return sum
21 385
 }

+ 22 - 1
controllers/device_api_controllor.go Dosyayı Görüntüle

@@ -1,6 +1,7 @@
1 1
 package controllers
2 2
 
3 3
 import (
4
+	"sws_xcx/enums"
4 5
 	"sws_xcx/service"
5 6
 	"sws_xcx/utils"
6 7
 )
@@ -50,7 +51,7 @@ func (c *DeviceApiController) GetDeviceDetail() {
50 51
 }
51 52
 
52 53
 // @Title BindDevice
53
-// @Description 绑定设备
54
+// @Description 通过扫码绑定设备
54 55
 // @Param   qrcode query string true "设备二维码"
55 56
 // @Success 200  success
56 57
 // @Failure 500 error
@@ -65,6 +66,26 @@ func (c *DeviceApiController) BindDevice() {
65 66
 	c.ServeSuccessJSON(new(interface{}))
66 67
 }
67 68
 
69
+// @Title BindDevice
70
+// @Description 通过设备ID绑定设备
71
+// @Param   deviceId query string true "设备ID"
72
+// @Success 200  success
73
+// @Failure 500 error
74
+// @Security token
75
+// @router /binddevicebyid [post]
76
+func (c *DeviceApiController) BindDeviceById() {
77
+	deviceId, err := c.GetUint64("deviceId")
78
+	if err != nil || deviceId == 0 {
79
+		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamFormatWrong)
80
+		return
81
+	}
82
+	if err := service.NewDeviceService().BindDeviceById(c.CurrentUser.Id, deviceId); err != nil {
83
+		c.ServeDynamicFailJsonSend(err.Error())
84
+		return
85
+	}
86
+	c.ServeSuccessJSON(new(interface{}))
87
+}
88
+
68 89
 // @Title UnBindDevice
69 90
 // @Description 解绑设备
70 91
 // @Param   deviceid query int true "设备ID"

+ 1 - 1
controllers/message_api_controllor.go Dosyayı Görüntüle

@@ -116,7 +116,7 @@ func (c *MessageApiControllor) PutEmqxMessage() {
116 116
 	}
117 117
 
118 118
 	if len(checkItems) < count {
119
-		c.ServeDynamicFailJsonSend("接收的数据检查项目配置不一致")
119
+		c.ServeDynamicFailJsonSend("接收的数据检查项目配置不一致")
120 120
 		return
121 121
 	}
122 122
 

+ 6 - 1
controllers/user_api_controller.go Dosyayı Görüntüle

@@ -39,6 +39,11 @@ func (c *UserApiController) GetUserInfo() {
39 39
 		PatientId:               c.CurrentUser.PatientId,
40 40
 	}
41 41
 
42
+	patient, _ := service.NewXcxUserService().GetPatientInfo(c.CurrentUser.PatientId)
43
+
44
+	resp.DialysisNo = patient.DialysisNo
45
+	resp.HealthCareNo = patient.HealthCareNo
46
+
42 47
 	p, err := service.NewUserHealthProfileService().GetUserHealthProfileByUserId(c.CurrentUser.Id)
43 48
 	if err != nil {
44 49
 		c.ServeDynamicFailJsonSend(err.Error())
@@ -108,7 +113,7 @@ func (c *UserApiController) SaveUserInfo() {
108 113
 		return
109 114
 	}
110 115
 
111
-	p, err1 := service.NewXcxUserService().GetMobilePatientInfo(req.Phone, req.RealName, req.IdCard)
116
+	p, err1 := service.NewXcxUserService().GetMobilePatientInfo(req.InpatientRegPhone, req.RealName, req.IdCard)
112 117
 
113 118
 	err := c.updateCurrentUser(func(u *models.XcxUser) {
114 119
 		u.Avatar = req.Avatar

+ 12 - 0
enums/enums.go Dosyayı Görüntüle

@@ -4,3 +4,15 @@ const (
4 4
 	EventTypeEmqx   = "emq"
5 5
 	EventTypeQrCode = "device_qr_code"
6 6
 )
7
+
8
+const (
9
+	AlertGradeNORMAL = 1
10
+	AlertGradeMEDIUM = 2
11
+	AlertGradeHIGH   = 3
12
+)
13
+
14
+var AlertGradeMap = map[int]string{
15
+	AlertGradeNORMAL: "您的身体状态良好,请继续保持良好的生活习惯,注意劳逸结合、合理饮食,保持健康睡眠和适量运动,促进身体循环代谢,精神旺盛,请您继续努力保持",
16
+	AlertGradeMEDIUM: "您的身体状况有所下降,若身体不适感明显,建议您前往附近医疗机构进行临床检查和诊断。请您持续关注身体健康,1日后再次检查",
17
+	AlertGradeHIGH:   "您的身体存在疾病隐患,多项指标出现异常,建议您尽快前往附近医疗机构进行临床检查和诊断。请您持续关注身体健康,1日后再次检查",
18
+}

+ 40 - 0
models/httpmodels.go Dosyayı Görüntüle

@@ -74,6 +74,9 @@ type UserInfoResp struct {
74 74
 	PatientId int64 ` json:"patient_id"`
75 75
 	UserOrgId int64 ` json:"user_org_id"`
76 76
 
77
+	DialysisNo   string `gorm:"column:dialysis_no" json:"dialysis_no" description:" 透析号"`
78
+	HealthCareNo string `gorm:"column:health_care_no" json:"health_care_no" description:" 医保号"`
79
+
77 80
 	Ctime Time `json:"ctime" description:"创建时间"`
78 81
 	Mtime Time `json:"mtime" description:"更新时间 "`
79 82
 }
@@ -190,3 +193,40 @@ type AppCheckRecordVO struct {
190 193
 	// AlertItems is a list of alert items.
191 194
 	AlertItems []string `json:"alert_items" description:"异常项"`
192 195
 }
196
+
197
+// AppCheckRecordItemDetailsVO 结构体表示检测记录项的详细信息
198
+type AppCheckRecordItemDetailsVO struct {
199
+	NameCn          string             `json:"name_cn" description:"中文名字"`
200
+	NameEn          string             `json:"name_en" description:"英文名字"`
201
+	Unit            string             `json:"unit" description:"单位"`
202
+	Value           string             `json:"value" description:"检测值"`
203
+	ValueIndex      string             `json:"value_index" description:"检测值索引"`
204
+	CheckItemScopes []CheckItemScopeVO `json:"check_item_scopes" description:"检测范围"`
205
+	ReferenceValue  string             `json:"reference_value" description:"参考值"`
206
+	Describe        string             `json:"describe" description:"描述"`
207
+	Alert           bool               `json:"alert" description:"true:异常,false:正常"`
208
+	ID              int                `json:"id" description:"id"`
209
+}
210
+
211
+// AppCheckRecordItemVO 结构体表示检测记录项
212
+type AppCheckRecordItemVO struct {
213
+	AlertCount    int                           `json:"alert_count" description:"异常数量"`
214
+	NormalCount   int                           `json:"normal_count" description:"正常数量"`
215
+	Describe      string                        `json:"describe" description:"描述"`
216
+	CheckDate     time.Time                     `json:"check_date" description:"检测日期"`
217
+	CheckRecordID int64                         `json:"check_record_id" description:"检测记录id"`
218
+	UserID        int64                         `json:"user_id" description:"绑定用户id 默认自己"`
219
+	AlertGrade    int                           `json:"alert_grade" description:"风险等级 1 低  2 中 3 高"`
220
+	Bind          bool                          `json:"bind" description:"false 未绑定用户 true 绑定"`
221
+	Items         []AppCheckRecordItemDetailsVO `json:"items" description:"检测详情"`
222
+	Status        int                           `json:"status" description:"设备绑定状态(扫码查看结果时返回):1 未绑定 2设备为他人绑定 3设备为自己绑定"`
223
+}
224
+
225
+type AppCheckRecordItemReportVO struct {
226
+	Unit            string `json:"unit" description:"单位"`
227
+	Value           string `json:"value" description:"检测值"`
228
+	CheckValueIndex int    `json:"check_value_index" description:"检测值下标"`
229
+	Describe        string `json:"describe" description:"描述"`
230
+	ID              int    `json:"id" description:"id"`
231
+	Date            Time   `json:"date" description:"检测时间"`
232
+}

+ 4 - 0
routers/router.go Dosyayı Görüntüle

@@ -39,6 +39,10 @@ func init() {
39 39
 				beego.NSInclude(
40 40
 					&controllers.SysDicApiController{},
41 41
 				)),
42
+			beego.NSNamespace("/api/checkrecord",
43
+				beego.NSInclude(
44
+					&controllers.CheckRecordApiController{},
45
+				)),
42 46
 		)
43 47
 	beego.AddNamespace(ns)
44 48
 	controllers.ApiControllersRegisterRouters()

+ 21 - 0
service/checkrecordservice.go Dosyayı Görüntüle

@@ -21,6 +21,16 @@ func NewCheckRecordService() *CheckRecordService {
21 21
 	}
22 22
 }
23 23
 
24
+func (s *CheckRecordService) GetCheckRecordByAcc(deviceId uint64, acc int) (record models.CheckRecord, err error) {
25
+	record = models.CheckRecord{}
26
+	err = s.rdb.Model(&record).Where("device_id = ? and acc = ?", deviceId, acc).First(&record).Error
27
+	if err != nil && err == gorm.ErrRecordNotFound {
28
+		err = nil
29
+	}
30
+
31
+	return
32
+}
33
+
24 34
 func (s *CheckRecordService) GetCheckRecordList(pageNum, pageSize int, userid uint64) (vos []models.AppCheckRecordVO, total int, err error) {
25 35
 	offset := (pageNum - 1) * pageSize
26 36
 	records := make([]*models.CheckRecord, pageSize)
@@ -84,3 +94,14 @@ func (s *CheckRecordService) CreateCheckRecordItem(checkRecordItem *models.Check
84 94
 func (s *CheckRecordService) UpdateCheckRecordAlertItems(id int64, alertItemIds string) error {
85 95
 	return s.wdb.Model(&models.CheckRecord{}).Where("id = ?", id).Update("alert_item_ids", alertItemIds).Error
86 96
 }
97
+
98
+func (s *CheckRecordService) GetCheckRecordItems(recordId int64) (recordItems []*models.CheckRecordItem, err error) {
99
+	err = s.rdb.Model(&models.CheckRecordItem{}).Where("check_id = ?", recordId).Find(&recordItems).Error
100
+	return
101
+}
102
+
103
+func (s *CheckRecordService) GetCheckRecordById(id int64) (record models.CheckRecord, err error) {
104
+
105
+	err = s.rdb.Model(&record).Where("id = ?", id).First(&record).Error
106
+	return
107
+}

+ 57 - 1
service/deviceservice.go Dosyayı Görüntüle

@@ -28,6 +28,22 @@ func (s *DeviceService) GetDeviceInfo(id int) (models.Device, error) {
28 28
 	return device, err
29 29
 }
30 30
 
31
+// func (s *DeviceService) GetDeviceBind(deviceId uint64, userId uint64) (models.DeviceRelate, error) {
32
+// 	var device_relate models.DeviceRelate
33
+// 	db := s.rdb.Model(&device_relate)
34
+// 	if deviceId > 0 {
35
+// 		db = db.Where("device_id = ?", deviceId)
36
+// 	}
37
+// 	if userId > 0 {
38
+// 		db = db.Where("user_id = ?", userId)
39
+// 	}
40
+// 	err := db.First(&device_relate).Error
41
+// 	if err == nil || err == gorm.ErrRecordNotFound {
42
+// 		err = nil
43
+// 	}
44
+// 	return device_relate, err
45
+// }
46
+
31 47
 func (s *DeviceService) GetDeviceByNo(serialno string) (models.Device, error) {
32 48
 	var device models.Device
33 49
 	err := s.rdb.Model(&device).Where("serialno = ?", serialno).First(&device).Error
@@ -75,7 +91,47 @@ func (s *DeviceService) BindDevice(userId uint64, qrcode string) error {
75 91
 		if dr.DeleteFlag == 0 {
76 92
 			return errors.New("该设备已绑定其他用户")
77 93
 		} else { //其他用户解绑了设备
78
-			return s.wdb.Model(dr).Update("delete_flag", 0, "user_id", userId).Error
94
+			return s.wdb.Model(dr).Updates(map[string]interface{}{"delete_flag": 0, "user_id": userId}).Error
95
+		}
96
+	} else if dr.DeleteFlag == 1 { //直接解绑了该设备 重新绑定
97
+
98
+		return s.wdb.Model(dr).Update("delete_flag", 0).Error
99
+
100
+	} else {
101
+		return errors.New("设备已绑定")
102
+	}
103
+
104
+}
105
+
106
+func (s *DeviceService) BindDeviceById(userId, deviceId uint64) error {
107
+	var device models.Device
108
+	err := s.rdb.Model(&device).Where("id= ?  and delete_flag =0", deviceId).First(&device).Error
109
+	if err != nil {
110
+		if err == gorm.ErrRecordNotFound {
111
+			return errors.New("设备不存在")
112
+		}
113
+		return err
114
+	}
115
+	dr := &models.DeviceRelate{}
116
+	err = s.rdb.Model(dr).Where("device_id = ?", device.Id).First(dr).Error
117
+	if err != nil {
118
+		if err == gorm.ErrRecordNotFound {
119
+			dr = &models.DeviceRelate{
120
+				UserId:   userId,
121
+				DeviceId: device.Id,
122
+				Name:     device.DeviceName,
123
+			}
124
+
125
+			return s.wdb.Model(dr).Create(dr).Error
126
+		}
127
+		return err
128
+	}
129
+
130
+	if dr.UserId != userId {
131
+		if dr.DeleteFlag == 0 {
132
+			return errors.New("该设备已绑定其他用户")
133
+		} else { //其他用户解绑了设备
134
+			return s.wdb.Model(dr).Updates(map[string]interface{}{"delete_flag": 0, "user_id": userId}).Error
79 135
 		}
80 136
 	} else if dr.DeleteFlag == 1 { //直接解绑了该设备 重新绑定
81 137
 

+ 10 - 0
service/userservice.go Dosyayı Görüntüle

@@ -57,3 +57,13 @@ func (s *XcxUserService) GetMobilePatientInfo(mobile, name, idCard string) (mode
57 57
 	}
58 58
 	return patients, err
59 59
 }
60
+
61
+func (s *XcxUserService) GetPatientInfo(id int64) (models.XcxPatients, error) {
62
+
63
+	patients := models.XcxPatients{}
64
+	err := ReadXtDB().Model(&patients).Find(&patients, id).Error
65
+	if err == gorm.ErrRecordNotFound {
66
+		err = nil
67
+	}
68
+	return patients, err
69
+}

+ 333 - 1
swagger/swagger.json Dosyayı Görüntüle

@@ -11,12 +11,128 @@
11 11
     },
12 12
     "basePath": "/xcx",
13 13
     "paths": {
14
+        "/api/checkrecord/getcheckrecorditembyid": {
15
+            "get": {
16
+                "tags": [
17
+                    "api/checkrecord"
18
+                ],
19
+                "description": "通过检测ID查看检测结果\n\u003cbr\u003e",
20
+                "operationId": "CheckRecordApiController.GetCheckRecordItemById",
21
+                "parameters": [
22
+                    {
23
+                        "in": "query",
24
+                        "name": "checkid",
25
+                        "description": "检测ID",
26
+                        "required": true,
27
+                        "type": "integer",
28
+                        "format": "int64"
29
+                    }
30
+                ],
31
+                "responses": {
32
+                    "200": {
33
+                        "description": "success",
34
+                        "schema": {
35
+                            "$ref": "#/definitions/models.AppCheckRecordItemVO"
36
+                        }
37
+                    },
38
+                    "500": {
39
+                        "description": "error"
40
+                    }
41
+                },
42
+                "security": [
43
+                    {
44
+                        "token": []
45
+                    }
46
+                ]
47
+            }
48
+        },
49
+        "/api/checkrecord/getcheckrecordlist": {
50
+            "get": {
51
+                "tags": [
52
+                    "api/checkrecord"
53
+                ],
54
+                "description": "分页获取检测记录\n\u003cbr\u003e",
55
+                "operationId": "CheckRecordApiController.GetCheckRecordList",
56
+                "parameters": [
57
+                    {
58
+                        "in": "query",
59
+                        "name": "pageNum",
60
+                        "description": "当前页(从1开始)",
61
+                        "required": true,
62
+                        "type": "integer",
63
+                        "format": "int64"
64
+                    },
65
+                    {
66
+                        "in": "query",
67
+                        "name": "pageSize",
68
+                        "description": "分页大小",
69
+                        "required": true,
70
+                        "type": "integer",
71
+                        "format": "int64"
72
+                    }
73
+                ],
74
+                "responses": {
75
+                    "200": {
76
+                        "description": "success",
77
+                        "schema": {
78
+                            "type": "array",
79
+                            "items": {
80
+                                "$ref": "#/definitions/models.AppCheckRecordVO"
81
+                            }
82
+                        }
83
+                    },
84
+                    "500": {
85
+                        "description": "error"
86
+                    }
87
+                },
88
+                "security": [
89
+                    {
90
+                        "token": []
91
+                    }
92
+                ]
93
+            }
94
+        },
95
+        "/api/checkrecord/qrcodecheckrecord": {
96
+            "get": {
97
+                "tags": [
98
+                    "api/checkrecord"
99
+                ],
100
+                "description": "通过扫描二维码查看检测结果\n\u003cbr\u003e",
101
+                "operationId": "CheckRecordApiController.QrCodeCheckRecord",
102
+                "parameters": [
103
+                    {
104
+                        "in": "query",
105
+                        "name": "qrcode",
106
+                        "description": "扫描二维码的内容",
107
+                        "required": true,
108
+                        "type": "integer",
109
+                        "format": "int64"
110
+                    }
111
+                ],
112
+                "responses": {
113
+                    "200": {
114
+                        "description": "success",
115
+                        "schema": {
116
+                            "$ref": "#/definitions/models.AppCheckRecordItemVO"
117
+                        }
118
+                    },
119
+                    "500": {
120
+                        "description": "error"
121
+                    }
122
+                },
123
+                "security": [
124
+                    {
125
+                        "token": []
126
+                    }
127
+                ]
128
+            }
129
+        },
14 130
         "/api/device/binddevice": {
15 131
             "post": {
16 132
                 "tags": [
17 133
                     "api/device"
18 134
                 ],
19
-                "description": "绑定设备\n\u003cbr\u003e",
135
+                "description": "通过扫码绑定设备\n\u003cbr\u003e",
20 136
                 "operationId": "DeviceApiController.BindDevice",
21 137
                 "parameters": [
22 138
                     {
@@ -42,6 +158,37 @@
42 158
                 ]
43 159
             }
44 160
         },
161
+        "/api/device/binddevicebyid": {
162
+            "post": {
163
+                "tags": [
164
+                    "api/device"
165
+                ],
166
+                "description": "通过设备ID绑定设备\n\u003cbr\u003e",
167
+                "operationId": "DeviceApiController.BindDevice",
168
+                "parameters": [
169
+                    {
170
+                        "in": "query",
171
+                        "name": "deviceId",
172
+                        "description": "设备ID",
173
+                        "required": true,
174
+                        "type": "string"
175
+                    }
176
+                ],
177
+                "responses": {
178
+                    "200": {
179
+                        "description": "success"
180
+                    },
181
+                    "500": {
182
+                        "description": "error"
183
+                    }
184
+                },
185
+                "security": [
186
+                    {
187
+                        "token": []
188
+                    }
189
+                ]
190
+            }
191
+        },
45 192
         "/api/device/getdevicedetail": {
46 193
             "get": {
47 194
                 "tags": [
@@ -414,6 +561,163 @@
414 561
         }
415 562
     },
416 563
     "definitions": {
564
+        "models.AppCheckRecordItemDetailsVO": {
565
+            "title": "AppCheckRecordItemDetailsVO",
566
+            "type": "object",
567
+            "properties": {
568
+                "alert": {
569
+                    "description": "true:异常,false:正常",
570
+                    "type": "boolean"
571
+                },
572
+                "check_item_scopes": {
573
+                    "description": "检测范围",
574
+                    "type": "array",
575
+                    "items": {
576
+                        "$ref": "#/definitions/models.CheckItemScopeVO"
577
+                    }
578
+                },
579
+                "describe": {
580
+                    "description": "描述",
581
+                    "type": "string"
582
+                },
583
+                "id": {
584
+                    "description": "id",
585
+                    "type": "integer",
586
+                    "format": "int64"
587
+                },
588
+                "name_cn": {
589
+                    "description": "中文名字",
590
+                    "type": "string"
591
+                },
592
+                "name_en": {
593
+                    "description": "英文名字",
594
+                    "type": "string"
595
+                },
596
+                "reference_value": {
597
+                    "description": "参考值",
598
+                    "type": "string"
599
+                },
600
+                "unit": {
601
+                    "description": "单位",
602
+                    "type": "string"
603
+                },
604
+                "value": {
605
+                    "description": "检测值",
606
+                    "type": "string"
607
+                },
608
+                "value_index": {
609
+                    "description": "检测值索引",
610
+                    "type": "string"
611
+                }
612
+            }
613
+        },
614
+        "models.AppCheckRecordItemVO": {
615
+            "title": "AppCheckRecordItemVO",
616
+            "type": "object",
617
+            "properties": {
618
+                "alert_count": {
619
+                    "description": "异常数量",
620
+                    "type": "integer",
621
+                    "format": "int64"
622
+                },
623
+                "alert_grade": {
624
+                    "description": "风险等级 1 低  2 中 3 高",
625
+                    "type": "integer",
626
+                    "format": "int64"
627
+                },
628
+                "bind": {
629
+                    "description": "false 未绑定用户 true 绑定",
630
+                    "type": "boolean"
631
+                },
632
+                "check_date": {
633
+                    "description": "检测日期",
634
+                    "type": "string",
635
+                    "format": "datetime"
636
+                },
637
+                "check_record_id": {
638
+                    "description": "检测记录id",
639
+                    "type": "integer",
640
+                    "format": "int64"
641
+                },
642
+                "describe": {
643
+                    "description": "描述",
644
+                    "type": "string"
645
+                },
646
+                "items": {
647
+                    "description": "检测详情",
648
+                    "type": "array",
649
+                    "items": {
650
+                        "$ref": "#/definitions/models.AppCheckRecordItemDetailsVO"
651
+                    }
652
+                },
653
+                "normal_count": {
654
+                    "description": "正常数量",
655
+                    "type": "integer",
656
+                    "format": "int64"
657
+                },
658
+                "status": {
659
+                    "description": "设备绑定状态(扫码查看结果时返回):1 未绑定 2设备为他人绑定 3设备为自己绑定",
660
+                    "type": "integer",
661
+                    "format": "int64"
662
+                },
663
+                "user_id": {
664
+                    "description": "绑定用户id 默认自己",
665
+                    "type": "integer",
666
+                    "format": "int64"
667
+                }
668
+            }
669
+        },
670
+        "models.AppCheckRecordVO": {
671
+            "title": "AppCheckRecordVO",
672
+            "type": "object",
673
+            "properties": {
674
+                "alert_count": {
675
+                    "description": "异常数量",
676
+                    "type": "integer",
677
+                    "format": "int64"
678
+                },
679
+                "alert_items": {
680
+                    "description": "异常项",
681
+                    "type": "array",
682
+                    "items": {
683
+                        "type": "string"
684
+                    }
685
+                },
686
+                "bind": {
687
+                    "description": "0 未绑定用户 1 绑定",
688
+                    "type": "integer",
689
+                    "format": "int64"
690
+                },
691
+                "check_date": {
692
+                    "$ref": "#/definitions/models.Time",
693
+                    "description": "检测日期"
694
+                },
695
+                "check_record_id": {
696
+                    "description": "检测记录id",
697
+                    "type": "integer",
698
+                    "format": "int64"
699
+                },
700
+                "describe": {
701
+                    "description": "描述",
702
+                    "type": "string"
703
+                },
704
+                "normal_count": {
705
+                    "description": "正常数量",
706
+                    "type": "integer",
707
+                    "format": "int64"
708
+                },
709
+                "user_id": {
710
+                    "description": "绑定用户id 默认自己",
711
+                    "type": "integer",
712
+                    "format": "int64"
713
+                },
714
+                "view": {
715
+                    "description": "是否查看 1 已查看 0 未查看",
716
+                    "type": "integer",
717
+                    "format": "int64"
718
+                }
719
+            }
720
+        },
417 721
         "models.CheckItem": {
418 722
             "title": "CheckItem",
419 723
             "type": "object",
@@ -489,6 +793,26 @@
489 793
                 }
490 794
             }
491 795
         },
796
+        "models.CheckItemScopeVO": {
797
+            "title": "CheckItemScopeVO",
798
+            "type": "object",
799
+            "properties": {
800
+                "index": {
801
+                    "type": "integer",
802
+                    "format": "int64"
803
+                },
804
+                "num": {
805
+                    "type": "string"
806
+                },
807
+                "type": {
808
+                    "type": "integer",
809
+                    "format": "int64"
810
+                },
811
+                "value": {
812
+                    "type": "string"
813
+                }
814
+            }
815
+        },
492 816
         "models.Device": {
493 817
             "title": "Device",
494 818
             "type": "object",
@@ -839,10 +1163,18 @@
839 1163
                     "$ref": "#/definitions/models.Time",
840 1164
                     "description": "创建时间"
841 1165
                 },
1166
+                "dialysis_no": {
1167
+                    "description": " 透析号",
1168
+                    "type": "string"
1169
+                },
842 1170
                 "email": {
843 1171
                     "description": "邮件",
844 1172
                     "type": "string"
845 1173
                 },
1174
+                "health_care_no": {
1175
+                    "description": " 医保号",
1176
+                    "type": "string"
1177
+                },
846 1178
                 "id": {
847 1179
                     "description": "Primary Key ID",
848 1180
                     "type": "integer",

+ 241 - 1
swagger/swagger.yml Dosyayı Görüntüle

@@ -8,12 +8,92 @@ info:
8 8
     name: 领透科技
9 9
 basePath: /xcx
10 10
 paths:
11
+  /api/checkrecord/getcheckrecorditembyid:
12
+    get:
13
+      tags:
14
+      - api/checkrecord
15
+      description: |-
16
+        通过检测ID查看检测结果
17
+        <br>
18
+      operationId: CheckRecordApiController.GetCheckRecordItemById
19
+      parameters:
20
+      - in: query
21
+        name: checkid
22
+        description: 检测ID
23
+        required: true
24
+        type: integer
25
+        format: int64
26
+      responses:
27
+        "200":
28
+          description: success
29
+          schema:
30
+            $ref: '#/definitions/models.AppCheckRecordItemVO'
31
+        "500":
32
+          description: error
33
+      security:
34
+      - token: []
35
+  /api/checkrecord/getcheckrecordlist:
36
+    get:
37
+      tags:
38
+      - api/checkrecord
39
+      description: |-
40
+        分页获取检测记录
41
+        <br>
42
+      operationId: CheckRecordApiController.GetCheckRecordList
43
+      parameters:
44
+      - in: query
45
+        name: pageNum
46
+        description: 当前页(从1开始)
47
+        required: true
48
+        type: integer
49
+        format: int64
50
+      - in: query
51
+        name: pageSize
52
+        description: 分页大小
53
+        required: true
54
+        type: integer
55
+        format: int64
56
+      responses:
57
+        "200":
58
+          description: success
59
+          schema:
60
+            type: array
61
+            items:
62
+              $ref: '#/definitions/models.AppCheckRecordVO'
63
+        "500":
64
+          description: error
65
+      security:
66
+      - token: []
67
+  /api/checkrecord/qrcodecheckrecord:
68
+    get:
69
+      tags:
70
+      - api/checkrecord
71
+      description: |-
72
+        通过扫描二维码查看检测结果
73
+        <br>
74
+      operationId: CheckRecordApiController.QrCodeCheckRecord
75
+      parameters:
76
+      - in: query
77
+        name: qrcode
78
+        description: 扫描二维码的内容
79
+        required: true
80
+        type: integer
81
+        format: int64
82
+      responses:
83
+        "200":
84
+          description: success
85
+          schema:
86
+            $ref: '#/definitions/models.AppCheckRecordItemVO'
87
+        "500":
88
+          description: error
89
+      security:
90
+      - token: []
11 91
   /api/device/binddevice:
12 92
     post:
13 93
       tags:
14 94
       - api/device
15 95
       description: |-
16
-        绑定设备
96
+        通过扫码绑定设备
17 97
         <br>
18 98
       operationId: DeviceApiController.BindDevice
19 99
       parameters:
@@ -29,6 +109,27 @@ paths:
29 109
           description: error
30 110
       security:
31 111
       - token: []
112
+  /api/device/binddevicebyid:
113
+    post:
114
+      tags:
115
+      - api/device
116
+      description: |-
117
+        通过设备ID绑定设备
118
+        <br>
119
+      operationId: DeviceApiController.BindDevice
120
+      parameters:
121
+      - in: query
122
+        name: deviceId
123
+        description: 设备ID
124
+        required: true
125
+        type: string
126
+      responses:
127
+        "200":
128
+          description: success
129
+        "500":
130
+          description: error
131
+      security:
132
+      - token: []
32 133
   /api/device/getdevicedetail:
33 134
     get:
34 135
       tags:
@@ -287,6 +388,125 @@ paths:
287 388
       security:
288 389
       - token: []
289 390
 definitions:
391
+  models.AppCheckRecordItemDetailsVO:
392
+    title: AppCheckRecordItemDetailsVO
393
+    type: object
394
+    properties:
395
+      alert:
396
+        description: true:异常,false:正常
397
+        type: boolean
398
+      check_item_scopes:
399
+        description: 检测范围
400
+        type: array
401
+        items:
402
+          $ref: '#/definitions/models.CheckItemScopeVO'
403
+      describe:
404
+        description: 描述
405
+        type: string
406
+      id:
407
+        description: id
408
+        type: integer
409
+        format: int64
410
+      name_cn:
411
+        description: 中文名字
412
+        type: string
413
+      name_en:
414
+        description: 英文名字
415
+        type: string
416
+      reference_value:
417
+        description: 参考值
418
+        type: string
419
+      unit:
420
+        description: 单位
421
+        type: string
422
+      value:
423
+        description: 检测值
424
+        type: string
425
+      value_index:
426
+        description: 检测值索引
427
+        type: string
428
+  models.AppCheckRecordItemVO:
429
+    title: AppCheckRecordItemVO
430
+    type: object
431
+    properties:
432
+      alert_count:
433
+        description: 异常数量
434
+        type: integer
435
+        format: int64
436
+      alert_grade:
437
+        description: 风险等级 1 低  2 中 3 高
438
+        type: integer
439
+        format: int64
440
+      bind:
441
+        description: false 未绑定用户 true 绑定
442
+        type: boolean
443
+      check_date:
444
+        description: 检测日期
445
+        type: string
446
+        format: datetime
447
+      check_record_id:
448
+        description: 检测记录id
449
+        type: integer
450
+        format: int64
451
+      describe:
452
+        description: 描述
453
+        type: string
454
+      items:
455
+        description: 检测详情
456
+        type: array
457
+        items:
458
+          $ref: '#/definitions/models.AppCheckRecordItemDetailsVO'
459
+      normal_count:
460
+        description: 正常数量
461
+        type: integer
462
+        format: int64
463
+      status:
464
+        description: 设备绑定状态(扫码查看结果时返回):1 未绑定 2设备为他人绑定 3设备为自己绑定
465
+        type: integer
466
+        format: int64
467
+      user_id:
468
+        description: 绑定用户id 默认自己
469
+        type: integer
470
+        format: int64
471
+  models.AppCheckRecordVO:
472
+    title: AppCheckRecordVO
473
+    type: object
474
+    properties:
475
+      alert_count:
476
+        description: 异常数量
477
+        type: integer
478
+        format: int64
479
+      alert_items:
480
+        description: 异常项
481
+        type: array
482
+        items:
483
+          type: string
484
+      bind:
485
+        description: 0 未绑定用户 1 绑定
486
+        type: integer
487
+        format: int64
488
+      check_date:
489
+        $ref: '#/definitions/models.Time'
490
+        description: 检测日期
491
+      check_record_id:
492
+        description: 检测记录id
493
+        type: integer
494
+        format: int64
495
+      describe:
496
+        description: 描述
497
+        type: string
498
+      normal_count:
499
+        description: 正常数量
500
+        type: integer
501
+        format: int64
502
+      user_id:
503
+        description: 绑定用户id 默认自己
504
+        type: integer
505
+        format: int64
506
+      view:
507
+        description: 是否查看 1 已查看 0 未查看
508
+        type: integer
509
+        format: int64
290 510
   models.CheckItem:
291 511
     title: CheckItem
292 512
     type: object
@@ -344,6 +564,20 @@ definitions:
344 564
       unit:
345 565
         description: 单位
346 566
         type: string
567
+  models.CheckItemScopeVO:
568
+    title: CheckItemScopeVO
569
+    type: object
570
+    properties:
571
+      index:
572
+        type: integer
573
+        format: int64
574
+      num:
575
+        type: string
576
+      type:
577
+        type: integer
578
+        format: int64
579
+      value:
580
+        type: string
347 581
   models.Device:
348 582
     title: Device
349 583
     type: object
@@ -611,9 +845,15 @@ definitions:
611 845
       ctime:
612 846
         $ref: '#/definitions/models.Time'
613 847
         description: 创建时间
848
+      dialysis_no:
849
+        description: ' 透析号'
850
+        type: string
614 851
       email:
615 852
         description: 邮件
616 853
         type: string
854
+      health_care_no:
855
+        description: ' 医保号'
856
+        type: string
617 857
       id:
618 858
         description: Primary Key ID
619 859
         type: integer

+ 291 - 0
tests/default_test.go Dosyayı Görüntüle

@@ -4,7 +4,9 @@ import (
4 4
 	"encoding/json"
5 5
 	"errors"
6 6
 	"fmt"
7
+	"math"
7 8
 	"path/filepath"
9
+	"regexp"
8 10
 	"runtime"
9 11
 	"strconv"
10 12
 	"strings"
@@ -14,6 +16,8 @@ import (
14 16
 	"sws_xcx/service"
15 17
 	"sws_xcx/utils"
16 18
 	"testing"
19
+	"time"
20
+	"unicode/utf8"
17 21
 
18 22
 	//beego "github.com/beego/beego/v2/server/web"
19 23
 	//"github.com/beego/beego/v2/core/logs"
@@ -208,6 +212,293 @@ func TestHandleMsg(t *testing.T) {
208 212
 
209 213
 }
210 214
 
215
+var DIGITS = []rune{
216
+	'S', 'V', 'X', '5', '0', '8', '-', 'N',
217
+	'i', 'm', 'd', 'u', 'H', 'O', 'Q', 'E',
218
+	'D', 'v', 't', '2', 'c', 'p', '1', '3',
219
+	'z', 'R', 'a', 'W', 'l', 'G', 'k', 'A',
220
+	'9', 'o', 's', 'g', 'y', '4', 'w', 'L',
221
+	'T', 'Y', 'b', '+', 'J', 'x', '7', 'r',
222
+	'I', 'n', 'f', 'Z', 'e', 'M', 'C', 'P',
223
+	'U', 'B', 'j', '6', 'F', 'K', 'h', 'q',
224
+}
225
+
226
+func TestHandleQrCode(t *testing.T) {
227
+
228
+	result := "http://d.j6c.cn/E0YUQ|XGU|5Vy.z6k&EZf"
229
+	//result = "E0YUQ|XGU|5Vy.z6k&EZf"
230
+	var userId uint64
231
+
232
+	if result != "" {
233
+
234
+		re := regexp.MustCompile(`(http.*/)?(.+)$`)
235
+		matches := re.FindStringSubmatch(result)
236
+
237
+		str := matches[2]
238
+
239
+		parity := str[len(str)-1:]
240
+		st := int8(0)
241
+		result1 := result[:len(result)-1]
242
+
243
+		for i := 0; i < utf8.RuneCountInString(result1); i++ {
244
+			r, _ := utf8.DecodeRuneInString(result1[i:])
245
+			st += int8(r)
246
+			st = int8(getUint8(int(st)))
247
+		}
248
+		digit := DIGITS[getUint8(int(^st))%64]
249
+		if string(digit) != parity {
250
+			t.Error("检测数据校验不通过")
251
+			return
252
+		}
253
+		item, err := strconv.ParseInt(str[:1], 16, 32)
254
+		if err != nil {
255
+			t.Error(err)
256
+			return
257
+		}
258
+		if item != 14 && item != 11 {
259
+			t.Error("无法解析检测结果")
260
+			return
261
+		}
262
+
263
+		strs := str[1 : len(str)-1]
264
+		strs = regexp.MustCompile(`[._&$|]`).ReplaceAllString(strs, " ")
265
+		strsArray := strings.Fields(strs)
266
+
267
+		if len(strsArray) < 5 {
268
+			t.Error("无法解析检测结果")
269
+			return
270
+		}
271
+
272
+		serialno := "09" + formatNumber(radixString(strsArray[0]), 8)
273
+		serialno += formatNumber(radixString(strsArray[1]), 7)
274
+
275
+		acc := int(radixString(strsArray[2]))
276
+
277
+		checkResultStr := formatNumber(radixString(strsArray[3]), 7)
278
+		if item == 14 {
279
+			checkResultStr += formatNumber(radixString(strsArray[4]), 7)
280
+		} else if item == 11 {
281
+			checkResultStr += formatNumber(radixString(strsArray[4]), 4)
282
+		}
283
+
284
+		fmt.Println("Device Name:", serialno)
285
+		fmt.Println("Acc:", acc)
286
+		fmt.Println("Check Result String:", checkResultStr)
287
+
288
+		device, err := service.NewDeviceService().GetDeviceByNo(serialno)
289
+		if err != nil {
290
+			t.Error(err)
291
+			return
292
+		}
293
+		if device.Id == 0 {
294
+			t.Error("不是本系统中的设备,无法解析结果")
295
+			return
296
+		}
297
+		ds := service.NewDeviceService()
298
+		dr, err := ds.GetDeviceRelateByDeviceId(device.Id)
299
+		if err != nil {
300
+			t.Error(err)
301
+			return
302
+		}
303
+		var status int
304
+		if dr.Id == 0 {
305
+			//设备未绑定 提示绑定
306
+			status = 1
307
+
308
+		} else if dr.UserId != userId {
309
+			//别人已经绑定设备,返回结果 并提示
310
+			status = 2
311
+
312
+		} else {
313
+			//自己绑定的设备,返回结果不提示
314
+			status = 3
315
+		}
316
+		da := strings.Split(checkResultStr, "")
317
+		count := len(da)
318
+		checkItems, err := service.NewCheckItemService().GetCheckItems("cn", device.DeviceType)
319
+
320
+		if err != nil {
321
+			utils.ErrorLog("GetCheckItems %v:", err)
322
+			t.Error(err)
323
+			return
324
+		}
325
+		crs := service.NewCheckRecordService()
326
+		record, err := crs.GetCheckRecordByAcc(device.Id, acc)
327
+		if err != nil {
328
+			utils.ErrorLog("GetCheckRecordByAcc %v:", err)
329
+			t.Error(err)
330
+		}
331
+		if record.Id == 0 {
332
+			//创建记录
333
+			err = ds.CreateDeviceMessageLog(models.DeviceMessageLog{
334
+				DeviceName: device.DeviceName,
335
+				Content:    result,
336
+				EventType:  enums.EventTypeQrCode,
337
+			})
338
+			if err != nil {
339
+				utils.ErrorLog("CreateDeviceMessageLog %v:", err)
340
+				t.Error(err)
341
+				return
342
+			}
343
+			if len(checkItems) < count {
344
+				t.Error("接收的数据与检查项目配置不一致")
345
+				return
346
+			}
347
+			checkRecord := &models.CheckRecord{
348
+				Acc:          acc,
349
+				PutSources:   enums.EventTypeQrCode,
350
+				DeviceId:     device.Id,
351
+				UserId:       dr.UserId,
352
+				DeviceStatus: device.Status,
353
+				Ctime:        time.Now(),
354
+			}
355
+			if dr.UserId > 0 {
356
+
357
+				hp, err := service.NewUserHealthProfileService().GetUserHealthProfileByUserId(dr.UserId)
358
+				if err != nil {
359
+					utils.ErrorLog("GetUserHealthProfileByUserId %v:", err)
360
+					t.Error(err)
361
+					return
362
+				}
363
+				checkRecord.UserHealthProfileId = int64(hp.Id)
364
+			}
365
+			err = crs.CreateCheckRecord(checkRecord)
366
+			if err != nil {
367
+				utils.ErrorLog("CreateCheckRecord %v:", err)
368
+				t.Error(err)
369
+				return
370
+			}
371
+			alerts := make([]string, 0)
372
+			for i := 0; i < count; i++ {
373
+				vi, _ := strconv.Atoi(da[i])
374
+				err = createCheckRecordItem(checkItems, checkRecord.Id, &alerts, vi, i+1, crs)
375
+				if err != nil {
376
+					utils.ErrorLog("createCheckRecordItem valule:%v, err:%v:", vi, err)
377
+				}
378
+			}
379
+
380
+			if len(alerts) > 0 {
381
+				alertItemIds := strings.Join(alerts, ",")
382
+				err = crs.UpdateCheckRecordAlertItems(checkRecord.Id, alertItemIds)
383
+				if err != nil {
384
+					utils.ErrorLog("UpdateCheckRecordAlertItems %v:", err)
385
+					t.Error(err)
386
+					return
387
+				}
388
+
389
+			} else {
390
+				utils.TraceLog("无异常数据")
391
+			}
392
+			record = *checkRecord
393
+		}
394
+
395
+		recordItems, err := crs.GetCheckRecordItems(record.Id)
396
+		if err != nil {
397
+			utils.ErrorLog("GetCheckRecordItems %v:", err)
398
+			t.Error(err)
399
+			return
400
+		}
401
+		checkRecordItem, err := analyzeCheckRecord(recordItems, checkItems)
402
+		if err != nil {
403
+			t.Error(err)
404
+			return
405
+		}
406
+		checkRecordItem.Status = status
407
+		checkRecordItem.CheckDate = record.Ctime
408
+		checkRecordItem.UserID = int64(record.UserId)
409
+		checkRecordItem.Bind = checkRecordItem.UserID > 0
410
+		checkRecordItem.CheckRecordID = record.Id
411
+
412
+		t.Logf("result:%+v", checkRecordItem)
413
+
414
+	}
415
+
416
+}
417
+
418
+func analyzeCheckRecord(ritems []*models.CheckRecordItem, citems []*models.CheckItem) (models.AppCheckRecordItemVO, error) {
419
+	var result models.AppCheckRecordItemVO
420
+	var details []models.AppCheckRecordItemDetailsVO
421
+
422
+	for _, ri := range ritems {
423
+		detail := models.AppCheckRecordItemDetailsVO{}
424
+		item := findItem(citems, ri.CheckItemId)
425
+		if item == nil {
426
+			continue
427
+		}
428
+		if ri.CheckValue != "" && item.ScopeList != "" {
429
+			var scopes []*models.CheckItemScopeVO
430
+			err := json.Unmarshal([]byte(item.ScopeList), &scopes)
431
+			if err != nil {
432
+				return result, err
433
+			}
434
+			for _, scope := range scopes {
435
+				if ri.CheckValueIndex == scope.Index {
436
+					if scope.Type == 1 {
437
+						result.NormalCount += 1
438
+						detail.Alert = false
439
+
440
+					} else {
441
+						result.AlertCount += 1
442
+						detail.Alert = true
443
+					}
444
+					detail.ValueIndex = strconv.Itoa(ri.CheckValueIndex)
445
+					detail.ID = item.Id
446
+					detail.Value = scope.Value
447
+					detail.NameCn = item.NameCn
448
+					detail.NameEn = item.NameEn
449
+					detail.ReferenceValue = item.ReferenceValue
450
+					//detail.Describe = item.Details
451
+					detail.Unit = item.Unit
452
+					details = append(details, detail)
453
+					break
454
+				}
455
+			}
456
+			result.Items = details
457
+			if result.AlertCount > 1 {
458
+				result.AlertGrade = enums.AlertGradeHIGH
459
+			} else if result.AlertCount == 1 {
460
+				result.AlertGrade = enums.AlertGradeMEDIUM
461
+
462
+			} else {
463
+				result.AlertGrade = enums.AlertGradeNORMAL
464
+			}
465
+			result.Describe = enums.AlertGradeMap[result.AlertGrade]
466
+		}
467
+	}
468
+
469
+	return result, nil
470
+}
471
+
472
+func formatNumber(num int64, width int) string {
473
+	format := fmt.Sprintf("%%0%dd", width)
474
+	return fmt.Sprintf(format, num)
475
+}
476
+
477
+func getUint8(val int) uint8 {
478
+	return uint8(val & 0xFF)
479
+}
480
+
481
+func indexDigits(ch rune) int {
482
+	for i, digit := range DIGITS {
483
+		if ch == digit {
484
+			return i
485
+		}
486
+	}
487
+	return -1
488
+}
489
+
490
+func radixString(str string) int64 {
491
+	sum := int64(0)
492
+	len := len(str)
493
+
494
+	for i := 0; i < len; i++ {
495
+		index := indexDigits(rune(str[len-i-1]))
496
+		sum += int64(index) * int64(math.Pow(64, float64(i)))
497
+	}
498
+
499
+	return sum
500
+}
501
+
211 502
 func createCheckRecordItem(items []*models.CheckItem, crId int64, alerts *[]string, vi, n int, crs *service.CheckRecordService) error {
212 503
 	item := findItem(items, n)
213 504
 	if item == nil {

+ 28 - 0
tests/gendb_test.go Dosyayı Görüntüle

@@ -1,9 +1,13 @@
1 1
 package test
2 2
 
3 3
 import (
4
+	"encoding/json"
5
+	"fmt"
6
+	"strings"
4 7
 	"sws_xcx/models"
5 8
 	"sws_xcx/service"
6 9
 	"testing"
10
+	"time"
7 11
 
8 12
 	"github.com/jinzhu/gorm"
9 13
 )
@@ -97,3 +101,27 @@ func TestGetMobilePatientInfo(t *testing.T) {
97 101
 	}
98 102
 	t.Logf("id: %d orgid: %d", p.ID, p.UserOrgId)
99 103
 }
104
+
105
+func TestLoginRedis(t *testing.T) {
106
+
107
+	s := service.NewXcxUserService()
108
+	u, err := s.GetUser(1)
109
+	if err != nil {
110
+		t.Error(err)
111
+		return
112
+
113
+	}
114
+	key := "47ca0e8d-fad7-4ef4-8dfc-5a36dd0d0993"
115
+	uJson, _ := json.Marshal(u)
116
+	redisCli := service.RedisClient()
117
+	defer redisCli.Close()
118
+	redisCli.Set(fmt.Sprintf("session:%v", key), uJson, time.Hour*time.Duration(7200))
119
+
120
+}
121
+
122
+func TestStr(t *testing.T) {
123
+	str := "1234567"
124
+
125
+	strArr := strings.Split(str, "")
126
+	t.Log(strArr)
127
+}