Просмотр исходного кода

Merge branch '20211122' of http://git.shengws.com/csx/XT_New into 20211122

csx 3 лет назад
Родитель
Сommit
053753a306
58 измененных файлов: 86 добавлений и 25392 удалений
  1. 2 2
      conf/app.conf
  2. 32 14
      controllers/drug_stock_api_contorller.go
  3. 1 12
      controllers/schedule_api_controller.go
  4. 0 400
      models/service/admin_service.go
  5. 0 231
      models/service/app_version.go
  6. 0 45
      models/service/auto_clear_schedules_service.go
  7. 0 148
      models/service/auto_create_staff_schedule_service.go
  8. 0 261
      models/service/auto_create_week_disinfection.go
  9. 0 149
      models/service/auto_create_week_plan.go
  10. 0 281
      models/service/auto_create_week_schedules_service.go
  11. 0 3319
      models/service/common_service.go
  12. 0 239
      models/service/data.go
  13. 0 290
      models/service/db.go
  14. 0 27
      models/service/db_err_service.go
  15. 0 715
      models/service/device_service.go
  16. 0 304
      models/service/dialysis_parameter_service.go
  17. 0 1083
      models/service/dialysis_service.go
  18. 0 84
      models/service/district_service.go
  19. 0 345
      models/service/doctor_advice_service.go
  20. 0 617
      models/service/doctor_schedule_service.go
  21. 0 165
      models/service/gobal_config_service.go
  22. 0 37
      models/service/home_service.go
  23. 0 213
      models/service/inspection_service.go
  24. 0 120
      models/service/integration_service.go
  25. 0 55
      models/service/invoice_service.go
  26. 0 246
      models/service/login_service.go
  27. 0 1238
      models/service/manage_service.go
  28. 0 69
      models/service/management_service/management_analyse_service.go
  29. 0 103
      models/service/management_service/management_models.go
  30. 0 1672
      models/service/mobile_dialysis_service.go
  31. 0 144
      models/service/new_sms_service.go
  32. 0 202
      models/service/orginfo_service.go
  33. 0 64
      models/service/patient_dataconfig_service.go
  34. 0 523
      models/service/patient_schedule_template_service.go
  35. 0 1361
      models/service/patient_service.go
  36. 0 1446
      models/service/patientmanage_service.go
  37. 0 149
      models/service/pay_service.go
  38. 0 723
      models/service/print_data_service/schedule_dialysis/print_schedule_dialysis_models.go
  39. 0 188
      models/service/print_data_service/schedule_dialysis/print_schedule_dialysis_service.go
  40. 0 1370
      models/service/qcd_service.go
  41. 0 20
      models/service/redis.go
  42. 0 34
      models/service/regist_service.go
  43. 0 763
      models/service/role_service.go
  44. 0 536
      models/service/schedule_service.go
  45. 0 270
      models/service/sign_weigh_service.go
  46. 0 185
      models/service/sms_service.go
  47. 0 73
      models/service/statistics_service.go
  48. 0 1778
      models/service/statistics_service/index_evaluation_service.go
  49. 0 185
      models/service/statistics_service/index_models.go
  50. 0 2131
      models/service/stock_service.go
  51. 0 34
      models/service/subscibe_service.go
  52. 0 160
      models/service/user_service.go
  53. 0 449
      models/service/verify_login_token_service.go
  54. 0 105
      models/service/vm_service.go
  55. 10 5
      service/gobal_config_service.go
  56. 2 2
      service/schedule_service.go
  57. 37 6
      service/stock_service.go
  58. 2 2
      service/warhouse_service.go

+ 2 - 2
conf/app.conf Просмотреть файл

@@ -1,6 +1,6 @@
1 1
 appname = 血透
2
-httpport = 9531
3
-runmode = prod
2
+httpport = 9529
3
+runmode = dev
4 4
 
5 5
 #
6 6
 copyrequestbody = true

+ 32 - 14
controllers/drug_stock_api_contorller.go Просмотреть файл

@@ -587,8 +587,8 @@ func (c *StockDrugApiController) EditDrugWarehouse() {
587 587
 						StockMaxNumber:   warehousing_count,
588 588
 					}
589 589
 					if max_unit == min_unit {
590
-						warehouseInfo.StockMaxNumber = 0
591
-						warehouseInfo.StockMinNumber = warehousing_count
590
+						warehouseInfo.StockMaxNumber = warehousing_count
591
+						warehouseInfo.StockMinNumber = 0
592 592
 						warehouseInfo.MaxUnit = min_unit
593 593
 					}
594 594
 					warehousingInfo = append(warehousingInfo, warehouseInfo)
@@ -620,8 +620,8 @@ func (c *StockDrugApiController) EditDrugWarehouse() {
620 620
 						BatchNumber:      batch_number,
621 621
 					}
622 622
 					if max_unit == min_unit {
623
-						warehouseInfo.StockMaxNumber = 0
624
-						warehouseInfo.StockMinNumber = warehousing_count
623
+						warehouseInfo.StockMaxNumber = warehousing_count
624
+						warehouseInfo.StockMinNumber = 0
625 625
 						warehouseInfo.MaxUnit = min_unit
626 626
 					}
627 627
 
@@ -1470,11 +1470,7 @@ func (c *StockDrugApiController) CreateDrugWarehouseOut() {
1470 1470
 			return
1471 1471
 		} else {
1472 1472
 			service.AddSigleDrugWarehouseOut(&warehouseOut)
1473
-			//list, _ := service.GetLastWarehouseOut(adminUserInfo.CurrentOrgId)
1474
-			//for _, item := range drugFlow {
1475
-			//	item.WarehouseOutId = list.ID
1476
-			//}
1477
-			//service.CreateDrugFlow(drugFlow)
1473
+
1478 1474
 			// 出库流程
1479 1475
 			// 1.查询改药品在药品库的规格信息,并将处方里的规格进行换算(尽量将拆零单位转换成包装单位)
1480 1476
 			drup, _ := service.FindBaseDrugLibRecord(item.OrgId, item.DrugId)
@@ -1592,14 +1588,24 @@ func (c *StockDrugApiController) DeleteDrugWarehouseOut() {
1592 1588
 }
1593 1589
 func (this *StockDrugApiController) DeleteDrugWarehouseOutInfo() {
1594 1590
 	id, _ := this.GetInt64("id", 0)
1595
-	fmt.Println(id)
1596 1591
 	if id == 0 {
1597 1592
 		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
1598 1593
 		return
1599 1594
 	}
1595
+	//查询详情
1596
+	info, _ := service.GetDrugWarehosueOutInfo(id)
1597
+	drug, _ := service.GetBaseDrugMedical(info.DrugId)
1600 1598
 
1599
+	if info.CountUnit == drug.MaxUnit {
1600
+		//回退库存
1601
+		service.ModeifyDrugWarehosueInfo(info.WarehouseInfoId, info.Count)
1602
+	}
1603
+	if info.CountUnit == drug.MinUnit && drug.MaxUnit != drug.MinUnit {
1604
+		service.ModeFyStockMinById(info.WarehouseInfoId, info.Count)
1605
+	}
1606
+	//删除流水
1607
+	service.DeleteDrugWarehouseOutInfoById(info.ID)
1601 1608
 	err := service.UpDateDrugWarehouseOutStatus(id)
1602
-	service.DeleteDrugWarehouseOutInfoById(id)
1603 1609
 	if err != nil {
1604 1610
 		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDeleteFail)
1605 1611
 	} else {
@@ -2695,7 +2701,7 @@ func (this *StockDrugApiController) DeleteDrugCancelStock() {
2695 2701
 			//回退库存
2696 2702
 			service.ModifyDrugWarehouseByInfoId(item.CancelStockId, item.Count)
2697 2703
 		}
2698
-		if item.MaxUnit == medical.MinUnit {
2704
+		if item.MaxUnit == medical.MinUnit && medical.MaxUnit != medical.MinUnit {
2699 2705
 			service.ModifyDrugWarehouseByStockMin(item.CancelStockId, item.Count)
2700 2706
 		}
2701 2707
 	}
@@ -2716,9 +2722,21 @@ func (this *StockDrugApiController) DeleteDrugCancelStockInfo() {
2716 2722
 		return
2717 2723
 	}
2718 2724
 
2719
-	err := service.UpDateDrugCancleStockStatus(id)
2725
+	//查询
2726
+	cancelinfo, _ := service.GetDrugCancelById(id)
2720 2727
 
2721
-	service.UpDateDrugCancelStockById(id)
2728
+	drug, _ := service.GetBaseDrugMedical(cancelinfo.DrugId)
2729
+	if drug.MaxUnit == cancelinfo.MaxUnit {
2730
+		service.ModeFyDrugWareseInfo(cancelinfo.BatchNumberId, cancelinfo.Count)
2731
+	}
2732
+	if drug.MinUnit == cancelinfo.MaxUnit && drug.MaxUnit != drug.MinUnit {
2733
+		service.ModeFyDrugWarehouseMin(cancelinfo.BatchNumberId, cancelinfo.Count)
2734
+	}
2735
+	//扣减库存
2736
+
2737
+	err := service.UpDateDrugCancleStockStatus(id)
2738
+	//删除流水
2739
+	service.UpDateDrugCancelStockById(cancelinfo.ID)
2722 2740
 	if err != nil {
2723 2741
 		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDeleteFail)
2724 2742
 	} else {

+ 1 - 12
controllers/schedule_api_controller.go Просмотреть файл

@@ -1417,27 +1417,16 @@ func (this *ScheduleApiController) ExportSchedule() {
1417 1417
 			schedule_date := time.Now().Format("2006-01-02")
1418 1418
 			date, _ := utils.ParseTimeStringToTime("2006-01-02", schedule_date)
1419 1419
 			clear_schedule_date := date.Unix() //根据日期去清除,该日期未来的排班数据
1420
-			//	err := service.UpdateScheduleStatus(clear_schedule_date, this.GetAdminUserInfo().CurrentOrgId)
1421 1420
 			if err == nil {
1422
-				//清除该机构的排班
1423
-				//if delete_type == 1 {
1424
-				//  service.ModeScheduleByTimeOne(theTimeStart.Unix(), theTimeEnd.Unix(), this.GetAdminUserInfo().CurrentOrgId)
1425
-				//}
1426
-				//if delete_type == 0 {
1427
-				//  service.ModeScheduleByTime(theTimeStart.Unix(), theTimeEnd.Unix(), this.GetAdminUserInfo().CurrentOrgId)
1428
-				//}
1429 1421
 
1430 1422
 				for _, item := range schedules {
1431
-					// fmt.Println("clear_schedule_date3232232332232332232323",clear_schedule_date)
1432 1423
 					if item.ScheduleDate > clear_schedule_date {
1433
-						//删除当天的以后日期排班
1434
-						// service.DeleteScheduleExist(item.ScheduleDate, item.UserOrgId)
1435 1424
 						//查找当天日期是否存在
1436 1425
 						_, errcode := service.GetTodayScheduleIsExistOne(item.PatientId, item.ScheduleDate, item.UserOrgId)
1437 1426
 						if errcode == gorm.ErrRecordNotFound {
1438 1427
 
1439 1428
 							//清除当天该床位已有的患者
1440
-							service.ModeFyScheduleById(item.ScheduleDate, item.BedId, item.ScheduleType)
1429
+							service.ModeFyScheduleById(item.ScheduleDate, item.BedId, item.ScheduleType, item.UserOrgId)
1441 1430
 							service.CreateSchedule(item)
1442 1431
 						} else if errcode == nil {
1443 1432
 							schedule := models.XtSchedule{

+ 0 - 400
models/service/admin_service.go Просмотреть файл

@@ -1,400 +0,0 @@
1
-// 统计后台的 service
2
-
3
-package service
4
-
5
-import (
6
-	"XT_New/models"
7
-	"XT_New/models/admin_models"
8
-	"time"
9
-
10
-	"github.com/jinzhu/gorm"
11
-)
12
-
13
-func GetAdminAccount(account string, password string) (*admin_models.AdminAccount, error) {
14
-	var model admin_models.AdminAccount
15
-	err := readUserDb.Where("account = ? AND pwd = ? AND status = 1", account, password).First(&model).Error
16
-	if err != nil {
17
-		if err == gorm.ErrRecordNotFound {
18
-			return nil, nil
19
-		}
20
-		return nil, err
21
-	}
22
-	return &model, nil
23
-}
24
-
25
-// 获取总机构数
26
-func GetTotalOrgCount() (int, error) {
27
-	var count int
28
-	err := readUserDb.Model(&models.Org{}).Where("status <> 0").Count(&count).Error
29
-	if err != nil {
30
-		return 0, err
31
-	}
32
-	return count, nil
33
-}
34
-
35
-// 获取一段时间内注册的机构数量
36
-func GetRegistedOrgCountFromDayToDay(from time.Time, to time.Time) (int, error) {
37
-	var count int
38
-	err := readUserDb.Model(&models.Org{}).Where("status <> 0 AND ctime >= ? AND ctime <= ?", from.Unix(), to.Unix()).Count(&count).Error
39
-	if err != nil {
40
-		return 0, err
41
-	}
42
-	return count, nil
43
-}
44
-
45
-// 获取一段时间内注册的机构
46
-func GetRegistedOrgsFromDayToDay(from time.Time, to time.Time) ([]*models.Org, error) {
47
-	var orgs []*models.Org
48
-	err := readUserDb.Model(&models.Org{}).Where("status <> 0 AND ctime >= ? AND ctime <= ?", from.Unix(), to.Unix()).Find(&orgs).Error
49
-	if err != nil {
50
-		return nil, err
51
-	}
52
-	return orgs, nil
53
-}
54
-
55
-// 获取一段时间内的活跃机构数
56
-func GetActiveOrgCountFromDayToDay(from time.Time, to time.Time) (int, error) {
57
-	var count int
58
-	rows, err := readUserDb.Raw("SELECT COUNT(DISTINCT org_id) AS count FROM sgj_user_admin_login_log WHERE ctime >= ? AND ctime <= ?", from.Unix(), to.Unix()).Rows()
59
-	if err != nil {
60
-		return 0, err
61
-	}
62
-	if rows.Next() {
63
-		rows.Scan(&count)
64
-	}
65
-	return count, nil
66
-}
67
-
68
-type ActiveOrgListVM struct {
69
-	models.Org
70
-	ActiveTime int64 `gorm:"column:active_time" json:"active_time"`
71
-}
72
-
73
-// 获取一段时间内的活跃机构
74
-func GetActiveOrgsFromDayToDay(from time.Time, to time.Time) ([]*ActiveOrgListVM, error) {
75
-	var orgs []*ActiveOrgListVM
76
-	err := readUserDb.Raw("select * from (select log.org_id, org.*, log.ctime as active_time from sgj_user_admin_login_log as log left join sgj_user_org as org on log.org_id = org.id where log.ctime >= ? AND log.ctime <= ? AND org.status <> 0 order by log.ctime desc) as t group by t.org_id;", from.Unix(), to.Unix()).Scan(&orgs).Error
77
-	if err != nil {
78
-		return nil, err
79
-	}
80
-	return orgs, nil
81
-}
82
-
83
-// 获取一段时间内的活跃账户数
84
-func GetActiveAdminUserCountFromDayToDay(from time.Time, to time.Time) (int, error) {
85
-	var count int
86
-	rows, err := readUserDb.Raw("SELECT COUNT(DISTINCT admin_user_id) AS count FROM sgj_user_admin_login_log WHERE ctime >= ? AND ctime <= ? AND operate_type = 1", from.Unix(), to.Unix()).Rows()
87
-	if err != nil {
88
-		return 0, err
89
-	}
90
-	if rows.Next() {
91
-		rows.Scan(&count)
92
-	}
93
-	return count, nil
94
-}
95
-
96
-type ActiveAdminUserListVM struct {
97
-	models.App_Role
98
-	OrgName    string `gorm:"column:org_name" json:"org_name"`
99
-	ActiveTime int64  `gorm:"column:active_time" json:"active_time"`
100
-}
101
-
102
-// 获取一段时间内的活跃账户
103
-func GetActiveAdminUsersFromDayToDay(from time.Time, to time.Time) ([]*ActiveAdminUserListVM, error) {
104
-	var users []*ActiveAdminUserListVM
105
-	err := readUserDb.Raw("select * from (select log.admin_user_id as uid, admin.*, org.org_name, log.ctime as active_time from sgj_user_admin_login_log as log left join sgj_user_admin_role as admin on log.admin_user_id = admin.admin_user_id left join sgj_user_org as org on log.org_id = org.id where log.ctime >= ? AND log.ctime <= ? AND log.operate_type = 1 AND admin.status > 0 order by log.ctime desc) as t group by t.uid;", from.Unix(), to.Unix()).Scan(&users).Error
106
-	if err != nil {
107
-		return nil, err
108
-	}
109
-	return users, nil
110
-}
111
-
112
-// 获取即将到期机构数
113
-func GetWillExpireOrgCountFromDayToDay(from time.Time, to time.Time) (int, error) {
114
-	var count int
115
-	rows, err := readUserDb.Raw("SELECT COUNT(DISTINCT org_id) AS count FROM sgj_serve_subscibe WHERE period_end >= ? AND period_end <= ? AND state <> 9 GROUP BY org_id;", from.Unix(), to.Unix()).Rows()
116
-	if err != nil {
117
-		return 0, err
118
-	}
119
-	if rows.Next() {
120
-		rows.Scan(&count)
121
-	}
122
-	return count, nil
123
-}
124
-
125
-// 获取已到期机构数
126
-func GetDidExpiredOrgCountFromDayToDay(from time.Time, to time.Time) (int, error) {
127
-	var count int
128
-	rows, err := readUserDb.Raw("SELECT COUNT(DISTINCT org_id) AS count FROM sgj_serve_subscibe WHERE period_end >= ? AND period_end <= ? AND state <> 9 GROUP BY org_id;", from.Unix(), to.Unix()).Rows()
129
-	if err != nil {
130
-		return 0, err
131
-	}
132
-	if rows.Next() {
133
-		rows.Scan(&count)
134
-	}
135
-	return count, nil
136
-}
137
-
138
-type ExpireOrgListVM struct {
139
-	OrgID      int64  `gorm:"column:org_id" json:"org_id"`
140
-	OrgName    string `gorm:"column:org_name" json:"org_name"`
141
-	PeriodEnd  int64  `gorm:"column:period_end" json:"period_end"`
142
-	Telephone  string `gorm:"column:telephone" json:"telephone"`
143
-	ExpireDays int    `gorm:"-" json:"expire_days"`
144
-}
145
-
146
-// 获取即将到期机构
147
-func GetWillExpireOrgsFromDayToDay(from time.Time, to time.Time) ([]*ExpireOrgListVM, error) {
148
-	var vms []*ExpireOrgListVM
149
-	err := readUserDb.Raw("select s_o.org_id, s_o.period_end, o.org_name, o.telephone from (select ss.* from (select s.org_id as org_id, s.id as sid, s.period_end from sgj_serve_subscibe as s where s.period_end <= ? AND s.period_end >= ? AND s.state <> 9 order by s.id desc) as ss group by ss.org_id) as s_o left join sgj_user_org as o on o.id = s_o.org_id", to.Unix(), from.Unix()).Scan(&vms).Error
150
-	if err != nil {
151
-		return nil, err
152
-	}
153
-	for _, vm := range vms {
154
-		vm.ExpireDays = time.Unix(vm.PeriodEnd, 0).Day() - from.Day()
155
-	}
156
-	return vms, nil
157
-}
158
-
159
-// 获取已到期机构
160
-func GetDidExpireOrgsFromDayToDay(from time.Time, to time.Time) ([]*ExpireOrgListVM, error) {
161
-	var vms []*ExpireOrgListVM
162
-	err := readUserDb.Raw("select s_o.org_id, s_o.period_end, o.org_name, o.telephone from (select ss.* from (select s.org_id as org_id, s.id as sid, s.period_end from sgj_serve_subscibe as s where s.period_end >= ? AND s.period_end <= ? AND s.state <> 9 order by s.id desc) as ss group by ss.org_id) as s_o left join sgj_user_org as o on o.id = s_o.org_id", from.Unix(), to.Unix()).Scan(&vms).Error
163
-	if err != nil {
164
-		return nil, err
165
-	}
166
-	for _, vm := range vms {
167
-		vm.ExpireDays = to.Day() - time.Unix(vm.PeriodEnd, 0).Day()
168
-	}
169
-	return vms, nil
170
-}
171
-
172
-// 获取一段时间内的透析次数
173
-func GetDialysisTimesFromDayToDay(from time.Time, to time.Time) (int, error) {
174
-	var count int
175
-	err := readDb.Model(&models.DialysisOrder{}).Where("status > 0 AND dialysis_date >= ? AND dialysis_date <= ?", from.Unix(), to.Unix()).Count(&count).Error
176
-	if err != nil {
177
-		return 0, err
178
-	}
179
-	return count, nil
180
-}
181
-
182
-// 获取一段时间内的监控次数
183
-func GetMonitoringTimesFromDayToDay(from time.Time, to time.Time) (int, error) {
184
-	var count int
185
-	err := readDb.Model(&models.MonitoringRecord{}).Where("status > 0 AND monitoring_date >= ? AND monitoring_date <= ?", from.Unix(), to.Unix()).Count(&count).Error
186
-	if err != nil {
187
-		return 0, err
188
-	}
189
-	return count, nil
190
-}
191
-
192
-// 获取一段时间内新增病人数量
193
-func GetNewPatientCountFromDayToDay(from time.Time, to time.Time) (int, error) {
194
-	var count int
195
-	err := readDb.Model(&models.Patients{}).Where("status > 0 AND created_time >= ? AND created_time <= ?", from.Unix(), to.Unix()).Count(&count).Error
196
-	if err != nil {
197
-		return 0, err
198
-	}
199
-	return count, nil
200
-}
201
-
202
-// 获取病人性别分布
203
-func GetPatientGenderDistribution() (int, int, int, error) {
204
-	var maleCount, femaleCount, unknowGenderCount int
205
-	rows, err := readDb.Raw("SELECT count(id), gender FROM xt_patients WHERE (status > 0) group by gender;").Rows()
206
-	if err != nil {
207
-		return 0, 0, 0, err
208
-	}
209
-	for rows.Next() {
210
-		var gender, count int
211
-		rows.Scan(&count, &gender)
212
-		if gender == 1 {
213
-			maleCount = count
214
-		} else if gender == 2 {
215
-			femaleCount = count
216
-		} else {
217
-			unknowGenderCount = count
218
-		}
219
-	}
220
-	return maleCount, femaleCount, unknowGenderCount, nil
221
-}
222
-
223
-// 获取某种传染病的病人数,diseaseType = 0时为没有传染病
224
-// 1乙肝 2丙肝 3艾滋病 4肺结核 5梅毒
225
-func GetInfectiousDiseasePatientCount(diseaseType int) (int, error) {
226
-	if diseaseType == 0 {
227
-		var count int
228
-		rows, err := readDb.Raw("select count(p.id) from xt_patients as p where id not in (select p_d.patient_id from xt_patients_infectious_diseases as p_d where status = 1 group by p_d.patient_id) and status = 1;").Rows()
229
-		if err != nil {
230
-			return 0, err
231
-		}
232
-		if rows.Next() {
233
-			rows.Scan(&count)
234
-		}
235
-		return count, nil
236
-
237
-	} else {
238
-		var count int
239
-		rows, err := readDb.Raw("select count(distinct patient_id) from xt_patients_infectious_diseases where status = 1 and disease_id = ?;", diseaseType).Rows()
240
-		if err != nil {
241
-			return 0, err
242
-		}
243
-		if rows.Next() {
244
-			rows.Scan(&count)
245
-		}
246
-		return count, nil
247
-	}
248
-}
249
-
250
-// 获取患者年龄分布
251
-func GetPatientAgeDistribution() ([]*PatientAgeCountStruct, error) {
252
-	var counts []*PatientAgeCountStruct
253
-	err := readDb.Raw(`SELECT nnd AS 'age',COUNT(*) AS 'count' FROM (
254
-		SELECT
255
-			CASE
256
-				WHEN (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + (DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%m%d') <= DATE_FORMAT(NOW(), '%m%d'))<10 THEN '10'
257
-				WHEN (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + (DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%m%d') <= DATE_FORMAT(NOW(), '%m%d') )>=10 AND (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + (DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%m%d') <= DATE_FORMAT(NOW(), '%m%d') )<20 THEN '20'
258
-				WHEN (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + (DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%m%d') <= DATE_FORMAT(NOW(), '%m%d') )>=20 AND (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + (DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%m%d') <= DATE_FORMAT(NOW(), '%m%d') )<30 THEN '30'
259
-				WHEN (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + (DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%m%d') <= DATE_FORMAT(NOW(), '%m%d') )>=30 AND (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + (DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%m%d') <= DATE_FORMAT(NOW(), '%m%d') )<40 THEN '40'
260
-				WHEN (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + (DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%m%d') <= DATE_FORMAT(NOW(), '%m%d') )>=40 AND (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + (DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%m%d') <= DATE_FORMAT(NOW(), '%m%d') )<50 THEN '50'
261
-				WHEN (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + (DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%m%d') <= DATE_FORMAT(NOW(), '%m%d') )>=50 AND (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + (DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%m%d') <= DATE_FORMAT(NOW(), '%m%d') )<60 THEN '60'
262
-				WHEN (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + (DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%m%d') <= DATE_FORMAT(NOW(), '%m%d') )>=60 AND (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + (DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%m%d') <= DATE_FORMAT(NOW(), '%m%d') )<70 THEN '70'
263
-				WHEN (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + (DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%m%d') <= DATE_FORMAT(NOW(), '%m%d') )>=70 AND (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + (DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%m%d') <= DATE_FORMAT(NOW(), '%m%d') )<80 THEN '80'
264
-				WHEN (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + (DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%m%d') <= DATE_FORMAT(NOW(), '%m%d') )>=80 AND (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + (DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%m%d') <= DATE_FORMAT(NOW(), '%m%d') )<90 THEN '90'
265
-				WHEN (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + (DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%m%d') <= DATE_FORMAT(NOW(), '%m%d') )>=90 AND (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + (DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%m%d') <= DATE_FORMAT(NOW(), '%m%d') )<100 THEN '100'
266
-				ELSE '-1'
267
-			END
268
-		AS nnd FROM xt_patients where status=1
269
-	) a GROUP BY nnd;`).Scan(&counts).Error
270
-	if err != nil {
271
-		return nil, err
272
-	}
273
-	return counts, nil
274
-}
275
-
276
-func GetAdminUserElectronicSignatureTwo(userid int64) (*models.AdminUserElectronicSignature, error) {
277
-	var es models.AdminUserElectronicSignature
278
-	err := readUserDb.Model(&models.AdminUserElectronicSignature{}).Where("creator=? and status=1", userid).First(&es).Error
279
-
280
-	if err == gorm.ErrRecordNotFound {
281
-		return nil, nil
282
-	}
283
-	if err != nil {
284
-		return nil, err
285
-	}
286
-	return &es, nil
287
-}
288
-
289
-func GetAdminUserElectronicSignature(orgID int64, appID int64, userID int64) (*models.AdminUserElectronicSignature, error) {
290
-	var es models.AdminUserElectronicSignature
291
-	err := readUserDb.Model(&models.AdminUserElectronicSignature{}).Where("org_id=? and app_id=? and creator=? and status=1", orgID, appID, userID).First(&es).Error
292
-
293
-	if err == gorm.ErrRecordNotFound {
294
-		return nil, nil
295
-	}
296
-	if err != nil {
297
-		return nil, err
298
-	}
299
-	return &es, nil
300
-}
301
-
302
-func GetPatinentHead(orgid int64, appid int64, userid int64) (*models.SgjUserAdminPatientHead, error) {
303
-	var es models.SgjUserAdminPatientHead
304
-	err := readUserDb.Model(&models.SgjUserAdminPatientHead{}).Where("org_id = ? and app_id = ? and creator=? and status =1", orgid, appid, userid).First(&es).Error
305
-	if err == gorm.ErrRecordNotFound {
306
-		return nil, nil
307
-	}
308
-	if err != nil {
309
-		return nil, err
310
-	}
311
-	return &es, nil
312
-}
313
-
314
-func CreateAdminUserElectronicSignature(es *models.AdminUserElectronicSignature) error {
315
-	err := writeUserDb.Create(es).Error
316
-	return err
317
-}
318
-
319
-func SaveAdminUserElectronicSignature(es *models.AdminUserElectronicSignature) error {
320
-	err := writeUserDb.Save(es).Error
321
-	return err
322
-}
323
-
324
-func CreateAdminUserHead(es *models.SgjUserAdminPatientHead) error {
325
-	err := writeUserDb.Create(es).Error
326
-	return err
327
-}
328
-func SaveAdminUserHead(es *models.SgjUserAdminPatientHead) error {
329
-	err := writeUserDb.Create(es).Error
330
-	return err
331
-}
332
-
333
-func GetAdminUserSpecialPermission(orgID int64, appID int64, adminUserID int64, permissionType models.SpecialPermissionType) (*models.AdminUserSpecialPermission, error) {
334
-	var record models.AdminUserSpecialPermission
335
-	err := readDb.Model(&models.AdminUserSpecialPermission{}).Where("org_id = ? AND app_id = ? AND admin_user_id = ? AND permission = ? AND status = 1", orgID, appID, adminUserID, permissionType).First(&record).Error
336
-	if err != nil {
337
-		if err == gorm.ErrRecordNotFound {
338
-			return nil, nil
339
-		} else {
340
-			return nil, err
341
-		}
342
-	}
343
-	return &record, nil
344
-}
345
-
346
-func SaveAdminUserSpecialPermission(permission *models.AdminUserSpecialPermission) error {
347
-	err := writeDb.Save(permission).Error
348
-	return err
349
-}
350
-
351
-func GetAllValidAdminUsersWithSpecialPermission(orgID int64, appID int64, permissionType models.SpecialPermissionType) ([]*models.AdminUserSpecialPermission, error) {
352
-	var records []*models.AdminUserSpecialPermission
353
-	err := readDb.Model(&models.AdminUserSpecialPermission{}).Where("org_id = ? AND app_id = ? AND permission = ? AND status = 1", orgID, appID, permissionType).Find(&records).Error
354
-	if err != nil {
355
-		return nil, err
356
-	}
357
-	return records, nil
358
-}
359
-
360
-func GetAllSpecialPermissionAdminUsersWithoutStatus(orgID int64, appID int64, permissionType models.SpecialPermissionType) ([]*models.AdminUserSpecialPermission, error) {
361
-	var records []*models.AdminUserSpecialPermission
362
-	err := readDb.Model(&models.AdminUserSpecialPermission{}).Where("org_id = ? AND app_id = ? AND permission = ?", orgID, appID, permissionType).Find(&records).Error
363
-	if err != nil {
364
-		return nil, err
365
-	}
366
-	return records, nil
367
-}
368
-
369
-func CancelAllSpecialPermissionAdminUsers(orgID int64, appID int64, permissionType models.SpecialPermissionType) error {
370
-	tx := writeDb.Begin()
371
-	updateTime := time.Now().Unix()
372
-	err := tx.Model(&models.AdminUserSpecialPermission{}).Where("org_id = ? AND app_id = ? AND status = 1 AND permission = ?", orgID, appID, permissionType).Updates(map[string]interface{}{"status": 0, "mtime": updateTime}).Error
373
-	if err != nil {
374
-		tx.Rollback()
375
-		return err
376
-	}
377
-	tx.Commit()
378
-	return nil
379
-}
380
-
381
-func BatchSaveSpecialPermissionAdminUsers(users []*models.AdminUserSpecialPermission) error {
382
-	tx := writeDb.Begin()
383
-	for _, user := range users {
384
-		tx.Save(user)
385
-	}
386
-	return tx.Commit().Error
387
-}
388
-
389
-func ModifyAdminUserName(name string, id int64) error {
390
-	tx := writeUserDb.Begin()
391
-	updateTime := time.Now().Unix()
392
-	err := tx.Model(&models.AdminUser{}).Where("id = ?", id).Updates(map[string]interface{}{"name": name, "mtime": updateTime}).Error
393
-	if err != nil {
394
-		tx.Rollback()
395
-		return err
396
-	}
397
-	tx.Commit()
398
-	return nil
399
-
400
-}

+ 0 - 231
models/service/app_version.go Просмотреть файл

@@ -1,231 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	"github.com/jinzhu/gorm"
6
-	"time"
7
-)
8
-
9
-func GetAppVersionByAppType(apptype int64) (*models.AppVersion, error) {
10
-	var version models.AppVersion
11
-	err := readDb.Model(&models.AppVersion{}).Where("app_type=?", apptype).First(&version).Error
12
-	if err == gorm.ErrRecordNotFound {
13
-		return nil, nil
14
-	}
15
-
16
-	if err != nil {
17
-		return nil, err
18
-	}
19
-	return &version, nil
20
-}
21
-
22
-func GetAllAppOrg() ([]*models.OrgApp, error) {
23
-	var app []*models.OrgApp
24
-	err := readUserDb.Model(&models.OrgApp{}).Where("status = 1 AND org_id > 0").Group("org_id").Find(&app).Error
25
-	if err == gorm.ErrRecordNotFound {
26
-		return nil, nil
27
-	}
28
-
29
-	if err != nil {
30
-		return nil, err
31
-	}
32
-	return app, nil
33
-}
34
-
35
-func GetSystemApp() ([]*models.OrgApp, error) {
36
-	var app []*models.OrgApp
37
-	err := readDb.Model(&models.OrgApp{}).Where("status = 1 AND org_id = 0 ").Find(&app).Error
38
-	if err == gorm.ErrRecordNotFound {
39
-		return nil, nil
40
-	}
41
-
42
-	if err != nil {
43
-		return nil, err
44
-	}
45
-	return app, nil
46
-}
47
-
48
-func GetApp() ([]*models.OrgApp, error) {
49
-	var app []*models.OrgApp
50
-	err := readDb.Model(&models.OrgApp{}).Where("status = 1 AND org_id = 0").Find(&app).Error
51
-	if err == gorm.ErrRecordNotFound {
52
-		return nil, nil
53
-	}
54
-
55
-	if err != nil {
56
-		return nil, err
57
-	}
58
-	return app, nil
59
-}
60
-
61
-func GetAppByType(orgID int64, app_type int) (*models.OrgApp, error) {
62
-	var apps models.OrgApp
63
-	err := readUserDb.Where("app_type = ? AND org_id = ? AND status = 1", app_type, orgID).First(&apps).Error
64
-	if err != nil {
65
-		return nil, err
66
-	}
67
-	return &apps, nil
68
-}
69
-
70
-func CreateOrgApp(app *models.OrgApp) {
71
-	writeUserDb.Create(&app)
72
-
73
-}
74
-
75
-func GetAllUserRole(org_id int64) (appRole []*models.App_Role) {
76
-	if org_id == 0 {
77
-		readUserDb.Model(&models.App_Role{}).Where("status = 1").Find(&appRole)
78
-
79
-	} else {
80
-		readUserDb.Model(&models.App_Role{}).Where("status = 1 AND org_id = ? ", org_id).Find(&appRole)
81
-
82
-	}
83
-	return
84
-}
85
-
86
-func GetAllUserRoleByUserTypeOne(org_id int) (appRole []*models.App_Role) {
87
-	readUserDb.Model(&models.App_Role{}).Where("status = 1 AND user_type = 1").Find(&appRole)
88
-	return
89
-}
90
-
91
-func GetAllUserRoleByUserTypeOther() (appRole []*models.App_Role) {
92
-	//app, _ := GetOrgApp(int64(org_id), 3)
93
-
94
-	//if org_id == 0 {
95
-	readUserDb.Model(&models.App_Role{}).Where("status = 1 AND user_type > 1").Find(&appRole)
96
-	//
97
-	//} else {
98
-	//	readUserDb.Model(&models.App_Role{}).Where("status = 1 AND org_id = ?  AND user_type > 1 AND app_id = ? ", org_id, app.Id).Find(&appRole)
99
-	//
100
-	//}
101
-	return
102
-}
103
-
104
-func FindRoleByUserTypeOne(org_id int64) (role models.Role) {
105
-	readUserDb.Model(&models.Role{}).Where("status = 1 AND org_id = ? AND is_system = 2 AND role_name = '医生'", org_id).First(&role)
106
-	return
107
-}
108
-
109
-func FindRoleByUserTypeTwo(org_id int64) (role models.Role) {
110
-	readUserDb.Model(&models.Role{}).Where("status = 1 AND org_id = ? AND is_system = 3 AND role_name = '护士'", org_id).First(&role)
111
-	return
112
-}
113
-
114
-func GetAllRole() ([]*models.Role, error) {
115
-	var app []*models.Role
116
-	err := readUserDb.Model(&models.Role{}).Where("status = 1 AND org_id > 0").Group("org_id").Find(&app).Error
117
-	if err == gorm.ErrRecordNotFound {
118
-		return nil, nil
119
-	}
120
-	if err != nil {
121
-		return nil, err
122
-	}
123
-	return app, nil
124
-}
125
-
126
-func UpdateRoleIds(id int64, ids string) {
127
-	writeUserDb.Model(&models.App_Role{}).Where("status = 1 AND id = ?", id).Updates(map[string]interface{}{"role_ids": ids, "mtime": time.Now().Unix()})
128
-
129
-}
130
-
131
-func GetOrgAppA(orgID int64, app_type int) (*models.OrgApp, error) {
132
-	var apps models.OrgApp
133
-	err := readUserDb.Where("app_type = ? AND org_id = ? AND status = 1", app_type, orgID).First(&apps).Error
134
-	if err != nil {
135
-		return nil, err
136
-	}
137
-	return &apps, nil
138
-}
139
-
140
-func GetOrgByIdB(orgID int64) (*models.Org, error) {
141
-	var org models.Org
142
-	err := readUserDb.Model(&models.Org{}).Where("id = ?", orgID).First(&org).Error
143
-	if err != nil {
144
-		if err == gorm.ErrRecordNotFound {
145
-			return nil, nil
146
-		} else {
147
-			return nil, err
148
-		}
149
-	}
150
-	return &org, nil
151
-}
152
-
153
-func GetOrgAppB(orgID int64, app_type int) (*models.OrgApp, error) {
154
-	var apps models.OrgApp
155
-	err := readUserDb.Where("app_type = ? AND org_id = ? AND status = 1", app_type, orgID).First(&apps).Error
156
-	if err != nil {
157
-		return nil, err
158
-	}
159
-	return &apps, nil
160
-}
161
-
162
-func CreateOrgRoleB(role *models.Role) (err error) {
163
-	err = writeUserDb.Create(&role).Error
164
-	return
165
-}
166
-
167
-func CreateRolePurviewB(purview *models.RolePurview) (err error) {
168
-	err = writeUserDb.Create(&purview).Error
169
-	return
170
-}
171
-
172
-func CreateFuncRolePurviewB(purview *models.SgjUserRoleFuncPurview) (err error) {
173
-	err = writeUserDb.Create(&purview).Error
174
-	return
175
-}
176
-
177
-func GetSystemRole(orgID int64) ([]*models.Role, error) {
178
-	var roles []*models.Role
179
-	err := readUserDb.Where(" org_id = ? AND status = 1 AND is_system > 1", orgID).First(&roles).Error
180
-	if err != nil {
181
-		return nil, err
182
-	}
183
-	return roles, nil
184
-}
185
-
186
-func HandleData() {
187
-	var pe []*models.PredialysisEvaluation
188
-	//readDb.Model(&models.DialysisPrescription{}).Where("user_org_id = 12 AND record_date <= 1587571200").Find(&prescription)
189
-	//for _, item := range prescription {
190
-	//	writeDb.Model(&models.AssessmentAfterDislysis{}).Where("user_org_id =12 AND assessment_date = ?", item.RecordDate).Updates(map[string]interface{}{"mtime": time.Now().Unix(), "actual_ultrafiltration": item.Ultrafiltration})
191
-	//}
192
-	readDb.Model(&models.PredialysisEvaluation{}).Where("status = 1 AND user_org_id = 9538 AND dialysis_order_id > 0").Find(&pe)
193
-
194
-	for _, item := range pe {
195
-		var sch models.Schedule
196
-		err := readDb.Model(&models.Schedule{}).Where("status = 1 AND schedule_date = ? AND patient_id = ? AND user_org_id = 9538", item.AssessmentDate, item.PatientId).First(&sch).Error
197
-
198
-		if err == nil {
199
-			if sch.ID > 0 {
200
-				order := &models.DialysisOrder{
201
-					DialysisDate:   sch.ScheduleDate,
202
-					UserOrgId:      9538,
203
-					PatientId:      sch.PatientId,
204
-					Stage:          2,
205
-					BedID:          sch.BedId,
206
-					StartNurse:     554,
207
-					FinishNurse:    554,
208
-					Status:         1,
209
-					CreatedTime:    sch.ScheduleDate,
210
-					UpdatedTime:    sch.ScheduleDate,
211
-					StartTime:      sch.ScheduleDate,
212
-					EndTime:        sch.ScheduleDate,
213
-					PunctureNurse:  554,
214
-					Creator:        554,
215
-					Modifier:       554,
216
-					FinishCreator:  554,
217
-					FinishModifier: 554,
218
-					SchedualType:   sch.ScheduleType,
219
-				}
220
-				writeDb.Create(&order)
221
-			}
222
-		}
223
-
224
-	}
225
-
226
-}
227
-
228
-func FindAllOrgByImportType() (org []*models.Org, err error) {
229
-	err = readUserDb.Model(&models.Org{}).Where("status =1 AND import = 0").Find(&org).Error
230
-	return
231
-}

+ 0 - 45
models/service/auto_clear_schedules_service.go Просмотреть файл

@@ -1,45 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	"XT_New/utils"
6
-	"time"
7
-
8
-	"github.com/robfig/cron"
9
-)
10
-
11
-// cron表达式 https://www.cnblogs.com/zuxingyu/p/6023919.html
12
-var clearSchedulesCronJob *cron.Cron
13
-
14
-func init() {
15
-	utils.InfoLog("开启自动清除排班定时任务")
16
-	clearSchedulesCronJob = cron.New()
17
-	spec := "0 0 1 * * ?" // 每天凌晨1点清除已排班未上机的排班数据
18
-	clearSchedulesCronJob.AddFunc(spec, func() {
19
-		AutoClearSchedules()
20
-	})
21
-}
22
-
23
-func BeginAutoClearSchedulesJob() {
24
-	clearSchedulesCronJob.Start()
25
-}
26
-
27
-func AutoClearSchedules() {
28
-	utils.TraceLog("自动清除排班任务开始执行")
29
-	//查出所有机构
30
-	var schedules []*models.Schedule
31
-	err = readDb.Table("xt_schedule as s").Where("s.status = 1").Select("distinct(s.user_org_id)").Find(&schedules).Error
32
-	//遍历所有机构
33
-	scheduleDate := utils.ZeroHourTimeOfDay(time.Now())
34
-	for _, item := range schedules {
35
-		//将今天(不包括今天)以前的的排班数据进行软删除
36
-		writeDb.
37
-			Table("xt_schedule as s").
38
-			Where("s.schedule_date < ? AND s.status = 1 AND "+
39
-				"s.user_org_id = ? AND "+
40
-				"NOT EXISTS (Select * FROM `xt_dialysis_order` as d Where  d.`status` = 1 AND"+
41
-				" d.`patient_id` = s.patient_id AND "+
42
-				" d.user_org_id = s.user_org_id AND d.dialysis_date = s.schedule_date)", scheduleDate.Unix(), item.UserOrgId).Updates(map[string]interface{}{"status": 0, "updated_time": time.Now().Unix()})
43
-	}
44
-	utils.SuccessLog("自动清除排班任务完成")
45
-}

+ 0 - 148
models/service/auto_create_staff_schedule_service.go Просмотреть файл

@@ -1,148 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	"fmt"
6
-	"github.com/jinzhu/gorm"
7
-	"github.com/robfig/cron"
8
-	"time"
9
-)
10
-
11
-//// cron表达式 https://www.cnblogs.com/zuxingyu/p/6023919.html
12
-//var createWeekDisinfectionCronJob *cron.Cron
13
-//
14
-//func init() {
15
-//  createWeekDisinfectionCronJob = cron.New()
16
-//  //spec := "0 0 23 * * ?" // 每天23点执行一次
17
-//  spec := "0 55 23 * * ?" // 每天23点55执行一次
18
-//  //spec := "0 0 5 * * ?" // 每天23点55执行一次
19
-//  //spec := "0 */1 * * * ?" // 每1分钟执行一次
20
-//  createWeekDisinfectionCronJob.AddFunc(spec, func() {
21
-//
22
-//    AutoCreateWeekDisinfectionJob()
23
-//  })
24
-//}
25
-//
26
-//func BeginAutoCreateWeekDisinfectionJob() {
27
-//
28
-//  createWeekDisinfectionCronJob.Start()
29
-//}
30
-
31
-//// cron表达式 https://www.cnblogs.com/zuxingyu/p/6023919.html
32
-
33
-var createStaffScheduleCronJob *cron.Cron
34
-
35
-func init() {
36
-	createStaffScheduleCronJob = cron.New()
37
-	//spec := "0 */1 * * * ?" // 每1分钟执行一次
38
-	//spec := "0 55 23 * * ?" // 每天23点55执行一次
39
-	spec := "0 0 0 ? * Sun"
40
-	createStaffScheduleCronJob.AddFunc(spec, func() {
41
-		AutoCreateStaffScheduleJob()
42
-	})
43
-}
44
-
45
-func BeginAutoCreateStaffScheduleJob() {
46
-
47
-	createStaffScheduleCronJob.Start()
48
-}
49
-
50
-func AutoCreateStaffScheduleJob() {
51
-
52
-	now := time.Now()
53
-
54
-	offset := int(time.Monday - now.Weekday())
55
-	if offset > 0 {
56
-		offset = -6
57
-	}
58
-	weekStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset)
59
-	fmt.Println("weekStart", weekStart.Unix())
60
-	start_time := weekStart.Unix()
61
-	fmt.Println("start_time", start_time)
62
-	weekEnd := time.Date(now.Year(), now.Month(), now.Day()+6, 0, 0, 0, 0, time.Local).AddDate(0, 0, offset)
63
-	fmt.Println("weekEnd", weekEnd.Unix())
64
-	end_time := weekEnd.Unix()
65
-	fmt.Println("end_time", end_time)
66
-
67
-	//查询该机构的连续排班是否开启
68
-	// 获取所有机构信息
69
-	orgs, _ := GetAllOrgs()
70
-	for _, item := range orgs {
71
-		fmt.Println(item)
72
-		//查询该机构是否开启连续排班功能
73
-		schdule, _ := GetAutoContinueSchdule(item.ID)
74
-		//如果状态值未开启不生成连续排班
75
-		if schdule.IsStatus == 0 {
76
-			fmt.Println("连续排班未开启")
77
-		}
78
-		//连续排班开启
79
-		if schdule.IsStatus == 1 {
80
-			//查询该机构本周的排班数据
81
-			schedules, _ := GeThisWeekScheduleData(item.ID, start_time, end_time)
82
-			for _, it := range schedules {
83
-				staffSchedule := models.StaffSchedule{
84
-					DoctorId:     it.DoctorId,
85
-					DoctorType:   it.DoctorType,
86
-					ScheduleType: it.ScheduleType,
87
-					ScheduleWeek: it.ScheduleWeek,
88
-					UserOrgId:    it.UserOrgId,
89
-					StartTime:    it.StartTime + 604800,
90
-					EndTime:      it.EndTime + 604800,
91
-					Status:       1,
92
-					Ctime:        time.Now().Unix(),
93
-					ScheduleDate: it.ScheduleDate + 604800,
94
-				}
95
-				//产询该机构下周是否填加了数据
96
-				_, errcode := GetNextWeekData(it.UserOrgId, it.DoctorId, it.ScheduleDate+604800)
97
-				if errcode == gorm.ErrRecordNotFound {
98
-					AddSchedules(&staffSchedule)
99
-				} else {
100
-					fmt.Println("下周数据已生成")
101
-				}
102
-				//if len(schedules) != len(schedule) {
103
-				//    AddSchedules(&staffSchedule)
104
-				//}else{
105
-				//   fmt.Println("下周数据已生成")
106
-				//   //createStaffScheduleCronJob.Stop()
107
-				//}
108
-			}
109
-		}
110
-	}
111
-}
112
-
113
-func GetAllOrgs() (orgs []*models.SgjUserOrg, err error) {
114
-
115
-	err = UserReadDB().Model(&orgs).Where("status = 1").Find(&orgs).Error
116
-	return orgs, err
117
-}
118
-
119
-func GetAutoContinueSchdule(orgid int64) (models.ContinueSchedule, error) {
120
-
121
-	schedule := models.ContinueSchedule{}
122
-	err := XTReadDB().Model(&schedule).Where("user_org_id = ? and status = 1", orgid).Find(&schedule).Error
123
-	return schedule, err
124
-}
125
-
126
-func GeThisWeekScheduleData(orgid int64, startime int64, endtime int64) (staffschedule []*models.StaffSchedule, err error) {
127
-
128
-	err = XTReadDB().Model(&staffschedule).Where("user_org_id = ? and status = 1 and start_time>=? and end_time<=?", orgid, startime, endtime).Find(&staffschedule).Error
129
-	return staffschedule, err
130
-}
131
-
132
-func AddSchedules(schedule *models.StaffSchedule) error {
133
-
134
-	err := XTWriteDB().Model(&schedule).Create(&schedule).Error
135
-	return err
136
-}
137
-
138
-func GetNextWeekData(orgid int64, docid int64, scheduledate int64) (*models.StaffSchedule, error) {
139
-	schedule := models.StaffSchedule{}
140
-	err := XTReadDB().Model(&schedule).Where("user_org_id = ? and status = 1 and doctor_id =? and schedule_date =?", orgid, docid, scheduledate).Find(&schedule).Error
141
-	if err == gorm.ErrRecordNotFound {
142
-		return nil, err
143
-	}
144
-	if err != nil {
145
-		return nil, err
146
-	}
147
-	return &schedule, nil
148
-}

+ 0 - 261
models/service/auto_create_week_disinfection.go Просмотреть файл

@@ -1,261 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	"XT_New/utils"
6
-	"fmt"
7
-	"github.com/jinzhu/gorm"
8
-	"github.com/robfig/cron"
9
-	"strconv"
10
-	"time"
11
-)
12
-
13
-// cron表达式 https://www.cnblogs.com/zuxingyu/p/6023919.html
14
-var createWeekDisinfectionCronJob *cron.Cron
15
-
16
-func init() {
17
-	createWeekDisinfectionCronJob = cron.New()
18
-	//spec := "0 0 23 * * ?" // 每天23点执行一次
19
-	spec := "0 55 23 * * ?" // 每天23点55执行一次
20
-	//spec := "0 0 5 * * ?" // 每天23点55执行一次
21
-	//spec := "0 */1 * * * ?" // 每1分钟执行一次
22
-	createWeekDisinfectionCronJob.AddFunc(spec, func() {
23
-
24
-		AutoCreateWeekDisinfectionJob()
25
-	})
26
-}
27
-
28
-func BeginAutoCreateWeekDisinfectionJob() {
29
-
30
-	createWeekDisinfectionCronJob.Start()
31
-}
32
-
33
-func AutoCreateWeekDisinfectionJob() {
34
-	timeStr := time.Now().Format("2006-01-02")
35
-	timeLayout := "2006-01-02 15:04:05"
36
-	fmt.Println("timeStr:", timeStr)
37
-	timeStringToTime, _ := utils.ParseTimeStringToTime(timeLayout, timeStr+" 00:00:00")
38
-	timenow := timeStringToTime.Unix()
39
-	fmt.Println("timenow是什么", timenow)
40
-	//查询当天排班所有机构
41
-	org, errs := GetAllOrgID(timenow)
42
-	fmt.Print("错误是什么", errs)
43
-	//fmt.Println("查询有机构失败", err)
44
-	for _, item := range org {
45
-		//查询机构是否开启自动使用登记
46
-		remander, errs := GetRemanderDatas(item.UserOrgId)
47
-		fmt.Print("查询自动使用登记错误", errs)
48
-		//开启
49
-		if remander.IsRun == 1 {
50
-			fmt.Println("机构id", item.UserOrgId)
51
-			//查询当天机构的所有下机病人id
52
-			order, _ := GetAllPatientByOrgID(item.UserOrgId, timenow)
53
-			for _, it := range order {
54
-				//fmt.Println("病人", it.PatientId)
55
-
56
-				//查询病人信息
57
-				patients, err := GetPatientInformation(it.PatientId, it.UserOrgId)
58
-				fmt.Println("查询病人信息报错", err)
59
-				var con = ""
60
-				if patients.IsInfectious == 0 {
61
-					con = ""
62
-				}
63
-				if patients.IsInfectious == 1 {
64
-					con = "无"
65
-				}
66
-				if patients.IsInfectious == 2 {
67
-					con = "有"
68
-				}
69
-				//fmt.Print("con------------------------", con)
70
-				//	fmt.Print("传染病", patients.IsInfectious)
71
-				//查询病人的班次
72
-				//schedules, _ := GetAllPatientSchedule(it.PatientId, it.UserOrgId,timenow)
73
-				schedules, _ := GetAllPatientSchedule(it.PatientId, it.UserOrgId, timenow)
74
-				fmt.Println("班次", schedules.ScheduleType)
75
-				//查询病人今日的透析模式
76
-				prescription, _ := GetDialysisPrescription(it.PatientId, it.UserOrgId, timenow)
77
-				fmt.Println("透析模式", prescription.ModeId)
78
-
79
-				//查询病人今日透后评估数据
80
-				dislysis, err := GetAssessmentAfterDissData(it.PatientId, it.UserOrgId, timenow)
81
-				fmt.Println("透后评估错误", err)
82
-				fmt.Print("透析时长", dislysis.ActualTreatmentHour+'h'+dislysis.ActualTreatmentMinute+'m'+'i'+'n')
83
-				//			//根据床位号获取设备id
84
-				addmacher, _ := GetEquimentID(schedules.BedId, it.UserOrgId)
85
-				//unitype, err := strconv.ParseInt(addmacher.UnitType, 10, 64)
86
-				fmt.Println(" 设备id", addmacher.ID)
87
-				//根据设备id获取设备类型
88
-				//equimentname, _ := GetAddmacher(addmacher.ID, it.UserOrgId)
89
-
90
-				fmt.Println("班次", it.SchedualType)
91
-				//查看该设备是否有消毒计划,无怎返回,有则添加
92
-				plan, errplan := GetDisinfection(addmacher.UnitType, it.SchedualType, it.UserOrgId)
93
-				fmt.Print("plan", plan)
94
-				fmt.Println("错误是什么", errplan)
95
-				if errplan == gorm.ErrRecordNotFound {
96
-					fmt.Println("该设备无消毒计划")
97
-					return
98
-				} else if errplan == nil {
99
-					//fmt.Println("消毒时长", plan.DisinfecTime)
100
-					//fmt.Println("基表消毒方式", plan.Way)
101
-					//fmt.Println("基表消毒液", plan.MachineDisinfectant)
102
-					//fmt.Println("液路消毒方式", plan.DisinfectanWay)
103
-					//fmt.Println("液路消毒液", plan.Disinfectant)
104
-					//fmt.Println("上机时间", it.StartTime)
105
-					//fmt.Println("下机时间", it.EndTime)
106
-					//fmt.Println("传染病", con)
107
-					//fmt.Println("体重减少", strconv.FormatFloat(dislysis.WeightLoss, 'f', -1, 64))
108
-					//fmt.Println("时间超滤量", strconv.FormatFloat(dislysis.ActualUltrafiltration, 'f', -1, 64))
109
-					//fmt.Println("透析时长", strconv.FormatInt(dislysis.ActualTreatmentHour, 10))
110
-					//查询该病人是否有记录,无记录的则添加
111
-					information, errcode := GetInfor(it.PatientId, timenow, it.UserOrgId, it.SchedualType)
112
-					//fmt.Println("errcode是什么", errcode)
113
-					fmt.Println("information", information)
114
-					if errcode == gorm.ErrRecordNotFound {
115
-						information := models.DeviceInformation{
116
-							Date:                  timenow,
117
-							Zone:                  schedules.PartitionId,
118
-							Class:                 it.SchedualType,
119
-							BedNumber:             schedules.BedId,
120
-							PatientId:             schedules.PatientId,
121
-							DialysisMode:          prescription.ModeId,
122
-							LongTime:              strconv.FormatInt(plan.DisinfecTime, 10),
123
-							Disinfection:          1,
124
-							DialysisConcentration: 1,
125
-							DisinfectionStatus:    1,
126
-							Move:                  1,
127
-							UserOrgId:             it.UserOrgId,
128
-							DisinfectType:         plan.Way,                 //基表消毒方式
129
-							DisinfectantType:      plan.MachineDisinfectant, //基表消毒液
130
-							FluidPath:             plan.DisinfectanWay,      //液路消毒方式
131
-							Disinfectant:          plan.Disinfectant,        //液路消毒液
132
-							Ctime:                 time.Now().Unix(),
133
-							Status:                1,
134
-							SignName:              it.FinishNurse,
135
-							EquimentId:            addmacher.ID,
136
-							DisinfectionResidue:   2,
137
-							Bed:                   addmacher.BedNumber,
138
-							StartTime:             it.StartTime,
139
-							EndTime:               it.EndTime,
140
-							Contagion:             con,
141
-							WeightLoss:            dislysis.WeightLoss,
142
-							Hyperfiltratio:        dislysis.ActualUltrafiltration,
143
-							DialysisHour:          strconv.FormatInt(dislysis.ActualTreatmentHour, 10),
144
-							MachineRun:            1,
145
-						}
146
-						err := CreateInformation(&information)
147
-						fmt.Println("报错", err)
148
-					} else if errcode == nil {
149
-
150
-					} else {
151
-
152
-					}
153
-				} else {
154
-
155
-					return
156
-				}
157
-			}
158
-		}
159
-
160
-		//关闭
161
-		if remander.IsRun == 2 {
162
-			fmt.Print("已关闭")
163
-		}
164
-	}
165
-
166
-}
167
-
168
-//
169
-//func GetAllOrgID(status int64) (org []*models.Org, err error) {
170
-//
171
-//	err = UserReadDB().Where("status = ?", status).Find(&org).Error
172
-//
173
-//	return org, err
174
-//}
175
-
176
-//查询当天有排班的所有机构
177
-func GetAllOrgID(time int64) (schedule []*models.XtSchedule, err error) {
178
-
179
-	err = XTReadDB().Raw("select user_org_id,id,partition_id,bed_id,patient_id,schedule_date,schedule_type,schedule_week,mode_id from xt_schedule where schedule_date = ?  group by user_org_id", time).Scan(&schedule).Error
180
-
181
-	return schedule, err
182
-}
183
-
184
-func GetAllPatientByOrgID(orgid int64, timenow int64) (order []*models.DialysisOrder, err error) {
185
-
186
-	err = XTReadDB().Where("user_org_id = ? AND dialysis_date = ? AND stage = 2 AND status = ?", orgid, timenow, 1).Find(&order).Error
187
-	return order, err
188
-}
189
-
190
-func CreateInformation(information *models.DeviceInformation) error {
191
-	err := UserWriteDB().Create(&information).Error
192
-	return err
193
-}
194
-
195
-func GetAllPatientSchedule(patientid int64, orgID int64, timenow int64) (models.Schedule, error) {
196
-	schedules := models.Schedule{}
197
-	err := XTReadDB().Where("patient_id = ? AND user_org_id = ? AND schedule_date = ?", patientid, orgID, timenow).Find(&schedules).Error
198
-	return schedules, err
199
-}
200
-
201
-func GetInfor(patientid int64, timenow int64, orgid int64, class int64) (*models.DeviceInformation, error) {
202
-	var pre models.DeviceInformation
203
-	var err error
204
-	err = readUserDb.Model(&pre).Where("patient_id = ? AND date = ? AND user_org_id = ? AND class = ? AND status = 1", patientid, timenow, orgid, class).Find(&pre).Error
205
-	if err == gorm.ErrRecordNotFound {
206
-		return nil, err
207
-	}
208
-	if err != nil {
209
-		return nil, err
210
-	}
211
-	return &pre, nil
212
-}
213
-
214
-func GetDisinfection(equitType int64, scheduleType int64, orgID int64) (*models.DevicePlan, error) {
215
-	var plan models.DevicePlan
216
-	var err error
217
-	err = readUserDb.Model(&plan).Where("device_type = ? AND classtime = ? AND user_org_id = ? AND status = 1", equitType, scheduleType, orgID).Find(&plan).Error
218
-	if err == gorm.ErrRecordNotFound {
219
-		return nil, err
220
-	}
221
-	if err != nil {
222
-		return nil, err
223
-	}
224
-	return &plan, nil
225
-}
226
-
227
-func GetDialysisPrescription(patientid int64, orgID int64, timenow int64) (models.DialysisPrescription, error) {
228
-	prescription := models.DialysisPrescription{}
229
-	err := XTReadDB().Model(&prescription).Where("patient_id = ? AND user_org_id = ? AND record_date = ?", patientid, orgID, timenow).Find(&prescription).Error
230
-	return prescription, err
231
-}
232
-
233
-func GetAssessmentAfterDissData(patientid int64, orgID int64, timenow int64) (models.XtAssessmentAfterDislysis, error) {
234
-	dislysis := models.XtAssessmentAfterDislysis{}
235
-	err := XTReadDB().Where("patient_id = ? AND user_org_id = ? AND assessment_date = ?", patientid, orgID, timenow).Find(&dislysis).Error
236
-	return dislysis, err
237
-}
238
-
239
-func GetEquimentID(bedId int64, orgID int64) (models.DeviceAddmacher, error) {
240
-	addmacher := models.DeviceAddmacher{}
241
-	err := readUserDb.Model(&addmacher).Where("bed_id = ? AND user_org_id = ? AND status = ?", bedId, orgID, 1).Find(&addmacher).Error
242
-	return addmacher, err
243
-}
244
-
245
-func GetAddmacher(equitmentid int64, orgid int64) (models.DeviceEquimentname, error) {
246
-	equimentname := models.DeviceEquimentname{}
247
-	err := readUserDb.Model(&equimentname).Where("equitment_id = ? AND user_org_id = ? AND status = 1", equitmentid, orgid).Find(&equimentname).Error
248
-	return equimentname, err
249
-}
250
-
251
-func GetPatientInformation(id int64, orgid int64) (models.Patients, error) {
252
-	patients := models.Patients{}
253
-	err := XTReadDB().Where("id = ? AND user_org_id = ?", id, orgid).Find(&patients).Error
254
-	return patients, err
255
-}
256
-
257
-func GetRemanderDatas(orgid int64) (remander models.DeviceRemander, err error) {
258
-
259
-	err = UserReadDB().Model(&models.DeviceRemander{}).Where("user_org_id = ? and status = 1", orgid).Find(&remander).Error
260
-	return
261
-}

+ 0 - 149
models/service/auto_create_week_plan.go Просмотреть файл

@@ -1,149 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	"XT_New/utils"
6
-	"fmt"
7
-	"github.com/jinzhu/gorm"
8
-	"github.com/robfig/cron"
9
-	"strconv"
10
-	"time"
11
-)
12
-
13
-var createWeekPlanCronJob *cron.Cron
14
-
15
-func init() {
16
-	utils.InfoLog("第二次开启自动消毒时任务")
17
-	spec := "0 0 22 * * ?" // 每天22点执行一次
18
-	//spec := "0 */1 * * * ?" // 每1分钟执行一次
19
-	createWeekPlanCronJob = cron.New()
20
-	createWeekDisinfectionCronJob.AddFunc(spec, func() {
21
-		AutoCreateWeekPlanJob()
22
-	})
23
-}
24
-
25
-func BeginAutoCreatePlanJob() {
26
-	createWeekPlanCronJob.Start()
27
-}
28
-
29
-func AutoCreateWeekPlanJob() {
30
-
31
-	timeStr := time.Now().Format("2006-01-02")
32
-	timeLayout := "2006-01-02 15:04:05"
33
-	fmt.Println("timeStr:", timeStr)
34
-	timeStringToTime, _ := utils.ParseTimeStringToTime(timeLayout, timeStr+" 00:00:00")
35
-	timenow := timeStringToTime.Unix()
36
-	fmt.Println("timenow是什么", timenow)
37
-	//查询当天排班所有机构
38
-	org, errs := GetAllOrgID(timenow)
39
-	fmt.Print("错误是什么", errs)
40
-	fmt.Println("查询有机构失败", err)
41
-	for _, item := range org {
42
-		//查询机构是否开启自动使用登记
43
-		remander, errs := GetRemanderDatas(item.UserOrgId)
44
-		fmt.Print("查询自动使用登记错误", errs)
45
-		//开启
46
-		if remander.IsRun == 1 {
47
-			fmt.Println("机构id", item.UserOrgId)
48
-			//查询当天机构的所有下机病人id
49
-			order, _ := GetAllPatientByOrgID(item.UserOrgId, timenow)
50
-			for _, it := range order {
51
-				fmt.Println("病人", it.PatientId)
52
-
53
-				//查询病人信息
54
-				patients, err := GetPatientInformation(it.PatientId, it.UserOrgId)
55
-				fmt.Println("查询病人信息报错", err)
56
-				var con = ""
57
-				if patients.IsInfectious == 0 {
58
-					con = ""
59
-				}
60
-				if patients.IsInfectious == 1 {
61
-					con = "无"
62
-				}
63
-				if patients.IsInfectious == 2 {
64
-					con = "有"
65
-				}
66
-
67
-				//查询病人的班次
68
-				//schedules, _ := GetAllPatientSchedule(it.PatientId, it.UserOrgId,timenow)
69
-				schedules, _ := GetAllPatientSchedule(it.PatientId, it.UserOrgId, timenow)
70
-				fmt.Println("班次", schedules.ScheduleType)
71
-				//查询病人今日的透析模式
72
-				prescription, _ := GetDialysisPrescription(it.PatientId, it.UserOrgId, timenow)
73
-				fmt.Println("透析模式", prescription.ModeId)
74
-
75
-				//查询病人今日透后评估数据
76
-				dislysis, err := GetAssessmentAfterDissData(it.PatientId, it.UserOrgId, timenow)
77
-				fmt.Println("透后", err)
78
-				//			//根据床位号获取设备id
79
-				addmacher, _ := GetEquimentID(schedules.BedId, it.UserOrgId)
80
-				//unitype, err := strconv.ParseInt(addmacher.UnitType, 10, 64)
81
-				fmt.Println(" 设备id", addmacher.ID)
82
-				//根据设备id获取设备类型
83
-				//equimentname, _ := GetAddmacher(addmacher.ID, it.UserOrgId)
84
-
85
-				fmt.Println("班次", it.SchedualType)
86
-				//查看该设备是否有消毒计划,无怎返回,有则添加
87
-				plan, errplan := GetDisinfection(addmacher.UnitType, it.SchedualType, it.UserOrgId)
88
-				fmt.Print("plan", plan)
89
-				fmt.Println("错误", errplan)
90
-				if errplan == gorm.ErrRecordNotFound {
91
-					fmt.Println("该设备无消毒计划")
92
-					return
93
-				} else if errplan == nil {
94
-					//查询该病人是否有记录,无记录的则添加
95
-					information, errcode := GetInfor(it.PatientId, timenow, it.UserOrgId, it.SchedualType)
96
-					fmt.Println("errcode是什么", errcode)
97
-					fmt.Println("information", information)
98
-					if errcode == gorm.ErrRecordNotFound {
99
-						information := models.DeviceInformation{
100
-							Date:                  timenow,
101
-							Zone:                  schedules.PartitionId,
102
-							Class:                 it.SchedualType,
103
-							BedNumber:             schedules.BedId,
104
-							PatientId:             schedules.PatientId,
105
-							DialysisMode:          prescription.ModeId,
106
-							LongTime:              strconv.FormatInt(plan.DisinfecTime, 10),
107
-							Disinfection:          1,
108
-							DialysisConcentration: 1,
109
-							DisinfectionStatus:    1,
110
-							Move:                  1,
111
-							UserOrgId:             it.UserOrgId,
112
-							DisinfectType:         plan.Way,                 //基表消毒方式
113
-							DisinfectantType:      plan.MachineDisinfectant, //基表消毒液
114
-							FluidPath:             plan.DisinfectanWay,      //液路消毒方式
115
-							Disinfectant:          plan.Disinfectant,        //液路消毒液
116
-							Ctime:                 time.Now().Unix(),
117
-							Status:                1,
118
-							SignName:              it.FinishNurse,
119
-							EquimentId:            addmacher.ID,
120
-							DisinfectionResidue:   2,
121
-							Bed:                   addmacher.BedNumber,
122
-							StartTime:             it.StartTime,
123
-							EndTime:               it.EndTime,
124
-							Contagion:             con,
125
-							WeightLoss:            dislysis.WeightLoss,
126
-							Hyperfiltratio:        dislysis.ActualUltrafiltration,
127
-							DialysisHour:          strconv.FormatInt(dislysis.ActualTreatmentHour, 10),
128
-							MachineRun:            1,
129
-						}
130
-						err := CreateInformation(&information)
131
-						fmt.Println("报错", err)
132
-					} else if errcode == nil {
133
-
134
-					} else {
135
-
136
-					}
137
-				} else {
138
-
139
-					return
140
-				}
141
-			}
142
-		}
143
-
144
-		//关闭
145
-		if remander.IsRun == 2 {
146
-			fmt.Print("已关闭")
147
-		}
148
-	}
149
-}

+ 0 - 281
models/service/auto_create_week_schedules_service.go Просмотреть файл

@@ -1,281 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"fmt"
5
-	"strings"
6
-	"time"
7
-
8
-	"XT_New/models"
9
-	"XT_New/utils"
10
-
11
-	"github.com/jinzhu/gorm"
12
-	"github.com/robfig/cron"
13
-)
14
-
15
-// cron表达式 https://www.cnblogs.com/zuxingyu/p/6023919.html
16
-var createWeekSchedulesCronJob *cron.Cron
17
-
18
-func init() {
19
-	utils.InfoLog("开启自动排班定时任务")
20
-	createWeekSchedulesCronJob = cron.New()
21
-	spec := "0 0 0 ? * MON" // 每周一凌晨0点生成排班
22
-	createWeekSchedulesCronJob.AddFunc(spec, func() {
23
-		AutoCreateWeekSchedules()
24
-	})
25
-}
26
-
27
-func BeginAutoCreateWeekSchedulesJob() {
28
-	createWeekSchedulesCronJob.Start()
29
-}
30
-
31
-func AutoCreateWeekSchedules() {
32
-	utils.TraceLog("自动排班任务开始执行")
33
-	var modes []*models.PatientScheduleTemplateMode
34
-	getModesErr := readDb.Model(&models.PatientScheduleTemplateMode{}).Where("mode <> 0 AND status = 1").Find(&modes).Error
35
-	if getModesErr != nil {
36
-		utils.ErrorLog("自动排班-获取启用模板模式列表失败:%v", getModesErr)
37
-		CreateDBErrorRecord(0, "自动排班-获取启用模板模式列表失败:%v", getModesErr)
38
-		return
39
-	}
40
-
41
-	for _, mode := range modes {
42
-		templates, getTemplatesErr := GetOrgPatientScheduleTemplateIDs(mode.OrgID)
43
-		if getTemplatesErr != nil {
44
-			utils.ErrorLog("自动排班-org_id: %v :获取模板 ID 失败:%v", mode.OrgID, getTemplatesErr)
45
-			CreateDBErrorRecord(mode.OrgID, "自动排班-org_id: %v :获取模板 ID 失败:%v", mode.OrgID, getTemplatesErr)
46
-			continue
47
-		} else if len(templates) == 0 {
48
-			utils.WarningLog("自动排班-org_id: %v :没有模板", mode.OrgID)
49
-			continue
50
-		}
51
-
52
-		now := time.Now()
53
-		nextSecWeek := now.AddDate(0, 0, 14)
54
-		tx := writeDb.Begin()
55
-
56
-		if mode.Mode == 1 { // 用第一周模板生成下第二周的排班
57
-			items, getItemsErr := GetOrgPatientScheduleTemplateItemsWithoutPatientByTemplateID(mode.OrgID, templates[0].ID)
58
-			if getItemsErr != nil {
59
-				utils.ErrorLog("自动排班-org_id: %v :获取第一周模板Item失败:%v", mode.OrgID, getItemsErr)
60
-				CreateDBErrorRecord(mode.OrgID, "自动排班-org_id: %v :获取第一周模板Item失败:%v", mode.OrgID, getItemsErr)
61
-				continue
62
-			}
63
-			insertErr := _refreshWeekSchedulesWithTemplateItems(tx, mode.OrgID, nextSecWeek, items, nil)
64
-			if insertErr != nil {
65
-				utils.ErrorLog("自动排班-org_id: %v :使用第一周模板插入下第二周排班失败:%v", mode.OrgID, insertErr)
66
-				CreateDBErrorRecord(mode.OrgID, "自动排班-org_id: %v :使用第一周模板插入下第二周排班失败:%v", mode.OrgID, insertErr)
67
-				tx.Rollback()
68
-				continue
69
-			}
70
-
71
-		} else if mode.Mode == 2 { // mode.ExecuteTimes % 2 的结果,如果为0,用第一周模板生成下第二周的排班,否则用第二周的模板生成排班
72
-			if mode.ExecuteTimes%2 == 0 {
73
-				items, getItemsErr := GetOrgPatientScheduleTemplateItemsWithoutPatientByTemplateID(mode.OrgID, templates[0].ID)
74
-				if getItemsErr != nil {
75
-					utils.ErrorLog("自动排班-org_id: %v :获取第一周模板Item失败:%v", mode.OrgID, getItemsErr)
76
-					CreateDBErrorRecord(mode.OrgID, "自动排班-org_id: %v :获取第一周模板Item失败:%v", mode.OrgID, getItemsErr)
77
-					continue
78
-				}
79
-
80
-				insertErr := _refreshWeekSchedulesWithTemplateItems(tx, mode.OrgID, nextSecWeek, items, nil)
81
-				if insertErr != nil {
82
-					utils.ErrorLog("自动排班-org_id: %v :使用第一周模板插入下第二周排班失败:%v", mode.OrgID, insertErr)
83
-					CreateDBErrorRecord(mode.OrgID, "自动排班-org_id: %v :使用第一周模板插入下第二周排班失败:%v", mode.OrgID, insertErr)
84
-					tx.Rollback()
85
-					continue
86
-				}
87
-
88
-			} else {
89
-				if len(templates) < 2 {
90
-					utils.WarningLog("自动排班-org_id: %v :没有第二周的模板")
91
-					continue
92
-				}
93
-				items, getItemsErr := GetOrgPatientScheduleTemplateItemsWithoutPatientByTemplateID(mode.OrgID, templates[1].ID)
94
-				if getItemsErr != nil {
95
-					utils.ErrorLog("自动排班-org_id: %v :获取第二周模板Item失败:%v", mode.OrgID, getItemsErr)
96
-					CreateDBErrorRecord(mode.OrgID, "自动排班-org_id: %v :获取第二周模板Item失败:%v", mode.OrgID, getItemsErr)
97
-					continue
98
-				}
99
-
100
-				insertErr := _refreshWeekSchedulesWithTemplateItems(tx, mode.OrgID, nextSecWeek, items, nil)
101
-				if insertErr != nil {
102
-					utils.ErrorLog("自动排班-org_id: %v :使用第二周模板插入下第二周排班失败:%v", mode.OrgID, insertErr)
103
-					CreateDBErrorRecord(mode.OrgID, "自动排班-org_id: %v :使用第二周模板插入下第二周排班失败:%v", mode.OrgID, insertErr)
104
-					tx.Rollback()
105
-					continue
106
-				}
107
-			}
108
-		}
109
-
110
-		mode.ExecuteTimes += 1
111
-		mode.ModifyTime = now.Unix()
112
-		updateModeErr := tx.Save(mode).Error
113
-		if updateModeErr != nil {
114
-			utils.ErrorLog("自动排班-org_id:%v :更新启用模板模式的执行次数失败:%v", mode.OrgID, updateModeErr)
115
-			CreateDBErrorRecord(mode.OrgID, "自动排班-org_id:%v :更新启用模板模式的执行次数失败:%v", mode.OrgID, updateModeErr)
116
-			tx.Rollback()
117
-			continue
118
-		}
119
-
120
-		tx.Commit()
121
-		utils.SuccessLog("自动排班-插入排班成功:org_id: %v", mode.OrgID)
122
-
123
-		time.Sleep(time.Second * 30)
124
-	}
125
-
126
-	utils.SuccessLog("自动排班任务完成")
127
-}
128
-
129
-func _refreshWeekSchedulesWithTemplateItems(tx *gorm.DB, orgID int64, week time.Time, templateItems []*models.PatientScheduleTemplateItem, deviceNumberMap map[int64]*DeviceNumberViewModel) error {
130
-	if deviceNumberMap == nil {
131
-		deviceNumbers, getDeviceNumbersErr := GetAllValidDeviceNumbers(orgID)
132
-		if getDeviceNumbersErr != nil {
133
-			return getDeviceNumbersErr
134
-		}
135
-		deviceNumberMap = make(map[int64]*DeviceNumberViewModel, 0)
136
-		for _, deviceNumber := range deviceNumbers {
137
-			deviceNumberMap[deviceNumber.ID] = deviceNumber
138
-		}
139
-	}
140
-
141
-	now := time.Now()
142
-	monday, sunday := utils.GetMondayAndSundayOfWeekDate(&week)
143
-	disableErr := tx.Model(&models.Schedule{}).Where("user_org_id = ? AND status = 1 AND schedule_date >= ? AND schedule_date <= ?", orgID, monday.Unix(), sunday.Unix()).Updates(map[string]interface{}{"status": 0, "mtime": now.Unix()}).Error
144
-	if disableErr != nil {
145
-		return disableErr
146
-	}
147
-
148
-	// 批量插入排班
149
-	if len(templateItems) > 0 {
150
-		valueStrs := make([]string, 0, len(templateItems))
151
-		values := make([]interface{}, 0, len(templateItems)*11)
152
-		for _, item := range templateItems {
153
-			deviceNumber := deviceNumberMap[item.DeviceNumberID]
154
-			if deviceNumber == nil {
155
-				continue
156
-			}
157
-
158
-			valueStrs = append(valueStrs, "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
159
-			values = append(values, orgID)
160
-			values = append(values, deviceNumber.ZoneID)
161
-			values = append(values, item.DeviceNumberID)
162
-			values = append(values, item.PatientID)
163
-			values = append(values, monday.AddDate(0, 0, int(item.Weekday-1)).Unix())
164
-			values = append(values, item.Weekday)
165
-			values = append(values, item.TimeType)
166
-			values = append(values, item.TreatMode)
167
-			values = append(values, 1)
168
-			values = append(values, now.Unix())
169
-			values = append(values, now.Unix())
170
-		}
171
-
172
-		sql := fmt.Sprintf("INSERT INTO xt_schedule (user_org_id, partition_id, bed_id, patient_id, schedule_date, schedule_week, schedule_type, mode_id, status, created_time, updated_time) VALUES %v;", strings.Join(valueStrs, ", "))
173
-		if insertErr := tx.Exec(sql, values...).Error; insertErr != nil {
174
-			return insertErr
175
-		}
176
-	}
177
-	return nil
178
-}
179
-
180
-func FakeAutoCreateNextTwoWeekSchedules(orgID int64) {
181
-	mode, getModeErr := GetOrgPatientScheduleTemplateMode(orgID)
182
-	if getModeErr != nil {
183
-		utils.ErrorLog("%v", getModeErr)
184
-		return
185
-	}
186
-
187
-	templates, getTemplatesErr := GetOrgPatientScheduleTemplateIDs(mode.OrgID)
188
-	if getTemplatesErr != nil {
189
-		utils.ErrorLog("获取模板 ID 失败:%v", getTemplatesErr)
190
-		return
191
-	} else if len(templates) == 0 {
192
-		utils.WarningLog("没有模板")
193
-		return
194
-	}
195
-
196
-	deviceNumbers, getDeviceNumbersErr := GetAllValidDeviceNumbers(orgID)
197
-	if getDeviceNumbersErr != nil {
198
-		utils.ErrorLog("获取床位列表失败:%v", getDeviceNumbersErr)
199
-		return
200
-	}
201
-	deviceNumberMap := make(map[int64]*DeviceNumberViewModel, 0)
202
-	for _, deviceNumber := range deviceNumbers {
203
-		deviceNumberMap[deviceNumber.ID] = deviceNumber
204
-	}
205
-
206
-	now := time.Now()
207
-	tx := writeDb.Begin()
208
-
209
-	if mode.Mode == 1 { // 用第一周模板生成下两周的排班
210
-		items, getItemsErr := GetOrgPatientScheduleTemplateItemsWithoutPatientByTemplateID(mode.OrgID, templates[0].ID)
211
-		if getItemsErr != nil {
212
-			utils.ErrorLog("获取第一周模板Item失败:%v", getItemsErr)
213
-			return
214
-		}
215
-		insertErr := _refreshWeekSchedulesWithTemplateItems(tx, mode.OrgID, now.AddDate(0, 0, 7), items, deviceNumberMap)
216
-		if insertErr != nil {
217
-			utils.ErrorLog("使用第一周模板插入下第一周排班失败:%v", insertErr)
218
-			tx.Rollback()
219
-			return
220
-		}
221
-		insertErr = _refreshWeekSchedulesWithTemplateItems(tx, mode.OrgID, now.AddDate(0, 0, 14), items, deviceNumberMap)
222
-		if insertErr != nil {
223
-			utils.ErrorLog("使用第一周模板插入下第二周排班失败:%v", insertErr)
224
-			tx.Rollback()
225
-			return
226
-		}
227
-
228
-	} else if mode.Mode == 2 {
229
-		firstItems, getFirstItemsErr := GetOrgPatientScheduleTemplateItemsWithoutPatientByTemplateID(mode.OrgID, templates[0].ID)
230
-		if getFirstItemsErr != nil {
231
-			utils.ErrorLog("获取第一周模板Item失败:%v", getFirstItemsErr)
232
-			return
233
-		}
234
-		secItems, getSecItemsErr := GetOrgPatientScheduleTemplateItemsWithoutPatientByTemplateID(mode.OrgID, templates[1].ID)
235
-		if getSecItemsErr != nil {
236
-			utils.ErrorLog("获取第一周模板Item失败:%v", getSecItemsErr)
237
-			return
238
-		}
239
-
240
-		if mode.ExecuteTimes%2 == 0 {
241
-			insertErr := _refreshWeekSchedulesWithTemplateItems(tx, mode.OrgID, now.AddDate(0, 0, 7), firstItems, deviceNumberMap)
242
-			if insertErr != nil {
243
-				utils.ErrorLog("使用第一周模板插入下第一周排班失败:%v", insertErr)
244
-				tx.Rollback()
245
-				return
246
-			}
247
-			insertErr = _refreshWeekSchedulesWithTemplateItems(tx, mode.OrgID, now.AddDate(0, 0, 14), secItems, deviceNumberMap)
248
-			if insertErr != nil {
249
-				utils.ErrorLog("使用第二周模板插入下第二周排班失败:%v", insertErr)
250
-				tx.Rollback()
251
-				return
252
-			}
253
-
254
-		} else { // mode.ExecuteTimes%2 == 1
255
-			insertErr := _refreshWeekSchedulesWithTemplateItems(tx, mode.OrgID, now.AddDate(0, 0, 7), secItems, deviceNumberMap)
256
-			if insertErr != nil {
257
-				utils.ErrorLog("使用第二周模板插入下第一周排班失败:%v", mode.OrgID, insertErr)
258
-				tx.Rollback()
259
-				return
260
-			}
261
-			insertErr = _refreshWeekSchedulesWithTemplateItems(tx, mode.OrgID, now.AddDate(0, 0, 14), firstItems, deviceNumberMap)
262
-			if insertErr != nil {
263
-				utils.ErrorLog("使用第一周模板插入下第二周排班失败:%v", mode.OrgID, insertErr)
264
-				tx.Rollback()
265
-				return
266
-			}
267
-		}
268
-	}
269
-
270
-	mode.ExecuteTimes += 2
271
-	mode.ModifyTime = now.Unix()
272
-	updateModeErr := tx.Save(mode).Error
273
-	if updateModeErr != nil {
274
-		utils.ErrorLog("更新启用模板模式的执行次数失败:%v", mode.OrgID, updateModeErr)
275
-		tx.Rollback()
276
-		return
277
-	}
278
-
279
-	tx.Commit()
280
-	utils.SuccessLog("模拟自动更新下两周排班成功")
281
-}

Разница между файлами не показана из-за своего большого размера
+ 0 - 3319
models/service/common_service.go


+ 0 - 239
models/service/data.go Просмотреть файл

@@ -1,239 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	_ "github.com/astaxie/beego"
6
-	_ "strconv"
7
-	_ "strings"
8
-	"time"
9
-)
10
-
11
-//GetPatientList 返回患者的列表
12
-func GetConfigList(orgID int64) (dataconfig interface{}, err error) {
13
-	var configList []*models.Dataconfig
14
-
15
-	err = readDb.Model(&models.Dataconfig{}).Where("(org_id in (0,?) and status = 1) or (status = 0 and delete_id_system > 0 and org_id = ?)", orgID, orgID).Order("orders asc, id asc").Find(&configList).Error
16
-	if err != nil {
17
-		return nil, err
18
-	}
19
-
20
-	// configResult := make([]*ConfigViewModel,0)
21
-	childConfig := make(map[int64][]*models.Dataconfig)
22
-	resultConfig := make(map[string][]*models.ConfigViewModel)
23
-	deleteSystemChilds := make([]*models.Dataconfig, 0)
24
-	editSystemChilds := make([]*models.Dataconfig, 0)
25
-	for _, config := range configList {
26
-		if config.Status == 1 && config.DeleteIdSystem > 0 {
27
-			editSystemChilds = append(editSystemChilds, config)
28
-		}
29
-
30
-		if config.Status == 0 && config.DeleteIdSystem > 0 {
31
-			deleteSystemChilds = append(deleteSystemChilds, config)
32
-		}
33
-	}
34
-	continueFlag := false
35
-	for _, config := range configList {
36
-		continueFlag = false
37
-		if config.ParentId == 0 {
38
-			newConfig := &models.ConfigViewModel{
39
-				ID:           config.ID,
40
-				ParentId:     config.ParentId,
41
-				Module:       config.Module,
42
-				OrgId:        config.OrgId,
43
-				Name:         config.Name,
44
-				FieldName:    config.FieldName,
45
-				Value:        config.Value,
46
-				CreateUserId: config.CreateUserId,
47
-				Status:       config.Status,
48
-				Remark:       config.Remark,
49
-				Title:        config.Title,
50
-				Content:      config.Content,
51
-			}
52
-			// configResult = append(configResult,newConfig)
53
-			result := resultConfig[config.Module]
54
-			if result == nil {
55
-				result = make([]*models.ConfigViewModel, 0)
56
-			}
57
-			for _, vm := range editSystemChilds {
58
-				if vm.DeleteIdSystem == config.ID {
59
-					continueFlag = true
60
-					break
61
-				}
62
-			}
63
-
64
-			for _, _vm := range deleteSystemChilds {
65
-				if _vm.DeleteIdSystem == config.ID {
66
-					continueFlag = true
67
-					break
68
-				}
69
-			}
70
-			if config.OrgId != 0 && config.Status == 0 && config.DeleteIdSystem > 0 {
71
-				continue
72
-			}
73
-			if continueFlag {
74
-				continue
75
-			}
76
-			result = append(result, newConfig)
77
-			resultConfig[config.Module] = result
78
-		} else {
79
-			childs := childConfig[config.ParentId]
80
-			if childs == nil {
81
-				childs = make([]*models.Dataconfig, 0)
82
-			}
83
-			continueFlag := false
84
-			for _, vm := range editSystemChilds {
85
-				if vm.DeleteIdSystem == config.ID {
86
-					continueFlag = true
87
-					break
88
-				}
89
-			}
90
-
91
-			for _, _vm := range deleteSystemChilds {
92
-				if _vm.DeleteIdSystem == config.ID {
93
-					continueFlag = true
94
-					break
95
-				}
96
-			}
97
-			if config.OrgId != 0 && config.Status == 0 && config.DeleteIdSystem > 0 {
98
-				continue
99
-			}
100
-			if continueFlag {
101
-				continue
102
-			}
103
-
104
-			childs = append(childs, config)
105
-			childConfig[config.ParentId] = childs
106
-		}
107
-	}
108
-
109
-	for _, vm := range resultConfig {
110
-		for _, _vm := range vm {
111
-			_vm.Childs = childConfig[_vm.ID]
112
-		}
113
-		// vm.Childs = childConfig[vm.ID]
114
-	}
115
-	return resultConfig, err
116
-}
117
-
118
-func FindConfigByFieldname(module string, field_name string, org_id int64) (dataconfig models.Dataconfig, err error) {
119
-	err = readDb.Model(&models.Dataconfig{}).Where("module=? and field_name=? and org_id in (0,?) and status = 1", module, field_name, org_id).First(&dataconfig).Error
120
-	return
121
-}
122
-
123
-func FindConfigByTitle(module string, title string, org_id int64) (dataconfig models.Dataconfig, err error) {
124
-	err = readDb.Model(&models.Dataconfig{}).Where("module=? and title=? and org_id in (0,?) and status = 1", module, title, org_id).First(&dataconfig).Error
125
-	return
126
-}
127
-
128
-func FindConfigByName(module string, name string, parent_id int64, org_id int64) (dataconfig models.Dataconfig, err error) {
129
-	err = readDb.Model(&models.Dataconfig{}).Where("module=? and name=? and parent_id=? and org_id in (0,?) and status = 1", module, name, parent_id, org_id).First(&dataconfig).Error
130
-	return
131
-}
132
-
133
-func FindConfigByNameForUpdate(module string, name string, parent_id int64, org_id int64, id int64) (dataconfig models.Dataconfig, err error) {
134
-	err = readDb.Model(&models.Dataconfig{}).Where("module=? and name=? and parent_id=? and org_id in (0,?) and id != ? and status = 1", module, name, parent_id, org_id, id).First(&dataconfig).Error
135
-	return
136
-}
137
-
138
-func FindConfigByTitleForUpdate(module string, title string, org_id int64, id int64) (dataconfig models.Dataconfig, err error) {
139
-	err = readDb.Model(&models.Dataconfig{}).Where("module=? and title=? and org_id in (0,?) and id != ? and status = 1", module, title, org_id, id).First(&dataconfig).Error
140
-	return
141
-}
142
-
143
-func UpdateChildConfig(dataconfig *models.Dataconfig) (err error) {
144
-	err = readDb.Model(&models.Dataconfig{}).Where("id =?", dataconfig.ID).Update(map[string]interface{}{"name": dataconfig.Name, "update_time": dataconfig.UpdatedTime, "remark": dataconfig.Remark, "orders": dataconfig.Order}).Error
145
-	return
146
-}
147
-
148
-func UpdateTemplate(dataconfig *models.Dataconfig) (err error) {
149
-	err = readDb.Model(&models.Dataconfig{}).Where("id =?", dataconfig.ID).Update(map[string]interface{}{"title": dataconfig.Title, "content": dataconfig.Content, "update_time": dataconfig.UpdatedTime, "remark": dataconfig.Remark}).Error
150
-	return
151
-}
152
-
153
-func CreateConfig(dataconfig *models.Dataconfig) (err error) {
154
-	// readDb.Model(&models.Dataconfig{}).Where("module = ? and parent_id = 0 and org_id in (0,?)",dataconfig.Module,dataconfig.OrgId).Count(&total)
155
-	err = readDb.Create(&dataconfig).Error
156
-	return
157
-}
158
-
159
-func GetChildValue(module string, parent_id int64, org_id int64) (value int) {
160
-	readDb.Model(&models.Dataconfig{}).Where("module=? and parent_id=? and org_id in (0,?)", module, parent_id, org_id).Count(&value)
161
-	return
162
-}
163
-
164
-func DeleteChildConfig(dataconfig *models.Dataconfig) (err error) {
165
-	err = readDb.Model(&models.Dataconfig{}).Where("id =?", dataconfig.ID).Update(map[string]interface{}{"status": dataconfig.Status, "update_time": dataconfig.UpdatedTime}).Error
166
-	return
167
-}
168
-
169
-func FindFiledByOrgId(org_id int64) (filedConfig []*models.FiledConfig, err error) {
170
-	err = readDb.Model(&models.FiledConfig{}).Where("org_id =? AND  sys_module = 0", org_id).Find(&filedConfig).Error
171
-	return
172
-}
173
-
174
-func FindQualityByOrgId(orgid int64) (xtquality []*models.XtQualityControlStandard, err error) {
175
-
176
-	err = readDb.Model(&models.XtQualityControlStandard{}).Where("user_org_id =? and status =1 and is_status = 1", orgid).Find(&xtquality).Error
177
-	return
178
-}
179
-
180
-func GetDefaultSystolicPressure(orgid int64) (xtquality []*models.XtQualityControlStandard, err error) {
181
-
182
-	err = readDb.Model(&models.XtQualityControlStandard{}).Where("user_org_id = ? and status = 1 and is_status =0", orgid).Find(&xtquality).Error
183
-	return
184
-}
185
-
186
-func FindeInspectionByOrgId(orgid int64) (xtquality []*models.XtCheckConfiguration, err error) {
187
-
188
-	err = readDb.Model(&models.XtQualityControlStandard{}).Where("user_org_id = ? and status =1", orgid).Find(&xtquality).Error
189
-	return
190
-}
191
-
192
-func BatchInsertFiledConfig(org_id int64) (err error) {
193
-	err = readDb.Exec("INSERT  INTO sgj_xt.xt_filed_config  ( org_id,  module,  filed_name,  filed_name_cn,  is_show ) SELECT ?,  module,  filed_name,  filed_name_cn,  is_show FROM sgj_xt.xt_filed_config  WHERE org_id = 0 AND is_show = 1", org_id).Error
194
-	return
195
-}
196
-
197
-func BatchInsertQualityControl(org_id int64) (err error) {
198
-
199
-	err = readDb.Exec("INSERT INTO xt_quality_control_standard(user_org_id,inspection_major,inspection_minor,min_range,large_range,sort,created_time,status,range_type,range_value,is_status) SELECT ?,inspection_major,inspection_minor,min_range,large_range,sort,created_time,status,range_type,range_value,is_status FROM xt_quality_control_standard where user_org_id = 0 and is_status = 1", org_id).Error
200
-	return
201
-}
202
-
203
-func BathInsertQualityControlTwo(org_id int64) (err error) {
204
-	err = readDb.Exec("INSERT INTO xt_quality_control_standard(user_org_id,inspection_major,inspection_minor,min_range,large_range,sort,created_time,status,range_type,range_value,is_status) SELECT ?,inspection_major,inspection_minor,min_range,large_range,sort,created_time,status,range_type,range_value,is_status FROM xt_quality_control_standard where user_org_id = 0 and is_status = 0", org_id).Error
205
-	return
206
-}
207
-
208
-func BatchInspectionConfiguration(orgid int64) (err error) {
209
-
210
-	err = readDb.Exec("INSERT INTO xt_check_configuration(user_org_id,inspection_major,inspection_frequency,sort,created_time,status) SELECT ?,inspection_major,inspection_frequency,sort,created_time,status FROM xt_check_configuration where user_org_id = 0", orgid).Error
211
-	return
212
-}
213
-
214
-func ShowFiledConfig(org_id int64, isShow int, id int64) (err error) {
215
-	err = readDb.Model(&models.FiledConfig{}).Where("org_id = ? AND id = ?", org_id, id).Updates(map[string]interface{}{"ctime": time.Now().Unix(), "mtime": time.Now().Unix(), "is_show": isShow}).Error
216
-	return
217
-}
218
-
219
-func FindSysDialysisFiledByOrgId() (filedConfig []*models.FiledConfig, err error) {
220
-	err = readDb.Model(&models.FiledConfig{}).Where("org_id =? AND id in (11250,11251,11252,11253,11254,11255,11256,11257,11258,11259,11260,11261,11262)", 0).Find(&filedConfig).Error
221
-	return
222
-}
223
-
224
-func BatchInsertFiledSystemConfig(org_id int64) (err error) {
225
-	err = readDb.Exec("INSERT  INTO sgj_xt.xt_filed_config  ( org_id,  module,  filed_name,  filed_name_cn,  is_show ) SELECT ?,  module,  filed_name,  filed_name_cn,  is_show FROM sgj_xt.xt_filed_config  WHERE org_id = 9442", org_id).Error
226
-	return
227
-}
228
-
229
-func BatchInsertDoctorSchedule(orgid int64) (err error) {
230
-
231
-	err = readDb.Exec("INSERT INTO sgj_xt.xt_doctor_schedules(user_org_id,class_name,class_attributes,timeone_start,timeone_type,timeone_end,timetwo_start,timetwo_type,timetwo_end,work_time,remarks,status,ctime,minute) SELECT ?, class_name,class_attributes,timeone_start,timeone_type,timeone_end,timetwo_start,timetwo_type,timetwo_end,work_time,remarks,status,ctime,minute FROM xt_doctor_schedules WHERE user_org_id = 0", orgid).Error
232
-	return
233
-}
234
-
235
-func CreateContinueSchedule(schedule *models.ContinueSchedule) error {
236
-
237
-	err := writeDb.Model(&schedule).Create(&schedule).Error
238
-	return err
239
-}

+ 0 - 290
models/service/db.go Просмотреть файл

@@ -1,290 +0,0 @@
1
-// Pipe - A small and beautiful blogging platform written in golang.
2
-// Copyright (C) 2017-2018, b3log.org
3
-//
4
-// This program is free software: you can redistribute it and/or modify
5
-// it under the terms of the GNU General Public License as published by
6
-// the Free Software Foundation, either version 3 of the License, or
7
-// (at your option) any later version.
8
-//
9
-// This program is distributed in the hope that it will be useful,
10
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
-// GNU General Public License for more details.
13
-//
14
-// You should have received a copy of the GNU General Public License
15
-// along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
-
17
-package service
18
-
19
-import (
20
-	"fmt"
21
-
22
-	"github.com/astaxie/beego"
23
-	"github.com/jinzhu/gorm"
24
-	_ "github.com/jinzhu/gorm/dialects/mysql" // mysql
25
-)
26
-
27
-var readDb *gorm.DB
28
-var writeDb *gorm.DB
29
-var readUserDb *gorm.DB
30
-var writeUserDb *gorm.DB
31
-
32
-var readDb2 *gorm.DB
33
-
34
-var readMiddleDb *gorm.DB
35
-var writeMiddleDb *gorm.DB
36
-
37
-var readPatientDb *gorm.DB
38
-var writePatientDb *gorm.DB
39
-
40
-var readSgjPatientDb *gorm.DB
41
-var writeSgjPatientDb *gorm.DB
42
-
43
-var readUserDbT *gorm.DB
44
-var writeUserDbT *gorm.DB
45
-
46
-var err error
47
-
48
-func ConnectDB() {
49
-	readHost := beego.AppConfig.String("readmysqlhost")
50
-	readPort := beego.AppConfig.String("readmysqlport")
51
-	readUser := beego.AppConfig.String("readmysqluser")
52
-	readPass := beego.AppConfig.String("readmysqlpass")
53
-	readName := beego.AppConfig.String("readmysqlname")
54
-
55
-	readHost2 := beego.AppConfig.String("readmysqlhost2")
56
-	readPort2 := beego.AppConfig.String("readmysqlport2")
57
-	readUser2 := beego.AppConfig.String("readmysqluser2")
58
-	readPass2 := beego.AppConfig.String("readmysqlpass2")
59
-	readName2 := beego.AppConfig.String("readmysqlname2")
60
-
61
-	writeHost := beego.AppConfig.String("writemysqlhost")
62
-	writePort := beego.AppConfig.String("writemysqlport")
63
-	writeUser := beego.AppConfig.String("writemysqluser")
64
-	writePass := beego.AppConfig.String("writemysqlpass")
65
-	writeName := beego.AppConfig.String("writemysqlname")
66
-
67
-	readUserHost := beego.AppConfig.String("readuserhost")
68
-	readUserPort := beego.AppConfig.String("readuserport")
69
-	readUserUser := beego.AppConfig.String("readuseruser")
70
-	readUserPass := beego.AppConfig.String("readuserpass")
71
-	readUserName := beego.AppConfig.String("readusername")
72
-
73
-	writeUserHost := beego.AppConfig.String("writeuserhost")
74
-	writeUserPort := beego.AppConfig.String("writeuserport")
75
-	writeUserUser := beego.AppConfig.String("writeuseruser")
76
-	writeUserPass := beego.AppConfig.String("writeuserpass")
77
-	writeUserName := beego.AppConfig.String("writeusername")
78
-
79
-	readMiddleHost := beego.AppConfig.String("readmiddlehost")
80
-	readMiddlePort := beego.AppConfig.String("readmiddleport")
81
-	readMiddleUser := beego.AppConfig.String("readmiddleuser")
82
-	readMiddlePass := beego.AppConfig.String("readmiddlepass")
83
-	readMiddleName := beego.AppConfig.String("readmiddlename")
84
-
85
-	writeMiddleHost := beego.AppConfig.String("writemiddlehost")
86
-	writeMiddlePort := beego.AppConfig.String("writemiddleport")
87
-	writeMiddleUser := beego.AppConfig.String("writemiddleuser")
88
-	writeMiddlePass := beego.AppConfig.String("writemiddlepass")
89
-	writeMiddleName := beego.AppConfig.String("writemiddlename")
90
-
91
-	readPatientHost := beego.AppConfig.String("readpatienthost")
92
-	readPatientPort := beego.AppConfig.String("readpatientport")
93
-	readPatientUser := beego.AppConfig.String("readpatientuser")
94
-	readPatientPass := beego.AppConfig.String("readpatientpass")
95
-	readPatientName := beego.AppConfig.String("readpatientname")
96
-
97
-	writePatientHost := beego.AppConfig.String("writepatienthost")
98
-	writePatientPort := beego.AppConfig.String("writepatientport")
99
-	writePatientUser := beego.AppConfig.String("writepatientuser")
100
-	writePatientPass := beego.AppConfig.String("writepatientpass")
101
-	writePatientName := beego.AppConfig.String("writepatientname")
102
-
103
-	readSgjPatientHost := beego.AppConfig.String("readsgjpatientmysqlhost")
104
-	readSgjPatientPort := beego.AppConfig.String("readsgjpatientmysqlport")
105
-	readSgjPatientUser := beego.AppConfig.String("readsgjpatientmysqluser")
106
-	readSgjPatientPass := beego.AppConfig.String("readsgjpatientmysqlpass")
107
-	readSgjPatientName := beego.AppConfig.String("readsgjpatientmysqlname")
108
-
109
-	writeSgjPatientHost := beego.AppConfig.String("writesgjpatientmysqlhost")
110
-	writeSgjPatientPort := beego.AppConfig.String("writesgjpatientmysqlport")
111
-	writeSgjPatientUser := beego.AppConfig.String("writesgjpatientmysqluser")
112
-	writeSgjPatientPass := beego.AppConfig.String("writesgjpatientmysqlpass")
113
-	writeSgjPatientName := beego.AppConfig.String("writesgjpatientmysqlname")
114
-
115
-	readUserHostT := beego.AppConfig.String("readuserhostTest")
116
-	readUserPortT := beego.AppConfig.String("readuserportTest")
117
-	readUserUserT := beego.AppConfig.String("readuseruserTest")
118
-	readUserPassT := beego.AppConfig.String("readuserpassTest")
119
-	readUserNameT := beego.AppConfig.String("readusernameTest")
120
-
121
-	writeUserHostT := beego.AppConfig.String("writeuserhostTest")
122
-	writeUserPortT := beego.AppConfig.String("writeuserportTest")
123
-	writeUserUserT := beego.AppConfig.String("writeuseruserTest")
124
-	writeUserPassT := beego.AppConfig.String("writeuserpassTest")
125
-	writeUserNameT := beego.AppConfig.String("writeusernameTest")
126
-
127
-	rdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readUser, readPass, readHost, readPort, readName)
128
-	rdsn2 := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readUser2, readPass2, readHost2, readPort2, readName2)
129
-
130
-	wdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writeUser, writePass, writeHost, writePort, writeName)
131
-
132
-	rudsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readUserUser, readUserPass, readUserHost, readUserPort, readUserName)
133
-	wudsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writeUserUser, writeUserPass, writeUserHost, writeUserPort, writeUserName)
134
-
135
-	rmdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readMiddleUser, readMiddlePass, readMiddleHost, readMiddlePort, readMiddleName)
136
-	wmdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writeMiddleUser, writeMiddlePass, writeMiddleHost, writeMiddlePort, writeMiddleName)
137
-
138
-	rpdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readPatientUser, readPatientPass, readPatientHost, readPatientPort, readPatientName)
139
-	wpdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writePatientUser, writePatientPass, writePatientHost, writePatientPort, writePatientName)
140
-
141
-	rspdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readSgjPatientUser, readSgjPatientPass, readSgjPatientHost, readSgjPatientPort, readSgjPatientName)
142
-	wspdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writeSgjPatientUser, writeSgjPatientPass, writeSgjPatientHost, writeSgjPatientPort, writeSgjPatientName)
143
-
144
-	rudsnT := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readUserUserT, readUserPassT, readUserHostT, readUserPortT, readUserNameT)
145
-	wudsnT := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writeUserUserT, writeUserPassT, writeUserHostT, writeUserPortT, writeUserNameT)
146
-
147
-	readDb, err = gorm.Open("mysql", rdsn)
148
-	readDb2, err = gorm.Open("mysql", rdsn2)
149
-
150
-	if err != nil {
151
-		//beego.Error(err)
152
-	}
153
-	readDb.DB().SetMaxIdleConns(10)
154
-	readDb.DB().SetMaxOpenConns(100)
155
-	readDb.LogMode(true)
156
-
157
-	readDb2.DB().SetMaxIdleConns(10)
158
-	readDb2.DB().SetMaxOpenConns(100)
159
-	readDb2.LogMode(true)
160
-
161
-	writeDb, err = gorm.Open("mysql", wdsn)
162
-	if err != nil {
163
-		//beego.Error(err)
164
-	}
165
-	writeDb.DB().SetMaxIdleConns(10)
166
-	writeDb.DB().SetMaxOpenConns(100)
167
-	writeDb.LogMode(true)
168
-
169
-	readUserDbT, err = gorm.Open("mysql", rudsnT)
170
-	if err != nil {
171
-		//beego.Error(err)
172
-	}
173
-	readUserDbT.DB().SetMaxIdleConns(10)
174
-	readUserDbT.DB().SetMaxOpenConns(100)
175
-	readUserDbT.LogMode(true)
176
-
177
-	writeUserDbT, err = gorm.Open("mysql", wudsnT)
178
-	if err != nil {
179
-		//beego.Error(err)
180
-	}
181
-	writeUserDbT.DB().SetMaxIdleConns(10)
182
-	writeUserDbT.DB().SetMaxOpenConns(100)
183
-	writeUserDbT.LogMode(true)
184
-
185
-	readUserDb, err = gorm.Open("mysql", rudsn)
186
-	if err != nil {
187
-		//beego.Error(err)
188
-	}
189
-	readUserDb.DB().SetMaxIdleConns(10)
190
-	readUserDb.DB().SetMaxOpenConns(100)
191
-	readUserDb.LogMode(true)
192
-
193
-	writeUserDb, err = gorm.Open("mysql", wudsn)
194
-	if err != nil {
195
-		//beego.Error(err)
196
-	}
197
-	writeUserDb.DB().SetMaxIdleConns(10)
198
-	writeUserDb.DB().SetMaxOpenConns(100)
199
-	writeUserDb.LogMode(true)
200
-
201
-	readMiddleDb, err = gorm.Open("mysql", rmdsn)
202
-	if err != nil {
203
-		//beego.Error(err)
204
-	}
205
-	readMiddleDb.DB().SetMaxIdleConns(10)
206
-	readMiddleDb.DB().SetMaxOpenConns(100)
207
-	readMiddleDb.LogMode(true)
208
-
209
-	writeMiddleDb, err = gorm.Open("mysql", wmdsn)
210
-	if err != nil {
211
-		//beego.Error(err)
212
-	}
213
-	writeMiddleDb.DB().SetMaxIdleConns(10)
214
-	writeMiddleDb.DB().SetMaxOpenConns(100)
215
-	writeMiddleDb.LogMode(true)
216
-
217
-	readPatientDb, err = gorm.Open("mysql", rpdsn)
218
-	if err != nil {
219
-		beego.Error(err)
220
-	}
221
-	readPatientDb.DB().SetMaxIdleConns(10)
222
-	readPatientDb.DB().SetMaxOpenConns(100)
223
-	readPatientDb.LogMode(true)
224
-
225
-	writePatientDb, err = gorm.Open("mysql", wpdsn)
226
-	if err != nil {
227
-		beego.Error(err)
228
-	}
229
-	writePatientDb.DB().SetMaxIdleConns(10)
230
-	writePatientDb.DB().SetMaxOpenConns(100)
231
-	writePatientDb.LogMode(true)
232
-
233
-	readSgjPatientDb, err = gorm.Open("mysql", rspdsn)
234
-	if err != nil {
235
-		beego.Error(err)
236
-	}
237
-	readSgjPatientDb.DB().SetMaxIdleConns(10)
238
-	readSgjPatientDb.DB().SetMaxOpenConns(100)
239
-	readSgjPatientDb.LogMode(true)
240
-
241
-	writeSgjPatientDb, err = gorm.Open("mysql", wspdsn)
242
-	if err != nil {
243
-		beego.Error(err)
244
-	}
245
-	writeSgjPatientDb.DB().SetMaxIdleConns(10)
246
-	writeSgjPatientDb.DB().SetMaxOpenConns(100)
247
-	writeSgjPatientDb.LogMode(true)
248
-}
249
-
250
-//func DisconnectDB() {
251
-//	if err := readDb.Close(); nil != err {
252
-//		beego.Error("Disconnect from database failed: " + err.Error())
253
-//	}
254
-//}
255
-
256
-func XTReadDB() *gorm.DB {
257
-	return readDb
258
-}
259
-func XTWriteDB() *gorm.DB {
260
-	return writeDb
261
-}
262
-func UserReadDB() *gorm.DB {
263
-	return readUserDb
264
-}
265
-func UserWriteDB() *gorm.DB {
266
-	return writeUserDb
267
-}
268
-
269
-func MiddleReadDB() *gorm.DB {
270
-	return readMiddleDb
271
-}
272
-func MiddleWriteDB() *gorm.DB {
273
-	return writeMiddleDb
274
-}
275
-
276
-func PatientReadDB() *gorm.DB {
277
-	return readPatientDb
278
-}
279
-
280
-func PatientWriteDB() *gorm.DB {
281
-	return writePatientDb
282
-}
283
-
284
-func SgjPatientReadDB() *gorm.DB {
285
-	return readSgjPatientDb
286
-}
287
-
288
-func SgjPatientWriteDB() *gorm.DB {
289
-	return writeSgjPatientDb
290
-}

+ 0 - 27
models/service/db_err_service.go Просмотреть файл

@@ -1,27 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"fmt"
5
-	"time"
6
-
7
-	"XT_New/models"
8
-	"XT_New/utils"
9
-)
10
-
11
-func CreateDBErrorRecord(orgID int64, decsFormat string, v ...interface{}) {
12
-	if orgID < 0 {
13
-		orgID = 0
14
-	}
15
-	now := time.Now()
16
-	record := models.DBErrorRecord{
17
-		OrgID:      orgID,
18
-		ErrDesc:    fmt.Sprintf(decsFormat, v...),
19
-		Status:     1,
20
-		CreateTime: now.Unix(),
21
-		ModifyTime: now.Unix(),
22
-	}
23
-	insertErr := writeDb.Save(&record).Error
24
-	if insertErr != nil {
25
-		utils.ErrorLog("插入数据库执行错误记录失败:%v", insertErr)
26
-	}
27
-}

+ 0 - 715
models/service/device_service.go Просмотреть файл

@@ -1,715 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	"fmt"
6
-	"github.com/jinzhu/gorm"
7
-	"strings"
8
-	"time"
9
-)
10
-
11
-//////// 设备基本信息
12
-
13
-func GetValidDevicesBy(orgID int64, deviceType int, zoneID int64) ([]*models.Device, error) {
14
-	var devices []*models.Device
15
-	db := readDb.Model(&models.Device{}).Where("org_id = ? AND status = 1", orgID)
16
-	if deviceType != 0 {
17
-		db = db.Where("device_type = ?", deviceType)
18
-	}
19
-	if zoneID != 0 {
20
-		db = db.Where("device_zone_id = ?", zoneID)
21
-	}
22
-	err := db.Find(&devices).Error
23
-	if err != nil {
24
-		return nil, err
25
-	}
26
-	return devices, nil
27
-}
28
-
29
-// 根据设备关联表的 id,获取设备关联信息
30
-func GetDeviceByID(orgID int64, deviceID int64) (*models.Device, error) {
31
-	var device models.Device
32
-	err := readDb.Model(&models.Device{}).Where("org_id = ? AND id = ?", orgID, deviceID).First(&device).Error
33
-	if err != nil {
34
-		if err == gorm.ErrRecordNotFound {
35
-			return nil, nil
36
-		} else {
37
-			return nil, err
38
-		}
39
-	}
40
-	return &device, nil
41
-}
42
-
43
-func GetDMDeviceByID(orgID int64, id int64) (*models.DeviceDM, error) {
44
-	var device models.DeviceDM
45
-	err := readDb.Model(&models.DeviceDM{}).Where("org_id = ? AND id = ?", orgID, id).First(&device).Error
46
-	if err != nil {
47
-		if err == gorm.ErrRecordNotFound {
48
-			return nil, nil
49
-		} else {
50
-			return nil, err
51
-		}
52
-	}
53
-	return &device, nil
54
-}
55
-
56
-func GetWTEDeviceByID(orgID int64, id int64) (*models.DeviceWTE, error) {
57
-	var device models.DeviceWTE
58
-	err := readDb.Model(&models.DeviceWTE{}).Where("org_id = ? AND id = ?", orgID, id).First(&device).Error
59
-	if err != nil {
60
-		if err == gorm.ErrRecordNotFound {
61
-			return nil, nil
62
-		} else {
63
-			return nil, err
64
-		}
65
-	}
66
-	return &device, nil
67
-}
68
-
69
-// type DeviceBaseInfoViewModel struct {
70
-// 	DeviceType     int   `json:"device_type"`
71
-// 	DeviceNumberID int64 `gorm:"column:device_number_id" json:"device_number_id"`
72
-
73
-// 	ID                 int64  `gorm:"column:id" json:"id"`
74
-// 	SerialNumber       string `json:"serial_number"`        // 序列号
75
-// 	Name               string `json:"name"`                 // 设备名
76
-// 	Manufacturer       string `json:"manufacturer"`         // 生产厂家
77
-// 	RepairFactory      string `json:"repair_factory"`       // 维修厂家
78
-// 	Model              string `json:"model"`                // 型号
79
-// 	Department         string `json:"department"`           // 使用科室
80
-// 	DepartmentNumber   string `json:"department_number"`    // 科室编号
81
-// 	PurchaseDate       int64  `json:"purchase_date"`        // 购买日期
82
-// 	InstallDate        int64  `json:"install_date"`         // 安装日期
83
-// 	CommissioningDate  int64  `json:"commissioning_date"`   // 启用日期
84
-// 	Maintainer         string `json:"maintainer"`           // 维修工程师
85
-// 	MaintenanceCall    string `json:"maintenance_call"`     // 维修联系电话
86
-// 	WarrantyPeriod     string `json:"warranty_period"`      // 保修期限
87
-// 	DeviceStatus       int    `json:"device_status"`        // 机器状态 1.使用机 2.备用机 3.急诊机 4.报废机
88
-// 	InitialUseTimes    int    `json:"initial_use_times"`    // 初始使用次数
89
-// 	Mark               string `json:"mark"`                 // 备注
90
-// 	RetirementDate     int64  `json:"retirement_date"`      // 报废日期
91
-// 	RetirementReason   string `json:"retirement_reason"`    // 报废原因
92
-// 	ServiceLife        int    `json:"service_life"`         // 使用年限
93
-// 	WorkingTime        int    `json:"working_time"`         // 工作时长
94
-// 	TreatmentMode      string `json:"treatment_mode"`       // 治疗模式  DeviceType = 1
95
-// 	ReverseOsmosisMode int    `json:"reverse_osmosis_mode"` // 反渗模式  DeviceType = 2
96
-// }
97
-
98
-// // TODO
99
-// func GetDeviceBaseInfoByDeviceID(deviceID int64) (*DeviceBaseInfoViewModel, error) {
100
-// 	return nil, nil
101
-// }
102
-
103
-// 创建透析机
104
-func CreateDMDevice(dmDevice *models.DeviceDM, deviceNumber *models.DeviceNumber) (*models.Device, error) {
105
-	now := time.Now().Unix()
106
-	dmDevice.Status = 1
107
-	dmDevice.CreateTime = now
108
-	dmDevice.ModifyTime = now
109
-	tx := writeDb.Begin()
110
-	createDMErr := tx.Model(&models.DeviceDM{}).Create(dmDevice).Error
111
-	if createDMErr != nil {
112
-		tx.Rollback()
113
-		return nil, createDMErr
114
-	}
115
-	device := models.Device{
116
-		OrgID:        dmDevice.OrgID,
117
-		DeviceType:   1,
118
-		DMID:         dmDevice.ID,
119
-		SerialNumber: dmDevice.SerialNumber,
120
-		Name:         dmDevice.Name,
121
-		Model:        dmDevice.Model,
122
-		Status:       1,
123
-		CreateTime:   now,
124
-		ModifyTime:   now,
125
-	}
126
-	if deviceNumber != nil {
127
-		device.DeviceNumber = deviceNumber.Number
128
-		device.DeviceNumberID = deviceNumber.ID
129
-		device.DeviceZoneID = deviceNumber.ZoneID
130
-		device.DeviceGroupID = deviceNumber.GroupID
131
-	}
132
-	createDeviceErr := tx.Model(&models.Device{}).Create(&device).Error
133
-	if createDeviceErr != nil {
134
-		tx.Rollback()
135
-		return nil, createDeviceErr
136
-	}
137
-	tx.Commit()
138
-	return &device, nil
139
-}
140
-
141
-// 创建水处理机
142
-func CreateWTEDevice(wteDevice *models.DeviceWTE, deviceNumber *models.DeviceNumber) (*models.Device, error) {
143
-	now := time.Now().Unix()
144
-	wteDevice.Status = 1
145
-	wteDevice.CreateTime = now
146
-	wteDevice.ModifyTime = now
147
-	tx := writeDb.Begin()
148
-	createWTEErr := tx.Model(&models.DeviceWTE{}).Create(wteDevice).Error
149
-	if createWTEErr != nil {
150
-		tx.Rollback()
151
-		return nil, createWTEErr
152
-	}
153
-	device := models.Device{
154
-		OrgID:        wteDevice.OrgID,
155
-		DeviceType:   2,
156
-		WTEID:        wteDevice.ID,
157
-		SerialNumber: wteDevice.SerialNumber,
158
-		Name:         wteDevice.Name,
159
-		Model:        wteDevice.Model,
160
-		Status:       1,
161
-		CreateTime:   now,
162
-		ModifyTime:   now,
163
-	}
164
-	if deviceNumber != nil {
165
-		device.DeviceNumber = deviceNumber.Number
166
-		device.DeviceNumberID = deviceNumber.ID
167
-		device.DeviceZoneID = deviceNumber.ZoneID
168
-		device.DeviceGroupID = deviceNumber.GroupID
169
-	}
170
-	createDeviceErr := tx.Model(&models.Device{}).Create(&device).Error
171
-	if createDeviceErr != nil {
172
-		tx.Rollback()
173
-		return nil, createDeviceErr
174
-	}
175
-	tx.Commit()
176
-	return &device, nil
177
-}
178
-
179
-func UpdateDMDevice(dmDevice *models.DeviceDM, deviceNumber *models.DeviceNumber, device *models.Device) error {
180
-	now := time.Now().Unix()
181
-	tx := writeDb.Begin()
182
-	dmDevice.ModifyTime = now
183
-	updateDMErr := tx.Save(dmDevice).Error
184
-	if updateDMErr != nil {
185
-		tx.Rollback()
186
-		return updateDMErr
187
-	}
188
-	device.SerialNumber = dmDevice.SerialNumber
189
-	device.Name = dmDevice.Name
190
-	device.Model = dmDevice.Model
191
-	if deviceNumber != nil {
192
-		device.DeviceNumberID = deviceNumber.ID
193
-		device.DeviceNumber = deviceNumber.Number
194
-		device.DeviceZoneID = deviceNumber.ZoneID
195
-		device.DeviceGroupID = deviceNumber.GroupID
196
-
197
-	} else {
198
-		device.DeviceNumberID = 0
199
-		device.DeviceNumber = ""
200
-		device.DeviceZoneID = 0
201
-		device.DeviceGroupID = 0
202
-	}
203
-	device.ModifyTime = now
204
-	updateDeviceErr := tx.Save(device).Error
205
-	if updateDeviceErr != nil {
206
-		tx.Rollback()
207
-		return updateDeviceErr
208
-	}
209
-	tx.Commit()
210
-	return nil
211
-}
212
-
213
-func UpdateWTEDevice(wteDevice *models.DeviceWTE, deviceNumber *models.DeviceNumber, device *models.Device) error {
214
-	now := time.Now().Unix()
215
-	tx := writeDb.Begin()
216
-	wteDevice.ModifyTime = now
217
-	updateWTEErr := tx.Save(wteDevice).Error
218
-	if updateWTEErr != nil {
219
-		tx.Rollback()
220
-		return updateWTEErr
221
-	}
222
-	device.SerialNumber = wteDevice.SerialNumber
223
-	device.Name = wteDevice.Name
224
-	device.Model = wteDevice.Model
225
-	device.DeviceNumberID = deviceNumber.ID
226
-	device.DeviceNumber = deviceNumber.Number
227
-	device.ModifyTime = now
228
-	updateDeviceErr := tx.Save(device).Error
229
-	if updateDeviceErr != nil {
230
-		tx.Rollback()
231
-		return updateDeviceErr
232
-	}
233
-	tx.Commit()
234
-	return nil
235
-}
236
-
237
-func UpdateDevice(device *models.Device) error {
238
-	err := writeDb.Save(device).Error
239
-	return err
240
-}
241
-
242
-func GetDeviceCountForDeviceNumberID(orgID int64, deviceNumberID int64) (int, error) {
243
-	var count int
244
-	err := readDb.Model(&models.Device{}).Where("device_number_id = ? AND org_id = ? AND status = 1", deviceNumberID, orgID).Count(&count).Error
245
-	if err != nil {
246
-		return 0, err
247
-	}
248
-	return count, nil
249
-}
250
-
251
-//////// 分区 Zone
252
-
253
-func GetAllValidDeviceZones(orgID int64) ([]*models.DeviceZone, error) {
254
-	var zones []*models.DeviceZone
255
-	err := readDb.Model(&models.DeviceZone{}).Where("org_id = ? AND status = 1", orgID).Find(&zones).Error
256
-	if err != nil {
257
-		return nil, err
258
-	}
259
-	return zones, nil
260
-}
261
-
262
-func GetDeviceZoneByID(orgID int64, zoneID int64) (*models.DeviceZone, error) {
263
-	var zone models.DeviceZone
264
-	err := readDb.Model(&models.DeviceZone{}).Where("org_id = ? AND id = ?", orgID, zoneID).First(&zone).Error
265
-	if err != nil {
266
-		if err == gorm.ErrRecordNotFound {
267
-			return nil, nil
268
-		} else {
269
-			return nil, err
270
-		}
271
-	}
272
-	return &zone, nil
273
-}
274
-
275
-func GetZoneByName(name string, orgid int64) (*models.DeviceZone, error) {
276
-	zones := models.DeviceZone{}
277
-	err := XTReadDB().Model(&zones).Where("name = ? and org_id = ? and status = 1", name, orgid).Find(&zones).Error
278
-	if err == gorm.ErrRecordNotFound {
279
-		return nil, err
280
-	}
281
-	if err != nil {
282
-		return nil, err
283
-	}
284
-
285
-	return &zones, nil
286
-}
287
-
288
-func GetZoneByNameOne(name string, orgid int64) (zone models.DeviceZone, err error) {
289
-
290
-	err = XTReadDB().Model(&zone).Where("name = ? and org_id=? and status = 1", name, orgid).First(&zone).Error
291
-	return zone, err
292
-}
293
-
294
-func CreateDeviceZone(orgID int64, name string, type_ int) (*models.DeviceZone, error) {
295
-	now := time.Now().Unix()
296
-	zone := models.DeviceZone{
297
-		OrgID:      orgID,
298
-		Name:       name,
299
-		Type:       type_,
300
-		Status:     1,
301
-		CreateTime: now,
302
-		ModifyTime: now,
303
-	}
304
-	err := writeDb.Model(&models.DeviceZone{}).Create(&zone).Error
305
-	if err != nil {
306
-		return nil, err
307
-	}
308
-	return &zone, nil
309
-}
310
-
311
-func UpdateDeviceZone(zone *models.DeviceZone) error {
312
-	err := writeDb.Save(zone).Error
313
-	return err
314
-}
315
-
316
-//////// 分组 Group
317
-
318
-func GetAllValidDeviceGroups(orgID int64) ([]*models.DeviceGroup, error) {
319
-	var groups []*models.DeviceGroup
320
-	err := readDb.Model(&models.DeviceGroup{}).Where("org_id = ? AND status = 1", orgID).Find(&groups).Error
321
-	if err != nil {
322
-		return nil, err
323
-	}
324
-	return groups, nil
325
-}
326
-
327
-func GetDeviceGroupByID(orgID int64, groupID int64) (*models.DeviceGroup, error) {
328
-	var group models.DeviceGroup
329
-	err := readDb.Model(&models.DeviceGroup{}).Where("org_id = ? AND id = ?", orgID, groupID).First(&group).Error
330
-	if err != nil {
331
-		if err == gorm.ErrRecordNotFound {
332
-			return nil, nil
333
-		} else {
334
-			return nil, err
335
-		}
336
-	}
337
-	return &group, nil
338
-}
339
-
340
-func GetDeviceGroupName(name string, orgid int64) (*models.DeviceGroup, error) {
341
-	group := models.DeviceGroup{}
342
-	err := XTReadDB().Model(&group).Where("name = ? and org_id = ? and status =1", name, orgid).Find(&group).Error
343
-	if err == gorm.ErrRecordNotFound {
344
-		return nil, err
345
-	}
346
-	if err != nil {
347
-		return nil, err
348
-	}
349
-
350
-	return &group, nil
351
-
352
-}
353
-
354
-func CreateDeviceGroup(orgID int64, name string) (*models.DeviceGroup, error) {
355
-	now := time.Now().Unix()
356
-	group := models.DeviceGroup{
357
-		OrgID:      orgID,
358
-		Name:       name,
359
-		Status:     1,
360
-		CreateTime: now,
361
-		ModifyTime: now,
362
-	}
363
-	err := writeDb.Model(&models.DeviceGroup{}).Create(&group).Error
364
-	if err != nil {
365
-		return nil, err
366
-	}
367
-	return &group, nil
368
-}
369
-
370
-func GetUpdateDeviceGroupByName(name string, orgid int64) (group models.DeviceGroup, err error) {
371
-	err = XTReadDB().Model(&group).Where("name = ? and org_id = ? and status =1", name, orgid).Find(&group).Error
372
-	return group, err
373
-}
374
-
375
-func UpdateDeviceGroup(group *models.DeviceGroup) error {
376
-	err := writeDb.Save(group).Error
377
-	return err
378
-}
379
-
380
-//////// 机号 Number
381
-
382
-type DeviceNumberViewModel struct {
383
-	models.DeviceNumber
384
-	ZoneName  string `gorm:"column:zone_name" json:"zone_name"`
385
-	GroupName string `gorm:"column:group_name" json:"group_name"`
386
-}
387
-
388
-func GetAllValidDeviceNumbers(orgID int64) ([]*DeviceNumberViewModel, error) {
389
-	var vms []*DeviceNumberViewModel = make([]*DeviceNumberViewModel, 0)
390
-	rows, err := readDb.Raw("SELECT n.*, z.name as zone_name, g.name as group_name FROM xt_device_number as n join xt_device_zone as z on z.id = n.zone_id AND z.status = 1 join xt_device_group as g on g.id = n.group_id WHERE (n.org_id = ? AND n.status = 1)", orgID).Rows()
391
-	defer rows.Close()
392
-	if err != nil {
393
-		return nil, err
394
-	}
395
-	for rows.Next() {
396
-		var vm DeviceNumberViewModel
397
-		readDb.ScanRows(rows, &vm)
398
-		vms = append(vms, &vm)
399
-	}
400
-	return vms, nil
401
-}
402
-
403
-func GetAllBedNumber(orgId int64) (devicenumber []*models.XtDeviceNumber, err error) {
404
-
405
-	err = XTReadDB().Raw("select id as bed_id,org_id,number as bed_number,group_id,zone_id from xt_device_number as n Where NOT EXISTS (select id,bed_id from sgj_users.xt_device_addmacher as a where a.bed_id = n.id and a.status = 1) AND n.org_id = ? AND n.status = 1 ", orgId).Scan(&devicenumber).Error
406
-	return devicenumber, err
407
-}
408
-
409
-func GetAllBedNumberTwo(orgId int64, id int64) (devicenumber []*models.XtDeviceNumber, err error) {
410
-
411
-	err = XTReadDB().Raw("select id as bed_id,org_id,number as bed_number,group_id,zone_id from xt_device_number as n Where NOT EXISTS (select id,bed_id from sgj_users.xt_device_addmacher as a where a.bed_id = n.id and a.status = 1 and a.id <> ?) AND n.org_id = ? AND n.status = 1 ", id, orgId).Scan(&devicenumber).Error
412
-	return devicenumber, err
413
-}
414
-
415
-func GetAllMachineByOrgId(orgid int64) (addmacher []*models.DeviceAddmacher, err error) {
416
-
417
-	err = UserReadDB().Where("user_org_id = ? AND status = 1", orgid).Find(&addmacher).Error
418
-	return addmacher, err
419
-}
420
-
421
-func GetAllDeviceNumbers(orgID int64, record_date int64, schedule_type int64) ([]*DeviceNumberViewModel, error) {
422
-	var vms []*DeviceNumberViewModel = make([]*DeviceNumberViewModel, 0)
423
-	rows, err := readDb.Raw("SELECT n.*, z.name as zone_name, g.name as group_name FROM xt_device_number as n join xt_device_zone as z on z.id = n.zone_id join xt_device_group as g on g.id = n.group_id  WHERE (n.org_id = ? AND n.status = 1) AND NOT EXISTS (Select * FROM xt_schedule as s, `xt_dialysis_order` as d Where d.`dialysis_date` = ? AND d.`status` = 1 AND d.`patient_id` = s.`patient_id` AND   s.user_org_id = n.org_id AND s.`bed_id` = n.id AND s.`schedule_date` = ? AND s.`schedule_type` = ? AND s.status = 1 )", orgID, record_date, record_date, schedule_type).Rows()
424
-	defer rows.Close()
425
-	if err != nil {
426
-		return nil, err
427
-	}
428
-	for rows.Next() {
429
-		var vm DeviceNumberViewModel
430
-		readDb.ScanRows(rows, &vm)
431
-		vms = append(vms, &vm)
432
-	}
433
-	return vms, nil
434
-}
435
-
436
-func GetDeviceNumberByID(orgID int64, numberID int64) (*models.DeviceNumber, error) {
437
-	var number models.DeviceNumber
438
-	err := readDb.Model(&models.DeviceNumber{}).Where("org_id = ? AND id = ?", orgID, numberID).First(&number).Error
439
-	if err != nil {
440
-		if err == gorm.ErrRecordNotFound {
441
-			return nil, nil
442
-		} else {
443
-			return nil, err
444
-		}
445
-	}
446
-	return &number, nil
447
-}
448
-
449
-func GetCreateDeviceNumber(num string, orgid int64) (*models.DeviceNumber, error) {
450
-	number := models.DeviceNumber{}
451
-	err := XTReadDB().Model(&number).Where("number = ? and org_id = ? and status = 1", num, orgid).Find(&number).Error
452
-	if err == gorm.ErrRecordNotFound {
453
-		return nil, err
454
-	}
455
-	if err != nil {
456
-		return nil, err
457
-	}
458
-
459
-	return &number, nil
460
-}
461
-
462
-func CreateDeviceNumber(orgID int64, number string, zoneID int64, groupID int64) (*models.DeviceNumber, error) {
463
-	now := time.Now().Unix()
464
-	numberModel := models.DeviceNumber{
465
-		OrgID:      orgID,
466
-		Number:     number,
467
-		ZoneID:     zoneID,
468
-		GroupID:    groupID,
469
-		Status:     1,
470
-		CreateTime: now,
471
-		ModifyTime: now,
472
-	}
473
-	err := writeDb.Model(&models.DeviceNumber{}).Create(&numberModel).Error
474
-	if err != nil {
475
-		return nil, err
476
-	}
477
-	return &numberModel, nil
478
-}
479
-
480
-func GetDeviceNumberByName(num string, orgid int64) (number models.DeviceNumber, err error) {
481
-
482
-	err = XTReadDB().Model(&number).Where("number = ? and org_id = ? and status =1", num, orgid).First(&number).Error
483
-	return number, err
484
-}
485
-
486
-func UpdateDeviceNumber(number *models.DeviceNumber) error {
487
-	now := time.Now().Unix()
488
-	number.ModifyTime = now
489
-	tx := writeDb.Begin()
490
-	updateNumberErr := tx.Save(number).Error
491
-	if updateNumberErr != nil {
492
-		tx.Rollback()
493
-		return updateNumberErr
494
-	}
495
-	updateDeviceErr := tx.Model(&models.Device{}).Where("org_id = ? AND device_number_id = ?", number.OrgID, number.ID).Updates(map[string]interface{}{"device_number": number.Number}).Error
496
-	if updateDeviceErr != nil {
497
-		tx.Rollback()
498
-		return updateDeviceErr
499
-	}
500
-	tx.Commit()
501
-	return nil
502
-}
503
-
504
-func GetDeviceNumberCountForZoneID(orgID int64, zoneID int64) (int, error) {
505
-	var count int
506
-	err := readDb.Model(&models.DeviceNumber{}).Where("zone_id = ? AND org_id = ? AND status = 1", zoneID, orgID).Count(&count).Error
507
-	if err != nil {
508
-		return 0, err
509
-	}
510
-	return count, nil
511
-}
512
-
513
-func GetDeviceNumberCountForGroupID(orgID int64, groupID int64) (int, error) {
514
-	var count int
515
-	err := readDb.Model(&models.DeviceNumber{}).Where("group_id = ? AND org_id = ? AND status = 1", groupID, orgID).Count(&count).Error
516
-	if err != nil {
517
-		return 0, err
518
-	}
519
-	return count, nil
520
-}
521
-
522
-func GetScheduleCountForDeviceNumber(orgID int64, deviceNumberID int64, beginDate int64) (int, error) {
523
-	var count int
524
-	err := readDb.Model(&models.Schedule{}).Where("bed_id = ? AND user_org_id = ? AND schedule_date >= ? AND status = 1", deviceNumberID, orgID, beginDate).Count(&count).Error
525
-	if err != nil {
526
-		return 0, err
527
-	}
528
-	return count, nil
529
-}
530
-
531
-func GetScheduleTemplateItemCountForDeviceNumber(orgID int64, deviceNumberID int64) (int, error) {
532
-	var count int
533
-	err := readDb.Model(&models.PatientScheduleTemplateItem{}).Where("device_number_id = ? AND org_id = ? AND status = 1", deviceNumberID, orgID).Count(&count).Error
534
-	if err != nil {
535
-		return 0, err
536
-	}
537
-	return count, nil
538
-}
539
-
540
-func GetZoneId(bednumber int64, orgid int64) (models.DeviceNumber, error) {
541
-
542
-	number := models.DeviceNumber{}
543
-	err := XTReadDB().Model(&number).Where("id = ? AND org_id = ?", bednumber, orgid).Find(&number).Error
544
-	return number, err
545
-}
546
-
547
-//func AddMacher(deviceaddmacher *models.DeviceAddmacher) error{
548
-//	fmt.Println("进来了没哟")
549
-//	tx := writeDb.Begin()
550
-//	err := tx.Model(&models.DeviceAddmachers{}).Create(&deviceaddmacher).Error
551
-//	fmt.Println("错误是什么",err)
552
-//	if err !=nil{
553
-//		tx.Rollback()
554
-//	}
555
-//	tx.Commit()
556
-//	return err
557
-//}
558
-
559
-// func CreateMacher(machers *models.DeviceAddmacher) error {
560
-
561
-// 	begin := writeDb.Begin()
562
-// 	fmt.Println("hhhhhhhh",begin)
563
-// 	err := begin.Model(&models.DeviceAddmacher{}).Create(machers).Error
564
-// 	fmt.Println("err",err)
565
-// 	if err !=nil{
566
-// 		begin.Rollback()
567
-// 	}
568
-// 	begin.Commit()
569
-// 	fmt.Println("执行了没有")
570
-// 	return err
571
-// }
572
-
573
-func GetLastMacherData(orgid int64) (models.DeviceAddmacher, error) {
574
-	addmacher := models.DeviceAddmacher{}
575
-	err := UserReadDB().Model(&addmacher).Where("user_org_id = ? AND status = ?", orgid, 1).Last(&addmacher).Error
576
-	return addmacher, err
577
-}
578
-
579
-func AddTreatMode(machineid int64, orgid int64, treatmodes []int64) (err error) {
580
-	utx := XTWriteDB().Begin()
581
-	if len(treatmodes) > 0 {
582
-		thisSQL := "INSERT INTO xt_device_treatmentmode(machine_id,treate_mode,status,ctime,user_org_id) VALUES "
583
-		insertParams := make([]string, 0)
584
-		insertData := make([]interface{}, 0)
585
-		for _, contagion := range treatmodes {
586
-			insertParams = append(insertParams, "(?, ?, ?, ?, ?)")
587
-			insertData = append(insertData, machineid)
588
-			insertData = append(insertData, contagion)
589
-			insertData = append(insertData, 1)
590
-			insertData = append(insertData, time.Now().Unix())
591
-			insertData = append(insertData, orgid)
592
-		}
593
-		thisSQL += strings.Join(insertParams, ",")
594
-		err = utx.Exec(thisSQL, insertData...).Error
595
-		if err != nil {
596
-			utx.Rollback()
597
-			return
598
-		}
599
-	}
600
-	utx.Commit()
601
-	return
602
-}
603
-
604
-//func DeleteBedNumber(id int64,orgid int64)(error){
605
-//	//err := writeDb.Model(&models.DeviceNumber{}).Where("id = ? AND org_id = ?", id, orgid).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
606
-//	err := writeDb.Model(&models.DeviceNumber{}).Where("id = ? AND org_id = ?", id, orgid).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
607
-//
608
-//
609
-//	fmt.Println("错误是什么",err)
610
-//	return  err
611
-//
612
-//}
613
-//
614
-//func DeleteZoneId(id int64,orgid int64)(error)  {
615
-//	err := writeDb.Model(&models.DeviceZone{}).Where("id = ? AND org_id = ?", id, orgid).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
616
-//	return  err
617
-//}
618
-
619
-func GetAllMachineInfo(page int64, limit int64, keyword string, zoneid int64, equimentid int64, statusid int64, orgid int64) (addmahcer []*models.DeviceAddmachers, total int64, err error) {
620
-
621
-	//db := readUserDb().Table("xt_device_addmacher as a").Where("a.status = 1")
622
-	db := readUserDb.Table("xt_device_addmacher as a").Where("a.status = 1")
623
-	table := XTReadDB().Table("xt_device_zone as x")
624
-	d := readUserDb.Table("xt_device_mode as m")
625
-	d2 := XTReadDB().Table("xt_device_number as n")
626
-	d3 := XTReadDB().Table("xt_device_information as i")
627
-	fmt.Print("d", d)
628
-	fmt.Println("table", table)
629
-	fmt.Print("d2", d2, d3)
630
-	if orgid > 0 {
631
-		db = db.Where("a.user_org_id = ?", orgid)
632
-	}
633
-	if zoneid > 0 {
634
-		db = db.Where("a.zone_id = ?", zoneid)
635
-	}
636
-	if equimentid > 0 {
637
-		db = db.Where("a.device_type = ?", equimentid)
638
-	}
639
-	if statusid > 0 {
640
-		db = db.Where("a.machine_status = ?", statusid)
641
-	}
642
-
643
-	if len(keyword) > 0 {
644
-		keyword = "%" + keyword + "%"
645
-		db = db.Where("a.serial_number LIKE ? OR a.device_name LIKE ? OR a.unit_type LIKE ?", keyword, keyword, keyword)
646
-	}
647
-
648
-	offset := (page - 1) * limit
649
-
650
-	err = db.Group("a.id").Order("a.ctime asc").Select("a.id,a.serial_number,a.device_type,a.bed_number,a.device_name,a.manufacture_factory,a.service_manufacturer,a.unit_type,a.use_section,a.section_number,a.buy_date,a.install_date,a.start_date,a.maintenace_engineer,a.telephone,a.guarantee_date,a.machine_status,a.user_total,a.disinfection_mode,a.remarks,a.rubbish_date,a.rubbish_reason,a.user_year,a.work_time,a.revers_mode,a.user_org_id,a.status,a.ctime,a.mtime,a.bed_id,x.name,m.device_mode,n.number,i.equiment_id").Count(&total).
651
-		Joins("Left JOIN xt_device_mode as m on m.id = a.unit_type ").Joins("left join sgj_xt.xt_device_number as n on n.id = a.bed_id").Joins("Left JOIN sgj_xt.xt_device_zone as x On x.id = n.zone_id").Joins("left join xt_device_information as i on i.bed_number = a.bed_id").Offset(offset).Limit(limit).Scan(&addmahcer).Error
652
-
653
-	if err != nil {
654
-
655
-		return
656
-	}
657
-	return
658
-}
659
-
660
-func GetAllMachine(zoneid int64, classid int64, deviceid int64, timenow int64, orgid int64) (addmahcer []*models.DeviceAddmachers, err error) {
661
-	fmt.Println("timenow", timenow)
662
-	db := readUserDb.Table("xt_device_addmacher as a").Where("a.status = 1")
663
-	//db := XTReadDB().Table("xt_device_addmacher as a").Where("a.status = 1")
664
-	tab := XTReadDB().Table("xt_schedule as x")
665
-	fmt.Println("tab", tab)
666
-	d := readUserDb.Table("xt_device_mode as m")
667
-	fmt.Print("d", d)
668
-	table := XTReadDB().Table("xt_device_number as n")
669
-	fmt.Print("table", table)
670
-	if orgid > 0 {
671
-		db = db.Where("a.user_org_id = ?", orgid)
672
-	}
673
-	if zoneid > 0 {
674
-		db = db.Where("a.zone_id = ?", zoneid)
675
-	}
676
-
677
-	if deviceid > 0 {
678
-		db = db.Where("a.device_type = ?", deviceid)
679
-	}
680
-	if classid > 0 {
681
-		error := db.Joins("LEFT JOIN sgj_xt.xt_schedule as x On x.bed_id = a.bed_id").Joins("LEFT JOIN xt_device_mode as d on d.id = a.unit_type").Joins("lefj join sgj_xt.xt_device_number as n on n.id = a.bed_id").Where("x.user_org_id = ? AND x.schedule_date = ? AND x.schedule_type = ? AND x.status = ?", orgid, timenow, classid, 1).Order("a.ctime desc").Select("a.id,a.serial_number,a.device_type,a.bed_number,a.device_name,a.manufacture_factory,a.service_manufacturer,a.unit_type,a.use_section,a.section_number,a.buy_date,a.install_date,a.start_date,a.maintenace_engineer,a.telephone,a.guarantee_date,a.machine_status,a.user_total,a.disinfection_mode,a.remarks,a.rubbish_date,a.rubbish_reason,a.user_year,a.work_time,a.revers_mode,a.user_org_id,a.status,a.ctime,a.mtime,d.device_mode,n.number").Find(&addmahcer).Error
682
-		fmt.Println("err", error)
683
-	} else {
684
-		err = db.Order("a.ctime asc").Select("a.id,a.serial_number,a.device_type,a.bed_number,a.device_name,a.manufacture_factory,a.service_manufacturer,a.unit_type,a.use_section,a.section_number,a.buy_date,a.install_date,a.start_date,a.maintenace_engineer,a.telephone,a.guarantee_date,a.machine_status,a.user_total,a.disinfection_mode,a.remarks,a.rubbish_date,a.rubbish_reason,a.user_year,a.work_time,a.revers_mode,a.user_org_id,a.status,a.ctime,a.mtime,a.bed_id,d.device_mode,n.number").Joins("LEFT JOIN xt_device_mode as d on d.id = a.unit_type").Joins("left join sgj_xt.xt_device_number as n on n.id = a.bed_id").Find(&addmahcer).Error
685
-		fmt.Println("错误是什么", err)
686
-		if err != nil {
687
-
688
-			return
689
-		}
690
-	}
691
-	return
692
-}
693
-
694
-func GetMachineDetail(id int64, orgid int64) (models.DeviceAddmachers, error) {
695
-	addmacher := models.DeviceAddmachers{}
696
-	//  //	//err := readUserDb.Model(&addmacher).Where("id = ? AND user_org_id = ? AND status = 1", id, orgid).Find(&addmacher).Error
697
-	db := readUserDb.Table("xt_device_addmacher as a").Where("a.status =1")
698
-	d := readUserDb.Table("xt_device_mode as d")
699
-	fmt.Print("d", d)
700
-	err := db.Select("a.id,a.serial_number,a.device_type,a.bed_number,a.device_name,a.manufacture_factory,a.service_manufacturer,a.unit_type as device_mode,a.use_section,a.section_number,a.buy_date,a.install_date,a.start_date,a.maintenace_engineer,a.telephone,a.guarantee_date,a.machine_status,a.user_total,a.disinfection_mode,a.remarks,a.rubbish_date,a.rubbish_reason,a.user_year,a.work_time,a.revers_mode,a.user_org_id,a.status,a.ctime,a.mtime,a.zone_id,a.bed_id").Joins("left join xt_device_mode as d on d.id = a.unit_type ").Where("a.id = ? and a.user_org_id = ?", id, orgid).Find(&addmacher).Error
701
-	return addmacher, err
702
-}
703
-
704
-func GetTreatModel(id int64, orgid int64) (mode []*models.DeviceTreatmentmode, err error) {
705
-	err = XTReadDB().Model(&mode).Where("machine_id = ? AND user_org_id = ? AND status = 1 ", id, orgid).Find(&mode).Error
706
-
707
-	return mode, err
708
-}
709
-
710
-func GetPatientId(id int64) (models.XtPatientsNew, error) {
711
-
712
-	patientsNew := models.XtPatientsNew{}
713
-	err := XTReadDB().Model(&patientsNew).Where("blood_id = ? and status = 1", id).Find(&patientsNew).Error
714
-	return patientsNew, err
715
-}

+ 0 - 304
models/service/dialysis_parameter_service.go Просмотреть файл

@@ -1,304 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	"fmt"
6
-	"github.com/jinzhu/gorm"
7
-)
8
-
9
-func GetDialysisParametersByKeyword(orgID int64, keyword string, schedulType int64, partitionType int64, page int64, limit int64, schedulDate int64) ([]*models.DialysisParameter, error, int64) {
10
-	fmt.Println("scheduletye ======================", schedulType)
11
-	var patients []*models.Patients
12
-	getPatientErr := readDb.Model(&models.Patients{}).Where("status = 1 AND user_org_id = ? AND (name like ? OR dialysis_no like ?)", orgID, "%"+keyword+"%", "%"+keyword+"%").Find(&patients).Error
13
-	if getPatientErr != nil {
14
-		return nil, getPatientErr, 0
15
-	}
16
-	patientIDs := make([]int64, len(patients))
17
-	for index, patient := range patients {
18
-		patientIDs[index] = patient.ID
19
-	}
20
-
21
-	db := readDb.
22
-		Model(&models.DialysisSchedule{}).
23
-		Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
24
-		// Preload("DeviceZone", "status = 1 AND org_id = ?", orgID).
25
-		Preload("TreatmentMode", "status = 1").
26
-		Preload("Prescription", "status = 1 AND user_org_id = ?", orgID).
27
-		Preload("AssessmentBeforeDislysis", "status = 1 AND  user_org_id = ?", orgID).
28
-		Preload("AssessmentAfterDislysis", "status = 1 AND  user_org_id = ?", orgID).
29
-		Preload("MonitoringRecord", "status = 1 AND  user_org_id = ?", orgID).
30
-		Preload("DialysisOrder", "status = 1 AND user_org_id = ?", orgID).
31
-		Preload("MonitorPatients", "status = 1 AND user_org_id = ?", orgID)
32
-	db = db.Where("xt_schedule.status = 1 AND patient_id in (?)", patientIDs)
33
-	if schedulType > 0 {
34
-		db = db.Where("schedule_type = ?", schedulType)
35
-	}
36
-	if partitionType > 0 {
37
-		db = db.Joins("inner join xt_device_number as d_n on d_n.id = xt_schedule.bed_id and d_n.zone_id = ? and d_n.status = 1", partitionType)
38
-	}
39
-	if schedulDate > 0 {
40
-		db = db.Where("schedule_date = ?", schedulDate)
41
-	}
42
-	var schedules []*models.DialysisParameter
43
-	total := int64(0)
44
-	err := db.Count(&total).Offset(limit * (page - 1)).Limit(limit).Order("schedule_date desc").Find(&schedules).Error
45
-	return schedules, err, total
46
-}
47
-
48
-func GetDialysisParameter(orgID int64, schedulDate int64, schedulType int64, partitionType int64, page int64, limit int64) (schedule []*models.DialysisParameter, err error, total int64) {
49
-	db := readDb.
50
-		Model(&models.MonitorDialysisSchedule{}).
51
-		Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
52
-		Preload("TreatmentMode", "status = 1").
53
-		Preload("Prescription", "status = 1 AND user_org_id = ?", orgID).
54
-		Preload("AssessmentBeforeDislysis", "status = 1 AND  user_org_id = ?", orgID).
55
-		Preload("AssessmentAfterDislysis", "status = 1 AND  user_org_id = ?", orgID).
56
-		Preload("MonitoringRecord", func(db *gorm.DB) *gorm.DB {
57
-			return db.Where("status = 1 AND user_org_id = ?", orgID).Order("operate_time asc")
58
-		}).
59
-		Preload("DialysisOrder", "status = 1 AND user_org_id = ?", orgID).
60
-		Preload("MonitorPatients", "status = 1 AND user_org_id = ?", orgID)
61
-	db = db.Where("xt_schedule.status = 1 AND user_org_id = ?", orgID)
62
-	if schedulDate > 0 {
63
-		db = db.Where("schedule_date = ?", schedulDate)
64
-	}
65
-	if schedulType > 0 {
66
-		db = db.Where("schedule_type = ?", schedulType)
67
-	}
68
-	if partitionType > 0 {
69
-		db = db.Joins("inner join xt_device_number on xt_device_number.id = xt_schedule.bed_id and xt_device_number.zone_id = ? and xt_device_number.status = 1", partitionType)
70
-	}
71
-	offset := (page - 1) * limit
72
-	err = db.Count(&total).Offset(offset).Limit(limit).Order("bed_id desc").Find(&schedule).Error
73
-	return schedule, err, total
74
-}
75
-
76
-func GetDialysisBatchParameters(schIDs []string, orgID int64) (schedule []*models.DialysisParameter, err error) {
77
-
78
-	db := readDb.
79
-		Model(&models.DialysisSchedule{}).
80
-		Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
81
-		// Preload("DeviceZone", "status = 1 AND org_id = ?", orgID).
82
-		Preload("TreatmentMode", "status = 1").
83
-		Preload("Prescription", "status = 1 AND user_org_id = ?", orgID).
84
-		Preload("AssessmentBeforeDislysis", "status = 1 AND  user_org_id = ?", orgID).
85
-		Preload("AssessmentAfterDislysis", "status = 1 AND  user_org_id = ?", orgID).
86
-		Preload("MonitoringRecord", "status = 1 AND  user_org_id = ?", orgID).
87
-		Preload("DialysisOrder", "status = 1 AND user_org_id = ?", orgID).
88
-		Preload("MonitorPatients", "status = 1 AND user_org_id = ?", orgID)
89
-	db = db.Where("xt_schedule.status = 1 AND id in (?)", schIDs)
90
-	var schedules []*models.DialysisParameter
91
-	err = db.Order("schedule_date desc").Find(&schedules).Error
92
-	return schedules, err
93
-}
94
-
95
-func GetWareHouseOutList(startime int64, endtime int64, orgid int64) (warehouse []*models.XtWarehouseOutInfo, err error) {
96
-
97
-	db := XTReadDB().Table("xt_warehouse_out_info as x").Where("x.status = 1")
98
-	if startime > 0 {
99
-		db = db.Where("x.sys_record_time >=?", startime)
100
-	}
101
-	if endtime > 0 {
102
-		db = db.Where("x.sys_record_time<=?", endtime)
103
-	}
104
-	if orgid > 0 {
105
-		db = db.Where("x.org_id = ?", orgid)
106
-	}
107
-	err = db.Select("x.id,x.warehouse_out_id,x.good_id,x.good_type_id,x.count,x.warehouse_out_order_number,x.sys_record_time,s.specification_name,t.type_name").Joins("left join xt_good_information as s on s.id = x.good_id").Where("s.status = 1 and s.org_id = ?", orgid).Joins("left join xt_goods_type as t on t.id = x.good_type_id").Order("x.id desc").Scan(&warehouse).Error
108
-	return warehouse, err
109
-}
110
-
111
-func GetAllMaterial(startime int64, endtime int64, orgid int64) (reducedetail []*models.XtAutomaticReduceDetail, err error) {
112
-
113
-	db := XTReadDB().Table("xt_automatic_reduce_detail as x").Where("x.status = 1")
114
-	if startime > 0 {
115
-		db = db.Where("x.record_time>=?", startime)
116
-	}
117
-	if endtime > 0 {
118
-		db = db.Where("x.record_time<=?", endtime)
119
-	}
120
-	if orgid > 0 {
121
-		db = db.Where("x.org_id = ?", orgid)
122
-	}
123
-	err = db.Select("x.patient_id,x.record_time,x.good_id,t.type_name").Joins("left join xt_goods_type as t on t.id = x.good_type_id").Group("x.good_type_id").Scan(&reducedetail).Error
124
-	return reducedetail, err
125
-}
126
-
127
-func GetCollectList(limit int64, page int64, partitionType int64, schedulType int64, schedulDate int64, orgID int64, keyword string) ([]*models.DialysisParameter, error, int64) {
128
-
129
-	var patients []*models.Patients
130
-	getPatientErr := readDb.Model(&models.Patients{}).Where("status = 1 AND user_org_id = ? AND (name like ? OR dialysis_no like ?)", orgID, "%"+keyword+"%", "%"+keyword+"%").Find(&patients).Error
131
-	if getPatientErr != nil {
132
-		return nil, getPatientErr, 0
133
-	}
134
-	patientIDs := make([]int64, len(patients))
135
-	for index, patient := range patients {
136
-		patientIDs[index] = patient.ID
137
-	}
138
-
139
-	db := readDb.
140
-		Model(&models.DialysisSchedule{}).
141
-		Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
142
-		// Preload("DeviceZone", "status = 1 AND org_id = ?", orgID).
143
-		Preload("TreatmentMode", "status = 1").
144
-		Preload("Prescription", "status = 1 AND user_org_id = ?", orgID).
145
-		Preload("AssessmentBeforeDislysis", "status = 1 AND  user_org_id = ?", orgID).
146
-		Preload("AssessmentAfterDislysis", "status = 1 AND  user_org_id = ?", orgID).
147
-		Preload("MonitoringRecord", "status = 1 AND  user_org_id = ?", orgID).
148
-		Preload("DialysisOrder", "status = 1 AND user_org_id = ?", orgID).
149
-		Preload("MonitorPatients", "status = 1 AND user_org_id = ?", orgID)
150
-	db = db.Where("xt_schedule.status = 1 AND patient_id in (?)", patientIDs)
151
-	if schedulType > 0 {
152
-		db = db.Where("schedule_type = ?", schedulType)
153
-	}
154
-	if partitionType > 0 {
155
-		db = db.Joins("inner join xt_device_number as d_n on d_n.id = xt_schedule.bed_id and d_n.zone_id = ? and d_n.status = 1", partitionType)
156
-		// db = db.Where("partition_id = ?", partitionType)
157
-	}
158
-	if schedulDate > 0 {
159
-		db = db.Where("schedule_date = ?", schedulDate)
160
-	}
161
-	var schedules []*models.DialysisParameter
162
-	total := int64(0)
163
-	err := db.Count(&total).Offset(limit * (page - 1)).Limit(limit).Order("schedule_date desc").Find(&schedules).Error
164
-	return schedules, err, total
165
-}
166
-
167
-func GetDialysisConsumables(startime int64, endtime int64, orgid int64) (reducedetail []*models.XtAutomaticReduceDetail, err error) {
168
-
169
-	db := XTReadDB().Table("xt_automatic_reduce_detail as x").Where("x.status = 1")
170
-	table := XTReadDB().Table("xt_warehouse_out_info as f").Where("f.status = 1 and f.org_id = ?", orgid)
171
-	fmt.Println(table)
172
-	if startime > 0 {
173
-		db = db.Where("x.record_time >=?", startime)
174
-	}
175
-	if endtime > 0 {
176
-		db = db.Where("x.record_time <=?", endtime)
177
-	}
178
-	if orgid > 0 {
179
-		db = db.Where("x.org_id =?", orgid)
180
-	}
181
-	err = db.Select("x.patient_id,x.count,x.good_id,x.good_type_id,t.specification_name,s.type_name").Joins("left join xt_good_information as t on t.id = x.good_id").Where("t.org_id = ? and t.status = 1", orgid).Joins("left join xt_goods_type as s on s.id = x.good_type_id").Joins("left join xt_warehouse_out_info as f on f.id = x.warehouse_out_id").Scan(&reducedetail).Error
182
-	return reducedetail, err
183
-}
184
-
185
-func GetBatchCollection(orgID int64, schIDs []string) (schedules []*models.DialysisParameter, err error) {
186
-
187
-	db := readDb.
188
-		Model(&models.DialysisSchedule{}).
189
-		Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
190
-		// Preload("DeviceZone", "status = 1 AND org_id = ?", orgID).
191
-		Preload("TreatmentMode", "status = 1").
192
-		Preload("Prescription", "status = 1 AND user_org_id = ?", orgID).
193
-		Preload("AssessmentBeforeDislysis", "status = 1 AND  user_org_id = ?", orgID).
194
-		Preload("AssessmentAfterDislysis", "status = 1 AND  user_org_id = ?", orgID).
195
-		Preload("MonitoringRecord", "status = 1 AND  user_org_id = ?", orgID).
196
-		Preload("DialysisOrder", "status = 1 AND user_org_id = ?", orgID).
197
-		Preload("MonitorPatients", "status = 1 AND user_org_id = ?", orgID)
198
-	db = db.Where("xt_schedule.status = 1 AND id in (?)", schIDs)
199
-	err = db.Order("schedule_date desc").Find(&schedules).Error
200
-	return schedules, err
201
-}
202
-
203
-func GetAnticoagulantCount(startime int64, endtime int64, orgid int64) (prescriptionCount []*models.DialysisPrescriptionCount, err error) {
204
-
205
-	db := XTReadDB().Table("xt_dialysis_prescription as x").Where("x.status = 1")
206
-	if orgid > 0 {
207
-		db = db.Where("x.user_org_id = ? and x.anticoagulant <> 0", orgid)
208
-	}
209
-	if startime > 0 {
210
-		db = db.Where("x.record_date >= ?", startime)
211
-	}
212
-	if endtime > 0 {
213
-		db = db.Where("x.record_date<=?", endtime)
214
-	}
215
-
216
-	err = db.Select("x.patient_id,x.anticoagulant,x.record_date,count(id) as count").Group("x.anticoagulant").Scan(&prescriptionCount).Error
217
-	return prescriptionCount, err
218
-}
219
-
220
-func GetDialysisTodaySchedulePatient(orgid int64, startime int64, page int64, limit int64) (schedule []*models.XtSchedule, err error) {
221
-	offset := (page - 1) * limit
222
-	err = XTReadDB().Model(&schedule).Where("user_org_id = ? and schedule_date = ? and status = 1", orgid, startime).Offset(offset).Limit(limit).Find(&schedule).Error
223
-	return schedule, err
224
-}
225
-
226
-func GetToDayDialysisPrescription(patientid int64, orgid int64, startime int64) (*models.XtDialysisPrescription, error) {
227
-	prescription := models.XtDialysisPrescription{}
228
-	err := XTReadDB().Model(&prescription).Where("patient_id = ? and user_org_id = ? and record_date = ? and status = 1", patientid, orgid, startime).Find(&prescription).Error
229
-	if err == gorm.ErrRecordNotFound {
230
-		return nil, err
231
-	}
232
-	if err != nil {
233
-		return nil, err
234
-	}
235
-	return &prescription, nil
236
-
237
-}
238
-
239
-func GetLastDialysisPrescription(patientid int64, orgid int64) (models.XtDialysisPrescription, error) {
240
-
241
-	prescription := models.XtDialysisPrescription{}
242
-	err = XTReadDB().Model(&prescription).Where("patient_id = ? and user_org_id = ? and status = 1", patientid, orgid).Last(&prescription).Error
243
-	return prescription, err
244
-}
245
-
246
-func GetLastAssessmentBeforDialysis(patientid int64, orgid int64) (models.PredialysisEvaluation, error) {
247
-
248
-	evaluation := models.PredialysisEvaluation{}
249
-	err := XTReadDB().Model(&evaluation).Where("patient_id = ? and user_org_id = ? and status = 1", patientid, orgid).Last(&evaluation).Error
250
-	return evaluation, err
251
-}
252
-
253
-func GetDialysisPrescriptionList(patientid int64, orgid int64, startime int64) (models.XtDialysisPrescription, error) {
254
-	prescription := models.XtDialysisPrescription{}
255
-	err := XTReadDB().Model(&prescription).Where("patient_id = ? and user_org_id = ? and status = 1 and record_date = ?", patientid, orgid, startime).Find(&prescription).Error
256
-	return prescription, err
257
-}
258
-
259
-func GetTodayAssessmentBeforDialysis(patientid int64, orgid int64, startime int64) (*models.PredialysisEvaluation, error) {
260
-
261
-	evaluation := models.PredialysisEvaluation{}
262
-	err := XTReadDB().Model(&evaluation).Where("patient_id = ? and user_org_id = ? and assessment_date = ? and status = 1", patientid, orgid, startime).Find(&evaluation).Error
263
-	if err == gorm.ErrRecordNotFound {
264
-		return nil, err
265
-	}
266
-	if err != nil {
267
-		return nil, err
268
-	}
269
-	return &evaluation, nil
270
-}
271
-
272
-func GetAssessmentBeforDialysisByStartime(patientid int64, orgid int64, startime int64) (models.PredialysisEvaluation, error) {
273
-	evaluation := models.PredialysisEvaluation{}
274
-	err := XTReadDB().Model(&evaluation).Where("patient_id = ? and user_org_id = ? and assessment_date = ? and status = 1", patientid, orgid, startime).Find(&evaluation).Error
275
-	return evaluation, err
276
-}
277
-
278
-func GetAotoMaticReduceByPatientId(patientid int64, orgid int64, startime int64, endtime int64) (*models.BloodAutomaticReduceDetail, error) {
279
-
280
-	detail := models.BloodAutomaticReduceDetail{}
281
-	err := XTReadDB().Model(&detail).Where("patient_id = ? and org_id =? and record_time >=? and record_time <=? and status = 1", patientid, orgid, startime, endtime).Find(&detail).Error
282
-	if err == gorm.ErrRecordNotFound {
283
-		return nil, err
284
-	}
285
-	if err != nil {
286
-		return nil, err
287
-	}
288
-	return &detail, nil
289
-}
290
-
291
-func GetMaticReduece(patientid int64, orgid int64) (models.BloodAutomaticReduceDetail, error) {
292
-
293
-	detail := models.BloodAutomaticReduceDetail{}
294
-	err := XTReadDB().Model(&detail).Where("patient_id = ? and org_id= ?  and status = 1", patientid, orgid).Last(&detail).Error
295
-
296
-	return detail, err
297
-}
298
-
299
-func GetMaticeReduceByPatientId(patientid int64, orgid int64, startime int64, endtime int64) (models.BloodAutomaticReduceDetail, error) {
300
-
301
-	detail := models.BloodAutomaticReduceDetail{}
302
-	err := XTReadDB().Model(&detail).Where("patient_id = ? and org_id = ? and record_time >=? and record_time<=? and status =1", patientid, orgid, startime, endtime).Find(&detail).Error
303
-	return detail, err
304
-}

Разница между файлами не показана из-за своего большого размера
+ 0 - 1083
models/service/dialysis_service.go


+ 0 - 84
models/service/district_service.go Просмотреть файл

@@ -1,84 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	"XT_New/utils"
6
-	"github.com/jinzhu/gorm"
7
-)
8
-
9
-func GetDistrictsByUpid(id int64) (dis []*models.District, err error) {
10
-	err = readUserDb.Model(&models.District{}).Where("upid=?", id).Find(&dis).Error
11
-	return
12
-}
13
-
14
-func GetProvinceWithName(name string) (*models.District, error) {
15
-	var province models.District
16
-	err := readUserDb.Model(&models.District{}).Where("level = 1 AND name like ?", "%"+name+"%").First(&province).Error
17
-	if err != nil {
18
-		if err == gorm.ErrRecordNotFound {
19
-			return nil, nil
20
-		} else {
21
-			return nil, err
22
-		}
23
-	}
24
-	return &province, nil
25
-}
26
-
27
-func GetCityWithName(provinceID int64, cityName string) (*models.District, error) {
28
-	var city models.District
29
-	err := readUserDb.Model(&models.District{}).Where("level = 2 AND upid = ? AND name like ?", provinceID, "%"+cityName+"%").First(&city).Error
30
-	if err != nil {
31
-		if err == gorm.ErrRecordNotFound {
32
-			return nil, nil
33
-		} else {
34
-			return nil, err
35
-		}
36
-	}
37
-	return &city, nil
38
-}
39
-
40
-func GetDistrictWithName(cityID int64, name string) (*models.District, error) {
41
-	var district models.District
42
-	err := readUserDb.Model(&models.District{}).Where("level = 3 AND upid = ? AND name like ?", cityID, "%"+name+"%").First(&district).Error
43
-	if err != nil {
44
-		if err == gorm.ErrRecordNotFound {
45
-			return nil, nil
46
-		} else {
47
-			return nil, err
48
-		}
49
-	}
50
-	return &district, nil
51
-}
52
-
53
-func GetAllProvince() []*models.District {
54
-	var province []*models.District
55
-	err := readUserDb.Model(&models.District{}).Where("level = 1").Find(&province).Error
56
-	if err != nil {
57
-		utils.ErrorLog("获取所有省份失败: %v", err)
58
-		return nil
59
-	} else {
60
-		return province
61
-	}
62
-}
63
-
64
-func GetCitiesWithProvinceID(provinceID int) []*models.District {
65
-	var cities []*models.District
66
-	err := readUserDb.Model(&models.District{}).Where("level = 2 AND upid = ?", provinceID).Find(&cities).Error
67
-	if err != nil {
68
-		utils.ErrorLog("获取省份 id 为 %v 下的城市失败: %v", provinceID, err)
69
-		return nil
70
-	} else {
71
-		return cities
72
-	}
73
-}
74
-
75
-func GetDistrictsWithCityID(cityID int) []*models.District {
76
-	var districts []*models.District
77
-	err := readUserDb.Model(&models.District{}).Where("level = 3 AND upid = ?", cityID).Find(&districts).Error
78
-	if err != nil {
79
-		utils.ErrorLog("获取城市 id 为 %v 下的区县失败: %v", cityID, err)
80
-		return nil
81
-	} else {
82
-		return districts
83
-	}
84
-}

+ 0 - 345
models/service/doctor_advice_service.go Просмотреть файл

@@ -1,345 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	"strings"
6
-	"time"
7
-
8
-	"github.com/jinzhu/gorm"
9
-)
10
-
11
-func GetPublicDrugDics() (drugs []*models.DrugDic, total int64, err error) {
12
-	err = readDb.Model(&models.DrugDic{}).Where("org_id = 0 and status=1").Count(&total).Order("id desc").Find(&drugs).Error
13
-	return
14
-}
15
-
16
-func GetPublicDrugWayDics() (drugways []*models.DrugwayDic, total int64, err error) {
17
-	err = readDb.Model(&models.DrugwayDic{}).Where("org_id = 0 and status=1").Count(&total).Order("id desc").Find(&drugways).Error
18
-	return
19
-}
20
-
21
-func GetPublicExecutionFrequencyDics() (dics []*models.ExecutionFrequencyDic, total int64, err error) {
22
-	err = readDb.Model(&models.ExecutionFrequencyDic{}).Where("org_id = 0 and status=1").Count(&total).Order("id desc").Find(&dics).Error
23
-	return
24
-}
25
-
26
-func GetDrugDics(orgid int64) (drugs []*models.DrugDic, total int64, err error) {
27
-	err = readDb.Model(&models.DrugDic{}).Where("org_id =? and status=1", orgid).Count(&total).Order("id desc").Find(&drugs).Error
28
-	return
29
-}
30
-
31
-func GetAdviceTemplates(orgid int64) (templates []*models.DoctorAdviceTemplate, total int64, err error) {
32
-	err = readDb.Model(&models.DoctorAdviceTemplate{}).Where("org_id =? and status=1", orgid).Count(&total).Order("id desc").Find(&templates).Error
33
-	return
34
-}
35
-
36
-func GetDrugWayDics(orgid int64) (drugways []*models.DrugwayDic, total int64, err error) {
37
-	err = readDb.Model(&models.DrugwayDic{}).Where("(org_id =? or org_id = 0) and status=1", orgid).Count(&total).Order("id desc").Find(&drugways).Error
38
-	return
39
-}
40
-
41
-func GetExecutionFrequencyDics(orgid int64) (dics []*models.ExecutionFrequencyDic, total int64, err error) {
42
-	err = readDb.Model(&models.ExecutionFrequencyDic{}).Where("(org_id =? or org_id = 0) and status=1", orgid).Count(&total).Order("id desc").Find(&dics).Error
43
-	return
44
-}
45
-
46
-func CreateDrugDic(d *models.DrugDic) (err error) {
47
-	err = readDb.Create(&d).Error
48
-	return
49
-}
50
-
51
-func UpdateDrugDic(d *models.DrugDic) (err error) {
52
-	err = readDb.Save(&d).Error
53
-	return
54
-}
55
-
56
-func FindDrugDic(orgid, id int64) (*models.DrugDic, error) {
57
-	var drugdic models.DrugDic
58
-	err := readDb.Model(&models.DrugDic{}).Where("id=? and org_id =? and status=1", id, orgid).First(&drugdic).Error
59
-	if err == gorm.ErrRecordNotFound {
60
-		return nil, nil
61
-	}
62
-
63
-	if err != nil {
64
-		return nil, err
65
-	}
66
-	return &drugdic, nil
67
-}
68
-
69
-func CreateDrugWay(d *models.DrugwayDic) (err error) {
70
-	err = readDb.Create(&d).Error
71
-	return
72
-}
73
-
74
-func FindDrugWay(orgid, id int64) (*models.DrugwayDic, error) {
75
-	var drugway models.DrugwayDic
76
-	err := readDb.Model(&models.DrugwayDic{}).Where("id=? and org_id =? and status=1", id, orgid).First(&drugway).Error
77
-	if err == gorm.ErrRecordNotFound {
78
-		return nil, nil
79
-	}
80
-
81
-	if err != nil {
82
-		return nil, err
83
-	}
84
-	return &drugway, nil
85
-}
86
-
87
-func UpdateDrugWay(d *models.DrugwayDic) (err error) {
88
-	err = readDb.Save(&d).Error
89
-	return
90
-}
91
-
92
-func CreateExecutionFrequency(d *models.ExecutionFrequencyDic) (err error) {
93
-	err = readDb.Create(&d).Error
94
-	return
95
-}
96
-
97
-func FindExecutionFrequency(orgid, id int64) (*models.ExecutionFrequencyDic, error) {
98
-	var ef models.ExecutionFrequencyDic
99
-	err := readDb.Model(&models.ExecutionFrequencyDic{}).Where("id=? and org_id =? and status=1", id, orgid).First(&ef).Error
100
-	if err == gorm.ErrRecordNotFound {
101
-		return nil, nil
102
-	}
103
-
104
-	if err != nil {
105
-		return nil, err
106
-	}
107
-	return &ef, nil
108
-}
109
-
110
-func UpdateExecutionFrequency(d *models.ExecutionFrequencyDic) (err error) {
111
-	err = readDb.Save(&d).Error
112
-	return
113
-}
114
-
115
-func CreateAdviceTemplate(d *models.DoctorAdviceTemplate) (err error) {
116
-	err = readDb.Create(&d).Error
117
-	return
118
-}
119
-
120
-func FindAdviceTemplate(orgid, id int64) (*models.DoctorAdviceTemplate, error) {
121
-	var template models.DoctorAdviceTemplate
122
-	err := readDb.Model(&models.DoctorAdviceTemplate{}).Where("id=? and org_id =? and status=1", id, orgid).First(&template).Error
123
-	if err == gorm.ErrRecordNotFound {
124
-		return nil, nil
125
-	}
126
-
127
-	if err != nil {
128
-		return nil, err
129
-	}
130
-	return &template, nil
131
-}
132
-
133
-func UpdateAdviceTemplate(d *models.DoctorAdviceTemplate) (err error) {
134
-	err = writeDb.Save(&d).Error
135
-	return
136
-}
137
-
138
-func UpdateAdviceAndSubAdviceTemplate(d *models.DoctorAdviceTemplate) (err error) {
139
-	err = writeDb.Save(&d).Error
140
-	err = writeDb.Model(&models.DoctorAdviceTemplate{}).Where("status=1 AND parent_id = ?", d.ID).Updates(map[string]interface{}{"status": 2, "updated_time": time.Now().Unix()}).Error
141
-	return
142
-}
143
-
144
-func CreateTemplate(template *models.DoctorAdviceParentTemplate) (err error) {
145
-	err = readDb.Create(&template).Error
146
-	return
147
-}
148
-
149
-//func CreateBatchRecord(template []*models.DoctorAdviceTemplate) (err error) {
150
-//	err = writeDb.Create(template).Error
151
-//	return
152
-//}
153
-
154
-func CreateSubTemplate(template []*models.DoctorAdviceTemplate) (err error) {
155
-	if len(template) > 0 {
156
-		utx := writeDb.Begin()
157
-		if len(template) > 0 {
158
-			thisSQL := "INSERT INTO xt_doctor_advice_template (org_id, advice_name, advice_desc, single_dose, single_dose_unit,prescribing_number," +
159
-				"prescribing_number_unit,delivery_way,execution_frequency,advice_doctor,status,created_time,updated_time,template_id,drug_spec,drug_spec_unit,advice_type,day_count,week_days,frequency_type) VALUES "
160
-			insertParams := make([]string, 0)
161
-			insertData := make([]interface{}, 0)
162
-			for _, info := range template {
163
-				insertParams = append(insertParams, "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
164
-				insertData = append(insertData, info.OrgId)
165
-				insertData = append(insertData, info.AdviceName)
166
-				insertData = append(insertData, info.AdviceDesc)
167
-				insertData = append(insertData, info.SingleDose)
168
-				insertData = append(insertData, info.SingleDoseUnit)
169
-				insertData = append(insertData, info.PrescribingNumber)
170
-				insertData = append(insertData, info.PrescribingNumberUnit)
171
-				insertData = append(insertData, info.DeliveryWay)
172
-				insertData = append(insertData, info.ExecutionFrequency)
173
-				insertData = append(insertData, info.AdviceDoctor)
174
-				insertData = append(insertData, info.Status)
175
-				insertData = append(insertData, info.CreatedTime)
176
-				insertData = append(insertData, info.UpdatedTime)
177
-				insertData = append(insertData, info.TemplateId)
178
-				insertData = append(insertData, info.DrugSpec)
179
-				insertData = append(insertData, info.DrugSpecUnit)
180
-				insertData = append(insertData, info.AdviceType)
181
-				insertData = append(insertData, info.DayCount)
182
-				insertData = append(insertData, info.WeekDays)
183
-				insertData = append(insertData, info.FrequencyType)
184
-			}
185
-			thisSQL += strings.Join(insertParams, ", ")
186
-			err = utx.Exec(thisSQL, insertData...).Error
187
-			if err != nil {
188
-				utx.Rollback()
189
-				return
190
-			}
191
-		}
192
-		utx.Commit()
193
-	}
194
-	return
195
-
196
-}
197
-
198
-func FindDoctorAdviceTemplateById(id int64, org_id int64) (temps models.DoctorAdviceParentTemplate, err error) {
199
-	err = readDb.Model(&models.DoctorAdviceParentTemplate{}).Preload("DoctorAdviceTemplate", "status = 1").Where("org_id = ? AND status=1 AND id = ?", org_id, id).Order("id desc").First(&temps).Error
200
-	return
201
-}
202
-
203
-func FindAllAdviceTemplate(org_id int64, advice_type int64) (temps []*models.DoctorAdviceParentTemplate, err error) {
204
-	err = readDb.Model(&models.DoctorAdviceParentTemplate{}).Preload("DoctorAdviceTemplate", func(db *gorm.DB) *gorm.DB {
205
-		return db.Select("id,advice_name,advice_desc,single_dose,single_dose_unit,prescribing_number,prescribing_number_unit,delivery_way,execution_frequency,status,created_time,updated_time,parent_id,template_id,drug_spec,drug_spec_unit,advice_type,day_count,week_days,frequency_type, IF(parent_id>0, parent_id, id) as advice_order").Where("status = 1").Order("advice_order desc, id")
206
-	}).Where("org_id = ? AND status=1 AND advice_type = ?", org_id, advice_type).Find(&temps).Error
207
-	return
208
-}
209
-
210
-func GetAllAdviceSubTemplates(orgid int64, template_id int64) (total int64, err error) {
211
-	err = readDb.Model(&models.DoctorAdviceTemplate{}).Where("org_id =? AND status=1 AND template_id = ?", orgid, template_id).Count(&total).Error
212
-	return
213
-}
214
-
215
-func UpdateParentAdviceTemplates(orgid int64, tempelate_id int64) (err error) {
216
-	err = readDb.Model(&models.DoctorAdviceParentTemplate{}).Where("org_id =? AND status=1 AND id = ?", orgid, tempelate_id).Updates(map[string]interface{}{"status": "0", "updated_time": time.Now().Unix()}).Error
217
-	return
218
-}
219
-
220
-func FindTemplateRecordByName(orgid int64, name string) (total int64) {
221
-	readDb.Model(&models.DoctorAdviceParentTemplate{}).Where("name = ? AND org_id = ? AND status= 1 ", name, orgid).Count(&total)
222
-	return
223
-}
224
-
225
-func FindParentTemplateRecordById(orgid int64, template_id int64) (parentTemplate models.DoctorAdviceParentTemplate, err error) {
226
-	err = readDb.Model(&models.DoctorAdviceParentTemplate{}).Where("id = ? AND org_id = ? AND status= 1 ", template_id, orgid).First(&parentTemplate).Error
227
-	return
228
-}
229
-
230
-func DeleteParentDoctorAdviceByTemplateId(template_id int64, org_id int64) (err error) {
231
-
232
-	ut := writeDb.Begin()
233
-	err = writeDb.Model(&models.DoctorAdviceParentTemplate{}).Where("status=1 AND id = ? AND org_id = ?", template_id, org_id).Updates(map[string]interface{}{"status": "0", "updated_time": time.Now().Unix()}).Error
234
-
235
-	if err != nil {
236
-		ut.Rollback()
237
-		return
238
-	}
239
-	err = writeDb.Model(&models.DoctorAdviceTemplate{}).Where("status=1 AND template_id = ? AND org_id = ?", template_id, org_id).Updates(map[string]interface{}{"status": "2", "updated_time": time.Now().Unix()}).Error
240
-	if err != nil {
241
-		ut.Rollback()
242
-		return
243
-	}
244
-	ut.Commit()
245
-	return err
246
-}
247
-
248
-func ModifyTemplateName(id int64, template_name string) (err error) {
249
-	err = writeDb.Model(&models.DoctorAdviceParentTemplate{}).Where("status=1 AND id = ?", id).Updates(map[string]interface{}{"name": template_name, "updated_time": time.Now().Unix()}).Error
250
-	return err
251
-}
252
-
253
-func FindOtherAllAdviceTemplate(org_id int64) (temps []*models.DoctorAdviceParentTemplate, err error) {
254
-	err = readDb.Model(&models.DoctorAdviceParentTemplate{}).Preload("DoctorAdviceTemplate", func(db *gorm.DB) *gorm.DB {
255
-		return db.Select("id,advice_name,advice_desc,single_dose,single_dose_unit,prescribing_number,prescribing_number_unit,delivery_way,execution_frequency,status,created_time,updated_time,parent_id,template_id,drug_spec,drug_spec_unit,advice_type,day_count,week_days,frequency_type, IF(parent_id>0, parent_id, id) as advice_order").Where("status = 1").Order("advice_order desc, id")
256
-	}).Where("org_id = ? AND status=1 ", org_id).Find(&temps).Error
257
-	return
258
-	//.Scan(&advices).Error
259
-
260
-}
261
-
262
-func GetHandleData(id int64) (models.ConfigViewModel, error) {
263
-	config := models.ConfigViewModel{}
264
-	err := readDb.Model(&config).Where("id=?", id).Find(&config).Error
265
-	return config, err
266
-}
267
-
268
-func UpdateDataTwo(id int64, model models.ConfigViewModel) error {
269
-
270
-	err := writeDb.Model(&model).Where("id=?", id).Update(map[string]interface{}{"name": model.Name, "orders": model.Order, "remark": model.Remark, "update_time": time.Now().Unix()}).Error
271
-	return err
272
-}
273
-
274
-type AdviceDate struct {
275
-	RecordDate int64
276
-}
277
-
278
-type DoctorAdvice struct {
279
-	ID                    int64           `gorm:"column:id" json:"id" form:"id"`
280
-	GroupNo               int64           `gorm:"column:groupno" json:"groupno" form:"groupno"`
281
-	UserOrgId             int64           `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
282
-	PatientId             int64           `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
283
-	AdviceType            int64           `gorm:"column:advice_type" json:"advice_type" form:"advice_type"`
284
-	AdviceDate            int64           `gorm:"column:advice_date" json:"advice_date" form:"advice_date"`
285
-	StartTime             int64           `gorm:"column:start_time" json:"start_time" form:"start_time"`
286
-	AdviceName            string          `gorm:"column:advice_name" json:"advice_name" form:"advice_name"`
287
-	AdviceDesc            string          `gorm:"column:advice_desc" json:"advice_desc" form:"advice_desc"`
288
-	ReminderDate          int64           `gorm:"column:reminder_date" json:"reminder_date" form:"reminder_date"`
289
-	SingleDose            float64         `gorm:"column:single_dose" json:"single_dose" form:"single_dose"`
290
-	SingleDoseUnit        string          `gorm:"column:single_dose_unit" json:"single_dose_unit" form:"single_dose_unit"`
291
-	DrugSpec              float64         `gorm:"column:drug_spec" json:"drug_spec" form:"drug_spec"`
292
-	DrugSpecUnit          string          `gorm:"column:drug_spec_unit" json:"drug_spec_unit" form:"drug_spec_unit"`
293
-	PrescribingNumber     float64         `gorm:"column:prescribing_number" json:"prescribing_number" form:"prescribing_number"`
294
-	PrescribingNumberUnit string          `gorm:"column:prescribing_number_unit" json:"prescribing_number_unit" form:"prescribing_number_unit"`
295
-	DeliveryWay           string          `gorm:"column:delivery_way" json:"delivery_way" form:"delivery_way"`
296
-	ExecutionFrequency    string          `gorm:"column:execution_frequency" json:"execution_frequency" form:"execution_frequency"`
297
-	AdviceDoctor          int64           `gorm:"column:advice_doctor" json:"advice_doctor" form:"advice_doctor"`
298
-	Status                int64           `gorm:"column:status" json:"status" form:"status"`
299
-	CreatedTime           int64           `gorm:"column:created_time" json:"created_time" form:"created_time"`
300
-	UpdatedTime           int64           `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
301
-	AdviceAffirm          string          `gorm:"column:advice_affirm" json:"advice_affirm" form:"advice_affirm"`
302
-	Remark                string          `gorm:"column:remark" json:"remark" form:"remark"`
303
-	StopTime              int64           `gorm:"column:stop_time" json:"stop_time" form:"stop_time"`
304
-	StopReason            string          `gorm:"column:stop_reason" json:"stop_reason" form:"stop_reason"`
305
-	StopDoctor            int64           `gorm:"column:stop_doctor" json:"stop_doctor" form:"stop_doctor"`
306
-	StopState             int64           `gorm:"column:stop_state" json:"stop_state" form:"stop_state"`
307
-	ParentId              int64           `gorm:"column:parent_id" json:"parent_id" form:"parent_id"`
308
-	ExecutionTime         int64           `gorm:"column:execution_time" json:"execution_time" form:"execution_time"`
309
-	ExecutionStaff        int64           `gorm:"column:execution_staff" json:"execution_staff" form:"execution_staff"`
310
-	ExecutionState        int64           `gorm:"column:execution_state" json:"execution_state" form:"execution_state"`
311
-	Checker               int64           `gorm:"column:checker" json:"checker" form:"checker"`
312
-	RecordDate            int64           `gorm:"column:record_date" json:"record_date"`
313
-	DialysisOrderId       int64           `gorm:"column:dialysis_order_id" json:"dialysis_order_id"`
314
-	CheckTime             int64           `gorm:"column:check_time" json:"check_time" form:"check_time"`
315
-	CheckState            int64           `gorm:"column:check_state" json:"check_state" form:"check_state"`
316
-	AdviceId              int64           `gorm:"-"`
317
-	RemindType            int64           `gorm:"column:remind_type" json:"remind_type"`
318
-	FrequencyType         int64           `gorm:"column:frequency_type" json:"frequency_type"`
319
-	DayCount              int64           `gorm:"column:day_count" json:"day_count"`
320
-	WeekDay               string          `gorm:"column:week_day" json:"week_day"`
321
-	DoctorAdvice          []*DoctorAdvice `gorm:"ForeignKey:ParentId;AssociationForeignKey:ID" json:"children"`
322
-	TemplateId            string          `gorm:"column:template_id" json:"template_id"`
323
-	Modifier              int64           `gorm:"column:modifier" json:"modifier" form:"modifier"`
324
-	IsCheck               int64           `gorm:"-" json:"is_check" form:"is_check"`
325
-}
326
-
327
-func (DoctorAdvice) TableName() string {
328
-	return "xt_doctor_advice"
329
-}
330
-
331
-func GetDoctorAdviceByType(change_type int64, record_time int64, org_id int64, patient_id int64) (advice []*DoctorAdvice, sch models.Schedule, err error) {
332
-	if change_type == 1 { //根据日期取出上一方数据
333
-		var Id AdviceDate
334
-		err = readDb.Model(&DoctorAdvice{}).Where("patient_id = ? AND user_org_id = ? AND status=1 AND record_date < ?", patient_id, org_id, record_time).Select("record_date").Group("record_date").Order("record_date asc").Scan(&Id).Error
335
-		err = readDb.Model(&models.Schedule{}).Where("patient_id = ? AND user_org_id = ? AND  status=1 AND schedule_date  = ?", patient_id, org_id, Id.RecordDate).Find(&sch).Error
336
-		err = readDb.Model(&DoctorAdvice{}).Where("patient_id = ? AND user_org_id = ? AND  status=1 AND record_date  = ? AND parent_id= 0", patient_id, org_id, Id.RecordDate).Preload("DoctorAdvice", "status = 1 AND user_org_id = ? AND patient_id = ?", org_id, patient_id).Find(&advice).Error
337
-
338
-	} else if change_type == 2 {
339
-		var Id AdviceDate
340
-		err = readDb.Model(&DoctorAdvice{}).Where("patient_id = ? AND user_org_id = ? AND status=1 AND record_date > ?", patient_id, org_id, record_time).Select("record_date").Group("record_date").Order("record_date desc").Scan(&Id).Error
341
-		err = readDb.Model(&models.Schedule{}).Where("patient_id = ? AND user_org_id = ? AND  status=1 AND schedule_date  = ?", patient_id, org_id, Id.RecordDate).Find(&sch).Error
342
-		err = readDb.Model(&DoctorAdvice{}).Where("patient_id = ? AND user_org_id = ? AND  status=1 AND record_date  = ? AND parent_id= 0", patient_id, org_id, Id.RecordDate).Preload("DoctorAdvice", "status = 1 AND user_org_id = ? AND patient_id = ?", org_id, patient_id).Find(&advice).Error
343
-	}
344
-	return
345
-}

+ 0 - 617
models/service/doctor_schedule_service.go Просмотреть файл

@@ -1,617 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	"fmt"
6
-	"github.com/jinzhu/gorm"
7
-	"time"
8
-)
9
-
10
-func GetClassName(orgid int64, class_name string) (*models.DoctorSchedules, error) {
11
-
12
-	schedules := models.DoctorSchedules{}
13
-	err := XTReadDB().Model(&schedules).Where("user_org_id = ? and status = 1 and class_name = ?", orgid, class_name).Find(&schedules).Error
14
-	if err == gorm.ErrRecordNotFound {
15
-		return nil, err
16
-	}
17
-	if err != nil {
18
-		return nil, err
19
-	}
20
-	return &schedules, nil
21
-}
22
-
23
-func CreateDotorSchedule(schedules *models.DoctorSchedules) error {
24
-
25
-	err := XTWriteDB().Create(&schedules).Error
26
-	return err
27
-}
28
-
29
-func GetDoctorScheduleByOrgId(orgid int64) (*models.DoctorSchedules, error) {
30
-	schedules := models.DoctorSchedules{}
31
-	err := XTReadDB().Model(&schedules).Where("user_org_id = ? and status = 1", orgid).Find(&schedules).Error
32
-	if err == gorm.ErrRecordNotFound {
33
-		return nil, err
34
-	}
35
-	if err != nil {
36
-		return nil, err
37
-	}
38
-	return &schedules, nil
39
-}
40
-
41
-func GetDoctorScheduleList(orgid int64, page int64, limit int64) (schedules []*models.DoctorSchedules, total int64, err error) {
42
-	offset := (page - 1) * limit
43
-	err = XTReadDB().Model(&schedules).Where("user_org_id = ? and status =1", orgid).Count(&total).Offset(offset).Limit(limit).Find(&schedules).Error
44
-	return schedules, total, err
45
-}
46
-
47
-func GetScheduleDetail(id int64) (models.DoctorSchedules, error) {
48
-	schedules := models.DoctorSchedules{}
49
-	err := XTReadDB().Model(&schedules).Where("id=? and status = 1", id).Find(&schedules).Error
50
-	return schedules, err
51
-}
52
-
53
-func GetClassNameIsExsit(classname string, orgid int64, id int64) (schedule models.DoctorSchedules, err error) {
54
-
55
-	err = XTReadDB().Model(&schedule).Where("class_name = ? and user_org_id =? and id <> ?", classname, orgid, id).First(&schedule).Error
56
-	return schedule, err
57
-}
58
-
59
-func UpdateScheduleList(id int64, schedules *models.DoctorSchedules) error {
60
-
61
-	err := XTReadDB().Model(&schedules).Where("id=?", id).Updates(map[string]interface{}{"class_name": schedules.ClassName, "class_attributes": schedules.ClassAttributes, "timeone_start": schedules.TimeoneStart, "timeone_type": schedules.TimeoneType, "timeone_end": schedules.TimeoneEnd, "timetwo_start": schedules.TimetwoStart, "timetwo_type": schedules.TimetwoType, "timetwo_end": schedules.TimetwoEnd, "work_time": schedules.WorkTime, "remarks": schedules.Remarks, "minute": schedules.Minute, "mtime": time.Now().Unix()}).Error
62
-	return err
63
-}
64
-
65
-func GetStaffScheduleByScheduleType(id int64, orgid int64) (*models.StaffSchedule, error) {
66
-	schedule := models.StaffSchedule{}
67
-	err := XTReadDB().Model(&schedule).Where("schedule_type = ? and user_org_id = ? and status = 1", id, orgid).Find(&schedule).Error
68
-	if err == gorm.ErrRecordNotFound {
69
-		return nil, err
70
-	}
71
-	if err != nil {
72
-		return nil, err
73
-	}
74
-	return &schedule, nil
75
-}
76
-
77
-func DeleteScheduleById(id int64) error {
78
-	schedules := models.DoctorSchedules{}
79
-	err := XTWriteDB().Model(&schedules).Where("id=?", id).Updates(map[string]interface{}{"status": 0}).Error
80
-	return err
81
-}
82
-
83
-func GetDoctorList(orgid int64, appid int64) (role []*models.XTSgjUserAdminRole, err error) {
84
-
85
-	err = UserReadDB().Model(&role).Where("org_id = ? and app_id = ? and (user_type = 2 or user_type = 3) and status = 1 and is_sort = 1", orgid, appid).Order("user_type desc").Find(&role).Error
86
-	return role, err
87
-}
88
-
89
-func GetAllDoctorList(orgid int64, appid int64) (role []*models.XTSgjUserAdminRole, err error) {
90
-
91
-	err = UserReadDB().Model(&role).Where("org_id =? and app_id = ? and user_type = 2 and status = 1", orgid, appid).Order("sort desc").Find(&role).Error
92
-	return role, err
93
-}
94
-
95
-func GetAllNurseList(orgid int64, appid int64) (role []*models.XTSgjUserAdminRole, err error) {
96
-
97
-	err = UserReadDB().Model(&role).Where("org_id = ? and app_id = ? and user_type =3 and status =1", orgid, appid).Order("sort desc").Find(&role).Error
98
-	return role, err
99
-}
100
-
101
-func GetScheduleList(orgid int64) (schedule []*models.DoctorSchedules, err error) {
102
-
103
-	err = XTReadDB().Model(&schedule).Where("user_org_id = ? and status = 1", orgid).Find(&schedule).Error
104
-	return schedule, err
105
-}
106
-
107
-func GetScheduleListDetail(doctor_id int64, orgid int64, scheduledate int64) (*models.StaffSchedule, error) {
108
-	schedule := models.StaffSchedule{}
109
-	err := XTReadDB().Model(&schedule).Where("doctor_id = ? and user_org_id = ? and status =1 and schedule_date = ?", doctor_id, orgid, scheduledate).Find(&schedule).Error
110
-	if err == gorm.ErrRecordNotFound {
111
-		return nil, err
112
-	}
113
-	if err != nil {
114
-		return nil, err
115
-	}
116
-	return &schedule, nil
117
-}
118
-
119
-func AddSchedule(schedule *models.StaffSchedule) error {
120
-
121
-	err := XTWriteDB().Create(&schedule).Error
122
-	return err
123
-}
124
-
125
-func UpdateStaffList(schedule *models.StaffSchedule, id int64) error {
126
-	err := XTReadDB().Model(&schedule).Where("id=?", id).Updates(map[string]interface{}{"doctor_id": schedule.DoctorId, "doctor_type": schedule.DoctorType, "schedule_type": schedule.ScheduleType, "schedule_week": schedule.ScheduleWeek, "schedule_date": schedule.ScheduleDate, "mtime": time.Now().Unix()}).Error
127
-	return err
128
-}
129
-
130
-func GetStaffScheduleList(orgid int64, startime int64, endtime int64) (schedule []*models.XtStaffSchedule, err error) {
131
-
132
-	db := XTReadDB().Table("xt_staff_schedule as x").Where("x.status = 1")
133
-	if startime > 0 {
134
-		db = db.Where("x.start_time >=?", startime)
135
-	}
136
-	if endtime > 0 {
137
-		db = db.Where("x.end_time <=?", endtime)
138
-	}
139
-	if orgid > 0 {
140
-		db = db.Where("x.user_org_id = ?", orgid)
141
-	}
142
-	err = db.Group("x.id").Select("x.id,x.doctor_id,x.doctor_type,x.schedule_type,x.schedule_week,x.user_org_id,x.start_time,x.end_time,x.schedule_date,r.user_name,s.class_name,r.admin_user_id,r.user_type,s.class_attributes,r.sort,r.is_sort,s.work_time,s.minute").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.doctor_id").Joins("left join xt_doctor_schedules as s on s.id = x.schedule_type").Where("r.org_id = ? and r.status = 1 and s.user_org_id = ? and s.status = 1 and r.is_sort = 1", orgid, orgid).Scan(&schedule).Error
143
-	return schedule, err
144
-}
145
-
146
-func GetStaffScheduleListTwo(orgid int64, startime int64, endtime int64) (schedule []*models.StaffSchedule, err error) {
147
-
148
-	err = XTReadDB().Model(&schedule).Where("user_org_id = ? and start_time>=? and end_time<=? and status = 1", orgid, startime, endtime).Find(&schedule).Error
149
-	return schedule, err
150
-}
151
-
152
-func GetNextWeekSchedule(orgid int64, startime int64, endtime int64) (*models.StaffSchedule, error) {
153
-	schedule := models.StaffSchedule{}
154
-	err := XTReadDB().Model(&schedule).Where("user_org_id = ? and status = 1 and start_time >=? and end_time<=?", orgid, startime, endtime).Find(&schedule).Error
155
-	if err == gorm.ErrRecordNotFound {
156
-		return nil, err
157
-	}
158
-	if err != nil {
159
-		return nil, err
160
-	}
161
-	return &schedule, nil
162
-}
163
-
164
-func GetScheduleByDoctorId(doctorid int64, startime int64, endtime int64, orgid int64) (schedule []*models.XtStaffSchedule, err error) {
165
-	fmt.Println(doctorid, startime, endtime)
166
-	db := XTReadDB().Table("xt_staff_schedule as x").Where("x.status = 1")
167
-	if startime > 0 {
168
-		db = db.Where("x.start_time >=?", startime)
169
-	}
170
-	if endtime > 0 {
171
-		db = db.Where("x.end_time <=?", endtime)
172
-	}
173
-	if orgid > 0 {
174
-		db = db.Where("x.user_org_id = ?", orgid)
175
-	}
176
-	if doctorid == 0 {
177
-		db = db.Where("x.doctor_type = 2 or x.doctor_type = 3")
178
-	}
179
-	if doctorid > 0 {
180
-		db = db.Where("x.doctor_type = ?", doctorid)
181
-	}
182
-	err = db.Group("x.id").Select("x.id,x.doctor_id,x.doctor_type,x.schedule_type,x.schedule_week,x.user_org_id,x.start_time,x.end_time,x.schedule_date,r.user_name,s.class_name,r.admin_user_id,s.class_attributes,r.sort,r.is_sort").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.doctor_id").Joins("left join xt_doctor_schedules as s on s.id = x.schedule_type").Where("r.org_id = ? and r.status = 1 and s.user_org_id = ?", orgid, orgid).Scan(&schedule).Error
183
-	return schedule, err
184
-}
185
-
186
-func ToSearchSeacheduleList(keywords string, startime int64, endtime int64, orgid int64) (schedule []*models.XtStaffSchedule, err error) {
187
-	db := XTReadDB().Table("xt_staff_schedule as x").Where("x.status = 1")
188
-	if startime > 0 {
189
-		db = db.Where("x.start_time >=?", startime)
190
-	}
191
-	if endtime > 0 {
192
-		db = db.Where("x.end_time <=?", endtime)
193
-	}
194
-	if orgid > 0 {
195
-		db = db.Where("x.user_org_id = ?", orgid)
196
-	}
197
-	likeKey := "%" + keywords + "%"
198
-	//if(doctorid >0){
199
-	//  db = db.Where("x.doctor_id = ?", doctorid)
200
-	//}
201
-	err = db.Group("x.id").Select("x.id,x.doctor_id,x.doctor_type,x.schedule_type,x.schedule_week,x.user_org_id,x.start_time,x.schedule_date,x.end_time,r.user_type,r.user_name,s.class_name,r.admin_user_id,s.class_attributes,r.sort,r.is_sort").Joins("left join sgj_users.sgj_user_admin_role AS r ON r.admin_user_id = x.doctor_id").Joins("left join xt_doctor_schedules as s on s.id = x.schedule_type and s.user_org_id = ?", orgid).Where("r.org_id = ? and r.status = 1 and r.is_sort = 1  and r.user_name like ?", orgid, likeKey).Scan(&schedule).Error
202
-	return schedule, err
203
-}
204
-
205
-func DeleteStaffSchedule(orgid int64, startime int64, endtime int64) error {
206
-
207
-	schedule := models.StaffSchedule{}
208
-	err := XTWriteDB().Model(&schedule).Where("user_org_id = ? and start_time >= ? and end_time <=?", orgid, startime, endtime).Updates(map[string]interface{}{"status": 0}).Error
209
-	return err
210
-}
211
-
212
-func GetContinueScheduleByOrgId(orgid int64) (*models.ContinueSchedule, error) {
213
-
214
-	//schedules := models.DoctorSchedules{}
215
-	//err := XTReadDB().Model(&schedules).Where("user_org_id = ? and status = 1", orgid).Find(&schedules).Error
216
-	//if err == gorm.ErrRecordNotFound {
217
-	//  return nil, err
218
-	//}
219
-	//if err != nil {
220
-	//  return nil, err
221
-	//}
222
-	//return &schedules, nil
223
-	schedule := models.ContinueSchedule{}
224
-	err := XTReadDB().Model(&schedule).Where("user_org_id = ? and status = 1", orgid).Find(&schedule).Error
225
-	if err == gorm.ErrRecordNotFound {
226
-		return nil, err
227
-	}
228
-	if err != nil {
229
-		return nil, err
230
-	}
231
-	return &schedule, nil
232
-}
233
-
234
-func UpdateContinusSchedule(schedule *models.ContinueSchedule, orgid int64) error {
235
-
236
-	err := XTWriteDB().Model(&schedule).Where("user_org_id = ? and status = 1", orgid).Updates(map[string]interface{}{"is_status": schedule.IsStatus, "mtime": time.Now().Unix()}).Error
237
-	return err
238
-}
239
-
240
-func SaveNurseSort(role *models.App_Role, id int64) error {
241
-
242
-	err := UserWriteDB().Model(&role).Where("id = ?", id).Updates(map[string]interface{}{"sort": role.Sort}).Error
243
-	return err
244
-}
245
-
246
-func SaveIsSchedule(id int64, role *models.App_Role) error {
247
-
248
-	err := UserWriteDB().Model(&role).Where("id=?", id).Updates(map[string]interface{}{"is_sort": role.IsSort}).Error
249
-	return err
250
-}
251
-
252
-func GetScheduleListTotal(orgid int64, startime int64, endtime int64) (schedule []*models.CountStaffSchedule, err error) {
253
-
254
-	db := XTReadDB().Table("xt_staff_schedule as x").Where("x.status = 1")
255
-	if startime > 0 {
256
-		db = db.Where("x.start_time >=?", startime)
257
-	}
258
-	if endtime > 0 {
259
-		db = db.Where("x.end_time <=?", endtime)
260
-	}
261
-	if orgid > 0 {
262
-		db = db.Where("x.user_org_id = ?", orgid)
263
-	}
264
-	err = db.Group("x.doctor_id,x.schedule_type").Select("x.doctor_id,x.schedule_type,x.start_time,x.end_time,x.schedule_date,r.user_name,s.class_name,r.sort,r.is_sort,count(s.class_name) as count").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.doctor_id").Joins("left join xt_doctor_schedules as s on s.id = x.schedule_type").Where("r.org_id = ? and r.status = 1 and s.user_org_id = ? and s.status = 1", orgid, orgid).Scan(&schedule).Error
265
-	return schedule, err
266
-}
267
-
268
-func GetTotalMinutes(orgid int64, startime int64, endtime int64) (schedule []*models.CountStaffSchedule, err error) {
269
-
270
-	db := XTReadDB().Table("xt_staff_schedule as x").Where("x.status = 1")
271
-	if startime > 0 {
272
-		db = db.Where("x.start_time >=?", startime)
273
-	}
274
-	if endtime > 0 {
275
-		db = db.Where("x.end_time <=?", endtime)
276
-	}
277
-	if orgid > 0 {
278
-		db = db.Where("x.user_org_id = ?", orgid)
279
-	}
280
-	err = db.Group("x.doctor_id").Select("x.doctor_id,x.schedule_type,x.start_time,x.end_time,x.schedule_date,r.user_name,s.class_name,r.sort,r.is_sort,sum(s.minute) as totalminute").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.doctor_id").Joins("left join xt_doctor_schedules as s on s.id = x.schedule_type").Where("r.org_id = ? and r.status = 1 and s.user_org_id = ? and s.status = 1 and s.class_attributes = 1", orgid, orgid).Scan(&schedule).Error
281
-	return schedule, err
282
-}
283
-
284
-func GetTotalMinutesOne(orgid int64, startime int64, endtime int64) (schedule []*models.CountStaffSchedule, err error) {
285
-	db := XTReadDB().Table("xt_staff_schedule as x").Where("x.status = 1")
286
-	if startime > 0 {
287
-		db = db.Where("x.start_time >=?", startime)
288
-	}
289
-	if endtime > 0 {
290
-		db = db.Where("x.end_time <=?", endtime)
291
-	}
292
-	if orgid > 0 {
293
-		db = db.Where("x.user_org_id = ?", orgid)
294
-	}
295
-	err = db.Group("x.doctor_id").Select("x.doctor_id,x.schedule_type,x.start_time,x.end_time,x.schedule_date,r.user_name,s.class_name,r.sort,r.is_sort,sum(s.minute) as totalminute").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.doctor_id").Joins("left join xt_doctor_schedules as s on s.id = x.schedule_type").Where("r.org_id = ? and r.status = 1 and s.user_org_id = ? and s.status = 1 ", orgid, orgid).Scan(&schedule).Error
296
-	return schedule, err
297
-}
298
-
299
-func GetTotalMinutesTwo(orgid int64, startime int64, endtime int64) (schedule []*models.CountStaffSchedule, err error) {
300
-	db := XTReadDB().Table("xt_staff_schedule as x").Where("x.status = 1")
301
-	if startime > 0 {
302
-		db = db.Where("x.start_time >=?", startime)
303
-	}
304
-	if endtime > 0 {
305
-		db = db.Where("x.end_time <=?", endtime)
306
-	}
307
-	if orgid > 0 {
308
-		db = db.Where("x.user_org_id = ?", orgid)
309
-	}
310
-	err = db.Group("x.doctor_id").Select("x.doctor_id,x.schedule_type,x.start_time,x.end_time,x.schedule_date,r.user_name,s.class_name,r.sort,r.is_sort,sum(s.minute) as workminute").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.doctor_id").Joins("left join xt_doctor_schedules as s on s.id = x.schedule_type").Where("r.org_id = ? and r.status = 1 and s.user_org_id = ? and s.status = 1 and s.class_attributes = 1", orgid, orgid).Scan(&schedule).Error
311
-	return schedule, err
312
-}
313
-
314
-func GetChartTotalMinutesOne(orgid int64, startime int64, endtime int64, keywords string) (schedule []*models.CountStaffSchedule, err error) {
315
-	likeKey := "%" + keywords + "%"
316
-	db := XTReadDB().Table("xt_staff_schedule as x").Where("x.status = 1")
317
-	if startime > 0 {
318
-		db = db.Where("x.start_time >=?", startime)
319
-	}
320
-	if endtime > 0 {
321
-		db = db.Where("x.end_time <=?", endtime)
322
-	}
323
-	if orgid > 0 {
324
-		db = db.Where("x.user_org_id = ?", orgid)
325
-	}
326
-	err = db.Group("x.doctor_id").Select("x.doctor_id,x.schedule_type,x.start_time,x.end_time,x.schedule_date,r.user_name,s.class_name,r.sort,r.is_sort,sum(s.minute) as totalminute").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.doctor_id").Where("r.user_name like ?", likeKey).Joins("left join xt_doctor_schedules as s on s.id = x.schedule_type").Where("r.org_id = ? and r.status = 1 and s.user_org_id = ? and s.status = 1 ", orgid, orgid).Scan(&schedule).Error
327
-	return schedule, err
328
-}
329
-
330
-func GetChartTotalMinutesTwo(orgid int64, startime int64, endtime int64, keywords string) (schedule []*models.CountStaffSchedule, err error) {
331
-	likeKey := "%" + keywords + "%"
332
-	db := XTReadDB().Table("xt_staff_schedule as x").Where("x.status = 1")
333
-	if startime > 0 {
334
-		db = db.Where("x.start_time >=?", startime)
335
-	}
336
-	if endtime > 0 {
337
-		db = db.Where("x.end_time <=?", endtime)
338
-	}
339
-	if orgid > 0 {
340
-		db = db.Where("x.user_org_id = ?", orgid)
341
-	}
342
-	err = db.Group("x.doctor_id").Select("x.doctor_id,x.schedule_type,x.start_time,x.end_time,x.schedule_date,r.user_name,s.class_name,r.sort,r.is_sort,sum(s.minute) as workminute").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.doctor_id").Where("r.user_name like ?", likeKey).Joins("left join xt_doctor_schedules as s on s.id = x.schedule_type").Where("r.org_id = ? and r.status = 1 and s.user_org_id = ? and s.status = 1 and s.class_attributes = 1", orgid, orgid).Scan(&schedule).Error
343
-	return schedule, err
344
-}
345
-
346
-func GetTotalWorkDay(orgid int64, startime int64, endtime int64) (schedule []*models.CountStaffSchedule, err error) {
347
-
348
-	db := XTReadDB().Table("xt_staff_schedule as x").Where("x.status = 1")
349
-	if startime > 0 {
350
-		db = db.Where("x.start_time >=?", startime)
351
-	}
352
-	if endtime > 0 {
353
-		db = db.Where("x.end_time <=?", endtime)
354
-	}
355
-	if orgid > 0 {
356
-		db = db.Where("x.user_org_id = ?", orgid)
357
-	}
358
-	err = db.Group("x.doctor_id").Select("x.doctor_id,x.schedule_type,x.start_time,x.end_time,x.schedule_date,r.user_name,s.class_name,r.sort,r.is_sort,count(x.id) as count").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.doctor_id").Joins("left join xt_doctor_schedules as s on s.id = x.schedule_type").Where("r.org_id = ? and r.status = 1 and s.user_org_id = ? and s.status = 1 and s.class_attributes = 1", orgid, orgid).Scan(&schedule).Error
359
-	return schedule, err
360
-}
361
-
362
-func GetTotalNoWorkDay(orgid int64, startime int64, endtime int64) (schedule []*models.CountStaffSchedule, err error) {
363
-
364
-	db := XTReadDB().Table("xt_staff_schedule as x").Where("x.status = 1")
365
-	if startime > 0 {
366
-		db = db.Where("x.start_time >=?", startime)
367
-	}
368
-	if endtime > 0 {
369
-		db = db.Where("x.end_time <=?", endtime)
370
-	}
371
-	if orgid > 0 {
372
-		db = db.Where("x.user_org_id = ?", orgid)
373
-	}
374
-	err = db.Group("x.doctor_id").Select("x.doctor_id,x.schedule_type,x.start_time,x.end_time,x.schedule_date,r.user_name,s.class_name,r.sort,r.is_sort,count(x.id) as count").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.doctor_id").Joins("left join xt_doctor_schedules as s on s.id = x.schedule_type").Where("r.org_id = ? and r.status = 1 and s.user_org_id = ? and s.status = 1 and s.class_attributes = 2", orgid, orgid).Scan(&schedule).Error
375
-	return schedule, err
376
-}
377
-
378
-func GetSearchScheduleListTotal(orgid int64, startime int64, endtime int64, keywords string) (schedule []*models.CountStaffSchedule, err error) {
379
-	likeKey := "%" + keywords + "%"
380
-	db := XTReadDB().Table("xt_staff_schedule as x").Where("x.status = 1")
381
-	if startime > 0 {
382
-		db = db.Where("x.start_time >=?", startime)
383
-	}
384
-	if endtime > 0 {
385
-		db = db.Where("x.end_time <=?", endtime)
386
-	}
387
-	if orgid > 0 {
388
-		db = db.Where("x.user_org_id = ?", orgid)
389
-	}
390
-	err = db.Group("x.doctor_id,x.schedule_type").Select("x.doctor_id,x.schedule_type,x.start_time,x.end_time,x.schedule_date,r.user_name,s.class_name,r.sort,r.is_sort,count(s.class_name) as count").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.doctor_id").Where("r.user_name like ?", likeKey).Joins("left join xt_doctor_schedules as s on s.id = x.schedule_type").Where("r.org_id = ? and r.status = 1 and s.user_org_id = ? and s.status = 1 ", orgid, orgid).Scan(&schedule).Error
391
-	return schedule, err
392
-}
393
-
394
-func GeSearchtTotalMinutes(orgid int64, startime int64, endtime int64, keywords string) (schedule []*models.CountStaffSchedule, err error) {
395
-	likeKey := "%" + keywords + "%"
396
-	db := XTReadDB().Table("xt_staff_schedule as x").Where("x.status = 1")
397
-	if startime > 0 {
398
-		db = db.Where("x.start_time >=?", startime)
399
-	}
400
-	if endtime > 0 {
401
-		db = db.Where("x.end_time <=?", endtime)
402
-	}
403
-	if orgid > 0 {
404
-		db = db.Where("x.user_org_id = ?", orgid)
405
-	}
406
-	err = db.Group("x.doctor_id").Select("x.doctor_id,x.schedule_type,x.start_time,x.end_time,x.schedule_date,r.user_name,s.class_name,r.sort,r.is_sort,sum(s.minute) as totalminute").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.doctor_id").Where("r.user_name like ?", likeKey).Joins("left join xt_doctor_schedules as s on s.id = x.schedule_type").Where("r.org_id = ? and r.status = 1 and s.user_org_id = ? and s.status = 1  and s.class_attributes = 1", orgid, orgid).Scan(&schedule).Error
407
-	return schedule, err
408
-}
409
-
410
-func GetSearchWorkDay(orgid int64, startime int64, endtime int64, keywords string) (schedule []*models.CountStaffSchedule, err error) {
411
-	likeKey := "%" + keywords + "%"
412
-	db := XTReadDB().Table("xt_staff_schedule as x").Where("x.status = 1")
413
-	if startime > 0 {
414
-		db = db.Where("x.start_time >=?", startime)
415
-	}
416
-	if endtime > 0 {
417
-		db = db.Where("x.end_time <=?", endtime)
418
-	}
419
-	if orgid > 0 {
420
-		db = db.Where("x.user_org_id = ?", orgid)
421
-	}
422
-	err = db.Group("x.doctor_id").Select("x.doctor_id,x.schedule_type,x.start_time,x.end_time,x.schedule_date,r.user_name,s.class_name,r.sort,r.is_sort,count(x.id) as count").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.doctor_id").Where("r.user_name like ?", likeKey).Joins("left join xt_doctor_schedules as s on s.id = x.schedule_type").Where("r.org_id = ? and r.status = 1 and s.user_org_id = ? and s.status = 1 and s.class_attributes = 1", orgid, orgid).Scan(&schedule).Error
423
-	return schedule, err
424
-}
425
-
426
-func GetSearchWorkNoDay(orgid int64, startime int64, endtime int64, keywords string) (schedule []*models.CountStaffSchedule, err error) {
427
-	likeKey := "%" + keywords + "%"
428
-	db := XTReadDB().Table("xt_staff_schedule as x").Where("x.status = 1")
429
-	if startime > 0 {
430
-		db = db.Where("x.start_time >=?", startime)
431
-	}
432
-	if endtime > 0 {
433
-		db = db.Where("x.end_time <=?", endtime)
434
-	}
435
-	if orgid > 0 {
436
-		db = db.Where("x.user_org_id = ?", orgid)
437
-	}
438
-	err = db.Group("x.doctor_id").Select("x.doctor_id,x.schedule_type,x.start_time,x.end_time,x.schedule_date,r.user_name,s.class_name,r.sort,r.is_sort,count(x.id) as count").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.doctor_id").Where("r.user_name like ?", likeKey).Joins("left join xt_doctor_schedules as s on s.id = x.schedule_type").Where("r.org_id = ? and r.status = 1 and s.user_org_id = ? and s.status = 1 and s.class_attributes = 2", orgid, orgid).Scan(&schedule).Error
439
-	return schedule, err
440
-}
441
-
442
-func ChagneScheduleListTotal(orgid int64, startime int64, endtime int64, doctortype int64) (schedule []*models.CountStaffSchedule, err error) {
443
-
444
-	db := XTReadDB().Table("xt_staff_schedule as x").Where("x.status = 1")
445
-	if startime > 0 {
446
-		db = db.Where("x.start_time >=?", startime)
447
-	}
448
-	if endtime > 0 {
449
-		db = db.Where("x.end_time <=?", endtime)
450
-	}
451
-	if orgid > 0 {
452
-		db = db.Where("x.user_org_id = ?", orgid)
453
-	}
454
-	if doctortype == 0 {
455
-		db = db.Where("x.doctor_type = 2 or x.doctor_type = 3")
456
-	}
457
-	if doctortype > 0 {
458
-		db = db.Where("x.doctor_type = ?", doctortype)
459
-	}
460
-	err = db.Group("x.doctor_id,x.schedule_type").Select("x.doctor_id,x.schedule_type,x.start_time,x.end_time,x.schedule_date,r.user_name,s.class_name,r.sort,r.is_sort,count(s.class_name) as count").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.doctor_id").Joins("left join xt_doctor_schedules as s on s.id = x.schedule_type").Where("r.org_id = ? and r.status = 1 and s.user_org_id = ? and s.status = 1 ", orgid, orgid).Scan(&schedule).Error
461
-	return schedule, err
462
-}
463
-
464
-func ChangeScheduleMinute(orgid int64, startime int64, endtime int64, doctortype int64) (schedule []*models.CountStaffSchedule, err error) {
465
-
466
-	db := XTReadDB().Table("xt_staff_schedule as x").Where("x.status = 1")
467
-	if startime > 0 {
468
-		db = db.Where("x.start_time >=?", startime)
469
-	}
470
-	if endtime > 0 {
471
-		db = db.Where("x.end_time <=?", endtime)
472
-	}
473
-	if orgid > 0 {
474
-		db = db.Where("x.user_org_id = ?", orgid)
475
-	}
476
-	if doctortype == 0 {
477
-		db = db.Where("x.doctor_type = 2 or x.doctor_type = 3")
478
-	}
479
-	if doctortype > 0 {
480
-		db = db.Where("x.doctor_type = ?", doctortype)
481
-	}
482
-	err = db.Group("x.doctor_id").Select("x.doctor_id,x.schedule_type,x.start_time,x.end_time,x.schedule_date,r.user_name,s.class_name,r.sort,r.is_sort,sum(s.minute) as totalminute").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.doctor_id").Joins("left join xt_doctor_schedules as s on s.id = x.schedule_type").Where("r.org_id = ? and r.status = 1 and s.user_org_id = ? and s.status = 1 and s.class_attributes = 1", orgid, orgid).Scan(&schedule).Error
483
-	return schedule, err
484
-}
485
-
486
-func ChangeWorkDay(orgid int64, startime int64, endtime int64, doctortype int64) (schedule []*models.CountStaffSchedule, err error) {
487
-
488
-	db := XTReadDB().Table("xt_staff_schedule as x").Where("x.status = 1")
489
-	if startime > 0 {
490
-		db = db.Where("x.start_time >=?", startime)
491
-	}
492
-	if endtime > 0 {
493
-		db = db.Where("x.end_time <=?", endtime)
494
-	}
495
-	if orgid > 0 {
496
-		db = db.Where("x.user_org_id = ?", orgid)
497
-	}
498
-	if doctortype == 0 {
499
-		db = db.Where("x.doctor_type = 2 or x.doctor_type = 3")
500
-	}
501
-	if doctortype > 0 {
502
-		db = db.Where("x.doctor_type = ?", doctortype)
503
-	}
504
-	err = db.Group("x.doctor_id").Select("x.doctor_id,x.schedule_type,x.start_time,x.end_time,x.schedule_date,r.user_name,s.class_name,r.sort,r.is_sort,count(x.id) as count").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.doctor_id").Joins("left join xt_doctor_schedules as s on s.id = x.schedule_type").Where("r.org_id = ? and r.status = 1 and s.user_org_id = ? and s.status = 1 and s.class_attributes = 1", orgid, orgid).Scan(&schedule).Error
505
-	return schedule, err
506
-}
507
-
508
-func ChangeNoWorkDay(orgid int64, startime int64, endtime int64, doctortype int64) (schedule []*models.CountStaffSchedule, err error) {
509
-
510
-	db := XTReadDB().Table("xt_staff_schedule as x").Where("x.status = 1")
511
-	if startime > 0 {
512
-		db = db.Where("x.start_time >=?", startime)
513
-	}
514
-	if endtime > 0 {
515
-		db = db.Where("x.end_time <=?", endtime)
516
-	}
517
-	if orgid > 0 {
518
-		db = db.Where("x.user_org_id = ?", orgid)
519
-	}
520
-	if doctortype == 0 {
521
-		db = db.Where("x.doctor_type = 2 or x.doctor_type = 3")
522
-	}
523
-	if doctortype > 0 {
524
-		db = db.Where("x.doctor_type = ?", doctortype)
525
-	}
526
-	err = db.Group("x.doctor_id").Select("x.doctor_id,x.schedule_type,x.start_time,x.end_time,x.schedule_date,r.user_name,s.class_name,r.sort,r.is_sort,count(x.id) as count").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.doctor_id").Joins("left join xt_doctor_schedules as s on s.id = x.schedule_type").Where("r.org_id = ? and r.status = 1 and s.user_org_id = ? and s.status = 1 and s.class_attributes = 2", orgid, orgid).Scan(&schedule).Error
527
-	return schedule, err
528
-}
529
-
530
-func ChartTotalMinute(orgid int64, startime int64, endtime int64, doctortype int64) (schedule []*models.CountStaffSchedule, err error) {
531
-	db := XTReadDB().Table("xt_staff_schedule as x").Where("x.status = 1")
532
-	if startime > 0 {
533
-		db = db.Where("x.start_time >=?", startime)
534
-	}
535
-	if endtime > 0 {
536
-		db = db.Where("x.end_time <=?", endtime)
537
-	}
538
-	if orgid > 0 {
539
-		db = db.Where("x.user_org_id = ?", orgid)
540
-	}
541
-	if doctortype == 0 {
542
-		db = db.Where("x.doctor_type = 2 or x.doctor_type = 3")
543
-	}
544
-	if doctortype > 0 {
545
-		db = db.Where("x.doctor_type = ?", doctortype)
546
-	}
547
-	err = db.Group("x.doctor_id").Select("x.doctor_id,x.schedule_type,x.start_time,x.end_time,x.schedule_date,r.user_name,s.class_name,r.sort,r.is_sort,sum(s.minute) as totalminute").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.doctor_id").Joins("left join xt_doctor_schedules as s on s.id = x.schedule_type").Where("r.org_id = ? and r.status = 1 and s.user_org_id = ? and s.status = 1 ", orgid, orgid).Scan(&schedule).Error
548
-	return schedule, err
549
-}
550
-
551
-func ChartWorkDayMinute(orgid int64, startime int64, endtime int64, doctortype int64) (schedule []*models.CountStaffSchedule, err error) {
552
-
553
-	db := XTReadDB().Table("xt_staff_schedule as x").Where("x.status = 1")
554
-	if startime > 0 {
555
-		db = db.Where("x.start_time >=?", startime)
556
-	}
557
-	if endtime > 0 {
558
-		db = db.Where("x.end_time <=?", endtime)
559
-	}
560
-	if orgid > 0 {
561
-		db = db.Where("x.user_org_id = ?", orgid)
562
-	}
563
-	if doctortype == 0 {
564
-		db = db.Where("x.doctor_type = 2 or x.doctor_type = 3")
565
-	}
566
-	if doctortype > 0 {
567
-		db = db.Where("x.doctor_type = ?", doctortype)
568
-	}
569
-	err = db.Group("x.doctor_id").Select("x.doctor_id,x.schedule_type,x.start_time,x.end_time,x.schedule_date,r.user_name,s.class_name,r.sort,r.is_sort,sum(s.minute) as workminute").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.doctor_id").Joins("left join xt_doctor_schedules as s on s.id = x.schedule_type").Where("r.org_id = ? and r.status = 1 and s.user_org_id = ? and s.status = 1 and s.class_attributes = 1", orgid, orgid).Scan(&schedule).Error
570
-	return schedule, err
571
-}
572
-
573
-func GetMySchedule(startime int64, endtime int64, orgid int64, creator int64) (schedule []*models.XtStaffSchedule, err error) {
574
-	db := XTReadDB().Table("xt_staff_schedule as x").Where("x.status = 1")
575
-	err = db.Group("x.id").Select("x.doctor_id,x.schedule_week,s.class_name").Where("x.start_time >=? and x.end_time<=? and x.user_org_id = ? and x.doctor_id = ?", startime, endtime, orgid, creator).Joins("left join xt_doctor_schedules as s on s.id = x.schedule_type").Scan(&schedule).Error
576
-	return schedule, err
577
-}
578
-
579
-func GetAllMobileZone(orgid int64) (zone []*models.DeviceZone, err error) {
580
-
581
-	err = XTReadDB().Model(&zone).Where("org_id = ? and status = 1", orgid).Find(&zone).Error
582
-	return zone, err
583
-}
584
-
585
-func GetPatientSchedule(startime int64, zoneid int64, classtype int64, orgid int64) (schedule []*models.Schedule, err error) {
586
-
587
-	db := XTReadDB().Table("xt_schedule as s")
588
-	if zoneid > 0 {
589
-		db = db.Where("s.partition_id = ?", zoneid)
590
-	}
591
-	if classtype > 0 {
592
-		db = db.Where("s.schedule_type = ?", classtype)
593
-	}
594
-	err = db.Preload("DeviceZone", " status= 1").Preload("DeviceNumber", "status= 1").
595
-		Preload("DialysisOrder", "status =1").Joins("JOIN xt_patients as p ON p.id = s.patient_id").Where("s.user_org_id = ? and s.schedule_date = ? and s.status =1", orgid, startime).
596
-		Select("s.id, s.user_org_id, s.partition_id, s.bed_id, s.patient_id, s.schedule_date, s.schedule_type, s.schedule_week, s.mode_id,p.name as patient").Find(&schedule).Error
597
-	return schedule, err
598
-}
599
-
600
-func DeleteSchedule(id int64) error {
601
-
602
-	schedule := models.XtSchedule{}
603
-
604
-	err := XTWriteDB().Model(&schedule).Where("id=? and status = 1", id).Updates(map[string]interface{}{"status": 0}).Error
605
-	return err
606
-}
607
-
608
-func GetSearchPatient(keywords string, orgid int64, startime int64) (schedule []*models.Schedule, err error) {
609
-
610
-	likeKey := "%" + keywords + "%"
611
-	db := XTReadDB().Table("xt_schedule as s")
612
-	err = db.Preload("DeviceZone", " status= 1").Preload("DeviceNumber", "status= 1").
613
-		Preload("DialysisOrder", "status =1").
614
-		Joins("JOIN xt_patients as p ON p.id = s.patient_id And(p.name LIKE ? OR p.dialysis_no LIKE ?)", likeKey, likeKey).Where("s.user_org_id = ? and s.schedule_date = ? and s.status =1", orgid, startime).
615
-		Select("s.id, s.user_org_id, s.partition_id, s.bed_id, s.patient_id, s.schedule_date, s.schedule_type, s.schedule_week, s.mode_id,p.name as patient").Find(&schedule).Error
616
-	return schedule, err
617
-}

+ 0 - 165
models/service/gobal_config_service.go Просмотреть файл

@@ -1,165 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	"github.com/jinzhu/gorm"
6
-)
7
-
8
-func CreateAutomaticReduceRecord(config *models.GobalConfig) (err error) {
9
-	err = writeDb.Model(&models.GobalConfig{}).Create(config).Error
10
-	return
11
-}
12
-
13
-func FindAutomaticReduceRecordByOrgId(org_id int64) (err error, config models.GobalConfig) {
14
-	err = readDb.Model(&models.GobalConfig{}).Where("status = 1 AND org_id = ?", org_id).Find(&config).Error
15
-	return
16
-}
17
-
18
-func UpdateAutomaticReduceRecord(config *models.GobalConfig) (err error) {
19
-	err = writeDb.Save(config).Error
20
-	return
21
-}
22
-
23
-func CreatePrintTemplateRecord(template *models.GobalTemplate) (err error) {
24
-	err = writeDb.Model(&models.GobalTemplate{}).Create(template).Error
25
-	return
26
-}
27
-
28
-func FindPrintTemplateByOrgId(org_id int64) (err error, template models.GobalTemplate) {
29
-	err = readDb.Model(&models.GobalTemplate{}).Where("status = 1 AND org_id = ?", org_id).Find(&template).Error
30
-	return
31
-}
32
-
33
-func UpdatePrintTemplate(template *models.GobalTemplate) (err error) {
34
-	err = writeDb.Save(template).Error
35
-	return
36
-}
37
-
38
-func CreateConfigData(config *models.DataUploadConfig) (err error) {
39
-	err = writeDb.Create(config).Error
40
-	return
41
-}
42
-
43
-func SaveConfigData(config *models.DataUploadConfig) (err error) {
44
-	err = writeDb.Save(config).Error
45
-	return
46
-}
47
-
48
-func GetConfigData(org_id int64, config_type int64) (config models.DataUploadConfig, err error) {
49
-	err = readDb.Model(&models.DataUploadConfig{}).Where("status = 1 AND  org_id = ? AND config_type = ?", org_id, config_type).First(&config).Error
50
-	return
51
-}
52
-
53
-func GetDockingStatus(config_type int64, province int64, city int64) (config models.DockingStatus, err error) {
54
-	err = readDb.Model(&models.DockingStatus{}).Where("status = 1 AND  docking_type = ? AND province_id = ? AND city_id = ?", config_type, province, city).First(&config).Error
55
-	return
56
-}
57
-
58
-func GetConfigDataById(id int64) (config models.DataUploadConfig, err error) {
59
-	err = readDb.Model(&models.DataUploadConfig{}).Where("id = ?", id).First(&config).Error
60
-	return
61
-}
62
-
63
-func FindDoctorAdviceRecordByOrgId(org_id int64) (err error, config models.DoctorAdviceConfig) {
64
-	err = readDb.Model(&models.DoctorAdviceConfig{}).Where("status = 1 AND user_org_id = ?", org_id).Find(&config).Error
65
-	return
66
-}
67
-
68
-func CreateDoctorAdviceRecord(config *models.DoctorAdviceConfig) (err error) {
69
-	err = writeDb.Model(&models.DoctorAdviceConfig{}).Create(config).Error
70
-	return
71
-}
72
-
73
-func UpdateDoctorAdviceRecord(config *models.DoctorAdviceConfig) (err error) {
74
-	err = writeDb.Save(config).Error
75
-	return
76
-}
77
-
78
-func UpdateFiledConfig(org_id int64) (err error) {
79
-	err = writeDb.Model(&models.FiledConfig{}).Where("org_id = ? AND sys_module = 0", org_id).Updates(map[string]interface{}{"is_show": 1}).Error
80
-	return
81
-}
82
-
83
-func FindAllHideFiledConfig(template_id int64) (err error, config []*models.FiledConfig) {
84
-	err = readDb.Model(&models.FiledConfig{}).Where("sys_module = ?  AND is_show = 2", template_id).Find(&config).Error
85
-	return
86
-}
87
-
88
-func UpdateShowFieldConfig(org_id int64, fileds []string) (err error) {
89
-	err = writeDb.Model(&models.FiledConfig{}).Where("org_id = ? AND filed_name in (?) AND sys_module = 0 ", org_id, fileds).Updates(map[string]interface{}{"is_show": 2}).Error
90
-	return
91
-}
92
-
93
-func FindAllAdviceParentTemplate(org_id int64) (template []*models.DoctorAdviceParentTemplate) {
94
-	readDb.Model(&models.DoctorAdviceParentTemplate{}).Preload("DoctorAdviceTemplate", func(db *gorm.DB) *gorm.DB {
95
-		return db.Preload("SubDoctorAdviceTemplate", "status = 1 AND org_id = ?", org_id).Where("status = 1 AND parent_id = 0  AND org_id = ?", org_id)
96
-	}).Where("status = 1 AND org_id = ? ", org_id).Find(&template)
97
-	return
98
-}
99
-
100
-func CreateDoctorParentTemplate(template *models.DoctorAdviceParentTemplate) (err error) {
101
-	err = writeDb.Create(&template).Error
102
-	return
103
-}
104
-
105
-func FindAllAdviceTemplates(org_id int64, parent_template_id int64) (template []*models.DoctorAdviceTemplate, err error) {
106
-	err = readDb.Model(&models.DoctorAdviceTemplate{}).Where("status = 1 AND org_id = ? AND template_id = ?", org_id, parent_template_id).Find(&template).Error
107
-	return
108
-}
109
-
110
-func CreateDoctorTemplate(template *models.DoctorAdviceTemplate) (err error) {
111
-	err = writeDb.Create(&template).Error
112
-	return
113
-}
114
-
115
-func CreateSystemDialysisSolution(solution *models.SystemPrescription) (err error) {
116
-	err = writeDb.Create(solution).Error
117
-	return
118
-}
119
-
120
-func UpdateSystemDialysisSolution(solution *models.SystemPrescription) (err error) {
121
-	err = writeDb.Save(solution).Error
122
-	return
123
-}
124
-
125
-func FindSystemDialysisSolution(orgID int64, id int64) (solution models.SystemPrescription, err error) {
126
-	err = readDb.Model(&models.SystemPrescription{}).Where("id = ? and status=1 and user_org_id=?", id, orgID).First(&solution).Error
127
-	return
128
-}
129
-
130
-func FindAllSystemPrescription(orgID int64) (solution []*models.SystemPrescription, err error) {
131
-	err = readDb.Model(&models.SystemPrescription{}).Where("status=1 and user_org_id=?", orgID).Find(&solution).Error
132
-	return
133
-}
134
-
135
-func FindSystemDialysisPrescriptionByMode(orgID int64, id int64) (solution models.SystemPrescription, err error) {
136
-	err = readDb.Model(&models.SystemPrescription{}).Where("mode_id = ? and status=1 and user_org_id=?", id, orgID).First(&solution).Error
137
-	return
138
-}
139
-
140
-func CreateAdviceInitConfig(adviceInit *models.AdviceInit) (err error) {
141
-	err = writeDb.Create(&adviceInit).Error
142
-	return
143
-}
144
-
145
-func FindAdviceInitConfig(org_id int64) (adviceInit models.AdviceInit, err error) {
146
-	err = readDb.Model(&models.AdviceInit{}).Where("user_org_id = ? AND status = 1 ", org_id).First(&adviceInit).Error
147
-	return
148
-}
149
-
150
-func GetPrint(ids []int64, orgid int64) (doctor []*models.DoctorAdvice, err error) {
151
-
152
-	if len(ids) == 1 {
153
-		err = XTReadDB().Model(&doctor).Where("groupno = ? and user_org_id = ?", ids[0], orgid).Find(&doctor).Error
154
-	} else {
155
-		err = XTReadDB().Model(&doctor).Where("groupno IN(?) and user_org_id = ?", ids, orgid).Find(&doctor).Error
156
-	}
157
-
158
-	return doctor, err
159
-}
160
-
161
-func GetExportLogByType(org_id int64, log_type int64) (log []*models.ExportLog, err error) {
162
-	err = readDb.Model(&models.ExportLog{}).Where("user_org_id = ? AND status = 1 AND log_type = ?", org_id, log_type).
163
-		Preload("ExportErrLog", "status = 1").Order("export_time desc").Find(&log).Error
164
-	return
165
-}

+ 0 - 37
models/service/home_service.go Просмотреть файл

@@ -1,37 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	"github.com/jinzhu/gorm"
6
-)
7
-
8
-func GetHomeData(adminUserId int64) (adminUser models.VMAdminUser, err error) {
9
-	err = readUserDb.Model(&models.VMAdminUser{}).Where("status = 1 AND id = ?", adminUserId).
10
-		Preload("Org", "status = 1").
11
-		Preload("VMApp_Role", func(db *gorm.DB) *gorm.DB {
12
-			return db.Preload("Org", "status = 1").Where("status = 1")
13
-		}).Find(&adminUser).Error
14
-	return
15
-}
16
-
17
-func GetCreator(id int64, orgid int64) (models.SgjUserAdminRole, error) {
18
-	role := models.SgjUserAdminRole{}
19
-	err := UserReadDB().Model(&role).Where("admin_user_id = ? and org_id = ? and status =1", id, orgid).Find(&role).Error
20
-	return role, err
21
-}
22
-
23
-func GetSuperAdmin(id int64) (models.SgjUserAdmin, error) {
24
-	admin := models.SgjUserAdmin{}
25
-	err := UserReadDB().Model(&admin).Where("id=? and status =1", id).Find(&admin).Error
26
-	return admin, err
27
-}
28
-
29
-func GetAllApp(org_id int64) (apps []*models.OrgApp, err error) {
30
-	err = readUserDb.Model(&models.OrgApp{}).Where("status = 1 AND pid > 0 AND org_id = ?", org_id).Order("number asc").Find(&apps).Error
31
-	return
32
-}
33
-
34
-func GetSystemBanner() (banners []*models.VMAdminBanner, err error) {
35
-	err = readUserDb.Model(&models.VMAdminBanner{}).Where("status = 1 ").Find(&banners).Error
36
-	return
37
-}

+ 0 - 213
models/service/inspection_service.go Просмотреть файл

@@ -1,213 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	"errors"
6
-	"strings"
7
-	"time"
8
-)
9
-
10
-func GetInspectionReference(orgId int64) (reference []*models.InspectionReference, err error) {
11
-	var count int
12
-	err = readDb.Model(&models.InspectionReference{}).Where("org_id=? and status=1", orgId).Count(&count).Error
13
-	if count > 0 {
14
-		err = readDb.Model(&models.InspectionReference{}).Where("org_id=? and status=1", orgId).Order("project_id").Find(&reference).Error
15
-	} else {
16
-		err = readDb.Model(&models.InspectionReference{}).Where("org_id=0 and status=1").Order("project_id").Find(&reference).Error
17
-	}
18
-	return
19
-}
20
-
21
-func GetPatientInspectionProjectCount(orgId, patientId int64) (projectCounts []*models.UserInspectionProjectCount, err error) {
22
-	err = readDb.Model(&models.Inspection{}).Where("patient_id=? and org_id=? and status=1", patientId, orgId).Select("count(distinct inspect_date) as count, project_id, patient_id").Group("project_id").Scan(&projectCounts).Error
23
-	return
24
-}
25
-
26
-func GetPatientInspectionByDate(orgId, patientId, date, projectId int64) (inspections []*models.Inspection, err error) {
27
-	err = readDb.Model(&models.Inspection{}).Where("patient_id=? and org_id=? and project_id =? and inspect_date =? and status=1", patientId, orgId, projectId, date).Find(&inspections).Error
28
-	return
29
-}
30
-
31
-func GetAdvices(orgid int64, patientid int64, recorddate int64) (advcie []*models.DoctorAdvice, err error) {
32
-
33
-	err = XTReadDB().Model(&models.DoctorAdvice{}).Where("patient_id = ? and user_org_id = ? and record_date = ? and status =1", patientid, orgid, recorddate).Find(&advcie).Error
34
-	return
35
-}
36
-
37
-func CreatePatientInspection(inspectins []models.Inspection) (err error) {
38
-	if len(inspectins) == 0 {
39
-		err = errors.New("Inspections Cant be nil.")
40
-		return
41
-	}
42
-
43
-	thisSQL := "INSERT INTO xt_inspection (patient_id, org_id, project_id, item_id, item_name, project_name, inspect_type, inspect_value, inspect_date, status, created_time, updated_time) VALUES "
44
-	insertParams := make([]string, 0)
45
-	insertData := make([]interface{}, 0)
46
-	for _, inspectin := range inspectins {
47
-		insertParams = append(insertParams, "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
48
-		insertData = append(insertData, inspectin.PatientId)
49
-		insertData = append(insertData, inspectin.OrgId)
50
-		insertData = append(insertData, inspectin.ProjectId)
51
-		insertData = append(insertData, inspectin.ItemId)
52
-		insertData = append(insertData, inspectin.ItemName)
53
-		insertData = append(insertData, inspectin.ProjectName)
54
-		insertData = append(insertData, inspectin.InspectType)
55
-		insertData = append(insertData, inspectin.InspectValue)
56
-		insertData = append(insertData, inspectin.InspectDate)
57
-		insertData = append(insertData, 1)
58
-		insertData = append(insertData, inspectin.CreatedTime)
59
-		insertData = append(insertData, inspectin.UpdatedTime)
60
-	}
61
-	thisSQL += strings.Join(insertParams, ", ")
62
-	err = writeDb.Exec(thisSQL, insertData...).Error
63
-	return
64
-}
65
-
66
-func EditPatientInspection(add []models.Inspection, edit []models.Inspection, noDeleteIDs []int64, patientId, orgId, projectId, date int64) (err error) {
67
-	if len(add) == 0 && len(edit) == 0 && len(noDeleteIDs) == 0 {
68
-		err = errors.New(" Cant be nil.")
69
-		return
70
-	}
71
-
72
-	tx := writeDb.Begin()
73
-
74
-	if len(noDeleteIDs) > 0 {
75
-		err = tx.Model(&models.Inspection{}).Where("patient_id=? and org_id=? and project_id =? and inspect_date =? and id NOT IN (?) and status=1", patientId, orgId, projectId, date, noDeleteIDs).Update(map[string]interface{}{"Status": 0, "UpdatedTime": time.Now().Unix()}).Error
76
-		if err != nil {
77
-			tx.Rollback()
78
-			return
79
-		}
80
-	}
81
-
82
-	if len(edit) > 0 {
83
-		for _, item := range edit {
84
-			err = tx.Save(&item).Error
85
-			if err != nil {
86
-				tx.Rollback()
87
-				return
88
-			}
89
-		}
90
-	}
91
-	if len(add) > 0 {
92
-		thisSQL := "INSERT INTO xt_inspection (patient_id, org_id, project_id, item_id, item_name, project_name, inspect_type, inspect_value, inspect_date, status, created_time, updated_time) VALUES "
93
-		insertParams := make([]string, 0)
94
-		insertData := make([]interface{}, 0)
95
-		for _, inspectin := range add {
96
-			insertParams = append(insertParams, "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
97
-			insertData = append(insertData, inspectin.PatientId)
98
-			insertData = append(insertData, inspectin.OrgId)
99
-			insertData = append(insertData, inspectin.ProjectId)
100
-			insertData = append(insertData, inspectin.ItemId)
101
-			insertData = append(insertData, inspectin.ItemName)
102
-			insertData = append(insertData, inspectin.ProjectName)
103
-			insertData = append(insertData, inspectin.InspectType)
104
-			insertData = append(insertData, inspectin.InspectValue)
105
-			insertData = append(insertData, inspectin.InspectDate)
106
-			insertData = append(insertData, 1)
107
-			insertData = append(insertData, inspectin.CreatedTime)
108
-			insertData = append(insertData, inspectin.UpdatedTime)
109
-		}
110
-		thisSQL += strings.Join(insertParams, ", ")
111
-		err = tx.Exec(thisSQL, insertData...).Error
112
-		if err != nil {
113
-			tx.Rollback()
114
-			return
115
-		}
116
-	}
117
-	tx.Commit()
118
-
119
-	return
120
-}
121
-
122
-func DeletePatientInspection(orgId, patientId, projectId, date int64) (err error) {
123
-	err = writeDb.Model(&models.Inspection{}).Where("patient_id=? and org_id=? and project_id =? and inspect_date =? and status=1", patientId, orgId, projectId, date).Update(map[string]interface{}{"Status": 0, "UpdatedTime": time.Now().Unix()}).Error
124
-	return
125
-}
126
-
127
-func GetPatientInspections(orgId, patientId, projectId, page int64) (inspections []*models.Inspection, total int64, date int64, err error) {
128
-
129
-	var projectCount models.UserInspectionProjectCount
130
-	err = readDb.Model(&models.Inspection{}).Where("patient_id=? and org_id=? and project_id=? and status=1", patientId, orgId, projectId).Select("count(distinct inspect_date) as count, project_id, patient_id").Scan(&projectCount).Error
131
-
132
-	if err != nil {
133
-		return
134
-	}
135
-
136
-	total = projectCount.Count
137
-	if total == 0 || page > total {
138
-		return
139
-	}
140
-
141
-	var Id models.InspectionDate
142
-	err = readDb.Model(&models.Inspection{}).Where("patient_id=? and org_id=? and project_id=? and status=1", patientId, orgId, projectId).Select("inspect_date").Group("inspect_date").Order("inspect_date desc").Offset(page - 1).Limit(1).Scan(&Id).Error
143
-	if err != nil {
144
-		return
145
-	}
146
-	if Id.InspectDate == 0 {
147
-		return
148
-	}
149
-
150
-	date = Id.InspectDate
151
-
152
-	inspections, err = GetPatientInspectionByDate(orgId, patientId, Id.InspectDate, projectId)
153
-	if err != nil {
154
-		return
155
-	}
156
-
157
-	return
158
-
159
-}
160
-
161
-type DateViewModel struct {
162
-	inspect_date int64 `gorm:"column:inspect_date" json:"inspect_date"`
163
-	project_id   int64 `gorm:"column:project_id" json:"project_id"`
164
-}
165
-
166
-func FindLastRecordDate(orgId int64, patientId int64, project_id int64) (inspections models.Inspection, err error) {
167
-	err = readDb.Raw("SELECT max(inspect_date) as inspect_date,project_id   FROM `xt_inspection`  WHERE (status = 1 AND org_id = ? AND project_id = ?  AND patient_id = ?) ORDER BY `xt_inspection`.`id` ASC LIMIT 1", orgId, project_id, patientId).Scan(&inspections).Error
168
-	return
169
-}
170
-
171
-func UpDateInfectiousRecordTime(orgId int64, patientId int64, time int64, remind_cycle int64) (err error) {
172
-	err = writeDb.Model(&models.Patients{}).Where("status = 1 AND user_org_id = ? AND id = ?", orgId, patientId).Updates(map[string]interface{}{"infectious_next_record_time": time, "remind_cycle": remind_cycle}).Error
173
-	return
174
-}
175
-
176
-func GetAllPatientInspection(orgId, patientId, page int64, projectId int64, start_time int64, end_time int64) (inspections []*models.Inspection, date int64, err error) {
177
-
178
-	//var projectCount models.UserInspectionProjectCount
179
-	//err = readDb.Model(&models.Inspection{}).Where("patient_id=? and org_id=? and project_id in (?)  and status=1", patientId, orgId,projectId).Select("count(distinct inspect_date) as count, project_id, patient_id").Scan(&projectCount).Error
180
-	//
181
-	//if err != nil {
182
-	//	return
183
-	//}
184
-	//
185
-	//total = projectCount.Count
186
-	//if total == 0 || page > total {
187
-	//	return
188
-	//}
189
-
190
-	var Id models.InspectionDate
191
-	err = readDb.Model(&models.Inspection{}).Where("patient_id=? and org_id=? and project_id=? and status=1 and inspect_date >= ? and inspect_date <= ?", patientId, orgId, projectId, start_time, end_time).Select("inspect_date").Group("inspect_date").Order("inspect_date desc").Offset(page - 1).Limit(1).Scan(&Id).Error
192
-	if err != nil {
193
-		return
194
-	}
195
-	if Id.InspectDate == 0 {
196
-		return
197
-	}
198
-
199
-	date = Id.InspectDate
200
-
201
-	inspections, err = GetPatientInspectionByDate(orgId, patientId, Id.InspectDate, projectId)
202
-	if err != nil {
203
-		return
204
-	}
205
-
206
-	return
207
-
208
-}
209
-
210
-func GetAllInspectionReference(orgId int64) (inspectionReference []*models.InspectionReference, err error) {
211
-	err = readDb.Model(&models.InspectionReference{}).Where("org_id = ? AND status = 1", orgId).Find(&inspectionReference).Error
212
-	return
213
-}

+ 0 - 120
models/service/integration_service.go Просмотреть файл

@@ -1,120 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	"github.com/jinzhu/gorm"
6
-	"time"
7
-)
8
-
9
-func UpdateSysItemIdByID(sysInspection *models.InspectionReference) error {
10
-	db := XTWriteDB()
11
-	err := db.Model(&models.InspectionReference{}).Update(&sysInspection).Error
12
-	return err
13
-}
14
-
15
-func GetSysInspectionList(orgID int64) (sysInspection []*models.InspectionReference, ownerInspection []*models.InspectionReference, err error) {
16
-	db := XTReadDB()
17
-	err = db.Model(&models.InspectionReference{}).Where("org_id= 0 and status=1").Find(&sysInspection).Error
18
-	err = db.Model(&models.InspectionReference{}).Where("org_id= ? and status=1", orgID).Find(&ownerInspection).Error
19
-	return
20
-}
21
-
22
-func GetSyncList(orgID int64, page, limit int64) (patients []*models.MiddleSyncInfo, total int64, err error) {
23
-	//db := MiddleReadDB()
24
-	db := MiddleReadDB()
25
-	offset := (page - 1) * limit
26
-	err = db.Model(&models.MiddleSyncInfo{}).Where("org_id=? ", orgID).Count(&total).Offset(offset).Limit(limit).Find(&patients).Error
27
-	return
28
-}
29
-
30
-func SaveInterface(interfaceinfo *models.MiddleInterface) error {
31
-	db := MiddleWriteDB()
32
-	if interfaceinfo.ID > 0 {
33
-		err := db.Save(&interfaceinfo).Error
34
-		return err
35
-	} else {
36
-		err := db.Create(&interfaceinfo).Error
37
-		return err
38
-	}
39
-}
40
-
41
-func GetInterface(orgID int64) (interfaceinfo models.MiddleInterface, err error) {
42
-	db := MiddleReadDB()
43
-	err = db.Model(&models.MiddleInterface{}).Where("org_id=? and status=1", orgID).First(&interfaceinfo).Error
44
-	return
45
-}
46
-
47
-func GetIntegrationPatientList(orgID int64, page, limit int64) (patients []*models.VMPatients, total int64, err error) {
48
-	//db := MiddleReadDB()
49
-	db := readDb.Model(&models.VMPatients{}).Where("status=1")
50
-	if orgID > 0 {
51
-		db = db.Where("user_org_id=?", orgID)
52
-	}
53
-	offset := (page - 1) * limit
54
-	err = db.Preload("VMHisPatients", func(db *gorm.DB) *gorm.DB {
55
-		return readMiddleDb.Model(&models.VMHisPatients{}).Where("status = 1 AND user_org_id = ?", orgID)
56
-	}).Preload("Contagions", "status = 1").Group("id").Count(&total).Offset(offset).Limit(limit).Find(&patients).Error
57
-	return
58
-}
59
-
60
-func UpdatePatientsHis(org_id int64, his_user_id string, id int64) (err error) {
61
-	db := MiddleWriteDB()
62
-	err = db.Model(&models.HisPatients{}).Where("user_org_id = ? AND id = ?", org_id, id).Updates(map[string]interface{}{"mtime": time.Now().Unix(), "his_user_id": his_user_id}).Error
63
-	return
64
-}
65
-
66
-func CreatePatientsHis(patient *models.HisPatients) (err error) {
67
-	db := MiddleWriteDB()
68
-	err = db.Save(&patient).Error
69
-	return
70
-}
71
-
72
-func FindVMPatientById(orgID int64, id int64) (patient models.VMPatients, err error) {
73
-	db := XTReadDB()
74
-	err = db.Model(&models.VMPatients{}).Where("id = ? and user_org_id=? and status=1", id, orgID).First(&patient).Error
75
-	return
76
-}
77
-
78
-func FindHisPatientByHisId(orgID int64, his_user_id string) (total int64, err error) {
79
-	db := MiddleReadDB()
80
-	err = db.Model(&models.HisPatients{}).Where("his_user_id = ? and user_org_id=? and status=1", his_user_id, orgID).Count(&total).Error
81
-	return
82
-
83
-}
84
-
85
-func GetAdminUsers(orgID int64, appID int64, page int, limit int) (admins []*models.VMUserAdminRole, total int64, err error) {
86
-	db := readUserDb.Model(&models.VMUserAdminRole{}).Where("status=1")
87
-	if orgID > 0 {
88
-		db = db.Where("org_id = ? AND app_id = ?", orgID, appID)
89
-	}
90
-	offset := (page - 1) * limit
91
-	err = db.Preload("HisUserAdminRole", func(db *gorm.DB) *gorm.DB {
92
-		return readMiddleDb.Model(&models.HisUserAdminRole{}).Where("status = 1 AND org_id = ? AND app_id = ?", orgID, appID)
93
-	}).Preload("VMUserAdmin", "status = 1").Preload("VMUserRole", "status = 1 AND org_id = ? AND app_id = ?", orgID, appID).Count(&total).Offset(offset).Limit(limit).Find(&admins).Error
94
-	return
95
-}
96
-
97
-func UpdateAdminsHis(org_id int64, his_user_id string, id int64) (err error) {
98
-	db := MiddleWriteDB()
99
-	err = db.Model(&models.HisUserAdminRole{}).Where("org_id = ? AND id = ?", org_id, id).Updates(map[string]interface{}{"mtime": time.Now().Unix(), "his_user_id": his_user_id}).Error
100
-	return
101
-}
102
-
103
-func CreateAdminsHis(admin *models.HisUserAdminRole) (err error) {
104
-	db := MiddleWriteDB()
105
-	err = db.Save(&admin).Error
106
-	return
107
-}
108
-
109
-func FindVMAdminRoleById(orgID int64, id int64, app_id int64) (admin models.VMUserAdminRole, err error) {
110
-	db := UserReadDB()
111
-	err = db.Model(&models.VMUserAdminRole{}).Where("admin_user_id = ? and org_id=?  and app_id = ? and status=1", id, orgID, app_id).First(&admin).Error
112
-	return
113
-}
114
-
115
-func FindHisAdminByHisId(orgID int64, his_user_id string, app_id int64) (total int64, err error) {
116
-	db := MiddleReadDB()
117
-	err = db.Model(&models.HisUserAdminRole{}).Where("his_user_id = ? and org_id=? and app_id = ? and status=1", his_user_id, orgID, app_id).Count(&total).Error
118
-	return
119
-
120
-}

+ 0 - 55
models/service/invoice_service.go Просмотреть файл

@@ -1,55 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	"github.com/jinzhu/gorm"
6
-	"strconv"
7
-)
8
-
9
-func GetInvoiceByOrderId(orgId int64, orderID int64) (*models.ServeInvoice, error) {
10
-	var invoice models.ServeInvoice
11
-	orderLike := "%," + strconv.FormatInt(orderID, 10) + ",%"
12
-	err := readUserDb.Model(&models.ServeInvoice{}).Where("org_id=? and orders LIKE ?", orgId, orderLike).First(&invoice).Error
13
-	if err == gorm.ErrRecordNotFound {
14
-		return nil, nil
15
-	}
16
-	if err != nil {
17
-		return nil, err
18
-	}
19
-
20
-	return &invoice, nil
21
-}
22
-
23
-func CreateInvoice(m *models.ServeInvoice) error {
24
-	err := writeUserDb.Create(m).Error
25
-	return err
26
-}
27
-func FindUnInvoiceOrders(orgID int64) (list []*models.ServeOrder, err error) {
28
-	// 这一段是查询出还没有开票的订单
29
-	// SELECT so.* from sgj_users.sgj_serve_order as so WHERE NOT EXISTS
30
-	// (select o.id
31
-	// from sgj_users.sgj_serve_order as o
32
-	// JOIN sgj_users.sgj_serve_invoice as i ON  FIND_IN_SET(o.id, i.orders)
33
-	// WHERE o.org_id=13 and o.order_status=2 and o.status=1 and so.id=o.id )
34
-
35
-	err = readUserDb.Table("sgj_serve_order as so").Where("so.org_id=? and so.order_status=2 and so.status=1", orgID).Where("NOT EXISTS (?)", readUserDb.Table("sgj_serve_order as o").Joins("JOIN sgj_serve_invoice as i ON FIND_IN_SET(o.id, i.orders)").Where("o.org_id=? and o.order_status=2 and o.status=1 and i.status=1 and so.id=o.id", orgID).Select("o.id").QueryExpr()).Find(&list).Error
36
-	return
37
-
38
-}
39
-
40
-func FindInvoices(orgID int64) (list []*models.ServeInvoice, err error) {
41
-	err = readUserDb.Model(&models.ServeInvoice{}).Where("org_id=? and status=1", orgID).Find(&list).Error
42
-	return
43
-}
44
-func FindServeOrdersByIDs(orgId int64, ids []int64) (hads []*models.ServeOrder, nos []*models.ServeOrder, err error) {
45
-
46
-	err = readUserDb.Table("sgj_serve_order as so").Where("so.id IN (?) and so.org_id=? and so.order_status=2 and so.status=1", ids, orgId).Where("EXISTS (?)", readUserDb.Table("sgj_serve_order as o").Joins("JOIN sgj_serve_invoice as i ON FIND_IN_SET(o.id, i.orders)").Where("so.id IN (?) and o.org_id=? and o.order_status=2 and o.status=1 and i.status=1 and so.id=o.id", ids, orgId).Select("o.id").QueryExpr()).Find(&hads).Error
47
-	if err != nil {
48
-		return
49
-	}
50
-	err = readUserDb.Table("sgj_serve_order as so").Where("so.id  IN (?) and so.org_id=? and so.order_status=2 and so.status=1", ids, orgId).Where("NOT EXISTS (?)", readUserDb.Table("sgj_serve_order as o").Joins("JOIN sgj_serve_invoice as i ON FIND_IN_SET(o.id, i.orders)").Where("so.id IN (?) and o.org_id=? and o.order_status=2 and o.status=1 and i.status=1 and so.id=o.id", ids, orgId).Select("o.id").QueryExpr()).Find(&nos).Error
51
-	if err != nil {
52
-		return
53
-	}
54
-	return
55
-}

+ 0 - 246
models/service/login_service.go Просмотреть файл

@@ -1,246 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	"XT_New/utils"
6
-
7
-	"github.com/jinzhu/gorm"
8
-)
9
-
10
-func IsSuperAdmin(mobile string) bool {
11
-	var count int
12
-	readUserDb.Model(&models.AdminUser{}).Where("mobile = ? AND is_super_admin = 1 AND status = 1", mobile).Count(&count)
13
-	return count == 1
14
-}
15
-
16
-func GetValidAdminUserByMobileReturnErr(mobile string) (*models.AdminUser, error) {
17
-	var user models.AdminUser
18
-	err := readUserDb.Where("mobile = ? AND status = 1", mobile).First(&user).Error
19
-	if err != nil {
20
-		if err == gorm.ErrRecordNotFound {
21
-			return nil, nil
22
-		} else {
23
-			return nil, err
24
-		}
25
-	}
26
-	return &user, nil
27
-}
28
-
29
-func DidAdminUserCreateOrg(adminUserID int64) (bool, error) {
30
-	var count int
31
-	err := readUserDb.Model(&models.Org{}).Where("creator = ? AND status <> 0", adminUserID).Count(&count).Error
32
-	return count > 0, err
33
-}
34
-
35
-func DidAdminUserOrgCreateApp(adminUserID int, appType int) (bool, error) {
36
-	var count int
37
-	db := readUserDb.Model(&models.OrgApp{}).Where("creator = ? AND status = 1 AND open_status = 1", adminUserID)
38
-	if appType != 0 {
39
-		db = db.Where("app_type = ?", appType)
40
-	}
41
-	err := db.Count(&count).Error
42
-	return count > 0, err
43
-}
44
-
45
-func GetAdminUserLastLoginLog(adminUserID int, appType int) (*models.AdminUserLoginLog, error) {
46
-	var record models.AdminUserLoginLog
47
-	var err error
48
-	if appType > 0 {
49
-		err = readUserDb.Last(&record, "admin_user_id = ? AND operate_type <> 2 AND app_type = ?", adminUserID, appType).Error
50
-	} else {
51
-		err = readUserDb.Last(&record, "admin_user_id = ? AND operate_type <> 2", adminUserID).Error
52
-	}
53
-
54
-	if err == gorm.ErrRecordNotFound {
55
-		return nil, nil
56
-	}
57
-	return &record, err
58
-}
59
-
60
-func GetAdminUserPrioritizedAppType(adminUserID int) (int8, error) {
61
-	rows, err := readUserDb.Raw("SELECT app.app_type FROM sgj_user_org_app AS app, sgj_user_admin_role AS r WHERE r.admin_user_id = ? AND r.app_id = app.id AND app.status = 1 AND app.open_status = 1 AND r.status = 1 ORDER BY app.org_id ASC, app.app_type ASC LIMIT 1;", adminUserID).Rows()
62
-	defer rows.Close()
63
-	if err != nil {
64
-		return 0, err
65
-	} else {
66
-		if rows.Next() {
67
-			var appType int8
68
-			rows.Scan(&appType)
69
-			return appType, nil
70
-		} else {
71
-			return 0, nil
72
-		}
73
-	}
74
-}
75
-
76
-func GetAdminUserAllOrgWithUID(adminUserID int, isSuperAdmin bool) ([]*models.Org, error) {
77
-	if isSuperAdmin {
78
-		var org models.Org
79
-		err := readUserDb.Preload("OrgGallery", "status = 1").Where("creator = ? AND status <> 0", adminUserID).First(&org).Error
80
-		if err != nil {
81
-			return nil, err
82
-		}
83
-		return []*models.Org{&org}, nil
84
-
85
-	} else {
86
-		rows, err := readUserDb.Raw("SELECT org.*, COUNT(DISTINCT org.id) FROM sgj_user_admin_role AS u_r, sgj_user_org AS org WHERE u_r.admin_user_id = ? AND u_r.org_id = org.id AND u_r.status = 1 AND org.status <> 0 GROUP BY org.id ORDER BY org.id;", adminUserID).Rows()
87
-		defer rows.Close()
88
-		if err != nil {
89
-			return nil, err
90
-		} else {
91
-			orgs := make([]*models.Org, 0)
92
-			for rows.Next() {
93
-				var org models.Org
94
-				if scanErr := readUserDb.Preload("OrgGallery", "status = 1").ScanRows(rows, &org); scanErr != nil {
95
-					return nil, scanErr
96
-
97
-				} else {
98
-					orgs = append(orgs, &org)
99
-				}
100
-			}
101
-			return orgs, nil
102
-		}
103
-	}
104
-}
105
-
106
-func GetAdminUserAllOrgApp(adminUserID int, orgID int) ([]*models.OrgApp, error) {
107
-	rows, err := readUserDb.Raw("SELECT app.* from sgj_user_admin_role AS u_r, sgj_user_org_app AS app WHERE u_r.admin_user_id = ? AND u_r.org_id = ? AND u_r.app_id = app.id AND u_r.status = 1 AND app.status = 1 ORDER BY app_type ASC;", adminUserID, orgID).Rows()
108
-	defer rows.Close()
109
-	if err != nil {
110
-		return nil, err
111
-	} else {
112
-		apps := make([]*models.OrgApp, 0)
113
-		for rows.Next() {
114
-			var app models.OrgApp
115
-			if scanErr := readUserDb.ScanRows(rows, &app); scanErr != nil {
116
-				return nil, scanErr
117
-			} else {
118
-				apps = append(apps, &app)
119
-			}
120
-		}
121
-		return apps, nil
122
-	}
123
-}
124
-
125
-func InsertLoginLog(loginLog *models.AdminUserLoginLog) error {
126
-	tx := writeUserDb.Begin()
127
-	if err := tx.Create(loginLog).Error; err != nil {
128
-		tx.Rollback()
129
-		return err
130
-	}
131
-	return tx.Commit().Error
132
-}
133
-
134
-//func GetAppRole(adminUserID int, orgID int, appID int) (*models.App_Role, error) {
135
-//	var appRole models.App_Role
136
-//	err := readUserDb.Where("admin_user_id = ? AND org_id = ? AND app_id = ? AND status = 1", adminUserID, orgID, appID).First(&appRole).Error
137
-//	if err != nil {
138
-//		return nil, err
139
-//	}
140
-//	return &appRole, nil
141
-//}
142
-
143
-// 获取最近被创建的血透系统管理员角色(AppType为3)
144
-func GetLastXTAdminRole(adminUserID int64, appType int) (*models.App_Role, error) {
145
-	var appRole models.App_Role
146
-	// 	select a_r.* from sgj_user_admin_role as a_r
147
-	// join sgj_user_admin as a on a.id = a_r.admin_user_id
148
-	// join sgj_user_org_app as app on app.id = a_r.app_id and app.status = 1 and app.app_type = 3
149
-	// where a_r.status = 1 and a_r.admin_user_id = 380
150
-	err := readUserDb.Table("sgj_user_admin_role").
151
-		Select("sgj_user_admin_role.*").
152
-		Joins("join sgj_user_admin as a on a.id = sgj_user_admin_role.admin_user_id").
153
-		Joins("join sgj_user_org_app as app on app.id = sgj_user_admin_role.app_id and app.status = 1 and app.app_type = ?", appType).
154
-		Where("sgj_user_admin_role.status = 1 and sgj_user_admin_role.admin_user_id = ?", adminUserID).
155
-		Order("sgj_user_admin_role.id desc").
156
-		First(&appRole).
157
-		Error
158
-	if err != nil {
159
-		if err == gorm.ErrRecordNotFound {
160
-			return nil, nil
161
-		} else {
162
-			return nil, err
163
-		}
164
-	}
165
-	return &appRole, nil
166
-}
167
-
168
-func GetOrgById(orgID int64) (*models.Org, error) {
169
-	var org models.Org
170
-	err := readUserDb.Model(&models.Org{}).Where("id = ?", orgID).First(&org).Error
171
-	if err != nil {
172
-		if err == gorm.ErrRecordNotFound {
173
-			return nil, nil
174
-		} else {
175
-			return nil, err
176
-		}
177
-	}
178
-	return &org, nil
179
-}
180
-
181
-func GetAppById(appID int64) (*models.OrgApp, error) {
182
-	var app models.OrgApp
183
-	err := readUserDb.Model(&models.OrgApp{}).Where("id = ?", appID).First(&app).Error
184
-	if err != nil {
185
-		if err == gorm.ErrRecordNotFound {
186
-			return nil, nil
187
-		} else {
188
-			return nil, err
189
-		}
190
-	}
191
-	return &app, nil
192
-}
193
-
194
-func GetOrgServeSubscibe(orgID int64) (*models.ServeSubscibe, error) {
195
-	var model models.ServeSubscibe
196
-	err := readUserDb.Model(&models.ServeSubscibe{}).Where("org_id = ? AND status = 1", orgID).First(&model).Error
197
-	if err != nil {
198
-		if err == gorm.ErrRecordNotFound {
199
-			return nil, nil
200
-		} else {
201
-			return nil, err
202
-		}
203
-	}
204
-	return &model, nil
205
-}
206
-
207
-//
208
-func GetAppRoleById(id int64) (*models.App_Role, error) {
209
-	var model models.App_Role
210
-	err := readUserDb.Model(&models.App_Role{}).Where("id = ? AND status = 1", id).First(&model).Error
211
-	if err != nil {
212
-		if err == gorm.ErrRecordNotFound {
213
-			return nil, nil
214
-		} else {
215
-			return nil, err
216
-		}
217
-	}
218
-	return &model, nil
219
-}
220
-
221
-func IsMobileRegister(mobile string) bool {
222
-	var count int
223
-	err := readUserDb.
224
-		Model(&models.AdminUser{}).
225
-		Where("mobile = ?", mobile).
226
-		Count(&count).
227
-		Error
228
-	if err != nil {
229
-		utils.ErrorLog("判断手机号是否被注册时失败: %v", err)
230
-		return true
231
-	}
232
-	return count > 0
233
-}
234
-
235
-func FindAppRoleById(id int64) (*models.App_Role, error) {
236
-	var model models.App_Role
237
-	err := readUserDb.Model(&models.App_Role{}).Where("id = ? ", id).First(&model).Error
238
-	if err != nil {
239
-		if err == gorm.ErrRecordNotFound {
240
-			return nil, nil
241
-		} else {
242
-			return nil, err
243
-		}
244
-	}
245
-	return &model, nil
246
-}

Разница между файлами не показана из-за своего большого размера
+ 0 - 1238
models/service/manage_service.go


+ 0 - 69
models/service/management_service/management_analyse_service.go Просмотреть файл

@@ -1,69 +0,0 @@
1
-package management_service
2
-
3
-import "XT_New/service"
4
-
5
-type ChartDataStruct struct {
6
-	Date  string `json:"date"`
7
-	Value int64  `json:"value"`
8
-}
9
-
10
-//患者统计
11
-func GetPatientChartData(user_org_id int64, start_time int64, end_time int64, statistics_type int) (datas []*ChartDataStruct, total int64, err error) {
12
-	db := service.XTReadDB()
13
-	switch statistics_type {
14
-	case 1:
15
-		err = db.Raw("select from_unixtime(created_time,'%m-%d') as date, count(distinct id) as value  from xt_patients patient   Where  patient.user_org_id = ? AND patient.created_time >=? AND patient.created_time <=? AND patient.status = 1   AND patient.lapseto = 1  Group by date", user_org_id, start_time, end_time).Scan(&datas).Error
16
-
17
-		break
18
-	case 2:
19
-		//err = db.Raw("select from_unixtime(assessment_date,'%Y-%m-%d') as date, weight_after as value from xt_assessment_after_dislysis  Where status = 1 AND user_org_id = ? AND patient_id = ?  AND assessment_date <= ? AND  assessment_date >= ? ", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error
20
-		err = db.Raw("select from_unixtime(lapseto_time,'%m-%d') as date, count(distinct patient_id) as value  from xt_patient_lapseto lapseto JOIN `xt_patients` patient ON lapseto.`patient_id` = patient.id AND patient.user_org_id = ? Where lapseto.status = 1 AND lapseto.lapseto_type = 2 AND lapseto.lapseto_time >= ? AND lapseto.lapseto_time <= ?   Group by date", user_org_id, start_time, end_time).Scan(&datas).Error
21
-		//err = db.Raw("select from_unixtime(updated_time,'%m-%d') as date, count(distinct id) as value  from xt_patients patient   Where  patient.user_org_id = ? AND patient.updated_time >=? AND patient.updated_time <=? AND patient.status = 1   AND patient.lapseto = 2  Group by date", user_org_id, start_time, end_time).Scan(&datas).Error
22
-
23
-		break
24
-	}
25
-	for _, item := range datas {
26
-		total = total + item.Value
27
-	}
28
-
29
-	if err != nil {
30
-		return nil, 0, err
31
-	}
32
-	return datas, total, nil
33
-}
34
-
35
-type PatientTableStruct struct {
36
-	Date     string `json:"date"`
37
-	Name     string `json:"name"`
38
-	IdCardNo string `json:"id_card_no"`
39
-	Gender   int    `json:"gender"`
40
-}
41
-
42
-func GetPatientTableData(orgID int64, page, limit, start, end int64, statistics_type int) ([]*PatientTableStruct, int64, error) {
43
-	//offset := (page - 1) * limit
44
-	var total int64
45
-	var err error
46
-	var patients []*PatientTableStruct
47
-	readDb := service.XTReadDB()
48
-	if statistics_type == 1 {
49
-		db := readDb.Raw("select from_unixtime(patient.`created_time`,'%Y-%m-%d %H:%m') as date , patient.name as name, patient.`id_card_no` as id_card_no, patient.`gender` as gender  from `xt_patients` patient Where patient.user_org_id = ? AND patient.status = 1 AND patient.lapseto = ?  AND patient.created_time >= ? AND patient.created_time <= ?  ", orgID, statistics_type, start, end)
50
-		err = db.Order("patient.created_time desc").Scan(&patients).Error
51
-
52
-	} else {
53
-
54
-		db := readDb.Raw("select from_unixtime(lapseto.`lapseto_time`,'%Y-%m-%d %H:%m') as date , patient.name as name, patient.`id_card_no` as id_card_no, patient.`gender` as gender  from xt_patient_lapseto lapseto JOIN `xt_patients` patient ON lapseto.`patient_id` = patient.id AND patient.user_org_id = ? Where lapseto.status = 1 AND lapseto.lapseto_type = ? AND lapseto.lapseto_time >= ? AND lapseto.lapseto_time <= ?  ", orgID, statistics_type, start, end)
55
-		//db := readDb.Raw("select from_unixtime(patient.`updated_time`,'%Y-%m-%d %H:%m') as date , patient.name as name, patient.`id_card_no` as id_card_no, patient.`gender` as gender  from `xt_patients` patient Where patient.user_org_id = ? AND patient.status = 1 AND patient.lapseto = ?  AND patient.updated_time >= ? AND patient.updated_time <= ?  ", orgID, statistics_type, start, end)
56
-		err = db.Group("lapseto.`patient_id`").Order("lapseto.lapseto_time desc").Scan(&patients).Error
57
-
58
-	}
59
-
60
-	return patients, total, err
61
-}
62
-
63
-func GetLapsetoPatientTotal(orgID int64, statistics_type int) (Total int64, err error) {
64
-	readDb := service.XTReadDB()
65
-	//err = readDb.Raw("select count(*) as total from xt_patient_lapseto lapseto JOIN `xt_patients` patient ON lapseto.`patient_id` = patient.id AND patient.user_org_id = ? Where lapseto.status = 1 AND lapseto.lapseto_type =?", orgID, statistics_type).Count(&Total).Error
66
-	err = readDb.Raw("select count(*) as total from `xt_patients` patient Where patient.user_org_id = ? AND patient.status = 1 AND patient.lapseto = ?", orgID, statistics_type).Count(&Total).Error
67
-
68
-	return Total, err
69
-}

+ 0 - 103
models/service/management_service/management_models.go Просмотреть файл

@@ -1,103 +0,0 @@
1
-package management_service
2
-
3
-type PatientLapseto struct {
4
-	ID          int64 `gorm:"column:id" json:"id" form:"id"`
5
-	PatientId   int64 `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
6
-	LapsetoType int64 `gorm:"column:lapseto_type" json:"lapseto_type" form:"lapseto_type"`
7
-	LapsetoTime int64 `gorm:"column:lapseto_time" json:"lapseto_time" form:"lapseto_time"`
8
-	Status      int64 `gorm:"column:status" json:"status" form:"status"`
9
-	CreatedTime int64 `gorm:"column:created_time" json:"created_time" form:"created_time"`
10
-	UpdatedTime int64 `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
11
-}
12
-
13
-func (PatientLapseto) TableName() string {
14
-	return "xt_patient_lapseto"
15
-}
16
-
17
-type Patients struct {
18
-	ID                           int64   `gorm:"column:id" json:"id" form:"id"`
19
-	UserOrgId                    int64   `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
20
-	UserId                       int64   `gorm:"column:user_id" json:"user_id" form:"user_id"`
21
-	Avatar                       string  `gorm:"column:avatar" json:"avatar" form:"avatar"`
22
-	PatientType                  int64   `gorm:"column:patient_type" json:"patient_type" form:"patient_type"`
23
-	DialysisNo                   string  `gorm:"column:dialysis_no" json:"dialysis_no" form:"dialysis_no"`
24
-	AdmissionNumber              string  `gorm:"column:admission_number" json:"admission_number" form:"admission_number"`
25
-	Source                       int64   `gorm:"column:source" json:"source" form:"source"`
26
-	Lapseto                      int64   `gorm:"column:lapseto" json:"lapseto" form:"lapseto"`
27
-	PartitionId                  int64   `gorm:"column:partition_id" json:"partition_id" form:"partition_id"`
28
-	BedId                        int64   `gorm:"column:bed_id" json:"bed_id" form:"bed_id"`
29
-	Name                         string  `gorm:"column:name" json:"name" form:"name"`
30
-	Alias                        string  `gorm:"column:alias" json:"alias" form:"alias"`
31
-	Gender                       int64   `gorm:"column:gender" json:"gender" form:"gender"`
32
-	MaritalStatus                int64   `gorm:"column:marital_status" json:"marital_status" form:"marital_status"`
33
-	IdCardNo                     string  `gorm:"column:id_card_no" json:"id_card_no" form:"id_card_no"`
34
-	Birthday                     int64   `gorm:"column:birthday" json:"birthday" form:"birthday"`
35
-	ReimbursementWayId           int64   `gorm:"column:reimbursement_way_id" json:"reimbursement_way_id" form:"reimbursement_way_id"`
36
-	HealthCareType               int64   `gorm:"column:health_care_type" json:"health_care_type" form:"health_care_type"`
37
-	HealthCareNo                 string  `gorm:"column:health_care_no" json:"health_care_no" form:"health_care_no"`
38
-	HealthCareDueDate            int64   `gorm:"column:health_care_due_date" json:"health_care_due_date" form:"health_care_due_date"`
39
-	Height                       int64   `gorm:"column:height" json:"height" form:"height"`
40
-	BloodType                    int64   `gorm:"column:blood_type" json:"blood_type" form:"blood_type"`
41
-	Rh                           int64   `gorm:"column:rh" json:"rh" form:"rh"`
42
-	HealthCareDueAlertDate       int64   `gorm:"column:health_care_due_alert_date" json:"health_care_due_alert_date" form:"health_care_due_alert_date"`
43
-	EducationLevel               int64   `gorm:"column:education_level" json:"education_level" form:"education_level"`
44
-	Profession                   int64   `gorm:"column:profession" json:"profession" form:"profession"`
45
-	Phone                        string  `gorm:"column:phone" json:"phone" form:"phone"`
46
-	HomeTelephone                string  `gorm:"column:home_telephone" json:"home_telephone" form:"home_telephone"`
47
-	RelativePhone                string  `gorm:"column:relative_phone" json:"relative_phone" form:"relative_phone"`
48
-	RelativeRelations            string  `gorm:"column:relative_relations" json:"relative_relations" form:"relative_relations"`
49
-	HomeAddress                  string  `gorm:"column:home_address" json:"home_address" form:"home_address"`
50
-	WorkUnit                     string  `gorm:"column:work_unit" json:"work_unit" form:"work_unit"`
51
-	UnitAddress                  string  `gorm:"column:unit_address" json:"unit_address" form:"unit_address"`
52
-	Children                     int64   `gorm:"column:children" json:"children" form:"children"`
53
-	ReceivingDate                int64   `gorm:"column:receiving_date" json:"receiving_date" form:"receiving_date"`
54
-	IsHospitalFirstDialysis      int64   `gorm:"column:is_hospital_first_dialysis" json:"is_hospital_first_dialysis" form:"is_hospital_first_dialysis"`
55
-	FirstDialysisDate            int64   `gorm:"column:first_dialysis_date" json:"first_dialysis_date" form:"first_dialysis_date"`
56
-	FirstDialysisHospital        string  `gorm:"column:first_dialysis_hospital" json:"first_dialysis_hospital" form:"first_dialysis_hospital"`
57
-	PredialysisCondition         string  `gorm:"column:predialysis_condition" json:"predialysis_condition" form:"predialysis_condition"`
58
-	PreHospitalDialysisFrequency string  `gorm:"column:pre_hospital_dialysis_frequency" json:"pre_hospital_dialysis_frequency" form:"pre_hospital_dialysis_frequency"`
59
-	PreHospitalDialysisTimes     int64   `gorm:"column:pre_hospital_dialysis_times" json:"pre_hospital_dialysis_times" form:"pre_hospital_dialysis_times"`
60
-	HospitalFirstDialysisDate    int64   `gorm:"column:hospital_first_dialysis_date" json:"hospital_first_dialysis_date" form:"hospital_first_dialysis_date"`
61
-	InductionPeriod              int64   `gorm:"column:induction_period" json:"induction_period" form:"induction_period"`
62
-	InitialDialysis              int64   `gorm:"column:initial_dialysis" json:"initial_dialysis" form:"initial_dialysis"`
63
-	TotalDialysis                int64   `gorm:"column:total_dialysis" json:"total_dialysis" form:"total_dialysis"`
64
-	AttendingDoctorId            int64   `gorm:"column:attending_doctor_id" json:"attending_doctor_id" form:"attending_doctor_id"`
65
-	HeadNurseId                  int64   `gorm:"column:head_nurse_id" json:"head_nurse_id" form:"head_nurse_id"`
66
-	Evaluate                     string  `gorm:"column:evaluate" json:"evaluate" form:"evaluate"`
67
-	Diagnose                     string  `gorm:"column:diagnose" json:"diagnose" form:"diagnose"`
68
-	Remark                       string  `gorm:"column:remark" json:"remark" form:"remark"`
69
-	RegistrarsId                 int64   `gorm:"column:registrars_id" json:"registrars_id" form:"registrars_id"`
70
-	Registrars                   string  `gorm:"column:registrars" json:"registrars" form:"registrars"`
71
-	QrCode                       string  `gorm:"column:qr_code" json:"qr_code" form:"qr_code"`
72
-	BindingState                 int64   `gorm:"column:binding_state" json:"binding_state" form:"binding_state"`
73
-	PatientComplains             string  `gorm:"column:patient_complains" json:"patient_complains" form:"patient_complains"`
74
-	PresentHistory               string  `gorm:"column:present_history" json:"present_history" form:"present_history"`
75
-	PastHistory                  string  `gorm:"column:past_history" json:"past_history" form:"past_history"`
76
-	Temperature                  float64 `gorm:"column:temperature" json:"temperature" form:"temperature"`
77
-	Pulse                        int64   `gorm:"column:pulse" json:"pulse" form:"pulse"`
78
-	Respiratory                  int64   `gorm:"column:respiratory" json:"respiratory" form:"respiratory"`
79
-	Sbp                          int64   `gorm:"column:sbp" json:"sbp" form:"sbp"`
80
-	Dbp                          int64   `gorm:"column:dbp" json:"dbp" form:"dbp"`
81
-	Status                       int64   `gorm:"column:status" json:"status" form:"status"`
82
-	CreatedTime                  int64   `gorm:"column:created_time" json:"created_time" form:"created_time"`
83
-	UpdatedTime                  int64   `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
84
-	Nation                       string  `gorm:"column:nation" json:"nation" form:"nation"`
85
-	NativePlace                  string  `gorm:"column:native_place" json:"native_place" form:"native_place"`
86
-	Age                          int64   `gorm:"column:age" json:"age" form:"age"`
87
-	InfectiousNextRecordTime     int64   `gorm:"column:infectious_next_record_time" json:"infectious_next_record_time" form:"infectious_next_record_time"`
88
-	IsInfectious                 int64   `gorm:"column:is_infectious" json:"is_infectious" form:"is_infectious"`
89
-	IsOpenRemind                 int64   `gorm:"column:is_open_remind" json:"is_open_remind" form:"is_open_remind"`
90
-	RemindCycle                  int64   `gorm:"column:remind_cycle" json:"remind_cycle" form:"remind_cycle"`
91
-	ResponseResult               string  `gorm:"column:response_result" json:"response_result" form:"response_result"`
92
-	FirstTreatmentDate           int64   `gorm:"column:first_treatment_date" json:"first_treatment_date" form:"first_treatment_date"`
93
-	DialysisAge                  int64   `gorm:"column:dialysis_age" json:"dialysis_age" form:"dialysis_age"`
94
-	ExpenseKind                  int64   `gorm:"column:expense_kind" json:"expense_kind" form:"expense_kind"`
95
-	TellPhone                    string  `gorm:"column:tell_phone" json:"tell_phone" form:"tell_phone"`
96
-	ContactName                  string  `gorm:"column:contact_name" json:"contact_name" form:"contact_name"`
97
-	UserSysBeforeCount           int64   `gorm:"column:user_sys_before_count" json:"user_sys_before_count" form:"user_sys_before_count"`
98
-	IsExcelExport                int64   `gorm:"column:is_excel_export" json:"is_excel_export" form:"is_excel_export"`
99
-}
100
-
101
-func (Patients) TableName() string {
102
-	return "xt_patients"
103
-}

Разница между файлами не показана из-за своего большого размера
+ 0 - 1672
models/service/mobile_dialysis_service.go


+ 0 - 144
models/service/new_sms_service.go Просмотреть файл

@@ -1,144 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"bytes"
5
-	"encoding/base64"
6
-	"encoding/json"
7
-	"io/ioutil"
8
-	"math/rand"
9
-	"net/http"
10
-	"strconv"
11
-	"strings"
12
-	"time"
13
-
14
-	"XT_New/utils"
15
-
16
-	"github.com/astaxie/beego"
17
-)
18
-
19
-type NewSMSServiceError struct {
20
-	Err string
21
-}
22
-
23
-func (e *NewSMSServiceError) Error() string {
24
-	return e.Err
25
-}
26
-
27
-// 有如下两个外部可调用的接口:SendSMSUseTemplate、SendSMSWithCustomContent两个函数
28
-// 但是实际上我打算将 SendSMSUseTemplate 作为底层函数使用,不直接提供外界:
29
-// 这需要提供数个默认模板,通过为这几个模板创建独立便利函数,封装 SendSMSUseTemplate 的参数 defaultTemplateID 和 params
30
-
31
-// 发送验证码短信
32
-// 参数 aespass 是加密后的地址信息,用于限制频繁调用
33
-func SendVerificationCodeSMS(mobile string, aespass string) error {
34
-	if len(mobile) == 0 {
35
-		return &SMSServiceError{Err: "手机号为空"}
36
-	}
37
-	if err := newCheckVerificationCodeSMSLimit(aespass, mobile); err != nil {
38
-		return err
39
-	}
40
-
41
-	var code_str string
42
-	for i := 0; i < 6; i++ {
43
-		rand.Seed(time.Now().UnixNano())
44
-		code_str += strconv.Itoa(rand.Intn(10))
45
-	}
46
-	templateID, _ := beego.AppConfig.Int("sms_verification_code_templateid")
47
-	utils.TraceLog("验证码为%v", code_str)
48
-	_, _, err := batchSendMessage(templateID, []string{code_str}, []string{mobile})
49
-	if err == nil {
50
-		redisClient := RedisClient()
51
-		defer redisClient.Close()
52
-		cur_date := time.Now().Format("2006-01-02")
53
-		redisClient.Set("code_msg_"+mobile, code_str, time.Minute*10)
54
-		redisClient.Incr("code_msg_" + mobile + "_" + cur_date).Result()
55
-		// 取出地址信息,因为上面已经验证过,这里就直接解密而不做错误判断了
56
-		bytesPass, _ := base64.StdEncoding.DecodeString(aespass)
57
-		tpass := utils.AESDecrypt(bytesPass)
58
-		redisClient.Incr("ip:host_" + cur_date + "_" + tpass).Result()
59
-	}
60
-	return err
61
-}
62
-
63
-func newCheckVerificationCodeSMSLimit(aespass string, mobile string) error {
64
-	redisClient := RedisClient()
65
-	defer redisClient.Close()
66
-	bytesPass, err := base64.StdEncoding.DecodeString(aespass)
67
-	if err != nil {
68
-		return &SMSServiceError{Err: "缺少关键参数"}
69
-	}
70
-	tpass := utils.AESDecrypt(bytesPass)
71
-	if len(tpass) == 0 {
72
-		return &SMSServiceError{Err: "缺少关键参数"}
73
-	}
74
-
75
-	cur_date := time.Now().Format("2006-01-02")
76
-	add_redis, err := redisClient.Get("ip:host_" + cur_date + "_" + tpass).Result()
77
-	if err != nil {
78
-		return &SMSServiceError{Err: "缺少关键参数"}
79
-	}
80
-	ip_max_send_count, _ := beego.AppConfig.Int("ip_max_send_count")
81
-	if add_count, _ := strconv.Atoi(add_redis); add_count >= ip_max_send_count {
82
-		return &SMSServiceError{Err: "当前IP发送短信超过限制"}
83
-	}
84
-
85
-	moblie_count, _ := redisClient.Get("code_msg_" + mobile + "_" + cur_date).Result()
86
-	moblie_count_int, _ := strconv.Atoi(moblie_count)
87
-	if moblie_max, _ := beego.AppConfig.Int("moblie_max_send_count"); moblie_count_int >= moblie_max {
88
-		return &SMSServiceError{Err: "当前手机号发送短信超过限制"}
89
-	}
90
-
91
-	return nil
92
-}
93
-
94
-// 指定模板群发短信
95
-// 返回值为发送了 n 条短信、短信平台返回的 report 数组[{"code":"0", "msg":"OK", "smsid":"f96f79240e372587e9284cd580d8f953", "mobile":"18011984299", "count":"1"}]
96
-func batchSendMessage(templateID int, params []string, mobiles []string) (int, []interface{}, error) {
97
-	sms_api := beego.AppConfig.String("sms_baseUrl") + "sendsms"
98
-	mobileStr := strings.Join(mobiles, ",")
99
-	appID, sid, token := getSMSConfig()
100
-	requestParams := make(map[string]interface{})
101
-	requestParams["appid"] = appID
102
-	requestParams["sid"] = sid
103
-	requestParams["token"] = token
104
-	requestParams["templateid"] = strconv.Itoa(templateID)
105
-	requestParams["mobile"] = mobileStr
106
-	if params != nil && len(params) != 0 {
107
-		paramStr := strings.Join(params, ",")
108
-		requestParams["param"] = paramStr
109
-	}
110
-
111
-	paramsBytes, _ := json.Marshal(requestParams)
112
-	resp, requestErr := http.Post(sms_api, "application/json", bytes.NewBuffer(paramsBytes))
113
-
114
-	if requestErr != nil {
115
-		utils.ErrorLog("短信平台模板群发接口调用失败: %v", requestErr)
116
-		return 0, nil, requestErr
117
-	}
118
-	defer resp.Body.Close()
119
-	body, ioErr := ioutil.ReadAll(resp.Body)
120
-	if ioErr != nil {
121
-		utils.ErrorLog("短信平台模板群发接口返回数据读取失败: %v", ioErr)
122
-		return 0, nil, ioErr
123
-	}
124
-	var respJSON map[string]interface{}
125
-	utils.InfoLog(string(body))
126
-	if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
127
-		utils.ErrorLog("短信平台模板群发接口返回数据解析JSON失败: %v", err)
128
-		return 0, nil, err
129
-	}
130
-	if respJSON["code"].(string) != "000000" {
131
-		msg := respJSON["msg"].(string)
132
-		utils.ErrorLog("短信平台模板群发接口请求失败: %v", msg)
133
-		return 0, nil, &SMSServiceError{"短信平台模板群发接口请求失败"}
134
-
135
-	} else {
136
-		utils.SuccessLog("短信发送成功 report: %v", respJSON["report"])
137
-		if len(mobiles) > 1 {
138
-			count, _ := strconv.Atoi(respJSON["count_sum"].(string))
139
-			return count, respJSON["report"].([]interface{}), nil
140
-		} else {
141
-			return 1, nil, nil
142
-		}
143
-	}
144
-}

+ 0 - 202
models/service/orginfo_service.go Просмотреть файл

@@ -1,202 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	"fmt"
6
-	"github.com/jinzhu/gorm"
7
-	"strconv"
8
-	"time"
9
-)
10
-
11
-func GetOrgTypes() (ots []*models.OrgType, err error) {
12
-	err = readUserDb.Model(&models.OrgType{}).Where("status=1").Order("sort_no").Find(&ots).Error
13
-	return
14
-}
15
-
16
-func UpdateOrgInfo(org *models.Org) (err error) {
17
-	err = writeUserDb.Model(&models.Org{}).Where("id=?", org.Id).Update(org).Error
18
-	return
19
-}
20
-
21
-func GetIllnessList() (ills []*models.Illness, err error) {
22
-	err = readUserDb.Where("status=1").Find(&ills).Error
23
-	return
24
-}
25
-
26
-func CreateOrgGalleryItem(item *models.OrgGallery) (err error) {
27
-	err = writeUserDb.Create(item).Error
28
-	return
29
-}
30
-
31
-func DeleteOrgGalleryItem(id int64) (err error) {
32
-	err = writeUserDb.Model(&models.OrgGallery{}).Where("id=?", id).Update(map[string]interface{}{"Status": 0, "Mtime": time.Now().Unix()}).Error
33
-	return
34
-}
35
-
36
-func CreateOrg(org *models.Org, name string, openXT bool, openCDM bool, openSCRM bool, openMall bool) error {
37
-	now := time.Now()
38
-	tx_admin := writeUserDb.Begin()
39
-	if err := tx_admin.Create(org).Error; err != nil {
40
-		tx_admin.Rollback()
41
-		return err
42
-	}
43
-	role := models.Role{
44
-		RoleName:     "超级管理员",
45
-		RoleIntro:    "",
46
-		Creator:      org.Creator,
47
-		OrgId:        org.Id,
48
-		AppId:        0,
49
-		IsSuperAdmin: true,
50
-		Status:       1,
51
-		CreateTime:   now.Unix(),
52
-		ModifyTime:   now.Unix(),
53
-	}
54
-	if err := tx_admin.Create(&role).Error; err != nil {
55
-		tx_admin.Rollback()
56
-		return err
57
-	}
58
-
59
-	// app 的创建顺序也决定了登录后前往 app 的优先级
60
-	if err := createOrgApp(tx_admin, &role, name, 3, openXT); err != nil {
61
-		tx_admin.Rollback()
62
-		return err
63
-	}
64
-
65
-	nextMonthDate := now.AddDate(0, 0, 30)
66
-	subscibe := models.ServeSubscibe{
67
-		OrgId:       int64(org.Id),
68
-		PeriodStart: now.Unix(),
69
-		PeriodEnd:   nextMonthDate.Unix(),
70
-		Status:      1,
71
-		CreatedTime: now.Unix(),
72
-		UpdatedTime: now.Unix(),
73
-		State:       9,
74
-	}
75
-	if err := tx_admin.Create(&subscibe).Error; err != nil {
76
-		tx_admin.Rollback()
77
-		return err
78
-	}
79
-
80
-	tx_patient := writeSgjPatientDb.Begin()
81
-	if err := tx_patient.Exec("INSERT INTO sgj_patient_articles_menu (name, status, type, user_org_id, ctime, mtime) VALUES(?, ?, ?, ?, ?, ?);", "科普教育", 1, 1, org.Id, now.Unix(), now.Unix()).Error; err != nil {
82
-		tx_patient.Rollback()
83
-		tx_admin.Rollback()
84
-		return err
85
-	}
86
-	if err := tx_patient.Exec("INSERT INTO sgj_patient_good_category (user_org_id, category_name, status, created_time, updated_time) VALUES(?, ?, ?, ?, ?);", org.Id, "普通商品", 1, now.Unix(), now.Unix()).Error; err != nil {
87
-		tx_patient.Rollback()
88
-		tx_admin.Rollback()
89
-		return err
90
-	}
91
-
92
-	if err := tx_admin.Exec("INSERT INTO sgj_user_membership_card (user_org_id, card_name, card_level, upgrade_integral, card_right, use_notice, background_type, background, service_phone, status, created_time, updated_time) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", org.Id, "普通会员", 0, 0, "", "", 1, "#CACA41", "", 1, now.Unix(), now.Unix()).Error; err != nil {
93
-		tx_admin.Rollback()
94
-		tx_patient.Rollback()
95
-		return err
96
-	}
97
-
98
-	tx_admin.Commit()
99
-	tx_patient.Commit()
100
-	return nil
101
-}
102
-
103
-func createOrgApp(tx *gorm.DB, superAdminRole *models.Role, userName string, appType int, open bool) error {
104
-
105
-	//创建应用
106
-	now := time.Now().Unix()
107
-	var app_id int64
108
-	apps, _ := FindSystemOrgApp()
109
-	for _, item := range apps {
110
-		app := &VMOrgApp{
111
-			AppType:    item.AppType,
112
-			Creator:    int(superAdminRole.Creator),
113
-			OrgId:      int(superAdminRole.OrgId),
114
-			OpenStatus: item.OpenStatus,
115
-			Status:     1,
116
-			CreateTime: now,
117
-			ModifyTime: now,
118
-			Name:       item.Name,
119
-			Url:        item.Url,
120
-			Number:     item.Number,
121
-			Pid:        0,
122
-		}
123
-		writeUserDb.Create(&app)
124
-		if app.AppType == 3 {
125
-			app_id = app.ID
126
-
127
-		}
128
-		fmt.Println(item.VMOrgApp)
129
-
130
-		for _, subItem := range item.VMOrgApp {
131
-			app := &VMOrgApp{
132
-				AppType:    subItem.AppType,
133
-				Creator:    int(superAdminRole.Creator),
134
-				OrgId:      int(superAdminRole.OrgId),
135
-				OpenStatus: subItem.OpenStatus,
136
-				Status:     1,
137
-				CreateTime: now,
138
-				ModifyTime: now,
139
-				Name:       subItem.Name,
140
-				Url:        subItem.Url,
141
-				Number:     subItem.Number,
142
-				Pid:        app.ID,
143
-			}
144
-			writeUserDb.Create(&app)
145
-		}
146
-	}
147
-
148
-	//string := strconv.FormatInt(int64,10        /)
149
-	app_role := models.App_Role{
150
-		AdminUserId: superAdminRole.Creator,
151
-		OrgId:       superAdminRole.OrgId,
152
-		AppId:       app_id,
153
-		RoleId:      superAdminRole.Id,
154
-		RoleIds:     strconv.FormatInt(superAdminRole.Id, 10),
155
-		Avatar:      "",
156
-		UserName:    userName,
157
-		Intro:       "",
158
-		UserType:    1,
159
-		UserTitle:   0,
160
-		Status:      1,
161
-		CreateTime:  now,
162
-		ModifyTime:  now,
163
-	}
164
-	if createApp_RoleErr := tx.Create(&app_role).Error; createApp_RoleErr != nil {
165
-		return createApp_RoleErr
166
-	}
167
-	return nil
168
-}
169
-
170
-func GetOrgTypeByName(org_type_name string) (org_type models.OrgType) {
171
-	readUserDb.Model(&models.OrgType{}).Where("status = 1 AND name = ?", org_type_name).First(&org_type)
172
-	return
173
-}
174
-
175
-type VMOrgApp struct {
176
-	ID         int64       `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id"` // ID
177
-	AppType    int         `gorm:"column:app_type" json:"app_type"`
178
-	Creator    int         `json:"creator"` // 创建者,即管理员用户的 id
179
-	OrgId      int         `gorm:"column:org_id" json:"org_id"`
180
-	OpenStatus int         `gorm:"column:open_status" json:"open_status"`
181
-	Status     int8        `json:"status"`                    // 状态 0.无效 1.有效 2.禁用
182
-	CreateTime int64       `gorm:"column:ctime" json:"ctime"` // 创建时间
183
-	ModifyTime int64       `gorm:"column:mtime" json:"mtime"` // 修改时间
184
-	Name       string      `gorm:"column:name" json:"name" form:"name"`
185
-	Url        string      `gorm:"column:url" json:"url" form:"url"`
186
-	Pid        int64       `gorm:"column:pid" json:"pid" form:"pid"`
187
-	Number     int64       `gorm:"column:number" json:"order" form:"number"`
188
-	VMOrgApp   []*VMOrgApp `gorm:"ForeignKey:Pid;AssociationForeignKey:Id" `
189
-}
190
-
191
-func (VMOrgApp) TableName() string {
192
-	return "sgj_user_org_app"
193
-}
194
-
195
-func FindSystemOrgApp() (app []*VMOrgApp, err error) {
196
-	err = readUserDb.Model(&VMOrgApp{}).Preload("VMOrgApp", "org_id = 0 AND status =1 AND pid > 0").Where("status = 1 AND org_id = 0 AND pid = 0").Find(&app).Error
197
-	return
198
-}
199
-
200
-func GetAllOrgByAdminUserId() {
201
-
202
-}

+ 0 - 64
models/service/patient_dataconfig_service.go Просмотреть файл

@@ -1,64 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	"time"
6
-
7
-	"github.com/jinzhu/gorm"
8
-)
9
-
10
-func GetPatientByID(orgID int64, patientID int64) (*models.Patients, error) {
11
-	var patient models.Patients
12
-	err := readDb.Model(&models.Patients{}).Where("id = ? and user_org_id=? and status=1", patientID, orgID).First(&patient).Error
13
-	if err != nil {
14
-		if err == gorm.ErrRecordNotFound {
15
-			return nil, nil
16
-		} else {
17
-			return nil, err
18
-		}
19
-	}
20
-	return &patient, nil
21
-}
22
-
23
-func GetPatientCourseOfDisease(orgID int64, patientID int64, startTime int64, endTime int64) ([]*models.PatientDiseaseCourse, error) {
24
-	var records []*models.PatientDiseaseCourse
25
-	err := readDb.Model(&models.PatientDiseaseCourse{}).Where("org_id = ? and patient_id = ? and record_time >= ? and record_time <= ? and status = 1", orgID, patientID, startTime, endTime).Order("record_time desc").Find(&records).Error
26
-	if err != nil {
27
-		return nil, err
28
-	}
29
-	return records, nil
30
-}
31
-
32
-func CreatePatientCourseOfDisease(record *models.PatientDiseaseCourse) error {
33
-	err := writeDb.Model(&models.PatientDiseaseCourse{}).Create(record).Error
34
-	return err
35
-}
36
-
37
-func GetPatientRescueRecords(orgID int64, patientID int64, startTime int64, endTime int64) ([]*models.PatientRescueRecord, error) {
38
-	var records []*models.PatientRescueRecord
39
-	err := readDb.Model(&models.PatientRescueRecord{}).Where("org_id = ? and patient_id = ? and record_time >= ? and record_time <= ? and status = 1", orgID, patientID, startTime, endTime).Order("record_time desc").Find(&records).Error
40
-	if err != nil {
41
-		return nil, err
42
-	}
43
-	return records, nil
44
-}
45
-
46
-func CreatePatientRescueRecord(record *models.PatientRescueRecord) error {
47
-	err := writeDb.Model(&models.PatientRescueRecord{}).Create(record).Error
48
-	return err
49
-}
50
-
51
-func ModifyPatientCourses(record *models.PatientDiseaseCourse) error {
52
-	err := writeDb.Model(&models.PatientDiseaseCourse{}).Where("org_id = ? and patient_id = ? and status = 1 and id = ?", record.OrgID, record.PatientID, record.ID).Updates(map[string]interface{}{"content": record.Content, "record_time": record.RecordTime, "mtime": time.Now().Unix(), "title": record.Title}).Error
53
-	return err
54
-}
55
-
56
-func DeletePatientCoursesInBatch(orgID int64, patientID int64, recordIDs []int64) error {
57
-	err := writeDb.Model(&models.PatientDiseaseCourse{}).Where("org_id = ? and patient_id = ? and id in (?) and status = 1", orgID, patientID, recordIDs).Updates(map[string]interface{}{"status": 2, "mtime": time.Now().Unix()}).Error
58
-	return err
59
-}
60
-
61
-func DeletePatientResuceRecordsInBatch(orgID int64, patientID int64, recordIDs []int64) error {
62
-	err := writeDb.Model(&models.PatientRescueRecord{}).Where("org_id = ? and patient_id = ? and id in (?) and status = 1", orgID, patientID, recordIDs).Updates(map[string]interface{}{"status": 2, "mtime": time.Now().Unix()}).Error
63
-	return err
64
-}

+ 0 - 523
models/service/patient_schedule_template_service.go Просмотреть файл

@@ -1,523 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"fmt"
5
-	"strings"
6
-	"time"
7
-
8
-	"XT_New/models"
9
-	"XT_New/utils"
10
-
11
-	"github.com/jinzhu/gorm"
12
-)
13
-
14
-func GetOrgPatientScheduleTemplateMode(orgID int64) (*models.PatientScheduleTemplateMode, error) {
15
-	var mode models.PatientScheduleTemplateMode
16
-	err := readDb.Model(&models.PatientScheduleTemplateMode{}).Where("org_id = ? AND status = 1", orgID).First(&mode).Error
17
-	if err != nil {
18
-		if err == gorm.ErrRecordNotFound {
19
-			return nil, nil
20
-		} else {
21
-			return nil, err
22
-		}
23
-	}
24
-	return &mode, nil
25
-}
26
-
27
-// 获取至多两个模板ID
28
-func GetOrgPatientScheduleTemplateIDs(orgID int64) ([]*models.PatientScheduleTemplateId, error) {
29
-	var ids []*models.PatientScheduleTemplateId
30
-	err := readDb.Model(&models.PatientScheduleTemplateId{}).Where("org_id = ? AND status = 1", orgID).Limit(2).Find(&ids).Error
31
-	if err != nil {
32
-		return nil, err
33
-	}
34
-	return ids, nil
35
-}
36
-
37
-func GetOrgPatientScheduleTemplateIDByTemplateID(orgID int64, templateID int64) (*models.PatientScheduleTemplateId, error) {
38
-	var id models.PatientScheduleTemplateId
39
-	err := readDb.Model(&models.PatientScheduleTemplateId{}).Where("org_id = ? AND id = ? AND status = 1", orgID, templateID).First(&id).Error
40
-	if err != nil {
41
-		if err == gorm.ErrRecordNotFound {
42
-			return nil, nil
43
-		} else {
44
-			return nil, err
45
-		}
46
-	}
47
-	return &id, nil
48
-}
49
-
50
-type PatientScheduleTemplateItemViewModel struct {
51
-	models.PatientScheduleTemplateItem
52
-
53
-	Patient *models.Patients `gorm:"ForeignKey:PatientID" json:"patient"`
54
-}
55
-
56
-type PatientScheduleTemplateViewModel struct {
57
-	// ID    int64 `gorm:"column:id" json:"id" form:"id"`
58
-	// OrgID int64 `gorm:"column:org_id" json:"-" form:"org_id"`
59
-	models.PatientScheduleTemplateId
60
-
61
-	Items []*PatientScheduleTemplateItemViewModel `gorm:"ForeignKey:TemplateID" json:"items"`
62
-}
63
-
64
-func (PatientScheduleTemplateViewModel) TableName() string {
65
-	return "xt_patient_schedule_template_id"
66
-}
67
-
68
-// 获取至多两个模板ID及其对应的模板排班列表
69
-func GetOrgPatientScheduleTemplateItems(orgID int64) ([]*PatientScheduleTemplateViewModel, error) {
70
-	var vms []*PatientScheduleTemplateViewModel
71
-	err := readDb.
72
-		Model(&PatientScheduleTemplateViewModel{}).
73
-		Preload("Items", "org_id = ? AND status = 1", orgID).
74
-		Preload("Items.Patient", "user_org_id = ? AND status = 1", orgID).
75
-		Where("org_id = ? AND status = 1", orgID).
76
-		Limit(2).
77
-		Find(&vms).
78
-		Error
79
-	if err != nil {
80
-		return nil, err
81
-	}
82
-	return vms, nil
83
-}
84
-
85
-// 获取指定模板ID的模板排班列表
86
-func GetOrgPatientScheduleTemplateItemsByTemplateID(orgID int64, templateID int64) ([]*PatientScheduleTemplateItemViewModel, error) {
87
-	var vms []*PatientScheduleTemplateItemViewModel
88
-	err := readDb.
89
-		Model(&PatientScheduleTemplateItemViewModel{}).
90
-		Preload("Patient", "user_org_id = ? AND status = 1", orgID).
91
-		Where("org_id = ? AND template_id = ? AND status = 1", orgID, templateID).
92
-		Find(&vms).
93
-		Error
94
-	if err != nil {
95
-		return nil, err
96
-	}
97
-	return vms, nil
98
-}
99
-
100
-func GetOrgPatientScheduleTemplateItemsWithoutPatientByTemplateID(orgID int64, templateID int64) ([]*models.PatientScheduleTemplateItem, error) {
101
-	var items []*models.PatientScheduleTemplateItem
102
-	err := readDb.Raw("select item.id,item.org_id,item.template_id,item.device_number_id,item.patient_id,item.treat_mode,item.weekday,item.time_type,item.status,item.status,item.ctime,item.mtime from xt_patient_schedule_template_item as item left join xt_patients as patient on item.patient_id = patient.id where item.org_id = ? AND item.template_id = ? AND item.status = 1 and patient.lapseto = 1 and patient.status = 1", orgID, templateID).Scan(&items).Error
103
-	// err := readDb.
104
-	// 	Model(&models.PatientScheduleTemplateItem{}).
105
-	// 	Where("org_id = ? AND template_id = ? AND status = 1", orgID, templateID).
106
-	// 	Find(&items).
107
-	// 	Error
108
-	if err != nil {
109
-		return nil, err
110
-	}
111
-	return items, nil
112
-}
113
-
114
-type ScheduleDeviceNumberViewModel struct {
115
-	models.DeviceNumber
116
-
117
-	Zone *models.DeviceZone `gorm:"ForeignKey:ZoneID" json:"zone"`
118
-}
119
-
120
-func GetScheduleValidDeviceNumbers(orgID int64) ([]*ScheduleDeviceNumberViewModel, error) {
121
-	var vms []*ScheduleDeviceNumberViewModel
122
-	err := readDb.Model(&ScheduleDeviceNumberViewModel{}).Preload("Zone", "status = 1").Where("org_id = ? AND status = 1", orgID).Order("zone_id asc").Order("id asc").Find(&vms).Error
123
-	if err != nil {
124
-		return nil, err
125
-	}
126
-	return vms, nil
127
-}
128
-
129
-// 创建两个默认模板
130
-func CreateTwoPatientScheduleTemplates(orgID int64) (*PatientScheduleTemplateViewModel, *PatientScheduleTemplateViewModel, error) {
131
-	now := time.Now().Unix()
132
-	firstTemp := models.PatientScheduleTemplateId{}
133
-	firstTemp.OrgID = orgID
134
-	firstTemp.Status = 1
135
-	firstTemp.CreateTime = now
136
-	firstTemp.ModifyTime = now
137
-
138
-	secondTemp := models.PatientScheduleTemplateId{}
139
-	secondTemp.OrgID = orgID
140
-	secondTemp.Status = 1
141
-	secondTemp.CreateTime = now
142
-	secondTemp.ModifyTime = now
143
-
144
-	tx := writeDb.Begin()
145
-	if err := tx.Model(&models.PatientScheduleTemplateId{}).Create(&firstTemp).Error; err != nil {
146
-		tx.Rollback()
147
-		return nil, nil, err
148
-	}
149
-	if err := tx.Model(&models.PatientScheduleTemplateId{}).Create(&secondTemp).Error; err != nil {
150
-		tx.Rollback()
151
-		return nil, nil, err
152
-	}
153
-
154
-	vm1 := PatientScheduleTemplateViewModel{}
155
-	vm1.ID = firstTemp.ID
156
-	vm1.Items = make([]*PatientScheduleTemplateItemViewModel, 0, 0)
157
-
158
-	vm2 := PatientScheduleTemplateViewModel{}
159
-	vm2.ID = secondTemp.ID
160
-	vm2.Items = make([]*PatientScheduleTemplateItemViewModel, 0, 0)
161
-	tx.Commit()
162
-	return &vm1, &vm2, nil
163
-}
164
-
165
-func CreatePatientScheduleTemplate(orgID int64) (*PatientScheduleTemplateViewModel, error) {
166
-	now := time.Now().Unix()
167
-	temp := models.PatientScheduleTemplateId{}
168
-	temp.OrgID = orgID
169
-	temp.Status = 1
170
-	temp.CreateTime = now
171
-	temp.ModifyTime = now
172
-	tx := writeDb.Begin()
173
-	if err := tx.Model(&models.PatientScheduleTemplateId{}).Create(&temp).Error; err != nil {
174
-		tx.Rollback()
175
-		return nil, err
176
-	}
177
-	vm := PatientScheduleTemplateViewModel{}
178
-	vm.ID = temp.ID
179
-	vm.Items = make([]*PatientScheduleTemplateItemViewModel, 0, 0)
180
-	tx.Commit()
181
-	return &vm, nil
182
-}
183
-
184
-type PatientScheduleTemplatePatientVM struct {
185
-	ID   int64  `gorm:"column:id" json:"id" form:"id"`
186
-	Name string `gorm:"column:name" json:"name" form:"name"`
187
-
188
-	Contagions []*PatientScheduleContagion `gorm:"ForeignKey:PatientID" json:"contagions"`
189
-}
190
-
191
-func (PatientScheduleTemplatePatientVM) TableName() string {
192
-	return "xt_patients"
193
-}
194
-
195
-type PatientScheduleContagion struct {
196
-	ID        int64 `gorm:"column:id" json:"id" form:"id"`
197
-	PatientID int64 `gorm:"column:patient_id" json:"-"`
198
-	DiseaseID int64 `gorm:"column:disease_id" json:"disease_id" form:"disease_id"`
199
-}
200
-
201
-func (PatientScheduleContagion) TableName() string {
202
-	return "xt_patients_infectious_diseases"
203
-}
204
-
205
-func PatientScheduleTemplateGetAllValidPatient(orgID int64) ([]*PatientScheduleTemplatePatientVM, error) {
206
-	var vms []*PatientScheduleTemplatePatientVM
207
-	err := readDb.
208
-		Model(&PatientScheduleTemplatePatientVM{}).
209
-		Preload("Contagions", "status = 1").
210
-		Where("user_org_id = ? and lapseto=1 AND status = 1", orgID).
211
-		Find(&vms).
212
-		Error
213
-	if err != nil {
214
-		return nil, err
215
-	}
216
-	return vms, nil
217
-}
218
-
219
-func UpdateScheduleTemplate(orgID int64, templateID int64,
220
-	addTemplateItems []*models.PatientScheduleTemplateItem,
221
-	delTemplateItems []*models.PatientScheduleTemplateItem,
222
-	changeTemplateItems []*models.PatientScheduleTemplateItem,
223
-	shouldUpdateNextWeekSchedules bool,
224
-	shouldUpdateNextSecondWeekSchedules bool) error {
225
-
226
-	now := time.Now()
227
-	tx := writeDb.Begin()
228
-
229
-	// 批量插入 add template item
230
-	if len(addTemplateItems) > 0 {
231
-		// utils.TraceLog("addTemplateItems len: %v", len(addTemplateItems))
232
-		valueStrs := make([]string, 0, len(addTemplateItems))
233
-		values := make([]interface{}, 0, len(addTemplateItems)*10)
234
-		for _, item := range addTemplateItems {
235
-			valueStrs = append(valueStrs, "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
236
-			values = append(values, orgID)
237
-			values = append(values, templateID)
238
-			values = append(values, item.DeviceNumberID)
239
-			values = append(values, item.PatientID)
240
-			values = append(values, item.TreatMode)
241
-			values = append(values, item.Weekday)
242
-			values = append(values, item.TimeType)
243
-			values = append(values, 1)
244
-			values = append(values, now.Unix())
245
-			values = append(values, now.Unix())
246
-		}
247
-
248
-		sql := fmt.Sprintf("INSERT INTO xt_patient_schedule_template_item (org_id, template_id, device_number_id, patient_id, treat_mode, weekday, time_type, status, ctime, mtime) VALUES %v;", strings.Join(valueStrs, ", "))
249
-		if insertErr := tx.Exec(sql, values...).Error; insertErr != nil {
250
-			tx.Rollback()
251
-			return insertErr
252
-		}
253
-	}
254
-
255
-	// 批量假删除 del template item
256
-	if len(delTemplateItems) > 0 {
257
-		// utils.TraceLog("delTemplateItems len: %v", len(delTemplateItems))
258
-		ins := make([]string, 0, len(delTemplateItems))
259
-		for _, item := range delTemplateItems {
260
-			ins = append(ins, fmt.Sprintf("(%v, %v, %v, %v, %v)", orgID, templateID, item.DeviceNumberID, item.Weekday, item.TimeType))
261
-		}
262
-
263
-		sql := fmt.Sprintf("UPDATE xt_patient_schedule_template_item SET status = 0, mtime = %v WHERE status = 1 AND (org_id, template_id, device_number_id, weekday, time_type) IN (%v);", now.Unix(), strings.Join(ins, ","))
264
-		if delErr := tx.Exec(sql).Error; delErr != nil {
265
-			tx.Rollback()
266
-			return delErr
267
-		}
268
-	}
269
-
270
-	// 批量更新 change template item
271
-	if len(changeTemplateItems) > 0 {
272
-		// utils.TraceLog("changeTemplateItems len: %v", len(changeTemplateItems))
273
-		for _, item := range changeTemplateItems {
274
-			if updateErr := tx.Exec("UPDATE xt_patient_schedule_template_item SET patient_id = ?, treat_mode = ?, mtime = ? WHERE status = 1 AND org_id = ? AND template_id = ? AND device_number_id = ? AND weekday = ? AND time_type = ?;", item.PatientID, item.TreatMode, now.Unix(), orgID, templateID, item.DeviceNumberID, item.Weekday, item.TimeType).Error; updateErr != nil {
275
-				tx.Rollback()
276
-				return updateErr
277
-			}
278
-		}
279
-	}
280
-
281
-	// 更改下两周的排班
282
-	deviceNumbers, getDeviceNumbersErr := GetAllValidDeviceNumbers(orgID)
283
-	if getDeviceNumbersErr != nil {
284
-		tx.Rollback()
285
-		return getDeviceNumbersErr
286
-	}
287
-	devicesMap := make(map[int64]*DeviceNumberViewModel, 0)
288
-	for _, deviceNumber := range deviceNumbers {
289
-		devicesMap[deviceNumber.ID] = deviceNumber
290
-	}
291
-	if shouldUpdateNextWeekSchedules {
292
-		nextWeek := now.AddDate(0, 0, 7)
293
-		if updateErr := _updateWeekSchedules(tx, orgID, nextWeek, addTemplateItems, delTemplateItems, changeTemplateItems, devicesMap); updateErr != nil {
294
-			tx.Rollback()
295
-			return updateErr
296
-		}
297
-	}
298
-	if shouldUpdateNextSecondWeekSchedules {
299
-		nextWeek := now.AddDate(0, 0, 14)
300
-		if updateErr := _updateWeekSchedules(tx, orgID, nextWeek, addTemplateItems, delTemplateItems, changeTemplateItems, devicesMap); updateErr != nil {
301
-			tx.Rollback()
302
-			return updateErr
303
-		}
304
-	}
305
-
306
-	tx.Commit()
307
-	return nil
308
-}
309
-
310
-func _updateWeekSchedules(tx *gorm.DB, orgID int64, week time.Time, addTemplateItems []*models.PatientScheduleTemplateItem, delTemplateItems []*models.PatientScheduleTemplateItem, changeTemplateItems []*models.PatientScheduleTemplateItem, deviceNumberMap map[int64]*DeviceNumberViewModel) error {
311
-	if deviceNumberMap == nil {
312
-		deviceNumbers, getDeviceNumbersErr := GetAllValidDeviceNumbers(orgID)
313
-		if getDeviceNumbersErr != nil {
314
-			return getDeviceNumbersErr
315
-		}
316
-		deviceNumberMap = make(map[int64]*DeviceNumberViewModel, 0)
317
-		for _, deviceNumber := range deviceNumbers {
318
-			deviceNumberMap[deviceNumber.ID] = deviceNumber
319
-		}
320
-	}
321
-
322
-	now := time.Now()
323
-	monday, _ := utils.GetMondayAndSundayOfWeekDate(&week)
324
-
325
-	// 先取消要取消的排班和新排班可能存在的重复排班
326
-	delIns := make([]string, 0, len(addTemplateItems)+len(delTemplateItems))
327
-	addValueStrs := make([]string, 0, len(addTemplateItems))
328
-	addValues := make([]interface{}, 0, len(addTemplateItems)*11)
329
-
330
-	for _, item := range addTemplateItems {
331
-		scheduleDate := monday.AddDate(0, 0, int(item.Weekday-1))
332
-		delIns = append(delIns, fmt.Sprintf("(%v, %v, %v)", item.DeviceNumberID, scheduleDate.Unix(), item.TimeType))
333
-
334
-		// 构建新排班的条件
335
-		deviceNumber := deviceNumberMap[item.DeviceNumberID]
336
-		if deviceNumber != nil {
337
-			addValueStrs = append(addValueStrs, "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
338
-			addValues = append(addValues, orgID)
339
-			addValues = append(addValues, deviceNumber.ZoneID)
340
-			addValues = append(addValues, item.DeviceNumberID)
341
-			addValues = append(addValues, item.PatientID)
342
-			addValues = append(addValues, scheduleDate.Unix())
343
-			addValues = append(addValues, item.Weekday)
344
-			addValues = append(addValues, item.TimeType)
345
-			addValues = append(addValues, item.TreatMode)
346
-			addValues = append(addValues, 1)
347
-			addValues = append(addValues, now.Unix())
348
-			addValues = append(addValues, now.Unix())
349
-		}
350
-	}
351
-	for _, item := range delTemplateItems {
352
-		delIns = append(delIns, fmt.Sprintf("(%v, %v, %v)", item.DeviceNumberID, monday.AddDate(0, 0, int(item.Weekday-1)).Unix(), item.TimeType))
353
-	}
354
-	if len(delIns) > 0 {
355
-		sql := fmt.Sprintf("UPDATE xt_schedule SET status = 0, updated_time = %v WHERE user_org_id = %v AND status = 1 AND (bed_id, schedule_date, schedule_type) IN (%v);", now.Unix(), orgID, strings.Join(delIns, ","))
356
-		if delErr := tx.Exec(sql).Error; delErr != nil {
357
-			tx.Rollback()
358
-			return delErr
359
-		}
360
-	}
361
-
362
-	// 批量插入排班
363
-	if len(addValueStrs) > 0 {
364
-		sql := fmt.Sprintf("INSERT INTO xt_schedule (user_org_id, partition_id, bed_id, patient_id, schedule_date, schedule_week, schedule_type, mode_id, status, created_time, updated_time) VALUES %v;", strings.Join(addValueStrs, ", "))
365
-		if insertErr := tx.Exec(sql, addValues...).Error; insertErr != nil {
366
-			return insertErr
367
-		}
368
-	}
369
-
370
-	// 更新已有排班
371
-	if len(changeTemplateItems) > 0 {
372
-		for _, item := range changeTemplateItems {
373
-			if updateErr := tx.Exec("UPDATE xt_schedule SET patient_id = ?, mode_id = ?, updated_time = ? WHERE status = 1 AND user_org_id = ? AND bed_id = ? AND schedule_date = ? AND schedule_type = ?;", item.PatientID, item.TreatMode, now.Unix(), orgID, item.DeviceNumberID, monday.AddDate(0, 0, int(item.Weekday-1)).Unix(), item.TimeType).Error; updateErr != nil {
374
-				tx.Rollback()
375
-				return updateErr
376
-			}
377
-		}
378
-	}
379
-
380
-	return nil
381
-}
382
-
383
-func SavePatientScheduleTemplateMode(templateMode *models.PatientScheduleTemplateMode) error {
384
-	tx := writeDb.Begin()
385
-	saveErr := tx.Save(templateMode).Error
386
-	if saveErr != nil {
387
-		tx.Rollback()
388
-		return saveErr
389
-	}
390
-	tx.Commit()
391
-	return nil
392
-}
393
-
394
-// 1 -> 0 或 2 -> 0 则不处理排班,但清除所有模板item
395
-func SavePatientScheduleTemplateModeAndClearAllTemplateItems(templateMode *models.PatientScheduleTemplateMode) error {
396
-	tx := writeDb.Begin()
397
-	saveErr := tx.Save(templateMode).Error
398
-	if saveErr != nil {
399
-		tx.Rollback()
400
-		return saveErr
401
-	}
402
-	disableErr := tx.Model(&models.PatientScheduleTemplateItem{}).Where("org_id = ? AND status = 1", templateMode.OrgID).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
403
-	if disableErr != nil {
404
-		tx.Rollback()
405
-		return disableErr
406
-	}
407
-	tx.Commit()
408
-	return nil
409
-}
410
-
411
-// 0 -> 1 或 0 -> 2 则直接清除下两周的排班
412
-func SavePatientScheduleTemplateModeAndClearNextTwoWeekSchedules(templateMode *models.PatientScheduleTemplateMode) error {
413
-	tx := writeDb.Begin()
414
-	saveErr := tx.Save(templateMode).Error
415
-	if saveErr != nil {
416
-		tx.Rollback()
417
-		return saveErr
418
-	}
419
-
420
-	now := time.Now()
421
-	nextWeek := now.AddDate(0, 0, 7)
422
-	nextMonday, _ := utils.GetMondayAndSundayOfWeekDate(&nextWeek)
423
-	nextSecWeek := now.AddDate(0, 0, 14)
424
-	_, nextSecSunday := utils.GetMondayAndSundayOfWeekDate(&nextSecWeek)
425
-	disableErr := tx.Model(&models.Schedule{}).Where("user_org_id = ? AND status = 1 AND schedule_date >= ? AND schedule_date <= ?", templateMode.OrgID, nextMonday.Unix(), nextSecSunday.Unix()).Updates(map[string]interface{}{"status": 0, "mtime": now.Unix()}).Error
426
-	if disableErr != nil {
427
-		tx.Rollback()
428
-		return disableErr
429
-	}
430
-
431
-	tx.Commit()
432
-	return nil
433
-}
434
-
435
-// 1 -> 2 清除第二周排班
436
-func SavePatientScheduleTemplateModeAndClearNextSecondWeekSchedules(templateMode *models.PatientScheduleTemplateMode) error {
437
-	tx := writeDb.Begin()
438
-	saveErr := tx.Save(templateMode).Error
439
-	if saveErr != nil {
440
-		tx.Rollback()
441
-		return saveErr
442
-	}
443
-
444
-	now := time.Now()
445
-	nextSecWeek := now.AddDate(0, 0, 14)
446
-	nextSecMonday, nextSecSunday := utils.GetMondayAndSundayOfWeekDate(&nextSecWeek)
447
-	disableErr := tx.Model(&models.Schedule{}).Where("user_org_id = ? AND status = 1 AND schedule_date >= ? AND schedule_date <= ?", templateMode.OrgID, nextSecMonday.Unix(), nextSecSunday.Unix()).Updates(map[string]interface{}{"status": 0, "mtime": now.Unix()}).Error
448
-	if disableErr != nil {
449
-		tx.Rollback()
450
-		return disableErr
451
-	}
452
-
453
-	tx.Commit()
454
-	return nil
455
-}
456
-
457
-// 2 -> 1 清除第二周模板item,清除第二周排班,将第一周的排班重复到第二周
458
-func SavePatientScheduleTemplateMode2To1(templateMode *models.PatientScheduleTemplateMode, secondWeekTemplateID int64, firstWeekTemplateItems []*models.PatientScheduleTemplateItem) error {
459
-	tx := writeDb.Begin()
460
-	saveErr := tx.Save(templateMode).Error
461
-	if saveErr != nil {
462
-		tx.Rollback()
463
-		return saveErr
464
-	}
465
-
466
-	now := time.Now()
467
-
468
-	disableItemsErr := tx.Model(&models.PatientScheduleTemplateItem{}).Where("template_id = ? AND status = 1", secondWeekTemplateID).Updates(map[string]interface{}{"status": 0, "mtime": now.Unix()}).Error
469
-	if disableItemsErr != nil {
470
-		tx.Rollback()
471
-		return disableItemsErr
472
-	}
473
-
474
-	nextSecWeek := now.AddDate(0, 0, 14)
475
-	nextSecMonday, nextSecSunday := utils.GetMondayAndSundayOfWeekDate(&nextSecWeek)
476
-	disableSchsErr := tx.Model(&models.Schedule{}).Where("user_org_id = ? AND status = 1 AND schedule_date >= ? AND schedule_date <= ?", templateMode.OrgID, nextSecMonday.Unix(), nextSecSunday.Unix()).Updates(map[string]interface{}{"status": 0, "mtime": now.Unix()}).Error
477
-	if disableSchsErr != nil {
478
-		tx.Rollback()
479
-		return disableSchsErr
480
-	}
481
-
482
-	if len(firstWeekTemplateItems) > 0 {
483
-		deviceNumbers, getDeviceNumbersErr := GetAllValidDeviceNumbers(templateMode.OrgID)
484
-		if getDeviceNumbersErr != nil {
485
-			tx.Rollback()
486
-			return getDeviceNumbersErr
487
-		}
488
-		deviceNumberMap := make(map[int64]*DeviceNumberViewModel, 0)
489
-		for _, deviceNumber := range deviceNumbers {
490
-			deviceNumberMap[deviceNumber.ID] = deviceNumber
491
-		}
492
-
493
-		valueStrs := make([]string, 0, len(firstWeekTemplateItems))
494
-		values := make([]interface{}, 0, len(firstWeekTemplateItems)*11)
495
-		for _, item := range firstWeekTemplateItems {
496
-			deviceNumber := deviceNumberMap[item.DeviceNumberID]
497
-			if deviceNumber == nil {
498
-				continue
499
-			}
500
-
501
-			valueStrs = append(valueStrs, "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
502
-			values = append(values, templateMode.OrgID)
503
-			values = append(values, deviceNumber.ZoneID)
504
-			values = append(values, item.DeviceNumberID)
505
-			values = append(values, item.PatientID)
506
-			values = append(values, nextSecMonday.AddDate(0, 0, int(item.Weekday-1)).Unix())
507
-			values = append(values, item.Weekday)
508
-			values = append(values, item.TimeType)
509
-			values = append(values, item.TreatMode)
510
-			values = append(values, 1)
511
-			values = append(values, now.Unix())
512
-			values = append(values, now.Unix())
513
-		}
514
-
515
-		sql := fmt.Sprintf("INSERT INTO xt_schedule (user_org_id, partition_id, bed_id, patient_id, schedule_date, schedule_week, schedule_type, mode_id, status, created_time, updated_time) VALUES %v;", strings.Join(valueStrs, ", "))
516
-		if insertErr := tx.Exec(sql, values...).Error; insertErr != nil {
517
-			return insertErr
518
-		}
519
-	}
520
-
521
-	tx.Commit()
522
-	return nil
523
-}

Разница между файлами не показана из-за своего большого размера
+ 0 - 1361
models/service/patient_service.go


Разница между файлами не показана из-за своего большого размера
+ 0 - 1446
models/service/patientmanage_service.go


+ 0 - 149
models/service/pay_service.go Просмотреть файл

@@ -1,149 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	"github.com/jinzhu/gorm"
6
-	"strconv"
7
-	"time"
8
-)
9
-
10
-func FindServiceSubscibeByOrgId(orgId int64) (*models.ServeSubscibe, error) {
11
-	subscibe := models.ServeSubscibe{}
12
-	err = readUserDb.Model(&models.ServeOrder{}).Preload("Org", "status=1").Where("org_id=? and status=1", orgId).First(&subscibe).Error
13
-
14
-	var count int64
15
-	err = readDb.Model(&models.Patients{}).Where("user_org_id=? and status = 1", orgId).Count(&count).Error
16
-	subscibe.Patients = count
17
-
18
-	return &subscibe, err
19
-}
20
-
21
-func FindOrgAppByOrgId(orgId int64) (*models.OrgApp, error) {
22
-	app := models.OrgApp{}
23
-	err = readUserDb.Model(&models.OrgApp{}).Where("org_id=? and status=1", orgId).First(&app).Error
24
-	return &app, err
25
-}
26
-
27
-func FindAllProduct() ([]*models.ServeProduct, error) {
28
-	product := []*models.ServeProduct{}
29
-	err := readUserDb.Model(&models.ServeProduct{}).Where("status=1").Find(&product).Error
30
-	return product, err
31
-}
32
-
33
-func FindProductByID(id int64) (*models.ServeProduct, error) {
34
-	var product models.ServeProduct
35
-	err := readUserDb.Where("id = ?  and status=1", id).First(&product).Error
36
-	if err == gorm.ErrRecordNotFound {
37
-		return nil, nil
38
-	}
39
-	if err != nil {
40
-		return nil, err
41
-	}
42
-	return &product, err
43
-}
44
-
45
-func CreateOrderRecord(order *models.ServeOrder) {
46
-	writeUserDb.Create(order)
47
-}
48
-func CreateOrderInfomation(info *models.ServeOrderInfomation) {
49
-	writeUserDb.Create(info)
50
-}
51
-
52
-func FindOrderInfomationByID(orderNumber string, orgId int64) (*models.ServeOrderInfomation, error) {
53
-	var order models.ServeOrderInfomation
54
-	err := readUserDb.Model(&models.ServeOrderInfomation{}).Where("order_number = ? and org_id=? and status=1", orderNumber, orgId).First(&order).Error
55
-	if err == gorm.ErrRecordNotFound {
56
-		return nil, nil
57
-	}
58
-
59
-	if err != nil {
60
-		return nil, err
61
-	}
62
-	return &order, err
63
-
64
-}
65
-
66
-func FindServeOrderByID(orgId, id int64) (*models.ServeOrder, error) {
67
-	var order models.ServeOrder
68
-	err := readUserDb.Model(&models.ServeOrder{}).Where("id = ? and org_id=? and status=1", id, orgId).First(&order).Error
69
-	if err == gorm.ErrRecordNotFound {
70
-		return nil, nil
71
-	}
72
-
73
-	if err != nil {
74
-		return nil, err
75
-	}
76
-	return &order, err
77
-}
78
-
79
-func UpdateOrderPayType(orgId int64, id int64) error {
80
-	err := writeUserDb.Model(&models.ServeOrder{}).Where("id = ? and org_id=? and status=1", id, orgId).Updates(map[string]interface{}{"pay_type": 2}).Error
81
-	return err
82
-}
83
-
84
-func UpdateOrderStatus(orgId int64, id int64) error {
85
-	err := writeUserDb.Model(&models.ServeOrder{}).Where("id = ? and org_id=? and status=1", id, orgId).Updates(map[string]interface{}{"order_status": 3}).Error
86
-	return err
87
-}
88
-
89
-func GetOrderList(orgId int64) ([]*models.ServeOrder, error) {
90
-	var orders []*models.ServeOrder
91
-	err := readUserDb.Model(&models.ServeOrder{}).Where("org_id=? and status=1", orgId).Order("created_time desc").Find(&orders).Error
92
-	for _, order := range orders {
93
-		tm := time.Unix(order.OrderExpireTime, 0)
94
-		order.OrderExpireTimeFormat = tm.Format("2006-01-02 15:04:05")
95
-	}
96
-
97
-	return orders, err
98
-}
99
-
100
-func FindServeOrderByOrderNumber(orderNumber string) (*models.ServeOrder, error) {
101
-	var order models.ServeOrder
102
-	err := readUserDb.Model(&models.ServeOrder{}).Where(" status=1 AND order_number = ? ", orderNumber).First(&order).Error
103
-	if err == gorm.ErrRecordNotFound {
104
-		return nil, nil
105
-	}
106
-
107
-	if err != nil {
108
-		return nil, err
109
-	}
110
-	return &order, err
111
-}
112
-
113
-func GetHetong(orgID, orderId int64) (*models.ServeOrderContract, error) {
114
-	var contract models.ServeOrderContract
115
-	var err error
116
-	err = readUserDb.Model(&models.ServeOrderContract{}).Where("order_id=? and org_id=? and status=1", orderId, orgID).First(&contract).Error
117
-
118
-	if err == gorm.ErrRecordNotFound {
119
-		return nil, nil
120
-	}
121
-	if err != nil {
122
-		return nil, err
123
-	}
124
-	return &contract, nil
125
-}
126
-
127
-func CreateHetong(m *models.ServeOrderContract) (err error) {
128
-	err = writeUserDb.Create(m).Error
129
-	return
130
-}
131
-
132
-func UpdateOrder(orderNumber string, Quantity int64, orgId int64, payment_transaction_id string, startTimes int64, endTimes int64) {
133
-	var startTime int64
134
-	var endTime int64
135
-
136
-	if startTimes == 0 && endTimes == 0 {
137
-		startTime = time.Now().Unix()
138
-		endTime = startTime + ((12 * 30 * 24 * 3600) * Quantity)
139
-	} else {
140
-
141
-		endTime = endTimes + ((12 * 30 * 24 * 3600) * Quantity)
142
-
143
-	}
144
-
145
-	tm := time.Unix(endTime, 0)
146
-	serve_duration := strconv.FormatInt(12*Quantity, 10) + "月" + "到期服务时间" + tm.Format("2006-01-02 15:04:05")
147
-	writeUserDb.Model(&models.ServeOrder{}).Where("order_number = ? and status=1", orderNumber).Updates(map[string]interface{}{"order_status": 2, "pay_type": 1, "period_start": startTime, "period_end": endTime, "serve_duration": serve_duration, "pay_time": time.Now().Unix(), "payment_transaction_id": payment_transaction_id})
148
-	writeUserDb.Model(&models.ServeSubscibe{}).Where("org_id = ? and status=1", orgId).Updates(map[string]interface{}{"period_start": startTime, "period_end": endTime, "updated_time": time.Now().Unix(), "state": 1})
149
-}

+ 0 - 723
models/service/print_data_service/schedule_dialysis/print_schedule_dialysis_models.go Просмотреть файл

@@ -1,723 +0,0 @@
1
-package schedule_dialysis
2
-
3
-type PatientVM struct {
4
-	ID                           int64   `gorm:"column:id" json:"id" form:"id"`
5
-	UserOrgId                    int64   `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
6
-	UserId                       int64   `gorm:"column:user_id" json:"user_id" form:"user_id"`
7
-	Avatar                       string  `gorm:"column:avatar" json:"avatar" form:"avatar"`
8
-	PatientType                  int64   `gorm:"column:patient_type" json:"patient_type" form:"patient_type"`
9
-	DialysisNo                   string  `gorm:"column:dialysis_no" json:"dialysis_no" form:"dialysis_no"`
10
-	AdmissionNumber              string  `gorm:"column:admission_number" json:"admission_number" form:"admission_number"`
11
-	Source                       int64   `gorm:"column:source" json:"source" form:"source"`
12
-	Lapseto                      int64   `gorm:"column:lapseto" json:"lapseto" form:"lapseto"`
13
-	PartitionId                  int64   `gorm:"column:partition_id" json:"partition_id" form:"partition_id"`
14
-	BedId                        int64   `gorm:"column:bed_id" json:"bed_id" form:"bed_id"`
15
-	Name                         string  `gorm:"column:name" json:"name" form:"name"`
16
-	Alias                        string  `gorm:"column:alias" json:"alias" form:"alias"`
17
-	Gender                       int64   `gorm:"column:gender" json:"gender" form:"gender"`
18
-	Nation                       string  `gorm:"column:nation" json:"nation" form:"nation"`
19
-	NativePlace                  string  `gorm:"column:native_place" json:"native_place" form:"native_place"`
20
-	MaritalStatus                int64   `gorm:"column:marital_status" json:"marital_status" form:"marital_status"`
21
-	IdCardNo                     string  `gorm:"column:id_card_no" json:"id_card_no" form:"id_card_no"`
22
-	Birthday                     int64   `gorm:"column:birthday" json:"birthday" form:"birthday"`
23
-	ReimbursementWayId           int64   `gorm:"column:reimbursement_way_id" json:"reimbursement_way_id" form:"reimbursement_way_id"`
24
-	HealthCareType               int64   `gorm:"column:health_care_type" json:"health_care_type" form:"health_care_type"`
25
-	HealthCareNo                 string  `gorm:"column:health_care_no" json:"health_care_no" form:"health_care_no"`
26
-	HealthCareDueDate            int64   `gorm:"column:health_care_due_date" json:"health_care_due_date" form:"health_care_due_date"`
27
-	Height                       int64   `gorm:"column:height" json:"height" form:"height"`
28
-	BloodType                    int64   `gorm:"column:blood_type" json:"blood_type" form:"blood_type"`
29
-	Rh                           int64   `gorm:"column:rh" json:"rh" form:"rh"`
30
-	HealthCareDueAlertDate       int64   `gorm:"column:health_care_due_alert_date" json:"health_care_due_alert_date" form:"health_care_due_alert_date"`
31
-	EducationLevel               int64   `gorm:"column:education_level" json:"education_level" form:"education_level"`
32
-	Profession                   int64   `gorm:"column:profession" json:"profession" form:"profession"`
33
-	Phone                        string  `gorm:"column:phone" json:"phone" form:"phone"`
34
-	HomeTelephone                string  `gorm:"column:home_telephone" json:"home_telephone" form:"home_telephone"`
35
-	RelativePhone                string  `gorm:"column:relative_phone" json:"relative_phone" form:"relative_phone"`
36
-	RelativeRelations            string  `gorm:"column:relative_relations" json:"relative_relations" form:"relative_relations"`
37
-	HomeAddress                  string  `gorm:"column:home_address" json:"home_address" form:"home_address"`
38
-	WorkUnit                     string  `gorm:"column:work_unit" json:"work_unit" form:"work_unit"`
39
-	UnitAddress                  string  `gorm:"column:unit_address" json:"unit_address" form:"unit_address"`
40
-	Children                     int64   `gorm:"column:children" json:"children" form:"children"`
41
-	ReceivingDate                int64   `gorm:"column:receiving_date" json:"receiving_date" form:"receiving_date"`
42
-	IsHospitalFirstDialysis      int64   `gorm:"column:is_hospital_first_dialysis" json:"is_hospital_first_dialysis" form:"is_hospital_first_dialysis"`
43
-	FirstDialysisDate            int64   `gorm:"column:first_dialysis_date" json:"first_dialysis_date" form:"first_dialysis_date"`
44
-	FirstDialysisHospital        string  `gorm:"column:first_dialysis_hospital" json:"first_dialysis_hospital" form:"first_dialysis_hospital"`
45
-	PredialysisCondition         string  `gorm:"column:predialysis_condition" json:"predialysis_condition" form:"predialysis_condition"`
46
-	PreHospitalDialysisFrequency string  `gorm:"column:pre_hospital_dialysis_frequency" json:"pre_hospital_dialysis_frequency" form:"pre_hospital_dialysis_frequency"`
47
-	PreHospitalDialysisTimes     int64   `gorm:"column:pre_hospital_dialysis_times" json:"pre_hospital_dialysis_times" form:"pre_hospital_dialysis_times"`
48
-	HospitalFirstDialysisDate    int64   `gorm:"column:hospital_first_dialysis_date" json:"hospital_first_dialysis_date" form:"hospital_first_dialysis_date"`
49
-	InductionPeriod              int64   `gorm:"column:induction_period" json:"induction_period" form:"induction_period"`
50
-	InitialDialysis              int64   `gorm:"column:initial_dialysis" json:"initial_dialysis" form:"initial_dialysis"`
51
-	TotalDialysis                int64   `gorm:"column:total_dialysis" json:"total_dialysis" form:"total_dialysis"`
52
-	AttendingDoctorId            int64   `gorm:"column:attending_doctor_id" json:"attending_doctor_id" form:"attending_doctor_id"`
53
-	HeadNurseId                  int64   `gorm:"column:head_nurse_id" json:"head_nurse_id" form:"head_nurse_id"`
54
-	Evaluate                     string  `gorm:"column:evaluate" json:"evaluate" form:"evaluate"`
55
-	Diagnose                     string  `gorm:"column:diagnose" json:"diagnose" form:"diagnose"`
56
-	Remark                       string  `gorm:"column:remark" json:"remark" form:"remark"`
57
-	RegistrarsId                 int64   `gorm:"column:registrars_id" json:"registrars_id" form:"registrars_id"`
58
-	Registrars                   string  `gorm:"column:registrars" json:"registrars" form:"registrars"`
59
-	QrCode                       string  `gorm:"column:qr_code" json:"qr_code" form:"qr_code"`
60
-	BindingState                 int64   `gorm:"column:binding_state" json:"binding_state" form:"binding_state"`
61
-	PatientComplains             string  `gorm:"column:patient_complains" json:"patient_complains"` // 主诉
62
-	PresentHistory               string  `gorm:"column:present_history" json:"present_history"`     // 现病史
63
-	PastHistory                  string  `gorm:"column:past_history" json:"past_history"`           // 既往史
64
-	Temperature                  float64 `gorm:"column:temperature" json:"temperature"`             // 体格检查-体温
65
-	Pulse                        int64   `gorm:"column:pulse" json:"pulse"`                         // 体格检查-脉搏
66
-	Respiratory                  int64   `gorm:"column:respiratory" json:"respiratory"`             // 体格检查-呼吸频率
67
-	SBP                          int64   `gorm:"column:sbp" json:"sbp"`                             // 体格检查-收缩压
68
-	DBP                          int64   `gorm:"column:dbp" json:"dbp"`                             // 体格检查-舒张压
69
-	Status                       int64   `gorm:"column:status" json:"status" form:"status"`
70
-	CreatedTime                  int64   `gorm:"column:created_time" json:"created_time" form:"created_time"`
71
-	UpdatedTime                  int64   `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
72
-	Age                          int64   `gorm:"column:age" json:"age"`
73
-	IsOpenRemind                 int64   `gorm:"column:is_open_remind" json:"is_open_remind"`
74
-	DialysisAge                  int64   `gorm:"column:dialysis_age" json:"dialysis_age" form:"dialysis_age"`
75
-	ExpenseKind                  int64   `gorm:"column:expense_kind" json:"expense_kind" form:"expense_kind"`
76
-	TellPhone                    string  `gorm:"column:tell_phone" json:"tell_phone" form:"tell_phone"`
77
-	FirstTreatmentDate           int64   `gorm:"column:first_treatment_date" json:"first_treatment_date" form:"first_treatment_date"`
78
-	UserSysBeforeCount           int64   `gorm:"column:user_sys_before_count" json:"user_sys_before_count" form:"user_sys_before_count"`
79
-}
80
-
81
-func (PatientVM) TableName() string {
82
-	return "xt_patients"
83
-}
84
-
85
-type DialysisOrderVM struct {
86
-	ID             int64           `gorm:"column:id" json:"id"`
87
-	DialysisDate   int64           `gorm:"column:dialysis_date" json:"dialysis_date"`
88
-	PatientID      int64           `gorm:"column:patient_id" json:"patient_id"`
89
-	Stage          int64           `gorm:"column:stage" json:"stage"`
90
-	BedID          int64           `gorm:"column:bed_id" json:"bed_id"`
91
-	StartNurse     int64           `gorm:"column:start_nurse" json:"start_nurse"`
92
-	FinishNurse    int64           `gorm:"column:finish_nurse" json:"finish_nurse"`
93
-	StartTime      int64           `gorm:"column:start_time" json:"start_time"`
94
-	EndTime        int64           `gorm:"column:end_time" json:"end_time"`
95
-	PunctureNurse  int64           `gorm:"column:puncture_nurse" json:"puncture_nurse"`
96
-	DeviceNumber   *DeviceNumberVM `gorm:"ForeignKey:BedID" json:"device_number"`
97
-	Creator        int64           `gorm:"column:creator" json:"creator"`
98
-	Modifier       int64           `gorm:"column:modifier" json:"modifier"`
99
-	FinishCreator  int64           `gorm:"column:finish_creator" json:"finish_creator"`
100
-	FinishModifier int64           `gorm:"column:finish_modifier" json:"finish_modifier"`
101
-	SchedualType   int64           `gorm:"column:schedual_type" json:"schedual_type"`
102
-	WashpipeNurse  int64           `gorm:"column:washpipe_nurse" json:"washpipe_nurse" form:"washpipe_nurse"`
103
-}
104
-
105
-func (DialysisOrderVM) TableName() string {
106
-	return "xt_dialysis_order"
107
-}
108
-
109
-type DeviceNumberVM struct {
110
-	ID           int64         `gorm:"column:id" json:"id"`
111
-	Number       string        `json:"number"`
112
-	ZoneID       int64         `gorm:"column:zone_id" json:"zone_id"`
113
-	DeviceZoneVM *DeviceZoneVM `gorm:"ForeignKey:ZoneID" json:"zone"`
114
-}
115
-
116
-func (DeviceNumberVM) TableName() string {
117
-	return "xt_device_number"
118
-}
119
-
120
-type DeviceZoneVM struct {
121
-	ID   int64  `gorm:"column:id" json:"id"`
122
-	Name string `json:"name"`
123
-	Type int    `json:"type"`
124
-}
125
-
126
-func (DeviceZoneVM) TableName() string {
127
-	return "xt_device_zone"
128
-}
129
-
130
-type PrescriptionVM struct {
131
-	ID                         int64   `gorm:"column:id" json:"id"`
132
-	PatientID                  int64   `gorm:"column:patient_id" json:"patient_id"`
133
-	DewaterAmount              float64 `gorm:"column:dewater_amount" json:"dewater_amount"`
134
-	PrescriptionDewatering     float64 `gorm:"column:prescription_dewatering" json:"prescription_dewatering"`
135
-	Anticoagulant              int64   `gorm:"column:anticoagulant" json:"anticoagulant"`
136
-	AnticoagulantShouji        float64 `gorm:"column:anticoagulant_shouji" json:"anticoagulant_shouji"`
137
-	AnticoagulantWeichi        float64 `gorm:"column:anticoagulant_weichi" json:"anticoagulant_weichi"`
138
-	AnticoagulantZongliang     float64 `gorm:"column:anticoagulant_zongliang" json:"anticoagulant_zongliang"`
139
-	AnticoagulantGaimingcheng  string  `gorm:"column:anticoagulant_gaimingcheng" json:"anticoagulant_gaimingcheng"`
140
-	AnticoagulantGaijiliang    string  `gorm:"column:anticoagulant_gaijiliang" json:"anticoagulant_gaijiliang"`
141
-	ModeId                     int64   `gorm:"column:mode_id" json:"mode_id"`
142
-	DialysisDuration           float64 `gorm:"column:dialysis_duration" json:"dialysis_duration"`
143
-	ReplacementTotal           float64 `gorm:"column:replacement_total" json:"replacement_total"`
144
-	ReplacementWay             int64   `gorm:"column:replacement_way" json:"replacement_way"`
145
-	HemodialysisMachine        int64   `gorm:"column:hemodialysis_machine" json:"hemodialysis_machine"`
146
-	BloodFilter                int64   `gorm:"column:blood_filter" json:"blood_filter"`
147
-	PerfusionApparatus         int64   `gorm:"column:perfusion_apparatus" json:"perfusion_apparatus"`
148
-	VascularAccessMode         int64   `gorm:"column:vascular_access_mode" json:"vascular_access_mode"`
149
-	VascularAccess             int64   `gorm:"column:vascular_access" json:"vascular_access"`
150
-	BloodFlowVolume            float64 `gorm:"column:blood_flow_volume" json:"blood_flow_volume"`
151
-	DialysateFlow              float64 `gorm:"column:dialysate_flow" json:"dialysate_flow"`
152
-	DisplaceLiqui              float64 `gorm:"column:displace_liqui" json:"displace_liqui"`
153
-	Kalium                     float64 `gorm:"column:kalium" json:"kalium"`
154
-	Sodium                     float64 `gorm:"column:sodium" json:"sodium"`
155
-	Calcium                    float64 `gorm:"column:calcium" json:"calcium"`
156
-	Bicarbonate                float64 `gorm:"column:bicarbonate" json:"bicarbonate"`
157
-	Glucose                    float64 `gorm:"column:glucose" json:"glucose"`
158
-	DialysateTemperature       float64 `gorm:"column:dialysate_temperature" json:"dialysate_temperature"`
159
-	Conductivity               float64 `gorm:"column:conductivity" json:"conductivity"`
160
-	PrescriptionDoctor         int64   `gorm:"column:prescription_doctor" json:"prescription_doctor"`
161
-	Remark                     string  `gorm:"column:remark" json:"remark"`
162
-	RecordDate                 int64   `gorm:"column:record_date" json:"record_date"`
163
-	RecordId                   int64   `gorm:"column:record_id" json:"record_id"`
164
-	Creater                    int64   `gorm:"column:creater" json:"creater"`
165
-	Modifier                   int64   `gorm:"column:modifier" json:"modifier"`
166
-	DialysisDurationHour       int64   `gorm:"column:dialysis_duration_hour" json:"dialysis_duration_hour"`
167
-	DialysisDurationMinute     int64   `gorm:"column:dialysis_duration_minute" json:"dialysis_duration_minute"`
168
-	DialysateFormulation       int64   `gorm:"column:dialysate_formulation" json:"dialysate_formulation"`
169
-	TargetUltrafiltration      float64 `gorm:"column:target_ultrafiltration" json:"target_ultrafiltration"`
170
-	DialyzerPerfusionApparatus string  `gorm:"column:dialyzer_perfusion_apparatus" json:"dialyzer_perfusion_apparatus"`
171
-	BodyFluid                  int64   `gorm:"column:body_fluid" json:"body_fluid"`
172
-	SpecialMedicine            int64   `gorm:"column:special_medicine" json:"special_medicine"`
173
-	SpecialMedicineOther       string  `gorm:"column:special_medicine_other" json:"special_medicine_other"`
174
-	DisplaceLiquiPart          int64   `gorm:"column:displace_liqui_part" json:"displace_liqui_part"`
175
-	BloodAccess                int64   `gorm:"column:blood_access" json:"blood_access"`
176
-	DisplaceLiquiValue         float64 `gorm:"column:displace_liqui_value" json:"displace_liqui_value"`
177
-	Ultrafiltration            float64 `gorm:"column:ultrafiltration" json:"ultrafiltration"`
178
-	BodyFluidOther             string  `gorm:"column:body_fluid_other" json:"body_fluid_other"`
179
-	Niprocart                  int64   `gorm:"column:niprocart" json:"niprocart"`
180
-	Jms                        int64   `gorm:"column:jms" json:"jms"`
181
-	FistulaNeedleSet           int64   `gorm:"column:fistula_needle_set" json:"fistula_needle_set"`
182
-	FistulaNeedleSet16         int64   `gorm:"column:fistula_needle_set_16" json:"fistula_needle_set_16"`
183
-	Hemoperfusion              int64   `gorm:"column:hemoperfusion" json:"hemoperfusion"`
184
-	DialyserSterilised         int64   `gorm:"column:dialyser_sterilised" json:"dialyser_sterilised"`
185
-	Filtryzer                  int64   `gorm:"column:filtryzer" json:"filtryzer"`
186
-	TargetKtv                  float64 `gorm:"column:target_ktv" json:"target_ktv"`
187
-	Dialyzers                  int64   `gorm:"column:dialyzers" json:"dialyzers"`
188
-	Injector                   int64   `gorm:"column:injector" json:"injector"`
189
-	Bloodlines                 int64   `gorm:"column:bloodlines" json:"bloodlines"`
190
-	TubingHemodialysis         int64   `gorm:"column:tubing_hemodialysis" json:"tubing_hemodialysis"`
191
-	Package                    int64   `gorm:"column:package" json:"package"`
192
-	ALiquid                    int64   `gorm:"column:a_liquid" json:"a_liquid"`
193
-	AnticoagulantStopTimeMin   int64   `gorm:"column:anticoagulant_stop_time_min" json:"anticoagulant_stop_time_min" form:"anticoagulant_stop_time_min"`
194
-	AnticoagulantStopTimeHour  int64   `gorm:"column:anticoagulant_stop_time_hour" json:"anticoagulant_stop_time_hour" form:"anticoagulant_stop_time_hour"`
195
-
196
-	HemodialysisPipelines      string  `gorm:"column:hemodialysis_pipelines" json:"hemodialysis_pipelines" form:"hemodialysis_pipelines"`
197
-	HemodialysisPipelinesCount float64 `gorm:"column:hemodialysis_pipelines_count" json:"hemodialysis_pipelines_count" form:"hemodialysis_pipelines_count"`
198
-	PunctureNeedle             string  `gorm:"column:puncture_needle" json:"puncture_needle" form:"puncture_needle"`
199
-	PunctureNeedleCount        float64 `gorm:"column:puncture_needle_count" json:"puncture_needle_count" form:"puncture_needle_count"`
200
-	Epo                        string  `gorm:"column:epo" json:"epo" form:"epo"`
201
-	EpoCount                   float64 `gorm:"column:epo_count" json:"epo_count" form:"epo_count"`
202
-}
203
-
204
-func (PrescriptionVM) TableName() string {
205
-	return "xt_dialysis_prescription"
206
-}
207
-
208
-type AssessmentBeforeDislysisVM struct {
209
-	ID                             int64   `gorm:"column:id" json:"id"`
210
-	PatientID                      int64   `gorm:"column:patient_id" json:"patient_id"`
211
-	AssessmentDate                 int64   `gorm:"column:assessment_date" json:"assessment_date"`
212
-	Temperature                    float64 `gorm:"column:temperature" json:"temperature"`
213
-	PulseFrequency                 float64 `gorm:"column:pulse_frequency" json:"pulse_frequency"`
214
-	BreathingRate                  float64 `gorm:"column:breathing_rate" json:"breathing_rate"`
215
-	SystolicBloodPressure          float64 `gorm:"column:systolic_blood_pressure" json:"systolic_blood_pressure"`
216
-	DiastolicBloodPressure         float64 `gorm:"column:diastolic_blood_pressure" json:"diastolic_blood_pressure"`
217
-	BloodPressureType              int64   `gorm:"column:blood_pressure_type" json:"blood_pressure_type"`
218
-	DryWeight                      float64 `gorm:"column:dry_weight" json:"dry_weight"`
219
-	WeightAfterLastTransparency    float64 `gorm:"column:weight_after_last_transparency" json:"weight_after_last_transparency"`
220
-	WeighingWay                    string  `gorm:"column:weighing_way" json:"weighing_way"`
221
-	WeighingBefore                 float64 `gorm:"column:weighing_before" json:"weighing_before"`
222
-	AdditionalWeight               float64 `gorm:"column:additional_weight" json:"additional_weight"`
223
-	WeightBefore                   float64 `gorm:"column:weight_before" json:"weight_before"`
224
-	WeightGain                     float64 `gorm:"column:weight_gain" json:"weight_gain"`
225
-	PreloadedDewatering            float64 `gorm:"column:preloaded_dewatering" json:"preloaded_dewatering"`
226
-	UltrafiltrationAmount          float64 `gorm:"column:ultrafiltration_amount" json:"ultrafiltration_amount"`
227
-	DialysisInterphase             string  `gorm:"column:dialysis_interphase" json:"dialysis_interphase"`
228
-	LastPostDialysis               string  `gorm:"column:last_post_dialysis" json:"last_post_dialysis"`
229
-	SymptomBeforeDialysis          string  `gorm:"column:symptom_before_dialysis" json:"symptom_before_dialysis"`
230
-	InternalFistula                string  `gorm:"column:internal_fistula" json:"internal_fistula"`
231
-	InternalFistulaSkin            string  `gorm:"column:internal_fistula_skin" json:"internal_fistula_skin"`
232
-	Catheter                       string  `gorm:"column:catheter" json:"catheter"`
233
-	CatheterBend                   int     `gorm:"column:catheter_bend" json:"catheter_bend"`
234
-	Complication                   string  `gorm:"column:complication" json:"complication"`
235
-	Evaluator                      int64   `gorm:"column:evaluator" json:"evaluator"`
236
-	Creater                        int64   `gorm:"column:creater" json:"creater"`
237
-	Remark                         string  `gorm:"column:remark" json:"remark"`
238
-	Modifier                       int64   `gorm:"column:modifier" json:"modifier"`
239
-	BloodAccessPartId              string  `gorm:"column:blood_access_part_id" json:"blood_access_part_id"`
240
-	BloodAccessPartOperaId         int64   `gorm:"column:blood_access_part_opera_id" json:"blood_access_part_opera_id"`
241
-	IsHemorrhage                   int64   `gorm:"column:is_hemorrhage" json:"is_hemorrhage"`
242
-	Hemorrhage                     string  `gorm:"column:hemorrhage" json:"hemorrhage"`
243
-	HemorrhageOther                string  `gorm:"column:hemorrhage_other" json:"hemorrhage_other"`
244
-	PunctureMethod                 string  `gorm:"column:puncture_method" json:"puncture_method"`
245
-	BloodAccessInternalFistula     string  `gorm:"column:blood_access_internal_fistula" json:"blood_access_internal_fistula"`
246
-	InternalFistulaOther           string  `gorm:"column:internal_fistula_other" json:"internal_fistula_other"`
247
-	BloodAccessNoise               int64   `gorm:"column:blood_access_noise" json:"blood_access_noise"`
248
-	PunctureWay                    string  `gorm:"column:puncture_way" json:"puncture_way"`
249
-	VenousCatheterization          int64   `gorm:"column:venous_catheterization" json:"venous_catheterization"`
250
-	VenousCatheterizationPart      int64   `gorm:"column:venous_catheterization_part" json:"venous_catheterization_part"`
251
-	VenousCatheterizationPartOther string  `gorm:"column:venous_catheterization_part_other" json:"venous_catheterization_part_other"`
252
-	DuctusArantii                  string  `gorm:"column:ductus_arantii" json:"ductus_arantii"`
253
-	EmergencyTreatment             int64   `gorm:"column:emergency_treatment" json:"emergency_treatment"`
254
-	EmergencyTreatmentOther        string  `gorm:"column:emergency_treatment_other" json:"emergency_treatment_other"`
255
-	DialysisCount                  string  `gorm:"column:dialysis_count" json:"dialysis_count"`
256
-	AssessmentDoctor               int64   `gorm:"column:assessment_doctor" json:"assessment_doctor"`
257
-	AssessmentTime                 int64   `gorm:"column:assessment_time" json:"assessment_time"`
258
-	MachineType                    string  `gorm:"column:machine_type" json:"machine_type"`
259
-	IsInfect                       int64   `gorm:"column:is_infect" json:"is_infect"`
260
-	Exposed                        float64 `gorm:"column:exposed" json:"exposed"`
261
-	Skin                           string  `gorm:"column:skin" json:"skin"`
262
-	SkinOther                      string  `gorm:"column:skin_other" json:"skin_other"`
263
-	InfectOther                    string  `gorm:"column:infect_other" json:"infect_other"`
264
-	DuctusArantiiOther             string  `gorm:"column:ductus_arantii_other" json:"ductus_arantii_other"`
265
-	PunctureNeedle                 string  `gorm:"column:puncture_needle" json:"puncture_needle"`
266
-	LastPostDialysisOther          string  `gorm:"column:last_post_dialysis_other" json:"last_post_dialysis_other"`
267
-	SymptomBeforeDialysisOther     string  `gorm:"column:symptom_before_dialysis_other" json:"symptom_before_dialysis_other"`
268
-	DialysisInterphaseOther        string  `gorm:"column:dialysis_interphase_other" json:"dialysis_interphase_other"`
269
-	CatheterSuture                 string  `gorm:"column:catheter_suture" json:"catheter_suture" form:"catheter_suture"`
270
-	CatheterSutureOther            string  `gorm:"column:catheter_suture_other" json:"catheter_suture_other" form:"catheter_suture_other"`
271
-	UrineVolume                    float64 `gorm:"column:urine_volume" json:"urine_volume" form:"urine_volume"`
272
-	Edema                          string  `gorm:"column:edema" json:"edema" form:"edema"`
273
-}
274
-
275
-func (AssessmentBeforeDislysisVM) TableName() string {
276
-	return "xt_assessment_before_dislysis"
277
-}
278
-
279
-type AssessmentAfterDislysisVM struct {
280
-	ID                              int64   `gorm:"column:id" json:"id"`
281
-	PatientID                       int64   `gorm:"column:patient_id" json:"patient_id"`
282
-	AssessmentDate                  int64   `gorm:"column:assessment_date" json:"assessment_date"`
283
-	Temperature                     float64 `gorm:"column:temperature" json:"temperature"`
284
-	PulseFrequency                  float64 `gorm:"column:pulse_frequency" json:"pulse_frequency"`
285
-	BreathingRate                   float64 `gorm:"column:breathing_rate" json:"breathing_rate"`
286
-	SystolicBloodPressure           float64 `gorm:"column:systolic_blood_pressure" json:"systolic_blood_pressure"`
287
-	DiastolicBloodPressure          float64 `gorm:"column:diastolic_blood_pressure" json:"diastolic_blood_pressure"`
288
-	BloodPressureType               int64   `gorm:"column:blood_pressure_type" json:"blood_pressure_type"`
289
-	ActualUltrafiltration           float64 `gorm:"column:actual_ultrafiltration" json:"actual_ultrafiltration"`
290
-	ActualDisplacement              float64 `gorm:"column:actual_displacement" json:"actual_displacement"`
291
-	ActualTreatmentHour             int64   `gorm:"column:actual_treatment_hour" json:"actual_treatment_hour"`
292
-	ActualTreatmentMinute           int64   `gorm:"column:actual_treatment_minute" json:"actual_treatment_minute"`
293
-	WeighingWay                     string  `gorm:"column:weighing_way" json:"weighing_way"`
294
-	WeightAfter                     float64 `gorm:"column:weight_after" json:"weight_after"`
295
-	WeightLoss                      float64 `gorm:"column:weight_loss" json:"weight_loss"`
296
-	Cruor                           string  `gorm:"column:cruor" json:"cruor"`
297
-	SymptomAfterDialysis            string  `gorm:"column:symptom_after_dialysis" json:"symptom_after_dialysis"`
298
-	InternalFistula                 string  `gorm:"column:internal_fistula" json:"internal_fistula"`
299
-	Catheter                        string  `gorm:"column:catheter" json:"catheter"`
300
-	Complication                    string  `gorm:"column:complication" json:"complication"`
301
-	Evaluator                       int64   `gorm:"column:evaluator" json:"evaluator"`
302
-	Remark                          string  `gorm:"column:remark" json:"remark"`
303
-	DialysisIntakes                 int64   `gorm:"column:dialysis_intakes" json:"dialysis_intakes"`
304
-	DialysisIntakesFeed             int64   `gorm:"column:dialysis_intakes_feed" json:"dialysis_intakes_feed"`
305
-	DialysisIntakesTransfusion      int64   `gorm:"column:dialysis_intakes_transfusion" json:"dialysis_intakes_transfusion"`
306
-	DialysisIntakesBloodTransfusion int64   `gorm:"column:dialysis_intakes_blood_transfusion" json:"dialysis_intakes_blood_transfusion"`
307
-	DialysisIntakesWashpipe         int64   `gorm:"column:dialysis_intakes_washpipe" json:"dialysis_intakes_washpipe"`
308
-	Creater                         int64   `gorm:"column:creater" json:"creater"`
309
-	Modifier                        int64   `gorm:"column:modifier" json:"modifier"`
310
-	BloodAccessPartId               int64   `gorm:"column:blood_access_part_id" json:"blood_access_part_id"`
311
-	BloodAccessPartOperaId          int64   `gorm:"column:blood_access_part_opera_id" json:"blood_access_part_opera_id"`
312
-	PuncturePointOozingBlood        int64   `gorm:"column:puncture_point_oozing_blood" json:"puncture_point_oozing_blood"`
313
-	PuncturePointHaematoma          int64   `gorm:"column:puncture_point_haematoma" json:"puncture_point_haematoma"`
314
-	InternalFistulaTremorAc         int64   `gorm:"column:internal_fistula_tremor_ac" json:"internal_fistula_tremor_ac"`
315
-	PatientGose                     int64   `gorm:"column:patient_gose" json:"patient_gose"`
316
-	InpatientDepartment             string  `gorm:"column:inpatient_department" json:"inpatient_department"`
317
-	ObservationContent              string  `gorm:"column:observation_content" json:"observation_content"`
318
-	ObservationContentOther         string  `gorm:"column:observation_content_other" json:"observation_content_other"`
319
-	DryWeight                       float64 `gorm:"column:dry_weight" json:"dry_weight"`
320
-	DialysisProcess                 int64   `gorm:"column:dialysis_process" json:"dialysis_process"`
321
-	InAdvanceMinute                 float64 `gorm:"column:in_advance_minute" json:"in_advance_minute"`
322
-	InAdvanceReason                 string  `gorm:"column:in_advance_reason" json:"in_advance_reason"`
323
-	HemostasisMinute                int64   `gorm:"column:hemostasis_minute" json:"hemostasis_minute"`
324
-	HemostasisOpera                 int64   `gorm:"column:hemostasis_opera" json:"hemostasis_opera"`
325
-	TremorNoise                     int64   `gorm:"column:tremor_noise" json:"tremor_noise"`
326
-	DisequilibriumSyndrome          int64   `gorm:"column:disequilibrium_syndrome" json:"disequilibrium_syndrome"`
327
-	DisequilibriumSyndromeOption    string  `gorm:"column:disequilibrium_syndrome_option" json:"disequilibrium_syndrome_option"`
328
-	ArterialTube                    int64   `gorm:"column:arterial_tube" json:"arterial_tube"`
329
-	IntravenousTube                 int64   `gorm:"column:intravenous_tube" json:"intravenous_tube"`
330
-	Dialyzer                        int64   `gorm:"column:dialyzer" json:"dialyzer"`
331
-	InAdvanceReasonOther            string  `gorm:"column:in_advance_reason_other" json:"in_advance_reason_other"`
332
-	AssessmentTime                  int64   `gorm:"column:assessment_time" json:"assessment_time"`
333
-	AssessmentDoctor                int64   `gorm:"column:assessment_doctor" json:"assessment_doctor"`
334
-	IsEat                           int64   `gorm:"column:is_eat" json:"is_eat"`
335
-	DialysisIntakesUnit             int64   `gorm:"column:dialysis_intakes_unit" json:"dialysis_intakes_unit"`
336
-	CvcA                            float64 `gorm:"column:cvc_a" json:"cvc_a" form:"cvc_a"`
337
-	CvcV                            float64 `gorm:"column:cvc_v" json:"cvc_v" form:"cvc_v"`
338
-	Channel                         int64   `gorm:"column:channel" json:"channel" form:"channel"`
339
-	ReturnBlood                     int64   `gorm:"column:return_blood" json:"return_blood" form:"return_blood"`
340
-	RehydrationVolume               int64   `gorm:"column:rehydration_volume" json:"rehydration_volume" form:"rehydration_volume"`
341
-	DialysisDuring                  int64   `gorm:"column:dialysis_during" json:"dialysis_during" form:"dialysis_during"`
342
-	StrokeVolume                    int64   `gorm:"column:stroke_volume" json:"stroke_volume" form:"stroke_volume"`
343
-	BloodFlow                       int64   `gorm:"column:blood_flow" json:"blood_flow" form:"blood_flow"`
344
-	SealingFluidDispose             string  `gorm:"column:sealing_fluid_dispose" json:"sealing_fluid_dispose" form:"sealing_fluid_dispose"`
345
-	SealingFluidSpecial             string  `gorm:"column:sealing_fluid_special" json:"sealing_fluid_special" form:"sealing_fluid_special"`
346
-}
347
-
348
-func (AssessmentAfterDislysisVM) TableName() string {
349
-	return "xt_assessment_after_dislysis"
350
-}
351
-
352
-type XtAssessmentAfterDislysisVM struct {
353
-	ID                              int64   `gorm:"column:id" json:"id"`
354
-	PatientID                       int64   `gorm:"column:patient_id" json:"patient_id"`
355
-	AssessmentDate                  int64   `gorm:"column:assessment_date" json:"assessment_date"`
356
-	Temperature                     float64 `gorm:"column:temperature" json:"temperature"`
357
-	PulseFrequency                  float64 `gorm:"column:pulse_frequency" json:"pulse_frequency"`
358
-	BreathingRate                   float64 `gorm:"column:breathing_rate" json:"breathing_rate"`
359
-	SystolicBloodPressure           float64 `gorm:"column:systolic_blood_pressure" json:"systolic_blood_pressure"`
360
-	DiastolicBloodPressure          float64 `gorm:"column:diastolic_blood_pressure" json:"diastolic_blood_pressure"`
361
-	BloodPressureType               int64   `gorm:"column:blood_pressure_type" json:"blood_pressure_type"`
362
-	ActualUltrafiltration           float64 `gorm:"column:actual_ultrafiltration" json:"actual_ultrafiltration"`
363
-	ActualDisplacement              float64 `gorm:"column:actual_displacement" json:"actual_displacement"`
364
-	ActualTreatmentHour             int64   `gorm:"column:actual_treatment_hour" json:"actual_treatment_hour"`
365
-	ActualTreatmentMinute           int64   `gorm:"column:actual_treatment_minute" json:"actual_treatment_minute"`
366
-	WeighingWay                     string  `gorm:"column:weighing_way" json:"weighing_way"`
367
-	WeightAfter                     float64 `gorm:"column:weight_after" json:"weight_after"`
368
-	WeightLoss                      float64 `gorm:"column:weight_loss" json:"weight_loss"`
369
-	Cruor                           string  `gorm:"column:cruor" json:"cruor"`
370
-	SymptomAfterDialysis            string  `gorm:"column:symptom_after_dialysis" json:"symptom_after_dialysis"`
371
-	InternalFistula                 string  `gorm:"column:internal_fistula" json:"internal_fistula"`
372
-	Catheter                        string  `gorm:"column:catheter" json:"catheter"`
373
-	Complication                    string  `gorm:"column:complication" json:"complication"`
374
-	Evaluator                       int64   `gorm:"column:evaluator" json:"evaluator"`
375
-	Remark                          string  `gorm:"column:remark" json:"remark"`
376
-	DialysisIntakes                 int64   `gorm:"column:dialysis_intakes" json:"dialysis_intakes"`
377
-	DialysisIntakesFeed             int64   `gorm:"column:dialysis_intakes_feed" json:"dialysis_intakes_feed"`
378
-	DialysisIntakesTransfusion      int64   `gorm:"column:dialysis_intakes_transfusion" json:"dialysis_intakes_transfusion"`
379
-	DialysisIntakesBloodTransfusion int64   `gorm:"column:dialysis_intakes_blood_transfusion" json:"dialysis_intakes_blood_transfusion"`
380
-	DialysisIntakesWashpipe         int64   `gorm:"column:dialysis_intakes_washpipe" json:"dialysis_intakes_washpipe"`
381
-	Creater                         int64   `gorm:"column:creater" json:"creater"`
382
-	Modifier                        int64   `gorm:"column:modifier" json:"modifier"`
383
-	BloodAccessPartId               int64   `gorm:"column:blood_access_part_id" json:"blood_access_part_id"`
384
-	BloodAccessPartOperaId          int64   `gorm:"column:blood_access_part_opera_id" json:"blood_access_part_opera_id"`
385
-	PuncturePointOozingBlood        int64   `gorm:"column:puncture_point_oozing_blood" json:"puncture_point_oozing_blood"`
386
-	PuncturePointHaematoma          int64   `gorm:"column:puncture_point_haematoma" json:"puncture_point_haematoma"`
387
-	InternalFistulaTremorAc         int64   `gorm:"column:internal_fistula_tremor_ac" json:"internal_fistula_tremor_ac"`
388
-	PatientGose                     int64   `gorm:"column:patient_gose" json:"patient_gose"`
389
-	InpatientDepartment             string  `gorm:"column:inpatient_department" json:"inpatient_department"`
390
-	ObservationContent              string  `gorm:"column:observation_content" json:"observation_content"`
391
-	ObservationContentOther         string  `gorm:"column:observation_content_other" json:"observation_content_other"`
392
-	DryWeight                       float64 `gorm:"column:dry_weight" json:"dry_weight"`
393
-	DialysisProcess                 int64   `gorm:"column:dialysis_process" json:"dialysis_process"`
394
-	InAdvanceMinute                 float64 `gorm:"column:in_advance_minute" json:"in_advance_minute"`
395
-	InAdvanceReason                 string  `gorm:"column:in_advance_reason" json:"in_advance_reason"`
396
-	HemostasisMinute                int64   `gorm:"column:hemostasis_minute" json:"hemostasis_minute"`
397
-	HemostasisOpera                 int64   `gorm:"column:hemostasis_opera" json:"hemostasis_opera"`
398
-	TremorNoise                     int64   `gorm:"column:tremor_noise" json:"tremor_noise"`
399
-	DisequilibriumSyndrome          int64   `gorm:"column:disequilibrium_syndrome" json:"disequilibrium_syndrome"`
400
-	DisequilibriumSyndromeOption    string  `gorm:"column:disequilibrium_syndrome_option" json:"disequilibrium_syndrome_option"`
401
-	ArterialTube                    int64   `gorm:"column:arterial_tube" json:"arterial_tube"`
402
-	IntravenousTube                 int64   `gorm:"column:intravenous_tube" json:"intravenous_tube"`
403
-	Dialyzer                        int64   `gorm:"column:dialyzer" json:"dialyzer"`
404
-	InAdvanceReasonOther            string  `gorm:"column:in_advance_reason_other" json:"in_advance_reason_other"`
405
-	AssessmentTime                  int64   `gorm:"column:assessment_time" json:"assessment_time"`
406
-	AssessmentDoctor                int64   `gorm:"column:assessment_doctor" json:"assessment_doctor"`
407
-	IsEat                           int64   `gorm:"column:is_eat" json:"is_eat"`
408
-	DialysisIntakesUnit             int64   `gorm:"column:dialysis_intakes_unit" json:"dialysis_intakes_unit"`
409
-	CvcA                            float64 `gorm:"column:cvc_a" json:"cvc_a" form:"cvc_a"`
410
-	CvcV                            float64 `gorm:"column:cvc_v" json:"cvc_v" form:"cvc_v"`
411
-	Channel                         int64   `gorm:"column:channel" json:"channel" form:"channel"`
412
-}
413
-
414
-func (XtAssessmentAfterDislysisVM) TableName() string {
415
-	return "xt_assessment_after_dislysis"
416
-}
417
-
418
-type ReceiveAssessmentVM struct {
419
-	ID                           int64  `gorm:"column:id" json:"id"`
420
-	PatientId                    int64  `gorm:"column:patient_id" json:"patient_id"`
421
-	RecordDate                   int64  `gorm:"column:record_date" json:"record_date"`
422
-	Way                          int64  `gorm:"column:way" json:"way"`
423
-	Consciousness                int64  `gorm:"column:consciousness" json:"consciousness" form:"consciousness"`
424
-	Appetite                     int64  `gorm:"column:appetite" json:"appetite"`
425
-	Condition                    int64  `gorm:"column:condition" json:"condition"`
426
-	Posture                      int64  `gorm:"column:posture" json:"posture"`
427
-	SickCondition                int64  `gorm:"column:sick_condition" json:"sick_condition"`
428
-	DangerLevel                  int64  `gorm:"column:danger_level" json:"danger_level"`
429
-	Intake                       int64  `gorm:"column:intake" json:"intake"`
430
-	Nutrition                    int64  `gorm:"column:nutrition" json:"nutrition"`
431
-	PsychologicalAssessment      int64  `gorm:"column:psychological_assessment" json:"psychological_assessment"`
432
-	PsychologicalAssessmentOther string `gorm:"column:psychological_assessment_other" json:"psychological_assessment_other"`
433
-	Score                        string `gorm:"column:score" json:"score"`
434
-	SickConditionOther           string `gorm:"column:sick_condition_other" json:"sick_condition_other"`
435
-	Precaution                   string `gorm:"column:precaution" json:"precaution"`
436
-	PrecautionOther              string `gorm:"column:precaution_other" json:"precaution_other"`
437
-	PsychologicalOther           string `gorm:"column:psychological_other" json:"psychological_other"`
438
-	IsPrecaution                 int64  `gorm:"column:is_precaution" json:"is_precaution"`
439
-	AdmissionNumber              string `gorm:"column:admission_number" json:"admission_number" form:"admission_number"`
440
-}
441
-
442
-func (ReceiveAssessmentVM) TableName() string {
443
-	return "xt_receive_treatment_asses"
444
-}
445
-
446
-type XtReceiveTreatmentAsses struct {
447
-	ID                           int64  `gorm:"column:id" json:"id" form:"id"`
448
-	Way                          int64  `gorm:"column:way" json:"way" form:"way"`
449
-	Consciousness                int64  `gorm:"column:consciousness" json:"consciousness" form:"consciousness"`
450
-	Appetite                     int64  `gorm:"column:appetite" json:"appetite" form:"appetite"`
451
-	Condition                    int64  `gorm:"column:condition" json:"condition" form:"condition"`
452
-	Creater                      int64  `gorm:"column:creater" json:"creater" form:"creater"`
453
-	Posture                      int64  `gorm:"column:posture" json:"posture" form:"posture"`
454
-	CreatedTime                  int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
455
-	UpdateTime                   int64  `gorm:"column:update_time" json:"update_time" form:"update_time"`
456
-	RecordId                     int64  `gorm:"column:record_id" json:"record_id" form:"record_id"`
457
-	RecordDate                   int64  `gorm:"column:record_date" json:"record_date" form:"record_date"`
458
-	Modifier                     int64  `gorm:"column:modifier" json:"modifier" form:"modifier"`
459
-	Status                       int64  `gorm:"column:status" json:"status" form:"status"`
460
-	UserOrgId                    int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
461
-	PatientId                    int64  `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
462
-	SickCondition                int64  `gorm:"column:sick_condition" json:"sick_condition" form:"sick_condition"`
463
-	SickConditionOther           string `gorm:"column:sick_condition_other" json:"sick_condition_other" form:"sick_condition_other"`
464
-	DangerLevel                  int64  `gorm:"column:danger_level" json:"danger_level" form:"danger_level"`
465
-	Intake                       int64  `gorm:"column:intake" json:"intake" form:"intake"`
466
-	Nutrition                    int64  `gorm:"column:nutrition" json:"nutrition" form:"nutrition"`
467
-	PsychologicalAssessment      int64  `gorm:"column:psychological_assessment" json:"psychological_assessment" form:"psychological_assessment"`
468
-	PsychologicalAssessmentOther string `gorm:"column:psychological_assessment_other" json:"psychological_assessment_other" form:"psychological_assessment_other"`
469
-	IsPrecaution                 int64  `gorm:"column:is_precaution" json:"is_precaution" form:"is_precaution"`
470
-	Score                        string `gorm:"column:score" json:"score" form:"score"`
471
-	Precaution                   string `gorm:"column:precaution" json:"precaution" form:"precaution"`
472
-	PrecautionOther              string `gorm:"column:precaution_other" json:"precaution_other" form:"precaution_other"`
473
-	PsychologicalOther           string `gorm:"column:psychological_other" json:"psychological_other" form:"psychological_other"`
474
-	AdmissionNumber              string `gorm:"column:admission_number" json:"admission_number" form:"admission_number"`
475
-}
476
-
477
-func (XtReceiveTreatmentAsses) TableName() string {
478
-	return "xt_receive_treatment_asses"
479
-}
480
-
481
-type MonitoringRecordVM struct {
482
-	ID                        int64   `gorm:"column:id" json:"id"`
483
-	PatientID                 int64   `gorm:"column:patient_id" json:"patient_id"`
484
-	MonitoringDate            int64   `gorm:"column:monitoring_date" json:"monitoring_date"`
485
-	OperateTime               int64   `gorm:"column:operate_time" json:"operate_time"`
486
-	PulseFrequency            float64 `gorm:"column:pulse_frequency" json:"pulse_frequency"`
487
-	BreathingRate             float64 `gorm:"column:breathing_rate" json:"breathing_rate"`
488
-	SystolicBloodPressure     float64 `gorm:"column:systolic_blood_pressure" json:"systolic_blood_pressure"`
489
-	DiastolicBloodPressure    float64 `gorm:"column:diastolic_blood_pressure" json:"diastolic_blood_pressure"`
490
-	BloodPressureType         int64   `gorm:"column:blood_pressure_type" json:"blood_pressure_type"`
491
-	BloodFlowVolume           float64 `gorm:"column:blood_flow_volume" json:"blood_flow_volume"`
492
-	VenousPressure            float64 `gorm:"column:venous_pressure" json:"venous_pressure"`
493
-	VenousPressureType        int64   `gorm:"column:venous_pressure_type" json:"venous_pressure_type"`
494
-	ArterialPressure          float64 `gorm:"column:arterial_pressure" json:"arterial_pressure"`
495
-	ArterialPressureType      int64   `gorm:"column:arterial_pressure_type" json:"arterial_pressure_type"`
496
-	TransmembranePressure     float64 `gorm:"column:transmembrane_pressure" json:"transmembrane_pressure"`
497
-	TransmembranePressureType int64   `gorm:"column:transmembrane_pressure_type" json:"transmembrane_pressure_type"`
498
-	UltrafiltrationRate       float64 `gorm:"column:ultrafiltration_rate" json:"ultrafiltration_rate"`
499
-	UltrafiltrationVolume     float64 `gorm:"column:ultrafiltration_volume" json:"ultrafiltration_volume"`
500
-	SodiumConcentration       float64 `gorm:"column:sodium_concentration" json:"sodium_concentration"`
501
-	DialysateTemperature      float64 `gorm:"column:dialysate_temperature" json:"dialysate_temperature"`
502
-	Temperature               float64 `gorm:"column:temperature" json:"temperature"`
503
-	ReplacementRate           float64 `gorm:"column:replacement_rate" json:"replacement_rate"`
504
-	DisplacementQuantity      float64 `gorm:"column:displacement_quantity" json:"displacement_quantity"`
505
-	Ktv                       float64 `gorm:"column:ktv" json:"ktv"`
506
-	Symptom                   string  `gorm:"column:symptom" json:"symptom"`
507
-	Dispose                   string  `gorm:"column:dispose" json:"dispose"`
508
-	Result                    string  `gorm:"column:result" json:"result"`
509
-	MonitoringNurse           int64   `gorm:"column:monitoring_nurse" json:"monitoring_nurse"`
510
-	Conductivity              float64 `gorm:"column:conductivity" json:"conductivity"`
511
-	DisplacementFlowQuantity  float64 `gorm:"column:displacement_flow_quantity" json:"displacement_flow_quantity"`
512
-	BloodOxygenSaturation     string  `gorm:"column:blood_oxygen_saturation" json:"blood_oxygen_saturation" form:"blood_oxygen_saturation"`
513
-	Creator                   int64   `gorm:"column:creator" json:"creator" form:"creator"`
514
-	Modify                    int64   `gorm:"column:modify" json:"modify" form:"modify"`
515
-	Heparin                   float64 `gorm:"column:heparin" json:"heparin" form:"heparin"`
516
-}
517
-
518
-func (MonitoringRecordVM) TableName() string {
519
-	return "xt_monitoring_record"
520
-}
521
-
522
-type ScheduleVM struct {
523
-	ID           int64 `gorm:"column:id" json:"id"`
524
-	PatientID    int64 `gorm:"column:patient_id" json:"patient_id"`
525
-	ScheduleDate int64 `gorm:"column:schedule_date" json:"schedule_date"`
526
-	BedID        int64 `gorm:"column:bed_id" json:"bed_id"`
527
-	PartitionId  int64 `gorm:"column:partition_id" json:"partition_id" form:"partition_id"`
528
-
529
-	Patient                  *PatientVM                  `gorm:"ForeignKey:PatientID" json:"patient"`
530
-	DialysisOrder            DialysisOrderVM             `gorm:"ForeignKey:DialysisDate,PatientID;AssociationForeignKey:ScheduleDate,PatientID" json:"dialysis_order"`
531
-	Prescription             PrescriptionVM              `gorm:"ForeignKey:RecordDate,PatientID;AssociationForeignKey:ScheduleDate,PatientID" json:"prescription"`
532
-	ReceiveAssessment        ReceiveAssessmentVM         `gorm:"ForeignKey:RecordDate,PatientID;AssociationForeignKey:ScheduleDate,PatientID" json:"receive_assessment"`
533
-	XtReceiveTreatmentAsses  *XtReceiveTreatmentAsses    `gorm:"ForeignKey:RecordDate,PatientID;AssociationForeignKey:ScheduleDate,PatientID" json:"xt_receive_assessment"`
534
-	AssessmentBeforeDislysis AssessmentBeforeDislysisVM  `gorm:"ForeignKey:AssessmentDate,PatientID;AssociationForeignKey:ScheduleDate,PatientID" json:"assessment_before_dislysis"`
535
-	AssessmentAfterDislysis  AssessmentAfterDislysisVM   `gorm:"ForeignKey:AssessmentDate,PatientID;AssociationForeignKey:ScheduleDate,PatientID" json:"assessment_after_dislysis"`
536
-	MonitoringRecords        []*MonitoringRecordVM       `gorm:"ForeignKey:MonitoringDate,PatientID;AssociationForeignKey:ScheduleDate,PatientID" json:"monitor_records"`
537
-	DeviceNumber             *DeviceNumberVM             `gorm:"ForeignKey:BedID" json:"device_number"`
538
-	DeviceZone               *DeviceZoneVM               `gorm:"ForeignKey:PartitionId" json:"device_zone"`
539
-	Advices                  []*DoctorAdviceVM           `gorm:"ForeignKey:RecordDate,PatientID;AssociationForeignKey:ScheduleDate,PatientId" json:"advices"`
540
-	DoubleCheck              *DoubleCheckVM              `gorm:"ForeignKey:CheckDate,PatientID;AssociationForeignKey:ScheduleDate,PatientID" json:"check"`
541
-	Summer                   *SummerVM                   `gorm:"ForeignKey:AssessmentDate,PatientID;AssociationForeignKey:ScheduleDate,PatientID" json:"summer"`
542
-	LastAfterWeight          XtAssessmentAfterDislysisVM `gorm:"ForeignKey:PatientID;AssociationForeignKey:PatientID" json:"lastafterweight"`
543
-}
544
-
545
-func (ScheduleVM) TableName() string {
546
-	return "xt_schedule"
547
-}
548
-
549
-type MedicalStaffVM struct {
550
-	Id       int64  `json:"id"`
551
-	Name     string `json:"name"`
552
-	UserType int64  `json:"user_type"`
553
-	ES_URL   string `gorm:"column:es_url" json:"es_url"`
554
-}
555
-
556
-type MedicalStaffElecSignature struct {
557
-	ID      int64  `gorm:"column:id" json:"id"`
558
-	Creator int64  `gorm:"column:creator" json:"creator"`
559
-	Url     string `gorm:"column:url" json:"url"`
560
-}
561
-
562
-func (MedicalStaffElecSignature) TableName() string {
563
-	return "sgj_user_admin_electronic_signature"
564
-}
565
-
566
-type XtDoctorAdvice struct {
567
-	ID                    int64   `gorm:"column:id" json:"id" form:"id"`
568
-	UserOrgId             int64   `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
569
-	PatientId             int64   `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
570
-	AdviceType            int64   `gorm:"column:advice_type" json:"advice_type" form:"advice_type"`
571
-	AdviceDate            int64   `gorm:"column:advice_date" json:"advice_date" form:"advice_date"`
572
-	StartTime             int64   `gorm:"column:start_time" json:"start_time" form:"start_time"`
573
-	AdviceName            string  `gorm:"column:advice_name" json:"advice_name" form:"advice_name"`
574
-	AdviceDesc            string  `gorm:"column:advice_desc" json:"advice_desc" form:"advice_desc"`
575
-	ReminderDate          int64   `gorm:"column:reminder_date" json:"reminder_date" form:"reminder_date"`
576
-	SingleDose            float64 `gorm:"column:single_dose" json:"single_dose" form:"single_dose"`
577
-	SingleDoseUnit        string  `gorm:"column:single_dose_unit" json:"single_dose_unit" form:"single_dose_unit"`
578
-	PrescribingNumber     float64 `gorm:"column:prescribing_number" json:"prescribing_number" form:"prescribing_number"`
579
-	PrescribingNumberUnit string  `gorm:"column:prescribing_number_unit" json:"prescribing_number_unit" form:"prescribing_number_unit"`
580
-	DeliveryWay           string  `gorm:"column:delivery_way" json:"delivery_way" form:"delivery_way"`
581
-	ExecutionFrequency    string  `gorm:"column:execution_frequency" json:"execution_frequency" form:"execution_frequency"`
582
-	AdviceDoctor          int64   `gorm:"column:advice_doctor" json:"advice_doctor" form:"advice_doctor"`
583
-	Status                int64   `gorm:"column:status" json:"status" form:"status"`
584
-	CreatedTime           int64   `gorm:"column:created_time" json:"created_time" form:"created_time"`
585
-	UpdatedTime           int64   `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
586
-	AdviceAffirm          string  `gorm:"column:advice_affirm" json:"advice_affirm" form:"advice_affirm"`
587
-	Remark                string  `gorm:"column:remark" json:"remark" form:"remark"`
588
-	StopTime              int64   `gorm:"column:stop_time" json:"stop_time" form:"stop_time"`
589
-	StopReason            string  `gorm:"column:stop_reason" json:"stop_reason" form:"stop_reason"`
590
-	StopDoctor            int64   `gorm:"column:stop_doctor" json:"stop_doctor" form:"stop_doctor"`
591
-	StopState             int64   `gorm:"column:stop_state" json:"stop_state" form:"stop_state"`
592
-	ParentId              int64   `gorm:"column:parent_id" json:"parent_id" form:"parent_id"`
593
-	ExecutionTime         int64   `gorm:"column:execution_time" json:"execution_time" form:"execution_time"`
594
-	ExecutionStaff        int64   `gorm:"column:execution_staff" json:"execution_staff" form:"execution_staff"`
595
-	ExecutionState        int64   `gorm:"column:execution_state" json:"execution_state" form:"execution_state"`
596
-	Checker               int64   `gorm:"column:checker" json:"checker" form:"checker"`
597
-	RecordDate            int64   `gorm:"column:record_date" json:"record_date" form:"record_date"`
598
-	DialysisOrderId       int64   `gorm:"column:dialysis_order_id" json:"dialysis_order_id" form:"dialysis_order_id"`
599
-	CheckTime             int64   `gorm:"column:check_time" json:"check_time" form:"check_time"`
600
-	CheckState            int64   `gorm:"column:check_state" json:"check_state" form:"check_state"`
601
-	DrugSpec              float64 `gorm:"column:drug_spec" json:"drug_spec" form:"drug_spec"`
602
-	DrugSpecUnit          string  `gorm:"column:drug_spec_unit" json:"drug_spec_unit" form:"drug_spec_unit"`
603
-	Groupno               int64   `gorm:"column:groupno" json:"groupno" form:"groupno"`
604
-	RemindType            int64   `gorm:"column:remind_type" json:"remind_type" form:"remind_type"`
605
-	FrequencyType         int64   `gorm:"column:frequency_type" json:"frequency_type" form:"frequency_type"`
606
-	DayCount              int64   `gorm:"column:day_count" json:"day_count" form:"day_count"`
607
-	WeekDay               string  `gorm:"column:week_day" json:"week_day" form:"week_day"`
608
-	TemplateId            string  `gorm:"column:template_id" json:"template_id" form:"template_id"`
609
-}
610
-
611
-func (XtDoctorAdvice) TableName() string {
612
-	return "xt_doctor_advice"
613
-}
614
-
615
-type DoctorAdviceVM struct {
616
-	ID                    int64   `gorm:"column:id" json:"id" form:"id"`
617
-	GroupNo               int64   `gorm:"column:groupno" json:"groupno" form:"groupno"`
618
-	UserOrgId             int64   `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
619
-	PatientId             int64   `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
620
-	AdviceType            int64   `gorm:"column:advice_type" json:"advice_type" form:"advice_type"`
621
-	AdviceDate            int64   `gorm:"column:advice_date" json:"advice_date" form:"advice_date"`
622
-	StartTime             int64   `gorm:"column:start_time" json:"start_time" form:"start_time"`
623
-	AdviceName            string  `gorm:"column:advice_name" json:"advice_name" form:"advice_name"`
624
-	AdviceDesc            string  `gorm:"column:advice_desc" json:"advice_desc" form:"advice_desc"`
625
-	ReminderDate          int64   `gorm:"column:reminder_date" json:"reminder_date" form:"reminder_date"`
626
-	SingleDose            float64 `gorm:"column:single_dose" json:"single_dose" form:"single_dose"`
627
-	SingleDoseUnit        string  `gorm:"column:single_dose_unit" json:"single_dose_unit" form:"single_dose_unit"`
628
-	DrugSpec              float64 `gorm:"column:drug_spec" json:"drug_spec" form:"drug_spec"`
629
-	DrugSpecUnit          string  `gorm:"column:drug_spec_unit" json:"drug_spec_unit" form:"drug_spec_unit"`
630
-	PrescribingNumber     float64 `gorm:"column:prescribing_number" json:"prescribing_number" form:"prescribing_number"`
631
-	PrescribingNumberUnit string  `gorm:"column:prescribing_number_unit" json:"prescribing_number_unit" form:"prescribing_number_unit"`
632
-	DeliveryWay           string  `gorm:"column:delivery_way" json:"delivery_way" form:"delivery_way"`
633
-	ExecutionFrequency    string  `gorm:"column:execution_frequency" json:"execution_frequency" form:"execution_frequency"`
634
-	AdviceDoctor          int64   `gorm:"column:advice_doctor" json:"advice_doctor" form:"advice_doctor"`
635
-	Status                int64   `gorm:"column:status" json:"status" form:"status"`
636
-	CreatedTime           int64   `gorm:"column:created_time" json:"created_time" form:"created_time"`
637
-	UpdatedTime           int64   `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
638
-	AdviceAffirm          string  `gorm:"column:advice_affirm" json:"advice_affirm" form:"advice_affirm"`
639
-	Remark                string  `gorm:"column:remark" json:"remark" form:"remark"`
640
-	StopTime              int64   `gorm:"column:stop_time" json:"stop_time" form:"stop_time"`
641
-	StopReason            string  `gorm:"column:stop_reason" json:"stop_reason" form:"stop_reason"`
642
-	StopDoctor            int64   `gorm:"column:stop_doctor" json:"stop_doctor" form:"stop_doctor"`
643
-	StopState             int64   `gorm:"column:stop_state" json:"stop_state" form:"stop_state"`
644
-	ParentId              int64   `gorm:"column:parent_id" json:"parent_id" form:"parent_id"`
645
-	ExecutionTime         int64   `gorm:"column:execution_time" json:"execution_time" form:"execution_time"`
646
-	ExecutionStaff        int64   `gorm:"column:execution_staff" json:"execution_staff" form:"execution_staff"`
647
-	ExecutionState        int64   `gorm:"column:execution_state" json:"execution_state" form:"execution_state"`
648
-	Checker               int64   `gorm:"column:checker" json:"checker" form:"checker"`
649
-	RecordDate            int64   `gorm:"column:record_date" json:"record_date"`
650
-	DialysisOrderId       int64   `gorm:"column:dialysis_order_id" json:"dialysis_order_id"`
651
-	CheckTime             int64   `gorm:"column:check_time" json:"check_time" form:"check_time"`
652
-	CheckState            int64   `gorm:"column:check_state" json:"check_state" form:"check_state"`
653
-	AdviceId              int64   `gorm:"-"`
654
-	RemindType            int64   `gorm:"column:remind_type" json:"remind_type"`
655
-	FrequencyType         int64   `gorm:"column:frequency_type" json:"frequency_type"`
656
-	DayCount              int64   `gorm:"column:day_count" json:"day_count"`
657
-	WeekDay               string  `gorm:"column:week_day" json:"week_day"`
658
-	TemplateId            string  `gorm:"column:template_id" json:"template_id"`
659
-	Modifier              int64   `gorm:"column:modifier" json:"modifier" form:"modifier"`
660
-}
661
-
662
-func (DoctorAdviceVM) TableName() string {
663
-	return "xt_doctor_advice"
664
-}
665
-
666
-type DoubleCheckVM struct {
667
-	ID                         int64  `gorm:"column:id" json:"id"`
668
-	UserOrgId                  int64  `gorm:"column:user_org_id" json:"user_org_id"`
669
-	PatientId                  int64  `gorm:"column:patient_id" json:"patient_id"`
670
-	DialysisOrderId            int64  `gorm:"column:dialysis_order_id" json:"dialysis_order_id"`
671
-	CheckDate                  int64  `gorm:"column:check_date" json:"check_date"`
672
-	DialysisItemCheck          int64  `gorm:"column:dialysis_item_check" json:"dialysis_item_check"`
673
-	DialysisItemDesc           string `gorm:"column:dialysis_item_desc" json:"dialysis_item_desc"`
674
-	DialysisParameterCheck     int64  `gorm:"column:dialysis_parameter_check" json:"dialysis_parameter_check"`
675
-	DialysisParameterDesc      string `gorm:"column:dialysis_parameter_desc" json:"dialysis_parameter_desc"`
676
-	VascularAccessVerification int64  `gorm:"column:vascular_access_verification" json:"vascular_access_verification"`
677
-	VascularAccessDesc         string `gorm:"column:vascular_access_desc" json:"vascular_access_desc"`
678
-	PipelineConnectionCheck    int64  `gorm:"column:pipeline_connection_check" json:"pipeline_connection_check"`
679
-	PipelineConnectionDesc     string `gorm:"column:pipeline_connection_desc" json:"pipeline_connection_desc"`
680
-	Collator                   int64  `gorm:"column:collator" json:"collator"`
681
-	Status                     int64  `gorm:"column:status" json:"status"`
682
-	CreatedTime                int64  `gorm:"column:created_time" json:"created_time"`
683
-	UpdatedTime                int64  `gorm:"column:updated_time" json:"updated_time"`
684
-	Creater                    int64  `gorm:"column:creater" json:"creater"`
685
-	Modifier                   int64  `gorm:"column:modifier" json:"modifier"`
686
-	CheckTime                  int64  `gorm:"column:check_time" json:"check_time"`
687
-	FirstCheckTime             int64  `gorm:"column:first_check_time" json:"first_check_time"`
688
-}
689
-
690
-func (DoubleCheckVM) TableName() string {
691
-	return "xt_double_check"
692
-}
693
-
694
-type SummerVM struct {
695
-	ID                int64  `gorm:"column:id" json:"id"`
696
-	UserOrgId         int64  `gorm:"column:user_org_id" json:"user_org_id"`
697
-	PatientId         int64  `gorm:"column:patient_id" json:"patient_id"`
698
-	AssessmentDate    int64  `gorm:"column:assessment_date" json:"assessment_date"`
699
-	DialysisOrderId   int64  `gorm:"column:dialysis_order_id" json:"dialysis_order_id"`
700
-	Mission           string `gorm:"column:mission" json:"mission"`
701
-	DialysisSummary   string `gorm:"column:dialysis_summary" json:"dialysis_summary"`
702
-	Change            int64  `gorm:"column:change" json:"change"`
703
-	SjNurse           int64  `gorm:"column:sj_nurse" json:"sj_nurse"`
704
-	ZlNurse           int64  `gorm:"column:zl_nurse" json:"zl_nurse"`
705
-	HdNurse           int64  `gorm:"column:hd_nurse" json:"hd_nurse"`
706
-	XjNurse           int64  `gorm:"column:xj_nurse" json:"xj_nurse"`
707
-	ZlDoctor          int64  `gorm:"column:zl_doctor" json:"zl_doctor"`
708
-	ChannelImage      string `gorm:"column:channel_image" json:"channel_image"`
709
-	Puncture          string `gorm:"column:puncture" json:"puncture"`
710
-	PunctureNeedle    string `gorm:"column:puncture_needle" json:"puncture_needle"`
711
-	PunctureDirection string `gorm:"column:puncture_direction" json:"puncture_direction"`
712
-	Status            int64  `gorm:"column:status" json:"status"`
713
-	CreatedTime       int64  `gorm:"column:created_time" json:"created_time"`
714
-	UpdatedTime       int64  `gorm:"column:updated_time" json:"updated_time"`
715
-	Creater           int64  `gorm:"column:creater" json:"creater"`
716
-	Modifier          int64  `gorm:"column:modifier" json:"modifier"`
717
-	NursingRecord     string `gorm:"column:nursing_record" json:"nursing_record" form:"nursing_record"`
718
-	SpecialRecord     string `gorm:"column:special_record" json:"special_record" form:"special_record"`
719
-}
720
-
721
-func (SummerVM) TableName() string {
722
-	return "xt_treatment_summary"
723
-}

+ 0 - 188
models/service/print_data_service/schedule_dialysis/print_schedule_dialysis_service.go Просмотреть файл

@@ -1,188 +0,0 @@
1
-package schedule_dialysis
2
-
3
-import (
4
-	"XT_New/models"
5
-	p_service "XT_New/service"
6
-	"XT_New/utils"
7
-	"fmt"
8
-	"time"
9
-
10
-	"github.com/jinzhu/gorm"
11
-)
12
-
13
-func GetSchedules(orgID int64, schIDs []string) ([]*ScheduleVM, error) {
14
-	recordDateStr := time.Now().Format("2006-01-02")
15
-	recordDate, _ := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
16
-	var schedules []*ScheduleVM
17
-	db := p_service.XTReadDB()
18
-	err := db.Model(&ScheduleVM{}).
19
-		Preload("Patient", "user_org_id = ? AND status = 1", orgID).
20
-		Preload("DialysisOrder", func(db *gorm.DB) *gorm.DB {
21
-			return db.Where("user_org_id = ? AND status = 1", orgID).Preload("DeviceNumber", "org_id = ? AND status = 1", orgID)
22
-		}).
23
-		Preload("Prescription", "user_org_id = ? AND status = 1", orgID).
24
-		Preload("ReceiveAssessment", "user_org_id = ? AND status = 1", orgID).
25
-		Preload("XtReceiveTreatmentAsses", "user_org_id = ? AND status = 1", orgID).
26
-		Preload("AssessmentBeforeDislysis", func(db *gorm.DB) *gorm.DB {
27
-			return db.Where("user_org_id = ? AND status = 1", orgID)
28
-		}).
29
-		Preload("AssessmentAfterDislysis", "user_org_id = ? AND status = 1", orgID).
30
-		Preload("LastAfterWeight", func(db *gorm.DB) *gorm.DB {
31
-			return db.Where("user_org_id = ? and status = 1 and assessment_date < ?", orgID, recordDate.Unix())
32
-		}).Preload("MonitoringRecords", func(db *gorm.DB) *gorm.DB {
33
-		return db.Where("user_org_id = ? AND status = 1", orgID).
34
-			Order("operate_time asc")
35
-	}).
36
-		Preload("DeviceNumber", "org_id = ? AND status = 1", orgID).
37
-		Preload("DeviceZone", "org_id = ? AND status = 1", orgID).
38
-		Preload("DoubleCheck", "user_org_id = ? AND status = 1", orgID).
39
-		Preload("Summer", "user_org_id = ? AND status = 1", orgID).
40
-		Preload("Advices", func(db *gorm.DB) *gorm.DB {
41
-			return db.Select("id, user_org_id, patient_id, advice_type, advice_date, record_date, start_time, drug_spec_unit,advice_name,advice_desc, reminder_date, drug_spec, drug_spec_unit, single_dose, single_dose_unit, prescribing_number, prescribing_number_unit, delivery_way, execution_frequency, advice_doctor, status, created_time,updated_time, advice_affirm, remark, stop_time, stop_reason, stop_doctor, stop_state, parent_id, execution_time, execution_staff, execution_state, checker, check_state, check_time, groupno, IF(parent_id > 0, parent_id, id) as advice_order").
42
-				Where("user_org_id = ? AND advice_type = 2 AND status = 1", orgID).
43
-				Order("start_time asc, groupno desc, advice_order desc, id asc")
44
-		}).
45
-		Where("user_org_id = ? AND status = 1 AND id in (?)", orgID, schIDs).
46
-		Find(&schedules).
47
-		Error
48
-	if err != nil {
49
-		return nil, err
50
-	}
51
-	for _, item := range schedules {
52
-		dialysis_count, _ := GetDialysisOrderCount(orgID, item.PatientID, item.ScheduleDate)
53
-		fmt.Println(dialysis_count)
54
-		item.Patient.TotalDialysis = dialysis_count
55
-		fmt.Println(item.Patient.TotalDialysis)
56
-
57
-	}
58
-	return schedules, nil
59
-}
60
-
61
-func GetMedicalStaffs(orgID int64, appID int64) ([]*MedicalStaffVM, error) {
62
-	var staffs []*MedicalStaffVM
63
-	db := p_service.UserReadDB()
64
-	// err := db.Table("sgj_user_admin_role as uar").
65
-	// 	Joins("JOIN sgj_user_admin as ua ON ua.id = uar.admin_user_id").
66
-	// 	Joins("LEFT JOIN sgj_user_admin_electronic_signature as es ON es.creator = uar.admin_user_id and es.status = 1").
67
-	// 	Where("uar.status = 1 and uar.org_id = ? and uar.app_id = ? and uar.user_type IN (2,3) and ua.status = 1", orgID, appID).
68
-	// 	Where("uar.status = 1 and uar.org_id = ? and uar.app_id = ? and ua.status = 1", orgID, appID).
69
-	// 	Select("ua.id, uar.user_name as name, uar.user_type, es.url as es_url").
70
-	// 	Scan(&staffs).
71
-	// 	Error
72
-
73
-	err := db.Table("sgj_user_admin_electronic_signature").
74
-		Where("org_id=? and app_id=? and status=1", orgID, appID).
75
-		Select("creator as id, url as es_url").Scan(&staffs).Error
76
-
77
-	if err != nil {
78
-		return nil, err
79
-	}
80
-	return staffs, nil
81
-}
82
-
83
-type AdminUserList struct {
84
-	Id       int64  `json:"id"`
85
-	Name     string `json:"name"`
86
-	UserType int64  `json:"user_type"`
87
-}
88
-type AdminUserListTwo struct {
89
-	Id       int64  `json:"id"`
90
-	Name     string `json:"name"`
91
-	UserType int64  `json:"user_type"`
92
-	Url      string `json:"url"`
93
-}
94
-
95
-func GetAllAdminUsers(orgId int64, appid int64) (list []*AdminUserList, err error) {
96
-	db := p_service.UserReadDB()
97
-	err = db.Table("sgj_user_admin_role as uar").Joins("JOIN sgj_user_admin as ua ON ua.id = uar.admin_user_id").Where("uar.status=1 and uar.org_id=? and uar.app_id =? and ua.status=1", orgId, appid).Select("ua.id, uar.user_name as name, uar.user_type").Scan(&list).Error
98
-	return
99
-}
100
-
101
-func GetAllName(orgId int64, appid int64) (list []AdminUserListTwo, err error) {
102
-	db := p_service.UserReadDB()
103
-	err = db.Table("sgj_user_admin_role as uar").Joins("left join sgj_user_admin as ua on ua.id = uar.admin_user_id").Joins("left join sgj_user_admin_electronic_signature  as e on e.creator = uar.admin_user_id").Where("uar.status=1 and uar.org_id=? and uar.app_id =? and ua.status=1 and e.status = 1 and e.org_id = ? and e.app_id = ?", orgId, appid, orgId, appid).Select("ua.id, uar.user_name as name, uar.user_type,e.url").Scan(&list).Error
104
-	return
105
-}
106
-
107
-func GetPatientCoursesRecords(orgID int64, id int64) (records models.PatientDiseaseCourse, err error) {
108
-	db := p_service.XTReadDB()
109
-	err = db.Model(&models.PatientDiseaseCourse{}).Where("org_id = ? and id = ? and status = 1", orgID, id).Find(&records).Error
110
-	return
111
-}
112
-
113
-func FindPatientWithDeviceById(orgID int64, patient_id int64, time int64) (patient models.SchedualPatient2, err error) {
114
-	db := p_service.XTReadDB()
115
-
116
-	err = db.Preload("DialysisSchedule", func(db *gorm.DB) *gorm.DB {
117
-		return db.Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
118
-			Preload("DeviceZone", "status = 1 AND org_id = ?", orgID).
119
-			Where("user_org_id = ? AND schedule_date = ? ", orgID, time)
120
-	}).Where("user_org_id=? and id = ? and status=1", orgID, patient_id).First(&patient).Error
121
-	return
122
-}
123
-
124
-func GetLastAfterWeight(orgID int64, patientID int64, maxDate int64) (*models.AssessmentAfterDislysis, error) {
125
-	var record models.AssessmentAfterDislysis
126
-	err := p_service.XTReadDB().Model(&models.AssessmentAfterDislysis{}).Where("patient_id = ? and user_org_id = ? and status = 1 and assessment_date < ?", patientID, orgID, maxDate).Order("assessment_date desc").First(&record).Error
127
-	if err != nil {
128
-		if err == gorm.ErrRecordNotFound {
129
-			return nil, nil
130
-		} else {
131
-			return nil, err
132
-		}
133
-	}
134
-	return &record, nil
135
-}
136
-
137
-//func GetAllName(orgid int64,appid int64)(sign,err error){
138
-//
139
-//  p_service.XTReadDB().Model(&sign).Where("org_id = ? and app_id =? and status = 1")
140
-//
141
-//}
142
-
143
-func FindPrintStockGoodInfoByType(types int, startTime int64, end_time int64, orgId int64) (list []*models.StockInfo, err error) {
144
-	db := p_service.XTReadDB()
145
-	db = db.Model(&models.StockInfo{})
146
-	db = db.Where("xt_good_information.org_id = ? AND xt_good_information.status = 1", orgId)
147
-	if types == 1 {
148
-		db = db.Joins("JOIN xt_warehouse_info AS info ON info.good_id=xt_good_information.id AND info.status = 1 AND info.org_id = ?", orgId).Group("xt_good_information.id")
149
-		db = db.Preload("QueryWarehousingInfo", func(db *gorm.DB) *gorm.DB {
150
-			return db.Where("xt_warehouse_info.org_id = ? AND xt_warehouse_info.status = 1", orgId).Joins("JOIN xt_warehouse AS warehouse ON warehouse.id = xt_warehouse_info.warehousing_id AND warehouse.status = 1 AND warehouse.warehousing_time >=? AND warehouse.warehousing_time<= ? AND warehouse.org_id = ?", startTime, end_time, orgId)
151
-		})
152
-	} else if types == 2 {
153
-		db = db.Joins("JOIN xt_sales_return_info AS info ON info.good_id=xt_good_information.id AND info.status = 1 AND info.org_id = ?", orgId).Group("xt_good_information.id")
154
-		db = db.Preload("QuerySalesReturnInfo", func(db *gorm.DB) *gorm.DB {
155
-			return db.Where("xt_sales_return_info.org_id = ? AND xt_sales_return_info.status = 1", orgId).Joins("JOIN xt_sales_return AS sales ON sales.id = xt_sales_return_info.sales_return_id AND sales.status = 1 AND sales.return_time >=? AND sales.return_time<= ? AND sales.org_id = ?", startTime, end_time, orgId)
156
-		})
157
-
158
-	} else if types == 3 {
159
-		db = db.Joins("JOIN xt_warehouse_out_info AS info ON info.good_id=xt_good_information.id AND info.status = 1 AND info.org_id = ?", orgId).Group("xt_good_information.id")
160
-		db = db.Preload("QueryWarehouseOutInfo", func(db *gorm.DB) *gorm.DB {
161
-			return db.Where("xt_warehouse_out_info.org_id = ? AND xt_warehouse_out_info.status = 1", orgId).Joins("JOIN xt_warehouse_out ON xt_warehouse_out.id = xt_warehouse_out_info.warehouse_out_id AND xt_warehouse_out.status = 1 AND xt_warehouse_out.warehouse_out_time >=? AND xt_warehouse_out.warehouse_out_time<= ? AND xt_warehouse_out.org_id = ? ", startTime, end_time, orgId)
162
-		})
163
-
164
-	} else if types == 4 {
165
-
166
-		db = db.Joins("JOIN xt_cancel_stock_info AS info ON info.good_id=xt_good_information.id AND info.status = 1 AND info.org_id = ?", orgId).Group("xt_good_information.id")
167
-		db = db.Preload("QueryCancelStockInfo", func(db *gorm.DB) *gorm.DB {
168
-			return db.Where("xt_cancel_stock_info.org_id = ? AND xt_cancel_stock_info.status = 1", orgId).Joins("JOIN xt_cancel_stock AS cancel ON cancel.id = xt_cancel_stock_info.cancel_stock_id AND cancel.status = 1 AND cancel.return_time >=? AND cancel.return_time<= ? AND cancel.org_id = ?", startTime, end_time, orgId)
169
-		})
170
-
171
-	}
172
-	db = db.Preload("GoodsType", "org_id = ? AND status = 1", orgId)
173
-	err = db.Order("ctime desc").Find(&list).Error
174
-	return
175
-}
176
-
177
-func GetOrgInfoTemplate(orgID int64) (models.GobalTemplate, error) {
178
-
179
-	var templateInfo models.GobalTemplate
180
-	var err error
181
-	err = p_service.XTReadDB().Model(&models.GobalTemplate{}).Where("org_id=? and status=1", orgID).First(&templateInfo).Error
182
-	return templateInfo, err
183
-}
184
-
185
-func GetDialysisOrderCount(orgID int64, patient_id int64, recordDate int64) (count int64, err error) {
186
-	err = p_service.XTReadDB().Model(&models.DialysisOrder{}).Where("dialysis_date <= ? AND status = 1 AND stage = 2 AND user_org_id = ? AND patient_id = ?", recordDate, orgID, patient_id).Count(&count).Error
187
-	return
188
-}

Разница между файлами не показана из-за своего большого размера
+ 0 - 1370
models/service/qcd_service.go


+ 0 - 20
models/service/redis.go Просмотреть файл

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

+ 0 - 34
models/service/regist_service.go Просмотреть файл

@@ -1,34 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/enums"
5
-	"XT_New/models"
6
-	"XT_New/utils"
7
-	"time"
8
-)
9
-
10
-func RegisterSuperAdmin(mobile string, password string) (*models.AdminUser, *enums.SGJError) {
11
-	tx := writeUserDb.Begin()
12
-	now := time.Now().Unix()
13
-	admin := models.AdminUser{
14
-		Mobile:       mobile,
15
-		Password:     password,
16
-		IsSuperAdmin: true,
17
-		Status:       1,
18
-		CreateTime:   now,
19
-		ModifyTime:   now,
20
-	}
21
-	registerSuccess := false
22
-	if createAdminErr := tx.Create(&admin).Error; createAdminErr != nil {
23
-		utils.ErrorLog("创建 AdminUser 失败:%v", createAdminErr)
24
-		tx.Rollback()
25
-	} else {
26
-		registerSuccess = true
27
-	}
28
-	tx.Commit()
29
-	if registerSuccess == true {
30
-		return &admin, nil
31
-	} else {
32
-		return nil, &enums.SGJError{Code: enums.ErrorCodeRegisterFail}
33
-	}
34
-}

+ 0 - 763
models/service/role_service.go Просмотреть файл

@@ -1,763 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"database/sql"
5
-	"strconv"
6
-	"strings"
7
-	"time"
8
-
9
-	"XT_New/models"
10
-	"XT_New/utils"
11
-
12
-	"github.com/jinzhu/gorm"
13
-)
14
-
15
-func GetRoles(orgID int64, appID int64, page int, count int) ([]*models.Role, int, error) {
16
-	var roles []*models.Role
17
-	var totalCount int
18
-	err := readUserDb.Model(&models.Role{}).
19
-		Where("org_id = ? AND app_id = ?", orgID, appID).
20
-		Count(&totalCount).
21
-		Order("ctime asc").Limit(count).Offset((page - 1) * count).
22
-		Find(&roles).
23
-		Error
24
-	if err != nil {
25
-		if err == gorm.ErrRecordNotFound {
26
-			return make([]*models.Role, 0), 0, nil
27
-		} else {
28
-			return nil, 0, err
29
-		}
30
-	}
31
-	return roles, totalCount, nil
32
-}
33
-
34
-func GetAppRole(orgID int64, appID int64, adminUserID int64) (*models.App_Role, error) {
35
-	var appRole models.App_Role
36
-	err := readUserDb.Model(models.App_Role{}).Preload("AdminUser", "status = 1").Where("org_id = ? and app_id = ? and admin_user_id = ?", orgID, appID, adminUserID).First(&appRole).Error
37
-	if err != nil {
38
-		if err == gorm.ErrRecordNotFound {
39
-			return nil, nil
40
-		} else {
41
-			return nil, err
42
-		}
43
-	}
44
-	if len(appRole.RoleIds) > 0 {
45
-		role_ids := strings.Split(appRole.RoleIds, ",")
46
-		for _, item := range role_ids {
47
-			id, _ := strconv.ParseInt(item, 10, 64)
48
-			if id != 0 {
49
-				role, _ := GetRoleByRoleID(id)
50
-				if role != nil {
51
-					if role.IsSystem == 1 && role.RoleName == "子管理员" {
52
-						appRole.IsSubSuperAdmin = true
53
-					}
54
-				}
55
-			}
56
-		}
57
-	}
58
-
59
-	return &appRole, nil
60
-}
61
-
62
-func CreateRole(adminUserID int64, orgID int64, appID int64, name string, intro string) (*models.Role, error) {
63
-	role := models.Role{
64
-		RoleName:     name,
65
-		RoleIntro:    intro,
66
-		Creator:      adminUserID,
67
-		OrgId:        orgID,
68
-		AppId:        appID,
69
-		IsSuperAdmin: false,
70
-		Status:       1,
71
-		CreateTime:   time.Now().Unix(),
72
-		ModifyTime:   time.Now().Unix(),
73
-	}
74
-	tx := writeUserDb.Begin()
75
-	if err := tx.Create(&role).Error; err != nil {
76
-		tx.Rollback()
77
-		return nil, err
78
-	}
79
-	tx.Commit()
80
-	return &role, nil
81
-}
82
-
83
-func GetRoleByRoleID(roleID int64) (*models.Role, error) {
84
-	var role models.Role
85
-	err := readUserDb.Model(&models.Role{}).Where("id = ?", roleID).First(&role).Error
86
-	if err != nil {
87
-		if err == gorm.ErrRecordNotFound {
88
-			return nil, nil
89
-		}
90
-		return nil, err
91
-	} else {
92
-		return &role, nil
93
-	}
94
-}
95
-
96
-func ModifyRole(role *models.Role) error {
97
-	tx := writeUserDb.Begin()
98
-	if err := tx.Save(role).Error; err != nil {
99
-		tx.Rollback()
100
-		return err
101
-	}
102
-	return tx.Commit().Error
103
-}
104
-
105
-// 拥有xx角色的管理员的数量
106
-func RoleAdminUserCount(orgID int64, appID int64, roleID int64) (int, error) {
107
-	var count int
108
-	err := readUserDb.Model(models.App_Role{}).
109
-		Where("org_id = ? AND app_id = ? AND role_id = ? AND status = 1", orgID, appID, roleID).
110
-		Count(&count).
111
-		Error
112
-	if err != nil {
113
-		return 0, err
114
-	} else {
115
-		return count, nil
116
-	}
117
-}
118
-
119
-type AdminUserManageViewModel struct {
120
-	AdminUserId int    `gorm:"admin_user_id" json:"user_id"`
121
-	UserName    string `gorm:"user_name" json:"user_name"`
122
-	RoleName    string `gorm:"role_name" json:"role_name"`
123
-	UserTitle   int    `gorm:"user_title" json:"user_title"`
124
-	Ip          string `gorm:"ip" json:"ip"`
125
-	Ctime       int64  `gorm:"ctime" json:"last_login_time"`
126
-	Status      int    `gorm:"status" json:"status"`
127
-	Avatar      string `gorm:"avatar" json:"avatar"`
128
-	RoleIds     string `gorm:"role_ids" json:"role_ids"`
129
-	// LastLoginTimeStr string `gorm:"-" json:"last_login_time_formatted"`
130
-	TitleName       string `gorm:"-" json:"title_name"`
131
-	IsSubSuperAdmin bool   `gorm:"-" json:"is_sub_super_admin"`
132
-	//mobile          string `gorm:"-" json:"mobile"`
133
-	Sort int `gorm:"sort" json:"sort"`
134
-}
135
-
136
-func GetAdminUsersAndLoginInfo(orgID int64, appID int64, page int, count int) ([]*AdminUserManageViewModel, int, error) {
137
-	if count <= 0 {
138
-		return []*AdminUserManageViewModel{}, 0, nil
139
-	}
140
-	if page < 1 {
141
-		page = 1
142
-	}
143
-	var viewModels []*AdminUserManageViewModel = make([]*AdminUserManageViewModel, 0)
144
-	rows, err := readUserDb.Raw("SELECT u_a_r.admin_user_id, u_a_r.user_name, u_a_r.user_title, u_l.ip, u_l.ctime, u_a_r.status,u_a_r.avatar,u_a_r.role_ids,u_a_r.sort FROM sgj_user_admin_role AS u_a_r   LEFT JOIN (SELECT * FROM (SELECT admin_user_id, org_id, app_id, ip, ctime FROM sgj_user_admin_login_log WHERE org_id = ? AND app_id = ?  ORDER BY ctime DESC) AS t GROUP BY admin_user_id) AS u_l  ON u_a_r.org_id = u_l.org_id AND u_a_r.app_id = u_l.app_id AND u_a_r.admin_user_id = u_l.admin_user_id WHERE u_a_r.org_id = ? AND u_a_r.app_id = ? GROUP BY u_a_r.admin_user_id  LIMIT ? OFFSET ?;", orgID, appID, orgID, appID, count, (page-1)*count).Rows()
145
-	defer rows.Close()
146
-	if err != nil {
147
-		if err == gorm.ErrRecordNotFound {
148
-			return viewModels, 0, nil
149
-		} else {
150
-			return nil, 0, err
151
-		}
152
-	}
153
-	for rows.Next() {
154
-		var viewModel AdminUserManageViewModel
155
-		readUserDb.ScanRows(rows, &viewModel)
156
-		title, _ := models.UserTitle[viewModel.UserTitle]
157
-		viewModel.TitleName = title
158
-		// if viewModel.Ctime == 0 {
159
-		// 	viewModel.LastLoginTimeStr = ""
160
-		// } else {
161
-		// 	loginTime := time.Unix(viewModel.Ctime, 0)
162
-		// 	viewModel.LastLoginTimeStr = loginTime.Format("2006-01-02 15:04")
163
-		// }
164
-		viewModels = append(viewModels, &viewModel)
165
-	}
166
-
167
-	for _, item := range viewModels {
168
-		if len(item.RoleIds) > 0 {
169
-			ids := strings.Split(item.RoleIds, ",")
170
-			for _, id := range ids {
171
-				id, _ := strconv.ParseInt(id, 10, 64)
172
-				if id != 0 {
173
-					role, _ := GetRoleByRoleID(id)
174
-					if role != nil {
175
-						if role.IsSystem == 1 && role.RoleName == "子管理员" {
176
-							item.IsSubSuperAdmin = true
177
-						}
178
-
179
-						if len(item.RoleName) == 0 {
180
-							item.RoleName = role.RoleName
181
-						} else {
182
-							item.RoleName = item.RoleName + "," + role.RoleName
183
-						}
184
-					}
185
-				}
186
-			}
187
-
188
-		}
189
-
190
-		//admin, _ := GetAdminUserByUserID(int64(item.AdminUserId))
191
-		//item.mobile = admin.Mobile
192
-
193
-	}
194
-
195
-	total := 0
196
-	//readUserDb.Table("sgj_user_admin_role as u_a_r").Joins("join sgj_user_role as u_r on u_r.org_id = u_a_r.org_id AND u_r.app_id = u_a_r.app_id AND u_r.id = u_a_r.role_id").Where("u_a_r.org_id = ? AND u_a_r.app_id = ?", orgID, appID).Count(&total)
197
-	return viewModels, total, nil
198
-}
199
-
200
-func GetValidRoleCount(orgID int64, appID int64, superAdminUserID int64) (int, error) {
201
-	var count int
202
-	err := readUserDb.Model(models.Role{}).
203
-		Where("org_id = ? AND app_id = ? AND creator = ? AND is_super_admin = 0 AND status = 1", orgID, appID, superAdminUserID).
204
-		Count(&count).
205
-		Error
206
-	if err != nil {
207
-		return 0, err
208
-	} else {
209
-		return count, nil
210
-	}
211
-}
212
-
213
-func GetAllValidRoles(orgID int64, appID int64) ([]*models.Role, error) {
214
-	var roles []*models.Role
215
-	err := readUserDb.Model(models.Role{}).
216
-		Where("org_id = ? AND app_id = ? AND status = 1", orgID, appID).
217
-		Order("number desc,ctime").
218
-		Find(&roles).
219
-		Error
220
-	if err != nil {
221
-		if err == gorm.ErrRecordNotFound {
222
-			return make([]*models.Role, 0), nil
223
-		} else {
224
-			return nil, err
225
-		}
226
-	}
227
-	return roles, nil
228
-}
229
-
230
-func IsRoleExist(orgID int64, appID int64, roleID int64) (bool, error) {
231
-	var count int
232
-	err := readUserDb.Model(models.Role{}).Where("org_id = ? AND app_id = ? AND id = ? AND status = 1", orgID, appID, roleID).Count(&count).Error
233
-	if err != nil {
234
-		return false, err
235
-	} else {
236
-		return count > 0, nil
237
-	}
238
-}
239
-
240
-type AdminUserEditViewModel struct {
241
-	AdminUserId int64  `gorm:"admin_user_id" json:"user_id"`
242
-	UserName    string `gorm:"user_name" json:"user_name"`
243
-	Mobile      string `gorm:"mobile" json:"mobile"`
244
-	UserType    int    `gorm:"user_type" json:"user_type"`
245
-	UserTitle   int    `gorm:"user_title" json:"user_title"`
246
-	Intro       string `gorm:"intro" json:"intro"`
247
-	RoleId      int64  `gorm:"role_id" json:"role_id"`
248
-}
249
-
250
-func GetGeneralAdminUser(orgID int64, appID int64, user_id int64) (*AdminUserEditViewModel, error) {
251
-	rows, err := readUserDb.Raw("SELECT u_a.mobile, u_a_r.admin_user_id, u_a_r.user_name, u_a_r.user_type, u_a_r.user_title, u_a_r.intro, u_a_r.role_id FROM sgj_user_admin AS u_a, sgj_user_admin_role AS u_a_r WHERE u_a.id = u_a_r.admin_user_id AND u_a.id = ? AND u_a_r.status = 1 AND u_a_r.org_id = ? AND u_a_r.app_id = ?;", user_id, orgID, appID).Rows()
252
-	defer rows.Close()
253
-	if err != nil {
254
-		if err == gorm.ErrRecordNotFound {
255
-			return nil, nil
256
-		} else {
257
-			return nil, err
258
-		}
259
-	}
260
-	if rows.Next() {
261
-		var viewModel AdminUserEditViewModel
262
-		err := readUserDb.ScanRows(rows, &viewModel)
263
-		if err != nil {
264
-			return nil, err
265
-		} else {
266
-			return &viewModel, nil
267
-		}
268
-	}
269
-	return nil, nil
270
-}
271
-
272
-func SaveAppRole(appRole *models.App_Role) error {
273
-	tx := writeUserDb.Begin()
274
-	if err := tx.Model(&models.App_Role{}).Save(appRole).Error; err != nil {
275
-		tx.Rollback()
276
-		return err
277
-	}
278
-	return tx.Commit().Error
279
-}
280
-
281
-func IsMobileDidUsedAtApp(orgID int64, appID int64, mobile string) (bool, error) {
282
-	var count int
283
-	rows, err := readUserDb.Raw("select count(u_a.id) as count from sgj_user_admin as u_a, sgj_user_admin_role as u_a_r where u_a_r.org_id = ? and u_a_r.app_id = ? and u_a.mobile = ? and u_a.id = u_a_r.admin_user_id;", orgID, appID, mobile).Rows()
284
-	defer rows.Close()
285
-	if err != nil {
286
-		if err == gorm.ErrRecordNotFound {
287
-			return false, nil
288
-		} else {
289
-			return true, err
290
-		}
291
-	}
292
-	if rows.Next() {
293
-		rows.Scan(&count)
294
-		return count > 0, nil
295
-	}
296
-	return true, nil
297
-}
298
-
299
-func IsUserSuperAdminWithMobile(mobile string) (bool, error) {
300
-	var user models.AdminUser
301
-	err := readUserDb.Where("mobile = ?", mobile).First(&user).Error
302
-	if err != nil {
303
-		if err == gorm.ErrRecordNotFound {
304
-			return false, nil
305
-		} else {
306
-			return false, err
307
-		}
308
-	}
309
-	return user.IsSuperAdmin, nil
310
-}
311
-
312
-func CreateGeneralAdminUser(orgID int64, appID int64, mobile string, name string, userTitle string, roleIds string, user_type int, user_title int) (*models.AdminUser, string, error) {
313
-	now := time.Now().Unix()
314
-	tx := writeUserDb.Begin()
315
-	var adminUser models.AdminUser
316
-	err := readUserDb.Where("mobile = ? AND status = 1", mobile).First(&adminUser).Error
317
-	password := ""
318
-	if err != nil {
319
-		if err != gorm.ErrRecordNotFound {
320
-			return nil, "", err
321
-		} else {
322
-			password = utils.RandomNumberString(6)
323
-			adminUser.Mobile = mobile
324
-			adminUser.Password = utils.String2md5(password)
325
-			adminUser.IsSuperAdmin = false
326
-			adminUser.Status = 1
327
-			adminUser.CreateTime = now
328
-			adminUser.ModifyTime = now
329
-			if createErr := tx.Create(&adminUser).Error; createErr != nil {
330
-				tx.Rollback()
331
-				return nil, "", createErr
332
-			}
333
-		}
334
-	}
335
-	app_role := models.App_Role{
336
-		AdminUserId:   adminUser.Id,
337
-		OrgId:         orgID,
338
-		AppId:         appID,
339
-		Avatar:        "",
340
-		UserName:      name,
341
-		UserTitleName: userTitle,
342
-		UserTitle:     int8(user_title),
343
-		UserType:      int8(user_type),
344
-		Status:        1,
345
-		CreateTime:    now,
346
-		ModifyTime:    now,
347
-		RoleIds:       roleIds,
348
-		IsSort:        1,
349
-	}
350
-	if createApp_RoleErr := tx.Create(&app_role).Error; createApp_RoleErr != nil {
351
-		tx.Rollback()
352
-		return nil, "", createApp_RoleErr
353
-	}
354
-
355
-	tx.Commit()
356
-	return &adminUser, password, nil
357
-}
358
-
359
-type PurviewTreeViewModel struct {
360
-	ID     int64                   `json:"id"`
361
-	PID    int64                   `json:"pid"`
362
-	Name   string                  `json:"name"`
363
-	Childs []*PurviewTreeViewModel `json:"childs"`
364
-	Number int64                   `json:"number"`
365
-}
366
-
367
-func GetAllGeneralPurviewVMsProcessed(module int) ([]*PurviewTreeViewModel, error) {
368
-	var originPurviews []*models.Purview
369
-	getPurviewErr := readUserDb.Model(models.Purview{}).Where("module = ? AND status = 1 AND super_admin_exclusive = 0", module).Order("listorder asc").Order("id asc").Find(&originPurviews).Error
370
-	if getPurviewErr != nil {
371
-		return nil, getPurviewErr
372
-	}
373
-	// 加工这些规则:树形化
374
-	purviewVMs := make([]*PurviewTreeViewModel, 0)
375
-	pid_childs := make(map[int64][]*PurviewTreeViewModel)
376
-	for _, purview := range originPurviews {
377
-		// warning:下面这个算法只适用最多两层树形结构的菜单,对于两层以上的会丢失掉第三层及其以下的节点
378
-		// 因为取出 originPurviews 的时候已经排过序了,所以顶级节点肯定最先处理,不需要担心子节点比父节点先处理
379
-		pvm := &PurviewTreeViewModel{
380
-			ID:     purview.Id,
381
-			PID:    purview.Parentid,
382
-			Name:   purview.Name,
383
-			Number: 2,
384
-		}
385
-		if purview.Parentid == 0 {
386
-			purviewVMs = append(purviewVMs, pvm)
387
-		} else {
388
-			childs := pid_childs[purview.Parentid]
389
-			if childs == nil {
390
-				childs = make([]*PurviewTreeViewModel, 0)
391
-			}
392
-			childs = append(childs, pvm)
393
-			pid_childs[purview.Parentid] = childs
394
-		}
395
-	}
396
-
397
-	for _, vm := range purviewVMs {
398
-		vm.Childs = pid_childs[vm.ID]
399
-	}
400
-
401
-	return purviewVMs, nil
402
-}
403
-
404
-func GetAllGeneralFuncPurviewVMsProcessed() ([]*PurviewTreeViewModel, error) {
405
-	var originPurviews []*models.SgjUserOperatePurview
406
-	getPurviewErr := readUserDb.Model(models.SgjUserOperatePurview{}).Where(" status = 1").Order("number asc").Find(&originPurviews).Error
407
-	if getPurviewErr != nil {
408
-		return nil, getPurviewErr
409
-	}
410
-	// 加工这些规则:树形化
411
-	purviewVMs := make([]*PurviewTreeViewModel, 0)
412
-	for _, purview := range originPurviews {
413
-		// warning:下面这个算法只适用最多两层树形结构的菜单,对于两层以上的会丢失掉第三层及其以下的节点
414
-		// 因为取出 originPurviews 的时候已经排过序了,所以顶级节点肯定最先处理,不需要担心子节点比父节点先处理
415
-		pvm := &PurviewTreeViewModel{
416
-			ID:   purview.ID,
417
-			PID:  purview.Parentid,
418
-			Name: purview.Name,
419
-		}
420
-		purviewVMs = append(purviewVMs, pvm)
421
-
422
-	}
423
-
424
-	return purviewVMs, nil
425
-}
426
-
427
-func GetRolePurviewIds(roleID int64) (string, error) {
428
-	var rolePurview models.RolePurview
429
-	err := readUserDb.Where("role_id = ?", roleID).First(&rolePurview).Error
430
-	if err != nil {
431
-		if err == gorm.ErrRecordNotFound {
432
-			return "", nil
433
-		} else {
434
-			return "", err
435
-		}
436
-	}
437
-	return rolePurview.PurviewIds, nil
438
-}
439
-
440
-func SaveRolePurviewIds(orgID int64, appID int64, roleID int64, purviewIds string) error {
441
-	var rolePurview models.RolePurview
442
-	getRPErr := readUserDb.Where("org_id = ? AND app_id = ? AND role_id = ?", orgID, appID, roleID).First(&rolePurview).Error
443
-	if getRPErr != nil {
444
-		if getRPErr == gorm.ErrRecordNotFound {
445
-			rolePurview = models.RolePurview{
446
-				RoleId:     roleID,
447
-				OrgId:      orgID,
448
-				AppId:      appID,
449
-				Status:     1,
450
-				CreateTime: time.Now().Unix(),
451
-			}
452
-		} else {
453
-			return getRPErr
454
-		}
455
-	}
456
-	rolePurview.PurviewIds = purviewIds
457
-	rolePurview.ModifyTime = time.Now().Unix()
458
-	tx := writeUserDb.Begin()
459
-	if err := tx.Save(&rolePurview).Error; err != nil {
460
-		tx.Rollback()
461
-		return err
462
-	}
463
-	return tx.Commit().Error
464
-}
465
-
466
-func SaveFuncRolePurviewIds(orgID int64, appID int64, roleID int64, funcPurviewIds string) error {
467
-	var rolePurview models.SgjUserRoleFuncPurview
468
-	getRPErr := readUserDb.Where("org_id = ? AND app_id = ? AND role_id = ?", orgID, appID, roleID).First(&rolePurview).Error
469
-	if getRPErr != nil {
470
-		if getRPErr == gorm.ErrRecordNotFound {
471
-			rolePurview = models.SgjUserRoleFuncPurview{
472
-				RoleId: roleID,
473
-				OrgId:  orgID,
474
-				AppId:  appID,
475
-				Status: 1,
476
-				Ctime:  time.Now().Unix(),
477
-			}
478
-		} else {
479
-			return getRPErr
480
-		}
481
-	}
482
-	rolePurview.PurviewIds = funcPurviewIds
483
-	rolePurview.Mtime = time.Now().Unix()
484
-	tx := writeUserDb.Begin()
485
-	if err := tx.Save(&rolePurview).Error; err != nil {
486
-		tx.Rollback()
487
-		return err
488
-	}
489
-	return tx.Commit().Error
490
-}
491
-
492
-func ModifyAdminUserInfo(adminUserID int64, orgID int64, appID int64, name string, avatar string, newPassword string) error {
493
-	tx := writeUserDb.Begin()
494
-	editInfoErr := tx.Exec("update sgj_user_admin_role set user_name = ?, avatar = ?, mtime = ? where admin_user_id = ? and org_id = ?", name, avatar, time.Now().Unix(), adminUserID, orgID).Error
495
-	if editInfoErr != nil {
496
-		tx.Rollback()
497
-		return editInfoErr
498
-	}
499
-	if len(newPassword) > 0 {
500
-		editPwdErr := tx.Exec("update sgj_user_admin set password = ?, mtime = ? where id = ?", newPassword, time.Now().Unix(), adminUserID).Error
501
-		if editPwdErr != nil {
502
-			tx.Rollback()
503
-			return editPwdErr
504
-		}
505
-	}
506
-	tx.Commit()
507
-	return nil
508
-}
509
-
510
-func GetOrgApp(orgID int64, app_type int) (*models.OrgApp, error) {
511
-	var apps models.OrgApp
512
-	err := readUserDb.Where("app_type = ? AND org_id = ? AND status = 1", app_type, orgID).First(&apps).Error
513
-	if err != nil {
514
-		return nil, err
515
-	}
516
-	return &apps, nil
517
-}
518
-
519
-func GetAllOrgValidRoles(orgID int64, isSubSuperAdmin bool) ([]*models.Role, error) {
520
-	var roles []*models.Role
521
-	db := readUserDb.Model(models.Org{})
522
-	if isSubSuperAdmin {
523
-		db = db.Where("role_name != '子管理员' AND is_system  != 1")
524
-	}
525
-	err := db.Where("org_id = ? AND status = 1", orgID).
526
-		Order("number desc,ctime").
527
-		Find(&roles).
528
-		Error
529
-	if err != nil {
530
-		if err == gorm.ErrRecordNotFound {
531
-			return make([]*models.Role, 0), nil
532
-		} else {
533
-			return nil, err
534
-		}
535
-	}
536
-	for _, item := range roles {
537
-		var total int64
538
-		readUserDb.Model(&models.App_Role{}).Where("org_id = ? AND find_in_set(?, role_ids)", orgID, item.Id).Count(&total)
539
-		item.StaffNumber = total
540
-	}
541
-	return roles, nil
542
-}
543
-
544
-func CreateUserRole(userRole *models.App_Role) (err error) {
545
-	err = writeUserDb.Create(&userRole).Error
546
-	return
547
-}
548
-
549
-func CreateOrgRole(role *models.Role) (err error) {
550
-	err = writeUserDb.Create(&role).Error
551
-	return
552
-}
553
-
554
-func GetRolePurview(roleID int64) (models.RolePurview, error) {
555
-	var rolePurviews models.RolePurview
556
-	var err error
557
-	err = readUserDb.Where("role_id = ?", roleID).First(&rolePurviews).Error
558
-	return rolePurviews, err
559
-}
560
-
561
-func GetFuncRolePurview(roleID int64) (models.SgjUserRoleFuncPurview, error) {
562
-	var rolePurviews models.SgjUserRoleFuncPurview
563
-	var err error
564
-	err = readUserDb.Where("role_id = ?", roleID).First(&rolePurviews).Error
565
-	return rolePurviews, err
566
-}
567
-
568
-func SaveRolePurview(purview *models.RolePurview) (err error) {
569
-	err = writeUserDb.Save(&purview).Error
570
-	return
571
-}
572
-
573
-func CreateRolePurview(purview *models.RolePurview) (err error) {
574
-	err = writeUserDb.Create(&purview).Error
575
-	return
576
-}
577
-
578
-func CreateFuncRolePurview(purview *models.SgjUserRoleFuncPurview) (err error) {
579
-	err = writeUserDb.Create(&purview).Error
580
-	return
581
-}
582
-
583
-func GetAllPurview(module int64, pid int64) ([]*models.Purview, error) {
584
-	var originPurviews []*models.Purview
585
-	getPurviewErr := readUserDb.Model(models.Purview{}).Preload("Purview", "status = 1").Where("module = ? AND status = 1 AND parentid = ? AND super_admin_exclusive = 0", module, pid).Order("listorder asc").Order("id asc").Find(&originPurviews).Error
586
-	return originPurviews, getPurviewErr
587
-}
588
-
589
-type NewAdminUserModel struct {
590
-	ID          int64  `gorm:"id" json:"id"`
591
-	AdminUserId int    `gorm:"admin_user_id" json:"user_id"`
592
-	UserName    string `gorm:"user_name" json:"user_name"`
593
-	UserTitle   int    `gorm:"user_title_name" json:"user_title_name"`
594
-	Ip          string `gorm:"ip" json:"ip"`
595
-	Ctime       int64  `gorm:"ctime" json:"last_login_time"`
596
-	Status      int    `gorm:"status" json:"status"`
597
-	Avatar      string `gorm:"avatar" json:"avatar"`
598
-	RoleIds     string `gorm:"role_ids" json:"role_ids"`
599
-	IsSubAdmin  bool   `gorm:"-" json:"is_sub_admin"`
600
-}
601
-
602
-func GetAllAdminUsersAndRole(orgID int64, appID int64, page int, count int) ([]*NewAdminUserModel, int, error) {
603
-	var viewModels []*NewAdminUserModel = make([]*NewAdminUserModel, 0)
604
-	var rows *sql.Rows
605
-	var err error
606
-	rows, err = readUserDb.Raw("SELECT u_a_r.id, u_a_r.admin_user_id, u_a_r.user_name,  u_a_r.user_title, u_a_r.status,u_a_r.avatar,u_a_r.role_ids FROM sgj_user_admin_role AS u_a_r  WHERE org_id = ? AND app_id = ? ORDER BY ctime asc", orgID, appID).Rows()
607
-	defer rows.Close()
608
-	if err != nil {
609
-		if err == gorm.ErrRecordNotFound {
610
-			return viewModels, 0, nil
611
-		} else {
612
-			return nil, 0, err
613
-		}
614
-	}
615
-	for rows.Next() {
616
-		var viewModel NewAdminUserModel
617
-		readUserDb.ScanRows(rows, &viewModel)
618
-		viewModels = append(viewModels, &viewModel)
619
-	}
620
-
621
-	for _, items := range viewModels {
622
-		if len(items.RoleIds) > 0 {
623
-			ids := strings.Split(items.RoleIds, ",")
624
-			for _, ids := range ids {
625
-				id, _ := strconv.ParseInt(ids, 10, 64)
626
-				if id != 0 {
627
-					role, _ := GetRoleByRoleID(id)
628
-					if role != nil {
629
-						if role.IsSystem == 1 && role.RoleName == "子管理员" {
630
-							items.IsSubAdmin = true
631
-						}
632
-					}
633
-				}
634
-			}
635
-		}
636
-	}
637
-
638
-	total := 0
639
-	return viewModels, total, nil
640
-}
641
-
642
-func FindAdminUserByID(admin_user_id int64, org_id int64) (total int64, err error) {
643
-	err = readUserDb.Model(&models.App_Role{}).Where("admin_user_id = ? AND org_id = ?", admin_user_id, org_id).Count(&total).Error
644
-	return
645
-}
646
-
647
-func GetRoleAndPurviewById(role_id int64, org_id int64, app_id int64) (rolePurview models.RolePurview, err error) {
648
-	err = readUserDb.Model(&models.RolePurview{}).Preload("Role", "status = 1").Where("role_id = ? AND status = 1 AND org_id = ? AND app_id = ?", role_id, org_id, app_id).First(&rolePurview).Error
649
-	return
650
-}
651
-
652
-func SaveRole(role *models.Role) (err error) {
653
-	err = writeUserDb.Save(&role).Error
654
-	return
655
-}
656
-
657
-// 拥有xx角色的管理员的数量
658
-func RoleAdminUserCountTwo(orgID int64, appID int64, roleID int64) (int, error) {
659
-	var count int
660
-	err := readUserDb.Model(models.App_Role{}).
661
-		Where("org_id = ? AND app_id = ? AND find_in_set(?, role_ids)", orgID, appID, roleID).
662
-		Count(&count).
663
-		Error
664
-	if err != nil {
665
-		return 0, err
666
-	} else {
667
-		return count, nil
668
-	}
669
-}
670
-
671
-func FindAdminUserID(id int64) (role models.App_Role, err error) {
672
-	err = readUserDb.Model(&models.App_Role{}).Where("id = ?", id).First(&role).Error
673
-	return
674
-}
675
-
676
-func SaveAdminUser(role *models.App_Role) (err error) {
677
-	err = writeUserDb.Save(&role).Error
678
-	return
679
-}
680
-
681
-func GetFunctionPurview() (purview []*models.SgjUserOperatePurview, err error) {
682
-	err = readUserDb.Model(&models.SgjUserOperatePurview{}).Where("status = 1 ").Order("number asc").Find(&purview).Error
683
-	return
684
-}
685
-
686
-func GetRoleFuncPurviewIds(roleID int64) (string, error) {
687
-	var rolePurview models.SgjUserRoleFuncPurview
688
-	err := readUserDb.Where("role_id = ?", roleID).First(&rolePurview).Error
689
-	if err != nil {
690
-		if err == gorm.ErrRecordNotFound {
691
-			return "", nil
692
-		} else {
693
-			return "", err
694
-		}
695
-	}
696
-	return rolePurview.PurviewIds, nil
697
-}
698
-
699
-func GetRoleFuncPurview(roleID int64) (rolePurviews models.SgjUserRoleFuncPurview, err error) {
700
-	err = readUserDb.Where("role_id = ?", roleID).First(&rolePurviews).Error
701
-	return
702
-}
703
-
704
-func SaveRoleFuncPurview(purview *models.SgjUserRoleFuncPurview) (err error) {
705
-	err = writeUserDb.Save(purview).Error
706
-	return
707
-}
708
-
709
-func GetUserAllRole(org_id int64, admin_user_id int64) (role models.App_Role, err error) {
710
-	err = readUserDb.Model(&models.App_Role{}).Where("status = 1 AND org_id = ? AND admin_user_id = ?", org_id, admin_user_id).First(&role).Error
711
-	return
712
-}
713
-
714
-func GetAllFunctionPurview() (purview []models.SgjUserOperatePurview, err error) {
715
-	err = readUserDb.Model(&models.SgjUserOperatePurview{}).Where("status = 1 ").Order("number asc").Find(&purview).Error
716
-	return
717
-}
718
-
719
-func FindErrorMsgByStr(str string) (string, error) {
720
-	var purview models.SgjUserOperatePurview
721
-	var err error
722
-	err = readUserDb.Model(&models.SgjUserOperatePurview{}).Where("find_in_set(?, urlfor)", str).First(&purview).Error
723
-	return purview.ErrorMsg, err
724
-
725
-}
726
-
727
-func GetNewAllOrgValidRoles(orgID int64) ([]*models.Role, error) {
728
-	var roles []*models.Role
729
-	db := readUserDb.Model(models.Org{})
730
-	err := db.Where("org_id = ? AND status = 1", orgID).
731
-		Order("number desc,ctime").
732
-		Find(&roles).
733
-		Error
734
-	if err != nil {
735
-		if err == gorm.ErrRecordNotFound {
736
-			return make([]*models.Role, 0), nil
737
-		} else {
738
-			return nil, err
739
-		}
740
-	}
741
-	for _, item := range roles {
742
-		var total int64
743
-		readUserDb.Model(&models.App_Role{}).Where("org_id = ? AND find_in_set(?, role_ids)", orgID, item.Id).Count(&total)
744
-		item.StaffNumber = total
745
-	}
746
-	return roles, nil
747
-}
748
-
749
-func FindRoleRecordByRoleName(name string, org_id int64) (total int64) {
750
-	readUserDb.Model(&models.Role{}).Where("status = 1 AND role_name = ? AND org_id = ?", name, org_id).Count(&total)
751
-	return
752
-}
753
-
754
-func FindAllFuncPurview(ids []string) (purview []*models.SgjUserOperatePurview, err error) {
755
-	err = readUserDb.Model(&models.SgjUserOperatePurview{}).Where("status = 1 AND id in (?)", ids).Order("number asc").Find(&purview).Error
756
-	return
757
-
758
-}
759
-
760
-func GetSystemPurview() (purview []*models.Purview, err error) {
761
-	err = readUserDb.Model(&models.Purview{}).Where("status = 1 AND module = 3 AND super_admin_exclusive = 1").Find(&purview).Error
762
-	return
763
-}

+ 0 - 536
models/service/schedule_service.go Просмотреть файл

@@ -1,536 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	"fmt"
6
-	"strconv"
7
-	"strings"
8
-	"time"
9
-
10
-	"github.com/jinzhu/gorm"
11
-)
12
-
13
-//GetSchedulePartitionPanel 取出排班面板,分区-机号
14
-func GetSchedulePartitionPanel(orgID int64) (partitions []*models.Partition, err error) {
15
-
16
-	err = readDb.Model(&models.DeviceZone{}).Preload("Jihaos", "org_id=? and status=1", orgID).Where("org_id=? and status=1", orgID).Find(&partitions).Error
17
-
18
-	return
19
-}
20
-
21
-func GetPatientWithScheduleAndSolution(orgID int64, keywords string, weekStart, weekEnd, schedule, contagion int64) (patients []*models.Patients, err error) {
22
-	db := readDb.Table("xt_patients as p").
23
-		Preload("DialysisSolutions", "user_org_id=? and initiate_mode=1 and affirm_state=1 and parent_id=0 and status=1", orgID).
24
-		Preload("Schedules", "user_org_id=? and schedule_date>=? and schedule_date<= ? and status=1", orgID, weekStart, weekEnd).
25
-		Preload("Contagions", "status=1").
26
-		Where("p.user_org_id=? and p.lapseto=1 and p.status=1", orgID)
27
-	if len(keywords) > 0 {
28
-		likeKey := "%" + keywords + "%"
29
-		db = db.Where("p.name LIKE ?", likeKey)
30
-	}
31
-
32
-	if schedule == 1 {
33
-		db = db.Where("EXISTS (?)", readDb.Table("xt_schedule as iss").Where("iss.patient_id=p.id and iss.schedule_date>=? and iss.schedule_date<= ? and iss.status=1", weekStart, weekEnd).QueryExpr())
34
-	} else if schedule == 2 {
35
-		db = db.Where("NOT EXISTS (?)", readDb.Table("xt_schedule as iss").Where("iss.patient_id=p.id and iss.schedule_date>=? and iss.schedule_date<= ? and iss.status=1", weekStart, weekEnd).QueryExpr())
36
-	}
37
-	if contagion > 0 {
38
-		db = db.Where("EXISTS (?)", readDb.Table("xt_patients_infectious_diseases as pid").Where("pid.patient_id=p.id and pid.disease_id=? and pid.status=1", contagion).QueryExpr())
39
-	}
40
-
41
-	err = db.Find(&patients).Error
42
-	return
43
-}
44
-
45
-func GetWeekSchedule(orgID int64, start, end int64) (schedules []*models.Schedule, err error) {
46
-
47
-	err = readDb.
48
-		Table("xt_schedule as s").
49
-		Preload("PatientInfectiousDiseases", "status = 1 ").
50
-		Joins("JOIN xt_patients as p ON p.id = s.patient_id").
51
-		Where("s.user_org_id=? and s.schedule_date>=? and s.schedule_date<=? and s.status=1", orgID, start, end).
52
-		Select("s.id, s.user_org_id, s.partition_id, s.bed_id, s.patient_id, s.schedule_date, s.schedule_type, s.schedule_week, s.mode_id, s.status, s.created_time, s.updated_time, p.name as patient").
53
-		Order("updated_time asc").
54
-		Find(&schedules).Error
55
-	return
56
-}
57
-
58
-func GetDaySchedule(orgID, start, end, patientID int64) (schedule models.Schedule, err error) {
59
-	err = readDb.Model(&models.Schedule{}).Where("user_org_id=? and patient_id=? and schedule_date>=? and schedule_date<=? and status=1", orgID, patientID, start, end).First(&schedule).Error
60
-	return
61
-}
62
-
63
-func GetDayScheduleTwo(orgID, start, patientID int64) (schedule models.Schedule, err error) {
64
-	err = readDb.Model(&models.Schedule{}).Where("user_org_id=? and patient_id=? and schedule_date = ? and status=1", orgID, patientID, start).Preload("DialysisOrder", "status = 1").First(&schedule).Error
65
-	return
66
-}
67
-
68
-func GetDayScheduleByBedid(orgID, start, bed_id int64, schedule_type int64) (schedule models.Schedule, err error) {
69
-	err = readDb.Model(&models.Schedule{}).Where("user_org_id=?  and schedule_date=? and bed_id=? and status=1 AND schedule_type = ?", orgID, start, bed_id, schedule_type).Preload("DialysisOrder", "status = 1").First(&schedule).Error
70
-	return
71
-}
72
-
73
-func GetPatientScheduleFormDay(orgID, start, end, patientID int64) (schedules []*models.PatientSchedule, err error) {
74
-
75
-	err = readDb.Table("xt_schedule as s").
76
-		Preload("DeviceZone", "org_id=? and status=1", orgID).
77
-		Preload("DeviceNumber", "org_id=? and status=1", orgID).
78
-		Where("s.patient_id =? and s.user_org_id=? and s.schedule_date>=? and s.schedule_date < ? and s.status=1", patientID, orgID, start, end).
79
-		Find(&schedules).Error
80
-
81
-	return
82
-}
83
-
84
-func GetNextSchedule(orgID, end, patientID int64) (schedules []*models.PatientSchedule, err error) {
85
-	err = readDb.Table("xt_schedule as s").
86
-		Preload("DeviceZone", "org_id=? and status=1", orgID).
87
-		Preload("DeviceNumber", "org_id=? and status=1", orgID).
88
-		Where("s.patient_id =? and s.user_org_id=? and s.schedule_date>=?  and s.status=1", patientID, orgID, end).
89
-		Find(&schedules).Error
90
-
91
-	return
92
-}
93
-
94
-func GetPointSchedule(orgID, scheduleDate, scheduleWeek, scheduleType, bedId int64) (schedule models.Schedule, err error) {
95
-	err = readDb.Model(&models.Schedule{}).Where("user_org_id=? and schedule_date=? and bed_id=? and schedule_week=? AND schedule_type=? and status=1", orgID, scheduleDate, bedId, scheduleWeek, scheduleType).First(&schedule).Error
96
-
97
-	if err == gorm.ErrRecordNotFound {
98
-		err = nil
99
-		return
100
-	}
101
-	return
102
-}
103
-
104
-func CreateSchedule(m *models.Schedule) error {
105
-	return writeDb.Model(&models.Schedule{}).Create(&m).Error
106
-}
107
-
108
-func GetSchedule(orgID, id int64) (*models.Schedule, error) {
109
-	var schedule models.Schedule
110
-	var err error
111
-	err = readDb.Model(&models.Schedule{}).Where("id = ? and user_org_id=? and status=1", id, orgID).First(&schedule).Error
112
-	if err != nil {
113
-		return nil, err
114
-	}
115
-	return &schedule, nil
116
-}
117
-
118
-func UpdateSchedule(m *models.Schedule) error {
119
-	return writeDb.Model(&models.Schedule{}).Save(&m).Error
120
-}
121
-
122
-func GetPatientScheduleFormToday(orgId, id, start int64) (schedules []*models.PatientSchedule, err error) {
123
-
124
-	err = readDb.Table("xt_schedule as s").
125
-		Preload("DeviceZone", "org_id=? and status=1", orgId).
126
-		Preload("DeviceNumber", "org_id=? and status=1", orgId).
127
-		Where("s.patient_id =? and s.user_org_id=? and s.schedule_date>=? and s.status=1", id, orgId, start).
128
-		Find(&schedules).Error
129
-
130
-	return
131
-}
132
-
133
-type WeekSchedulePrintVM struct {
134
-	ID             int64 `gorm:"column:id" json:"id"`
135
-	ZoneID         int64 `gorm:"column:partition_id" json:"zone_id"`
136
-	DeviceNumberID int64 `gorm:"column:bed_id" json:"device_number_id"`
137
-	PatientID      int64 `gorm:"column:patient_id" json:"patient_id"`
138
-	ScheduleDate   int64 `gorm:"column:schedule_date" json:"schedule_date"`
139
-	ScheduleType   int64 `gorm:"column:schedule_type" json:"schedule_type"`
140
-	ScheduleWeek   int64 `gorm:"column:schedule_week" json:"schedule_week"`
141
-	ModeID         int64 `gorm:"column:mode_id" json:"mode_id"`
142
-
143
-	Patient      *models.Patients      `gorm:"ForeignKey:PatientID" json:"patient"`
144
-	DeviceNumber *models.DeviceNumber  `gorm:"ForeignKey:DeviceNumberID" json:"device_number"`
145
-	Zone         *models.DeviceZone    `gorm:"ForeignKey:ZoneID" json:"zone"`
146
-	Mode         *models.TreatmentMode `gorm:"ForeignKey:ModeID" json:"mode"`
147
-}
148
-
149
-type PrintCount struct {
150
-	ScheduleType int64 `gorm:"column:schedule_type" json:"schedule_type"`
151
-	ScheduleWeek int64 `gorm:"column:schedule_week" json:"schedule_week"`
152
-	Count        int64
153
-}
154
-
155
-func GetPrinitWeekSchedules(orgID int64, start, end int64) ([]*WeekSchedulePrintVM, error) {
156
-	var schedules []*WeekSchedulePrintVM
157
-	err := readDb.Table("xt_schedule as s").
158
-		Preload("Patient", "status = 1 and user_org_id = ?", orgID).
159
-		Preload("DeviceNumber", "status = 1 and org_id = ?", orgID).
160
-		Preload("Zone", "status = 1 and org_id = ?", orgID).
161
-		Preload("Mode", "status = 1").
162
-		// Joins("JOIN xt_patients as p ON p.id = s.patient_id").
163
-		Where("s.user_org_id = ? and s.schedule_date >= ? and s.schedule_date <= ? and s.status = 1", orgID, start, end).
164
-		// Select("s.id, s.user_org_id, s.partition_id, s.bed_id, s.patient_id, s.schedule_date, s.schedule_type, s.schedule_week, s.mode_id").
165
-		Find(&schedules).Error
166
-	return schedules, err
167
-}
168
-
169
-func GetPrinitWeekTotal(orgid int64, startime int64, endtime int64) (print []*PrintCount, err error) {
170
-
171
-	db := XTReadDB().Table("xt_schedule as x").Where("x.status = 1")
172
-	if orgid > 0 {
173
-		db = db.Where("x.user_org_id = ?", orgid)
174
-	}
175
-	if startime > 0 {
176
-		db = db.Where("x.schedule_date >=?", startime)
177
-	}
178
-	if endtime > 0 {
179
-		db = db.Where("x.schedule_date <=?", endtime)
180
-	}
181
-	err = db.Select("x.schedule_type,x.schedule_week,count(x.patient_id) as count").Group("x.schedule_date,x.schedule_type").Scan(&print).Error
182
-	return print, err
183
-}
184
-
185
-func GetBloodPrintWeekTotal(orgid int64, startime int64, endtime int64) (print []*PrintCount, err error) {
186
-
187
-	db := XTReadDB().Table("xt_schedule as x").Where("x.status = 1")
188
-	if orgid > 0 {
189
-		db = db.Where("x.user_org_id = ?", orgid)
190
-	}
191
-	if startime > 0 {
192
-		db = db.Where("x.schedule_date >=?", startime)
193
-	}
194
-	if endtime > 0 {
195
-		db = db.Where("x.schedule_date <=?", endtime)
196
-	}
197
-	db = db.Where("x.mode_id = 2")
198
-	err = db.Select("x.schedule_type,x.schedule_week,count(x.patient_id) as count").Group("x.schedule_date,x.schedule_type").Scan(&print).Error
199
-	return print, err
200
-}
201
-
202
-func GetPerfusionWeekTotal(orgid int64, startime int64, endtime int64) (print []*PrintCount, err error) {
203
-
204
-	db := XTReadDB().Table("xt_schedule as x").Where("x.status = 1")
205
-	if orgid > 0 {
206
-		db = db.Where("x.user_org_id = ?", orgid)
207
-	}
208
-	if startime > 0 {
209
-		db = db.Where("x.schedule_date >=?", startime)
210
-	}
211
-	if endtime > 0 {
212
-		db = db.Where("x.schedule_date <=?", endtime)
213
-	}
214
-	db = db.Where("x.mode_id = 3")
215
-	err = db.Select("x.schedule_type,x.schedule_week,count(x.patient_id) as count").Group("x.schedule_date,x.schedule_type").Scan(&print).Error
216
-	return print, err
217
-}
218
-
219
-// func ExchangeScheduleTimeWithWeekSchedules(orgID int64, nextWeekSchs []*models.Schedule, nextTwoWeekSchs []*models.Schedule) error {
220
-// 	templateMode, getTemplateModeErr := GetOrgPatientScheduleTemplateMode(orgID)
221
-// 	if getTemplateModeErr != nil {
222
-// 		return getTemplateModeErr
223
-// 	}
224
-// 	if templateMode == nil {
225
-// 		return errors.New("模板模式不存在")
226
-// 	}
227
-
228
-// 	tx := writeDb.Begin()
229
-
230
-// 	updateTime := time.Now().Unix()
231
-
232
-// 	for _, sch := range nextWeekSchs {
233
-// 		sch.PatientInfectiousDiseases = nil
234
-
235
-// 		date := time.Unix(sch.ScheduleDate, 0)
236
-// 		sch.ScheduleDate = date.AddDate(0, 0, 7).Unix()
237
-// 		sch.UpdatedTime = updateTime
238
-
239
-// 		updateSchErr := tx.Save(sch).Error
240
-// 		if updateSchErr != nil {
241
-// 			tx.Rollback()
242
-// 			return updateSchErr
243
-// 		}
244
-// 	}
245
-
246
-// 	for _, sch := range nextTwoWeekSchs {
247
-// 		sch.PatientInfectiousDiseases = nil
248
-
249
-// 		date := time.Unix(sch.ScheduleDate, 0)
250
-// 		sch.ScheduleDate = date.AddDate(0, 0, -7).Unix()
251
-// 		sch.UpdatedTime = updateTime
252
-
253
-// 		updateSchErr := tx.Save(sch).Error
254
-// 		if updateSchErr != nil {
255
-// 			tx.Rollback()
256
-// 			return updateSchErr
257
-// 		}
258
-// 	}
259
-
260
-// 	templateMode.ModifyTime = updateTime
261
-// 	templateMode.ExecuteTimes += 1
262
-// 	updateModeErr := tx.Save(templateMode).Error
263
-// 	if updateModeErr != nil {
264
-// 		tx.Rollback()
265
-// 		return updateModeErr
266
-// 	}
267
-
268
-// 	tx.Commit()
269
-// 	return nil
270
-// }
271
-
272
-func GetSchedualPatientsByKeywordsAndWeek(keywords string, org_id int64, start_time int64, end_time int64) (schedule []*models.Schedule, err error) {
273
-	likeKey := "%" + keywords + "%"
274
-	err = readDb.
275
-		Table("xt_schedule as s").
276
-		Preload("PatientInfectiousDiseases", "status = 1 ").
277
-		Preload("DeviceZone", "status = 1 ").
278
-		Preload("DeviceNumber", "status = 1 ").
279
-		Preload("TreatmentMode", "status = 1 ").
280
-		Joins("JOIN xt_patients as p ON p.id = s.patient_id AND (p.name LIKE ? OR p.dialysis_no LIKE ?)", likeKey, likeKey).
281
-		Where("s.user_org_id=? and s.schedule_date >= ? and s.schedule_date <= ? and s.status=1", org_id, start_time, end_time).
282
-		Select("s.id, s.user_org_id, s.partition_id, s.bed_id, s.patient_id, s.schedule_date, s.schedule_type, s.schedule_week, s.mode_id, s.status, s.created_time, s.updated_time, p.name as patient").
283
-		Order("schedule_date asc").
284
-		Find(&schedule).Error
285
-	return
286
-
287
-}
288
-
289
-func GetSchedualPatientsByKeywords(keywords string, org_id int64) (schedule []*models.Schedule, err error) {
290
-	likeKey := "%" + keywords + "%"
291
-
292
-	err = readDb.
293
-		Table("xt_schedule as s").
294
-		Preload("PatientInfectiousDiseases", "status = 1 ").
295
-		Preload("DeviceZone", "status = 1 ").
296
-		Preload("DeviceNumber", "status = 1 ").
297
-		Preload("TreatmentMode", "status = 1 ").
298
-		Joins("JOIN xt_patients as p ON p.id = s.patient_id AND (p.name LIKE ? OR p.dialysis_no LIKE ?)", likeKey, likeKey).
299
-		Where("s.user_org_id=? and s.schedule_date >= UNIX_TIMESTAMP(DATE_FORMAT(NOW(),'%Y-%m-%d 00:00:00')) and s.schedule_date <= UNIX_TIMESTAMP(DATE_FORMAT( SUBDATE(CURDATE(),DATE_FORMAT(CURDATE(),'%w')-7), '%Y-%m-%d 23:59:59')) and s.status=1", org_id).
300
-		Select("s.id, s.user_org_id, s.partition_id, s.bed_id, s.patient_id, s.schedule_date, s.schedule_type, s.schedule_week, s.mode_id, s.status, s.created_time, s.updated_time, p.name as patient").
301
-		Order("schedule_date asc").
302
-		Find(&schedule).Error
303
-	return
304
-
305
-}
306
-
307
-func GetWeekDaySchedule(orgID int64, scheduleDate int64, scheduleDates *time.Time) (schedules []*models.WeekSchedule, err error) {
308
-
309
-	err = readDb.
310
-		Table("xt_schedule as s").
311
-		Preload("DeviceZone", "status = 1 ").
312
-		Preload("DeviceNumber", "status = 1 ").
313
-		Preload("DialysisPrescription", func(db *gorm.DB) *gorm.DB {
314
-			return db.Where("status = 1").Order("id asc")
315
-		}).
316
-		Joins("JOIN xt_patients as p ON p.id = s.patient_id").
317
-		Where("s.user_org_id=? and s.schedule_date = ? and s.status=1", orgID, scheduleDate).
318
-		Select("s.id, s.user_org_id, s.partition_id, s.bed_id, s.patient_id, s.schedule_date, s.schedule_type, s.schedule_week, s.mode_id, s.status, s.created_time, s.updated_time, p.name as patient").
319
-		Order("schedule_type").
320
-		Find(&schedules).Error
321
-
322
-	for _, item := range schedules {
323
-		_, config := FindDoctorAdviceRecordByOrgId(item.UserOrgId)
324
-		if config.IsOpenRemind > 0 {
325
-			//开启推送提醒逻辑    提交长期处方的时候,弹起长期医嘱推送
326
-			var advice_three []*models.DoctorAdvice
327
-			advices, _ := GetLastLongAdviceByGroupNoOther(item.UserOrgId, item.PatientId)
328
-			advices_two, _ := GetLastLongAdviceByGroupNoThreeOther(item.UserOrgId, item.PatientId)
329
-			for _, advice := range advices {
330
-				advice.IsCheck = 1
331
-				if advice.FrequencyType == 3 {
332
-					week := int(scheduleDates.Weekday())
333
-					fmt.Println(advice.WeekDay)
334
-					switch week {
335
-					case 1:
336
-						if strings.Index(advice.WeekDay, "周一") > -1 {
337
-							advice_three = append(advice_three, advice)
338
-						}
339
-						break
340
-					case 2:
341
-						if strings.Index(advice.WeekDay, "周二") > -1 {
342
-							advice_three = append(advice_three, advice)
343
-						}
344
-						break
345
-					case 3:
346
-						if strings.Index(advice.WeekDay, "周三") > -1 {
347
-							advice_three = append(advice_three, advice)
348
-						}
349
-						break
350
-					case 4:
351
-						if strings.Index(advice.WeekDay, "周四") > -1 {
352
-							advice_three = append(advice_three, advice)
353
-						}
354
-						break
355
-					case 5:
356
-						if strings.Index(advice.WeekDay, "周五") > -1 {
357
-							advice_three = append(advice_three, advice)
358
-						}
359
-						break
360
-					case 6:
361
-						if strings.Index(advice.WeekDay, "周六") > -1 {
362
-							advice_three = append(advice_three, advice)
363
-						}
364
-						break
365
-					case 0:
366
-						if strings.Index(advice.WeekDay, "周日") > -1 {
367
-							advice_three = append(advice_three, advice)
368
-						}
369
-						break
370
-					}
371
-				} else if advice.FrequencyType == 1 {
372
-					advice_three = append(advice_three, advice)
373
-				}
374
-			}
375
-
376
-			for _, advice := range advices_two {
377
-				now := scheduleDates.Unix()
378
-				dayStr := strconv.FormatInt(advice.DayCount, 10)
379
-				dayStr2 := "-" + dayStr
380
-				count, _ := strconv.ParseInt(dayStr2, 10, 64)
381
-				oldTime := scheduleDates.AddDate(0, 0, int(count)).Unix()
382
-				advices, _ := FindAllDoctorAdviceByTimeOther(now, oldTime, item.PatientId, item.UserOrgId, advice.TemplateId)
383
-				if len(advices) == 0 {
384
-					advice_three = append(advice_three, advice)
385
-				}
386
-			}
387
-
388
-			item.DoctorAdvice = append(item.DoctorAdvice, advice_three...)
389
-		}
390
-	}
391
-	return
392
-}
393
-
394
-func RemoveRepeatedElement(arr []*models.DoctorAdvice) (newArr []*models.DoctorAdvice) {
395
-	newArr = make([]*models.DoctorAdvice, 0)
396
-	for i := 0; i < len(arr); i++ {
397
-		repeat := false
398
-		for j := i + 1; j < len(arr); j++ {
399
-			if arr[i].ID == arr[j].ID {
400
-				repeat = true
401
-				break
402
-			}
403
-		}
404
-		if !repeat {
405
-			newArr = append(newArr, arr[i])
406
-		}
407
-	}
408
-	return
409
-}
410
-
411
-func GetLastLongAdviceByGroupNoOther(orgId int64, patient_id int64) (advice []*models.DoctorAdvice, err error) {
412
-	err = readDb.Model(&models.DoctorAdvice{}).Where("status = 1 AND user_org_id = ? AND patient_id = ? AND advice_type = 1  AND stop_state = 2 AND parent_id = 0", orgId, patient_id).Preload("ChildDoctorAdvice", "status = 1").Find(&advice).Error
413
-	return
414
-}
415
-
416
-func GetLastLongAdviceByGroupNoThreeOther(orgId int64, patient_id int64) (advice []*models.DoctorAdvice, err error) {
417
-	err = readDb.Model(&models.DoctorAdvice{}).Where("status = 1 AND user_org_id = ? AND patient_id = ?  AND  advice_type = 1 AND frequency_type = 2 AND stop_state = 2 AND parent_id = 0 ", orgId, patient_id).Preload("ChildDoctorAdvice", "status = 1").Find(&advice).Error
418
-	return
419
-}
420
-
421
-func FindAllDoctorAdviceByTimeOther(now int64, end int64, patient_id int64, orgId int64, temp_id string) (advice []*models.DoctorAdvice, err error) {
422
-	err = readDb.Model(&models.DoctorAdvice{}).Where("status = 1 AND user_org_id = ? AND patient_id = ? AND advice_type = 2   AND frequency_type = 2 AND advice_date > ? AND advice_date < ? AND template_id = ?  ", orgId, patient_id, end, now, temp_id).Preload("ChildDoctorAdvice", "status = 1").Find(&advice).Error
423
-	return
424
-}
425
-
426
-func FindSchPatientNameByName(name string, user_org_id int64) (patient []*models.Patients, err error) {
427
-	err = readDb.Model(&models.Patients{}).Where("user_org_id = ? AND name = ? AND status = 1", user_org_id, name).Find(&patient).Error
428
-	return
429
-}
430
-
431
-func UpdateScheduleStatus(date int64, org_id int64) (err error) {
432
-	err = readDb.Model(&models.Schedule{}).Where("user_org_id = ? AND schedule_date > ? AND status = 1", org_id, date).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
433
-	return
434
-}
435
-
436
-func FindDeviceZoneByName(name string, org_id int64) (zone models.DeviceZone, err error) {
437
-	err = readDb.Model(&models.DeviceZone{}).Where("org_id = ? AND name = ? AND status = 1", org_id, name).First(&zone).Error
438
-	return
439
-}
440
-
441
-func FindDeviceByName(device_name string, org_id int64, zone_id int64) (devices []*models.DeviceNumber, err error) {
442
-	err = readDb.Model(&models.DeviceNumber{}).Where("org_id = ? AND number = ? AND zone_id = ? AND status = 1", org_id, device_name, zone_id).Find(&devices).Error
443
-	return
444
-}
445
-
446
-func FindSchedualExportLog(org_id int64, export_time int64) (errLogs []*models.ExportErrLog, err error) {
447
-	err = readDb.Model(&models.ExportErrLog{}).Where("user_org_id = ? AND export_time = ? AND log_type = 2", org_id, export_time).Find(&errLogs).Error
448
-	return
449
-}
450
-
451
-func FindDeviceByNameTwo(device_name string, org_id int64, zone_id int64) (devices []*models.DeviceNumber, err error) {
452
-	err = readDb.Model(&models.DeviceNumber{}).Where("org_id = ? AND number = ? AND status = 1 AND zone_id = ?", org_id, device_name, zone_id).Find(&devices).Error
453
-	return
454
-}
455
-
456
-func UpdateScheduleTemplateStatus(org_id int64) (err error) {
457
-	err = readDb.Model(&models.PatientScheduleTemplateItem{}).Where("org_id = ? AND status = 1", org_id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
458
-	return
459
-}
460
-
461
-func CreateScheduleTemplate(m *models.PatientScheduleTemplateItem) error {
462
-	return writeDb.Model(&models.PatientScheduleTemplateItem{}).Create(&m).Error
463
-}
464
-
465
-func FindSchedualTemplateExportLog(org_id int64, export_time int64) (errLogs []*models.ExportErrLog, err error) {
466
-	err = readDb.Model(&models.ExportErrLog{}).Where("user_org_id = ? AND export_time = ? AND log_type = 3", org_id, export_time).Find(&errLogs).Error
467
-	return
468
-}
469
-
470
-func GetDialysisOrderByBedId(orgID, start, bed_id int64, schedule_type int64) (schedule models.DialysisOrder, err error) {
471
-	err = readDb.Model(&models.DialysisOrder{}).Where("user_org_id=?  and dialysis_date=? and bed_id=? and status=1 AND schedual_type = ?", orgID, start, bed_id, schedule_type).First(&schedule).Error
472
-	return
473
-}
474
-
475
-type VMDeviceNumber struct {
476
-	ID         int64             `gorm:"column:id" json:"id"`
477
-	OrgID      int64             `gorm:"column:org_id" json:"-"`
478
-	Number     string            `gorm:"column:number" json:"number"`
479
-	GroupID    int64             `gorm:"column:group_id" json:"group_id"`
480
-	ZoneID     int64             `gorm:"column:zone_id" json:"zone_id"`
481
-	Status     int8              `json:"-"`
482
-	CreateTime int64             `gorm:"column:ctime" json:"-"`
483
-	ModifyTime int64             `gorm:"column:mtime" json:"-"`
484
-	DeviceZone models.DeviceZone `json:"zone" gorm:"foreignkey:ID;AssociationForeignKey:ZoneID;"`
485
-}
486
-
487
-func (VMDeviceNumber) TableName() string {
488
-	return "xt_device_number"
489
-}
490
-
491
-type VMPatientScheduleTemplateItem struct {
492
-	ID             int64 `gorm:"column:id" json:"id" form:"id"`
493
-	OrgID          int64 `gorm:"column:org_id" json:"-" form:"org_id"`
494
-	TemplateID     int64 `gorm:"column:template_id" json:"template_id" form:"template_id"`
495
-	DeviceNumberID int64 `gorm:"column:device_number_id" json:"device_number_id" form:"device_number_id"`
496
-	PatientID      int64 `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
497
-	TreatMode      int64 `gorm:"column:treat_mode" json:"treat_mode" form:"treat_mode"` // 治疗模式
498
-	Weekday        int8  `gorm:"column  :weekday" json:"weekday" form:"weekday"`        // 周一-周日 1-7
499
-	TimeType       int8  `gorm:"column:time_type" json:"time_type" form:"time_type"`    // 上下晚 123
500
-	Status         int8  `gorm:"column:status" json:"status" form:"status"`
501
-	CreateTime     int64 `gorm:"column:ctime" json:"-" form:"ctime"`
502
-	ModifyTime     int64 `gorm:"column:mtime" json:"-" form:"mtime"`
503
-	IsExport       int64 `gorm:"column:is_export" json:"is_export" form:"is_export"`
504
-
505
-	Patient      string         `gorm:"-" json:"patient" form:"patient"`
506
-	DeviceNumber VMDeviceNumber `json:"number" gorm:"foreignkey:ID;AssociationForeignKey:DeviceNumberID;"`
507
-
508
-	PatientInfectiousDiseases []*models.InfectiousDiseases `json:"patient_contagions" gorm:"foreignkey:PatientId;AssociationForeignKey:PatientId;"`
509
-}
510
-
511
-func (VMPatientScheduleTemplateItem) TableName() string {
512
-	return "xt_patient_schedule_template_item"
513
-}
514
-
515
-func GetTemplateSchedualPatientsByKeywords(keywords string, org_id int64, template_id int64) (schedule []*VMPatientScheduleTemplateItem, err error) {
516
-	likeKey := "%" + keywords + "%"
517
-
518
-	err = readDb.
519
-		Table("xt_patient_schedule_template_item as s").
520
-		Preload("PatientInfectiousDiseases", "status = 1 ").
521
-		Preload("DeviceNumber", func(db *gorm.DB) *gorm.DB {
522
-			return db.Where("org_id = ? AND status = 1", org_id).Preload("DeviceZone", "org_id = ? AND status = 1", org_id)
523
-		}).
524
-		Joins("JOIN xt_patients as p ON p.id = s.patient_id AND (p.name LIKE ? OR p.dialysis_no LIKE ?)", likeKey, likeKey).
525
-		Where("s.template_id = ? AND s.org_id=?  and s.status=1", template_id, org_id).
526
-		Select("s.id, s.org_id, s.template_id, s.device_number_id, s.patient_id, s.treat_mode, s.weekday, s.time_type, s.status, s.ctime, s.mtime, p.name as patient").
527
-		Order("weekday asc").
528
-		Find(&schedule).Error
529
-	return
530
-
531
-}
532
-
533
-func UpdateNewScheduleTemplateStatus(id int64, org_id int64) (err error) {
534
-	err = readDb.Model(&models.PatientScheduleTemplateItem{}).Where("org_id = ? AND id = ?", org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
535
-	return
536
-}

+ 0 - 270
models/service/sign_weigh_service.go Просмотреть файл

@@ -1,270 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	"fmt"
6
-	"github.com/jinzhu/gorm"
7
-)
8
-
9
-func GetSignPatients(orgId int64, keywords string, dateTime, schedule_type int64) (patients []*models.SignPatients, err error) {
10
-	db := readDb.
11
-		Table("xt_patients as p").Where("p.user_org_id=?", orgId).
12
-		Preload("SignWeight", "user_org_id = ? AND record_date=? AND status = 1", orgId, dateTime).
13
-		Preload("DialysisOrder", "user_org_id = ? and dialysis_date = ? AND status = 1  ", orgId, dateTime).
14
-		Preload("Schedule", "user_org_id = ? and schedule_date=? and status = 1", orgId, dateTime).
15
-		Preload("PredialysisEvaluation", "user_org_id = ? and  assessment_date = ?", orgId, dateTime)
16
-	if len(keywords) > 0 {
17
-		likekey := "%" + keywords + "%"
18
-		db = db.Where("p.name LIKE ? OR p.dialysis_no LIKE ? ", likekey, likekey)
19
-	}
20
-	db = db.Where("p.status=1")
21
-
22
-	if schedule_type >= 1 && schedule_type <= 3 {
23
-		db = db.Joins("JOIN xt_schedule AS s ON s.patient_id=p.id").Where("s.schedule_date = ? and s.schedule_type=? and s.status=1", dateTime, schedule_type)
24
-	}
25
-	err = db.Select("p.id, p.user_org_id, p.user_id, p.avatar, p.patient_type, p.dialysis_no, p.admission_number, p.source, p.lapseto, p.partition_id, p.bed_id, p.name, p.alias, p.gender, p.marital_status, p.id_card_no, p.birthday, p.reimbursement_way_id, p.health_care_type, p.health_care_no, p.health_care_due_date, p.height, p.blood_type, p.rh, p.health_care_due_alert_date, p.education_level, p.profession, p.phone, p.home_telephone, p.relative_phone, p.relative_relations, p.home_address, p.work_unit, p.unit_address, p.children, p.receiving_date, p.is_hospital_first_dialysis, p.first_dialysis_date, p.first_dialysis_hospital, p.predialysis_condition, p.pre_hospital_dialysis_frequency, p.pre_hospital_dialysis_times, p.hospital_first_dialysis_date, p.induction_period, p.initial_dialysis, p.total_dialysis, p.attending_doctor_id, p.head_nurse_id, p.evaluate, p.diagnose, p.remark, p.registrars_id, p.registrars, p.qr_code, p.binding_state, p.status, p.created_time, p.updated_time").Find(&patients).Error
26
-
27
-	return
28
-}
29
-
30
-//GetSignPanels  签到称重班次休息
31
-func GetSignPanels(orgid, dateTime int64) (map[int64]map[string]int64, error) {
32
-	fmt.Println(dateTime)
33
-	fmt.Println("世界的尽头")
34
-	fmt.Println(orgid)
35
-	panel := map[int64]map[string]int64{
36
-		1: {"schedule": 0, "sign": 0, "before": 0, "after": 0},
37
-		2: {"schedule": 0, "sign": 0, "before": 0, "after": 0},
38
-		3: {"schedule": 0, "sign": 0, "before": 0, "after": 0},
39
-	}
40
-	var err error
41
-
42
-	type schedule struct {
43
-		ScheduleType int64
44
-		ScheduleNums int64
45
-	}
46
-
47
-	var schedulePanels []schedule
48
-	err = readDb.Model(&models.Schedule{}).Select("schedule_type, count(schedule_type) as schedule_nums").Where("schedule_date=? and user_org_id=? and status=?", dateTime, orgid, 1).Group("schedule_type").Scan(&schedulePanels).Error
49
-	if err != nil {
50
-		return panel, err
51
-		fmt.Println("panel是什么", panel)
52
-	}
53
-	for _, schedulePanel := range schedulePanels {
54
-		if _, exist := panel[schedulePanel.ScheduleType]; exist {
55
-			panel[schedulePanel.ScheduleType]["schedule"] = schedulePanel.ScheduleNums
56
-		}
57
-	}
58
-
59
-	type sign struct {
60
-		ScheduleType int64
61
-		SignNums     int64
62
-	}
63
-
64
-	var signPanels []sign
65
-	err = readDb.Table("xt_assessment_before_dislysis as sw").Joins("JOIN xt_schedule as s ON s.patient_id = sw.patient_id").Select("count(sw.id) as sign_nums,s.schedule_type").Where("s.schedule_date = ? and sw.assessment_date = ? and s.user_org_id = ? and sw.status = 1 and s.status = 1", dateTime, dateTime, orgid).Group("s.schedule_type").Scan(&signPanels).Error
66
-
67
-	if err != nil {
68
-		return panel, err
69
-	}
70
-	fmt.Println("singpanels是什么东西", signPanels)
71
-	for _, signPanel := range signPanels {
72
-		if _, exist := panel[signPanel.ScheduleType]; exist {
73
-			panel[signPanel.ScheduleType]["sign"] = signPanel.SignNums
74
-		}
75
-	}
76
-
77
-	type befor struct {
78
-		ScheduleType int64
79
-		SignNums     int64
80
-	}
81
-
82
-	var befors []befor
83
-	err = readDb.Table("xt_assessment_before_dislysis as sw").Joins("JOIN xt_schedule as s ON s.patient_id = sw.patient_id").Select("count(sw.id) as sign_nums,s.schedule_type").Where("s.schedule_date = ? and sw.assessment_date = ? and s.user_org_id = ? and sw.status = 1 and s.status = 1", dateTime, dateTime, orgid).Group("s.schedule_type").Scan(&befors).Error
84
-
85
-	if err != nil {
86
-		return panel, err
87
-	}
88
-	fmt.Println("singpanels是什么东西", befors)
89
-	for _, signPanel := range befors {
90
-		if _, exist := panel[signPanel.ScheduleType]; exist {
91
-			panel[signPanel.ScheduleType]["before"] = signPanel.SignNums
92
-		}
93
-	}
94
-
95
-	type after struct {
96
-		ScheduleType int64
97
-		AfterNums    int64
98
-	}
99
-
100
-	var afters []after
101
-	err = readDb.Table("xt_assessment_after_dislysis as sw").Joins("JOIN xt_schedule as s ON s.patient_id = sw.patient_id").Select("count(sw.id) as after_nums,s.schedule_type").Where("s.schedule_date = ? and sw.assessment_date = ? and s.user_org_id = ? and sw.status = 1 and s.status = 1", dateTime, dateTime, orgid).Group("s.schedule_type").Scan(&afters).Error
102
-
103
-	if err != nil {
104
-		return panel, err
105
-	}
106
-	fmt.Println("after是什么东西", afters)
107
-	for _, signPanel := range afters {
108
-		if _, exist := panel[signPanel.ScheduleType]; exist {
109
-			panel[signPanel.ScheduleType]["after"] = signPanel.AfterNums
110
-		}
111
-	}
112
-
113
-	return panel, nil
114
-
115
-}
116
-
117
-func GetPatientDateSign(orgid, dateTime, patientId int64) (*models.SigninAndWeigh, error) {
118
-	var sig models.SigninAndWeigh
119
-	var err error
120
-	err = readDb.Model(&models.SigninAndWeigh{}).Where("record_date = ? and patient_id=? and user_org_id=?", dateTime, patientId, orgid).First(&sig).Error
121
-	fmt.Println("错误", err)
122
-	if err == gorm.ErrRecordNotFound {
123
-		return nil, nil
124
-	}
125
-
126
-	if err != nil {
127
-		return nil, err
128
-	}
129
-
130
-	return &sig, nil
131
-}
132
-
133
-func EditPatientSign(m *models.SigninAndWeigh) error {
134
-	var err error
135
-	if m.ID > 0 {
136
-		err = writeDb.Save(&m).Error
137
-	} else {
138
-		err = writeDb.Create(&m).Error
139
-	}
140
-	return err
141
-}
142
-
143
-func GetPatientInformationList(orgid, patientId int64, datetime int64) *models.PredialysisEvaluation {
144
-	var pre models.PredialysisEvaluation
145
-	err := readDb.Model(&models.PredialysisEvaluation{}).Where("patient_id=? and user_org_id=? and assessment_date =?", patientId, orgid, datetime).First(&pre).Error
146
-	if err != nil {
147
-
148
-	}
149
-	return &pre
150
-}
151
-
152
-func GetInforByPatient(orgid, patientId int64, datetime int64) *models.AssessmentAfterDislysis {
153
-	var ass models.AssessmentAfterDislysis
154
-	err := readDb.Model(&models.AssessmentAfterDislysis{}).Where("patient_id=? and user_org_id=? and assessment_date=?", patientId, orgid, datetime).First(&ass).Error
155
-	if err != nil {
156
-
157
-	}
158
-
159
-	return &ass
160
-}
161
-
162
-func SaveData(pre *models.PredialysisEvaluation, patientId int64, orgId int64) error {
163
-	err := writeDb.Model(pre).Where("patient_id=? and user_org_id=?", patientId, orgId).Update(map[string]interface{}{"weight_before": pre.WeightBefore,
164
-		"dry_weight": pre.DryWeight, "temperature": pre.Temperature, "pulse_frequency": pre.PulseFrequency, "breathing_rate": pre.BreathingRate, "systolic_blood_pressure": pre.SystolicBloodPressure, "diastolic_blood_pressure": pre.DiastolicBloodPressure}).Error
165
-	return err
166
-}
167
-
168
-func Editdata(dis *models.AssessmentAfterDislysis, patientId int64, orgId int64) error {
169
-	err := writeDb.Model(dis).Where("patient_id=? and user_org_id=?", patientId, orgId).Update(map[string]interface{}{"weight_after": dis.WeightAfter,
170
-		"dry_weight": dis.DryWeight, "temperature": dis.Temperature, "pulse_frequency": dis.PulseFrequency, "breathing_rate": dis.BreathingRate, "systolic_blood_pressure": dis.SystolicBloodPressure, "diastolic_blood_pressure": dis.DiastolicBloodPressure}).Error
171
-
172
-	return err
173
-}
174
-
175
-func Savesignweigh(sw *models.SignWeight) error {
176
-	var err error
177
-	err = writeDb.Create(&sw).Error
178
-	return err
179
-}
180
-func Updatesignweigh(sw *models.SignWeight, patientId int64, orgId int64) error {
181
-	writeDb.Model(sw).Where("patient_id=? and user_org_id=?", patientId, orgId).Update(map[string]interface{}{"sign_time": sw.SignTime,
182
-		"record_date": sw.RecordDate, "weightbefore": sw.WeightBefore, "dry_weight_before": sw.DryWeightBefore, "temperature_before": sw.TemperatureBefore,
183
-		"pulse_frequency_before": sw.PulseFrequencyBefore, "breathing_rate_before": sw.BreathingRateBefore, "systolic_blood_pressure_before": sw.SystolicBloodPressureBefore,
184
-		"diastolic_blood_pressure_before": sw.DiastolicBloodPressureBefore, "weightafter": sw.WeightAfter, "temperature_after": sw.TemperatureAfter, "pulse_frequency_after": sw.PulseFrequencyAfter,
185
-		"breathing_rate_after": sw.BreathingRateAfter, "systolic_blood_pressure_after": sw.SystolicBloodPressureAfter, "diastolic_blood_pressure_after": sw.DiastolicBloodPressureAfter,
186
-		"status": sw.Status, "created_time": sw.CreatedTime, "weigh_before_time": sw.WeighBeforeTime, "weigh_time": sw.WeighTime})
187
-	return err
188
-}
189
-
190
-func GetSign(orgid, dateTime, patientId int64) (*models.SignWeight, error) {
191
-	var sigs models.SignWeight
192
-	var err error
193
-	err = readDb.Model(&models.SignWeight{}).Where("record_date = ? and patient_id=? and user_org_id = ?", dateTime, patientId, orgid).First(&sigs).Error
194
-	fmt.Println("错误", err)
195
-	if err == gorm.ErrRecordNotFound {
196
-
197
-		return nil, err
198
-	}
199
-	if err != nil {
200
-		return nil, err
201
-	}
202
-	return &sigs, nil
203
-}
204
-
205
-func GetSignweigh(orgid, patientId int64) *models.SignWeight {
206
-	var sw models.SignWeight
207
-	err := readDb.Model(&models.SignWeight{}).Where("patient_id=? and user_org_id =?", patientId, orgid).First(&sw).Error
208
-	if err != nil {
209
-
210
-	}
211
-	return &sw
212
-}
213
-
214
-func GetDislysisBerfore(orgid, dateTime, patientId int64) (*models.PredialysisEvaluation, error) {
215
-	var pre models.PredialysisEvaluation
216
-	var err error
217
-	err = readDb.Model(&models.PredialysisEvaluation{}).Where("assessment_date =? and patient_id =? and user_org_id = ?", dateTime, patientId, orgid).Find(&pre).Error
218
-	fmt.Println("错误", err)
219
-	if err == gorm.ErrRecordNotFound {
220
-		return nil, err
221
-	}
222
-	if err != nil {
223
-		return nil, err
224
-	}
225
-	return &pre, nil
226
-
227
-}
228
-
229
-func SaveDislysisiBefore(pre *models.PredialysisEvaluation) error {
230
-	var err error
231
-	err = writeDb.Create(&pre).Error
232
-	return err
233
-}
234
-
235
-func UpdataDislysisiBefore(pre *models.PredialysisEvaluation, patientId int64, orgId int64, datatime int64) error {
236
-	writeDb.Model(pre).Where("patient_id=? and user_org_id=? and assessment_date =?", patientId, orgId, datatime).Update(map[string]interface{}{"weight_before": pre.WeightBefore,
237
-		"dry_weight": pre.DryWeight, "temperature": pre.Temperature, "pulse_frequency": pre.PulseFrequency, "systolic_blood_pressure": pre.SystolicBloodPressure, "diastolic_blood_pressure": pre.DiastolicBloodPressure, "status": 1})
238
-	return err
239
-}
240
-
241
-func GetAssessmentaafterdislysis(orgid, dateTime, patientId int64) (*models.AssessmentAfterDislysis, error) {
242
-	var ass models.AssessmentAfterDislysis
243
-	var err error
244
-	err = readDb.Model(&models.AssessmentAfterDislysis{}).Where("assessment_date =? and patient_id =? and user_org_id = ?", dateTime, patientId, orgid).Find(&ass).Error
245
-	fmt.Println("错误", err)
246
-	if err == gorm.ErrRecordNotFound {
247
-		return nil, err
248
-	}
249
-	if err != nil {
250
-		return nil, err
251
-	}
252
-	return &ass, nil
253
-}
254
-func SaveAssessmentafter(ass *models.AssessmentAfterDislysis) error {
255
-	var err error
256
-	err = writeDb.Create(&ass).Error
257
-	return err
258
-}
259
-
260
-func UpdataAssessment(ass *models.AssessmentAfterDislysis, patientId int64, orgId int64, datetime int64) error {
261
-	writeDb.Model(ass).Where("patient_id=? and user_org_id=? and assessment_date=? ", patientId, orgId, datetime).Update(map[string]interface{}{"weight_after": ass.WeightAfter,
262
-		"dry_weight": ass.DryWeight, "temperature": ass.Temperature, "pulse_frequency": ass.PulseFrequency, "systolic_blood_pressure": ass.SystolicBloodPressure, "diastolic_blood_pressure": ass.DiastolicBloodPressure, "status": 1})
263
-	return err
264
-}
265
-
266
-func GetForenoonData(dataTime int64, orgid int64, scheduleType int64) (total int64, schedule []*models.Schedule, err error) {
267
-	err = readDb.Count(total).Where("schedule_date = ? AND user_org_id = ? AND schedule_type = ?", dataTime, orgid, scheduleType).Find(&scheduleType).Error
268
-	fmt.Println("heeeeeeeeeehhhhh", err)
269
-	return total, schedule, err
270
-}

+ 0 - 185
models/service/sms_service.go Просмотреть файл

@@ -1,185 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"bytes"
5
-	"encoding/json"
6
-	"io/ioutil"
7
-	"net/http"
8
-	"strconv"
9
-	"strings"
10
-	"time"
11
-
12
-	"XT_New/utils"
13
-
14
-	"github.com/astaxie/beego"
15
-)
16
-
17
-type SMSServiceError struct {
18
-	Err string
19
-}
20
-
21
-func (e *SMSServiceError) Error() string {
22
-	return e.Err
23
-}
24
-
25
-/* public */
26
-
27
-// 发送验证码短信
28
-func SMSSendVerificationCode(mobile string) error {
29
-	if len(mobile) == 0 {
30
-		return &SMSServiceError{Err: "手机号为空"}
31
-	}
32
-	if err := checkVerificationCodeSMSLimit(mobile); err != nil {
33
-		return err
34
-	}
35
-
36
-	code_str := utils.RandomNumberString(6)
37
-	templateID, _ := beego.AppConfig.Int("sms_verification_code_templateid")
38
-	_, _, _, err := singleSendMessageUseUCPaas(templateID, []string{code_str}, mobile)
39
-	if err == nil {
40
-		redisClient := RedisClient()
41
-		defer redisClient.Close()
42
-		cur_date := time.Now().Format("2006-01-02")
43
-		redisClient.Set("xt_modify_pwd_"+mobile, code_str, time.Minute*10)
44
-		redisClient.Incr("xt_modify_pwd_" + mobile + "_" + cur_date).Result()
45
-	}
46
-	return err
47
-}
48
-
49
-// 成为机构管理员的邀请短信
50
-func SMSSendInviteMobileToJoinOrgAdmin(name string, mobile string, password string) error {
51
-	if len(mobile) == 0 {
52
-		return &SMSServiceError{Err: "手机号为空"}
53
-	}
54
-	if len(password) == 0 {
55
-		_, _, _, err := singleSendMessageUseUCPaas(332784, []string{name, mobile}, mobile)
56
-		return err
57
-	} else {
58
-		_, _, _, err := singleSendMessageUseUCPaas(332783, []string{name, mobile, password}, mobile)
59
-		return err
60
-	}
61
-}
62
-
63
-/* private */
64
-
65
-// 检查验证码短信请求限制
66
-func checkVerificationCodeSMSLimit(mobile string) error {
67
-	redisClient := RedisClient()
68
-	defer redisClient.Close()
69
-
70
-	cur_date := time.Now().Format("2006-01-02")
71
-	moblie_count, _ := redisClient.Get("xt_modify_pwd_" + mobile + "_" + cur_date).Result()
72
-	moblie_count_int, _ := strconv.Atoi(moblie_count)
73
-	if moblie_max := 5; moblie_count_int >= moblie_max {
74
-		return &SMSServiceError{Err: "当前手机号发送短信超过限制"}
75
-	}
76
-
77
-	return nil
78
-}
79
-
80
-/* 最底层的短信平台创建模板和发送短信的函数 */
81
-
82
-// 获取短信平台信息
83
-func getSMSConfig() (string, string, string) {
84
-	return beego.AppConfig.String("sms_appId"),
85
-		beego.AppConfig.String("sms_sid"),
86
-		beego.AppConfig.String("sms_token")
87
-}
88
-
89
-// 用云之讯群发模板短信
90
-// 返回值为发送了 n 条短信
91
-func batchSendMessageUseUCPaas(templateID int, params []string, mobiles []string) (int, []interface{}, error) {
92
-	sms_api := beego.AppConfig.String("sms_baseUrl") + "sendsms_batch"
93
-	mobileStr := strings.Join(mobiles, ",")
94
-	appID, sid, token := getSMSConfig()
95
-	requestParams := make(map[string]interface{})
96
-	requestParams["appid"] = appID
97
-	requestParams["sid"] = sid
98
-	requestParams["token"] = token
99
-	requestParams["templateid"] = strconv.Itoa(templateID)
100
-	requestParams["mobile"] = mobileStr
101
-	if params != nil && len(params) != 0 {
102
-		paramStr := strings.Join(params, ",")
103
-		requestParams["param"] = paramStr
104
-	}
105
-
106
-	paramsBytes, _ := json.Marshal(requestParams)
107
-	resp, requestErr := http.Post(sms_api, "application/json", bytes.NewBuffer(paramsBytes))
108
-
109
-	if requestErr != nil {
110
-		utils.ErrorLog("短信平台模板群发接口调用失败: %v", requestErr)
111
-		return 0, nil, requestErr
112
-	}
113
-	defer resp.Body.Close()
114
-	body, ioErr := ioutil.ReadAll(resp.Body)
115
-	if ioErr != nil {
116
-		utils.ErrorLog("短信平台模板群发接口返回数据读取失败: %v", ioErr)
117
-		return 0, nil, ioErr
118
-	}
119
-	var respJSON map[string]interface{}
120
-	utils.InfoLog(string(body))
121
-	if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
122
-		utils.ErrorLog("短信平台模板群发接口返回数据解析JSON失败: %v", err)
123
-		return 0, nil, err
124
-	}
125
-	if respJSON["code"].(string) != "000000" {
126
-		msg := respJSON["msg"].(string)
127
-		utils.ErrorLog("短信平台模板群发接口请求失败: %v", msg)
128
-		return 0, nil, &SMSServiceError{"短信平台模板群发接口请求失败"}
129
-
130
-	} else {
131
-		utils.SuccessLog("短信发送成功 report: %v", respJSON["report"])
132
-		if len(mobiles) > 1 {
133
-			count, _ := strconv.Atoi(respJSON["count_sum"].(string))
134
-			return count, respJSON["report"].([]interface{}), nil
135
-		} else {
136
-			return 1, nil, nil
137
-		}
138
-	}
139
-}
140
-
141
-// 用云之讯单发模板短信
142
-// 返回值分别是 是否成功,code,msg,error
143
-func singleSendMessageUseUCPaas(templateID int, params []string, mobile string) (bool, string, string, error) {
144
-	sms_api := beego.AppConfig.String("sms_baseUrl") + "sendsms"
145
-	appID, sid, token := getSMSConfig()
146
-	requestParams := make(map[string]interface{})
147
-	requestParams["appid"] = appID
148
-	requestParams["sid"] = sid
149
-	requestParams["token"] = token
150
-	requestParams["templateid"] = strconv.Itoa(templateID)
151
-	requestParams["mobile"] = mobile
152
-	if params != nil && len(params) != 0 {
153
-		paramStr := strings.Join(params, ",")
154
-		requestParams["param"] = paramStr
155
-	}
156
-
157
-	paramsBytes, _ := json.Marshal(requestParams)
158
-	resp, requestErr := http.Post(sms_api, "application/json", bytes.NewBuffer(paramsBytes))
159
-
160
-	if requestErr != nil {
161
-		utils.ErrorLog("短信平台模板群发接口调用失败: %v", requestErr)
162
-		return false, "", "", requestErr
163
-	}
164
-	defer resp.Body.Close()
165
-	body, ioErr := ioutil.ReadAll(resp.Body)
166
-	if ioErr != nil {
167
-		utils.ErrorLog("短信平台模板群发接口返回数据读取失败: %v", ioErr)
168
-		return false, "", "", ioErr
169
-	}
170
-	var respJSON map[string]interface{}
171
-	utils.InfoLog(string(body))
172
-	if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
173
-		utils.ErrorLog("短信平台模板群发接口返回数据解析JSON失败: %v", err)
174
-		return false, "", "", err
175
-	}
176
-	if respJSON["code"].(string) != "000000" {
177
-		msg := respJSON["msg"].(string)
178
-		utils.ErrorLog("短信平台模板群发接口请求失败: %v", msg)
179
-		return false, "", "", &SMSServiceError{"短信平台模板群发接口请求失败"}
180
-
181
-	} else {
182
-		utils.SuccessLog("短信发送成功")
183
-		return true, respJSON["code"].(string), respJSON["msg"].(string), nil
184
-	}
185
-}

+ 0 - 73
models/service/statistics_service.go Просмотреть файл

@@ -1,73 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-)
6
-
7
-func GetDayDialysisCount(orgID, date int64) (total int64) {
8
-	readDb.Model(&models.DialysisOrder{}).Where("user_org_id=? and dialysis_date=? and status=1", orgID, date).Count(&total)
9
-	return
10
-}
11
-
12
-func GetTimebetweenDialysisCount(orgID, start, end int64) (total int64) {
13
-	readDb.Model(&models.DialysisOrder{}).Where("user_org_id=? and dialysis_date>=? and dialysis_date<=? and status=1", orgID, start, end).Count(&total)
14
-	return
15
-}
16
-
17
-type PatientContagionsCountStruct struct {
18
-	DiseaseId int64 `json:"disease_id"`
19
-	Count     int64 `json:"count"`
20
-}
21
-
22
-func GetPatientContagionCounts(orgID int64) (counts []*PatientContagionsCountStruct) {
23
-	readDb.Table("xt_patients_infectious_diseases AS pid").Joins("JOIN xt_patients AS p ON p.id=pid.patient_id").Where("p.user_org_id=? and p.status=1 and pid.status=1", orgID).Select("pid.disease_id, count(pid.disease_id) as count").Group("pid.disease_id").Scan(&counts)
24
-	return
25
-}
26
-
27
-type PatientGenderCountStruct struct {
28
-	Gender int64 `json:"gender"`
29
-	Count  int64 `json:"count"`
30
-}
31
-
32
-func GetPatientGenderCounts(orgID int64) (counts []*PatientGenderCountStruct) {
33
-	readDb.Model(&models.Patients{}).Where("user_org_id=? and status=1", orgID).Select("gender, count(gender) as count").Group("gender").Scan(&counts)
34
-	return
35
-}
36
-
37
-type PatientAgeCountStruct struct {
38
-	Age   int64 `json:"age"`
39
-	Count int64 `json:"count"`
40
-}
41
-
42
-func GetPatiendAgeBetweenCount(orgID int64) (counts []*PatientAgeCountStruct) {
43
-	readDb.Raw(`SELECT nnd AS 'age',COUNT(*) AS 'count' FROM(
44
-	 SELECT
45
-	 CASE
46
-	  WHEN (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + ( DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%m%d') <= DATE_FORMAT(NOW(), '%m%d') )<10 THEN '10'
47
-	  WHEN (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + ( FROM_UNIXTIME(birthday, '%m%d') <= DATE_FORMAT(NOW(), '%m%d') )>=10 AND (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + ( FROM_UNIXTIME(birthday, '%m%d') <= DATE_FORMAT(NOW(), '%m%d') )<20 THEN '20'
48
-	  WHEN (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + ( FROM_UNIXTIME(birthday, '%m%d') <= DATE_FORMAT(NOW(), '%m%d') )>=20 AND (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + ( FROM_UNIXTIME(birthday, '%m%d') <= DATE_FORMAT(NOW(), '%m%d') )<30 THEN '30'
49
-	  WHEN (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + ( FROM_UNIXTIME(birthday, '%m%d') <= DATE_FORMAT(NOW(), '%m%d') )>=30 AND (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + ( FROM_UNIXTIME(birthday, '%m%d') <= DATE_FORMAT(NOW(), '%m%d') )<40 THEN '40'
50
-	  WHEN (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + ( FROM_UNIXTIME(birthday, '%m%d') <= DATE_FORMAT(NOW(), '%m%d') )>=40 AND (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + ( FROM_UNIXTIME(birthday, '%m%d') <= DATE_FORMAT(NOW(), '%m%d') )<50 THEN '50'
51
-	  WHEN (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + ( FROM_UNIXTIME(birthday, '%m%d') <= DATE_FORMAT(NOW(), '%m%d') )>=50 AND (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + ( FROM_UNIXTIME(birthday, '%m%d') <= DATE_FORMAT(NOW(), '%m%d') )<60 THEN '60'
52
-	  WHEN (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + ( FROM_UNIXTIME(birthday, '%m%d') <= DATE_FORMAT(NOW(), '%m%d') )>=60 AND (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + ( FROM_UNIXTIME(birthday, '%m%d') <= DATE_FORMAT(NOW(), '%m%d') )<70 THEN '70'
53
-	  WHEN (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + ( FROM_UNIXTIME(birthday, '%m%d') <= DATE_FORMAT(NOW(), '%m%d') )>=70 AND (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + ( FROM_UNIXTIME(birthday, '%m%d') <= DATE_FORMAT(NOW(), '%m%d') )<80 THEN '80'
54
-	  WHEN (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + ( FROM_UNIXTIME(birthday, '%m%d') <= DATE_FORMAT(NOW(), '%m%d') )>=80 AND (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + ( FROM_UNIXTIME(birthday, '%m%d') <= DATE_FORMAT(NOW(), '%m%d') )<90 THEN '90'
55
-	  WHEN (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + ( FROM_UNIXTIME(birthday, '%m%d') <= DATE_FORMAT(NOW(), '%m%d') )>=90 AND (YEAR(NOW())-DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL birthday SECOND),'%Y')-1) + ( FROM_UNIXTIME(birthday, '%m%d') <= DATE_FORMAT(NOW(), '%m%d') )<100 THEN '100'
56
-	  ELSE '-1'
57
-	 END
58
-	 AS nnd FROM xt_patients where user_org_id=? and status=1
59
-	 )a GROUP BY nnd`, orgID).Scan(&counts)
60
-	return
61
-}
62
-
63
-type DialysisModeCountStruct struct {
64
-	Date      int64  `json:"date"`
65
-	Mode      int64  `json:"mode"`
66
-	Count     int64  `json:"count"`
67
-	DateMonth string `json:"date_month"`
68
-}
69
-
70
-func GetPatientDialysisModeBetweenCount(orgID int64, start, end int64) (counts []*DialysisModeCountStruct) {
71
-	readDb.Raw(`SELECT o.dialysis_date as date, p.mode_id as mode, count(p.mode_id) as count, FROM_UNIXTIME(o.dialysis_date, '%Y-%m') as date_month from xt_dialysis_order as o JOIN xt_dialysis_prescription as p ON p.record_date=o.dialysis_date WHERE o.user_org_id=? and p.user_org_id=? and o.status=1 and p.status=1 and o.dialysis_date>=? and o.dialysis_date<? group by FROM_UNIXTIME(o.dialysis_date, '%Y%m'), p.mode_id`, orgID, orgID, start, end).Scan(&counts)
72
-	return
73
-}

Разница между файлами не показана из-за своего большого размера
+ 0 - 1778
models/service/statistics_service/index_evaluation_service.go


+ 0 - 185
models/service/statistics_service/index_models.go Просмотреть файл

@@ -1,185 +0,0 @@
1
-package statistics_service
2
-
3
-type VMDialysisPrescription struct {
4
-	ID                         int64   `gorm:"column:id" json:"id"`
5
-	UserOrgId                  int64   `gorm:"column:user_org_id" json:"user_org_id"`
6
-	PatientId                  int64   `gorm:"column:patient_id" json:"patient_id"`
7
-	Anticoagulant              int64   `gorm:"column:anticoagulant" json:"anticoagulant"`
8
-	ModeId                     int64   `gorm:"column:mode_id" json:"mode_id"`
9
-	DialysisDuration           float64 `gorm:"column:dialysis_duration" json:"dialysis_duration"`
10
-	Kalium                     float64 `gorm:"column:kalium" json:"kalium"`
11
-	Sodium                     float64 `gorm:"column:sodium" json:"sodium"`
12
-	Calcium                    float64 `gorm:"column:calcium" json:"calcium"`
13
-	Status                     int64   `gorm:"column:status" json:"status"`
14
-	RecordDate                 int64   `gorm:"column:record_date" json:"record_date"`
15
-	DialysisDurationHour       int64   `gorm:"column:dialysis_duration_hour" json:"dialysis_duration_hour"`
16
-	DialysisDurationMinute     int64   `gorm:"column:dialysis_duration_minute" json:"dialysis_duration_minute"`
17
-	TargetUltrafiltration      float64 `gorm:"column:target_ultrafiltration" json:"target_ultrafiltration"`
18
-	DialyzerPerfusionApparatus string  `gorm:"column:dialyzer_perfusion_apparatus" json:"dialyzer_perfusion_apparatus"`
19
-	AnticoagulantStopTimeMin   int64   `gorm:"column:anticoagulant_stop_time_min" json:"anticoagulant_stop_time_min" form:"anticoagulant_stop_time_min"`
20
-	AnticoagulantStopTimeHour  int64   `gorm:"column:anticoagulant_stop_time_hour" json:"anticoagulant_stop_time_hour" form:"anticoagulant_stop_time_hour"`
21
-
22
-	HemodialysisPipelines      string  `gorm:"column:hemodialysis_pipelines" json:"hemodialysis_pipelines" form:"hemodialysis_pipelines"`
23
-	HemodialysisPipelinesCount float64 `gorm:"column:hemodialysis_pipelines_count" json:"hemodialysis_pipelines_count" form:"hemodialysis_pipelines_count"`
24
-	PunctureNeedle             string  `gorm:"column:puncture_needle" json:"puncture_needle" form:"puncture_needle"`
25
-	PunctureNeedleCount        float64 `gorm:"column:puncture_needle_count" json:"puncture_needle_count" form:"puncture_needle_count"`
26
-	Epo                        string  `gorm:"column:epo" json:"epo" form:"epo"`
27
-	EpoCount                   float64 `gorm:"column:epo_count" json:"epo_count" form:"epo_count"`
28
-}
29
-
30
-func (VMDialysisPrescription) TableName() string {
31
-	return "xt_dialysis_prescription"
32
-}
33
-
34
-type VMPredialysisEvaluation struct {
35
-	ID                        int64                     `gorm:"column:id" json:"id"`
36
-	UserOrgId                 int64                     `gorm:"column:user_org_id" json:"user_org_id"`
37
-	PatientId                 int64                     `gorm:"column:patient_id" json:"patient_id"`
38
-	AssessmentDate            int64                     `gorm:"column:assessment_date" json:"assessment_date"`
39
-	PulseFrequency            float64                   `gorm:"column:pulse_frequency" json:"pulse_frequency"`
40
-	SystolicBloodPressure     float64                   `gorm:"column:systolic_blood_pressure" json:"systolic_blood_pressure"`
41
-	DiastolicBloodPressure    float64                   `gorm:"column:diastolic_blood_pressure" json:"diastolic_blood_pressure"`
42
-	DryWeight                 float64                   `gorm:"column:dry_weight" json:"dry_weight"`
43
-	WeighingBefore            float64                   `gorm:"column:weighing_before" json:"weighing_before"`
44
-	WeightBefore              float64                   `gorm:"column:weight_before" json:"weight_before"`
45
-	BloodAccessPartId         string                    `gorm:"column:blood_access_part_id" json:"blood_access_part_id"`
46
-	VMAssessmentAfterDislysis VMAssessmentAfterDislysis `gorm:"ForeignKey:PatientId,AssessmentDate;AssociationForeignKey:PatientId,AssessmentDate" json:"after"`
47
-	VMPatients                VMPatients                `gorm:"ForeignKey:ID;AssociationForeignKey:PatientId" json:"patient"`
48
-	LastAfterWeight           float64                   `gorm:"-" json:"last_after_weight"`
49
-}
50
-
51
-func (VMPredialysisEvaluation) TableName() string {
52
-	return "xt_assessment_before_dislysis"
53
-}
54
-
55
-type VMAssessmentAfterDislysis struct {
56
-	ID                     int64   `gorm:"column:id" json:"id"`
57
-	UserOrgId              int64   `gorm:"column:user_org_id" json:"user_org_id"`
58
-	PatientId              int64   `gorm:"column:patient_id" json:"patient_id"`
59
-	AssessmentDate         int64   `gorm:"column:assessment_date" json:"assessment_date"`
60
-	PulseFrequency         float64 `gorm:"column:pulse_frequency" json:"pulse_frequency"`
61
-	SystolicBloodPressure  float64 `gorm:"column:systolic_blood_pressure" json:"systolic_blood_pressure"`
62
-	DiastolicBloodPressure float64 `gorm:"column:diastolic_blood_pressure" json:"diastolic_blood_pressure"`
63
-	ActualUltrafiltration  float64 `gorm:"column:actual_ultrafiltration" json:"actual_ultrafiltration"`
64
-	WeighingWay            string  `gorm:"column:weighing_way" json:"weighing_way"`
65
-	WeightAfter            float64 `gorm:"column:weight_after" json:"weight_after"`
66
-}
67
-
68
-func (VMAssessmentAfterDislysis) TableName() string {
69
-	return "xt_assessment_after_dislysis"
70
-}
71
-
72
-type VMPatients struct {
73
-	ID        int64  `gorm:"column:id" json:"id" form:"id"`
74
-	UserOrgId int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
75
-	Name      string `gorm:"column:name" json:"name" form:"name"`
76
-	Lapseto   int64  `gorm:"column:lapseto" json:"lapseto" form:"lapseto"`
77
-}
78
-
79
-func (VMPatients) TableName() string {
80
-	return "xt_patients"
81
-}
82
-
83
-type VMSchedule struct {
84
-	UserOrgId                 int64                     `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
85
-	BedId                     int64                     `gorm:"column:bed_id" json:"bed_id" form:"bed_id"`
86
-	ScheduleDate              int64                     `gorm:"column:schedule_date" json:"schedule_date" form:"schedule_date"`
87
-	PatientId                 int64                     `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
88
-	Status                    int64                     `gorm:"column:status" json:"status" form:"status"`
89
-	VMPredialysisEvaluation   VMPredialysisEvaluation   `gorm:"ForeignKey:AssessmentDate,PatientId;AssociationForeignKey:ScheduleDate,PatientId" json:"before"`
90
-	VMAssessmentAfterDislysis VMAssessmentAfterDislysis `gorm:"ForeignKey:AssessmentDate,PatientId;AssociationForeignKey:ScheduleDate,PatientId" json:"after"`
91
-	VMMinMonitoringRecord     VMMonitoringRecord        `gorm:"ForeignKey:MonitoringDate,PatientId;AssociationForeignKey:ScheduleDate,PatientId" json:"min_monitor"`
92
-	VMMaxMonitoringRecord     VMMonitoringRecord        `gorm:"ForeignKey:MonitoringDate,PatientId;AssociationForeignKey:ScheduleDate,PatientId" json:"max_monitor"`
93
-	VMPatients                VMPatients                `gorm:"ForeignKey:ID;AssociationForeignKey:PatientId" json:"patient"`
94
-}
95
-
96
-func (VMSchedule) TableName() string {
97
-	return "xt_schedule"
98
-}
99
-
100
-type VMMonitoringRecord struct {
101
-	ID                     int64   `gorm:"column:id" json:"id" form:"id"`
102
-	UserOrgId              int64   `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
103
-	PatientId              int64   `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
104
-	MonitoringDate         int64   `gorm:"column:monitoring_date" json:"monitoring_date" form:"monitoring_date"`
105
-	MonitoringTime         string  `gorm:"column:monitoring_time" json:"monitoring_time" form:"monitoring_time"`
106
-	SystolicBloodPressure  float64 `gorm:"column:systolic_blood_pressure" json:"systolic_blood_pressure" form:"systolic_blood_pressure"`
107
-	DiastolicBloodPressure float64 `gorm:"column:diastolic_blood_pressure" json:"diastolic_blood_pressure" form:"diastolic_blood_pressure"`
108
-	Status                 int64   `gorm:"column:status" json:"status" form:"status"`
109
-	OperateTime            int64   `gorm:"column:operate_time" json:"operate_time" form:"operate_time"`
110
-	PulseFrequency         float64 `gorm:"column:pulse_frequency" json:"pulse_frequency"`
111
-	BreathingRate          float64 `gorm:"column:breathing_rate" json:"breathing_rate"`
112
-	Temperature            float64 `gorm:"column:temperature" json:"temperature"`
113
-	BloodFlowVolume        float64 `gorm:"column:blood_flow_volume" json:"blood_flow_volume"`
114
-	VenousPressure         float64 `gorm:"column:venous_pressure" json:"venous_pressure"`
115
-	ArterialPressure       float64 `gorm:"column:arterial_pressure" json:"arterial_pressure"`
116
-	TransmembranePressure  float64 `gorm:"column:transmembrane_pressure" json:"transmembrane_pressure"`
117
-	DialysateTemperature   float64 `gorm:"column:dialysate_temperature" json:"dialysate_temperature"`
118
-	UltrafiltrationRate    float64 `gorm:"column:ultrafiltration_rate" json:"ultrafiltration_rate"`
119
-	UltrafiltrationVolume  float64 `gorm:"column:ultrafiltration_volume" json:"ultrafiltration_volume"`
120
-}
121
-
122
-func (VMMonitoringRecord) TableName() string {
123
-	return "xt_monitoring_record"
124
-}
125
-
126
-type VMUserAdminRole struct {
127
-	ID          int64  `gorm:"column:id" json:"id" form:"id"`
128
-	AdminUserId int64  `gorm:"column:admin_user_id" json:"admin_user_id" form:"admin_user_id"`
129
-	OrgId       int64  `gorm:"column:org_id" json:"org_id" form:"org_id"`
130
-	UserName    string `gorm:"column:user_name" json:"user_name" form:"user_name"`
131
-
132
-	PCount      int64 `gorm:"-" json:"p_count"`
133
-	CourseCount int64 `gorm:"-" json:"course_count" `
134
-	RescueCount int64 `gorm:"-" json:"rescue_count" `
135
-
136
-	PunctureCount       int64 `gorm:"-" json:"puncture_count" `
137
-	ChangemedicineCount int64 `gorm:"-" json:"change_medicine_count" `
138
-	CureCount           int64 `gorm:"-" json:"cure_count" `
139
-	MissionCount        int64 `gorm:"-" json:"mission_count" `
140
-
141
-	PRatio      string `gorm:"-" json:"p_ratio"`
142
-	CourseRatio string `gorm:"-" json:"course_ratio" `
143
-	RescueRatio string `gorm:"-" json:"rescue_ratio" `
144
-
145
-	PunctureRatio       string `gorm:"-" json:"puncture_ratio" `
146
-	ChangemedicineRatio string `gorm:"-" json:"change_medicine_ratio" `
147
-	CureRatio           string `gorm:"-" json:"cure_ratio" `
148
-	MissionRatio        string `gorm:"-" json:"mission_ratio" `
149
-}
150
-
151
-func (VMUserAdminRole) TableName() string {
152
-	return "sgj_user_admin_role"
153
-}
154
-
155
-type VMDeviceNumber struct {
156
-	ID      int64  `gorm:"column:id" json:"id" form:"id"`
157
-	OrgId   int64  `gorm:"column:org_id" json:"org_id" form:"org_id"`
158
-	Number  string `gorm:"column:number" json:"number" form:"number"`
159
-	GroupId int64  `gorm:"column:group_id" json:"group_id" form:"group_id"`
160
-	ZoneId  int64  `gorm:"column:zone_id" json:"zone_id" form:"zone_id"`
161
-	Status  int64  `gorm:"column:status" json:"status" form:"status"`
162
-	Ctime   int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
163
-	Mtime   int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
164
-}
165
-
166
-func (VMDeviceNumber) TableName() string {
167
-	return "xt_device_number"
168
-}
169
-
170
-type QualityControlStandard struct {
171
-	ID              int64  `gorm:"column:id" json:"id" form:"id"`
172
-	InspectionMajor int64  `gorm:"column:inspection_major" json:"inspection_major" form:"inspection_major"`
173
-	InspectionMinor int64  `gorm:"column:inspection_minor" json:"inspection_minor" form:"inspection_minor"`
174
-	MinRange        string `gorm:"column:min_range" json:"min_range" form:"min_range"`
175
-	LargeRange      string `gorm:"column:large_range" json:"large_range" form:"large_range"`
176
-	Sort            int64  `gorm:"column:sort" json:"sort" form:"sort"`
177
-	UserOrgId       int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
178
-	Status          int64  `gorm:"column:status" json:"status" form:"status"`
179
-	CreatedTime     int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
180
-	UpdatedTime     int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
181
-}
182
-
183
-func (QualityControlStandard) TableName() string {
184
-	return "xt_quality_control_standard"
185
-}

Разница между файлами не показана из-за своего большого размера
+ 0 - 2131
models/service/stock_service.go


+ 0 - 34
models/service/subscibe_service.go Просмотреть файл

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

+ 0 - 160
models/service/user_service.go Просмотреть файл

@@ -1,160 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-
6
-	"fmt"
7
-	"github.com/jinzhu/gorm"
8
-	"time"
9
-)
10
-
11
-func GetAdminUserByUserID(userID int64) (*models.AdminUser, error) {
12
-	var user models.AdminUser
13
-	err := readUserDb.Model(&models.AdminUser{}).Where("id = ?", userID).First(&user).Error
14
-	if err != nil {
15
-		if err == gorm.ErrRecordNotFound {
16
-			return nil, nil
17
-		} else {
18
-			return nil, err
19
-		}
20
-	}
21
-	return &user, nil
22
-}
23
-
24
-type AdminUserList struct {
25
-	Id       int64  `json:"id"`
26
-	Name     string `json:"name"`
27
-	UserType int64  `json:"user_type"`
28
-}
29
-
30
-func GetAllDoctorAndNurse(orgId, appid int64) (doctors []AdminUserList, nurses []AdminUserList, err error) {
31
-
32
-	var users []AdminUserList
33
-	err = readUserDb.Table("sgj_user_admin_role as uar").Joins("JOIN sgj_user_admin as ua ON ua.id = uar.admin_user_id").Where("uar.status=1 and org_id=? and app_id =? and uar.user_type IN (2,3) and ua.status=1", orgId, appid).Select("ua.id, uar.user_name as name, uar.user_type").Scan(&users).Error
34
-	if err != nil {
35
-		return
36
-	}
37
-	if len(users) == 0 {
38
-		return
39
-	}
40
-	for _, item := range users {
41
-		if item.UserType == 2 {
42
-			doctors = append(doctors, item)
43
-		} else {
44
-			nurses = append(nurses, item)
45
-		}
46
-	}
47
-	return
48
-}
49
-
50
-func GetAllAdminUsers(orgId, appid int64) (list []*AdminUserList, err error) {
51
-	//fmt.Println("orgid", orgId)
52
-	//fmt.Println("appid", appid)
53
-	err = readUserDb.Table("sgj_user_admin_role as uar").Joins("JOIN sgj_user_admin as ua ON ua.id = uar.admin_user_id").Where("uar.status=1 and uar.org_id=? and uar.app_id =? and ua.status=1", orgId, appid).Select("ua.id, uar.user_name as name, uar.user_type").Scan(&list).Error
54
-	//err = readUserDb.Table("sgj_user_admin_role as uar").Joins("JOIN sgj_user_admin as ua ON ua.id = uar.admin_user_id").Where("uar.status=1  and ua.status=1").Select("ua.id, uar.user_name as name, uar.user_type").Scan(&list).Error
55
-	return
56
-}
57
-
58
-func GetAdminUser(orgId, appid, id int64) (*AdminUserList, error) {
59
-	var err error
60
-	var user AdminUserList
61
-	err = readUserDb.Table("sgj_user_admin_role as uar").Joins("JOIN sgj_user_admin as ua ON ua.id = uar.admin_user_id").Where("uar.status=1 and uar.org_id=? and uar.app_id =? and uar.admin_user_id = ? and ua.status=1", orgId, appid, id).Select("ua.id, uar.user_name as name, uar.user_type").Order("uar.id ASC").Take(&user).Error
62
-
63
-	if err == gorm.ErrRecordNotFound {
64
-		return nil, nil
65
-	}
66
-
67
-	if err != nil {
68
-		return nil, err
69
-	}
70
-	return &user, nil
71
-}
72
-
73
-func GetSgjUserByMobild(mobile string) (user models.SgjUser, err error) {
74
-	err = readUserDb.Model(&models.SgjUser{}).Where("mobile=?", mobile).First(&user).Error
75
-	return
76
-}
77
-
78
-func GetSgjCoustomerByMobile(orgId int64, mobile string) (*models.SgjCustomer, error) {
79
-	var c models.SgjCustomer
80
-	var err error
81
-	err = readUserDb.Model(&models.SgjCustomer{}).Where("user_org_id=? and mobile=?", orgId, mobile).First(&c).Error
82
-	return &c, err
83
-}
84
-
85
-func GetAllGeneralAdminUsers(orgId, appid int64) (users []AdminUserList, err error) {
86
-	err = readUserDb.Table("sgj_user_admin_role as uar").Joins("JOIN sgj_user_admin as ua ON ua.id = uar.admin_user_id").Where("uar.status=1 and org_id=? and app_id =? and uar.user_type <> 1 and ua.status=1", orgId, appid).Select("ua.id, uar.user_name as name, uar.user_type").Scan(&users).Error
87
-	return
88
-}
89
-
90
-func GetDryWeightByPatientId(patientid int64, orgid int64) (pre []*models.SgjPatientDryweight, err error) {
91
-
92
-	err = XTReadDB().Where("patient_id = ? AND user_org_id = ?", patientid, orgid).Last(&pre).Error
93
-	return pre, err
94
-}
95
-
96
-func GetAllDoctor(orgid int64, appid int64) (appRole []*models.App_Role, err error) {
97
-
98
-	err = UserReadDB().Where("org_id = ? AND app_id = ? AND status = ? AND  (user_type = ? OR user_type = ?) ", orgid, appid, 1, 2, 1).Find(&appRole).Error
99
-	return appRole, err
100
-}
101
-
102
-func QueryDryWeight(orgid int64, patientid int64) (*models.SgjPatientDryweight, error) {
103
-	var dryweight models.SgjPatientDryweight
104
-	var err error
105
-	err = XTReadDB().Where("user_org_id = ? AND patient_id = ?", orgid, patientid).Find(&dryweight).Error
106
-	if err == gorm.ErrRecordNotFound {
107
-
108
-		return nil, err
109
-	}
110
-	if err != nil {
111
-		return nil, err
112
-	}
113
-	return &dryweight, nil
114
-}
115
-
116
-func CreatePatientWeight(dryweight *models.SgjPatientDryweight) error {
117
-
118
-	err := XTWriteDB().Create(&dryweight).Error
119
-	return err
120
-}
121
-
122
-func GetLastData(orgid int64) (models.SgjPatientDryweight, error) {
123
-	dryweight := models.SgjPatientDryweight{}
124
-	err := XTReadDB().Where("user_org_id = ? AND status = ?", orgid, 1).Last(&dryweight).Error
125
-	return dryweight, err
126
-
127
-}
128
-
129
-func UpdateDialysisPrescription(patientid int64, orgid int64, dryweight float64, prescription models.PredialysisEvaluation) error {
130
-	fmt.Println("patientid", patientid)
131
-	fmt.Println("orgid", orgid)
132
-	fmt.Println("dryweight", dryweight)
133
-	err := XTWriteDB().Model(&prescription).Where("patient_id = ? AND user_org_id = ?", patientid, orgid).Update(map[string]interface{}{"dry_weight": dryweight, "mtime": time.Now().Unix()}).Last(&prescription).Error
134
-	fmt.Println("错误是设么", err)
135
-	return err
136
-}
137
-
138
-func GetAllData(orgid int64, id int64, page int64, limit int64) (dry []*models.XtPatientDryweight, total int64, err error) {
139
-	offset := (page - 1) * limit
140
-	table := XTReadDB().Table("sgj_users.sgj_user_admin_role AS a")
141
-	fmt.Println("table", table)
142
-	err = XTReadDB().Table("xt_patient_dryweight as x").Select("x.id,x.dry_weight,x.creator,x.remakes,x.patient_id,x.ctime,x.status,x.user_org_id,x.adjusted_value,a.user_name").Where("x.user_org_id = ? AND x.patient_id = ? AND x.status = ? ", orgid, id, 1).Count(&total).Joins("LEFT  JOIN sgj_users.sgj_user_admin_role AS a ON a.admin_user_id = x.creator").Order("x.ctime desc").Offset(offset).Limit(limit).Group("id").Scan(&dry).Error
143
-	if err != nil {
144
-		return
145
-	}
146
-	return
147
-}
148
-
149
-func GetDryWeightDetailById(id int64) (models.SgjPatientDryweight, error) {
150
-
151
-	dryweight := models.SgjPatientDryweight{}
152
-	err := XTReadDB().Model(&dryweight).Where("id=? and status = 1", id).Find(&dryweight).Error
153
-	return dryweight, err
154
-}
155
-
156
-func ModifyDryWeightData(adjust *models.SgjPatientDryweight, id int64) error {
157
-
158
-	err := XTWriteDB().Model(&adjust).Where("id=?", id).Updates(map[string]interface{}{"dry_weight": adjust.DryWeight, "creator": adjust.Creator, "remakes": adjust.Remakes, "adjusted_value": adjust.AdjustedValue}).Error
159
-	return err
160
-}

+ 0 - 449
models/service/verify_login_token_service.go Просмотреть файл

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

+ 0 - 105
models/service/vm_service.go Просмотреть файл

@@ -1,105 +0,0 @@
1
-package service
2
-
3
-import (
4
-	"XT_New/models"
5
-	"strconv"
6
-)
7
-
8
-func CreateVMOrgPatient(patients *models.VMOrgPatients) {
9
-	writeDb.Model(&models.VMOrgPatients{}).Create(&patients)
10
-
11
-	var lapseto models.PatientLapseto
12
-	lapseto.PatientId = patients.ID
13
-	lapseto.LapsetoType = patients.Lapseto
14
-	lapseto.CreatedTime = patients.CreatedTime
15
-	lapseto.UpdatedTime = patients.CreatedTime
16
-	lapseto.Status = 1
17
-	lapseto.LapsetoTime = patients.CreatedTime
18
-	writeDb.Create(&lapseto)
19
-
20
-	if len(patients.ContagionIds) > 0 {
21
-		var diseases models.InfectiousDiseases
22
-		diseases.PatientId = patients.ID
23
-		diseases.Status = 1
24
-		diseases.UpdatedTime = patients.UpdatedTime
25
-		diseases.CreatedTime = patients.CreatedTime
26
-		id, _ := strconv.ParseInt(patients.ContagionIds, 10, 64)
27
-		diseases.DiseaseId = id
28
-		writeDb.Create(&diseases)
29
-	}
30
-
31
-}
32
-
33
-func CreateVMOrgNewPatient(patientsNew *models.XtPatientsNew) {
34
-	writeDb.Model(&models.XtPatientsNew{}).Create(&patientsNew)
35
-}
36
-
37
-func CreateVMZone(zone *models.VMDeviceZone) {
38
-	writeDb.Model(&models.VMDeviceZone{}).Create(&zone)
39
-}
40
-
41
-func CreateVMGroup(group *models.VMDeviceGroup) {
42
-	writeDb.Model(&models.VMDeviceGroup{}).Create(&group)
43
-}
44
-
45
-func CreateVMDeviceNumber(number *models.VMDeviceNumber) {
46
-	writeDb.Model(&models.VMDeviceNumber{}).Create(&number)
47
-}
48
-
49
-func CreateVMSch(sch *models.VMSchedule) {
50
-	writeDb.Model(&models.VMSchedule{}).Create(&sch)
51
-}
52
-
53
-func CreateVMSchMode(schMode *models.VMPatientScheduleTemplateMode) {
54
-	writeDb.Model(&models.VMPatientScheduleTemplateMode{}).Create(&schMode)
55
-}
56
-
57
-func CreateVMSchTemplateId(schTemplateId *models.VMPatientScheduleTemplateId) {
58
-	writeDb.Model(&models.VMPatientScheduleTemplateId{}).Create(&schTemplateId)
59
-}
60
-
61
-func CreateVMSchTemplate(schTemplate *models.VMPatientScheduleTemplateItem) {
62
-	writeDb.Model(&models.VMPatientScheduleTemplateItem{}).Create(&schTemplate)
63
-}
64
-
65
-func CreateVMPrescription(sys *models.SystemPrescription) {
66
-	writeDb.Model(&models.SystemPrescription{}).Create(&sys)
67
-}
68
-
69
-func CreatedDeviceMode(mode *models.VMDeviceMode) {
70
-
71
-	UserWriteDB().Model(&models.VMDeviceMode{}).Create(&mode)
72
-}
73
-
74
-func GetFirstDeviceMode(orgid int64) (models.VMDeviceMode, error) {
75
-	mode := models.VMDeviceMode{}
76
-	err = UserReadDB().Where("user_org_id = ? and status =1", orgid).First(&mode).Error
77
-	return mode, err
78
-}
79
-
80
-func GetFirstBedNumber(orgid int64) (models.VMDeviceNumber, error) {
81
-	number := models.VMDeviceNumber{}
82
-	err := XTReadDB().Where("org_id = ? and status =1", orgid).First(&number).Error
83
-	return number, err
84
-}
85
-
86
-func CreateDeviceAddMacher(addmacher *models.VmDeviceAddmacher) {
87
-
88
-	UserWriteDB().Model(&models.VmDeviceAddmacher{}).Create(&addmacher)
89
-}
90
-
91
-func GetLastMacher(orgid int64) (models.VmDeviceAddmacher, error) {
92
-	addmacher := models.VmDeviceAddmacher{}
93
-	err := UserReadDB().Where("user_org_id = ? and status =1", orgid).First(&addmacher).Error
94
-	return addmacher, err
95
-}
96
-
97
-func CreatedTreateMode(treatmentmode *models.VmDeviceTreatmentmode) {
98
-	XTWriteDB().Model(&models.VmDeviceTreatmentmode{}).Create(&treatmentmode)
99
-
100
-}
101
-
102
-func CreateVMPrintTemplate(template *models.VMGobalTemplate) (err error) {
103
-	err = writeDb.Model(&models.VMGobalTemplate{}).Create(template).Error
104
-	return
105
-}

+ 10 - 5
service/gobal_config_service.go Просмотреть файл

@@ -260,7 +260,9 @@ func GetDrugInOrderDetail(startime int64, endtime int64, orgid int64, orderType
260 260
 	db := XTReadDB().Table("xt_drug_warehouse_info as x").Where("x.status = 1")
261 261
 	dbOne := XTReadDB().Table("xt_base_drug as t").Where("t.status =1")
262 262
 	dbTwo := XTReadDB().Table("xt_drug_warehouse as s").Where("s.status = 1")
263
-	fmt.Print(dbOne, dbTwo)
263
+	dbThree := UserReadDB().Table("sgj_user_admin_role as r").Where("r.status = 1")
264
+
265
+	fmt.Print(dbOne, dbTwo, dbThree)
264 266
 	if startime > 0 {
265 267
 		db = db.Where("x.ctime >=?", startime)
266 268
 	}
@@ -275,8 +277,8 @@ func GetDrugInOrderDetail(startime int64, endtime int64, orgid int64, orderType
275 277
 	}
276 278
 
277 279
 	if len(keyword) > 0 {
278
-
279
-		db = db.Where("x.warehousing_order like ? or t.drug_name like ? or s.creater like ?", likeKey, likeKey, likeKey)
280
+		db = db.Joins("left join sgj_xt.xt_drug_warehouse as o on o.id = x.warehousing_id  left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = o.creater").Group("s.id")
281
+		db = db.Where("x.warehousing_order like ? or t.drug_name like ? or r.user_name like ? ", likeKey, likeKey, likeKey)
280 282
 
281 283
 	}
282 284
 
@@ -347,7 +349,8 @@ func GetDrugOutOrder(startime int64, endtime int64, orgid int64, orderType int64
347 349
 	}
348 350
 
349 351
 	if len(keyword) > 0 {
350
-		db = db.Where("x.warehouse_out_order_number like ? or b.drug_name like ? or t.creater like ?", likeKey, likeKey, likeKey)
352
+		db = db.Joins("left join sgj_xt.xt_drug_warehouse_out as o on o.id = x.warehouse_out_id  left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = o.creater").Group("x.id")
353
+		db = db.Where("x.warehouse_out_order_number like ? or b.drug_name like ?  or r.user_name like ?", likeKey, likeKey, likeKey)
351 354
 	}
352 355
 
353 356
 	if manufacturerId > 0 {
@@ -411,7 +414,9 @@ func GetDrugCancelOrder(startime int64, endtime int64, orgid int64, orderType in
411 414
 		db = db.Where("x.type = ? ", orderType)
412 415
 	}
413 416
 	if len(keyword) > 0 {
414
-		db = db.Where("x.order_number like ? or s.drug_spec like ? or t.creater like ?", likeKey, likeKey, likeKey)
417
+		db = db.Joins("left join sgj_xt.xt_drug_cancel_stock as o on o.id = x.cancel_stock_id  left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = o.creater").Group("o.id")
418
+
419
+		db = db.Where("x.order_number like ? or s.drug_spec like ? or r.user_name like ? or s.drug_name like ?", likeKey, likeKey, likeKey, likeKey)
415 420
 	}
416 421
 
417 422
 	if manufacturerId > 0 {

+ 2 - 2
service/schedule_service.go Просмотреть файл

@@ -199,10 +199,10 @@ func GetTodayScheduleIsExistOne(patientid int64, schedudate int64, orgid int64)
199 199
 	return &scheudle, nil
200 200
 }
201 201
 
202
-func ModeFyScheduleById(schedule_date int64, bedid int64, scheduletype int64) error {
202
+func ModeFyScheduleById(schedule_date int64, bedid int64, scheduletype int64, orgid int64) error {
203 203
 
204 204
 	schedule := models.XtSchedule{}
205
-	err := XTWriteDB().Model(&schedule).Where("schedule_date = ? and bed_id =? and schedule_type = ? and status = 1", schedule_date, bedid, scheduletype).Updates(map[string]interface{}{"status": 0}).Error
205
+	err := XTWriteDB().Model(&schedule).Where("schedule_date = ? and bed_id =? and schedule_type = ? and status = 1 and user_org_id = ?", schedule_date, bedid, scheduletype, orgid).Updates(map[string]interface{}{"status": 0}).Error
206 206
 	return err
207 207
 }
208 208
 

+ 37 - 6
service/stock_service.go Просмотреть файл

@@ -2323,20 +2323,20 @@ func UpDateWarehouseInfoByStock(info *models.WarehousingInfo) (err error) {
2323 2323
 	return err
2324 2324
 }
2325 2325
 
2326
-//func UpDateWarehouseInfoByStockDelete(id int64,count int64) (err error) {
2327
-//	err = DB.Model(&models.WarehousingInfo{}).Where("id = ?",info.ID).UpdateColumn("stock_count", gorm.Expr("stock_count + ?", count)).Error
2328
-//	return err
2329
-//}
2330
-
2331 2326
 func UpDateDrugWarehouseOutStatus(id int64) (err error) {
2332 2327
 	err = readDb.Model(&models.DrugWarehouseOutInfo{}).Where("id = ? AND status = 1", id).Update(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
2333 2328
 	return
2334 2329
 }
2335 2330
 
2336 2331
 func DeleteDrugWarehouseOutInfoById(id int64) (err error) {
2337
-	err = XTWriteDB().Model(&models.DrugFlow{}).Where("warehouse_out_detail_id = ? and satus = 1", id).Updates(map[string]interface{}{"status": 0}).Error
2332
+	err = XTWriteDB().Model(&models.DrugFlow{}).Where("warehouse_out_detail_id = ? and status = 1", id).Updates(map[string]interface{}{"status": 0}).Error
2338 2333
 	return
2339 2334
 }
2335
+func GetDrugWarehosueOutInfo(id int64) (models.DrugWarehouseOutInfo, error) {
2336
+	info := models.DrugWarehouseOutInfo{}
2337
+	err := XTReadDB().Where("id = ? and status = 1", id).Find(&info).Error
2338
+	return info, err
2339
+}
2340 2340
 
2341 2341
 func EditWarehouseOut(warehouseOut models.WarehouseOut) {
2342 2342
 	err = readDb.Model(&models.WarehouseOut{}).Where("id = ? AND status = 1", warehouseOut.ID).Update(map[string]interface{}{"mtime": time.Now().Unix(), "warehouse_out_time": warehouseOut.WarehouseOutTime, "dealer": warehouseOut.Dealer, "manufacturer": warehouseOut.Manufacturer}).Error
@@ -5674,3 +5674,34 @@ func ModifyDrugWarehouse(id int64, stock_max_number int64, stock_min_number int6
5674 5674
 	err = XTWriteDB().Model(&info).Where("id = ?", id).UpdateColumn("stock_min_number", gorm.Expr("stock_min_number + ?", stock_min_number)).Error
5675 5675
 	return info, err
5676 5676
 }
5677
+
5678
+func ModeifyDrugWarehosueInfo(id int64, stock_max_number int64) error {
5679
+
5680
+	err := XTWriteDB().Model(models.DrugWarehouseInfo{}).Where("id = ?", id).UpdateColumn("stock_max_number", gorm.Expr("stock_max_number + ?", stock_max_number)).Error
5681
+	return err
5682
+}
5683
+
5684
+func ModeFyStockMinById(id int64, stock_min_number int64) error {
5685
+	info := models.DrugWarehouseInfo{}
5686
+	err = XTWriteDB().Model(&info).Where("id = ?", id).UpdateColumn("stock_min_number", gorm.Expr("stock_min_number + ?", stock_min_number)).Error
5687
+	return err
5688
+}
5689
+
5690
+func GetDrugCancelById(id int64) (models.DrugCancelStockInfo, error) {
5691
+
5692
+	info := models.DrugCancelStockInfo{}
5693
+	err := XTReadDB().Where("id = ? and status = 1", id).Find(&info).Error
5694
+	return info, err
5695
+}
5696
+
5697
+func ModeFyDrugWareseInfo(id int64, stock_max_number int64) error {
5698
+	info := models.DrugWarehouseInfo{}
5699
+	err = XTWriteDB().Model(&info).Where("id = ?", id).UpdateColumn("stock_max_number", gorm.Expr("stock_max_number - ?", stock_max_number)).Error
5700
+	return err
5701
+}
5702
+
5703
+func ModeFyDrugWarehouseMin(id int64, stock_min_number int64) error {
5704
+	info := models.DrugWarehouseInfo{}
5705
+	err = XTWriteDB().Model(&info).Where("id = ?", id).UpdateColumn("stock_min_number", gorm.Expr("stock_min_number - ?", stock_min_number)).Error
5706
+	return err
5707
+}

+ 2 - 2
service/warhouse_service.go Просмотреть файл

@@ -806,7 +806,7 @@ func AutoDrugDeliverInfo(orgID int64, prescribingNumber int64, warehouseout *mod
806 806
 			WarehouseOutId:          warehouseout.ID,
807 807
 			Status:                  1,
808 808
 			Ctime:                   time.Now().Unix(),
809
-			Remark:                  warehouse.Remark,
809
+			Remark:                  advice.Remark,
810 810
 			OrgId:                   orgID,
811 811
 			Type:                    1,
812 812
 			Manufacturer:            advice.Manufacturer,
@@ -903,7 +903,7 @@ func AutoDrugDeliverInfo(orgID int64, prescribingNumber int64, warehouseout *mod
903 903
 			WarehouseOutId:          warehouseout.ID,
904 904
 			Status:                  1,
905 905
 			Ctime:                   time.Now().Unix(),
906
-			Remark:                  warehouse.Remark,
906
+			Remark:                  advice.Remark,
907 907
 			OrgId:                   orgID,
908 908
 			Type:                    1,
909 909
 			Manufacturer:            advice.Manufacturer,