Rick.Lan 4 ay önce
ebeveyn
işleme
0f57ea3031

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

@@ -42,6 +42,11 @@ func ApiControllersRegisterRouters() {
42 42
 
43 43
 	beego.Router("/xcx/api/sysdic/getdevicetypes", &SysDicApiController{}, "Get:GetDeviceTypes")
44 44
 
45
+	beego.Router("xcx/api/device/binddevice", &DeviceApiController{}, "Post:BindDevice")
46
+	beego.Router("/xcx/api/device/getdevicedetail", &DeviceApiController{}, "Get:GetDeviceDetail")
47
+	beego.Router("/xcx/api/device/getmydevices", &DeviceApiController{}, "Get:GetMyDevices")
48
+	beego.Router("/xcx/api/device/unbinddevice", &DeviceApiController{}, "Post:UnbindDevice")
49
+
45 50
 }
46 51
 
47 52
 type BaseApiController struct {
@@ -140,6 +145,12 @@ func (c *BaseApiController) ServeSuccessJSON(data interface{}) {
140 145
 	c.ServeJSON()
141 146
 }
142 147
 
148
+func (c *BaseApiController) ServeSuccessPageJSON(list interface{}, total int) {
149
+
150
+	c.Data["json"] = enums.MakeSuccessPageResponseJSON(list, total)
151
+	c.ServeJSON()
152
+}
153
+
143 154
 func (c *BaseApiController) ServeFailJSONWithSGJErrorCode(code int) {
144 155
 	c.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(code)
145 156
 	c.ServeJSON()

+ 16 - 0
controllers/check_record_api_controller.go Dosyayı Görüntüle

@@ -3,3 +3,19 @@ package controllers
3 3
 type CheckRecordApiController struct {
4 4
 	BaseApiAuthController
5 5
 }
6
+
7
+func (c *CheckRecordApiController) GetCheckRecordList() {
8
+
9
+}
10
+
11
+func (c *CheckRecordApiController) GetCheckRecordItemReport() {
12
+
13
+}
14
+
15
+func (c *CheckRecordApiController) GetCheckRecordItemById() {
16
+
17
+}
18
+
19
+func (c *CheckRecordApiController) QrCodeCheckRecord() {
20
+
21
+}

+ 17 - 11
controllers/device_api_controllor.go Dosyayı Görüntüle

@@ -1,6 +1,9 @@
1 1
 package controllers
2 2
 
3
-import "sws_xcx/service"
3
+import (
4
+	"sws_xcx/service"
5
+	"sws_xcx/utils"
6
+)
4 7
 
5 8
 type DeviceApiController struct {
6 9
 	BaseApiAuthController
@@ -17,7 +20,7 @@ func (c *DeviceApiController) GetMyDevices() {
17 20
 	devices, err := service.NewDeviceService().GetMyDevices(c.CurrentUser.Id)
18 21
 	if err != nil {
19 22
 		c.ServeDynamicFailJsonSend(err.Error())
20
-
23
+		return
21 24
 	}
22 25
 	c.ServeSuccessJSON(devices)
23 26
 
@@ -25,45 +28,46 @@ func (c *DeviceApiController) GetMyDevices() {
25 28
 
26 29
 // @Title GetDeviceDetail
27 30
 // @Description 根据设备ID获取设备详细信息
28
-// @Param   id path int true "设备ID"
31
+// @Param   deviceid query int true "设备ID"
29 32
 // @Success 200 {object} models.Device success
30 33
 // @Failure 500 error
31 34
 // @Security token
32 35
 // @router /getdevicedetail [get]
33 36
 func (c *DeviceApiController) GetDeviceDetail() {
34 37
 
35
-	id, err := c.GetInt("id")
38
+	utils.TraceLog(c.GetString("deviceid"))
39
+	id, err := c.GetInt("deviceid")
36 40
 	if err != nil {
37 41
 		c.ServeDynamicFailJsonSend(err.Error())
42
+		return
38 43
 	}
39 44
 	device, err := service.NewDeviceService().GetDeviceInfo(id)
40 45
 	if err != nil {
41 46
 		c.ServeDynamicFailJsonSend(err.Error())
47
+		return
42 48
 	}
43 49
 	c.ServeSuccessJSON(device)
44 50
 }
45 51
 
46 52
 // @Title BindDevice
47 53
 // @Description 绑定设备
48
-// @Param   deviceid path int true "设备ID"
54
+// @Param   qrcode query string true "设备二维码"
49 55
 // @Success 200  success
50 56
 // @Failure 500 error
51 57
 // @Security token
52 58
 // @router /binddevice [post]
53 59
 func (c *DeviceApiController) BindDevice() {
54
-	id, err := c.GetInt("deviceid")
55
-	if err != nil {
56
-		c.ServeDynamicFailJsonSend(err.Error())
57
-	}
58
-	if err := service.NewDeviceService().BindDevice(c.CurrentUser.Id, uint64(id)); err != nil {
60
+	qrcode := c.GetString("qrcode")
61
+	if err := service.NewDeviceService().BindDevice(c.CurrentUser.Id, qrcode); err != nil {
59 62
 		c.ServeDynamicFailJsonSend(err.Error())
63
+		return
60 64
 	}
61 65
 	c.ServeSuccessJSON(new(interface{}))
62 66
 }
63 67
 
64 68
 // @Title UnBindDevice
65 69
 // @Description 解绑设备
66
-// @Param   deviceid path int true "设备ID"
70
+// @Param   deviceid query int true "设备ID"
67 71
 // @Success 200  success
68 72
 // @Failure 500 error
69 73
 // @Security token
@@ -72,9 +76,11 @@ func (c *DeviceApiController) UnbindDevice() {
72 76
 	id, err := c.GetInt("deviceid")
73 77
 	if err != nil {
74 78
 		c.ServeDynamicFailJsonSend(err.Error())
79
+		return
75 80
 	}
76 81
 	if err := service.NewDeviceService().UnbindDevice(c.CurrentUser.Id, uint64(id)); err != nil {
77 82
 		c.ServeDynamicFailJsonSend(err.Error())
83
+		return
78 84
 	}
79 85
 	c.ServeSuccessJSON(new(interface{}))
80 86
 }

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

@@ -1,6 +1,14 @@
1 1
 package controllers
2 2
 
3 3
 import (
4
+	"encoding/json"
5
+	"errors"
6
+	"fmt"
7
+	"strconv"
8
+	"strings"
9
+	"sws_xcx/enums"
10
+	"sws_xcx/models"
11
+	"sws_xcx/service"
4 12
 	"sws_xcx/utils"
5 13
 )
6 14
 
@@ -10,10 +18,174 @@ type MessageApiControllor struct {
10 18
 
11 19
 func (c *MessageApiControllor) PutEmqxMessage() {
12 20
 
13
-	utils.InfoLog("Revice EMQX message: %s", c.Ctx.Input.RequestBody)
14
-	c.ServeSuccessJSON(map[string]interface{}{})
21
+	msg := &models.OpenEmqMsgReqVO{}
22
+	err := json.Unmarshal(c.Ctx.Input.RequestBody, msg)
23
+	if err != nil {
24
+		c.ServeDynamicFailJsonSend(err.Error())
25
+		return
26
+	}
27
+
28
+	ds := service.NewDeviceService()
29
+
30
+	device, err := ds.GetDeviceByNo(msg.UserName)
31
+	if err != nil {
32
+		utils.ErrorLog("GetDeviceByNo %v:", err)
33
+		c.ServeDynamicFailJsonSend(err.Error())
34
+		return
35
+	}
36
+	if device.Id == 0 {
37
+		msg := "非本系统设备,数据废弃"
38
+		utils.WarningLog(msg)
39
+		c.ServeDynamicFailJsonSend(msg)
40
+		return
41
+	}
42
+	err = ds.CreateDeviceMessageLog(models.DeviceMessageLog{
43
+		DeviceName: msg.DeviceName,
44
+		Content:    string(c.Ctx.Input.RequestBody),
45
+		EventType:  enums.EventTypeEmqx,
46
+		MessageId:  msg.Id,
47
+		Topic:      msg.Topic,
48
+	})
49
+
50
+	if err != nil {
51
+		utils.ErrorLog("CreateDeviceMessageLog %v:", err)
52
+		c.ServeDynamicFailJsonSend(err.Error())
53
+		return
54
+	}
55
+	payload := &models.OpenEmqPayloadReqVO{}
56
+	err = json.Unmarshal([]byte(msg.Payload), payload)
57
+	if err != nil {
58
+		utils.ErrorLog("json.Unmarshal %v:", err)
59
+		c.ServeDynamicFailJsonSend(err.Error())
60
+		return
61
+	}
62
+	if payload.Len != 23 {
63
+		utils.WarningLog("非标准数据,数据废弃:%v", msg.Payload)
64
+	}
65
+
66
+	dr, err := ds.GetDeviceRelateByDeviceId(device.Id)
67
+	if err != nil {
68
+		utils.ErrorLog("GetDeviceRelateByDeviceId %v:", err)
69
+		c.ServeDynamicFailJsonSend(err.Error())
70
+		return
71
+	}
72
+
73
+	checkRecord := &models.CheckRecord{
74
+
75
+		Acc:          payload.Acc,
76
+		PutSources:   enums.EventTypeEmqx,
77
+		MessageId:    msg.Id,
78
+		DeviceId:     device.Id,
79
+		UserId:       dr.UserId,
80
+		DeviceStatus: device.Status,
81
+	}
82
+
83
+	if dr.UserId > 0 {
84
+
85
+		hp, err := service.NewUserHealthProfileService().GetUserHealthProfileByUserId(dr.UserId)
86
+		if err != nil {
87
+			utils.ErrorLog("GetUserHealthProfileByUserId %v:", err)
88
+			c.ServeDynamicFailJsonSend(err.Error())
89
+			return
90
+		}
91
+		checkRecord.UserHealthProfileId = int64(hp.Id)
92
+	}
93
+	crs := service.NewCheckRecordService()
94
+	err = crs.CreateCheckRecord(checkRecord)
95
+	if err != nil {
96
+		utils.ErrorLog("CreateCheckRecord %v:", err)
97
+		c.ServeDynamicFailJsonSend(err.Error())
98
+		return
99
+	}
100
+
101
+	da := strings.Split(payload.Data, ",")
102
+	count := payload.Count
103
+	if len(da) != count {
104
+		utils.WarningLog("数据长度不匹配,截取存储 %+v", payload)
105
+		if len(da) < count {
106
+			count = len(da)
107
+		}
108
+	}
109
+
110
+	checkItems, err := service.NewCheckItemService().GetCheckItems("cn", device.DeviceType)
111
+
112
+	if err != nil {
113
+		utils.ErrorLog("GetCheckItems %v:", err)
114
+		c.ServeDynamicFailJsonSend(err.Error())
115
+		return
116
+	}
117
+
118
+	if len(checkItems) < count {
119
+		c.ServeDynamicFailJsonSend("接收的数据于检查项目配置不一致")
120
+		return
121
+	}
122
+
123
+	alerts := make([]string, 0)
124
+	for i := 0; i < count; i++ {
125
+		vi, _ := strconv.Atoi(da[i])
126
+		err = createCheckRecordItem(checkItems, checkRecord.Id, &alerts, vi, i+1, crs)
127
+		if err != nil {
128
+			utils.ErrorLog("createCheckRecordItem valule:%v, err:%v:", vi, err)
129
+		}
130
+	}
131
+
132
+	if len(alerts) > 0 {
133
+		alertItemIds := strings.Join(alerts, ",")
134
+		err = crs.UpdateCheckRecordAlertItems(checkRecord.Id, alertItemIds)
135
+		if err != nil {
136
+			utils.ErrorLog("UpdateCheckRecordAlertItems %v:", err)
137
+			c.ServeDynamicFailJsonSend(err.Error())
138
+			return
139
+		}
140
+
141
+	}
142
+
15 143
 }
16 144
 
17
-func HandleMsg(req []byte) {
145
+func createCheckRecordItem(items []*models.CheckItem, crId int64, alerts *[]string, vi, n int, crs *service.CheckRecordService) error {
146
+	item := findItem(items, n)
147
+	if item == nil {
148
+		return fmt.Errorf("检测项目不匹配,需要检查基础数据!序号:%v", n)
149
+	}
150
+
151
+	cri := models.CheckRecordItem{
152
+		CheckId:         crId,
153
+		CheckItemId:     n,
154
+		CheckValueIndex: vi,
155
+	}
156
+
157
+	scopes := []*models.CheckItemScopeVO{}
158
+	err := json.Unmarshal([]byte(item.ScopeList), &scopes)
159
+	if err != nil {
160
+		return fmt.Errorf("检测项目数值范围定义不正确 err:%v", err)
161
+	}
162
+	scope := findScope(scopes, vi)
163
+	if scope == nil {
164
+		return errors.New("检测结果不匹配")
165
+	}
166
+
167
+	cri.CheckValue = scope.Value
168
+	if scope.Type == 1 {
169
+		*alerts = append(*alerts, strconv.Itoa(n))
170
+	}
171
+	return crs.CreateCheckRecordItem(&cri)
172
+}
173
+
174
+func findScope(scopes []*models.CheckItemScopeVO, vi int) *models.CheckItemScopeVO {
175
+	for _, scope := range scopes {
176
+		if scope.Index == vi {
177
+			return scope
178
+		}
179
+	}
180
+	return nil
181
+}
18 182
 
183
+func findItem(items []*models.CheckItem, itemNumber int) *models.CheckItem {
184
+	//循环items
185
+	for _, item := range items {
186
+		if item.CheckItemNumber == itemNumber {
187
+			return item
188
+		}
189
+	}
190
+	return nil
19 191
 }

+ 2 - 0
controllers/user_api_controller.go Dosyayı Görüntüle

@@ -35,6 +35,8 @@ func (c *UserApiController) GetUserInfo() {
35 35
 		Source:                  c.CurrentUser.Source,
36 36
 		Ctime:                   models.Time(c.CurrentUser.Ctime),
37 37
 		Mtime:                   models.Time(c.CurrentUser.Mtime),
38
+		UserOrgId:               c.CurrentUser.UserOrgId,
39
+		PatientId:               c.CurrentUser.PatientId,
38 40
 	}
39 41
 
40 42
 	p, err := service.NewUserHealthProfileService().GetUserHealthProfileByUserId(c.CurrentUser.Id)

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

@@ -0,0 +1,6 @@
1
+package enums
2
+
3
+const (
4
+	EventTypeEmqx   = "emq"
5
+	EventTypeQrCode = "device_qr_code"
6
+)

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

@@ -490,6 +490,12 @@ func MakeSuccessResponseJSON(data interface{}) CommonResp {
490 490
 	return resp
491 491
 }
492 492
 
493
+func MakeSuccessPageResponseJSON(data interface{}, total int) CommonResp {
494
+	resp := CommonResp{Code: 0, State: 1, Msg: "success"}
495
+	resp.Data = map[string]interface{}{"total": total, "list": data}
496
+	return resp
497
+}
498
+
493 499
 func MakeFailResponseJSON(errMsg string, errCode int) CommonResp {
494 500
 	resp := CommonResp{Code: errCode, Msg: errMsg, State: 0}
495 501
 	return resp

+ 1 - 1
models/dbmodels.go Dosyayı Görüntüle

@@ -77,7 +77,7 @@ type Device struct {
77 77
 	BatchNumber          int       `json:"batch_number" gorm:"type:int(10); COMMENT:'批号'" description:"批号"`
78 78
 	ProductionDateNumber int       `json:"production_date_number" gorm:"type:int(10); COMMENT:'生产日期'" description:"生产日期"`
79 79
 	Number               int       `json:"number" gorm:"type:int(10); COMMENT:'序号'" description:"序号"`
80
-	QrCodeId             int64     `json:"qr_code_id" gorm:"type:bigint(20)"`
80
+	QrCode               string    `json:"qr_code" gorm:"type:varchar(255)"`
81 81
 	EmqPassword          string    `json:"emq_password" gorm:"type:varchar(255); COMMENT:'emq密码'" description:"emq密码"`
82 82
 	Status               int       `json:"status" gorm:"type:int(2); DEFAULT:'0'; COMMENT:'状态(0:未分配 1:已分配 2:包装中 3:待出厂 6:废弃 99:已出厂 100:销售中 101:已售出)'" description:"状态(0:未分配 1:已分配 2:包装中 3:待出厂 6:废弃 99:已出厂 100:销售中 101:已售出)"`
83 83
 	Ver                  string    `json:"ver" gorm:"type:varchar(255); COMMENT:'软件版本'" description:"软件版本"`

+ 32 - 5
models/httpmodels.go Dosyayı Görüntüle

@@ -71,6 +71,9 @@ type UserInfoResp struct {
71 71
 	IdCard            string `json:"id_card" description:"身份证号"`
72 72
 	InpatientRegPhone string `json:"inpatient_reg_phone" description:"住院登记手机号"`
73 73
 
74
+	PatientId int64 ` json:"patient_id"`
75
+	UserOrgId int64 ` json:"user_org_id"`
76
+
74 77
 	Ctime Time `json:"ctime" description:"创建时间"`
75 78
 	Mtime Time `json:"mtime" description:"更新时间 "`
76 79
 }
@@ -127,7 +130,7 @@ type DicResp struct {
127 130
 	Value int    `json:"value" description:"字典值"`
128 131
 }
129 132
 
130
-type OpenEmqMsgReqV0 struct {
133
+type OpenEmqMsgReqVO struct {
131 134
 	UserName   string `json:"username" description:"用户名"`
132 135
 	Topic      string `json:"topic" description:"主题"`
133 136
 	PeerHost   string `json:"peerhost" description:"主机"`
@@ -158,8 +161,32 @@ type OpenEmqPayloadReqVO struct {
158 161
 	Len        int    `json:"len"`        // 长度
159 162
 }
160 163
 type CheckItemScopeVO struct {
161
-	Index int     `json:"index"`
162
-	Type  int     `json:"type"`
163
-	Value string  `json:"value"`
164
-	Num   float64 `json:"num"`
164
+	Index int    `json:"index"`
165
+	Type  int    `json:"type"`
166
+	Value string `json:"value"`
167
+	Num   string `json:"num"`
168
+}
169
+
170
+type AppCheckRecordVO struct {
171
+
172
+	// AlertCount is the number of alerts.
173
+	AlertCount int `json:"alert_count" description:"异常数量"`
174
+	// NormalCount is the number of normal items.
175
+	NormalCount int `json:"normal_count" description:"正常数量"`
176
+	// Describe is the description of the record.
177
+	Describe string `json:"describe" description:"描述"`
178
+	// CheckDate is the date when the check was performed.
179
+	CheckDate Time `json:"check_date" description:"检测日期"`
180
+	// CheckRecordID is the ID of the check record.
181
+	CheckRecordId int64 `json:"check_record_id" description:"检测记录id"`
182
+	// UserID is the user ID, defaulting to the user's own ID.
183
+	UserId uint64 `json:"user_id" description:"绑定用户id 默认自己"`
184
+	// AlertGrade is the risk level: 1 for low, 2 for medium, 3 for high.
185
+	//AlertGrade int `json:"alert_grade" description:"风险等级 1 低  2 中 3 高"`
186
+	// View indicates whether the record has been viewed.
187
+	View int `json:"view" description:"是否查看 1 已查看 0 未查看"`
188
+	// Bind indicates whether the user is bound.
189
+	Bind int `json:"bind" description:"0 未绑定用户 1 绑定"`
190
+	// AlertItems is a list of alert items.
191
+	AlertItems []string `json:"alert_items" description:"异常项"`
165 192
 }

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

@@ -33,7 +33,7 @@ func init() {
33 33
 			),
34 34
 			beego.NSNamespace("/api/device",
35 35
 				beego.NSInclude(
36
-					&controllers.MessageApiControllor{},
36
+					&controllers.DeviceApiController{},
37 37
 				)),
38 38
 			beego.NSNamespace("/api/sysdic",
39 39
 				beego.NSInclude(

+ 5 - 2
service/checkitemservice.go Dosyayı Görüntüle

@@ -18,9 +18,12 @@ func NewCheckItemService() *CheckItemService {
18 18
 
19 19
 func (s *CheckItemService) GetCheckItems(lang, t string) ([]*models.CheckItem, error) {
20 20
 	var items []*models.CheckItem
21
-	db := s.rdb.Where("language = ? and delete_flag = ?", lang, 0)
21
+	db := s.rdb.Where(" delete_flag = ?", 0)
22 22
 	if t != "" {
23
-		db = db.Where("check_type = ?", t)
23
+		db = db.Where("device_type = ?", t)
24
+	}
25
+	if lang != "" {
26
+		db = db.Where("language = ? ", lang)
24 27
 	}
25 28
 	err := db.Order("check_item_number").Find(&items).Error
26 29
 	return items, err

+ 61 - 2
service/checkrecordservice.go Dosyayı Görüntüle

@@ -1,7 +1,10 @@
1 1
 package service
2 2
 
3 3
 import (
4
+	"strconv"
5
+	"strings"
4 6
 	"sws_xcx/models"
7
+	"sws_xcx/utils"
5 8
 
6 9
 	"github.com/jinzhu/gorm"
7 10
 )
@@ -18,10 +21,66 @@ func NewCheckRecordService() *CheckRecordService {
18 21
 	}
19 22
 }
20 23
 
21
-func (s *CheckRecordService) GetCheckRecordList(pageNum, pageSize int, search string) ([]*models.CheckRecord, int, error) {
22
-	return nil, 0, nil
24
+func (s *CheckRecordService) GetCheckRecordList(pageNum, pageSize int, userid uint64) (vos []models.AppCheckRecordVO, total int, err error) {
25
+	offset := (pageNum - 1) * pageSize
26
+	records := make([]*models.CheckRecord, pageSize)
27
+	err = s.rdb.Model(&models.CheckRecord{}).Where("user_id= ? and delete_flag = ?", 0).Count(&total).Order("id desc").Offset(offset).Limit(pageSize).Find(&records).Error
28
+	if len(records) > 0 {
29
+		is := NewCheckItemService()
30
+		cnItems, err1 := is.GetCheckItems("cn", "1")
31
+		if err1 != nil {
32
+			utils.ErrorLog("GetCheckItems err:%v ", err1)
33
+		}
34
+		mcn := make(map[int]models.CheckItem, len(cnItems))
35
+		for _, item := range cnItems {
36
+			mcn[item.Id] = *item
37
+		}
38
+
39
+		vos = make([]models.AppCheckRecordVO, len(records))
40
+		for i, r := range records {
41
+			vo := models.AppCheckRecordVO{}
42
+			vo.CheckRecordId = r.Id
43
+			vo.UserId = r.UserId
44
+			if r.UserId > 0 {
45
+				vo.Bind = 1
46
+			}
47
+			vo.CheckDate = models.Time(r.Ctime)
48
+			vo.View = r.View
49
+			vo.AlertCount = 0
50
+			//vo.AlertGrade = 0
51
+
52
+			if r.AlertItemIds != "" {
53
+				ids := strings.Split(r.AlertItemIds, ",")
54
+				names := make([]string, len(ids))
55
+				for j, id := range ids {
56
+
57
+					ii, _ := strconv.Atoi(id)
58
+					if item, ok := mcn[ii]; ok {
59
+						names[j] = item.NameCn
60
+					}
61
+
62
+				}
63
+				vo.AlertItems = names
64
+				vo.AlertCount = len(ids)
65
+			}
66
+			vo.NormalCount = len(cnItems) - vo.AlertCount
67
+
68
+			vos[i] = vo
69
+		}
70
+
71
+	}
72
+
73
+	return
23 74
 }
24 75
 
25 76
 func (s *CheckRecordService) CreateCheckRecord(checkRecord *models.CheckRecord) error {
26 77
 	return s.wdb.Model(checkRecord).Create(checkRecord).Error
27 78
 }
79
+
80
+func (s *CheckRecordService) CreateCheckRecordItem(checkRecordItem *models.CheckRecordItem) error {
81
+	return s.wdb.Model(checkRecordItem).Create(checkRecordItem).Error
82
+}
83
+
84
+func (s *CheckRecordService) UpdateCheckRecordAlertItems(id int64, alertItemIds string) error {
85
+	return s.wdb.Model(&models.CheckRecord{}).Where("id = ?", id).Update("alert_item_ids", alertItemIds).Error
86
+}

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

@@ -19,18 +19,18 @@ func NewDeviceService() *DeviceService {
19 19
 	}
20 20
 }
21 21
 
22
-func (s *DeviceService) GetDeviceInfo(id int) (*models.Device, error) {
23
-	var device *models.Device
24
-	err := s.rdb.Model(device).First(device, id).Error
22
+func (s *DeviceService) GetDeviceInfo(id int) (models.Device, error) {
23
+	var device models.Device
24
+	err := s.rdb.Model(&device).First(&device, id).Error
25 25
 	if err == nil || err == gorm.ErrRecordNotFound {
26 26
 		err = nil
27 27
 	}
28 28
 	return device, err
29 29
 }
30 30
 
31
-func (s *DeviceService) GetDeviceByNo(serialno string) (*models.Device, error) {
32
-	var device *models.Device
33
-	err := s.rdb.Model(device).Where("serialno = ?", serialno).First(device).Error
31
+func (s *DeviceService) GetDeviceByNo(serialno string) (models.Device, error) {
32
+	var device models.Device
33
+	err := s.rdb.Model(&device).Where("serialno = ?", serialno).First(&device).Error
34 34
 	if err == nil || err == gorm.ErrRecordNotFound {
35 35
 		err = nil
36 36
 	}
@@ -40,16 +40,16 @@ func (s *DeviceService) GetDeviceByNo(serialno string) (*models.Device, error) {
40 40
 func (s *DeviceService) GetMyDevices(userId uint64) ([]*models.Device, error) {
41 41
 	var devices []*models.Device
42 42
 	sql := "select d.* from device as d inner join device_relate as dr on d.id = dr.device_id where dr.user_id = ? and dr.delete_flag = 0"
43
-	err := s.rdb.Raw(sql).Scan(&devices).Error
43
+	err := s.rdb.Raw(sql, userId).Scan(&devices).Error
44 44
 	if err != nil {
45 45
 		return nil, err
46 46
 	}
47 47
 	return devices, nil
48 48
 }
49 49
 
50
-func (s *DeviceService) BindDevice(userId uint64, deviceId uint64) error {
50
+func (s *DeviceService) BindDevice(userId uint64, qrcode string) error {
51 51
 	var device models.Device
52
-	err := s.rdb.Model(&device).Where("id = ?  and delete_flag =0", deviceId).First(&device).Error
52
+	err := s.rdb.Model(&device).Where("qr_code = ?  and delete_flag =0", qrcode).First(&device).Error
53 53
 	if err != nil {
54 54
 		if err == gorm.ErrRecordNotFound {
55 55
 			return errors.New("设备不存在")
@@ -57,12 +57,12 @@ func (s *DeviceService) BindDevice(userId uint64, deviceId uint64) error {
57 57
 		return err
58 58
 	}
59 59
 	dr := &models.DeviceRelate{}
60
-	err = s.rdb.Model(dr).Where("device_id = ?", deviceId).First(dr).Error
60
+	err = s.rdb.Model(dr).Where("device_id = ?", device.Id).First(dr).Error
61 61
 	if err != nil {
62 62
 		if err == gorm.ErrRecordNotFound {
63 63
 			dr = &models.DeviceRelate{
64 64
 				UserId:   userId,
65
-				DeviceId: deviceId,
65
+				DeviceId: device.Id,
66 66
 				Name:     device.DeviceName,
67 67
 			}
68 68
 
@@ -75,11 +75,11 @@ func (s *DeviceService) BindDevice(userId uint64, deviceId uint64) error {
75 75
 		if dr.DeleteFlag == 0 {
76 76
 			return errors.New("该设备已绑定其他用户")
77 77
 		} else { //其他用户解绑了设备
78
-			return s.wdb.Model(dr).Where("id=?", dr.Id).Update("delete_flag", 0, "user_id", userId).Error
78
+			return s.wdb.Model(dr).Update("delete_flag", 0, "user_id", userId).Error
79 79
 		}
80 80
 	} else if dr.DeleteFlag == 1 { //直接解绑了该设备 重新绑定
81 81
 
82
-		return s.wdb.Model(dr).Where("id=?", dr.Id).Update("delete_flag", 0).Error
82
+		return s.wdb.Model(dr).Update("delete_flag", 0).Error
83 83
 
84 84
 	} else {
85 85
 		return errors.New("设备已绑定")

+ 180 - 39
swagger/swagger.json Dosyayı Görüntüle

@@ -11,6 +11,132 @@
11 11
     },
12 12
     "basePath": "/xcx",
13 13
     "paths": {
14
+        "/api/device/binddevice": {
15
+            "post": {
16
+                "tags": [
17
+                    "api/device"
18
+                ],
19
+                "description": "绑定设备\n\u003cbr\u003e",
20
+                "operationId": "DeviceApiController.BindDevice",
21
+                "parameters": [
22
+                    {
23
+                        "in": "query",
24
+                        "name": "qrcode",
25
+                        "description": "设备二维码",
26
+                        "required": true,
27
+                        "type": "string"
28
+                    }
29
+                ],
30
+                "responses": {
31
+                    "200": {
32
+                        "description": "success"
33
+                    },
34
+                    "500": {
35
+                        "description": "error"
36
+                    }
37
+                },
38
+                "security": [
39
+                    {
40
+                        "token": []
41
+                    }
42
+                ]
43
+            }
44
+        },
45
+        "/api/device/getdevicedetail": {
46
+            "get": {
47
+                "tags": [
48
+                    "api/device"
49
+                ],
50
+                "description": "根据设备ID获取设备详细信息\n\u003cbr\u003e",
51
+                "operationId": "DeviceApiController.GetDeviceDetail",
52
+                "parameters": [
53
+                    {
54
+                        "in": "query",
55
+                        "name": "deviceid",
56
+                        "description": "设备ID",
57
+                        "required": true,
58
+                        "type": "integer",
59
+                        "format": "int64"
60
+                    }
61
+                ],
62
+                "responses": {
63
+                    "200": {
64
+                        "description": "success",
65
+                        "schema": {
66
+                            "$ref": "#/definitions/models.Device"
67
+                        }
68
+                    },
69
+                    "500": {
70
+                        "description": "error"
71
+                    }
72
+                },
73
+                "security": [
74
+                    {
75
+                        "token": []
76
+                    }
77
+                ]
78
+            }
79
+        },
80
+        "/api/device/getmydevices": {
81
+            "get": {
82
+                "tags": [
83
+                    "api/device"
84
+                ],
85
+                "description": "获取绑定的设备列表\n\u003cbr\u003e",
86
+                "operationId": "DeviceApiController.GetMyDevices",
87
+                "responses": {
88
+                    "200": {
89
+                        "description": "success",
90
+                        "schema": {
91
+                            "type": "array",
92
+                            "items": {
93
+                                "$ref": "#/definitions/models.Device"
94
+                            }
95
+                        }
96
+                    },
97
+                    "500": {
98
+                        "description": "error"
99
+                    }
100
+                },
101
+                "security": [
102
+                    {
103
+                        "token": []
104
+                    }
105
+                ]
106
+            }
107
+        },
108
+        "/api/device/unbinddevice": {
109
+            "post": {
110
+                "tags": [
111
+                    "api/device"
112
+                ],
113
+                "description": "解绑设备\n\u003cbr\u003e",
114
+                "operationId": "DeviceApiController.UnBindDevice",
115
+                "parameters": [
116
+                    {
117
+                        "in": "query",
118
+                        "name": "deviceid",
119
+                        "description": "设备ID",
120
+                        "required": true,
121
+                        "type": "integer",
122
+                        "format": "int64"
123
+                    }
124
+                ],
125
+                "responses": {
126
+                    "200": {
127
+                        "description": "success"
128
+                    },
129
+                    "500": {
130
+                        "description": "error"
131
+                    }
132
+                },
133
+                "security": [
134
+                    {
135
+                        "token": []
136
+                    }
137
+                ]
138
+            }
139
+        },
14 140
         "/api/sysdic/getcheckitems": {
15 141
             "get": {
16 142
                 "tags": [
@@ -447,9 +573,8 @@
447 573
                     "type": "integer",
448 574
                     "format": "int64"
449 575
                 },
450
-                "qr_code_id": {
451
-                    "type": "integer",
452
-                    "format": "int64"
576
+                "qr_code": {
577
+                    "type": "string"
453 578
                 },
454 579
                 "sensor_mode": {
455 580
                     "description": "传感放大倍数",
@@ -497,18 +622,16 @@
497 622
             "type": "object",
498 623
             "properties": {
499 624
                 "birthday": {
500
-                    "description": "生日",
501
-                    "type": "string",
502
-                    "format": "datetime"
625
+                    "$ref": "#/definitions/models.Time",
626
+                    "description": "生日"
503 627
                 },
504 628
                 "blood_type": {
505 629
                     "description": "血型",
506 630
                     "type": "string"
507 631
                 },
508 632
                 "creatine_time": {
509
-                    "description": "肌酐检测时间",
510
-                    "type": "string",
511
-                    "format": "datetime"
633
+                    "$ref": "#/definitions/models.Time",
634
+                    "description": "肌酐检测时间"
512 635
                 },
513 636
                 "creatinine": {
514 637
                     "description": "血肌酐",
@@ -520,9 +643,8 @@
520 643
                     "type": "string"
521 644
                 },
522 645
                 "ctime": {
523
-                    "description": "创建时间",
524
-                    "type": "string",
525
-                    "format": "datetime"
646
+                    "$ref": "#/definitions/models.Time",
647
+                    "description": "创建时间"
526 648
                 },
527 649
                 "gender": {
528 650
                     "description": "性别(0:未知 1:男 2:女)",
@@ -544,9 +666,8 @@
544 666
                     "type": "string"
545 667
                 },
546 668
                 "mtime": {
547
-                    "description": "更新时间 ",
548
-                    "type": "string",
549
-                    "format": "datetime"
669
+                    "$ref": "#/definitions/models.Time",
670
+                    "description": "更新时间 "
550 671
                 },
551 672
                 "renal_function_status": {
552 673
                     "description": "肾功能情况(0:未透析,1: 血液透析,2:腹膜透析,3:肾脏移植)",
@@ -569,18 +690,16 @@
569 690
                     "format": "int64"
570 691
                 },
571 692
                 "urine_protein_24h_time": {
572
-                    "description": "24小时尿蛋白检测时间",
573
-                    "type": "string",
574
-                    "format": "datetime"
693
+                    "$ref": "#/definitions/models.Time",
694
+                    "description": "24小时尿蛋白检测时间"
575 695
                 },
576 696
                 "urine_protein_24h_unit": {
577 697
                     "description": "24小时尿蛋白单位(g/24h,mg/24h)",
578 698
                     "type": "string"
579 699
                 },
580 700
                 "urine_protein_time": {
581
-                    "description": "尿蛋白检测时间",
582
-                    "type": "string",
583
-                    "format": "datetime"
701
+                    "$ref": "#/definitions/models.Time",
702
+                    "description": "尿蛋白检测时间"
584 703
                 },
585 704
                 "urine_protein_unit": {
586 705
                     "description": "尿蛋白单位(g,mg)",
@@ -598,18 +717,16 @@
598 717
             "type": "object",
599 718
             "properties": {
600 719
                 "birthday": {
601
-                    "description": "生日",
602
-                    "type": "string",
603
-                    "format": "datetime"
720
+                    "description": "生日 yyyy-MM-dd HH:mm:ss",
721
+                    "type": "string"
604 722
                 },
605 723
                 "blood_type": {
606 724
                     "description": "血型",
607 725
                     "type": "string"
608 726
                 },
609 727
                 "creatine_time": {
610
-                    "description": "肌酐检测时间",
611
-                    "type": "string",
612
-                    "format": "datetime"
728
+                    "description": "肌酐检测时间 yyyy-MM-dd HH:mm:ss",
729
+                    "type": "string"
613 730
                 },
614 731
                 "creatinine": {
615 732
                     "description": "血肌酐",
@@ -650,18 +767,16 @@
650 767
                     "format": "int64"
651 768
                 },
652 769
                 "urine_protein_24h_time": {
653
-                    "description": "24小时尿蛋白检测时间",
654
-                    "type": "string",
655
-                    "format": "datetime"
770
+                    "description": "24小时尿蛋白检测时间 yyyy-MM-dd HH:mm:ss",
771
+                    "type": "string"
656 772
                 },
657 773
                 "urine_protein_24h_unit": {
658 774
                     "description": "24小时尿蛋白单位(g/24h,mg/24h)",
659 775
                     "type": "string"
660 776
                 },
661 777
                 "urine_protein_time": {
662
-                    "description": "尿蛋白检测时间",
663
-                    "type": "string",
664
-                    "format": "datetime"
778
+                    "description": "尿蛋白检测时间 yyyy-MM-dd HH:mm:ss",
779
+                    "type": "string"
665 780
                 },
666 781
                 "urine_protein_unit": {
667 782
                     "description": "尿蛋白单位(g,mg)",
@@ -708,6 +823,10 @@
708 823
                 }
709 824
             }
710 825
         },
826
+        "models.Time": {
827
+            "title": "Time",
828
+            "type": "object"
829
+        },
711 830
         "models.UserInfoResp": {
712 831
             "title": "UserInfoResp",
713 832
             "type": "object",
@@ -717,9 +836,8 @@
717 836
                     "type": "string"
718 837
                 },
719 838
                 "ctime": {
720
-                    "description": "创建时间",
721
-                    "type": "string",
722
-                    "format": "datetime"
839
+                    "$ref": "#/definitions/models.Time",
840
+                    "description": "创建时间"
723 841
                 },
724 842
                 "email": {
725 843
                     "description": "邮件",
@@ -739,9 +857,8 @@
739 857
                     "type": "string"
740 858
                 },
741 859
                 "mtime": {
742
-                    "description": "更新时间 ",
743
-                    "type": "string",
744
-                    "format": "datetime"
860
+                    "$ref": "#/definitions/models.Time",
861
+                    "description": "更新时间 "
745 862
                 },
746 863
                 "nick_name": {
747 864
                     "description": "昵称",
@@ -751,6 +868,10 @@
751 868
                     "description": "OpenID",
752 869
                     "type": "string"
753 870
                 },
871
+                "patient_id": {
872
+                    "type": "integer",
873
+                    "format": "int64"
874
+                },
754 875
                 "phone": {
755 876
                     "description": "手机号码",
756 877
                     "type": "string"
@@ -776,6 +897,10 @@
776 897
                 "union_id": {
777 898
                     "description": "unionid",
778 899
                     "type": "string"
900
+                },
901
+                "user_org_id": {
902
+                    "type": "integer",
903
+                    "format": "int64"
779 904
                 }
780 905
             }
781 906
         },
@@ -795,8 +920,16 @@
795 920
                 "openid": {
796 921
                     "type": "string"
797 922
                 },
923
+                "patient_id": {
924
+                    "type": "integer",
925
+                    "format": "int64"
926
+                },
798 927
                 "token": {
799 928
                     "type": "string"
929
+                },
930
+                "user_org_id": {
931
+                    "type": "integer",
932
+                    "format": "int64"
800 933
                 }
801 934
             }
802 935
         },
@@ -835,6 +968,10 @@
835 968
                     "description": "OpenID",
836 969
                     "type": "string"
837 970
                 },
971
+                "patient_id": {
972
+                    "type": "integer",
973
+                    "format": "int64"
974
+                },
838 975
                 "phone": {
839 976
                     "description": "手机号码",
840 977
                     "type": "string"
@@ -864,6 +1001,10 @@
864 1001
                 "union_id": {
865 1002
                     "description": "unionid",
866 1003
                     "type": "string"
1004
+                },
1005
+                "user_org_id": {
1006
+                    "type": "integer",
1007
+                    "format": "int64"
867 1008
                 }
868 1009
             }
869 1010
         }

+ 121 - 27
swagger/swagger.yml Dosyayı Görüntüle

@@ -8,6 +8,92 @@ info:
8 8
     name: 领透科技
9 9
 basePath: /xcx
10 10
 paths:
11
+  /api/device/binddevice:
12
+    post:
13
+      tags:
14
+      - api/device
15
+      description: |-
16
+        绑定设备
17
+        <br>
18
+      operationId: DeviceApiController.BindDevice
19
+      parameters:
20
+      - in: query
21
+        name: qrcode
22
+        description: 设备二维码
23
+        required: true
24
+        type: string
25
+      responses:
26
+        "200":
27
+          description: success
28
+        "500":
29
+          description: error
30
+      security:
31
+      - token: []
32
+  /api/device/getdevicedetail:
33
+    get:
34
+      tags:
35
+      - api/device
36
+      description: |-
37
+        根据设备ID获取设备详细信息
38
+        <br>
39
+      operationId: DeviceApiController.GetDeviceDetail
40
+      parameters:
41
+      - in: query
42
+        name: deviceid
43
+        description: 设备ID
44
+        required: true
45
+        type: integer
46
+        format: int64
47
+      responses:
48
+        "200":
49
+          description: success
50
+          schema:
51
+            $ref: '#/definitions/models.Device'
52
+        "500":
53
+          description: error
54
+      security:
55
+      - token: []
56
+  /api/device/getmydevices:
57
+    get:
58
+      tags:
59
+      - api/device
60
+      description: |-
61
+        获取绑定的设备列表
62
+        <br>
63
+      operationId: DeviceApiController.GetMyDevices
64
+      responses:
65
+        "200":
66
+          description: success
67
+          schema:
68
+            type: array
69
+            items:
70
+              $ref: '#/definitions/models.Device'
71
+        "500":
72
+          description: error
73
+      security:
74
+      - token: []
75
+  /api/device/unbinddevice:
76
+    post:
77
+      tags:
78
+      - api/device
79
+      description: |-
80
+        解绑设备
81
+        <br>
82
+      operationId: DeviceApiController.UnBindDevice
83
+      parameters:
84
+      - in: query
85
+        name: deviceid
86
+        description: 设备ID
87
+        required: true
88
+        type: integer
89
+        format: int64
90
+      responses:
91
+        "200":
92
+          description: success
93
+        "500":
94
+          description: error
95
+      security:
96
+      - token: []
11 97
   /api/sysdic/getcheckitems:
12 98
     get:
13 99
       tags:
@@ -324,9 +410,8 @@ definitions:
324 410
         description: 生产日期
325 411
         type: integer
326 412
         format: int64
327
-      qr_code_id:
328
-        type: integer
329
-        format: int64
413
+      qr_code:
414
+        type: string
330 415
       sensor_mode:
331 416
         description: 传感放大倍数
332 417
         type: string
@@ -361,16 +446,14 @@ definitions:
361 446
     type: object
362 447
     properties:
363 448
       birthday:
449
+        $ref: '#/definitions/models.Time'
364 450
         description: 生日
365
-        type: string
366
-        format: datetime
367 451
       blood_type:
368 452
         description: 血型
369 453
         type: string
370 454
       creatine_time:
455
+        $ref: '#/definitions/models.Time'
371 456
         description: 肌酐检测时间
372
-        type: string
373
-        format: datetime
374 457
       creatinine:
375 458
         description: 血肌酐
376 459
         type: integer
@@ -379,9 +462,8 @@ definitions:
379 462
         description: 肌酐单位(umol/L,mg/dl)
380 463
         type: string
381 464
       ctime:
465
+        $ref: '#/definitions/models.Time'
382 466
         description: 创建时间
383
-        type: string
384
-        format: datetime
385 467
       gender:
386 468
         description: 性别(0:未知 1:男 2:女)
387 469
         type: integer
@@ -398,9 +480,8 @@ definitions:
398 480
         description: 病情
399 481
         type: string
400 482
       mtime:
483
+        $ref: '#/definitions/models.Time'
401 484
         description: '更新时间 '
402
-        type: string
403
-        format: datetime
404 485
       renal_function_status:
405 486
         description: '肾功能情况(0:未透析,1: 血液透析,2:腹膜透析,3:肾脏移植)'
406 487
         type: integer
@@ -418,16 +499,14 @@ definitions:
418 499
         type: integer
419 500
         format: int64
420 501
       urine_protein_24h_time:
502
+        $ref: '#/definitions/models.Time'
421 503
         description: 24小时尿蛋白检测时间
422
-        type: string
423
-        format: datetime
424 504
       urine_protein_24h_unit:
425 505
         description: 24小时尿蛋白单位(g/24h,mg/24h)
426 506
         type: string
427 507
       urine_protein_time:
508
+        $ref: '#/definitions/models.Time'
428 509
         description: 尿蛋白检测时间
429
-        type: string
430
-        format: datetime
431 510
       urine_protein_unit:
432 511
         description: 尿蛋白单位(g,mg)
433 512
         type: string
@@ -440,16 +519,14 @@ definitions:
440 519
     type: object
441 520
     properties:
442 521
       birthday:
443
-        description: 生日
522
+        description: 生日 yyyy-MM-dd HH:mm:ss
444 523
         type: string
445
-        format: datetime
446 524
       blood_type:
447 525
         description: 血型
448 526
         type: string
449 527
       creatine_time:
450
-        description: 肌酐检测时间
528
+        description: 肌酐检测时间 yyyy-MM-dd HH:mm:ss
451 529
         type: string
452
-        format: datetime
453 530
       creatinine:
454 531
         description: 血肌酐
455 532
         type: integer
@@ -481,16 +558,14 @@ definitions:
481 558
         type: integer
482 559
         format: int64
483 560
       urine_protein_24h_time:
484
-        description: 24小时尿蛋白检测时间
561
+        description: 24小时尿蛋白检测时间 yyyy-MM-dd HH:mm:ss
485 562
         type: string
486
-        format: datetime
487 563
       urine_protein_24h_unit:
488 564
         description: 24小时尿蛋白单位(g/24h,mg/24h)
489 565
         type: string
490 566
       urine_protein_time:
491
-        description: 尿蛋白检测时间
567
+        description: 尿蛋白检测时间 yyyy-MM-dd HH:mm:ss
492 568
         type: string
493
-        format: datetime
494 569
       urine_protein_unit:
495 570
         description: 尿蛋白单位(g,mg)
496 571
         type: string
@@ -523,6 +598,9 @@ definitions:
523 598
       real_name:
524 599
         description: 真实姓名
525 600
         type: string
601
+  models.Time:
602
+    title: Time
603
+    type: object
526 604
   models.UserInfoResp:
527 605
     title: UserInfoResp
528 606
     type: object
@@ -531,9 +609,8 @@ definitions:
531 609
         description: 头像
532 610
         type: string
533 611
       ctime:
612
+        $ref: '#/definitions/models.Time'
534 613
         description: 创建时间
535
-        type: string
536
-        format: datetime
537 614
       email:
538 615
         description: 邮件
539 616
         type: string
@@ -548,15 +625,17 @@ definitions:
548 625
         description: 住院登记手机号
549 626
         type: string
550 627
       mtime:
628
+        $ref: '#/definitions/models.Time'
551 629
         description: '更新时间 '
552
-        type: string
553
-        format: datetime
554 630
       nick_name:
555 631
         description: 昵称
556 632
         type: string
557 633
       open_id:
558 634
         description: OpenID
559 635
         type: string
636
+      patient_id:
637
+        type: integer
638
+        format: int64
560 639
       phone:
561 640
         description: 手机号码
562 641
         type: string
@@ -577,6 +656,9 @@ definitions:
577 656
       union_id:
578 657
         description: unionid
579 658
         type: string
659
+      user_org_id:
660
+        type: integer
661
+        format: int64
580 662
   models.WxXcxLoginReq:
581 663
     title: WxXcxLoginReq
582 664
     type: object
@@ -589,8 +671,14 @@ definitions:
589 671
     properties:
590 672
       openid:
591 673
         type: string
674
+      patient_id:
675
+        type: integer
676
+        format: int64
592 677
       token:
593 678
         type: string
679
+      user_org_id:
680
+        type: integer
681
+        format: int64
594 682
   models.XcxUser:
595 683
     title: XcxUser
596 684
     type: object
@@ -619,6 +707,9 @@ definitions:
619 707
       open_id:
620 708
         description: OpenID
621 709
         type: string
710
+      patient_id:
711
+        type: integer
712
+        format: int64
622 713
       phone:
623 714
         description: 手机号码
624 715
         type: string
@@ -642,6 +733,9 @@ definitions:
642 733
       union_id:
643 734
         description: unionid
644 735
         type: string
736
+      user_org_id:
737
+        type: integer
738
+        format: int64
645 739
 securityDefinitions:
646 740
   token:
647 741
     type: apiKey

+ 29 - 12
tests/default_test.go Dosyayı Görüntüle

@@ -8,6 +8,7 @@ import (
8 8
 	"runtime"
9 9
 	"strconv"
10 10
 	"strings"
11
+	"sws_xcx/enums"
11 12
 	"sws_xcx/models"
12 13
 	_ "sws_xcx/routers"
13 14
 	"sws_xcx/service"
@@ -81,28 +82,29 @@ func TestHandleMsg(t *testing.T) {
81 82
 
82 83
 	req := []byte(`{"publish_received_at":1722839054218,"pub_props":{"User-Property":{}},"peerhost":"124.133.43.122","qos":0,"topic":"/CH-U100/09012201100010104/user/checkresult","clientid":"42915152F3F1","payload":"{\"productKey\":\"CH-U100\",\"deviceName\":\"09012201100010104\",\"acc\":12378,\"type\":0,\"count\":14,\"datatype\":0,\"verifycode\":212,\"data\":\"0,0,0,2,2,0,0,0,0,0,4,3,0,1\",\"origin\":\"4243305A0000010E0000000202000000000004030001D4\",\"len\":23}","username":"09012201100010104","event":"message.publish","metadata":{"rule_id":"checkresult"},"timestamp":1722839054218,"node":"emqx@127.0.0.1","id":"00061EE9B9D4F6AFF445000924860003","flags":{"retain":false,"dup":false}}`)
83 84
 
84
-	const EventType string = "emq"
85
-	msg := &models.OpenEmqMsgReqV0{}
85
+	msg := &models.OpenEmqMsgReqVO{}
86 86
 	err := json.Unmarshal(req, msg)
87 87
 	if err != nil {
88 88
 		t.Error(err)
89
+		return
89 90
 	}
90 91
 
91 92
 	ds := service.NewDeviceService()
92 93
 
93
-	device, err := ds.GetDeviceByNo(msg.DeviceName)
94
+	device, err := ds.GetDeviceByNo(msg.UserName)
94 95
 	if err != nil && err != gorm.ErrRecordNotFound {
95 96
 		utils.ErrorLog("GetDeviceByNo %v:", err)
96 97
 		t.Error(err)
98
+		return
97 99
 	}
98
-	if device == nil {
100
+	if device.Id == 0 {
99 101
 		utils.WarningLog("非本系统设备,数据废弃")
100 102
 		return
101 103
 	}
102 104
 	err = ds.CreateDeviceMessageLog(models.DeviceMessageLog{
103 105
 		DeviceName: msg.DeviceName,
104 106
 		Content:    string(req),
105
-		EventType:  EventType,
107
+		EventType:  enums.EventTypeEmqx,
106 108
 		MessageId:  msg.Id,
107 109
 		Topic:      msg.Topic,
108 110
 	})
@@ -110,12 +112,14 @@ func TestHandleMsg(t *testing.T) {
110 112
 	if err != nil {
111 113
 		utils.ErrorLog("CreateDeviceMessageLog %v:", err)
112 114
 		t.Error(err)
115
+		return
113 116
 	}
114 117
 	payload := &models.OpenEmqPayloadReqVO{}
115 118
 	err = json.Unmarshal([]byte(msg.Payload), payload)
116 119
 	if err != nil {
117 120
 		utils.ErrorLog("json.Unmarshal %v:", err)
118 121
 		t.Error(err)
122
+		return
119 123
 	}
120 124
 	if payload.Len != 23 {
121 125
 		utils.WarningLog("非标准数据,数据废弃:%v", msg.Payload)
@@ -125,12 +129,13 @@ func TestHandleMsg(t *testing.T) {
125 129
 	if err != nil {
126 130
 		utils.ErrorLog("GetDeviceRelateByDeviceId %v:", err)
127 131
 		t.Error(err)
132
+		return
128 133
 	}
129 134
 
130 135
 	checkRecord := &models.CheckRecord{
131 136
 
132 137
 		Acc:          payload.Acc,
133
-		PutSources:   EventType,
138
+		PutSources:   enums.EventTypeEmqx,
134 139
 		MessageId:    msg.Id,
135 140
 		DeviceId:     device.Id,
136 141
 		UserId:       dr.UserId,
@@ -143,6 +148,7 @@ func TestHandleMsg(t *testing.T) {
143 148
 		if err != nil {
144 149
 			utils.ErrorLog("GetUserHealthProfileByUserId %v:", err)
145 150
 			t.Error(err)
151
+			return
146 152
 		}
147 153
 		checkRecord.UserHealthProfileId = int64(hp.Id)
148 154
 	}
@@ -151,6 +157,7 @@ func TestHandleMsg(t *testing.T) {
151 157
 	if err != nil {
152 158
 		utils.ErrorLog("CreateCheckRecord %v:", err)
153 159
 		t.Error(err)
160
+		return
154 161
 	}
155 162
 	t.Log(checkRecord.Id)
156 163
 	t.Log(payload.Data)
@@ -169,28 +176,39 @@ func TestHandleMsg(t *testing.T) {
169 176
 	if err != nil {
170 177
 		utils.ErrorLog("GetCheckItems %v:", err)
171 178
 		t.Error(err)
179
+		return
172 180
 	}
173 181
 
174 182
 	if len(checkItems) < count {
175 183
 		t.Error("接收的数据于检查项目配置不一致")
184
+		return
176 185
 	}
177 186
 
178 187
 	alerts := make([]string, 0)
179 188
 	for i := 0; i < count; i++ {
180 189
 		vi, _ := strconv.Atoi(da[i])
181
-		err = createCheckRecordItem(checkItems, checkRecord.Id, alerts, vi, i+1)
190
+		err = createCheckRecordItem(checkItems, checkRecord.Id, &alerts, vi, i+1, crs)
182 191
 		if err != nil {
183 192
 			utils.ErrorLog("createCheckRecordItem valule:%v, err:%v:", vi, err)
184 193
 		}
185 194
 	}
186 195
 
187 196
 	if len(alerts) > 0 {
188
-		//save alerts
197
+		alertItemIds := strings.Join(alerts, ",")
198
+		err = crs.UpdateCheckRecordAlertItems(checkRecord.Id, alertItemIds)
199
+		if err != nil {
200
+			utils.ErrorLog("UpdateCheckRecordAlertItems %v:", err)
201
+			t.Error(err)
202
+			return
203
+		}
204
+
205
+	} else {
206
+		utils.TraceLog("无异常数据")
189 207
 	}
190 208
 
191 209
 }
192 210
 
193
-func createCheckRecordItem(items []*models.CheckItem, crId int64, alerts []string, vi, n int) error {
211
+func createCheckRecordItem(items []*models.CheckItem, crId int64, alerts *[]string, vi, n int, crs *service.CheckRecordService) error {
194 212
 	item := findItem(items, n)
195 213
 	if item == nil {
196 214
 		return fmt.Errorf("检测项目不匹配,需要检查基础数据!序号:%v", n)
@@ -214,10 +232,9 @@ func createCheckRecordItem(items []*models.CheckItem, crId int64, alerts []strin
214 232
 
215 233
 	cri.CheckValue = scope.Value
216 234
 	if scope.Type == 1 {
217
-		alerts = append(alerts, strconv.Itoa(n))
235
+		*alerts = append(*alerts, strconv.Itoa(n))
218 236
 	}
219
-	//create cri
220
-	return nil
237
+	return crs.CreateCheckRecordItem(&cri)
221 238
 }
222 239
 
223 240
 func findScope(scopes []*models.CheckItemScopeVO, vi int) *models.CheckItemScopeVO {

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

@@ -86,14 +86,14 @@ func TestHealthProfileService_SaveHealthProfile(t *testing.T) {
86 86
 func TestGetMobilePatientInfo(t *testing.T) {
87 87
 
88 88
 	s := service.NewXcxUserService()
89
-	mobile := "13058102387"
90
-	name := "李搜"
91
-	idcard := "111222900901222"
89
+	mobile := "13414858017"
90
+	name := "邹土贵"
91
+	idcard := "440804195502141115"
92 92
 
93 93
 	p, err := s.GetMobilePatientInfo(mobile, name, idcard)
94 94
 	if err != nil {
95 95
 		t.Error(err)
96 96
 		return
97 97
 	}
98
-	t.Logf("%+v", p)
98
+	t.Logf("id: %d orgid: %d", p.ID, p.UserOrgId)
99 99
 }