Bladeren bron

体积小

XMLWAN 2 jaren geleden
bovenliggende
commit
5c4a45361d
67 gewijzigde bestanden met toevoegingen van 45573 en 0 verwijderingen
  1. 21 0
      main.go
  2. 611 0
      models/common_models.go
  3. 83 0
      models/his_hospital_models.go
  4. 1418 0
      models/his_models.go
  5. 3319 0
      models/service/common_service.go
  6. 400 0
      service/admin_service.go
  7. 268 0
      service/app_version.go
  8. 46 0
      service/auto_clear_schedules_service.go
  9. 110 0
      service/auto_create_drug.go
  10. 149 0
      service/auto_create_staff_schedule_service.go
  11. 87 0
      service/auto_create_stock.go
  12. 261 0
      service/auto_create_week_disinfection.go
  13. 149 0
      service/auto_create_week_plan.go
  14. 281 0
      service/auto_create_week_schedules_service.go
  15. 3554 0
      service/common_service.go
  16. 345 0
      service/data.go
  17. 274 0
      service/db.go
  18. 27 0
      service/db_err_service.go
  19. 722 0
      service/device_service.go
  20. 454 0
      service/dialysis_parameter_service.go
  21. 1235 0
      service/dialysis_service.go
  22. 84 0
      service/district_service.go
  23. 482 0
      service/doctor_advice_service.go
  24. 637 0
      service/doctor_schedule_service.go
  25. 262 0
      service/drug_stock_service.go
  26. 1425 0
      service/gdyb_service.go
  27. 780 0
      service/gobal_config_service.go
  28. 48 0
      service/his_config_service.go
  29. 174 0
      service/his_hospital_service.go
  30. 750 0
      service/his_project_service.go
  31. 2108 0
      service/his_service.go
  32. 37 0
      service/home_service.go
  33. 219 0
      service/inspection_service.go
  34. 120 0
      service/integration_service.go
  35. 55 0
      service/invoice_service.go
  36. 246 0
      service/login_service.go
  37. 370 0
      service/manage_center_service.go
  38. 1543 0
      service/manage_service.go
  39. 69 0
      service/management_service/management_analyse_service.go
  40. 103 0
      service/management_service/management_models.go
  41. 2263 0
      service/mobile_dialysis_service.go
  42. 144 0
      service/new_sms_service.go
  43. 202 0
      service/orginfo_service.go
  44. 64 0
      service/patient_dataconfig_service.go
  45. 523 0
      service/patient_schedule_template_service.go
  46. 1517 0
      service/patient_service.go
  47. 1809 0
      service/patientmanage_service.go
  48. 149 0
      service/pay_service.go
  49. 744 0
      service/print_data_service/schedule_dialysis/print_schedule_dialysis_models.go
  50. 255 0
      service/print_data_service/schedule_dialysis/print_schedule_dialysis_service.go
  51. 1370 0
      service/qcd_service.go
  52. 20 0
      service/redis.go
  53. 34 0
      service/regist_service.go
  54. 937 0
      service/role_service.go
  55. 977 0
      service/schedule_service.go
  56. 1063 0
      service/self_drug_service.go
  57. 270 0
      service/sign_weigh_service.go
  58. 185 0
      service/sms_service.go
  59. 73 0
      service/statistics_service.go
  60. 1882 0
      service/statistics_service/index_evaluation_service.go
  61. 195 0
      service/statistics_service/index_models.go
  62. 4642 0
      service/stock_service.go
  63. 34 0
      service/subscibe_service.go
  64. 179 0
      service/user_service.go
  65. 449 0
      service/verify_login_token_service.go
  66. 105 0
      service/vm_service.go
  67. 2162 0
      service/warhouse_service.go

+ 21 - 0
main.go Bestand weergeven

@@ -0,0 +1,21 @@
1
+package main
2
+
3
+import (
4
+	_ "Xcx_New/routers"
5
+	"Xcx_New/service"
6
+	"github.com/astaxie/beego"
7
+)
8
+
9
+func init() {
10
+	service.ConnectDB()
11
+}
12
+
13
+func main() {
14
+	//service.BeginAutoCreateWeekSchedulesJob()
15
+	//service.BeginAutoCreateWeekDisinfectionJob()
16
+	//service.BeginAutoCreatePlanJob()
17
+	//service.AutoClearSchedules()
18
+	//service.BeginAutoCreateStaffScheduleJob()
19
+	beego.BConfig.WebConfig.Session.SessionGCMaxLifetime = 60
20
+	beego.Run()
21
+}

+ 611 - 0
models/common_models.go Bestand weergeven

@@ -0,0 +1,611 @@
1
+package models
2
+
3
+type QualityControlStandard struct {
4
+	ID              int64  `gorm:"column:id" json:"id" form:"id"`
5
+	InspectionMajor int64  `gorm:"column:inspection_major" json:"inspection_major" form:"inspection_major"`
6
+	InspectionMinor int64  `gorm:"column:inspection_minor" json:"inspection_minor" form:"inspection_minor"`
7
+	MinRange        string `gorm:"column:min_range" json:"min_range" form:"min_range"`
8
+	Sort            int64  `gorm:"column:sort" json:"sort" form:"sort"`
9
+	UserOrgId       int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
10
+	Status          int64  `gorm:"column:status" json:"status" form:"status"`
11
+	CreatedTime     int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
12
+	UpdatedTime     int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
13
+	LargeRange      string `gorm:"column:large_range" json:"large_range" form:"large_range"`
14
+	RangeType       int64  `gorm:"column:range_type" json:"range_type" form:"range_type"`
15
+	RangeValue      string `gorm:"column:range_value" json:"range_value" form:"range_value"`
16
+	Unit            string `gorm:"column:unit" json:"unit" form:"unit"`
17
+	ProjectName     string `gorm:"column:project_name" json:"project_name" form:"project_name"`
18
+	ItemName        string `gorm:"column:item_name" json:"item_name" form:"item_name"`
19
+	IsStatus        int64  `gorm:"column:is_status" json:"is_status" form:"is_status"`
20
+}
21
+
22
+type XtQualityControlStandard struct {
23
+	ID              int64  `gorm:"column:id" json:"id" form:"id"`
24
+	InspectionMajor int64  `gorm:"column:inspection_major" json:"inspection_major" form:"inspection_major"`
25
+	InspectionMinor int64  `gorm:"column:inspection_minor" json:"inspection_minor" form:"inspection_minor"`
26
+	MinRange        string `gorm:"column:min_range" json:"min_range" form:"min_range"`
27
+	Sort            int64  `gorm:"column:sort" json:"sort" form:"sort"`
28
+	UserOrgId       int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
29
+	Status          int64  `gorm:"column:status" json:"status" form:"status"`
30
+	CreatedTime     int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
31
+	UpdatedTime     int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
32
+	LargeRange      string `gorm:"column:large_range" json:"large_range" form:"large_range"`
33
+	RangeType       int64  `gorm:"column:range_type" json:"range_type" form:"range_type"`
34
+	RangeValue      string `gorm:"column:range_value" json:"range_value" form:"range_value"`
35
+	IsStatus        int64  `gorm:"column:is_status" json:"is_status" form:"is_status"`
36
+}
37
+
38
+func (XtQualityControlStandard) TableName() string {
39
+	return "xt_quality_control_standard"
40
+}
41
+
42
+type CheckConfiguration struct {
43
+	ID                  int64  `gorm:"column:id" json:"id" form:"id"`
44
+	InspectionMajor     int64  `gorm:"column:inspection_major" json:"inspection_major" form:"inspection_major"`
45
+	InspectionFrequency string `gorm:"column:inspection_frequency" json:"inspection_frequency" form:"inspection_frequency"`
46
+	Sort                int64  `gorm:"column:sort" json:"sort" form:"sort"`
47
+	UserOrgId           int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
48
+	Status              int64  `gorm:"column:status" json:"status" form:"status"`
49
+	CreatedTime         int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
50
+	UpdatedTime         int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
51
+	ProjectName         string `gorm:"column:project_name" json:"project_name" form:"project_name"`
52
+}
53
+
54
+type XtCheckConfiguration struct {
55
+	ID                  int64  `gorm:"column:id" json:"id" form:"id"`
56
+	InspectionMajor     int64  `gorm:"column:inspection_major" json:"inspection_major" form:"inspection_major"`
57
+	InspectionFrequency string `gorm:"column:inspection_frequency" json:"inspection_frequency" form:"inspection_frequency"`
58
+	Sort                int64  `gorm:"column:sort" json:"sort" form:"sort"`
59
+	UserOrgId           int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
60
+	Status              int64  `gorm:"column:status" json:"status" form:"status"`
61
+	CreatedTime         int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
62
+	UpdatedTime         int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
63
+}
64
+
65
+func (XtCheckConfiguration) TableName() string {
66
+	return "xt_check_configuration"
67
+}
68
+
69
+type PatientPrescriptionCountStruct struct {
70
+	ModeId int64 `json:"mode_id"`
71
+	Count  int64 `json:"count"`
72
+}
73
+
74
+type PatientLapsetoCountStruct struct {
75
+	lapseto_type int64 `json:"lapseto_type"`
76
+	Count        int64 `json:"count"`
77
+}
78
+
79
+type SgjDialysisOrder struct {
80
+	ID             int64  `gorm:"column:id" json:"id" form:"id"`
81
+	DialysisDate   int64  `gorm:"column:dialysis_date" json:"dialysis_date" form:"dialysis_date"`
82
+	UserOrgId      int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
83
+	PatientId      int64  `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
84
+	PrescriptionId int64  `gorm:"column:prescription_id" json:"prescription_id" form:"prescription_id"`
85
+	Stage          int64  `gorm:"column:stage" json:"stage" form:"stage"`
86
+	Remark         string `gorm:"column:remark" json:"remark" form:"remark"`
87
+	BedId          int64  `gorm:"column:bed_id" json:"bed_id" form:"bed_id"`
88
+	StartNurse     int64  `gorm:"column:start_nurse" json:"start_nurse" form:"start_nurse"`
89
+	FinishNurse    int64  `gorm:"column:finish_nurse" json:"finish_nurse" form:"finish_nurse"`
90
+	Status         int64  `gorm:"column:status" json:"status" form:"status"`
91
+	CreatedTime    int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
92
+	UpdatedTime    int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
93
+	StartTime      int64  `gorm:"column:start_time" json:"start_time" form:"start_time"`
94
+	EndTime        int64  `gorm:"column:end_time" json:"end_time" form:"end_time"`
95
+	PunctureNurse  int64  `gorm:"column:puncture_nurse" json:"puncture_nurse" form:"puncture_nurse"`
96
+	Creator        int64  `gorm:"column:creator" json:"creator" form:"creator"`
97
+	Modifier       int64  `gorm:"column:modifier" json:"modifier" form:"modifier"`
98
+	FinishCreator  int64  `gorm:"column:finish_creator" json:"finish_creator" form:"finish_creator"`
99
+	FinishModifier int64  `gorm:"column:finish_modifier" json:"finish_modifier" form:"finish_modifier"`
100
+	SchedualType   int64  `gorm:"column:schedual_type" json:"schedual_type" form:"schedual_type"`
101
+	Number         int64  `gorm:"column:number" json:"number" form:"number"`
102
+	UserName       int64  `gorm:"column:user_name" json:"user_name" form:"user_name"`
103
+	WashpipeNurse  int64  `gorm:"column:washpipe_nurse" json:"washpipe_nurse" form:"washpipe_nurse"`
104
+}
105
+
106
+func (SgjDialysisOrder) TableName() string {
107
+	return "xt_dialysis_order"
108
+}
109
+
110
+type PatientContagionsCountStruct struct {
111
+	DiseaseId int64 `json:"disease_id"`
112
+	Count     int64 `json:"count"`
113
+}
114
+
115
+type PatientAgeCountStruct struct {
116
+	Age   int64 `json:"age"`
117
+	Count int64 `json:"count"`
118
+}
119
+
120
+type DialysisAgePieDataStruct struct {
121
+	Age   int64 `json:"age"`
122
+	Count int64 `json:"count"`
123
+}
124
+
125
+type BloodPatients struct {
126
+	ID                           int64   `gorm:"column:id" json:"id" form:"id"`
127
+	UserOrgId                    int64   `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
128
+	UserId                       int64   `gorm:"column:user_id" json:"user_id" form:"user_id"`
129
+	Avatar                       string  `gorm:"column:avatar" json:"avatar" form:"avatar"`
130
+	PatientType                  int64   `gorm:"column:patient_type" json:"patient_type" form:"patient_type"`
131
+	DialysisNo                   string  `gorm:"column:dialysis_no" json:"dialysis_no" form:"dialysis_no"`
132
+	AdmissionNumber              string  `gorm:"column:admission_number" json:"admission_number" form:"admission_number"`
133
+	Source                       int64   `gorm:"column:source" json:"source" form:"source"`
134
+	Lapseto                      int64   `gorm:"column:lapseto" json:"lapseto" form:"lapseto"`
135
+	PartitionId                  int64   `gorm:"column:partition_id" json:"partition_id" form:"partition_id"`
136
+	BedId                        int64   `gorm:"column:bed_id" json:"bed_id" form:"bed_id"`
137
+	Name                         string  `gorm:"column:name" json:"name" form:"name"`
138
+	Alias                        string  `gorm:"column:alias" json:"alias" form:"alias"`
139
+	Gender                       int64   `gorm:"column:gender" json:"gender" form:"gender"`
140
+	MaritalStatus                int64   `gorm:"column:marital_status" json:"marital_status" form:"marital_status"`
141
+	IdCardNo                     string  `gorm:"column:id_card_no" json:"id_card_no" form:"id_card_no"`
142
+	Birthday                     int64   `gorm:"column:birthday" json:"birthday" form:"birthday"`
143
+	ReimbursementWayId           int64   `gorm:"column:reimbursement_way_id" json:"reimbursement_way_id" form:"reimbursement_way_id"`
144
+	HealthCareType               int64   `gorm:"column:health_care_type" json:"health_care_type" form:"health_care_type"`
145
+	HealthCareNo                 string  `gorm:"column:health_care_no" json:"health_care_no" form:"health_care_no"`
146
+	HealthCareDueDate            int64   `gorm:"column:health_care_due_date" json:"health_care_due_date" form:"health_care_due_date"`
147
+	Height                       int64   `gorm:"column:height" json:"height" form:"height"`
148
+	BloodType                    int64   `gorm:"column:blood_type" json:"blood_type" form:"blood_type"`
149
+	Rh                           int64   `gorm:"column:rh" json:"rh" form:"rh"`
150
+	HealthCareDueAlertDate       int64   `gorm:"column:health_care_due_alert_date" json:"health_care_due_alert_date" form:"health_care_due_alert_date"`
151
+	EducationLevel               int64   `gorm:"column:education_level" json:"education_level" form:"education_level"`
152
+	Profession                   int64   `gorm:"column:profession" json:"profession" form:"profession"`
153
+	Phone                        string  `gorm:"column:phone" json:"phone" form:"phone"`
154
+	HomeTelephone                string  `gorm:"column:home_telephone" json:"home_telephone" form:"home_telephone"`
155
+	RelativePhone                string  `gorm:"column:relative_phone" json:"relative_phone" form:"relative_phone"`
156
+	RelativeRelations            string  `gorm:"column:relative_relations" json:"relative_relations" form:"relative_relations"`
157
+	HomeAddress                  string  `gorm:"column:home_address" json:"home_address" form:"home_address"`
158
+	WorkUnit                     string  `gorm:"column:work_unit" json:"work_unit" form:"work_unit"`
159
+	UnitAddress                  string  `gorm:"column:unit_address" json:"unit_address" form:"unit_address"`
160
+	Children                     int64   `gorm:"column:children" json:"children" form:"children"`
161
+	ReceivingDate                int64   `gorm:"column:receiving_date" json:"receiving_date" form:"receiving_date"`
162
+	IsHospitalFirstDialysis      int64   `gorm:"column:is_hospital_first_dialysis" json:"is_hospital_first_dialysis" form:"is_hospital_first_dialysis"`
163
+	FirstDialysisDate            int64   `gorm:"column:first_dialysis_date" json:"first_dialysis_date" form:"first_dialysis_date"`
164
+	FirstDialysisHospital        string  `gorm:"column:first_dialysis_hospital" json:"first_dialysis_hospital" form:"first_dialysis_hospital"`
165
+	PredialysisCondition         string  `gorm:"column:predialysis_condition" json:"predialysis_condition" form:"predialysis_condition"`
166
+	PreHospitalDialysisFrequency string  `gorm:"column:pre_hospital_dialysis_frequency" json:"pre_hospital_dialysis_frequency" form:"pre_hospital_dialysis_frequency"`
167
+	PreHospitalDialysisTimes     int64   `gorm:"column:pre_hospital_dialysis_times" json:"pre_hospital_dialysis_times" form:"pre_hospital_dialysis_times"`
168
+	HospitalFirstDialysisDate    int64   `gorm:"column:hospital_first_dialysis_date" json:"hospital_first_dialysis_date" form:"hospital_first_dialysis_date"`
169
+	InductionPeriod              int64   `gorm:"column:induction_period" json:"induction_period" form:"induction_period"`
170
+	InitialDialysis              int64   `gorm:"column:initial_dialysis" json:"initial_dialysis" form:"initial_dialysis"`
171
+	TotalDialysis                int64   `gorm:"column:total_dialysis" json:"total_dialysis" form:"total_dialysis"`
172
+	AttendingDoctorId            int64   `gorm:"column:attending_doctor_id" json:"attending_doctor_id" form:"attending_doctor_id"`
173
+	HeadNurseId                  int64   `gorm:"column:head_nurse_id" json:"head_nurse_id" form:"head_nurse_id"`
174
+	Evaluate                     string  `gorm:"column:evaluate" json:"evaluate" form:"evaluate"`
175
+	Diagnose                     string  `gorm:"column:diagnose" json:"diagnose" form:"diagnose"`
176
+	Remark                       string  `gorm:"column:remark" json:"remark" form:"remark"`
177
+	RegistrarsId                 int64   `gorm:"column:registrars_id" json:"registrars_id" form:"registrars_id"`
178
+	Registrars                   string  `gorm:"column:registrars" json:"registrars" form:"registrars"`
179
+	QrCode                       string  `gorm:"column:qr_code" json:"qr_code" form:"qr_code"`
180
+	BindingState                 int64   `gorm:"column:binding_state" json:"binding_state" form:"binding_state"`
181
+	PatientComplains             string  `gorm:"column:patient_complains" json:"patient_complains" form:"patient_complains"`
182
+	PresentHistory               string  `gorm:"column:present_history" json:"present_history" form:"present_history"`
183
+	PastHistory                  string  `gorm:"column:past_history" json:"past_history" form:"past_history"`
184
+	Temperature                  float64 `gorm:"column:temperature" json:"temperature" form:"temperature"`
185
+	Pulse                        int64   `gorm:"column:pulse" json:"pulse" form:"pulse"`
186
+	Respiratory                  int64   `gorm:"column:respiratory" json:"respiratory" form:"respiratory"`
187
+	Sbp                          int64   `gorm:"column:sbp" json:"sbp" form:"sbp"`
188
+	Dbp                          int64   `gorm:"column:dbp" json:"dbp" form:"dbp"`
189
+	Status                       int64   `gorm:"column:status" json:"status" form:"status"`
190
+	CreatedTime                  int64   `gorm:"column:created_time" json:"created_time" form:"created_time"`
191
+	UpdatedTime                  int64   `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
192
+	Nation                       string  `gorm:"column:nation" json:"nation" form:"nation"`
193
+	NativePlace                  string  `gorm:"column:native_place" json:"native_place" form:"native_place"`
194
+	Age                          int64   `gorm:"column:age" json:"age" form:"age"`
195
+	InfectiousNextRecordTime     int64   `gorm:"column:infectious_next_record_time" json:"infectious_next_record_time" form:"infectious_next_record_time"`
196
+	IsInfectious                 int64   `gorm:"column:is_infectious" json:"is_infectious" form:"is_infectious"`
197
+	RemindCycle                  int64   `gorm:"column:remind_cycle" json:"remind_cycle" form:"remind_cycle"`
198
+	ResponseResult               string  `gorm:"column:response_result" json:"response_result" form:"response_result"`
199
+	IsOpenRemind                 int64   `gorm:"column:is_open_remind" json:"is_open_remind" form:"is_open_remind"`
200
+	FirstTreatmentDate           int64   `gorm:"column:first_treatment_date" json:"first_treatment_date" form:"first_treatment_date"`
201
+	DialysisAge                  int64   `gorm:"column:dialysis_age" json:"dialysis_age" form:"dialysis_age"`
202
+	ExpenseKind                  int64   `gorm:"column:expense_kind" json:"expense_kind" form:"expense_kind"`
203
+	TellPhone                    string  `gorm:"column:tell_phone" json:"tell_phone" form:"tell_phone"`
204
+	ContactName                  string  `gorm:"column:contact_name" json:"contact_name" form:"contact_name"`
205
+	UserSysBeforeCount           int64   `gorm:"column:user_sys_before_count" json:"user_sys_before_count" form:"user_sys_before_count"`
206
+	IsExcelExport                int64   `gorm:"column:is_excel_export" json:"is_excel_export" form:"is_excel_export"`
207
+}
208
+
209
+func (BloodPatients) TableName() string {
210
+	return "xt_patients"
211
+}
212
+
213
+type BloodDialysisPrescription struct {
214
+	ID                         int64   `gorm:"column:id" json:"id" form:"id"`
215
+	UserOrgId                  int64   `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
216
+	PatientId                  int64   `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
217
+	Dialyzer                   int64   `gorm:"column:dialyzer" json:"dialyzer" form:"dialyzer"`
218
+	MachineType                string  `gorm:"column:machine_type" json:"machine_type" form:"machine_type"`
219
+	DewaterAmount              float64 `gorm:"column:dewater_amount" json:"dewater_amount" form:"dewater_amount"`
220
+	DialyzerPerfusionApparatus string  `gorm:"column:dialyzer_perfusion_apparatus" json:"dialyzer_perfusion_apparatus" form:"dialyzer_perfusion_apparatus"`
221
+	PrescriptionDewatering     float64 `gorm:"column:prescription_dewatering" json:"prescription_dewatering" form:"prescription_dewatering"`
222
+	Anticoagulant              int64   `gorm:"column:anticoagulant" json:"anticoagulant" form:"anticoagulant"`
223
+	AnticoagulantShouji        float64 `gorm:"column:anticoagulant_shouji" json:"anticoagulant_shouji" form:"anticoagulant_shouji"`
224
+	AnticoagulantWeichi        float64 `gorm:"column:anticoagulant_weichi" json:"anticoagulant_weichi" form:"anticoagulant_weichi"`
225
+	AnticoagulantZongliang     float64 `gorm:"column:anticoagulant_zongliang" json:"anticoagulant_zongliang" form:"anticoagulant_zongliang"`
226
+	AnticoagulantGaimingcheng  string  `gorm:"column:anticoagulant_gaimingcheng" json:"anticoagulant_gaimingcheng" form:"anticoagulant_gaimingcheng"`
227
+	AnticoagulantGaijiliang    string  `gorm:"column:anticoagulant_gaijiliang" json:"anticoagulant_gaijiliang" form:"anticoagulant_gaijiliang"`
228
+	ModeId                     int64   `gorm:"column:mode_id" json:"mode_id" form:"mode_id"`
229
+	DialysisDurationHour       int64   `gorm:"column:dialysis_duration_hour" json:"dialysis_duration_hour" form:"dialysis_duration_hour"`
230
+	DialysisDurationMinute     int64   `gorm:"column:dialysis_duration_minute" json:"dialysis_duration_minute" form:"dialysis_duration_minute"`
231
+	DialysisDuration           float64 `gorm:"column:dialysis_duration" json:"dialysis_duration" form:"dialysis_duration"`
232
+	ReplacementTotal           float64 `gorm:"column:replacement_total" json:"replacement_total" form:"replacement_total"`
233
+	ReplacementWay             int64   `gorm:"column:replacement_way" json:"replacement_way" form:"replacement_way"`
234
+	HemodialysisMachine        int64   `gorm:"column:hemodialysis_machine" json:"hemodialysis_machine" form:"hemodialysis_machine"`
235
+	BloodFilter                int64   `gorm:"column:blood_filter" json:"blood_filter" form:"blood_filter"`
236
+	PerfusionApparatus         int64   `gorm:"column:perfusion_apparatus" json:"perfusion_apparatus" form:"perfusion_apparatus"`
237
+	DryWeight                  float64 `gorm:"column:dry_weight" json:"dry_weight" form:"dry_weight"`
238
+	VascularAccessMode         int64   `gorm:"column:vascular_access_mode" json:"vascular_access_mode" form:"vascular_access_mode"`
239
+	VascularAccess             int64   `gorm:"column:vascular_access" json:"vascular_access" form:"vascular_access"`
240
+	BloodFlowVolume            float64 `gorm:"column:blood_flow_volume" json:"blood_flow_volume" form:"blood_flow_volume"`
241
+	DialysateFlow              float64 `gorm:"column:dialysate_flow" json:"dialysate_flow" form:"dialysate_flow"`
242
+	DisplaceLiqui              float64 `gorm:"column:displace_liqui" json:"displace_liqui" form:"displace_liqui"`
243
+	Kalium                     float64 `gorm:"column:kalium" json:"kalium" form:"kalium"`
244
+	Sodium                     float64 `gorm:"column:sodium" json:"sodium" form:"sodium"`
245
+	Calcium                    float64 `gorm:"column:calcium" json:"calcium" form:"calcium"`
246
+	Bicarbonate                float64 `gorm:"column:bicarbonate" json:"bicarbonate" form:"bicarbonate"`
247
+	Glucose                    float64 `gorm:"column:glucose" json:"glucose" form:"glucose"`
248
+	DialysateTemperature       float64 `gorm:"column:dialysate_temperature" json:"dialysate_temperature" form:"dialysate_temperature"`
249
+	Conductivity               float64 `gorm:"column:conductivity" json:"conductivity" form:"conductivity"`
250
+	PrescriptionDoctor         int64   `gorm:"column:prescription_doctor" json:"prescription_doctor" form:"prescription_doctor"`
251
+	Creater                    int64   `gorm:"column:creater" json:"creater" form:"creater"`
252
+	Modifier                   int64   `gorm:"column:modifier" json:"modifier" form:"modifier"`
253
+	Remark                     string  `gorm:"column:remark" json:"remark" form:"remark"`
254
+	Status                     int64   `gorm:"column:status" json:"status" form:"status"`
255
+	CreatedTime                int64   `gorm:"column:created_time" json:"created_time" form:"created_time"`
256
+	UpdatedTime                int64   `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
257
+	RecordDate                 int64   `gorm:"column:record_date" json:"record_date" form:"record_date"`
258
+	RecordId                   int64   `gorm:"column:record_id" json:"record_id" form:"record_id"`
259
+	TargetUltrafiltration      float64 `gorm:"column:target_ultrafiltration" json:"target_ultrafiltration" form:"target_ultrafiltration"`
260
+	DialysateFormulation       int64   `gorm:"column:dialysate_formulation" json:"dialysate_formulation" form:"dialysate_formulation"`
261
+	BodyFluid                  int64   `gorm:"column:body_fluid" json:"body_fluid" form:"body_fluid"`
262
+	SpecialMedicine            int64   `gorm:"column:special_medicine" json:"special_medicine" form:"special_medicine"`
263
+	SpecialMedicineOther       string  `gorm:"column:special_medicine_other" json:"special_medicine_other" form:"special_medicine_other"`
264
+	DisplaceLiquiPart          int64   `gorm:"column:displace_liqui_part" json:"displace_liqui_part" form:"displace_liqui_part"`
265
+	BloodAccess                int64   `gorm:"column:blood_access" json:"blood_access" form:"blood_access"`
266
+	DisplaceLiquiValue         float64 `gorm:"column:displace_liqui_value" json:"displace_liqui_value" form:"displace_liqui_value"`
267
+	Ultrafiltration            float64 `gorm:"column:ultrafiltration" json:"ultrafiltration" form:"ultrafiltration"`
268
+	BodyFluidOther             string  `gorm:"column:body_fluid_other" json:"body_fluid_other" form:"body_fluid_other"`
269
+	Niprocart                  int64   `gorm:"column:niprocart" json:"niprocart" form:"niprocart"`
270
+	Jms                        int64   `gorm:"column:jms" json:"jms" form:"jms"`
271
+	FistulaNeedleSet           int64   `gorm:"column:fistula_needle_set" json:"fistula_needle_set" form:"fistula_needle_set"`
272
+	FistulaNeedleSet16         int64   `gorm:"column:fistula_needle_set_16" json:"fistula_needle_set_16" form:"fistula_needle_set_16"`
273
+	Hemoperfusion              int64   `gorm:"column:hemoperfusion" json:"hemoperfusion" form:"hemoperfusion"`
274
+	DialyserSterilised         int64   `gorm:"column:dialyser_sterilised" json:"dialyser_sterilised" form:"dialyser_sterilised"`
275
+	Filtryzer                  int64   `gorm:"column:filtryzer" json:"filtryzer" form:"filtryzer"`
276
+	TargetKtv                  float64 `gorm:"column:target_ktv" json:"target_ktv" form:"target_ktv"`
277
+	Dialyzers                  int64   `gorm:"column:dialyzers" json:"dialyzers" form:"dialyzers"`
278
+	Injector                   int64   `gorm:"column:injector" json:"injector" form:"injector"`
279
+	Bloodlines                 int64   `gorm:"column:bloodlines" json:"bloodlines" form:"bloodlines"`
280
+	TubingHemodialysis         int64   `gorm:"column:tubing_hemodialysis" json:"tubing_hemodialysis" form:"tubing_hemodialysis"`
281
+	Package                    int64   `gorm:"column:package" json:"package" form:"package"`
282
+	ALiquid                    int64   `gorm:"column:a_liquid" json:"a_liquid" form:"a_liquid"`
283
+	Name                       string  `gorm:"column:name" json:"name" form:"name"`
284
+	DialysisNo                 string  `gorm:"column:dialysis_no" json:"dialysis_no" form:"dialysis_no"`
285
+	IdCardNo                   string  `gorm:"column:id_card_no" json:"id_card_no" form:"id_card_no"`
286
+	TotalDialysis              int64   `gorm:"column:total_dialysis" json:"total_dialysis" form:"total_dialysis"`
287
+	UserSysBeforeCount         int64   `gorm:"column:user_sys_before_count" json:"user_sys_before_count" form:"user_sys_before_count"`
288
+	AnticoagulantStopTimeMin   int64   `gorm:"column:anticoagulant_stop_time_min" json:"anticoagulant_stop_time_min" form:"anticoagulant_stop_time_min"`
289
+	AnticoagulantStopTimeHour  int64   `gorm:"column:anticoagulant_stop_time_hour" json:"anticoagulant_stop_time_hour" form:"anticoagulant_stop_time_hour"`
290
+
291
+	HemodialysisPipelines      string  `gorm:"column:hemodialysis_pipelines" json:"hemodialysis_pipelines" form:"hemodialysis_pipelines"`
292
+	HemodialysisPipelinesCount float64 `gorm:"column:hemodialysis_pipelines_count" json:"hemodialysis_pipelines_count" form:"hemodialysis_pipelines_count"`
293
+	PunctureNeedle             string  `gorm:"column:puncture_needle" json:"puncture_needle" form:"puncture_needle"`
294
+	PunctureNeedleCount        float64 `gorm:"column:puncture_needle_count" json:"puncture_needle_count" form:"puncture_needle_count"`
295
+	Epo                        string  `gorm:"column:epo" json:"epo" form:"epo"`
296
+	EpoCount                   float64 `gorm:"column:epo_count" json:"epo_count" form:"epo_count"`
297
+}
298
+
299
+func (BloodDialysisPrescription) TableName() string {
300
+	return "xt_dialysis_prescription"
301
+}
302
+
303
+type DialysisTotalDataStruct struct {
304
+	Date   string `json:"date"`
305
+	Number string `json:"number"`
306
+	ModeID string `json:"mode_id"`
307
+}
308
+
309
+//type UserInspectionProjectCount struct {
310
+//  PatientId int64
311
+//  Count     int64
312
+//  ProjectId int64
313
+//}
314
+
315
+type InspectionReferenceMaps struct {
316
+	ProjectName        string               `gorm:"-" json:"project_name" form:"project_name"`
317
+	Project            string               `gorm:"-" json:"project" form:"project"`
318
+	ProjectId          int64                `gorm:"-" json:"project_id" form:"project_id"`
319
+	Count              int64                `gorm:"-" json:"count" form:"count"`
320
+	CheckConfiguration []CheckConfiguration `gorm:"-" json:"inspection_reference" form:"inspection_reference"`
321
+}
322
+
323
+type VmPatientInspectionTwo struct {
324
+	ItemId int64 `gorm:"column:item_id" json:"item_id" form:"item_id"`
325
+	Total  int64
326
+	Count  int64
327
+	Sort   int64 `gorm:"column:sort" json:"sort" form:"sort"`
328
+}
329
+
330
+type VmPatientInspection struct {
331
+	ID           int64  `gorm:"column:id" json:"id" form:"id"`
332
+	PatientId    int64  `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
333
+	OrgId        int64  `gorm:"column:org_id" json:"org_id" form:"org_id"`
334
+	ProjectId    int64  `gorm:"column:project_id" json:"project_id" form:"project_id"`
335
+	ItemId       int64  `gorm:"column:item_id" json:"item_id" form:"item_id"`
336
+	ItemName     string `gorm:"column:item_name" json:"item_name" form:"item_name"`
337
+	ProjectName  string `gorm:"column:project_name" json:"project_name" form:"project_name"`
338
+	InspectType  int64  `gorm:"column:inspect_type" json:"inspect_type" form:"inspect_type"`
339
+	InspectValue string `gorm:"column:inspect_value" json:"inspect_value" form:"inspect_value"`
340
+	InspectDate  int64  `gorm:"column:inspect_date" json:"inspect_date" form:"inspect_date"`
341
+	Status       int64  `gorm:"column:status" json:"status" form:"status"`
342
+	CreatedTime  int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
343
+	UpdatedTime  int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
344
+	Name         string `gorm:"column:name" json:"name" form:"name"`
345
+	RangMax      string `gorm:"column:range_max" json:"range_max" form:"range_max"`
346
+	RangMin      string `gorm:"column:range_min" json:"range_min" form:"range_min"`
347
+	Total        int64
348
+	Count        int64
349
+	Sort         int64 `gorm:"column:sort" json:"sort" form:"sort"`
350
+}
351
+
352
+type XtPatientInspection struct {
353
+	ID           int64  `gorm:"column:id" json:"id" form:"id"`
354
+	PatientId    int64  `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
355
+	OrgId        int64  `gorm:"column:org_id" json:"org_id" form:"org_id"`
356
+	ProjectId    int64  `gorm:"column:project_id" json:"project_id" form:"project_id"`
357
+	ItemId       int64  `gorm:"column:item_id" json:"item_id" form:"item_id"`
358
+	ItemName     string `gorm:"column:item_name" json:"item_name" form:"item_name"`
359
+	ProjectName  string `gorm:"column:project_name" json:"project_name" form:"project_name"`
360
+	InspectType  int64  `gorm:"column:inspect_type" json:"inspect_type" form:"inspect_type"`
361
+	InspectValue string `gorm:"column:inspect_value" json:"inspect_value" form:"inspect_value"`
362
+	InspectDate  int64  `gorm:"column:inspect_date" json:"inspect_date" form:"inspect_date"`
363
+	Status       int64  `gorm:"column:status" json:"status" form:"status"`
364
+	CreatedTime  int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
365
+	UpdatedTime  int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
366
+	Name         string `gorm:"column:name" json:"name" form:"name"`
367
+	RangMax      string `gorm:"column:range_max" json:"range_max" form:"range_max"`
368
+	RangMin      string `gorm:"column:range_min" json:"range_min" form:"range_min"`
369
+	Count        int64
370
+}
371
+
372
+type PatientsInspection struct {
373
+	ID           int64  `gorm:"column:id" json:"id" form:"id"`
374
+	PatientId    int64  `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
375
+	OrgId        int64  `gorm:"column:org_id" json:"org_id" form:"org_id"`
376
+	ProjectId    int64  `gorm:"column:project_id" json:"project_id" form:"project_id"`
377
+	ItemId       int64  `gorm:"column:item_id" json:"item_id" form:"item_id"`
378
+	ItemName     string `gorm:"column:item_name" json:"item_name" form:"item_name"`
379
+	ProjectName  string `gorm:"column:project_name" json:"project_name" form:"project_name"`
380
+	InspectType  int64  `gorm:"column:inspect_type" json:"inspect_type" form:"inspect_type"`
381
+	InspectValue string `gorm:"column:inspect_value" json:"inspect_value" form:"inspect_value"`
382
+	InspectDate  int64  `gorm:"column:inspect_date" json:"inspect_date" form:"inspect_date"`
383
+	Status       int64  `gorm:"column:status" json:"status" form:"status"`
384
+	CreatedTime  int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
385
+	UpdatedTime  int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
386
+	Name         string `gorm:"column:name" json:"name" form:"name"`
387
+}
388
+
389
+func (PatientsInspection) TableName() string {
390
+
391
+	return "xt_inspection"
392
+}
393
+
394
+type PatientInspectionProjectCount struct {
395
+	PatientId   int64
396
+	Count       int64
397
+	ProjectId   int64
398
+	ProjectName string
399
+	Name        string `gorm:"column:name" json:"name" form:"name"`
400
+}
401
+
402
+type ProjectCountOne struct {
403
+	Total   string
404
+	Count   int64
405
+	NoCount int64
406
+}
407
+
408
+type ProjectCountTwo struct {
409
+	Name  string
410
+	Count int64
411
+}
412
+
413
+type ProjectCount struct {
414
+	Total string
415
+	Count int64
416
+}
417
+
418
+type PatientInspectionCount struct {
419
+	ID           int64  `gorm:"column:id" json:"id" form:"id"`
420
+	PatientId    int64  `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
421
+	OrgId        int64  `gorm:"column:org_id" json:"org_id" form:"org_id"`
422
+	ProjectId    int64  `gorm:"column:project_id" json:"project_id" form:"project_id"`
423
+	ItemId       int64  `gorm:"column:item_id" json:"item_id" form:"item_id"`
424
+	ItemName     string `gorm:"column:item_name" json:"item_name" form:"item_name"`
425
+	ProjectName  string `gorm:"column:project_name" json:"project_name" form:"project_name"`
426
+	InspectType  int64  `gorm:"column:inspect_type" json:"inspect_type" form:"inspect_type"`
427
+	InspectValue string `gorm:"column:inspect_value" json:"inspect_value" form:"inspect_value"`
428
+	InspectDate  int64  `gorm:"column:inspect_date" json:"inspect_date" form:"inspect_date"`
429
+	Status       int64  `gorm:"column:status" json:"status" form:"status"`
430
+	CreatedTime  int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
431
+	UpdatedTime  int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
432
+	Name         string `gorm:"column:name" json:"name" form:"name"`
433
+	RangMax      string `gorm:"column:range_max" json:"range_max" form:"range_max"`
434
+	RangMin      string `gorm:"column:range_min" json:"range_min" form:"range_min"`
435
+	Unit         string `gorm:"column:unit" json:"unit" form:"unit"`
436
+	DialysisNo   string `gorm:"column:dialysis_no" json:"dialysis_no" form:"dialysis_no"`
437
+	RangeValue   string `gorm:"column:range_value" json:"range_value" form:"range_value"`
438
+	Sort         int64  `gorm:"column:sort" json:"sort" form:"sort"`
439
+	LargeRange   string `gorm:"column:large_range" json:"large_range" form:"large_range"`
440
+	MinRange     string `gorm:"column:min_range" json:"min_range" form:"min_range"`
441
+	RangeType    int64  `gorm:"column:range_type" json:"range_type" form:"range_type"`
442
+}
443
+
444
+func (PatientInspectionCount) TableName() string {
445
+
446
+	return "xt_inspection"
447
+}
448
+
449
+type BloodDialysisOrderCount struct {
450
+	PatientId int64 `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
451
+	Count     int64
452
+}
453
+
454
+type BloodDialysisOrder struct {
455
+	ID                 int64  `gorm:"column:id" json:"id" form:"id"`
456
+	DialysisDate       int64  `gorm:"column:dialysis_date" json:"dialysis_date" form:"dialysis_date"`
457
+	UserOrgId          int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
458
+	PatientId          int64  `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
459
+	PrescriptionId     int64  `gorm:"column:prescription_id" json:"prescription_id" form:"prescription_id"`
460
+	Stage              int64  `gorm:"column:stage" json:"stage" form:"stage"`
461
+	Remark             string `gorm:"column:remark" json:"remark" form:"remark"`
462
+	BedId              int64  `gorm:"column:bed_id" json:"bed_id" form:"bed_id"`
463
+	StartNurse         int64  `gorm:"column:start_nurse" json:"start_nurse" form:"start_nurse"`
464
+	FinishNurse        int64  `gorm:"column:finish_nurse" json:"finish_nurse" form:"finish_nurse"`
465
+	Status             int64  `gorm:"column:status" json:"status" form:"status"`
466
+	CreatedTime        int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
467
+	UpdatedTime        int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
468
+	PunctureNurse      int64  `gorm:"column:puncture_nurse" json:"puncture_nurse" form:"puncture_nurse"`
469
+	Creator            int64  `gorm:"column:creator" json:"creator" form:"creator"`
470
+	Modifier           int64  `gorm:"column:modifier" json:"modifier" form:"modifier"`
471
+	FinishCreator      int64  `gorm:"column:finish_creator" json:"finish_creator" form:"finish_creator"`
472
+	FinishModifier     int64  `gorm:"column:finish_modifier" json:"finish_modifier" form:"finish_modifier"`
473
+	SchedualType       int64  `gorm:"column:schedual_type" json:"schedual_type" form:"schedual_type"`
474
+	StartTime          int64  `gorm:"column:start_time" json:"start_time" form:"start_time"`
475
+	EndTime            int64  `gorm:"column:end_time" json:"end_time" form:"end_time"`
476
+	ModeId             int64  `gorm:"column:mode_id" json:"mode_id" form:"mode_id"`
477
+	Name               string `gorm:"column:name" json:"name" form:"name"`
478
+	DialysisNo         string `gorm:"column:dialysis_no" json:"dialysis_no" form:"dialysis_no"`
479
+	IdCardNo           string `gorm:"column:id_card_no" json:"id_card_no" form:"id_card_no"`
480
+	TotalDialysis      int64  `gorm:"column:total_dialysis" json:"total_dialysis" form:"total_dialysis"`
481
+	UserSysBeforeCount int64  `gorm:"column:user_sys_before_count" json:"user_sys_before_count" form:"user_sys_before_count"`
482
+}
483
+
484
+type TreatDialysisOrder struct {
485
+	Date string `json:"date"`
486
+}
487
+
488
+type TreatTotalStruct struct {
489
+	Number string `json:"number"`
490
+	ModeID string `json:"mode_id"`
491
+}
492
+
493
+type XTMonitoringRecords struct {
494
+	ID                     int64   `gorm:"column:id" json:"id"`
495
+	UserOrgId              int64   `gorm:"column:user_org_id" json:"user_org_id"`
496
+	PatientId              int64   `gorm:"column:patient_id" json:"patient_id"`
497
+	SystolicBloodPressure  float64 `gorm:"column:systolic_blood_pressure" json:"systolic_blood_pressure"`
498
+	DiastolicBloodPressure float64 `gorm:"column:diastolic_blood_pressure" json:"diastolic_blood_pressure"`
499
+	Monitoring_date        int64   `gorm:"column:monitoring_date" json:"monitoring_date"`
500
+	Name                   string  `gorm:"column:name" json:"name"`
501
+}
502
+
503
+type XTMonitoringRecord struct {
504
+	ID                        int64   `gorm:"column:id" json:"id"`
505
+	UserOrgId                 int64   `gorm:"column:user_org_id" json:"user_org_id"`
506
+	PatientId                 int64   `gorm:"column:patient_id" json:"patient_id"`
507
+	DialysisOrderId           int64   `gorm:"column:dialysis_order_id" json:"dialysis_order_id"`
508
+	MonitoringDate            int64   `gorm:"column:monitoring_date" json:"monitoring_date"`
509
+	OperateTime               int64   `gorm:"column:operate_time" json:"operate_time"`
510
+	MonitoringTime            string  `gorm:"column:monitoring_time" json:"monitoring_time"`
511
+	PulseFrequency            float64 `gorm:"column:pulse_frequency" json:"pulse_frequency"`
512
+	BreathingRate             float64 `gorm:"column:breathing_rate" json:"breathing_rate"`
513
+	SystolicBloodPressure     float64 `gorm:"column:systolic_blood_pressure" json:"systolic_blood_pressure"`
514
+	DiastolicBloodPressure    float64 `gorm:"column:diastolic_blood_pressure" json:"diastolic_blood_pressure"`
515
+	BloodPressureType         int64   `gorm:"column:blood_pressure_type" json:"blood_pressure_type"`
516
+	Pic                       string  `gorm:"column:pic" json:"pic"`
517
+	BloodFlowVolume           float64 `gorm:"column:blood_flow_volume" json:"blood_flow_volume"`
518
+	VenousPressure            float64 `gorm:"column:venous_pressure" json:"venous_pressure"`
519
+	VenousPressureType        int64   `gorm:"column:venous_pressure_type" json:"venous_pressure_type"`
520
+	ArterialPressure          float64 `gorm:"column:arterial_pressure" json:"arterial_pressure"`
521
+	ArterialPressureType      int64   `gorm:"column:arterial_pressure_type" json:"arterial_pressure_type"`
522
+	TransmembranePressure     float64 `gorm:"column:transmembrane_pressure" json:"transmembrane_pressure"`
523
+	TransmembranePressureType int64   `gorm:"column:transmembrane_pressure_type" json:"transmembrane_pressure_type"`
524
+	UltrafiltrationRate       float64 `gorm:"column:ultrafiltration_rate" json:"ultrafiltration_rate"`
525
+	UltrafiltrationVolume     float64 `gorm:"column:ultrafiltration_volume" json:"ultrafiltration_volume"`
526
+	SodiumConcentration       float64 `gorm:"column:sodium_concentration" json:"sodium_concentration"`
527
+	DialysateTemperature      float64 `gorm:"column:dialysate_temperature" json:"dialysate_temperature"`
528
+	Temperature               float64 `gorm:"column:temperature" json:"temperature"`
529
+	ReplacementRate           float64 `gorm:"column:replacement_rate" json:"replacement_rate"`
530
+	DisplacementQuantity      float64 `gorm:"column:displacement_quantity" json:"displacement_quantity"`
531
+	Ktv                       float64 `gorm:"column:ktv" json:"ktv"`
532
+	Symptom                   string  `gorm:"column:symptom" json:"symptom"`
533
+	Dispose                   string  `gorm:"column:dispose" json:"dispose"`
534
+	Result                    string  `gorm:"column:result" json:"result"`
535
+	MonitoringNurse           int64   `gorm:"column:monitoring_nurse" json:"monitoring_nurse"`
536
+	Status                    int64   `gorm:"column:status" json:"status"`
537
+	CreatedTime               int64   `gorm:"column:created_time" json:"created_time"`
538
+	UpdatedTime               int64   `gorm:"column:updated_time" json:"updated_time"`
539
+	Conductivity              float64 `gorm:"column:conductivity" json:"conductivity"`
540
+	DisplacementFlowQuantity  float64 `gorm:"column:displacement_flow_quantity" json:"displacement_flow_quantity"`
541
+	BloodOxygenSaturation     string  `gorm:"column:blood_oxygen_saturation" json:"blood_oxygen_saturation" form:"blood_oxygen_saturation"`
542
+	Creator                   int64   `gorm:"column:creator" json:"creator" form:"creator"`
543
+	Modify                    int64   `gorm:"column:modify" json:"modify" form:"modify"`
544
+	Heparin                   float64 `gorm:"column:heparin" json:"heparin" form:"heparin"`
545
+	DialysateFlow             float64 `gorm:"column:dialysate_flow" json:"dialysate_flow" form:"dialysate_flow"`
546
+	Sort                      int64   `gorm:"column:sort" json:"sort"`
547
+}
548
+
549
+func (XTMonitoringRecord) TableName() string {
550
+	return "xt_monitoring_record"
551
+}
552
+
553
+type VmMonitoringRecord struct {
554
+	ID                     int64   `gorm:"column:id" json:"id"`
555
+	UserOrgId              int64   `gorm:"column:user_org_id" json:"user_org_id"`
556
+	PatientId              int64   `gorm:"column:patient_id" json:"patient_id"`
557
+	MonitoringTime         string  `gorm:"column:monitoring_time" json:"monitoring_time"`
558
+	SystolicBloodPressure  float64 `gorm:"column:systolic_blood_pressure" json:"systolic_blood_pressure"`
559
+	DiastolicBloodPressure float64 `gorm:"column:diastolic_blood_pressure" json:"diastolic_blood_pressure"`
560
+}
561
+
562
+func (VmMonitoringRecord) TableName() string {
563
+	return "xt_monitoring_record"
564
+}
565
+
566
+type XtPatientsInspection struct {
567
+	ID           int64  `gorm:"column:id" json:"id" form:"id"`
568
+	PatientId    int64  `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
569
+	OrgId        int64  `gorm:"column:org_id" json:"org_id" form:"org_id"`
570
+	ItemId       int64  `gorm:"column:item_id" json:"item_id" form:"item_id"`
571
+	ItemName     string `gorm:"column:item_name" json:"item_name" form:"item_name"`
572
+	InspectType  int64  `gorm:"column:inspect_type" json:"inspect_type" form:"inspect_type"`
573
+	InspectValue string `gorm:"column:inspect_value" json:"inspect_value" form:"inspect_value"`
574
+	InspectDate  int64  `gorm:"column:inspect_date" json:"inspect_date" form:"inspect_date"`
575
+	Status       int64  `gorm:"column:status" json:"status" form:"status"`
576
+	CreatedTime  int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
577
+	UpdatedTime  int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
578
+	Name         string `gorm:"column:name" json:"name" form:"name"`
579
+	MinRange     string `gorm:"column:min_range" json:"min_range" form:"min_range"`
580
+	LargeRange   string `gorm:"column:large_range" json:"large_range" form:"large_range"`
581
+	RangeType    int64  `gorm:"column:range_type" json:"range_type" form:"range_type"`
582
+	RangeValue   string `gorm:"column:range_value" json:"range_value" form:"range_value"`
583
+}
584
+
585
+type BloodDialysisModeIdCount struct {
586
+	PatientId int64 `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
587
+	ModeId    int64 `gorm:"column:mode_id" json:"mode_id" form:"mode_id"`
588
+	Count     int64
589
+}
590
+
591
+type BloodTreateModeIdCount struct {
592
+	ModeId       int64 `gorm:"column:mode_id" json:"mode_id" form:"mode_id"`
593
+	Count        int64
594
+	DialysisDate int64 `gorm:"column:dialysis_date" json:"dialysis_date" form:"dialysis_date"`
595
+}
596
+
597
+type BloodLapsetoCount struct {
598
+	ID          int64 `gorm:"column:id" json:"id" form:"id"`
599
+	Count       int64
600
+	LapsetoTime int64 `gorm:"column:lapseto_time" json:"lapseto_time" form:"lapseto_time"`
601
+	LapsetoType int64 `gorm:"column:lapseto_type" json:"lapseto_type" form:"lapseto_type"`
602
+}
603
+
604
+type BloodDialysisOrderOne struct {
605
+	PatientId   int64 `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
606
+	CreatedTime int64 `gorm:"column:created_time" json:"created_time" form:"created_time"`
607
+	UpdatedTime int64 `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
608
+	ModeId      int64 `gorm:"column:mode_id" json:"mode_id" form:"mode_id"`
609
+	Count       int64
610
+	StartNurse  int64 `gorm:"column:start_nurse" json:"start_nurse" form:"start_nurse"`
611
+}

+ 83 - 0
models/his_hospital_models.go Bestand weergeven

@@ -0,0 +1,83 @@
1
+package models
2
+
3
+type HisHospitalOrder 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
+	HisPatientId          int64   `gorm:"column:his_patient_id" json:"his_patient_id" form:"his_patient_id"`
7
+	SettleAccountsDate    int64   `gorm:"column:settle_accounts_date" json:"settle_accounts_date" form:"settle_accounts_date"`
8
+	Ctime                 int64   `gorm:"column:ctime" json:"ctime" form:"ctime"`
9
+	Mtime                 int64   `gorm:"column:mtime" json:"mtime" form:"mtime"`
10
+	Status                int64   `gorm:"column:status" json:"status" form:"status"`
11
+	Number                string  `gorm:"column:number" json:"number" form:"number"`
12
+	PatientId             int64   `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
13
+	MedfeeSumamt          float64 `gorm:"column:medfee_sumamt" json:"medfee_sumamt" form:"medfee_sumamt"`
14
+	OrderStatus           float64 `gorm:"column:order_status" json:"order_status" form:"order_status"`
15
+	PayWay                int64   `gorm:"column:pay_way" json:"pay_way" form:"pay_way"`
16
+	PayPrice              float64 `gorm:"column:pay_price" json:"pay_price" form:"pay_price"`
17
+	PayCardNo             string  `gorm:"column:pay_card_no" json:"pay_card_no" form:"pay_card_no"`
18
+	DiscountPrice         float64 `gorm:"column:discount_price" json:"discount_price" form:"discount_price"`
19
+	PreferentialPrice     float64 `gorm:"column:preferential_price" json:"preferential_price" form:"preferential_price"`
20
+	RealityPrice          float64 `gorm:"column:reality_price" json:"reality_price" form:"reality_price"`
21
+	FoundPrice            float64 `gorm:"column:found_price" json:"found_price" form:"found_price"`
22
+	MedicalInsurancePrice float64 `gorm:"column:medical_insurance_price" json:"medical_insurance_price" form:"medical_insurance_price"`
23
+	PrivatePrice          float64 `gorm:"column:private_price" json:"private_price" form:"private_price"`
24
+	Creator               int64   `gorm:"column:creator" json:"creator" form:"creator"`
25
+	MdtrtId               string  `gorm:"column:mdtrt_id" json:"mdtrt_id" form:"mdtrt_id"`
26
+	MzNumber              string  `gorm:"column:mz_number" json:"mz_number" form:"mz_number"`
27
+
28
+	FaPiaoCode   string `gorm:"column:fa_piao_code" json:"fa_piao_code" form:"fa_piao_code"`
29
+	FaPiaoNumber string `gorm:"column:fa_piao_number" json:"fa_piao_number" form:"fa_piao_number"`
30
+
31
+	IsPre     int64  `gorm:"column:is_pre" json:"is_pre" form:"is_pre"`
32
+	Diagnosis string `gorm:"column:diagnosis" json:"diagnosis" form:"diagnosis"`
33
+}
34
+
35
+func (HisHospitalOrder) TableName() string {
36
+	return "his_order"
37
+}
38
+
39
+type HisHospitalCheckRecord struct {
40
+	ID                   int64            `gorm:"column:id" json:"id" form:"id"`
41
+	Name                 string           `gorm:"column:name" json:"name" form:"name"`
42
+	MedicalTreatmentType int64            `gorm:"column:medical_treatment_type" json:"medical_treatment_type" form:"medical_treatment_type"`
43
+	RecordDate           int64            `gorm:"column:record_date" json:"record_date" form:"record_date"`
44
+	IdCardNo             string           `gorm:"column:id_card_no" json:"id_card_no" form:"id_card_no"`
45
+	AdminUserId          int64            `gorm:"column:admin_user_id" json:"admin_user_id" form:"admin_user_id"`
46
+	Departments          int64            `gorm:"column:departments" json:"departments" form:"departments"`
47
+	UserOrgId            int64            `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
48
+	Status               int64            `gorm:"column:status" json:"status" form:"status"`
49
+	Ctime                int64            `gorm:"column:ctime" json:"ctime" form:"ctime"`
50
+	Mtime                int64            `gorm:"column:mtime" json:"mtime" form:"mtime"`
51
+	PatientId            int64            `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
52
+	Number               string           `gorm:"column:number" json:"number" form:"number"`
53
+	Doctor               int64            `gorm:"column:doctor" json:"doctor" form:"doctor"`
54
+	PsnNo                string           `gorm:"column:psn_no" json:"psn_no" form:"psn_no"`
55
+	PsnCertType          string           `gorm:"column:psn_cert_type" json:"psn_cert_type" form:"psn_cert_type"`
56
+	Certno               string           `gorm:"column:certno" json:"certno" form:"certno"`
57
+	PsnName              string           `gorm:"column:psn_name" json:"psn_name" form:"psn_name"`
58
+	Gend                 string           `gorm:"column:gend" json:"gend" form:"gend"`
59
+	Naty                 string           `gorm:"column:naty" json:"naty" form:"naty"`
60
+	MedType              int64            `gorm:"column:med_type" json:"med_type" form:"med_type"`
61
+	Brdy                 string           `gorm:"column:brdy" json:"brdy" form:"brdy"`
62
+	Iinfo                string           `gorm:"column:iinfo" json:"iinfo" form:"iinfo"`
63
+	Idetinfo             string           `gorm:"column:idetinfo" json:"idetinfo" form:"idetinfo"`
64
+	IptOtpNo             string           `gorm:"column:ipt_otp_no" json:"ipt_otp_no" form:"ipt_otp_no"`
65
+	AdmBed               int64            `gorm:"column:adm_bed" json:"adm_bed" form:"adm_bed"`
66
+	IdCardType           int64            `gorm:"column:id_card_type" json:"id_card_type" form:"id_card_type"`
67
+	Diagnosis            string           `gorm:"column:diagnosis" json:"diagnosis" form:"diagnosis"`
68
+	SickType             int64            `gorm:"column:sick_type" json:"sick_type" form:"sick_type"`
69
+	MdtrtCertType        string           `gorm:"column:mdtrt_cert_type" json:"mdtrt_cert_type" form:"mdtrt_cert_type"`
70
+	InHosptialTime       string           `gorm:"column:in_hosptial_time" json:"in_hosptial_time" form:"in_hosptial_time"`
71
+	OutHosptialTime      string           `gorm:"column:out_hosptial_time" json:"out_hosptial_time" form:"out_hosptial_time"`
72
+	InHospitalStatus     int64            `gorm:"column:in_hospital_status" json:"in_hospital_status" form:"in_hospital_status"`
73
+	Certificates         int64            `gorm:"column:certificates" json:"certificates" form:"certificates"`
74
+	InsutypeType         string           `gorm:"column:insutype_type" json:"insutype_type" form:"insutype_type"`
75
+	OutHospitalStatus    int64            `gorm:"column:out_hospital_status" json:"out_hospital_status" form:"out_hospital_status"`
76
+	OutWay               int64            `gorm:"column:out_way" json:"out_way" form:"out_way"`
77
+	Phone                string           `gorm:"column:phone" json:"phone" form:"phone"`
78
+	HisHospitalOrder     HisHospitalOrder `gorm:"ForeignKey:MdtrtId,PatientId;AssociationForeignKey:Number,PatientId" json:"order"`
79
+}
80
+
81
+func (HisHospitalCheckRecord) TableName() string {
82
+	return "his_hospital_check_record"
83
+}

Diff onderdrukt omdat het te groot bestand
+ 1418 - 0
models/his_models.go


Diff onderdrukt omdat het te groot bestand
+ 3319 - 0
models/service/common_service.go


+ 400 - 0
service/admin_service.go Bestand weergeven

@@ -0,0 +1,400 @@
1
+// 统计后台的 service
2
+
3
+package service
4
+
5
+import (
6
+	"Xcx_New/models"
7
+	"Xcx_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
+}

+ 268 - 0
service/app_version.go Bestand weergeven

@@ -0,0 +1,268 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_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
+}
232
+
233
+func FindAllPrescription(org_id int64) (prescription []*models.DialysisPrescription, err error) {
234
+	err = readDb.Model(&models.DialysisPrescription{}).Where("user_org_id=? AND status= 1 AND record_date >= 1593446400", org_id).Find(&prescription).Error
235
+	return
236
+}
237
+
238
+func AddSigleDialysisBeforePre(before *models.DialysisBeforePrepare) {
239
+	writeDb.Create(&before)
240
+}
241
+
242
+func GetAllHisDoctorInfo(org_id int64) (his []*models.HisDoctorAdviceInfo, err error) {
243
+	err = readDb.Model(&models.HisDoctorAdviceInfo{}).Where("user_org_id = ? AND status = 1", org_id).Find(&his).Error
244
+	return
245
+}
246
+
247
+func GetAllHisInfo(org_id int64) (his []*models.HisPrescriptionProject, err error) {
248
+	err = readDb.Model(&models.HisPrescriptionProject{}).Where("user_org_id = ? AND status = 1", org_id).Find(&his).Error
249
+	return
250
+}
251
+
252
+func UpDateHis(his *models.HisDoctorAdviceInfo) {
253
+	writeDb.Save(&his)
254
+}
255
+
256
+func UpDateHis2(his *models.HisPrescriptionProject) {
257
+	writeDb.Save(&his)
258
+}
259
+
260
+func GetAllHisOrder() (his []*models.HisOrder, err error) {
261
+	err = readDb.Model(&models.HisOrder{}).Where("user_org_id = 10106 AND status = 1 AND order_status = 2 AND settle_accounts_date < 1623168000").Find(&his).Error
262
+	return
263
+}
264
+
265
+func GetLastHisOrder() (his models.HisOrder, err error) {
266
+	err = readDb.Model(&models.HisOrder{}).Where("user_org_id = 4 AND status = 1 AND order_status = 2").Last(&his).Error
267
+	return
268
+}

+ 46 - 0
service/auto_clear_schedules_service.go Bestand weergeven

@@ -0,0 +1,46 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_New/models"
5
+	"Xcx_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).
43
+			Updates(map[string]interface{}{"status": 0, "updated_time": time.Now().Unix()})
44
+	}
45
+	utils.SuccessLog("自动清除排班任务完成")
46
+}

+ 110 - 0
service/auto_create_drug.go Bestand weergeven

@@ -0,0 +1,110 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_New/models"
5
+	"Xcx_New/utils"
6
+	"fmt"
7
+	"github.com/robfig/cron"
8
+	"strconv"
9
+	"time"
10
+)
11
+
12
+var createDrugCronJob *cron.Cron
13
+
14
+func init() {
15
+	createDrugCronJob = cron.New()
16
+	utils.InfoLog("开启自动更新药品库存定时任务")
17
+	spec := "0 */1 * * * ?" // 每1分钟执行一次
18
+	//spec := "0 55 23 * * ?" // 每天23点55执行一次
19
+	//spec := "0 0 0 ? * Sun"
20
+	createDrugCronJob.AddFunc(spec, func() {
21
+		AutoCreateDrugJob()
22
+	})
23
+
24
+}
25
+
26
+func BeginAutoCreateDrugJob() {
27
+
28
+	createDrugCronJob.Start()
29
+}
30
+
31
+func AutoCreateDrugJob() {
32
+
33
+	timeStr := time.Now().Format("2006-01-02")
34
+	timeLayout := "2006-01-02 15:04:05"
35
+	fmt.Println("timeStr:", timeStr)
36
+	timeStringToTime, _ := utils.ParseTimeStringToTime(timeLayout, timeStr+" 00:00:00")
37
+	timenow := timeStringToTime.Unix()
38
+	fmt.Println("timenow是什么", timenow)
39
+	//查询当天排班所有机构
40
+	org, errs := GetAllOrgName(timenow)
41
+	fmt.Print("错误是什么", errs)
42
+	fmt.Println("查询有机构失败", err)
43
+
44
+	var total int64
45
+	for _, item := range org {
46
+		fmt.Println("hhhh2h3h2323232323232323", item.UserOrgId)
47
+		//查询该机构下的所有药品信息
48
+		list, _ := FindAllDrugList(item.UserOrgId)
49
+		for _, ite := range list {
50
+			countList, _ := FindAllDrugTotalCount(ite.ID)
51
+			for _, it := range countList {
52
+				if ite.ID == it.DrugId {
53
+					//转为拆零数量
54
+					it.StockMaxNumber = it.StockMaxNumber * it.MinNumber
55
+
56
+					total = it.StockMaxNumber + it.StockMinNumber
57
+					fmt.Println(it.StockMaxNumber)
58
+					fmt.Println(it.StockMinNumber)
59
+					fmt.Println("total223232323232323232323", total)
60
+					formatInt := strconv.FormatInt(total, 10)
61
+					float, _ := strconv.ParseFloat(formatInt, 64)
62
+					fmt.Println("min_number2323232323232", float)
63
+					lib := models.BaseDrugLib{
64
+						Total: float,
65
+					}
66
+					UpdateDrugTotal(it.DrugId, lib)
67
+				}
68
+			}
69
+		}
70
+	}
71
+
72
+}
73
+
74
+//查询当天有排班的所有机构
75
+func GetAllOrgName(time int64) (schedule []*models.XtSchedule, err error) {
76
+
77
+	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
78
+
79
+	return schedule, err
80
+}
81
+
82
+//根据机构ID查询药品信息
83
+func FindAllDrugList(orgid int64) (lib []*models.BaseDrugLib, err error) {
84
+
85
+	err = XTReadDB().Where("org_id = ? and status = 1", orgid).Find(&lib).Error
86
+	return lib, err
87
+}
88
+
89
+//根据药品ID统计该药品的库存
90
+func FindAllDrugTotalCount(drug_id int64) (info []*models.DrugWarehouseInfoSix, err error) {
91
+
92
+	db := XTReadDB().Table("xt_drug_warehouse_info as x").Where("x.status = 1")
93
+	table := XTReadDB().Table("xt_base_drug as b").Where("b.status = 1")
94
+	fmt.Println(table)
95
+	if drug_id > 0 {
96
+		db = db.Where("x.drug_id = ?", drug_id)
97
+	}
98
+
99
+	err = db.Select("x.drug_id,sum(x.stock_max_number) as stock_max_number,sum(x.stock_min_number) as stock_min_number,b.min_number").Joins("left join xt_base_drug as b on b.id = x.drug_id").Scan(&info).Error
100
+
101
+	return info, err
102
+}
103
+
104
+//更新药品库的total字段
105
+
106
+func UpdateDrugTotal(id int64, lib models.BaseDrugLib) error {
107
+
108
+	err := XTWriteDB().Model(&lib).Where("id=? and status = 1", id).Updates(map[string]interface{}{"total": lib.Total}).Error
109
+	return err
110
+}

+ 149 - 0
service/auto_create_staff_schedule_service.go Bestand weergeven

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

+ 87 - 0
service/auto_create_stock.go Bestand weergeven

@@ -0,0 +1,87 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_New/models"
5
+	"Xcx_New/utils"
6
+	"fmt"
7
+	"github.com/robfig/cron"
8
+	"strconv"
9
+	"time"
10
+)
11
+
12
+var createStockCronJob *cron.Cron
13
+
14
+func init() {
15
+	utils.InfoLog("开启自动更新耗材库存定时任务")
16
+	createStockCronJob = cron.New()
17
+	spec := "0 */5 * * * ?" // 每1分钟执行一次
18
+	//spec := "0 55 23 * * ?" // 每天23点55执行一次
19
+	//spec := "0 0 0 ? * Sun"
20
+	createStockCronJob.AddFunc(spec, func() {
21
+		AutoCreateStockJob()
22
+	})
23
+}
24
+
25
+func BeginAutoCreateStockJob() {
26
+
27
+	createStockCronJob.Start()
28
+}
29
+
30
+func AutoCreateStockJob() {
31
+
32
+	timeStr := time.Now().Format("2006-01-02")
33
+	timeLayout := "2006-01-02 15:04:05"
34
+	fmt.Println("timeStr:", timeStr)
35
+	timeStringToTime, _ := utils.ParseTimeStringToTime(timeLayout, timeStr+" 00:00:00")
36
+	timenow := timeStringToTime.Unix()
37
+	fmt.Println("timenow是什么", timenow)
38
+	//查询当天排班所有机构
39
+	org, errs := GetAllOrgName(timenow)
40
+	fmt.Print("错误是什么", errs)
41
+	fmt.Println("查询有机构失败", err)
42
+
43
+	for _, item := range org {
44
+
45
+		information, _ := FindAlLGoodInformation(item.UserOrgId)
46
+		for _, ite := range information {
47
+			countList, _ := FindAllGoodInformationTotalCount(ite.ID)
48
+			for _, it := range countList {
49
+				if ite.ID == it.GoodId {
50
+					formatInt := strconv.FormatInt(it.StockCount, 10)
51
+					total, _ := strconv.ParseFloat(formatInt, 64)
52
+					info := models.GoodInfo{
53
+						Total: total,
54
+					}
55
+					UpdateStockTotal(it.GoodId, info)
56
+				}
57
+			}
58
+		}
59
+
60
+	}
61
+}
62
+
63
+//查询所有的耗材信息
64
+func FindAlLGoodInformation(orgid int64) (info []*models.GoodInfo, err error) {
65
+
66
+	err = XTReadDB().Where("org_id = ? and status = 1", orgid).Find(&info).Error
67
+	return info, err
68
+}
69
+
70
+func FindAllGoodInformationTotalCount(good_id int64) (info []*models.WarehousingInfo, err error) {
71
+
72
+	db := XTReadDB().Table("xt_warehouse_info as x").Where("x.status =1")
73
+
74
+	if good_id > 0 {
75
+		db = db.Where("x.good_id = ?", good_id)
76
+	}
77
+	err = db.Select("x.good_id,sum(x.stock_count) as stock_count,x.warehousing_count").Find(&info).Error
78
+	return info, err
79
+}
80
+
81
+//更新耗材库的total字段
82
+
83
+func UpdateStockTotal(id int64, lib models.GoodInfo) error {
84
+
85
+	err := XTWriteDB().Model(&lib).Where("id=? and status = 1", id).Updates(map[string]interface{}{"total": lib.Total}).Error
86
+	return err
87
+}

+ 261 - 0
service/auto_create_week_disinfection.go Bestand weergeven

@@ -0,0 +1,261 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_New/models"
5
+	"Xcx_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
+}

+ 149 - 0
service/auto_create_week_plan.go Bestand weergeven

@@ -0,0 +1,149 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_New/models"
5
+	"Xcx_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
+}

+ 281 - 0
service/auto_create_week_schedules_service.go Bestand weergeven

@@ -0,0 +1,281 @@
1
+package service
2
+
3
+import (
4
+	"fmt"
5
+	"strings"
6
+	"time"
7
+
8
+	"Xcx_New/models"
9
+	"Xcx_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
+}

Diff onderdrukt omdat het te groot bestand
+ 3554 - 0
service/common_service.go


+ 345 - 0
service/data.go Bestand weergeven

@@ -0,0 +1,345 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_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 GetDictConfigList(orgID int64) (dataconfig interface{}, err error) {
119
+	var configList []*models.DictionaryDataconfig
120
+
121
+	err = readDb.Model(&models.DictionaryDataconfig{}).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
122
+	if err != nil {
123
+		return nil, err
124
+	}
125
+
126
+	// configResult := make([]*ConfigViewModel,0)
127
+	childConfig := make(map[int64][]*models.DictionaryDataconfig)
128
+	resultConfig := make(map[string][]*models.DictionaryConfigViewModel)
129
+	deleteSystemChilds := make([]*models.DictionaryDataconfig, 0)
130
+	editSystemChilds := make([]*models.DictionaryDataconfig, 0)
131
+	for _, config := range configList {
132
+		if config.Status == 1 && config.DeleteIdSystem > 0 {
133
+			editSystemChilds = append(editSystemChilds, config)
134
+		}
135
+
136
+		if config.Status == 0 && config.DeleteIdSystem > 0 {
137
+			deleteSystemChilds = append(deleteSystemChilds, config)
138
+		}
139
+	}
140
+	continueFlag := false
141
+	for _, config := range configList {
142
+		continueFlag = false
143
+		if config.ParentId == 0 {
144
+			newConfig := &models.DictionaryConfigViewModel{
145
+				ID:           config.ID,
146
+				ParentId:     config.ParentId,
147
+				Module:       config.Module,
148
+				OrgId:        config.OrgId,
149
+				Name:         config.Name,
150
+				FieldName:    config.FieldName,
151
+				Value:        config.Value,
152
+				CreateUserId: config.CreateUserId,
153
+				Status:       config.Status,
154
+				Remark:       config.Remark,
155
+				Title:        config.Title,
156
+				Content:      config.Content,
157
+			}
158
+			// configResult = append(configResult,newConfig)
159
+			result := resultConfig[config.Module]
160
+			if result == nil {
161
+				result = make([]*models.DictionaryConfigViewModel, 0)
162
+			}
163
+			for _, vm := range editSystemChilds {
164
+				if vm.DeleteIdSystem == config.ID {
165
+					continueFlag = true
166
+					break
167
+				}
168
+			}
169
+
170
+			for _, _vm := range deleteSystemChilds {
171
+				if _vm.DeleteIdSystem == config.ID {
172
+					continueFlag = true
173
+					break
174
+				}
175
+			}
176
+			if config.OrgId != 0 && config.Status == 0 && config.DeleteIdSystem > 0 {
177
+				continue
178
+			}
179
+			if continueFlag {
180
+				continue
181
+			}
182
+			result = append(result, newConfig)
183
+			resultConfig[config.Module] = result
184
+		} else {
185
+			childs := childConfig[config.ParentId]
186
+			if childs == nil {
187
+				childs = make([]*models.DictionaryDataconfig, 0)
188
+			}
189
+			continueFlag := false
190
+			for _, vm := range editSystemChilds {
191
+				if vm.DeleteIdSystem == config.ID {
192
+					continueFlag = true
193
+					break
194
+				}
195
+			}
196
+
197
+			for _, _vm := range deleteSystemChilds {
198
+				if _vm.DeleteIdSystem == config.ID {
199
+					continueFlag = true
200
+					break
201
+				}
202
+			}
203
+			if config.OrgId != 0 && config.Status == 0 && config.DeleteIdSystem > 0 {
204
+				continue
205
+			}
206
+			if continueFlag {
207
+				continue
208
+			}
209
+
210
+			childs = append(childs, config)
211
+			childConfig[config.ParentId] = childs
212
+		}
213
+	}
214
+
215
+	for _, vm := range resultConfig {
216
+		for _, _vm := range vm {
217
+			_vm.Childs = childConfig[_vm.ID]
218
+		}
219
+		// vm.Childs = childConfig[vm.ID]
220
+	}
221
+	return resultConfig, err
222
+}
223
+
224
+func FindConfigByFieldname(module string, field_name string, org_id int64) (dataconfig models.Dataconfig, err error) {
225
+	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
226
+	return
227
+}
228
+
229
+func FindConfigByTitle(module string, title string, org_id int64) (dataconfig models.Dataconfig, err error) {
230
+	err = readDb.Model(&models.Dataconfig{}).Where("module=? and title=? and org_id in (0,?) and status = 1", module, title, org_id).First(&dataconfig).Error
231
+	return
232
+}
233
+
234
+func FindConfigByName(module string, name string, parent_id int64, org_id int64) (dataconfig models.Dataconfig, err error) {
235
+	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
236
+	return
237
+}
238
+
239
+func FindConfigByNameForUpdate(module string, name string, parent_id int64, org_id int64, id int64) (dataconfig models.Dataconfig, err error) {
240
+	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
241
+	return
242
+}
243
+
244
+func FindConfigByTitleForUpdate(module string, title string, org_id int64, id int64) (dataconfig models.Dataconfig, err error) {
245
+	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
246
+	return
247
+}
248
+
249
+func UpdateChildConfig(dataconfig *models.Dataconfig) (err error) {
250
+	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, "field_type": dataconfig.FieldType}).Error
251
+	return
252
+}
253
+
254
+func UpdateTemplate(dataconfig *models.Dataconfig) (err error) {
255
+	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
256
+	return
257
+}
258
+
259
+func CreateConfig(dataconfig *models.Dataconfig) (err error) {
260
+	// readDb.Model(&models.Dataconfig{}).Where("module = ? and parent_id = 0 and org_id in (0,?)",dataconfig.Module,dataconfig.OrgId).Count(&total)
261
+	err = readDb.Create(&dataconfig).Error
262
+	return
263
+}
264
+
265
+func GetChildValue(module string, parent_id int64, org_id int64) (value int) {
266
+	readDb.Model(&models.Dataconfig{}).Where("module=? and parent_id=? and org_id in (0,?)", module, parent_id, org_id).Count(&value)
267
+	return
268
+}
269
+
270
+func DeleteChildConfig(dataconfig *models.Dataconfig) (err error) {
271
+	err = readDb.Model(&models.Dataconfig{}).Where("id =?", dataconfig.ID).Update(map[string]interface{}{"status": dataconfig.Status, "update_time": dataconfig.UpdatedTime}).Error
272
+	return
273
+}
274
+
275
+func FindFiledByOrgId(org_id int64) (filedConfig []*models.FiledConfig, err error) {
276
+	err = readDb.Model(&models.FiledConfig{}).Where("org_id =? AND  sys_module = 0", org_id).Find(&filedConfig).Error
277
+	return
278
+}
279
+
280
+func FindQualityByOrgId(orgid int64) (xtquality []*models.XtQualityControlStandard, err error) {
281
+
282
+	err = readDb.Model(&models.XtQualityControlStandard{}).Where("user_org_id =? and status =1 and is_status = 1", orgid).Find(&xtquality).Error
283
+	return
284
+}
285
+
286
+func GetDefaultSystolicPressure(orgid int64) (xtquality []*models.XtQualityControlStandard, err error) {
287
+
288
+	err = readDb.Model(&models.XtQualityControlStandard{}).Where("user_org_id = ? and status = 1 and is_status =0", orgid).Find(&xtquality).Error
289
+	return
290
+}
291
+
292
+func FindeInspectionByOrgId(orgid int64) (xtquality []*models.XtCheckConfiguration, err error) {
293
+
294
+	err = readDb.Model(&models.XtQualityControlStandard{}).Where("user_org_id = ? and status =1", orgid).Find(&xtquality).Error
295
+	return
296
+}
297
+
298
+func BatchInsertFiledConfig(org_id int64) (err error) {
299
+	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
300
+	return
301
+}
302
+
303
+func BatchInsertQualityControl(org_id int64) (err error) {
304
+
305
+	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
306
+	return
307
+}
308
+
309
+func BathInsertQualityControlTwo(org_id int64) (err error) {
310
+	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
311
+	return
312
+}
313
+
314
+func BatchInspectionConfiguration(orgid int64) (err error) {
315
+
316
+	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
317
+	return
318
+}
319
+
320
+func ShowFiledConfig(org_id int64, isShow int, id int64) (err error) {
321
+	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
322
+	return
323
+}
324
+
325
+func FindSysDialysisFiledByOrgId() (filedConfig []*models.FiledConfig, err error) {
326
+	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
327
+	return
328
+}
329
+
330
+func BatchInsertFiledSystemConfig(org_id int64) (err error) {
331
+	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
332
+	return
333
+}
334
+
335
+func BatchInsertDoctorSchedule(orgid int64) (err error) {
336
+
337
+	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
338
+	return
339
+}
340
+
341
+func CreateContinueSchedule(schedule *models.ContinueSchedule) error {
342
+
343
+	err := writeDb.Model(&schedule).Create(&schedule).Error
344
+	return err
345
+}

+ 274 - 0
service/db.go Bestand weergeven

@@ -0,0 +1,274 @@
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 readMiddleDb *gorm.DB
33
+var writeMiddleDb *gorm.DB
34
+
35
+var readPatientDb *gorm.DB
36
+var writePatientDb *gorm.DB
37
+
38
+var readSgjPatientDb *gorm.DB
39
+var writeSgjPatientDb *gorm.DB
40
+
41
+var readUserDbT *gorm.DB
42
+var writeUserDbT *gorm.DB
43
+
44
+var err error
45
+
46
+func ConnectDB() {
47
+	readHost := beego.AppConfig.String("readmysqlhost")
48
+	readPort := beego.AppConfig.String("readmysqlport")
49
+	readUser := beego.AppConfig.String("readmysqluser")
50
+	readPass := beego.AppConfig.String("readmysqlpass")
51
+	readName := beego.AppConfig.String("readmysqlname")
52
+
53
+	writeHost := beego.AppConfig.String("writemysqlhost")
54
+	writePort := beego.AppConfig.String("writemysqlport")
55
+	writeUser := beego.AppConfig.String("writemysqluser")
56
+	writePass := beego.AppConfig.String("writemysqlpass")
57
+	writeName := beego.AppConfig.String("writemysqlname")
58
+
59
+	readUserHost := beego.AppConfig.String("readuserhost")
60
+	readUserPort := beego.AppConfig.String("readuserport")
61
+	readUserUser := beego.AppConfig.String("readuseruser")
62
+	readUserPass := beego.AppConfig.String("readuserpass")
63
+	readUserName := beego.AppConfig.String("readusername")
64
+
65
+	writeUserHost := beego.AppConfig.String("writeuserhost")
66
+	writeUserPort := beego.AppConfig.String("writeuserport")
67
+	writeUserUser := beego.AppConfig.String("writeuseruser")
68
+	writeUserPass := beego.AppConfig.String("writeuserpass")
69
+	writeUserName := beego.AppConfig.String("writeusername")
70
+
71
+	readMiddleHost := beego.AppConfig.String("readmiddlehost")
72
+	readMiddlePort := beego.AppConfig.String("readmiddleport")
73
+	readMiddleUser := beego.AppConfig.String("readmiddleuser")
74
+	readMiddlePass := beego.AppConfig.String("readmiddlepass")
75
+	readMiddleName := beego.AppConfig.String("readmiddlename")
76
+
77
+	writeMiddleHost := beego.AppConfig.String("writemiddlehost")
78
+	writeMiddlePort := beego.AppConfig.String("writemiddleport")
79
+	writeMiddleUser := beego.AppConfig.String("writemiddleuser")
80
+	writeMiddlePass := beego.AppConfig.String("writemiddlepass")
81
+	writeMiddleName := beego.AppConfig.String("writemiddlename")
82
+
83
+	readPatientHost := beego.AppConfig.String("readpatienthost")
84
+	readPatientPort := beego.AppConfig.String("readpatientport")
85
+	readPatientUser := beego.AppConfig.String("readpatientuser")
86
+	readPatientPass := beego.AppConfig.String("readpatientpass")
87
+	readPatientName := beego.AppConfig.String("readpatientname")
88
+
89
+	writePatientHost := beego.AppConfig.String("writepatienthost")
90
+	writePatientPort := beego.AppConfig.String("writepatientport")
91
+	writePatientUser := beego.AppConfig.String("writepatientuser")
92
+	writePatientPass := beego.AppConfig.String("writepatientpass")
93
+	writePatientName := beego.AppConfig.String("writepatientname")
94
+
95
+	readSgjPatientHost := beego.AppConfig.String("readsgjpatientmysqlhost")
96
+	readSgjPatientPort := beego.AppConfig.String("readsgjpatientmysqlport")
97
+	readSgjPatientUser := beego.AppConfig.String("readsgjpatientmysqluser")
98
+	readSgjPatientPass := beego.AppConfig.String("readsgjpatientmysqlpass")
99
+	readSgjPatientName := beego.AppConfig.String("readsgjpatientmysqlname")
100
+
101
+	writeSgjPatientHost := beego.AppConfig.String("writesgjpatientmysqlhost")
102
+	writeSgjPatientPort := beego.AppConfig.String("writesgjpatientmysqlport")
103
+	writeSgjPatientUser := beego.AppConfig.String("writesgjpatientmysqluser")
104
+	writeSgjPatientPass := beego.AppConfig.String("writesgjpatientmysqlpass")
105
+	writeSgjPatientName := beego.AppConfig.String("writesgjpatientmysqlname")
106
+
107
+	readUserHostT := beego.AppConfig.String("readuserhostTest")
108
+	readUserPortT := beego.AppConfig.String("readuserportTest")
109
+	readUserUserT := beego.AppConfig.String("readuseruserTest")
110
+	readUserPassT := beego.AppConfig.String("readuserpassTest")
111
+	readUserNameT := beego.AppConfig.String("readusernameTest")
112
+
113
+	writeUserHostT := beego.AppConfig.String("writeuserhostTest")
114
+	writeUserPortT := beego.AppConfig.String("writeuserportTest")
115
+	writeUserUserT := beego.AppConfig.String("writeuseruserTest")
116
+	writeUserPassT := beego.AppConfig.String("writeuserpassTest")
117
+	writeUserNameT := beego.AppConfig.String("writeusernameTest")
118
+
119
+	rdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readUser, readPass, readHost, readPort, readName)
120
+	wdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writeUser, writePass, writeHost, writePort, writeName)
121
+
122
+	rudsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readUserUser, readUserPass, readUserHost, readUserPort, readUserName)
123
+	wudsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writeUserUser, writeUserPass, writeUserHost, writeUserPort, writeUserName)
124
+
125
+	rmdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readMiddleUser, readMiddlePass, readMiddleHost, readMiddlePort, readMiddleName)
126
+	wmdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writeMiddleUser, writeMiddlePass, writeMiddleHost, writeMiddlePort, writeMiddleName)
127
+
128
+	rpdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readPatientUser, readPatientPass, readPatientHost, readPatientPort, readPatientName)
129
+	wpdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writePatientUser, writePatientPass, writePatientHost, writePatientPort, writePatientName)
130
+
131
+	rspdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readSgjPatientUser, readSgjPatientPass, readSgjPatientHost, readSgjPatientPort, readSgjPatientName)
132
+	wspdsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writeSgjPatientUser, writeSgjPatientPass, writeSgjPatientHost, writeSgjPatientPort, writeSgjPatientName)
133
+
134
+	rudsnT := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", readUserUserT, readUserPassT, readUserHostT, readUserPortT, readUserNameT)
135
+	wudsnT := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", writeUserUserT, writeUserPassT, writeUserHostT, writeUserPortT, writeUserNameT)
136
+
137
+	readDb, err = gorm.Open("mysql", rdsn)
138
+	if err != nil {
139
+		//beego.Error(err)
140
+	}
141
+	readDb.DB().SetMaxIdleConns(10)
142
+	readDb.DB().SetMaxOpenConns(100)
143
+	readDb.LogMode(true)
144
+
145
+	writeDb, err = gorm.Open("mysql", wdsn)
146
+	if err != nil {
147
+		//beego.Error(err)
148
+	}
149
+	writeDb.DB().SetMaxIdleConns(10)
150
+	writeDb.DB().SetMaxOpenConns(100)
151
+	writeDb.LogMode(true)
152
+
153
+	readUserDbT, err = gorm.Open("mysql", rudsnT)
154
+	if err != nil {
155
+		//beego.Error(err)
156
+	}
157
+	readUserDbT.DB().SetMaxIdleConns(10)
158
+	readUserDbT.DB().SetMaxOpenConns(100)
159
+	readUserDbT.LogMode(true)
160
+
161
+	writeUserDbT, err = gorm.Open("mysql", wudsnT)
162
+	if err != nil {
163
+		//beego.Error(err)
164
+	}
165
+	writeUserDbT.DB().SetMaxIdleConns(10)
166
+	writeUserDbT.DB().SetMaxOpenConns(100)
167
+	writeUserDbT.LogMode(true)
168
+
169
+	readUserDb, err = gorm.Open("mysql", rudsn)
170
+	if err != nil {
171
+		//beego.Error(err)
172
+	}
173
+	readUserDb.DB().SetMaxIdleConns(10)
174
+	readUserDb.DB().SetMaxOpenConns(100)
175
+	readUserDb.LogMode(true)
176
+
177
+	writeUserDb, err = gorm.Open("mysql", wudsn)
178
+	if err != nil {
179
+		//beego.Error(err)
180
+	}
181
+	writeUserDb.DB().SetMaxIdleConns(10)
182
+	writeUserDb.DB().SetMaxOpenConns(100)
183
+	writeUserDb.LogMode(true)
184
+
185
+	readMiddleDb, err = gorm.Open("mysql", rmdsn)
186
+	if err != nil {
187
+		//beego.Error(err)
188
+	}
189
+	readMiddleDb.DB().SetMaxIdleConns(10)
190
+	readMiddleDb.DB().SetMaxOpenConns(100)
191
+	readMiddleDb.LogMode(true)
192
+
193
+	writeMiddleDb, err = gorm.Open("mysql", wmdsn)
194
+	if err != nil {
195
+		//beego.Error(err)
196
+	}
197
+	writeMiddleDb.DB().SetMaxIdleConns(10)
198
+	writeMiddleDb.DB().SetMaxOpenConns(100)
199
+	writeMiddleDb.LogMode(true)
200
+
201
+	readPatientDb, err = gorm.Open("mysql", rpdsn)
202
+	if err != nil {
203
+		beego.Error(err)
204
+	}
205
+	readPatientDb.DB().SetMaxIdleConns(10)
206
+	readPatientDb.DB().SetMaxOpenConns(100)
207
+	readPatientDb.LogMode(true)
208
+
209
+	writePatientDb, err = gorm.Open("mysql", wpdsn)
210
+	if err != nil {
211
+		beego.Error(err)
212
+	}
213
+	writePatientDb.DB().SetMaxIdleConns(10)
214
+	writePatientDb.DB().SetMaxOpenConns(100)
215
+	writePatientDb.LogMode(true)
216
+
217
+	readSgjPatientDb, err = gorm.Open("mysql", rspdsn)
218
+	if err != nil {
219
+		beego.Error(err)
220
+	}
221
+	readSgjPatientDb.DB().SetMaxIdleConns(10)
222
+	readSgjPatientDb.DB().SetMaxOpenConns(100)
223
+	readSgjPatientDb.LogMode(true)
224
+
225
+	writeSgjPatientDb, err = gorm.Open("mysql", wspdsn)
226
+	if err != nil {
227
+		beego.Error(err)
228
+	}
229
+	writeSgjPatientDb.DB().SetMaxIdleConns(10)
230
+	writeSgjPatientDb.DB().SetMaxOpenConns(100)
231
+	writeSgjPatientDb.LogMode(true)
232
+}
233
+
234
+//func DisconnectDB() {
235
+//	if err := readDb.Close(); nil != err {
236
+//		beego.Error("Disconnect from database failed: " + err.Error())
237
+//	}
238
+//}
239
+
240
+func XTReadDB() *gorm.DB {
241
+	return readDb
242
+}
243
+func XTWriteDB() *gorm.DB {
244
+	return writeDb
245
+}
246
+func UserReadDB() *gorm.DB {
247
+	return readUserDb
248
+}
249
+func UserWriteDB() *gorm.DB {
250
+	return writeUserDb
251
+}
252
+
253
+func MiddleReadDB() *gorm.DB {
254
+	return readMiddleDb
255
+}
256
+func MiddleWriteDB() *gorm.DB {
257
+	return writeMiddleDb
258
+}
259
+
260
+func PatientReadDB() *gorm.DB {
261
+	return readPatientDb
262
+}
263
+
264
+func PatientWriteDB() *gorm.DB {
265
+	return writePatientDb
266
+}
267
+
268
+func SgjPatientReadDB() *gorm.DB {
269
+	return readSgjPatientDb
270
+}
271
+
272
+func SgjPatientWriteDB() *gorm.DB {
273
+	return writeSgjPatientDb
274
+}

+ 27 - 0
service/db_err_service.go Bestand weergeven

@@ -0,0 +1,27 @@
1
+package service
2
+
3
+import (
4
+	"fmt"
5
+	"time"
6
+
7
+	"Xcx_New/models"
8
+	"Xcx_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
+}

+ 722 - 0
service/device_service.go Bestand weergeven

@@ -0,0 +1,722 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_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) order by sort ", 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, sort 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
+		Sort:       sort,
473
+	}
474
+	err := writeDb.Model(&models.DeviceNumber{}).Create(&numberModel).Error
475
+	if err != nil {
476
+		return nil, err
477
+	}
478
+	return &numberModel, nil
479
+}
480
+
481
+func GetDeviceNumberByName(num string, orgid int64) (number models.DeviceNumber, err error) {
482
+
483
+	err = XTReadDB().Model(&number).Where("number = ? and org_id = ? and status =1", num, orgid).First(&number).Error
484
+	return number, err
485
+}
486
+
487
+func UpdateDeviceNumber(number *models.DeviceNumber) error {
488
+	now := time.Now().Unix()
489
+	number.ModifyTime = now
490
+	tx := writeDb.Begin()
491
+	updateNumberErr := tx.Save(number).Error
492
+	if updateNumberErr != nil {
493
+		tx.Rollback()
494
+		return updateNumberErr
495
+	}
496
+	updateDeviceErr := tx.Model(&models.Device{}).Where("org_id = ? AND device_number_id = ?", number.OrgID, number.ID).Updates(map[string]interface{}{"device_number": number.Number, "sort": number.Sort}).Error
497
+	if updateDeviceErr != nil {
498
+		tx.Rollback()
499
+		return updateDeviceErr
500
+	}
501
+	tx.Commit()
502
+	return nil
503
+}
504
+
505
+func GetDeviceNumberCountForZoneID(orgID int64, zoneID int64) (int, error) {
506
+	var count int
507
+	err := readDb.Model(&models.DeviceNumber{}).Where("zone_id = ? AND org_id = ? AND status = 1", zoneID, orgID).Count(&count).Error
508
+	if err != nil {
509
+		return 0, err
510
+	}
511
+	return count, nil
512
+}
513
+
514
+func GetDeviceNumberCountForGroupID(orgID int64, groupID int64) (int, error) {
515
+	var count int
516
+	err := readDb.Model(&models.DeviceNumber{}).Where("group_id = ? AND org_id = ? AND status = 1", groupID, orgID).Count(&count).Error
517
+	if err != nil {
518
+		return 0, err
519
+	}
520
+	return count, nil
521
+}
522
+
523
+func GetScheduleCountForDeviceNumber(orgID int64, deviceNumberID int64, beginDate int64) (int, error) {
524
+	var count int
525
+	err := readDb.Model(&models.Schedule{}).Where("bed_id = ? AND user_org_id = ? AND schedule_date >= ? AND status = 1", deviceNumberID, orgID, beginDate).Count(&count).Error
526
+	if err != nil {
527
+		return 0, err
528
+	}
529
+	return count, nil
530
+}
531
+
532
+func GetScheduleTemplateItemCountForDeviceNumber(orgID int64, deviceNumberID int64) (int, error) {
533
+	var count int
534
+	err := readDb.Model(&models.PatientScheduleTemplateItem{}).Where("device_number_id = ? AND org_id = ? AND status = 1", deviceNumberID, orgID).Count(&count).Error
535
+	if err != nil {
536
+		return 0, err
537
+	}
538
+	return count, nil
539
+}
540
+
541
+func GetZoneId(bednumber int64, orgid int64) (models.DeviceNumber, error) {
542
+
543
+	number := models.DeviceNumber{}
544
+	err := XTReadDB().Model(&number).Where("id = ? AND org_id = ?", bednumber, orgid).Find(&number).Error
545
+	return number, err
546
+}
547
+
548
+//func AddMacher(deviceaddmacher *models.DeviceAddmacher) error{
549
+//	fmt.Println("进来了没哟")
550
+//	tx := writeDb.Begin()
551
+//	err := tx.Model(&models.DeviceAddmachers{}).Create(&deviceaddmacher).Error
552
+//	fmt.Println("错误是什么",err)
553
+//	if err !=nil{
554
+//		tx.Rollback()
555
+//	}
556
+//	tx.Commit()
557
+//	return err
558
+//}
559
+
560
+// func CreateMacher(machers *models.DeviceAddmacher) error {
561
+//      fmt.Println("进来了米有")
562
+// 	begin := writeDb.Begin()
563
+// 	fmt.Println("hhhhhhhh",begin)
564
+// 	err := begin.Model(&models.DeviceAddmacher{}).Create(machers).Error
565
+// 	fmt.Println("err",err)
566
+// 	if err !=nil{
567
+// 		begin.Rollback()
568
+// 	}
569
+// 	begin.Commit()
570
+// 	fmt.Println("执行了没有")
571
+// 	return err
572
+// }
573
+
574
+func GetLastMacherData(orgid int64) (models.DeviceAddmacher, error) {
575
+	addmacher := models.DeviceAddmacher{}
576
+	err := UserReadDB().Model(&addmacher).Where("user_org_id = ? AND status = ?", orgid, 1).Last(&addmacher).Error
577
+	return addmacher, err
578
+}
579
+
580
+func AddTreatMode(machineid int64, orgid int64, treatmodes []int64) (err error) {
581
+	utx := XTWriteDB().Begin()
582
+	if len(treatmodes) > 0 {
583
+		thisSQL := "INSERT INTO xt_device_treatmentmode(machine_id,treate_mode,status,ctime,user_org_id) VALUES "
584
+		insertParams := make([]string, 0)
585
+		insertData := make([]interface{}, 0)
586
+		for _, contagion := range treatmodes {
587
+			insertParams = append(insertParams, "(?, ?, ?, ?, ?)")
588
+			insertData = append(insertData, machineid)
589
+			insertData = append(insertData, contagion)
590
+			insertData = append(insertData, 1)
591
+			insertData = append(insertData, time.Now().Unix())
592
+			insertData = append(insertData, orgid)
593
+		}
594
+		thisSQL += strings.Join(insertParams, ",")
595
+		err = utx.Exec(thisSQL, insertData...).Error
596
+		if err != nil {
597
+			utx.Rollback()
598
+			return
599
+		}
600
+	}
601
+	utx.Commit()
602
+	return
603
+}
604
+
605
+//func DeleteBedNumber(id int64,orgid int64)(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
+//	err := writeDb.Model(&models.DeviceNumber{}).Where("id = ? AND org_id = ?", id, orgid).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
608
+//
609
+//
610
+//	fmt.Println("错误是什么",err)
611
+//	return  err
612
+//
613
+//}
614
+//
615
+//func DeleteZoneId(id int64,orgid int64)(error)  {
616
+//	err := writeDb.Model(&models.DeviceZone{}).Where("id = ? AND org_id = ?", id, orgid).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
617
+//	return  err
618
+//}
619
+
620
+func GetAllMachineInfo(page int64, limit int64, keyword string, zoneid int64, equimentid int64, statusid int64, orgid int64) (addmahcer []*models.DeviceAddmachers, total int64, err error) {
621
+
622
+	//db := readUserDb().Table("xt_device_addmacher as a").Where("a.status = 1")
623
+	db := readUserDb.Table("xt_device_addmacher as a").Where("a.status = 1")
624
+	table := XTReadDB().Table("xt_device_zone as x")
625
+	d := readUserDb.Table("xt_device_mode as m")
626
+	d2 := XTReadDB().Table("xt_device_number as n")
627
+	d3 := XTReadDB().Table("xt_device_information as i")
628
+	fmt.Print("d", d)
629
+	fmt.Println("table", table)
630
+	fmt.Print("d2", d2, d3)
631
+	if orgid > 0 {
632
+		db = db.Where("a.user_org_id = ?", orgid)
633
+	}
634
+	if zoneid > 0 {
635
+		db = db.Where("a.zone_id = ?", zoneid)
636
+	}
637
+	if equimentid > 0 {
638
+		db = db.Where("a.device_type = ?", equimentid)
639
+	}
640
+	if statusid > 0 {
641
+		db = db.Where("a.machine_status = ?", statusid)
642
+	}
643
+
644
+	if len(keyword) > 0 {
645
+		keyword = "%" + keyword + "%"
646
+		db = db.Where("a.serial_number LIKE ? OR a.device_name LIKE ? OR a.unit_type LIKE ?", keyword, keyword, keyword)
647
+	}
648
+
649
+	offset := (page - 1) * limit
650
+
651
+	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).
652
+		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
653
+
654
+	if err != nil {
655
+
656
+		return
657
+	}
658
+	return
659
+}
660
+
661
+func GetAllMachine(zoneid int64, classid int64, deviceid int64, timenow int64, orgid int64) (addmahcer []*models.DeviceAddmachers, err error) {
662
+	fmt.Println("timenow", timenow)
663
+	db := readUserDb.Table("xt_device_addmacher as a").Where("a.status = 1")
664
+	//db := XTReadDB().Table("xt_device_addmacher as a").Where("a.status = 1")
665
+	tab := XTReadDB().Table("xt_schedule as x")
666
+	fmt.Println("tab", tab)
667
+	d := readUserDb.Table("xt_device_mode as m")
668
+	fmt.Print("d", d)
669
+	table := XTReadDB().Table("xt_device_number as n")
670
+	fmt.Print("table", table)
671
+	if orgid > 0 {
672
+		db = db.Where("a.user_org_id = ?", orgid)
673
+	}
674
+	if zoneid > 0 {
675
+		db = db.Where("a.zone_id = ?", zoneid)
676
+	}
677
+
678
+	if deviceid > 0 {
679
+		db = db.Where("a.device_type = ?", deviceid)
680
+	}
681
+	if classid > 0 {
682
+		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
683
+		fmt.Println("err", error)
684
+	} else {
685
+		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
686
+		fmt.Println("错误是什么", err)
687
+		if err != nil {
688
+
689
+			return
690
+		}
691
+	}
692
+	return
693
+}
694
+
695
+func GetMachineDetail(id int64, orgid int64) (models.DeviceAddmachers, error) {
696
+	addmacher := models.DeviceAddmachers{}
697
+	//  //	//err := readUserDb.Model(&addmacher).Where("id = ? AND user_org_id = ? AND status = 1", id, orgid).Find(&addmacher).Error
698
+	db := readUserDb.Table("xt_device_addmacher as a").Where("a.status =1")
699
+	d := readUserDb.Table("xt_device_mode as d")
700
+	fmt.Print("d", d)
701
+	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
702
+	return addmacher, err
703
+}
704
+
705
+func GetTreatModel(id int64, orgid int64) (mode []*models.DeviceTreatmentmode, err error) {
706
+	err = XTReadDB().Model(&mode).Where("machine_id = ? AND user_org_id = ? AND status = 1 ", id, orgid).Find(&mode).Error
707
+
708
+	return mode, err
709
+}
710
+
711
+func GetPatientId(id int64) (models.XtPatientsNew, error) {
712
+
713
+	patientsNew := models.XtPatientsNew{}
714
+	err := XTReadDB().Model(&patientsNew).Where("blood_id = ? and status = 1", id).Find(&patientsNew).Error
715
+	return patientsNew, err
716
+}
717
+
718
+func GetPatientInfectious(id int64) (infectious []*models.InfectiousDiseases, err error) {
719
+
720
+	err = XTReadDB().Where("patient_id=? and status=1", id).Find(&infectious).Error
721
+	return infectious, err
722
+}

+ 454 - 0
service/dialysis_parameter_service.go Bestand weergeven

@@ -0,0 +1,454 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_New/models"
5
+	"fmt"
6
+	"github.com/jinzhu/gorm"
7
+)
8
+
9
+type VMDialysisSchedule struct {
10
+	ID           int64 `gorm:"column:id" json:"id" form:"id"`
11
+	UserOrgId    int64 `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
12
+	PartitionId  int64 `gorm:"column:partition_id" json:"partition_id" form:"partition_id"`
13
+	BedId        int64 `gorm:"column:bed_id" json:"bed_id" form:"bed_id"`
14
+	PatientId    int64 `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
15
+	ScheduleDate int64 `gorm:"column:schedule_date" json:"schedule_date" form:"schedule_date"`
16
+	ScheduleType int64 `gorm:"column:schedule_type" json:"schedule_type" form:"schedule_type"`
17
+	ScheduleWeek int64 `gorm:"column:schedule_week" json:"schedule_week" form:"schedule_week"`
18
+	ModeId       int64 `gorm:"column:mode_id" json:"mode_id" form:"mode_id"`
19
+	Status       int64 `gorm:"column:status" json:"status" form:"status"`
20
+	CreatedTime  int64 `gorm:"column:created_time" json:"created_time" form:"created_time"`
21
+	UpdatedTime  int64 `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
22
+
23
+	MonitorPatients models.MonitorPatients `gorm:"ForeignKey:PatientId" json:"patient"`
24
+	DeviceNumber    models.DeviceNumber    `gorm:"ForeignKey:BedId" json:"device_number"`
25
+	DeviceZone      models.DeviceZone      `gorm:"ForeignKey:PartitionId" json:"device_zone"`
26
+	TreatmentMode   models.TreatmentMode   `gorm:"ForeignKey:ModeId" json:"treatment_mode"`
27
+
28
+	DialysisOrder            models.MonitorDialysisOrder  `gorm:"ForeignKey:PatientId;AssociationForeignKey:PatientId" json:"dialysis_order"`
29
+	Prescription             models.DialysisPrescription  `gorm:"ForeignKey:PatientId;AssociationForeignKey:PatientId" json:"prescription"`
30
+	AssessmentBeforeDislysis models.PredialysisEvaluation `gorm:"ForeignKey:PatientId;AssociationForeignKey:PatientId" json:"assessment_before_dislysis"`
31
+	AssessmentAfterDislysis  AssessmentAfterDislysis      `gorm:"ForeignKey:PatientId;AssociationForeignKey:PatientId" json:"assessment_after_dislysis"`
32
+	MonitoringRecord         []models.MonitoringRecord    `gorm:"ForeignKey:PatientId;AssociationForeignKey:PatientId" json:"monitoring_record"`
33
+
34
+	//Patient         string          `gorm:"-" json:"patient" form:"patient"`
35
+	//SchedualPatient SchedualPatient `gorm:"ForeignKey:PatientId"`
36
+	//DeviceNumber    DeviceNumber    `gorm:"ForeignKey:BedId"`
37
+	//DeviceZone      DeviceZone      `gorm:"ForeignKey:PartitionId"`
38
+	//TreatmentMode   TreatmentMode   `gorm:"ForeignKey:ModeId"`
39
+}
40
+
41
+func (VMDialysisSchedule) TableName() string {
42
+	return "xt_schedule"
43
+}
44
+
45
+type MonitorDialysisSchedule struct {
46
+	ID           int64 `gorm:"column:id" json:"id"`
47
+	UserOrgId    int64 `gorm:"column:user_org_id" json:"user_org_id"`
48
+	PartitionId  int64 `gorm:"column:partition_id" json:"partition_id"`
49
+	BedId        int64 `gorm:"column:bed_id" json:"bed_id"`
50
+	PatientId    int64 `gorm:"column:patient_id" json:"patient_id"`
51
+	ScheduleDate int64 `gorm:"column:schedule_date" json:"schedule_date"`
52
+	ScheduleType int64 `gorm:"column:schedule_type" json:"schedule_type"`
53
+	ModeId       int64 `gorm:"column:mode_id" json:"mode_id"`
54
+	Status       int64 `gorm:"column:status" json:"status"`
55
+
56
+	MonitorPatients models.MonitorPatients `gorm:"ForeignKey:PatientId" json:"patient"`
57
+	DeviceNumber    models.DeviceNumber    `gorm:"ForeignKey:BedId" json:"device_number"`
58
+	DeviceZone      models.DeviceZone      `gorm:"ForeignKey:PartitionId" json:"device_zone"`
59
+	TreatmentMode   models.TreatmentMode   `gorm:"ForeignKey:ModeId" json:"treatment_mode"`
60
+
61
+	DialysisOrder            models.MonitorDialysisOrder    `gorm:"ForeignKey:PatientId;AssociationForeignKey:PatientId" json:"dialysis_order"`
62
+	Prescription             models.DialysisPrescription    `gorm:"ForeignKey:PatientId;AssociationForeignKey:PatientId" json:"prescription"`
63
+	AssessmentBeforeDislysis models.PredialysisEvaluation   `gorm:"ForeignKey:PatientId;AssociationForeignKey:PatientId" json:"assessment_before_dislysis"`
64
+	AssessmentAfterDislysis  models.AssessmentAfterDislysis `gorm:"ForeignKey:PatientId;AssociationForeignKey:PatientId" json:"assessment_after_dislysis"`
65
+	MonitoringRecord         []models.MonitoringRecord      `gorm:"ForeignKey:PatientId;AssociationForeignKey:PatientId" json:"monitoring_record"`
66
+}
67
+
68
+func (MonitorDialysisSchedule) TableName() string {
69
+	return "xt_schedule"
70
+}
71
+
72
+func GetDialysisParametersByKeyword(orgID int64, keyword string, schedulType int64, partitionType int64, page int64, limit int64, schedulDate int64) ([]*VMDialysisSchedule, error, int64) {
73
+	fmt.Println("scheduletye ======================", schedulType)
74
+	var patients []*models.Patients
75
+	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
76
+	if getPatientErr != nil {
77
+		return nil, getPatientErr, 0
78
+	}
79
+	patientIDs := make([]int64, len(patients))
80
+	for index, patient := range patients {
81
+		patientIDs[index] = patient.ID
82
+	}
83
+
84
+	db := readDb.
85
+		Model(&VMDialysisSchedule{}).
86
+		Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
87
+		// Preload("DeviceZone", "status = 1 AND org_id = ?", orgID).
88
+		Preload("TreatmentMode", "status = 1").
89
+		Preload("Prescription", "status = 1 AND user_org_id = ? AND record_date = ?", orgID, schedulDate).
90
+		Preload("AssessmentBeforeDislysis", "status = 1 AND  user_org_id = ? AND assessment_date = ?", orgID, schedulDate).
91
+		Preload("AssessmentAfterDislysis", "status = 1 AND  user_org_id = ? AND assessment_date = ?", orgID, schedulDate).
92
+		Preload("MonitoringRecord", "status = 1 AND  user_org_id = ? AND monitoring_date = ?", orgID, schedulDate).
93
+		Preload("DialysisOrder", "status = 1 AND user_org_id = ? AND dialysis_date = ?", orgID, schedulDate).
94
+		Preload("MonitorPatients", "status = 1 AND user_org_id = ?", orgID)
95
+	db = db.Where("xt_schedule.status = 1 AND patient_id in (?)", patientIDs)
96
+	if schedulType > 0 {
97
+		db = db.Where("schedule_type = ?", schedulType)
98
+	}
99
+	if partitionType > 0 {
100
+		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)
101
+	}
102
+	if schedulDate > 0 {
103
+		db = db.Where("schedule_date = ?", schedulDate)
104
+	}
105
+	var schedules []*VMDialysisSchedule
106
+	total := int64(0)
107
+	err := db.Count(&total).Offset(limit * (page - 1)).Limit(limit).Order("schedule_date desc").Find(&schedules).Error
108
+	return schedules, err, total
109
+}
110
+
111
+func GetDialysisParameter(orgID int64, schedulDate int64, schedulType int64, partitionType int64, page int64, limit int64) (schedule []*MonitorDialysisSchedule, err error, total int64) {
112
+	db := readDb.
113
+		Model(&MonitorDialysisSchedule{}).
114
+		Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
115
+		Preload("TreatmentMode", "status = 1").
116
+		Preload("Prescription", "status = 1 AND user_org_id = ? AND record_date = ?", orgID, schedulDate).
117
+		Preload("AssessmentBeforeDislysis", "status = 1 AND  user_org_id = ? AND assessment_date = ?", orgID, schedulDate).
118
+		Preload("AssessmentAfterDislysis", "status = 1 AND  user_org_id = ? AND assessment_date = ?", orgID, schedulDate).
119
+		Preload("MonitoringRecord", "status = 1 AND  user_org_id = ? AND monitoring_date = ?", orgID, schedulDate).
120
+		Preload("DialysisOrder", "status = 1 AND user_org_id = ? AND dialysis_date = ?", orgID, schedulDate).
121
+		Preload("MonitorPatients", "status = 1 AND user_org_id = ?", orgID)
122
+	db = db.Where("xt_schedule.status = 1 AND user_org_id = ?", orgID)
123
+	if schedulDate > 0 {
124
+		db = db.Where("schedule_date = ?", schedulDate)
125
+	}
126
+	if schedulType > 0 {
127
+		db = db.Where("schedule_type = ?", schedulType)
128
+	}
129
+	if partitionType > 0 {
130
+		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)
131
+	}
132
+	offset := (page - 1) * limit
133
+	err = db.Count(&total).Offset(offset).Limit(limit).Order("id desc").Find(&schedule).Error
134
+	return schedule, err, total
135
+}
136
+
137
+func GetDialysisBatchParameters(schIDs []string, orgID int64) (schedule []*models.DialysisParameter, err error) {
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 id in (?)", schIDs)
151
+	var schedules []*models.DialysisParameter
152
+	err = db.Order("schedule_date desc").Find(&schedules).Error
153
+	return schedules, err
154
+}
155
+
156
+func GetWareHouseOutList(startime int64, endtime int64, orgid int64) (warehouse []*models.XtWarehouseOutInfo, err error) {
157
+
158
+	db := XTReadDB().Table("xt_warehouse_out_info as x").Where("x.status = 1")
159
+	if startime > 0 {
160
+		db = db.Where("x.sys_record_time >=?", startime)
161
+	}
162
+	if endtime > 0 {
163
+		db = db.Where("x.sys_record_time<=?", endtime)
164
+	}
165
+	if orgid > 0 {
166
+		db = db.Where("x.org_id = ?", orgid)
167
+	}
168
+	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
169
+	return warehouse, err
170
+}
171
+
172
+func GetAllMaterial(startime int64, endtime int64, orgid int64) (reducedetail []*models.XtAutomaticReduceDetail, err error) {
173
+
174
+	db := XTReadDB().Table("xt_automatic_reduce_detail as x").Where("x.status = 1")
175
+	if startime > 0 {
176
+		db = db.Where("x.record_time>=?", startime)
177
+	}
178
+	if endtime > 0 {
179
+		db = db.Where("x.record_time<=?", endtime)
180
+	}
181
+	if orgid > 0 {
182
+		db = db.Where("x.org_id = ?", orgid)
183
+	}
184
+	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
185
+	return reducedetail, err
186
+}
187
+
188
+func GetCollectList(limit int64, page int64, partitionType int64, schedulType int64, schedulDate int64, orgID int64, keyword string) ([]*models.DialysisParameter, error, int64) {
189
+
190
+	var patients []*models.Patients
191
+	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
192
+	if getPatientErr != nil {
193
+		return nil, getPatientErr, 0
194
+	}
195
+	patientIDs := make([]int64, len(patients))
196
+	for index, patient := range patients {
197
+		patientIDs[index] = patient.ID
198
+	}
199
+
200
+	db := readDb.
201
+		Model(&models.DialysisSchedule{}).
202
+		Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
203
+		// Preload("DeviceZone", "status = 1 AND org_id = ?", orgID).
204
+		Preload("TreatmentMode", "status = 1").
205
+		Preload("Prescription", "status = 1 AND user_org_id = ?", orgID).
206
+		Preload("AssessmentBeforeDislysis", "status = 1 AND  user_org_id = ?", orgID).
207
+		Preload("AssessmentAfterDislysis", "status = 1 AND  user_org_id = ?", orgID).
208
+		Preload("MonitoringRecord", "status = 1 AND  user_org_id = ?", orgID).
209
+		Preload("DialysisOrder", "status = 1 AND user_org_id = ?", orgID).
210
+		Preload("MonitorPatients", "status = 1 AND user_org_id = ?", orgID)
211
+	db = db.Where("xt_schedule.status = 1 AND patient_id in (?)", patientIDs)
212
+	if schedulType > 0 {
213
+		db = db.Where("schedule_type = ?", schedulType)
214
+	}
215
+	if partitionType > 0 {
216
+		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)
217
+		// db = db.Where("partition_id = ?", partitionType)
218
+	}
219
+	if schedulDate > 0 {
220
+		db = db.Where("schedule_date = ?", schedulDate)
221
+	}
222
+	var schedules []*models.DialysisParameter
223
+	total := int64(0)
224
+	err := db.Count(&total).Offset(limit * (page - 1)).Limit(limit).Order("schedule_date desc").Find(&schedules).Error
225
+	return schedules, err, total
226
+}
227
+
228
+func GetDialysisConsumables(startime int64, endtime int64, orgid int64) (reducedetail []*models.XtAutomaticReduceDetail, err error) {
229
+
230
+	db := XTReadDB().Table("xt_automatic_reduce_detail as x").Where("x.status = 1")
231
+	table := XTReadDB().Table("xt_warehouse_out_info as f").Where("f.status = 1 and f.org_id = ?", orgid)
232
+	fmt.Println(table)
233
+	if startime > 0 {
234
+		db = db.Where("x.record_time >=?", startime)
235
+	}
236
+	if endtime > 0 {
237
+		db = db.Where("x.record_time <=?", endtime)
238
+	}
239
+	if orgid > 0 {
240
+		db = db.Where("x.org_id =?", orgid)
241
+	}
242
+	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
243
+	return reducedetail, err
244
+}
245
+
246
+func GetBatchCollection(orgID int64, schIDs []string) (schedules []*models.DialysisParameter, err error) {
247
+
248
+	db := readDb.
249
+		Model(&models.DialysisSchedule{}).
250
+		Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
251
+		// Preload("DeviceZone", "status = 1 AND org_id = ?", orgID).
252
+		Preload("TreatmentMode", "status = 1").
253
+		Preload("Prescription", "status = 1 AND user_org_id = ?", orgID).
254
+		Preload("AssessmentBeforeDislysis", "status = 1 AND  user_org_id = ?", orgID).
255
+		Preload("AssessmentAfterDislysis", "status = 1 AND  user_org_id = ?", orgID).
256
+		Preload("MonitoringRecord", "status = 1 AND  user_org_id = ?", orgID).
257
+		Preload("DialysisOrder", "status = 1 AND user_org_id = ?", orgID).
258
+		Preload("MonitorPatients", "status = 1 AND user_org_id = ?", orgID)
259
+	db = db.Where("xt_schedule.status = 1 AND id in (?)", schIDs)
260
+	err = db.Order("schedule_date desc").Find(&schedules).Error
261
+	return schedules, err
262
+}
263
+
264
+func GetAnticoagulantCount(startime int64, endtime int64, orgid int64) (prescriptionCount []*models.DialysisPrescriptionCount, err error) {
265
+
266
+	db := XTReadDB().Table("xt_dialysis_prescription as x").Where("x.status = 1")
267
+	if orgid > 0 {
268
+		db = db.Where("x.user_org_id = ? and x.anticoagulant <> 0", orgid)
269
+	}
270
+	if startime > 0 {
271
+		db = db.Where("x.record_date >= ?", startime)
272
+	}
273
+	if endtime > 0 {
274
+		db = db.Where("x.record_date<=?", endtime)
275
+	}
276
+
277
+	err = db.Select("x.patient_id,x.anticoagulant,x.record_date,count(id) as count").Group("x.anticoagulant").Scan(&prescriptionCount).Error
278
+	return prescriptionCount, err
279
+}
280
+
281
+func GetDialysisTodaySchedulePatient(orgid int64, startime int64, page int64, limit int64, keywords string, schedulType int64, partiontype int64) (schedule []*models.XtScheduleTwo, err error) {
282
+	//offset := (page - 1) * limit
283
+	//err = XTReadDB().Model(&schedule).Where("user_org_id = ? and schedule_date = ? and status = 1", orgid, startime).Offset(offset).Limit(limit).Order("id desc").Find(&schedule).Error
284
+	//return schedule, err
285
+	keywords = "%" + keywords + "%"
286
+
287
+	offset := (page - 1) * limit
288
+	db := XTReadDB().Table("xt_schedule as x").Where("x.status = 1")
289
+	if schedulType > 0 {
290
+		db = db.Where("x.schedule_type = ?", schedulType)
291
+	}
292
+	if partiontype > 0 {
293
+		db = db.Where("x.partition_id = ?", partiontype)
294
+	}
295
+
296
+	table := XTReadDB().Table("xt_patients as s")
297
+	fmt.Println(table)
298
+	if len(keywords) > 0 {
299
+		err = db.Group("x.id").Select("x.id,x.patient_id,x.mode_id,s.name").Joins("left join xt_patients as s on s.id = x.patient_id").Where("x.user_org_id = ? and x.schedule_date = ? and x.status = 1 and s.name like ?", orgid, startime, keywords).Offset(offset).Limit(limit).Order("id desc").Scan(&schedule).Error
300
+		//db = db.Where("s.name like ?", keywords)
301
+	} else {
302
+		err = db.Group("x.id").Select("x.id,x.patient_id,x.mode_id,s.name").Joins("left join xt_patients as s on s.id = x.patient_id").Where("x.user_org_id = ? and x.schedule_date = ? and x.status = 1", orgid, startime).Offset(offset).Limit(limit).Order("id desc").Scan(&schedule).Error
303
+
304
+	}
305
+	return schedule, err
306
+}
307
+
308
+func GetToDayDialysisPrescription(patientid int64, orgid int64, startime int64) (*models.XtDialysisPrescription, error) {
309
+	prescription := models.XtDialysisPrescription{}
310
+	err := XTReadDB().Model(&prescription).Where("patient_id = ? and user_org_id = ? and record_date = ? and status = 1", patientid, orgid, startime).Find(&prescription).Error
311
+	if err == gorm.ErrRecordNotFound {
312
+		return nil, err
313
+	}
314
+	if err != nil {
315
+		return nil, err
316
+	}
317
+	return &prescription, nil
318
+
319
+}
320
+
321
+func GetLastDialysisPrescription(patientid int64, orgid int64) (models.XtDialysisPrescription, error) {
322
+
323
+	prescription := models.XtDialysisPrescription{}
324
+	err = XTReadDB().Model(&prescription).Where("patient_id = ? and user_org_id = ? and status = 1", patientid, orgid).Last(&prescription).Error
325
+	return prescription, err
326
+}
327
+
328
+func GetLastAssessmentBeforDialysis(patientid int64, orgid int64) (models.PredialysisEvaluation, error) {
329
+
330
+	evaluation := models.PredialysisEvaluation{}
331
+	err := XTReadDB().Model(&evaluation).Where("patient_id = ? and user_org_id = ? and status = 1", patientid, orgid).Last(&evaluation).Error
332
+	return evaluation, err
333
+}
334
+
335
+func GetDialysisPrescriptionList(patientid int64, orgid int64, startime int64) (models.DialysisPrescriptionParameter, error) {
336
+	prescription := models.DialysisPrescriptionParameter{}
337
+	err := XTReadDB().Model(&prescription).Where("patient_id = ? and user_org_id = ? and status = 1 and record_date = ?", patientid, orgid, startime).Find(&prescription).Error
338
+	return prescription, err
339
+}
340
+
341
+func GetTodayAssessmentBeforDialysis(patientid int64, orgid int64, startime int64) (*models.PredialysisEvaluationParameter, error) {
342
+
343
+	evaluation := models.PredialysisEvaluationParameter{}
344
+	err := XTReadDB().Model(&evaluation).Where("patient_id = ? and user_org_id = ? and assessment_date = ? and status = 1", patientid, orgid, startime).Find(&evaluation).Error
345
+	if err == gorm.ErrRecordNotFound {
346
+		return nil, err
347
+	}
348
+	if err != nil {
349
+		return nil, err
350
+	}
351
+	return &evaluation, nil
352
+}
353
+
354
+func GetAssessmentBeforDialysisByStartime(patientid int64, orgid int64, startime int64) (models.PredialysisEvaluation, error) {
355
+	evaluation := models.PredialysisEvaluation{}
356
+	err := XTReadDB().Model(&evaluation).Where("patient_id = ? and user_org_id = ? and assessment_date = ? and status = 1", patientid, orgid, startime).Find(&evaluation).Error
357
+	return evaluation, err
358
+}
359
+
360
+func GetAotoMaticReduceByPatientId(patientid int64, orgid int64, startime int64, endtime int64) (*models.BloodAutomaticReduceDetail, error) {
361
+
362
+	detail := models.BloodAutomaticReduceDetail{}
363
+	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
364
+	if err == gorm.ErrRecordNotFound {
365
+		return nil, err
366
+	}
367
+	if err != nil {
368
+		return nil, err
369
+	}
370
+	return &detail, nil
371
+}
372
+
373
+func GetMaticReduece(patientid int64, orgid int64) (models.BloodAutomaticReduceDetail, error) {
374
+
375
+	detail := models.BloodAutomaticReduceDetail{}
376
+	err := XTReadDB().Model(&detail).Where("patient_id = ? and org_id= ?  and status = 1", patientid, orgid).Last(&detail).Error
377
+
378
+	return detail, err
379
+}
380
+
381
+func GetMaticeReduceByPatientId(patientid int64, orgid int64, startime int64, endtime int64) (models.BloodAutomaticReduceDetail, error) {
382
+
383
+	detail := models.BloodAutomaticReduceDetail{}
384
+	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
385
+	return detail, err
386
+}
387
+
388
+func PCGetDialysisGoodsTwo(orgID int64, scheduleDate int64, schedule_type int64, partition_id int64, page int64, limit int64, keywords string) ([]*MDialysisGoodsVM, error, int64) {
389
+	var vms []*MDialysisGoodsVM
390
+	var total int64
391
+
392
+	db := readDb.
393
+		Model(&models.Schedule{}).Select("patient_id,mode_id").
394
+		Preload("SchedualPatient", "status = 1 AND user_org_id = ?", orgID).
395
+		Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
396
+		Preload("DeviceNumber.Zone", "status = 1 AND org_id = ?", orgID).
397
+		Preload("DialysisBeforePrepare", func(db *gorm.DB) *gorm.DB {
398
+			return db.Preload("VMGoodInfo", "status = 1 AND org_id = ?", orgID).Preload("GoodsType", "status = 1 AND (org_id = ? OR org_id = 0) ", orgID).Where("status = 1 AND user_org_id = ? AND record_date = ? AND count > 0 ", orgID, scheduleDate)
399
+		}).
400
+		Preload("AutomaticReduceDetail", func(db *gorm.DB) *gorm.DB {
401
+			return db.Preload("VMGoodInfo", "status = 1 AND org_id = ? ", orgID).Preload("GoodsType", "status = 1 AND (org_id = ? OR org_id = 0)  ", orgID).Where("status = 1 AND org_id = ? AND record_time = ?  AND count > 0", orgID, scheduleDate)
402
+		}).Where("xt_schedule.status = 1 AND xt_schedule.user_org_id = ?", orgID)
403
+
404
+	if scheduleDate != 0 {
405
+		db = db.Where("schedule_date = ?", scheduleDate)
406
+	}
407
+	if len(keywords) != 0 {
408
+		keywords = "%" + keywords + "%"
409
+		db = db.Joins("JOIN xt_patients AS patient ON patient.id=xt_schedule.patient_id AND patient.status = 1 AND patient.user_org_id = ? AND patient.name Like ?", orgID, keywords)
410
+	} else {
411
+		if schedule_type != 0 {
412
+			db = db.Where("schedule_type = ?", schedule_type)
413
+		}
414
+		if partition_id != 0 {
415
+			db = db.Where("partition_id = ?", partition_id)
416
+		}
417
+
418
+		db = db.Count(&total)
419
+		offset := (page - 1) * limit
420
+
421
+		db = db.Offset(offset).Limit(limit)
422
+
423
+	}
424
+
425
+	err := db.Find(&vms).Error
426
+
427
+	return vms, err, total
428
+}
429
+
430
+func PCGetDialysisGoodsThree(orgID int64, scheduleDate int64) ([]*MDialysisGoodsVM, error) {
431
+
432
+	var vms []*MDialysisGoodsVM
433
+
434
+	db := readDb.
435
+		Model(&models.Schedule{}).
436
+		Select("patient_id,mode_id").
437
+		Preload("SchedualPatient", "status = 1 AND user_org_id = ?", orgID).
438
+		Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
439
+		Preload("DeviceNumber.Zone", "status = 1 AND org_id = ?", orgID).
440
+		Preload("DialysisBeforePrepare", func(db *gorm.DB) *gorm.DB {
441
+			return db.Preload("VMGoodInfo", "status = 1 AND org_id = ?   ", orgID).Preload("GoodsType", "status = 1 AND (org_id = ? OR org_id = 0) ", orgID).Where("status = 1 AND user_org_id = ? AND record_date = ? AND count > 0 ", orgID, scheduleDate)
442
+		}).
443
+		Preload("AutomaticReduceDetail", func(db *gorm.DB) *gorm.DB {
444
+			return db.Preload("VMGoodInfo", "status = 1 AND org_id = ? ", orgID).Preload("GoodsType", "status = 1 AND (org_id = ? OR org_id = 0)  ", orgID).Where("status = 1 AND org_id = ? AND record_time = ?  AND count > 0", orgID, scheduleDate)
445
+		}).Where("xt_schedule.status = 1 AND xt_schedule.user_org_id = ?", orgID)
446
+
447
+	if scheduleDate != 0 {
448
+		db = db.Where("schedule_date = ?", scheduleDate)
449
+	}
450
+
451
+	err = db.Find(&vms).Error
452
+
453
+	return vms, err
454
+}

Diff onderdrukt omdat het te groot bestand
+ 1235 - 0
service/dialysis_service.go


+ 84 - 0
service/district_service.go Bestand weergeven

@@ -0,0 +1,84 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_New/models"
5
+	"Xcx_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
+}

+ 482 - 0
service/doctor_advice_service.go Bestand weergeven

@@ -0,0 +1,482 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_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 CreateHisAdviceTemplate(d *models.HisDoctorAdviceTemplate) (err error) {
121
+	err = readDb.Create(&d).Error
122
+	return
123
+}
124
+
125
+func FindAdviceTemplate(orgid, id int64) (*models.DoctorAdviceTemplate, error) {
126
+	var template models.DoctorAdviceTemplate
127
+	err := readDb.Model(&models.DoctorAdviceTemplate{}).Where("id=? and org_id =? and status=1", id, orgid).First(&template).Error
128
+	if err == gorm.ErrRecordNotFound {
129
+		return nil, nil
130
+	}
131
+
132
+	if err != nil {
133
+		return nil, err
134
+	}
135
+	return &template, nil
136
+}
137
+
138
+func FindHisAdviceTemplate(orgid, id int64) (*models.HisDoctorAdviceTemplate, error) {
139
+	var template models.HisDoctorAdviceTemplate
140
+	err := readDb.Model(&models.HisDoctorAdviceTemplate{}).Where("id=? and org_id =? and status=1", id, orgid).First(&template).Error
141
+	if err == gorm.ErrRecordNotFound {
142
+		return nil, nil
143
+	}
144
+
145
+	if err != nil {
146
+		return nil, err
147
+	}
148
+	return &template, nil
149
+}
150
+
151
+func UpdateAdviceTemplate(d *models.DoctorAdviceTemplate) (err error) {
152
+	err = writeDb.Save(&d).Error
153
+	return
154
+}
155
+
156
+func UpdateHisAdviceTemplate(d *models.HisDoctorAdviceTemplate) (err error) {
157
+	err = writeDb.Save(&d).Error
158
+	return
159
+}
160
+
161
+func UpdateAdviceAndSubAdviceTemplate(d *models.DoctorAdviceTemplate) (err error) {
162
+	err = writeDb.Save(&d).Error
163
+	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
164
+	return
165
+}
166
+
167
+func UpdateHisAdviceAndSubAdviceTemplate(d *models.HisDoctorAdviceTemplate) (err error) {
168
+	err = writeDb.Save(&d).Error
169
+	err = writeDb.Model(&models.HisDoctorAdviceTemplate{}).Where("status=1 AND parent_id = ?", d.ID).Updates(map[string]interface{}{"status": 2, "updated_time": time.Now().Unix()}).Error
170
+	return
171
+}
172
+
173
+func CreateTemplate(template *models.DoctorAdviceParentTemplate) (err error) {
174
+	err = readDb.Create(&template).Error
175
+	return
176
+}
177
+
178
+func CreateHisDoctorAdviceTemplate(template *models.HisDoctorAdviceParentTemplate) (err error) {
179
+	err = readDb.Create(&template).Error
180
+	return
181
+}
182
+
183
+func CreateHisSubDoctorAdviceTemplate(template []*models.HisDoctorAdviceTemplate) (err error) {
184
+	if len(template) > 0 {
185
+		utx := writeDb.Begin()
186
+		if len(template) > 0 {
187
+			thisSQL := "INSERT INTO his_doctor_advice_template (org_id, advice_name, advice_desc, single_dose, single_dose_unit,prescribing_number," +
188
+				"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,drug_id,way) VALUES "
189
+			insertParams := make([]string, 0)
190
+			insertData := make([]interface{}, 0)
191
+			for _, info := range template {
192
+				insertParams = append(insertParams, "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
193
+				insertData = append(insertData, info.OrgId)
194
+				insertData = append(insertData, info.AdviceName)
195
+				insertData = append(insertData, info.AdviceDesc)
196
+				insertData = append(insertData, info.SingleDose)
197
+				insertData = append(insertData, info.SingleDoseUnit)
198
+				insertData = append(insertData, info.PrescribingNumber)
199
+				insertData = append(insertData, info.PrescribingNumberUnit)
200
+				insertData = append(insertData, info.DeliveryWay)
201
+				insertData = append(insertData, info.ExecutionFrequency)
202
+				insertData = append(insertData, info.AdviceDoctor)
203
+				insertData = append(insertData, info.Status)
204
+				insertData = append(insertData, info.CreatedTime)
205
+				insertData = append(insertData, info.UpdatedTime)
206
+				insertData = append(insertData, info.TemplateId)
207
+				insertData = append(insertData, info.DrugSpec)
208
+				insertData = append(insertData, info.DrugSpecUnit)
209
+				insertData = append(insertData, info.AdviceType)
210
+				insertData = append(insertData, info.DayCount)
211
+				insertData = append(insertData, info.WeekDays)
212
+				insertData = append(insertData, info.FrequencyType)
213
+				insertData = append(insertData, info.DrugId)
214
+				insertData = append(insertData, info.Way)
215
+			}
216
+			thisSQL += strings.Join(insertParams, ", ")
217
+			err = utx.Exec(thisSQL, insertData...).Error
218
+			if err != nil {
219
+				utx.Rollback()
220
+				return
221
+			}
222
+		}
223
+		utx.Commit()
224
+	}
225
+	return
226
+
227
+}
228
+
229
+//func CreateBatchRecord(template []*models.DoctorAdviceTemplate) (err error) {
230
+//	err = writeDb.Create(template).Error
231
+//	return
232
+//}
233
+
234
+func CreateSubTemplate(template []*models.DoctorAdviceTemplate) (err error) {
235
+	if len(template) > 0 {
236
+		utx := writeDb.Begin()
237
+		if len(template) > 0 {
238
+			thisSQL := "INSERT INTO xt_doctor_advice_template (org_id, advice_name, advice_desc, single_dose, single_dose_unit,prescribing_number," +
239
+				"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,drug_id,way) VALUES "
240
+			insertParams := make([]string, 0)
241
+			insertData := make([]interface{}, 0)
242
+			for _, info := range template {
243
+				insertParams = append(insertParams, "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
244
+				insertData = append(insertData, info.OrgId)
245
+				insertData = append(insertData, info.AdviceName)
246
+				insertData = append(insertData, info.AdviceDesc)
247
+				insertData = append(insertData, info.SingleDose)
248
+				insertData = append(insertData, info.SingleDoseUnit)
249
+				insertData = append(insertData, info.PrescribingNumber)
250
+				insertData = append(insertData, info.PrescribingNumberUnit)
251
+				insertData = append(insertData, info.DeliveryWay)
252
+				insertData = append(insertData, info.ExecutionFrequency)
253
+				insertData = append(insertData, info.AdviceDoctor)
254
+				insertData = append(insertData, info.Status)
255
+				insertData = append(insertData, info.CreatedTime)
256
+				insertData = append(insertData, info.UpdatedTime)
257
+				insertData = append(insertData, info.TemplateId)
258
+				insertData = append(insertData, info.DrugSpec)
259
+				insertData = append(insertData, info.DrugSpecUnit)
260
+				insertData = append(insertData, info.AdviceType)
261
+				insertData = append(insertData, info.DayCount)
262
+				insertData = append(insertData, info.WeekDays)
263
+				insertData = append(insertData, info.FrequencyType)
264
+				insertData = append(insertData, info.DrugId)
265
+				insertData = append(insertData, info.Way)
266
+			}
267
+			thisSQL += strings.Join(insertParams, ", ")
268
+			err = utx.Exec(thisSQL, insertData...).Error
269
+			if err != nil {
270
+				utx.Rollback()
271
+				return
272
+			}
273
+		}
274
+		utx.Commit()
275
+	}
276
+	return
277
+
278
+}
279
+
280
+func FindDoctorAdviceTemplateById(id int64, org_id int64) (temps models.DoctorAdviceParentTemplate, err error) {
281
+	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
282
+	return
283
+}
284
+
285
+func FindHisDoctorAdviceTemplateById(id int64, org_id int64) (temps models.HisDoctorAdviceParentTemplate, err error) {
286
+	err = readDb.Model(&models.HisDoctorAdviceParentTemplate{}).Preload("HisDoctorAdviceTemplate", "status = 1").Where("org_id = ? AND status=1 AND id = ?", org_id, id).Order("id desc").First(&temps).Error
287
+	return
288
+}
289
+
290
+func FindAllAdviceTemplate(org_id int64, advice_type int64) (temps []*models.DoctorAdviceParentTemplate, err error) {
291
+	err = readDb.Model(&models.DoctorAdviceParentTemplate{}).Preload("DoctorAdviceTemplate", func(db *gorm.DB) *gorm.DB {
292
+		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,way,drug_id,drug_name_id, IF(parent_id>0, parent_id, id) as advice_order").Where("status = 1").Order("advice_order desc, id")
293
+	}).Where("org_id = ? AND status=1 AND advice_type = ?", org_id, advice_type).Find(&temps).Error
294
+	return
295
+}
296
+
297
+func GetAllAdviceSubTemplates(orgid int64, template_id int64) (total int64, err error) {
298
+	err = readDb.Model(&models.DoctorAdviceTemplate{}).Where("org_id =? AND status=1 AND template_id = ?", orgid, template_id).Count(&total).Error
299
+	return
300
+}
301
+
302
+func UpdateParentAdviceTemplates(orgid int64, tempelate_id int64) (err error) {
303
+	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
304
+	return
305
+}
306
+
307
+func FindTemplateRecordByName(orgid int64, name string) (total int64) {
308
+	readDb.Model(&models.DoctorAdviceParentTemplate{}).Where("name = ? AND org_id = ? AND status= 1 ", name, orgid).Count(&total)
309
+	return
310
+}
311
+
312
+func FindParentTemplateRecordById(orgid int64, template_id int64) (parentTemplate models.DoctorAdviceParentTemplate, err error) {
313
+	err = readDb.Model(&models.DoctorAdviceParentTemplate{}).Where("id = ? AND org_id = ? AND status= 1 ", template_id, orgid).First(&parentTemplate).Error
314
+	return
315
+}
316
+
317
+func FindParentHisTemplateRecordById(orgid int64, template_id int64) (parentTemplate models.HisDoctorAdviceParentTemplate, err error) {
318
+	err = readDb.Model(&models.HisDoctorAdviceParentTemplate{}).Where("id = ? AND org_id = ? AND status= 1 ", template_id, orgid).First(&parentTemplate).Error
319
+	return
320
+}
321
+
322
+func DeleteParentDoctorAdviceByTemplateId(template_id int64, org_id int64) (err error) {
323
+
324
+	ut := writeDb.Begin()
325
+	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
326
+
327
+	if err != nil {
328
+		ut.Rollback()
329
+		return
330
+	}
331
+	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
332
+	if err != nil {
333
+		ut.Rollback()
334
+		return
335
+	}
336
+	ut.Commit()
337
+	return err
338
+}
339
+
340
+func DeleteHisParentDoctorAdviceByTemplateId(template_id int64, org_id int64) (err error) {
341
+
342
+	ut := writeDb.Begin()
343
+	err = writeDb.Model(&models.HisDoctorAdviceParentTemplate{}).Where("status=1 AND id = ? AND org_id = ?", template_id, org_id).Updates(map[string]interface{}{"status": "0", "updated_time": time.Now().Unix()}).Error
344
+
345
+	if err != nil {
346
+		ut.Rollback()
347
+		return
348
+	}
349
+	err = writeDb.Model(&models.HisDoctorAdviceTemplate{}).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
350
+	if err != nil {
351
+		ut.Rollback()
352
+		return
353
+	}
354
+	ut.Commit()
355
+	return err
356
+}
357
+
358
+func ModifyTemplateName(id int64, template_name string) (err error) {
359
+	err = writeDb.Model(&models.DoctorAdviceParentTemplate{}).Where("status=1 AND id = ?", id).Updates(map[string]interface{}{"name": template_name, "updated_time": time.Now().Unix()}).Error
360
+	return err
361
+}
362
+
363
+func ModifyTemplateNameOne(id int64, template_name string, sort int64) (err error) {
364
+	err = writeDb.Model(&models.DoctorAdviceParentTemplate{}).Where("status=1 AND id = ?", id).Updates(map[string]interface{}{"name": template_name, "updated_time": time.Now().Unix(), "sort": sort}).Error
365
+	return err
366
+}
367
+
368
+func ModifyHisTemplateName(id int64, template_name string) (err error) {
369
+	err = writeDb.Model(&models.HisDoctorAdviceParentTemplate{}).Where("status=1 AND id = ?", id).Updates(map[string]interface{}{"name": template_name, "updated_time": time.Now().Unix()}).Error
370
+	return err
371
+}
372
+
373
+func FindOtherAllAdviceTemplate(org_id int64) (temps []*models.DoctorAdviceParentTemplate, err error) {
374
+	err = readDb.Model(&models.DoctorAdviceParentTemplate{}).Preload("DoctorAdviceTemplate", func(db *gorm.DB) *gorm.DB {
375
+		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,drug_id,way, IF(parent_id>0, parent_id, id) as advice_order").Where("status = 1").Order("advice_order desc, id")
376
+	}).Where("org_id = ? AND status=1 ", org_id).Find(&temps).Error
377
+	return
378
+	//.Scan(&advices).Error
379
+
380
+}
381
+
382
+func FindHisAllAdviceTemplate(org_id int64) (temps []*models.HisDoctorAdviceParentTemplate, err error) {
383
+	err = readDb.Model(&models.HisDoctorAdviceParentTemplate{}).Preload("HisDoctorAdviceTemplate", func(db *gorm.DB) *gorm.DB {
384
+		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,drug_id,way, IF(parent_id>0, parent_id, id) as advice_order").Where("status = 1").Order("advice_order desc, id")
385
+	}).Where("org_id = ? AND status=1 ", org_id).Find(&temps).Error
386
+	return
387
+	//.Scan(&advices).Error
388
+
389
+}
390
+
391
+func GetHandleData(id int64) (models.ConfigViewModel, error) {
392
+	config := models.ConfigViewModel{}
393
+	err := readDb.Model(&config).Where("id=?", id).Find(&config).Error
394
+	return config, err
395
+}
396
+
397
+func UpdateDataTwo(id int64, model models.ConfigViewModel) error {
398
+
399
+	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
400
+	return err
401
+}
402
+
403
+type AdviceDate struct {
404
+	RecordDate int64
405
+}
406
+
407
+type DoctorAdvice struct {
408
+	ID                    int64           `gorm:"column:id" json:"id" form:"id"`
409
+	GroupNo               int64           `gorm:"column:groupno" json:"groupno" form:"groupno"`
410
+	UserOrgId             int64           `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
411
+	PatientId             int64           `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
412
+	AdviceType            int64           `gorm:"column:advice_type" json:"advice_type" form:"advice_type"`
413
+	AdviceDate            int64           `gorm:"column:advice_date" json:"advice_date" form:"advice_date"`
414
+	StartTime             int64           `gorm:"column:start_time" json:"start_time" form:"start_time"`
415
+	AdviceName            string          `gorm:"column:advice_name" json:"advice_name" form:"advice_name"`
416
+	AdviceDesc            string          `gorm:"column:advice_desc" json:"advice_desc" form:"advice_desc"`
417
+	ReminderDate          int64           `gorm:"column:reminder_date" json:"reminder_date" form:"reminder_date"`
418
+	SingleDose            float64         `gorm:"column:single_dose" json:"single_dose" form:"single_dose"`
419
+	SingleDoseUnit        string          `gorm:"column:single_dose_unit" json:"single_dose_unit" form:"single_dose_unit"`
420
+	DrugSpec              float64         `gorm:"column:drug_spec" json:"drug_spec" form:"drug_spec"`
421
+	DrugSpecUnit          string          `gorm:"column:drug_spec_unit" json:"drug_spec_unit" form:"drug_spec_unit"`
422
+	PrescribingNumber     float64         `gorm:"column:prescribing_number" json:"prescribing_number" form:"prescribing_number"`
423
+	PrescribingNumberUnit string          `gorm:"column:prescribing_number_unit" json:"prescribing_number_unit" form:"prescribing_number_unit"`
424
+	DeliveryWay           string          `gorm:"column:delivery_way" json:"delivery_way" form:"delivery_way"`
425
+	ExecutionFrequency    string          `gorm:"column:execution_frequency" json:"execution_frequency" form:"execution_frequency"`
426
+	AdviceDoctor          int64           `gorm:"column:advice_doctor" json:"advice_doctor" form:"advice_doctor"`
427
+	Status                int64           `gorm:"column:status" json:"status" form:"status"`
428
+	CreatedTime           int64           `gorm:"column:created_time" json:"created_time" form:"created_time"`
429
+	UpdatedTime           int64           `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
430
+	AdviceAffirm          string          `gorm:"column:advice_affirm" json:"advice_affirm" form:"advice_affirm"`
431
+	Remark                string          `gorm:"column:remark" json:"remark" form:"remark"`
432
+	StopTime              int64           `gorm:"column:stop_time" json:"stop_time" form:"stop_time"`
433
+	StopReason            string          `gorm:"column:stop_reason" json:"stop_reason" form:"stop_reason"`
434
+	StopDoctor            int64           `gorm:"column:stop_doctor" json:"stop_doctor" form:"stop_doctor"`
435
+	StopState             int64           `gorm:"column:stop_state" json:"stop_state" form:"stop_state"`
436
+	ParentId              int64           `gorm:"column:parent_id" json:"parent_id" form:"parent_id"`
437
+	ExecutionTime         int64           `gorm:"column:execution_time" json:"execution_time" form:"execution_time"`
438
+	ExecutionStaff        int64           `gorm:"column:execution_staff" json:"execution_staff" form:"execution_staff"`
439
+	ExecutionState        int64           `gorm:"column:execution_state" json:"execution_state" form:"execution_state"`
440
+	Checker               int64           `gorm:"column:checker" json:"checker" form:"checker"`
441
+	RecordDate            int64           `gorm:"column:record_date" json:"record_date"`
442
+	DialysisOrderId       int64           `gorm:"column:dialysis_order_id" json:"dialysis_order_id"`
443
+	CheckTime             int64           `gorm:"column:check_time" json:"check_time" form:"check_time"`
444
+	CheckState            int64           `gorm:"column:check_state" json:"check_state" form:"check_state"`
445
+	AdviceId              int64           `gorm:"-"`
446
+	RemindType            int64           `gorm:"column:remind_type" json:"remind_type"`
447
+	FrequencyType         int64           `gorm:"column:frequency_type" json:"frequency_type"`
448
+	DayCount              int64           `gorm:"column:day_count" json:"day_count"`
449
+	WeekDay               string          `gorm:"column:week_day" json:"week_day"`
450
+	DoctorAdvice          []*DoctorAdvice `gorm:"ForeignKey:ParentId;AssociationForeignKey:ID" json:"children"`
451
+	TemplateId            string          `gorm:"column:template_id" json:"template_id"`
452
+	Modifier              int64           `gorm:"column:modifier" json:"modifier" form:"modifier"`
453
+	IsCheck               int64           `gorm:"-" json:"is_check" form:"is_check"`
454
+	Way                   int64           `gorm:"column:way" json:"way" form:"way"`
455
+	DrugId                int64           `gorm:"column:drug_id" json:"drug_id" form:"drug_id"`
456
+	DrugNameId            int64           `gorm:"column:drug_name_id" json:"drug_name_id" form:"drug_name_id"`
457
+}
458
+
459
+func (DoctorAdvice) TableName() string {
460
+	return "xt_doctor_advice"
461
+}
462
+
463
+func GetDoctorAdviceByType(change_type int64, record_time int64, org_id int64, patient_id int64) (advice []*DoctorAdvice, sch models.Schedule, err error) {
464
+	if change_type == 1 { //根据日期取出上一方数据
465
+		var Id AdviceDate
466
+		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
467
+		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
468
+		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
469
+
470
+	} else if change_type == 2 {
471
+		var Id AdviceDate
472
+		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
473
+		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
474
+		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
475
+	}
476
+	return
477
+}
478
+
479
+func GetDict(orgid int64) (drugways []*models.DrugwayDic, total int64, err error) {
480
+	err = readDb.Model(&models.DrugwayDic{}).Where("(org_id =? or org_id = 0) and status=1", orgid).Count(&total).Order("id desc").Find(&drugways).Error
481
+	return
482
+}

+ 637 - 0
service/doctor_schedule_service.go Bestand weergeven

@@ -0,0 +1,637 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_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", func(db *gorm.DB) *gorm.DB {
595
+		return XTReadDB().Model(&models.DeviceNumber{}).Where("status = 1 AND org_id = ?", orgid).Order("sort asc")
596
+	}).Preload("DialysisOrder", "status =1").Joins("JOIN xt_patients as p ON p.id = s.patient_id and p.lapseto = 1 and p.user_org_id =?", orgid).Where("s.user_org_id = ? and s.schedule_date = ? and s.status =1", orgid, startime).
597
+		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
598
+	return schedule, err
599
+}
600
+
601
+func DeleteSchedule(id int64) error {
602
+
603
+	schedule := models.XtSchedule{}
604
+
605
+	err := XTWriteDB().Model(&schedule).Where("id=? and status = 1", id).Updates(map[string]interface{}{"status": 0}).Error
606
+	return err
607
+}
608
+
609
+func GetSearchPatient(keywords string, orgid int64, startime int64) (schedule []*models.Schedule, err error) {
610
+
611
+	likeKey := "%" + keywords + "%"
612
+	db := XTReadDB().Table("xt_schedule as s")
613
+	err = db.Preload("DeviceZone", " status= 1").Preload("DeviceNumber", "status= 1").
614
+		Preload("DialysisOrder", "status =1").
615
+		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).
616
+		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
617
+	return schedule, err
618
+}
619
+
620
+func GetStaffScheduleById(ids []string) (schedule []*models.XtSchedule, err error) {
621
+
622
+	err = XTReadDB().Where("id in(?)", ids).Find(&schedule).Error
623
+	return schedule, err
624
+
625
+}
626
+
627
+func UpdateStaffSchedule(nextid int64, schedule models.XtSchedule) error {
628
+
629
+	err := XTWriteDB().Model(&schedule).Where("id = ?", nextid).Updates(map[string]interface{}{"patient_id": schedule.PatientId, "mode_id": schedule.ModeId}).Error
630
+	return err
631
+}
632
+
633
+func UpdateStaffScheduleOne(nextid int64, schedule models.WeekSchedule) error {
634
+
635
+	err := XTWriteDB().Model(&schedule).Where("id = ?", nextid).Updates(map[string]interface{}{"patient_id": schedule.PatientId, "mode_id": schedule.ModeId}).Error
636
+	return err
637
+}

+ 262 - 0
service/drug_stock_service.go Bestand weergeven

@@ -0,0 +1,262 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_New/models"
5
+	"github.com/jinzhu/gorm"
6
+)
7
+
8
+type DrugConfig struct {
9
+	ID                    int64        `gorm:"column:id" json:"id" form:"id"`
10
+	DrugName              string       `gorm:"column:drug_name" json:"drug_name" form:"drug_name"`
11
+	DrugCategory          int64        `gorm:"column:drug_category" json:"drug_category" form:"drug_category"`
12
+	DrugSpec              string       `gorm:"column:drug_spec" json:"drug_spec" form:"drug_spec"`
13
+	DrugType              int64        `gorm:"column:drug_type" json:"drug_type" form:"drug_type"`
14
+	DrugStatus            string       `gorm:"column:drug_status" json:"drug_status" form:"drug_status"`
15
+	Status                int64        `gorm:"column:status" json:"status" form:"status"`
16
+	OrgId                 int64        `gorm:"column:org_id" json:"org_id" form:"org_id"`
17
+	Manufacturer          int64        `gorm:"column:manufacturer" json:"manufacturer" form:"manufacturer"`
18
+	DrugSpecs             []DrugConfig `gorm:"ForeignKey:DrugName;AssociationForeignKey:DrugName" json:"drug_specs"`
19
+	RetailPrice           float64      `gorm:"column:retail_price" json:"retail_price" form:"retail_price"`
20
+	LastPrice             float64      `gorm:"column:last_price" json:"last_price" form:"last_price"`
21
+	MinUnit               string       `gorm:"column:min_unit" json:"min_unit" form:"min_unit"`
22
+	HospApprFlag          int64        `gorm:"column:hosp_appr_flag" json:"hosp_appr_flag" form:"hosp_appr_flag"`
23
+	LmtUsedFlag           int64        `gorm:"column:lmt_used_flag" json:"lmt_used_flag" form:"lmt_used_flag"`
24
+	Total                 float64      `gorm:"column:total" json:"total" form:"total"`
25
+	PrescribingNumberUnit string       `gorm:"column:prescribing_number_unit" json:"prescribing_number_unit" form:"prescribing_number_unit"`
26
+}
27
+
28
+func (DrugConfig) TableName() string {
29
+	return "xt_base_drug"
30
+}
31
+
32
+func GetDrugs(orgId int64) (drugs []*DrugConfig, err error) {
33
+	err = readDb.Model(&DrugConfig{}).Where("org_id = ? AND  status = 1  AND find_in_set('停用',drug_status) = 0", orgId).Preload("DrugSpecs", "status = 1  AND find_in_set('停用',drug_status) = 0 AND org_id = ?", orgId).Group("drug_name").Find(&drugs).Error
34
+	return
35
+}
36
+
37
+func FindAllDrugByManufactureId(manufacturer_id int64, dealer_id int64, org_id int64) (goodInfo []*DrugConfig, err error) {
38
+	db := readDb.Model(&DrugConfig{}).Where("org_id = ? AND status = 1 AND find_in_set('停用',drug_status) = 0", org_id)
39
+	if manufacturer_id > 0 {
40
+		db = db.Where("manufacturer = ?", manufacturer_id)
41
+	}
42
+	if dealer_id > 0 {
43
+		db = db.Where("dealer = ?", dealer_id)
44
+	}
45
+	err = db.Preload("DrugSpecs", "status = 1 AND org_id = ? AND find_in_set('停用',drug_status) = 0", org_id).Group("drug_name").Find(&goodInfo).Error
46
+	return goodInfo, err
47
+}
48
+
49
+type MedicineInsuranceDate struct {
50
+	RecordTime int64
51
+}
52
+
53
+func GetLastMedicineInsurance(orgID int64, type_id int64, module int64) (mip []*models.MedicineInsurancePercentage, err error) {
54
+	var mip_other models.MedicineInsurancePercentage
55
+	err = readDb.Model(&models.MedicineInsurancePercentage{}).Where("user_org_id = ? AND status=1 AND  type_id = ? AND module = ?", orgID, type_id, module).Last(&mip_other).Error
56
+	err = readDb.Model(&models.MedicineInsurancePercentage{}).Where("user_org_id = ? AND status=1 AND record_time = ? AND type_id = ? AND module = ?", orgID, mip_other.RecordTime, type_id, module).Find(&mip).Error
57
+	return
58
+}
59
+
60
+type DrugWarehouseInfo struct {
61
+	ID     int64  `gorm:"column:id" json:"id" form:"id"`
62
+	Number string `gorm:"column:number" json:"number" form:"number"`
63
+	Status int64  `gorm:"column:status" json:"status" form:"status"`
64
+	OrgId  int64  `gorm:"column:org_id" json:"org_id" form:"org_id"`
65
+}
66
+
67
+func (DrugWarehouseInfo) TableName() string {
68
+	return "xt_drug_warehouse_info"
69
+}
70
+func FindStockInNumber(orgId int64) (stockIns []*DrugWarehouseInfo, err error) {
71
+	err = readDb.Model(&DrugWarehouseInfo{}).Where("org_id = ? AND status = 1", orgId).Group("number").Find(&stockIns).Error
72
+	return
73
+}
74
+
75
+type DrugStockInfo struct {
76
+	ID           int64   `gorm:"column:id" json:"id" form:"id"`
77
+	DrugName     string  `gorm:"column:drug_name" json:"drug_name" form:"drug_name"`
78
+	DrugSpec     string  `gorm:"column:drug_spec" json:"drug_spec" form:"drug_spec"`
79
+	RetailPrice  float64 `gorm:"column:retail_price" json:"retail_price" form:"retail_price"`
80
+	LastPrice    float64 `gorm:"column:last_price" json:"last_price" form:"last_price"`
81
+	DrugStatus   string  `gorm:"column:drug_status" json:"drug_status" form:"drug_status"`
82
+	Status       int64   `gorm:"column:status" json:"status" form:"status"`
83
+	Ctime        int64   `gorm:"column:ctime" json:"ctime" form:"ctime"`
84
+	Mtime        int64   `gorm:"column:mtime" json:"mtime" form:"mtime"`
85
+	OrgId        int64   `gorm:"column:org_id" json:"org_id" form:"org_id"`
86
+	DrugCode     string  `gorm:"column:drug_code" json:"drug_code" form:"drug_code"`
87
+	HospApprFlag int64   `gorm:"column:hosp_appr_flag" json:"hosp_appr_flag" form:"hosp_appr_flag"`
88
+	LmtUsedFlag  int64   `gorm:"column:lmt_used_flag" json:"lmt_used_flag" form:"lmt_used_flag"`
89
+
90
+	QueryWarehousingInfo  []models.DrugWarehouseInfo    `gorm:"ForeignKey:DrugId;AssociationForeignKey:ID" json:"query_drug_warehousing_info"`
91
+	QuerySalesReturnInfo  []models.DrugSalesReturnInfo  `gorm:"ForeignKey:DrugId;AssociationForeignKey:ID" json:"query_drug_sales_return_info"`
92
+	QueryWarehouseOutInfo []models.DrugWarehouseOutInfo `gorm:"ForeignKey:DrugId;AssociationForeignKey:ID" json:"query_drug_warehouseout_info"`
93
+	QueryCancelStockInfo  []models.DrugCancelStockInfo  `gorm:"ForeignKey:DrugId;AssociationForeignKey:ID" json:"query_drug_cancel_stock_info"`
94
+
95
+	Total                 float64 `gorm:"column:total" json:"total" form:"total"`
96
+	PrescribingNumberUnit string  `gorm:"column:prescribing_number_unit" json:"prescribing_number_unit" form:"prescribing_number_unit"`
97
+}
98
+
99
+func (DrugStockInfo) TableName() string {
100
+	return "xt_base_drug"
101
+}
102
+
103
+func FindAllDrugStockInfo(orgId int64, page int64, limit int64, keyword string, drugCategory int64, startTime int64, endTime int64) (list []*DrugStockInfo, total int64, err error) {
104
+	db := readDb.Model(&DrugStockInfo{})
105
+	if drugCategory > 0 {
106
+		db = db.Where("xt_base_drug.org_id = ? AND xt_base_drug.status = 1 AND xt_base_drug.drug_category = ?", orgId, drugCategory)
107
+	} else {
108
+		db = db.Where("xt_base_drug.org_id = ? AND xt_base_drug.status = 1", orgId)
109
+	}
110
+
111
+	if startTime > 0 {
112
+
113
+		db = db.Preload("QueryWarehousingInfo", func(db *gorm.DB) *gorm.DB {
114
+			return db.Where("org_id = ? AND status = 1 and ctime >=?", orgId, startTime)
115
+		})
116
+		db = db.Preload("QuerySalesReturnInfo", "org_id = ? AND status = 1 and ctime>=?", orgId, startTime)
117
+		db = db.Preload("QueryWarehouseOutInfo", func(db *gorm.DB) *gorm.DB {
118
+			return db.Where("org_id = ? AND status = 1 and sys_record_time>=?", orgId, startTime)
119
+		})
120
+
121
+		db = db.Preload("QueryCancelStockInfo", "org_id = ? AND status = 1 and ctime>=?", orgId, startTime)
122
+	} else {
123
+
124
+		db = db.Preload("QueryWarehousingInfo", func(db *gorm.DB) *gorm.DB {
125
+			return db.Where("org_id = ? AND status = 1", orgId)
126
+		})
127
+		db = db.Preload("QuerySalesReturnInfo", "org_id = ? AND status = 1", orgId)
128
+		db = db.Preload("QueryWarehouseOutInfo", func(db *gorm.DB) *gorm.DB {
129
+			return db.Where("org_id = ? AND status = 1", orgId)
130
+		})
131
+		db = db.Preload("QueryCancelStockInfo", "org_id = ? AND status = 1", orgId)
132
+	}
133
+
134
+	if endTime > 0 {
135
+		db = db.Preload("QueryWarehousingInfo", func(db *gorm.DB) *gorm.DB {
136
+			return db.Where("org_id = ? AND status = 1  and ctime <=?", orgId, startTime, endTime)
137
+		})
138
+		db = db.Preload("QuerySalesReturnInfo", "org_id = ? AND status = 1 and ctime>=? and ctime<=?", orgId, startTime, endTime)
139
+		db = db.Preload("QueryWarehouseOutInfo", func(db *gorm.DB) *gorm.DB {
140
+			return db.Where("org_id = ? AND status = 1 and sys_record_time>=? and sys_record_time<=?", orgId, startTime, endTime)
141
+		})
142
+		db = db.Preload("QueryCancelStockInfo", "org_id = ? AND status = 1 and ctime >=? and ctime<=?", orgId, startTime, endTime)
143
+	} else {
144
+
145
+		db = db.Preload("QueryWarehousingInfo", func(db *gorm.DB) *gorm.DB {
146
+			return db.Where("org_id = ? AND status = 1", orgId)
147
+		})
148
+		db = db.Preload("QuerySalesReturnInfo", "org_id = ? AND status = 1", orgId)
149
+		db = db.Preload("QueryWarehouseOutInfo", func(db *gorm.DB) *gorm.DB {
150
+			return db.Where("org_id = ? AND status = 1", orgId)
151
+		})
152
+		db = db.Preload("QueryCancelStockInfo", "org_id = ? AND status = 1", orgId)
153
+	}
154
+
155
+	if len(keyword) > 0 {
156
+		likeKey := "%" + keyword + "%"
157
+		db = db.Where("xt_base_drug.drug_name LIKE ? OR xt_base_drug.drug_spec LIKE ?", likeKey, likeKey)
158
+	}
159
+	db = db.Count(&total)
160
+	offset := (page - 1) * limit
161
+	err = db.Offset(offset).Limit(limit).Order("ctime desc").Find(&list).Error
162
+	return
163
+}
164
+
165
+func GetCancelDrugOrderPrint(id []string, orgid int64) (info []*models.DrugCancelStock, err error) {
166
+
167
+	db := XTReadDB().Model(&info)
168
+
169
+	if len(id) > 0 {
170
+		db = db.Where("id in(?)", id)
171
+	}
172
+	if orgid > 0 {
173
+		db = db.Where("org_id= ?", orgid)
174
+	}
175
+
176
+	err = db.Preload("DrugCancelStockInfo", func(db *gorm.DB) *gorm.DB {
177
+		return db.Where("status = 1 AND org_id = ?", orgid).Preload("BaseDrugLib", "status = 1 AND org_id= ?", orgid)
178
+	}).Find(&info).Error
179
+
180
+	return info, err
181
+}
182
+
183
+func GetDrugCancelExportList(orderid []string, orgid int64) (info []*models.DrugCancelStockInfo, err error) {
184
+
185
+	db := XTReadDB().Model(&info)
186
+	if len(orderid) > 0 {
187
+		db = db.Where("cancel_stock_id in(?)", orderid)
188
+	}
189
+	if orgid > 0 {
190
+		db = db.Where("org_id = ?", orgid)
191
+	}
192
+	db = db.Preload("BaseDrugLib", "status = 1 and org_id = ?", orgid)
193
+	err = db.Find(&info).Error
194
+	return info, err
195
+}
196
+
197
+func GetDrugWarehouseInfoPrint(startime int64, endtime int64, orgid int64) (info []*models.XtDrugWarehouseInfo, err error) {
198
+
199
+	db := XTReadDB().Table("xt_drug_warehouse_info").Where("status = 1")
200
+	if startime > 0 {
201
+		db = db.Where("ctime >=?", startime)
202
+	}
203
+	if endtime > 0 {
204
+		db = db.Where("ctime<=?", endtime)
205
+	}
206
+	if orgid > 0 {
207
+		db = db.Where("org_id = ?", orgid)
208
+	}
209
+	err = db.Preload("XtBaseDrug", "status = 1 and org_id = ?", orgid).Group("drug_id").Find(&info).Error
210
+
211
+	//err = db.Select("x.id,x.warehousing_id,x.drug_id,x.number,x.product_date,x.expiry_date,sum(x.warehousing_count) as warehousing_count,x.price,x.total_price,x.dealer,x.manufacturer,x.remark,x.is_return,x.warehousing_order,x.type,x.retail_price,x.retail_total_price,x.warehouseing_unit,x.max_unit,x.min_unit,x.stock_max_number,x.stock_min_number,x.batch_number").Group("x.drug_id").Find(&DrugWarehouseInfo{}).Error
212
+	return info, err
213
+}
214
+
215
+//func GetDrugWarehouseInfoList(startime int64,endtime int64,orgid int64)(info []*models.BloodAutomaticReduceDetail,err error)  {
216
+//
217
+//
218
+//  db := XTReadDB().Table("xt_drug_warehouse_info as x").Where("x.status = 1")
219
+//  if startime > 0 {
220
+//    db = db.Where("x.ctime >=?", startime)
221
+//  }
222
+//  if endtime>0{
223
+//    db = db.Where("x.ctime<=?", endtime)
224
+//  }
225
+//  if orgid > 0{
226
+//    db = db.Where("x.org_id = ?", orgid)
227
+//  }
228
+//
229
+//
230
+//}
231
+
232
+func GetDrugOutOrderPrint(startime int64, endtime int64, orgid int64) (info []*models.XtDrugWarehouseOutInfo, err error) {
233
+
234
+	db := XTReadDB().Table("xt_drug_warehouse_out_info").Where("status = 1")
235
+	if startime > 0 {
236
+		db = db.Where("ctime >=?", startime)
237
+	}
238
+	if endtime > 0 {
239
+		db = db.Where("ctime<=?", endtime)
240
+	}
241
+	if orgid > 0 {
242
+		db = db.Where("org_id = ?", orgid)
243
+	}
244
+	err = db.Preload("XtBaseDrug", "status = 1 and org_id = ?", orgid).Group("drug_id").Find(&info).Error
245
+	return info, err
246
+}
247
+
248
+func GetDrugOutOrderPrintList(startime int64, endtime int64, orgid int64) (list []*models.XtDrugAutomaticReduceDetail, err error) {
249
+
250
+	db := XTReadDB().Table("xt_drug_automatic_reduce_detail").Where("status = 1")
251
+	if startime > 0 {
252
+		db = db.Where("ctime >=?", startime)
253
+	}
254
+	if endtime > 0 {
255
+		db = db.Where("ctime<=?", endtime)
256
+	}
257
+	if orgid > 0 {
258
+		db = db.Where("org_id = ?", orgid)
259
+	}
260
+	err = db.Preload("XtBaseDrug", "status = 1 and org_id = ?", orgid).Find(&list).Error
261
+	return list, err
262
+}

Diff onderdrukt omdat het te groot bestand
+ 1425 - 0
service/gdyb_service.go


+ 780 - 0
service/gobal_config_service.go Bestand weergeven

@@ -0,0 +1,780 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_New/models"
5
+	"fmt"
6
+	"github.com/jinzhu/gorm"
7
+	"time"
8
+)
9
+
10
+func CreateAutomaticReduceRecord(config *models.GobalConfig) (err error) {
11
+	err = writeDb.Model(&models.GobalConfig{}).Create(config).Error
12
+	return
13
+}
14
+
15
+func CreateDrugAutomaticReduceRecord(config *models.DrugStockConfig) (err error) {
16
+	err = writeDb.Model(&models.DrugStockConfig{}).Create(config).Error
17
+	return
18
+}
19
+
20
+func FindAutomaticReduceRecordByOrgId(org_id int64) (err error, config models.GobalConfig) {
21
+	err = readDb.Model(&models.GobalConfig{}).Where("status = 1 AND org_id = ?", org_id).Find(&config).Error
22
+	return
23
+}
24
+
25
+func FindDrugStockAutomaticReduceRecordByOrgId(org_id int64) (err error, config models.DrugStockConfig) {
26
+	err = readDb.Model(&models.DrugStockConfig{}).Where("status = 1 AND org_id = ?", org_id).Find(&config).Error
27
+	return
28
+}
29
+func UpdateAutomaticReduceRecord(config *models.GobalConfig) (err error) {
30
+	err = writeDb.Save(config).Error
31
+	return
32
+}
33
+
34
+func UpdateDrugStockAutomaticReduceRecord(config *models.DrugStockConfig) (err error) {
35
+	err = writeDb.Save(config).Error
36
+	return
37
+}
38
+
39
+func CreatePrintTemplateRecord(template *models.GobalTemplate) (err error) {
40
+	err = writeDb.Model(&models.GobalTemplate{}).Create(template).Error
41
+	return
42
+}
43
+
44
+func FindPrintTemplateByOrgId(org_id int64) (err error, template models.GobalTemplate) {
45
+	err = readDb.Model(&models.GobalTemplate{}).Where("status = 1 AND org_id = ?", org_id).Find(&template).Error
46
+	return
47
+}
48
+
49
+func UpdatePrintTemplate(template *models.GobalTemplate) (err error) {
50
+	err = writeDb.Save(template).Error
51
+	return
52
+}
53
+
54
+func CreateConfigData(config *models.DataUploadConfig) (err error) {
55
+	err = writeDb.Create(config).Error
56
+	return
57
+}
58
+
59
+func SaveConfigData(config *models.DataUploadConfig) (err error) {
60
+	err = writeDb.Save(config).Error
61
+	return
62
+}
63
+
64
+func GetConfigData(org_id int64, config_type int64) (config models.DataUploadConfig, err error) {
65
+	err = readDb.Model(&models.DataUploadConfig{}).Where("status = 1 AND  org_id = ? AND config_type = ?", org_id, config_type).First(&config).Error
66
+	return
67
+}
68
+
69
+func GetDockingStatus(config_type int64, province int64, city int64) (config models.DockingStatus, err error) {
70
+	err = readDb.Model(&models.DockingStatus{}).Where("status = 1 AND  docking_type = ? AND province_id = ? AND city_id = ?", config_type, province, city).First(&config).Error
71
+	return
72
+}
73
+
74
+func GetConfigDataById(id int64) (config models.DataUploadConfig, err error) {
75
+	err = readDb.Model(&models.DataUploadConfig{}).Where("id = ?", id).First(&config).Error
76
+	return
77
+}
78
+
79
+func FindDoctorAdviceRecordByOrgId(org_id int64) (err error, config models.DoctorAdviceConfig) {
80
+	err = readDb.Model(&models.DoctorAdviceConfig{}).Where("status = 1 AND user_org_id = ?", org_id).Find(&config).Error
81
+	return
82
+}
83
+
84
+func CreateDoctorAdviceRecord(config *models.DoctorAdviceConfig) (err error) {
85
+	err = writeDb.Model(&models.DoctorAdviceConfig{}).Create(config).Error
86
+	return
87
+}
88
+
89
+func UpdateDoctorAdviceRecord(config *models.DoctorAdviceConfig) (err error) {
90
+	err = writeDb.Save(config).Error
91
+	return
92
+}
93
+
94
+func UpdateFiledConfig(org_id int64) (err error) {
95
+	err = writeDb.Model(&models.FiledConfig{}).Where("org_id = ? AND sys_module = 0", org_id).Updates(map[string]interface{}{"is_show": 1}).Error
96
+	return
97
+}
98
+
99
+func FindAllHideFiledConfig(template_id int64) (err error, config []*models.FiledConfig) {
100
+	err = readDb.Model(&models.FiledConfig{}).Where("sys_module = ?  AND is_show = 2", template_id).Find(&config).Error
101
+	return
102
+}
103
+
104
+func UpdateShowFieldConfig(org_id int64, fileds []string) (err error) {
105
+	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
106
+	return
107
+}
108
+
109
+func FindAllAdviceParentTemplate(org_id int64) (template []*models.DoctorAdviceParentTemplate) {
110
+	readDb.Model(&models.DoctorAdviceParentTemplate{}).Preload("DoctorAdviceTemplate", func(db *gorm.DB) *gorm.DB {
111
+		return db.Preload("SubDoctorAdviceTemplate", "status = 1 AND org_id = ?", org_id).Where("status = 1 AND parent_id = 0  AND org_id = ?", org_id)
112
+	}).Where("status = 1 AND org_id = ? ", org_id).Find(&template)
113
+	return
114
+}
115
+
116
+func CreateDoctorParentTemplate(template *models.DoctorAdviceParentTemplate) (err error) {
117
+	err = writeDb.Create(&template).Error
118
+	return
119
+}
120
+
121
+func FindAllAdviceTemplates(org_id int64, parent_template_id int64) (template []*models.DoctorAdviceTemplate, err error) {
122
+	err = readDb.Model(&models.DoctorAdviceTemplate{}).Where("status = 1 AND org_id = ? AND template_id = ?", org_id, parent_template_id).Find(&template).Error
123
+	return
124
+}
125
+
126
+func CreateDoctorTemplate(template *models.DoctorAdviceTemplate) (err error) {
127
+	err = writeDb.Create(&template).Error
128
+	return
129
+}
130
+
131
+func CreateSystemDialysisSolution(solution *models.SystemPrescription) (err error) {
132
+	err = writeDb.Create(solution).Error
133
+	return
134
+}
135
+
136
+func UpdateSystemDialysisSolution(solution *models.SystemPrescription) (err error) {
137
+	err = writeDb.Save(solution).Error
138
+	return
139
+}
140
+
141
+func FindSystemDialysisSolution(orgID int64, id int64) (solution models.SystemPrescription, err error) {
142
+	err = readDb.Model(&models.SystemPrescription{}).Where("id = ? and status=1 and user_org_id=?", id, orgID).First(&solution).Error
143
+	return
144
+}
145
+
146
+func FindAllSystemPrescription(orgID int64) (solution []*models.SystemPrescription, err error) {
147
+	err = readDb.Model(&models.SystemPrescription{}).Where("status=1 and user_org_id=?", orgID).Find(&solution).Error
148
+	return
149
+}
150
+
151
+func FindSystemDialysisPrescriptionByMode(orgID int64, id int64) (solution models.SystemPrescription, err error) {
152
+	err = readDb.Model(&models.SystemPrescription{}).Where("mode_id = ? and status=1 and user_org_id=?", id, orgID).First(&solution).Error
153
+	return
154
+}
155
+
156
+func CreateAdviceInitConfig(adviceInit *models.AdviceInit) (err error) {
157
+	err = writeDb.Create(&adviceInit).Error
158
+	return
159
+}
160
+
161
+func FindAdviceInitConfig(org_id int64) (adviceInit models.AdviceInit, err error) {
162
+	err = readDb.Model(&models.AdviceInit{}).Where("user_org_id = ? AND status = 1 ", org_id).First(&adviceInit).Error
163
+	return
164
+}
165
+
166
+func GetPrint(ids []int64, orgid int64) (doctor []*models.DoctorAdvice, err error) {
167
+
168
+	if len(ids) == 1 {
169
+		err = XTReadDB().Model(&doctor).Where("groupno = ? and user_org_id = ?", ids[0], orgid).Find(&doctor).Error
170
+	} else {
171
+		err = XTReadDB().Model(&doctor).Where("groupno IN(?) and user_org_id = ?", ids, orgid).Find(&doctor).Error
172
+	}
173
+
174
+	return doctor, err
175
+}
176
+
177
+func GetExportLogByType(org_id int64, log_type int64) (log []*models.ExportLog, err error) {
178
+	err = readDb.Model(&models.ExportLog{}).Where("user_org_id = ? AND status = 1 AND log_type = ?", org_id, log_type).
179
+		Preload("ExportErrLog", "status = 1").Order("export_time desc").Find(&log).Error
180
+	return
181
+}
182
+
183
+func FindXTHisRecordByOrgId(org_id int64) (err error, config models.XtHisConfig) {
184
+	err = readDb.Model(&models.XtHisConfig{}).Where("status = 1 AND user_org_id = ?", org_id).Find(&config).Error
185
+	return
186
+}
187
+
188
+func UpdateXTHisRecord(config *models.XtHisConfig) (err error) {
189
+	err = writeDb.Save(config).Error
190
+	return
191
+}
192
+
193
+func CreateXTHisRecord(config *models.XtHisConfig) (err error) {
194
+	err = writeDb.Model(&models.XtHisConfig{}).Create(config).Error
195
+	return
196
+}
197
+
198
+//TODO:项目开关
199
+func FindXTHisProjectByOrgId(org_id int64) (err error, config models.XtHisProjectConfig) {
200
+	err = readDb.Model(&models.XtHisProjectConfig{}).Where("status = 1 AND user_org_id = ?", org_id).Find(&config).Error
201
+	return
202
+}
203
+
204
+func UpdateXTHisProjectRecord(config *models.XtHisProjectConfig) (err error) {
205
+	err = writeDb.Save(config).Error
206
+	return
207
+}
208
+
209
+func CreateXTHisProjectRecord(config *models.XtHisProjectConfig) (err error) {
210
+	err = writeDb.Model(&models.XtHisProjectConfig{}).Create(config).Error
211
+	return
212
+}
213
+
214
+func GetExportHisOrderList(user_org_id int64, start_time int64, end_time int64, p_type int64) (order []*models.HisOrder, err error) {
215
+	db := readDb.Model(&models.HisOrder{})
216
+	if start_time != 0 {
217
+		db = db.Where("his_order.settle_accounts_date>=?", start_time)
218
+	}
219
+	if end_time != 0 {
220
+		db = db.Where("his_order.settle_accounts_date<=?", end_time)
221
+	}
222
+
223
+	db = db.Where("his_order.status = 1 AND his_order.user_org_id = ? AND his_order.order_status > 1 AND p_type = ? ", user_org_id, p_type)
224
+
225
+	db = db.Preload("HisOrderInfo", "status = 1 AND user_org_id = ?", user_org_id).
226
+		Preload("Patients", "status = 1 AND user_org_id = ?", user_org_id).
227
+		Preload("HisPatient", "status = 1 AND user_org_id = ?", user_org_id).
228
+		Preload("HisPrescriptionInfo", func(db *gorm.DB) *gorm.DB {
229
+			return db.Where("status = 1 AND user_org_id = ?", user_org_id).Preload("XtHisDepartment", "status = 1")
230
+		})
231
+	err = db.Order("ctime desc").Find(&order).Error
232
+	return
233
+}
234
+
235
+func GetDrugInOrderDetail(startime int64, endtime int64, orgid int64, orderType int64, manufacturerId int64, keyword string, page int64, limit int64) (drugInfo []*models.BloodDrugWarehouseInfo, total int64, err error) {
236
+
237
+	likeKey := "%" + keyword + "%"
238
+	offset := (page - 1) * limit
239
+
240
+	db := XTReadDB().Table("xt_drug_warehouse_info as x").Where("x.status = 1")
241
+	dbOne := XTReadDB().Table("xt_base_drug as t").Where("t.status =1")
242
+	dbTwo := XTReadDB().Table("xt_drug_warehouse as s").Where("s.status = 1")
243
+	fmt.Print(dbOne, dbTwo)
244
+	if startime > 0 {
245
+		db = db.Where("x.ctime >=?", startime)
246
+	}
247
+	if endtime > 0 {
248
+		db = db.Where("x.ctime <=?", endtime)
249
+	}
250
+	if orgid > 0 {
251
+		db = db.Where("x.org_id =?", orgid)
252
+	}
253
+	if orderType > 0 {
254
+		db = db.Where("x.type = ?", orderType)
255
+	}
256
+
257
+	if len(keyword) > 0 {
258
+
259
+		db = db.Where("x.warehousing_order like ? or t.drug_name like ? or s.creater like ?", likeKey, likeKey, likeKey)
260
+
261
+	}
262
+
263
+	if manufacturerId > 0 {
264
+		err = db.Select("x.id,x.warehousing_id,x.drug_id,x.number,x.product_date,x.expiry_date,x.warehousing_count,x.price,x.total_price,x.dealer,t.manufacturer,x.remark,x.ctime,x.org_id,x.is_return,x.warehousing_order,x.type,x.retail_price,x.retail_total_price,t.drug_type,t.drug_name,t.drug_spec,t.min_unit,t.dose,t.dose_unit,t.max_unit,t.min_number,s.creater").Joins("left join xt_base_drug as t on t.id = x.drug_id and t.org_id = ? and t.status =1", orgid).Where("t.manufacturer = ?", manufacturerId).Joins("left join xt_drug_warehouse as s on s.id = x.warehousing_id and s.org_id = ? and s.status =1", orgid).Order("x.ctime desc").Count(&total).Offset(offset).Limit(limit).Scan(&drugInfo).Error
265
+	} else {
266
+		err = db.Select("x.id,x.warehousing_id,x.drug_id,x.number,x.product_date,x.expiry_date,x.warehousing_count,x.price,x.total_price,x.dealer,t.manufacturer,x.remark,x.ctime,x.org_id,x.is_return,x.warehousing_order,x.type,x.retail_price,x.retail_total_price,t.drug_type,t.drug_name,t.drug_spec,t.min_unit,t.dose,t.dose_unit,t.max_unit,t.min_number,s.creater").Joins("left join xt_base_drug as t on t.id = x.drug_id and t.org_id = ? and t.status =1", orgid).Joins("left join xt_drug_warehouse as s on s.id = x.warehousing_id and s.org_id = ? and s.status =1", orgid).Order("x.ctime desc").Count(&total).Offset(offset).Limit(limit).Scan(&drugInfo).Error
267
+	}
268
+
269
+	return drugInfo, total, err
270
+}
271
+
272
+func GetDrugReturnOrder(startime int64, endtime int64, orgid int64, orderType int64, manufacturerId int64, keyword string, limit int64, page int64) (returninfo []*models.BloodDrugSalesReturnInfo, total int64, err error) {
273
+
274
+	likeKey := "%" + keyword + "%"
275
+	offset := (page - 1) * limit
276
+	db := XTReadDB().Table("xt_drug_sales_return_info as x").Where("x.status =1")
277
+	dbOne := XTReadDB().Table("xt_base_drug as s").Where("s.status =1")
278
+	dbTwo := XTReadDB().Table("xt_drug_sales_return as r").Where("r.status = 1")
279
+	fmt.Print(dbOne, dbTwo)
280
+	if startime > 0 {
281
+		db = db.Where("x.ctime >= ?", startime)
282
+	}
283
+	if endtime > 0 {
284
+		db = db.Where("x.ctime <=?", endtime)
285
+	}
286
+	if orgid > 0 {
287
+		db = db.Where("x.org_id = ?", orgid)
288
+	}
289
+	if orderType > 0 {
290
+		db = db.Where("x.type = ?", orderType)
291
+	}
292
+
293
+	if len(keyword) > 0 {
294
+
295
+		db = db.Where("x.order_number like ? or s.drug_spec like ? or r.creater like ?", likeKey, likeKey, likeKey)
296
+	}
297
+
298
+	if manufacturerId > 0 {
299
+		err = db.Select("x.id,x.drug_id,x.sales_return_id,x.count,x.price,x.total,x.product_date,x.expiry_date,x.ctime,x.org_id,x.order_number,x.type,x.dealer,x.manufacturer,x.retail_price,x.retail_total_price,x.number,s.drug_name,s.drug_spec,s.drug_type,s.min_unit,r.creater").Joins("left join xt_base_drug as s on s.id = x.drug_id and s.org_id = ? and s.status = 1", orgid).Joins("left join xt_drug_sales_return as r on r.id = x.sales_return_id and r.org_id = ? and r.status =1", orgid).Where("r.manufacturer = ?", manufacturerId).Order("x.ctime desc").Count(&total).Offset(offset).Limit(limit).Scan(&returninfo).Error
300
+	} else {
301
+		err = db.Select("x.id,x.drug_id,x.sales_return_id,x.count,x.price,x.total,x.product_date,x.expiry_date,x.ctime,x.org_id,x.order_number,x.type,x.dealer,x.manufacturer,x.retail_price,x.retail_total_price,x.number,s.drug_name,s.drug_spec,s.drug_type,s.min_unit,r.creater").Joins("left join xt_base_drug as s on s.id = x.drug_id and s.org_id = ? and s.status = 1", orgid).Joins("left join xt_drug_sales_return as r on r.id = x.sales_return_id and r.org_id = ? and r.status =1", orgid).Order("x.ctime desc").Count(&total).Offset(offset).Limit(limit).Scan(&returninfo).Error
302
+	}
303
+
304
+	return returninfo, total, err
305
+}
306
+
307
+func GetDrugOutOrder(startime int64, endtime int64, orgid int64, orderType int64, manufacturerId int64, keyword string, page int64, limit int64) (outinfo []*models.BloodDrugWarehouseOutInfo, total int64, err error) {
308
+
309
+	likeKey := "%" + keyword + "%"
310
+	offset := (page - 1) * limit
311
+	db := XTReadDB().Table("xt_drug_warehouse_out_info as x").Where("x.status =1")
312
+	dbOne := XTReadDB().Table("xt_base_drug as b").Where("b.status =1")
313
+	dbTwo := XTReadDB().Table("xt_drug_warehouse_out as t").Where("t.status = 1")
314
+	fmt.Print(dbOne, dbTwo)
315
+	if startime > 0 {
316
+		db = db.Where("x.ctime >=?", startime)
317
+	}
318
+	if endtime > 0 {
319
+		db = db.Where("x.ctime <=?", endtime)
320
+	}
321
+
322
+	if orgid > 0 {
323
+		db = db.Where("x.org_id = ?", orgid)
324
+	}
325
+	if orderType > 0 {
326
+		db = db.Where("x.type = ?", orderType)
327
+	}
328
+
329
+	if len(keyword) > 0 {
330
+		db = db.Where("x.warehouse_out_order_number like ? or b.drug_name like ? or t.creater like ?", likeKey, likeKey, likeKey)
331
+	}
332
+
333
+	if manufacturerId > 0 {
334
+		err = db.Select("x.id,x.warehouse_out_id,x.drug_id,x.warehousing_out_target,x.count,x.price,x.total_price,x.product_date,x.expiry_date,x.ctime,x.org_id,x.remark,x.is_cancel,x.warehouse_out_order_number,x.type,x.dealer,x.manufacturer,x.is_sys,x.sys_record_time,x.retail_price,x.retail_total_price,b.drug_name,b.drug_spec,b.drug_type,b.min_unit,b.max_unit,b.min_number,b.dose,b.dose_unit,t.creater").Joins("left join xt_base_drug as b on b.id = x.drug_id and b.org_id = ? and b.status =1", orgid).Joins("left join xt_drug_warehouse_out as t on t.id = x.warehouse_out_id and t.org_id = ? and t.status  =1", orgid).Where("t.manufacturer = ?", manufacturerId).Order("x.ctime desc").Count(&total).Offset(offset).Limit(limit).Scan(&outinfo).Error
335
+	} else {
336
+		err = db.Select("x.id,x.warehouse_out_id,x.drug_id,x.warehousing_out_target,x.count,x.price,x.total_price,x.product_date,x.expiry_date,x.ctime,x.org_id,x.remark,x.is_cancel,x.warehouse_out_order_number,x.type,x.dealer,x.manufacturer,x.is_sys,x.sys_record_time,x.retail_price,x.retail_total_price,b.drug_name,b.drug_spec,b.drug_type,b.min_unit,b.max_unit,b.min_number,b.dose,b.dose_unit,t.creater").Joins("left join xt_base_drug as b on b.id = x.drug_id and b.org_id = ? and b.status =1", orgid).Joins("left join xt_drug_warehouse_out as t on t.id = x.warehouse_out_id and t.org_id = ? and t.status  =1", orgid).Order("x.ctime desc").Count(&total).Offset(offset).Limit(limit).Scan(&outinfo).Error
337
+	}
338
+
339
+	return outinfo, total, err
340
+}
341
+
342
+func GetDrugCancelOrder(startime int64, endtime int64, orgid int64, orderType int64, manufacturerId int64, keyword string, page int64, limit int64) (cancel []*models.BloodDrugCancelStockInfo, total int64, err error) {
343
+
344
+	likeKey := "%" + keyword + "%"
345
+	offset := (page - 1) * limit
346
+	db := XTReadDB().Table("xt_drug_cancel_stock_info as x").Where("x.status =1")
347
+	dbOne := XTReadDB().Table("xt_base_drug as s").Where("s.status =1")
348
+	dbTwo := XTReadDB().Table("xt_drug_cancel_stock as t").Where("t.status = 1")
349
+	fmt.Print(dbOne, dbTwo)
350
+	if startime > 0 {
351
+		db = db.Where("x.ctime >= ?", startime)
352
+	}
353
+	if endtime > 0 {
354
+		db = db.Where("x.ctime<=?", endtime)
355
+	}
356
+	if orgid > 0 {
357
+		db = db.Where("x.org_id = ?", orgid)
358
+	}
359
+	if orderType > 0 {
360
+		db = db.Where("x.type = ? ", orderType)
361
+	}
362
+	if len(keyword) > 0 {
363
+		db = db.Where("x.order_number like ? or s.drug_spec like ? or t.creater like ?", likeKey, likeKey, likeKey)
364
+	}
365
+
366
+	if manufacturerId > 0 {
367
+		err = db.Select("x.id,x.drug_id,x.cancel_stock_id,x.count,x.price,x.total,x.product_date,x.expiry_date,x.ctime,x.org_id,x.order_number,x.type,x.dealer,x.manufacturer,x.retail_price,x.retail_total_price,x.number,s.drug_name,s.drug_type,s.drug_spec,s.min_unit,t.creater,s.dose,s.dose_unit,s.min_number,s.max_unit").Joins("left join xt_base_drug as s on s.id = x.drug_id and s.org_id = ? and s.status = 1", orgid).Joins("left join xt_drug_cancel_stock as t on t.id = x.cancel_stock_id and t.org_id = ? and t.status =1", orgid).Where("t.manufacturer = ?", manufacturerId).Order("x.ctime desc").Count(&total).Offset(offset).Limit(limit).Scan(&cancel).Error
368
+	} else {
369
+		err = db.Select("x.id,x.drug_id,x.cancel_stock_id,x.count,x.price,x.total,x.product_date,x.expiry_date,x.ctime,x.org_id,x.order_number,x.type,x.dealer,x.manufacturer,x.retail_price,x.retail_total_price,x.number,s.drug_name,s.drug_type,s.drug_spec,s.min_unit,t.creater,s.dose,s.dose_unit,s.min_number,s.max_unit").Joins("left join xt_base_drug as s on s.id = x.drug_id and s.org_id = ? and s.status = 1", orgid).Joins("left join xt_drug_cancel_stock as t on t.id = x.cancel_stock_id and t.org_id = ? and t.status =1", orgid).Order("x.ctime desc").Count(&total).Offset(offset).Limit(limit).Scan(&cancel).Error
370
+	}
371
+
372
+	return cancel, total, err
373
+}
374
+
375
+func FindPrintStockGoodInfoByType(types int, startTime int64, end_time int64, orgId int64) (list []*models.StockInfo, err error) {
376
+
377
+	db := XTReadDB().Model(&models.StockInfo{})
378
+	db = db.Where("xt_good_information.org_id = ? AND xt_good_information.status = 1", orgId)
379
+	if types == 1 {
380
+		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")
381
+		db = db.Preload("QueryWarehousingInfo", func(db *gorm.DB) *gorm.DB {
382
+			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)
383
+		})
384
+	} else if types == 2 {
385
+		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")
386
+		db = db.Preload("QuerySalesReturnInfo", func(db *gorm.DB) *gorm.DB {
387
+			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)
388
+		})
389
+
390
+	} else if types == 3 {
391
+		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")
392
+		db = db.Preload("QueryWarehouseOutInfo", func(db *gorm.DB) *gorm.DB {
393
+			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)
394
+		})
395
+
396
+	} else if types == 4 {
397
+
398
+		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")
399
+		db = db.Preload("QueryCancelStockInfo", func(db *gorm.DB) *gorm.DB {
400
+			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)
401
+		})
402
+
403
+	}
404
+	db = db.Preload("GoodsType", "org_id = ? AND status = 1", orgId)
405
+	err = db.Order("ctime desc").Find(&list).Error
406
+	return
407
+}
408
+
409
+func GetOutStockTotalCountTwo(startime int64, endtime int64, orgid int64) (autoMatic []*models.NewXtAutomaticReduceDetail, err error) {
410
+
411
+	err = XTReadDB().Raw("SELECT good_id,SUM(b.count) as count FROM (SELECT DISTINCT x.patient_id,x.good_id,x.record_time,x.count FROM xt_automatic_reduce_detail as x WHERE x.org_id = ? and x.record_time >= ? and x.record_time<=? and `status` = 1)  as b GROUP BY good_id", orgid, startime, endtime).Scan(&autoMatic).Error
412
+
413
+	return autoMatic, err
414
+}
415
+
416
+func AddMonitorOpen(config *models.XtMonitorConfig) error {
417
+
418
+	err := XTWriteDB().Create(&config).Error
419
+
420
+	return err
421
+}
422
+
423
+func UpdateMonitorOpen(orgid int64, config *models.XtMonitorConfig) error {
424
+
425
+	err := XTWriteDB().Model(&config).Where("user_org_id = ? and status = 1", orgid).Updates(map[string]interface{}{"is_open": config.IsOpen, "mtime": time.Now().Unix()}).Error
426
+	return err
427
+}
428
+
429
+func GetMonitorConfig(orgid int64) (models.XtMonitorConfig, error) {
430
+
431
+	config := models.XtMonitorConfig{}
432
+	err := XTReadDB().Model(&config).Where("user_org_id = ? and status = 1", orgid).Find(&config).Error
433
+	return config, err
434
+}
435
+
436
+func AddOrderConfig(config *models.XtOrderConfig) error {
437
+
438
+	err := XTWriteDB().Create(&config).Error
439
+	return err
440
+}
441
+
442
+func UpdateOrderConfig(orgid int64, config *models.XtOrderConfig) error {
443
+
444
+	err := XTWriteDB().Model(&config).Where("user_org_id = ? and status = 1", orgid).Updates(map[string]interface{}{"is_open": config.IsOpen, "mtime": time.Now().Unix()}).Error
445
+	return err
446
+}
447
+
448
+func GetOrderConfigById(orgid int64) (*models.XtOrderConfig, error) {
449
+	config := models.XtOrderConfig{}
450
+	err := XTReadDB().Model(&config).Where("user_org_id = ? and status = 1", orgid).Find(&config).Error
451
+	if err == gorm.ErrRecordNotFound {
452
+		return nil, err
453
+	}
454
+	if err != nil {
455
+		return nil, err
456
+	}
457
+	return &config, nil
458
+}
459
+
460
+func GetOrderConfig(orgid int64) (models.XtOrderConfig, error) {
461
+	config := models.XtOrderConfig{}
462
+	err := XTReadDB().Where("user_org_id = ? and status = 1", orgid).Find(&config).Error
463
+	return config, err
464
+}
465
+
466
+func GetMonitorConfigById(orgid int64) (*models.XtMonitorConfig, error) {
467
+
468
+	config := models.XtMonitorConfig{}
469
+	err := XTReadDB().Model(&config).Where("user_org_id = ? and status = 1", orgid).Find(&config).Error
470
+	if err == gorm.ErrRecordNotFound {
471
+		return nil, err
472
+	}
473
+	if err != nil {
474
+		return nil, err
475
+	}
476
+	return &config, nil
477
+}
478
+
479
+func GetDrugAutoMaticList(orgid int64, warehouse_out_id int64, record_time int64, warehouse_out_order_number string) (auto []*models.VmDrugAutomaticReduceDetail, err error) {
480
+
481
+	db := XTReadDB().Table("xt_drug_automatic_reduce_detail as x").Where("x.status = 1")
482
+	err = db.Select("x.org_id,x.warehouse_out_id,x.record_time,x.drug_id,sum(x.count) as total").Where("x.org_id = ?  and x.record_time = ? and x.status= 1 and x.warehouse_out_order_number = ?", orgid, record_time, warehouse_out_order_number).Group("x.drug_id").Scan(&auto).Error
483
+	return auto, err
484
+
485
+}
486
+
487
+func GetAllBaseDrugList(orgid int64) (drug []*models.BaseDrugLib, err error) {
488
+
489
+	err = XTReadDB().Model(&drug).Where("org_id = ? and status = 1", orgid).Find(&drug).Error
490
+	return drug, err
491
+}
492
+
493
+func GetDrugWarehuseOrderInfo(orgid int64) (drug []*models.DrugWarehouseInfo, err error) {
494
+
495
+	err = XTReadDB().Where("org_id = ? and status = 1", orgid).Group("drug_id").Find(&drug).Error
496
+	return drug, err
497
+}
498
+
499
+func GetDrugStockList(page int64, limit int64, keyword string, drugcategory int64, startime int64, endtime int64, orgid int64) (list []*models.StDrugWarehouseInfo, total int64, err error) {
500
+	offset := (page - 1) * limit
501
+	db := XTReadDB().Table("xt_drug_warehouse_info as x").Where("x.status = 1")
502
+	likeKey := "%" + keyword + "%"
503
+	if orgid > 0 {
504
+		db = db.Where("x.org_id = ?", orgid)
505
+	}
506
+
507
+	if startime > 0 {
508
+		db = db.Where("x.ctime >=?", startime)
509
+	}
510
+	if endtime > 0 {
511
+		db = db.Where("x.ctime<=?", endtime)
512
+	}
513
+	if drugcategory > 0 && len(keyword) == 0 {
514
+		err = db.Select("x.id,x.warehousing_id,x.drug_id,x.number,x.product_date,x.expiry_date,x.warehousing_count,x.warehouseing_unit,x.stock_max_number,x.stock_min_number,x.price,x.total_price,x.dealer,x.remark,x.org_id,x.is_return,x.warehousing_order,x.type,x.retail_price,x.retail_total_price,x.batch_number,t.drug_name,t.drug_type,t.max_unit,t.min_unit,t.min_number,t.dose,t.dose_unit,t.last_price,t.manufacturer").Joins("left join xt_base_drug as t on t.id = x.drug_id and t.org_id =?", orgid).Where("t.drug_type = ?", drugcategory).Group("x.drug_id").Count(&total).Offset(offset).Limit(limit).Order("x.ctime desc").Scan(&list).Error
515
+		return
516
+	}
517
+	if drugcategory <= 0 && len(keyword) == 0 {
518
+		err = db.Select("x.id,x.warehousing_id,x.drug_id,x.number,x.product_date,x.expiry_date,x.warehousing_count,x.warehouseing_unit,x.stock_max_number,x.stock_min_number,x.price,x.total_price,x.dealer,x.remark,x.org_id,x.is_return,x.warehousing_order,x.type,x.retail_price,x.retail_total_price,x.batch_number,t.drug_name,t.drug_type,t.max_unit,t.min_unit,t.min_number,t.dose,t.dose_unit,t.last_price,t.manufacturer").Joins("left join xt_base_drug as t on t.id = x.drug_id and t.org_id = ?", orgid).Group("x.drug_id").Count(&total).Offset(offset).Limit(limit).Order("x.ctime desc").Scan(&list).Error
519
+		return
520
+	}
521
+
522
+	if len(keyword) > 0 && drugcategory == 0 {
523
+		err = db.Select("x.id,x.warehousing_id,x.drug_id,x.number,x.product_date,x.expiry_date,x.warehousing_count,x.warehouseing_unit,x.stock_max_number,x.stock_min_number,x.price,x.total_price,x.dealer,x.remark,x.org_id,x.is_return,x.warehousing_order,x.type,x.retail_price,x.retail_total_price,x.batch_number,t.drug_name,t.drug_type,t.max_unit,t.min_unit,t.min_number,t.dose,t.dose_unit,t.last_price,t.manufacturer").Joins("left join xt_base_drug as t on t.id = x.drug_id and t.org_id=?", orgid).Where("t.drug_name like ?", likeKey).Group("x.drug_id").Count(&total).Offset(offset).Limit(limit).Order("x.ctime desc").Scan(&list).Error
524
+		return
525
+	}
526
+	if len(keyword) <= 0 && drugcategory == 0 {
527
+		err = db.Select("x.id,x.warehousing_id,x.drug_id,x.number,x.product_date,x.expiry_date,x.warehousing_count,x.warehouseing_unit,x.stock_max_number,x.stock_min_number,x.price,x.total_price,x.dealer,x.remark,x.org_id,x.is_return,x.warehousing_order,x.type,x.retail_price,x.retail_total_price,x.batch_number,t.drug_name,t.drug_type,t.max_unit,t.min_unit,t.min_number,t.dose,t.dose_unit,t.last_price,t.manufacturer").Joins("left join xt_base_drug as t on t.id = x.drug_id and t.org_id = ?", orgid).Group("x.drug_id").Count(&total).Offset(offset).Limit(limit).Order("x.ctime desc").Scan(&list).Error
528
+		return
529
+	}
530
+
531
+	if len(keyword) > 0 && drugcategory > 0 {
532
+		err = db.Select("x.id,x.warehousing_id,x.drug_id,x.number,x.product_date,x.expiry_date,x.warehousing_count,x.warehouseing_unit,x.stock_max_number,x.stock_min_number,x.price,x.total_price,x.dealer,x.remark,x.org_id,x.is_return,x.warehousing_order,x.type,x.retail_price,x.retail_total_price,x.batch_number,t.drug_name,t.drug_type,t.max_unit,t.min_unit,t.min_number,t.dose,t.dose_unit,t.last_price,t.manufacturer").Joins("left join xt_base_drug as t on t.id = x.drug_id and t.org_id = ?", orgid).Where("t.drug_type = ? or t.drug_name like ?", drugcategory, likeKey).Group("x.drug_id").Count(&total).Offset(offset).Limit(limit).Order("x.ctime desc").Scan(&list).Error
533
+		return
534
+	}
535
+
536
+	return list, total, err
537
+}
538
+
539
+func GetAllBaseDurgListCount(page int64, limit int64, keyword string, drugcategory int64, startime int64, endtime int64, orgid int64) (drug []*models.VmBaseDrug, total int64, err error) {
540
+
541
+	offset := (page - 1) * limit
542
+	db := XTReadDB().Table("xt_base_drug").Where("status = 1")
543
+	likeKey := "%" + keyword + "%"
544
+	if orgid > 0 {
545
+		db = db.Where("org_id = ?", orgid)
546
+	}
547
+	if drugcategory > 0 {
548
+		db = db.Where("drug_type = ?", drugcategory)
549
+	}
550
+
551
+	if len(keyword) > 0 {
552
+		db = db.Where("drug_name like ?", likeKey)
553
+	}
554
+
555
+	err = db.Count(&total).Offset(offset).Limit(limit).Order("ctime desc").Preload("DrugWarehouseInfo", "status=1 and org_id = ? and ctime >=? and ctime<=?", orgid, startime, endtime).Preload("DrugCancelStockInfo", "status=1 and org_id = ? and ctime >=? and ctime<=?", orgid, startime, endtime).Preload("DrugWarehouseOutInfo", "status=1 and org_id = ? and ctime >=? and ctime<=?", orgid, startime, endtime).Find(&drug).Error
556
+	return drug, total, err
557
+}
558
+
559
+func GetDrugStockFlow(drugid int64, startime int64, endtime int64, page int64, limit int64, orgid int64) (list []*models.StDrugWarehouseInfo, total int64, err error) {
560
+
561
+	db := XTReadDB().Table("xt_drug_warehouse_info as x").Where("x.status = 1")
562
+	table := XTReadDB().Table("xt_base_drug as t").Where("t.status =1 ")
563
+	fmt.Println(table)
564
+	offset := (page - 1) * limit
565
+	if startime > 0 {
566
+		db = db.Where("x.ctime >=?", startime)
567
+	}
568
+	if endtime > 0 {
569
+		db = db.Where("x.ctime<=?", endtime)
570
+	}
571
+
572
+	if orgid > 0 {
573
+		db = db.Where("x.org_id = ?", orgid)
574
+	}
575
+
576
+	if drugid > 0 {
577
+		db = db.Where("x.drug_id = ?", drugid)
578
+	}
579
+
580
+	err = db.Joins("left join xt_base_drug as t on t.id = x.drug_id and t.status = 1 and t.org_id = ?", orgid).Select("x.id,x.warehousing_id,x.drug_id,x.number,x.product_date,x.expiry_date,x.warehousing_count,x.warehouseing_unit,x.max_unit,x.min_unit,x.stock_max_number,x.stock_min_number,x.price,x.total_price,x.dealer,x.remark,x.org_id,x.is_return,x.warehousing_order,x.type,x.retail_price,x.retail_total_price,x.batch_number,x.ctime,t.drug_name,t.drug_type,t.max_unit,t.min_unit,t.min_number,t.dose,t.dose_unit,t.last_price,t.manufacturer").Offset(offset).Count(&total).Order("x.ctime desc").Scan(&list).Error
581
+	return list, total, err
582
+}
583
+
584
+func GetDrugStockOutFlow(drugid int64, startime int64, endtime int64, page int64, limit int64, orgid int64, stocktype int64) (list []*models.VmDrugWarehouseOutInfo, total int64, err error) {
585
+
586
+	db := XTReadDB().Table("xt_drug_warehouse_out_info as x").Where("x.status = 1")
587
+	table := XTReadDB().Table("xt_base_drug as t").Where("t.status = 1")
588
+	fmt.Println(table)
589
+	offset := (page - 1) * limit
590
+	if startime > 0 {
591
+		db = db.Where("x.ctime >=?", startime)
592
+	}
593
+	if endtime > 0 {
594
+		db = db.Where("x.ctime<=?", endtime)
595
+	}
596
+
597
+	if orgid > 0 {
598
+		db = db.Where("x.org_id = ?", orgid)
599
+	}
600
+
601
+	if drugid > 0 {
602
+		db = db.Where("x.drug_id = ?", drugid)
603
+	}
604
+	if stocktype == 1 {
605
+		db = db.Where("x.is_sys = 0")
606
+	}
607
+	if stocktype == 2 {
608
+		db = db.Where("x.is_sys = 1")
609
+	}
610
+	err = db.Select("x.id,x.warehouse_out_id,x.drug_id,x.warehousing_out_target,x.count,x.price,x.total_price,x.product_date,x.expiry_date,x.org_id,x.remark,x.is_cancel,x.warehouse_out_order_number,x.type,x.dealer,x.manufacturer,x.is_sys,x.sys_record_time,x.retail_price,x.retail_total_price,x.warehouse_info_id,x.ctime,x.batch_number,x.count_unit,t.drug_name,t.drug_type,t.min_number,t.min_unit,t.max_unit").Joins("left join xt_base_drug as t on t.id = x.drug_id").Count(&total).Offset(offset).Limit(limit).Order("x.ctime desc").Scan(&list).Error
611
+	return list, total, err
612
+}
613
+
614
+func GetBatchOrderDetail(drugid int64, orgid int64, page int64, limit int64) (drug []*models.DrugWarehouseInfo, total int64, err error) {
615
+	offset := (page - 1) * limit
616
+	err = XTReadDB().Model(&drug).Where("drug_id = ? and org_id = ?", drugid, orgid).Count(&total).Offset(offset).Limit(limit).Find(&drug).Error
617
+	return drug, total, err
618
+}
619
+
620
+func GetDrugCountList(startime int64, endtime int64, orgid int64) (info []*models.VmDrugWarehouseInfo, err error) {
621
+
622
+	db := XTReadDB().Table("xt_drug_warehouse_info as x").Where("x.status = 1")
623
+
624
+	if startime > 0 {
625
+		db = db.Where("x.ctime >=?", startime)
626
+	}
627
+	if endtime > 0 {
628
+		db = db.Where("x.ctime<=?", endtime)
629
+	}
630
+	if orgid > 0 {
631
+		db = db.Where("x.org_id = ?", orgid)
632
+	}
633
+	err = db.Select("sum(x.warehousing_count) as count,x.drug_id").Group("x.drug_id").Scan(&info).Error
634
+	return info, err
635
+}
636
+
637
+func GetMinCountList(startime int64, endtime int64, orgid int64) (info []*models.VmDrugWarehouseInfo, err error) {
638
+	db := XTReadDB().Table("xt_drug_warehouse_info as x").Where("x.status = 1")
639
+
640
+	if startime > 0 {
641
+		db = db.Where("x.ctime >=?", startime)
642
+	}
643
+	if endtime > 0 {
644
+		db = db.Where("x.ctime<=?", endtime)
645
+	}
646
+	if orgid > 0 {
647
+		db = db.Where("x.org_id = ?", orgid)
648
+	}
649
+	err = db.Select("sum(x.stock_min_number) as count,x.drug_id").Group("x.drug_id").Scan(&info).Error
650
+	return info, err
651
+}
652
+
653
+func GetOutDrugCountList(startime int64, endtime int64, orgid int64) (info []*models.VmDrugWarehouseInfo, err error) {
654
+	db := XTReadDB().Table("xt_drug_warehouse_out_info as x").Where("x.status = 1")
655
+
656
+	if startime > 0 {
657
+		db = db.Where("x.ctime >=?", startime)
658
+	}
659
+	if endtime > 0 {
660
+		db = db.Where("x.ctime<=?", endtime)
661
+	}
662
+	if orgid > 0 {
663
+		db = db.Where("x.org_id = ?", orgid)
664
+	}
665
+	err = db.Select("x.count,x.drug_id,x.count_unit").Find(&info).Error
666
+	return info, err
667
+}
668
+
669
+func GetAutoDrugCountList(startime int64, endtime int64, orgid int64) (info []*models.DrugAutomaticReduceDetail, err error) {
670
+	db := XTReadDB().Table("xt_drug_automatic_reduce_detail as x").Where("x.status = 1")
671
+
672
+	if startime > 0 {
673
+		db = db.Where("x.record_time >=?", startime)
674
+	}
675
+	if endtime > 0 {
676
+		db = db.Where("x.record_time<=?", endtime)
677
+	}
678
+	if orgid > 0 {
679
+		db = db.Where("x.org_id = ?", orgid)
680
+	}
681
+	err = db.Select("x.count,x.drug_id,x.count_unit").Find(&info).Error
682
+	return info, err
683
+
684
+}
685
+
686
+func GetCancelDrugCountList(startime int64, endtime int64, orgid int64) (info []*models.DrugCancelStockInfo, err error) {
687
+
688
+	db := XTReadDB().Table(" xt_drug_cancel_stock_info as x").Where("x.status = 1")
689
+
690
+	if startime > 0 {
691
+		db = db.Where("x.ctime >=?", startime)
692
+	}
693
+	if endtime > 0 {
694
+		db = db.Where("x.ctime<=?", endtime)
695
+	}
696
+	if orgid > 0 {
697
+		db = db.Where("x.org_id = ?", orgid)
698
+	}
699
+	err = db.Select("sum(x.count) as count,x.drug_id").Group("x.drug_id").Scan(&info).Error
700
+	return info, err
701
+}
702
+
703
+func GetAllCountList(startime int64, endtime int64, orgid int64) (info []*models.DrugWarehouseInfo, err error) {
704
+	db := XTReadDB().Table("xt_drug_warehouse_info as x").Where("x.status = 1")
705
+
706
+	if startime > 0 {
707
+		db = db.Where("x.ctime >=?", startime)
708
+	}
709
+	if endtime > 0 {
710
+		db = db.Where("x.ctime<=?", endtime)
711
+	}
712
+	if orgid > 0 {
713
+		db = db.Where("x.org_id = ?", orgid)
714
+	}
715
+	err = db.Find(&info).Error
716
+	return info, err
717
+}
718
+
719
+func GetSingleOrderDetail(id int64, orgid int64) (info []*models.VmDrugWarehouseOutInfo, err error) {
720
+
721
+	db := XTReadDB().Table("xt_drug_warehouse_out_info as x").Where("x.status = 1")
722
+	table := XTReadDB().Table("xt_base_drug as t").Where("t.status = 1")
723
+	fmt.Println(table)
724
+	if orgid > 0 {
725
+		db = db.Where("x.org_id = ?", orgid)
726
+	}
727
+	if id > 0 {
728
+		db = db.Where("x.warehouse_out_id = ?", id)
729
+	}
730
+
731
+	err = db.Select("x.id,x.warehouse_out_id,x.drug_id,sum(x.count) as count,x.count_unit,x.price,x.total_price,x.product_date,x.expiry_date,x.remark,x.is_cancel,x.warehouse_out_order_number,x.type,x.dealer,t.manufacturer,x.is_sys,x.sys_record_time,x.retail_price,x.retail_total_price,t.drug_name,t.drug_type,t.max_unit,t.min_unit,t.min_number,x.number,x.batch_number,t.dose,t.dose_unit,t.last_price,t.min_price").Joins("left join xt_base_drug as t on t.id = x.drug_id").Group("x.drug_id").Scan(&info).Error
732
+	return info, err
733
+}
734
+
735
+func GetDrugStockFlowDetail(id int64, orgid int64) (drugflow []*models.XtDrugAutomaticReduceDetail, err error) {
736
+
737
+	err = XTReadDB().Where("record_time = ? and org_id = ? and status = 1", id, orgid).Find(&drugflow).Error
738
+	return drugflow, err
739
+}
740
+
741
+func GetAllSingleDrugDetail(id int64, orgid int64) (outInfo []*models.VmDrugWarehouseOutInfo, err error) {
742
+
743
+	db := XTReadDB().Table("xt_drug_warehouse_out_info as x").Where("x.status = 1")
744
+	table := XTReadDB().Table("xt_base_drug as t").Where("t.status = 1")
745
+	fmt.Println(table)
746
+	if orgid > 0 {
747
+		db = db.Where("x.org_id = ?", orgid)
748
+	}
749
+	if id > 0 {
750
+		db = db.Where("x.warehouse_out_id = ?", id)
751
+	}
752
+
753
+	err = db.Select("x.id,x.warehouse_out_id,x.drug_id,x.count,x.count_unit,x.price,x.total_price,x.product_date,x.expiry_date,x.remark,x.is_cancel,x.warehouse_out_order_number,x.type,x.dealer,t.manufacturer,x.is_sys,x.sys_record_time,x.retail_price,x.retail_total_price,t.drug_name,t.drug_type,t.max_unit,t.min_unit,t.min_number,x.number,x.batch_number,t.dose,t.dose_unit,t.last_price,t.min_price").Joins("left join xt_base_drug as t on t.id = x.drug_id").Scan(&outInfo).Error
754
+	return outInfo, err
755
+}
756
+
757
+func FindDrugStockUserDetailByIdThree(id int64, record_time int64, org_id int64) (user []*DrugAutomaticReduceDetail, err error, total int64) {
758
+
759
+	db := readDb.Model(&user)
760
+	db = db.Preload("Drug", "org_id = ? AND status = 1", org_id)
761
+	db = db.Preload("Patients", "user_org_id = ? AND status = 1", org_id)
762
+	db = db.Preload("DrugWarehouseOutInfo", "drug_id = ? and sys_record_time = ? and status = 1 and org_id = ?", id, record_time, org_id)
763
+	db = db.Where("status = 1 AND org_id = ? AND drug_id = ? AND record_time =?", org_id, id, record_time)
764
+	db = db.Count(&total)
765
+	err = db.Find(&user).Error
766
+	return user, err, total
767
+}
768
+
769
+func FindeDrugWarehouserInfo(ware_out_id int64, drug_id int64, orgid int64) (outInfo []*models.DrugWarehouseOutInfo, err error) {
770
+
771
+	err = XTReadDB().Where("warehouse_out_id = ? and drug_id = ? and org_id = ? and status = 1", ware_out_id, drug_id, orgid).Find(&outInfo).Error
772
+
773
+	return outInfo, err
774
+}
775
+
776
+func GetDrugFlowBatch(ware_out_id int64, drug_id int64, orgid int64) (flow []*models.DrugFlow, err error) {
777
+
778
+	err = XTReadDB().Where("warehouse_out_id = ? and drug_id = ? and user_org_id = ? and status = 1", ware_out_id, drug_id, orgid).Find(&flow).Error
779
+	return flow, err
780
+}

+ 48 - 0
service/his_config_service.go Bestand weergeven

@@ -0,0 +1,48 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_New/models"
5
+	"time"
6
+)
7
+
8
+func GetHisPrescriptionTemplatesList(patient_id int64, org_id int64, page int64, limit int64) (templates []*models.HisPrescriptionTemplate, total int64, err error) {
9
+	offset := (page - 1) * limit
10
+	db := readDb.Model(&models.HisPrescriptionTemplate{}).Where("user_org_id = ? AND patient_id= ? AND status = 1", org_id, patient_id)
11
+	err = db.Count(&total).Offset(offset).Limit(limit).Find(&templates).Error
12
+	return
13
+}
14
+
15
+func GetHisPrescriptionTemplateByID(template_id int64) (prescription models.HisPrescriptionTemplate, err error) {
16
+	err = readDb.Model(&models.HisPrescriptionTemplate{}).Where("id = ? AND status = 1 ", template_id).First(&prescription).Error
17
+	return
18
+}
19
+
20
+func SaveHisPrescriptionTemplate(template *models.HisPrescriptionTemplate) (err error) {
21
+	err = writeDb.Save(&template).Error
22
+	return
23
+
24
+}
25
+
26
+func DelelteHisPrescriptionInfoTemplate(id int64, user_org_id int64) (err error) {
27
+	err = writeDb.Model(&models.HisPrescriptionInfoTemplate{}).Where("user_org_id = ? AND id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
28
+	err = writeDb.Model(&models.HisPrescriptionAdviceTemplate{}).Where("user_org_id = ? AND prescription_id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
29
+	err = writeDb.Model(&models.HisPrescriptionProjectTemplate{}).Where("user_org_id = ? AND prescription_id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
30
+	return
31
+}
32
+
33
+func DelelteHisPrescriptionTemplate(id int64, user_org_id int64) (err error) {
34
+	err = writeDb.Model(&models.HisPrescriptionTemplate{}).Where("user_org_id = ? AND id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0}).Error
35
+	err = writeDb.Model(&models.HisPrescriptionInfoTemplate{}).Where("user_org_id = ? AND id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
36
+	return
37
+}
38
+
39
+func DelelteHisPrescriptionAdviceTemplate(id int64, user_org_id int64) (err error) {
40
+	err = writeDb.Model(&models.HisPrescriptionAdviceTemplate{}).Where("user_org_id = ? AND id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
41
+	return
42
+}
43
+
44
+func DelelteHisPrescriptionProjectTemplate(id int64, user_org_id int64) (err error) {
45
+	err = writeDb.Model(&models.HisPrescriptionProjectTemplate{}).Where("user_org_id = ? AND id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
46
+
47
+	return
48
+}

+ 174 - 0
service/his_hospital_service.go Bestand weergeven

@@ -0,0 +1,174 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_New/models"
5
+	"github.com/jinzhu/gorm"
6
+)
7
+
8
+type HospitalPatient struct {
9
+	ID                     int64                         `gorm:"column:id" json:"id" form:"id"`
10
+	UserOrgId              int64                         `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
11
+	Name                   string                        `gorm:"column:name" json:"name" form:"name"`
12
+	Status                 int64                         `gorm:"column:status" json:"status" form:"status"`
13
+	IdCardNo               string                        `gorm:"column:id_card_no" json:"id_card_no" form:"id_card_no"`
14
+	ScheduleType           int64                         `gorm:"column:schedule_type" json:"schedule_type" form:"schedule_type"`
15
+	Schedule               Schedule                      `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"schedule"`
16
+	HisHospitalCheckRecord models.HisHospitalCheckRecord `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"his_patient"`
17
+	VMHisPrescriptionInfo  VMHisPrescriptionInfo         `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"info"`
18
+	//HisHospitalOrder       models.HisHospitalOrder       `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"order"`
19
+}
20
+
21
+func (HospitalPatient) TableName() string {
22
+	return "xt_patients"
23
+}
24
+
25
+func GetHisHospitalPatientList(org_id int64, record_date int64) (patients []*HospitalPatient, err error) {
26
+	db := readDb.Model(&HospitalPatient{}).Where("xt_patients.user_org_id = ? AND xt_patients.status = 1", org_id)
27
+	db = db.Joins("join his_hospital_check_record as record ON record.patient_id = xt_patients.id AND record.status = 1 AND record.user_org_id = ? AND record.in_hospital_status = 1 AND record.out_hospital_status = 0", org_id)
28
+	db = db.Preload("HisHospitalCheckRecord", func(db *gorm.DB) *gorm.DB {
29
+		return db.Where("user_org_id = ? AND status = 1  AND in_hospital_status = 1 AND out_hospital_status = 0", org_id)
30
+	})
31
+	err = db.Preload("VMHisPrescriptionInfo", "user_org_id = ? AND status = 1 AND record_date = ? AND p_type = 1", org_id, record_date).Group("id").Find(&patients).Error
32
+	return
33
+}
34
+
35
+func GetNewAllChargeHisHospitalPatientList(org_id int64, record_date int64) (patients []*HospitalPatient, err error) {
36
+	db := readDb.Model(&HospitalPatient{}).Where("xt_patients.user_org_id = ? AND xt_patients.status = 1", org_id)
37
+	db = db.Joins("join his_hospital_check_record as hp ON hp.patient_id = xt_patients.id  AND hp.status = 1 AND hp.user_org_id = ? ", org_id)
38
+
39
+	db = db.Preload("HisHospitalCheckRecord", func(db *gorm.DB) *gorm.DB {
40
+		return db.Where("status = 1 AND user_org_id = ? AND in_hospital_status = 1", org_id).Preload("HisHospitalOrder", "user_org_id = ? AND status = 1", org_id)
41
+	})
42
+	//db = db.Preload("HisHospitalOrder", "user_org_id = ? AND status = 1 ", org_id)
43
+	err = db.Group("id").Find(&patients).Error
44
+	return
45
+}
46
+
47
+func GetNewHisHospitalPatientInfo(his_patient_id int64) (info models.HisHospitalCheckRecord, err error) {
48
+	err = readDb.Model(&models.HisHospitalCheckRecord{}).Where("id = ? AND status = 1 ", his_patient_id).First(&info).Error
49
+	return
50
+}
51
+
52
+func GetUnChargeHisHospitalPrescriptionFive(org_id int64, patient_id int64, his_patient_id int64, record_date int64) (prescription []*models.HisPrescription, err error) {
53
+	err = readDb.Model(&models.HisPrescription{}).
54
+		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
55
+			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("XtHisAddtionConfig", "status=1")
56
+		}).
57
+		Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
58
+			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("Drug", "status=1")
59
+		}).
60
+		Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
61
+			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("HisProject").Preload("GoodInfo", "status=1")
62
+		}).
63
+		Where("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ? AND order_status <> 2 AND order_status <> 3", org_id, record_date, patient_id).
64
+		Find(&prescription).Error
65
+	return
66
+}
67
+
68
+func GetChargeHisHospitalPrescriptionFive(org_id int64, patient_id int64, his_patient_id int64, record_date int64) (prescription []*models.HisPrescription, err error) {
69
+	err = readDb.Model(&models.HisPrescription{}).
70
+		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
71
+			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("XtHisAddtionConfig", "status=1")
72
+		}).
73
+		Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
74
+			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("Drug", "status=1")
75
+		}).
76
+		Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
77
+			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("HisProject").Preload("GoodInfo", "status=1")
78
+		}).
79
+		Where("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ? AND order_status = 2 ", org_id, record_date, patient_id).
80
+		Find(&prescription).Error
81
+	return
82
+}
83
+
84
+//
85
+type VMHospitalPatient struct {
86
+	ID                     int64                         `gorm:"column:id" json:"id" form:"id"`
87
+	UserOrgId              int64                         `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
88
+	Name                   string                        `gorm:"column:name" json:"name" form:"name"`
89
+	Status                 int64                         `gorm:"column:status" json:"status" form:"status"`
90
+	IdCardNo               string                        `gorm:"column:id_card_no" json:"id_card_no" form:"id_card_no"`
91
+	ScheduleType           int64                         `gorm:"column:schedule_type" json:"schedule_type" form:"schedule_type"`
92
+	Schedule               Schedule                      `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"schedule"`
93
+	HisHospitalCheckRecord models.HisHospitalCheckRecord `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"his_patient"`
94
+	VMHisPrescriptionInfo  VMHisPrescriptionInfo         `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"info"`
95
+}
96
+
97
+func (VMHospitalPatient) TableName() string {
98
+	return "xt_patients"
99
+}
100
+
101
+//
102
+//
103
+//func GetHisHospitalPatientPrescriptionList(org_id int64, record_date int64,page int64, limit int64) (patients []*HospitalPatient, err error) {
104
+//	offset := (page - 1) * limit
105
+//	db := readDb.Model(&HospitalPatient{}).Where("xt_patients.user_org_id = ? AND xt_patients.status = 1", org_id)
106
+//	db = db.Joins("join his_hospital_check_record as record ON record.patient_id = xt_patients.id AND record.status = 1 AND record.user_org_id = ?", org_id)
107
+//	db = db.Preload("HisHospitalCheckRecord", func(db *gorm.DB) *gorm.DB {
108
+//		return db.Where("user_org_id = ? AND status = 1  AND in_hospital_status = 1 AND out_hospital_status = 0", org_id)
109
+//	})
110
+//	err = db.Preload("VMHisPrescriptionInfo", "user_org_id = ? AND status = 1 AND record_date = ? AND p_type = 1", org_id, record_date).Group("id").Find(&patients).Error
111
+//	return
112
+//}
113
+
114
+//
115
+//func GetHisHospitalPatientPrescriptionList(org_id int64, keywords string, record_date int64, page int64, limit int64) (patients []*VMSchedule, err error, total int64) {
116
+//	offset := (page - 1) * limit
117
+//	db := readDb.Model(&VMHospitalPatient{}).Where("user_org_id = ? AND status = 1", org_id)
118
+//	if len(keywords) > 0 {
119
+//	wkkk	keywords = "%" + keywords + "%"
120
+//		db = db.Joins("JOIN xt_patients as p On xt_schedule.patient_id = p.id AND p.user_org_id = ? AND p.name like ?", org_id, keywords)
121
+//		db = db.Joins("JOIN his_prescription_info as info On xt_schedule.patient_id = info.patient_id  AND info.user_org_id = ? AND  info.record_date = ? AND info.prescription_number like ? AND info.p_type == 1", org_id, record_date, keywords)
122
+//	}
123
+//	db = db.Preload("Patients", "user_org_id = ? AND status = 1", org_id)
124
+//	db = db.Preload("HisPatient", "user_org_id = ? AND status = 1", org_id)
125
+//	db = db.Preload("HisPrescription", "user_org_id = ? AND status = 1 AND p_type == 1", org_id).
126
+//		Preload("VMHisPrescriptionInfo", "user_org_id = ? AND status = 1 AND p_type == 1", org_id)
127
+//	db = db.Count(&total)
128
+//	err = db.Limit(limit).Offset(offset).Find(&patients).Error
129
+//	return
130
+//}
131
+
132
+type VMHisHospitalPrescriptionInfo struct {
133
+	ID                 int64              `gorm:"column:id" json:"id" form:"id"`
134
+	UserOrgId          int64              `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
135
+	RecordDate         int64              `gorm:"column:record_date" json:"record_date" form:"record_date"`
136
+	PatientId          int64              `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
137
+	HisPatientId       int64              `gorm:"column:his_patient_id" json:"his_patient_id" form:"his_patient_id"`
138
+	Status             int64              `gorm:"column:status" json:"status" form:"status"`
139
+	Ctime              int64              `gorm:"column:ctime" json:"ctime" form:"ctime"`
140
+	Mtime              int64              `gorm:"column:mtime" json:"mtime" form:"mtime"`
141
+	Creator            int64              `gorm:"column:creator" json:"creator" form:"creator"`
142
+	Modifier           int64              `gorm:"column:modifier" json:"modifier" form:"modifier"`
143
+	Diagnosis          string             `gorm:"column:diagnosis" json:"diagnosis" form:"diagnosis"`
144
+	RegisterType       int64              `gorm:"column:register_type" json:"register_type" form:"register_type"`
145
+	Doctor             string             `gorm:"column:doctor" json:"doctor" form:"doctor"`
146
+	Departments        string             `gorm:"column:departments" json:"departments" form:"departments"`
147
+	SickHistory        string             `gorm:"column:sick_history" json:"sick_history" form:"sick_history"`
148
+	PrescriptionNumber string             `gorm:"column:prescription_number" json:"prescription_number" form:"prescription_number"`
149
+	BatchNumber        string             `gorm:"column:batch_number" json:"batch_number" form:"batch_number"`
150
+	PrescriptionStatus int64              `gorm:"column:prescription_status" json:"prescription_status" form:"prescription_status"`
151
+	DoctorId           int64              `gorm:"column:doctor_id" json:"doctor_id" form:"doctor_id"`
152
+	DepartmentId       int64              `gorm:"column:department_id" json:"department_id" form:"department_id"`
153
+	SickType           int64              `gorm:"column:sick_type" json:"sick_type" form:"sick_type"`
154
+	Patients           Patients           `gorm:"ForeignKey:ID;AssociationForeignKey:PatientId" json:"patients"`
155
+	HisPrescription    []*HisPrescription `gorm:"ForeignKey:PatientId,RecordDate;AssociationForeignKey:PatientId,RecordDate" json:"prescription"`
156
+}
157
+
158
+func (VMHisHospitalPrescriptionInfo) TableName() string {
159
+	return "his_prescription_info"
160
+}
161
+
162
+func GetHisHospitalPatientPrescriptionList(org_id int64, keywords string, record_date int64, page int64, limit int64) (patients []*VMHisHospitalPrescriptionInfo, err error, total int64) {
163
+	offset := (page - 1) * limit
164
+	db := readDb.Model(&VMHisHospitalPrescriptionInfo{}).Where("user_org_id = ? AND status = 1 AND record_date = ? AND p_type = 1 ", org_id, record_date)
165
+	if len(keywords) > 0 {
166
+		keywords = "%" + keywords + "%"
167
+		db = db.Joins("JOIN xt_patients as p On his_prescription_info.patient_id = p.id AND p.user_org_id = ? AND p.name like ?", org_id, keywords)
168
+	}
169
+	db = db.Preload("Patients", "user_org_id = ? AND status = 1", org_id)
170
+	db = db.Preload("HisPrescription", "user_org_id = ? AND status = 1 AND p_type = 1", org_id)
171
+	db = db.Count(&total)
172
+	err = db.Limit(limit).Offset(offset).Find(&patients).Error
173
+	return
174
+}

+ 750 - 0
service/his_project_service.go Bestand weergeven

@@ -0,0 +1,750 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_New/models"
5
+	"github.com/jinzhu/gorm"
6
+	"time"
7
+)
8
+
9
+func GetHisProjectIsExist(projectName string, orgid int64) (*models.XtHisProject, error) {
10
+
11
+	var project models.XtHisProject
12
+	var err error
13
+	err = XTReadDB().Model(&project).Where("project_name = ? and user_org_id = ? and status = 1", projectName, orgid).Find(&project).Error
14
+	if err == gorm.ErrRecordNotFound {
15
+		return nil, err
16
+	}
17
+
18
+	if err != nil {
19
+		return nil, err
20
+	}
21
+
22
+	return &project, nil
23
+}
24
+
25
+func CreateHisProject(project *models.XtHisProject) error {
26
+
27
+	err := XTWriteDB().Model(&project).Create(&project).Error
28
+	return err
29
+}
30
+
31
+func GetHisProjectList(orgid int64, limit int64, page int64, charge int64, start int64, keyword string, isMark int64) (hisproject []*models.XtHisProject, total int64, err error) {
32
+	offset := (page - 1) * limit
33
+	likeKey := "%" + keyword + "%"
34
+	db := XTReadDB().Table("xt_his_project as x").Where("x.status = 1")
35
+	if orgid > 0 {
36
+		db = db.Where("x.user_org_id = ?", orgid)
37
+	}
38
+	if start > 0 {
39
+		db = db.Where("x.medical_status = ?", start)
40
+	}
41
+	if charge > 0 {
42
+		db = db.Where("x.is_estimate = ? ", charge)
43
+	}
44
+	if len(keyword) > 0 {
45
+		db = db.Where("x.project_name like ?", likeKey)
46
+	}
47
+	if isMark > 0 {
48
+		db = db.Where("x.is_mark = ?", isMark)
49
+	}
50
+	err = db.Select("x.id,x.project_name,x.pinyin,x.wubi,x.price,x.unit,x.cost_classify,x.executive_section,x.medical_coverage,x.statistical_classification,x.disease_directory,x.is_record,x.medical_code,x.tube_color,x.medical_status,x.remark,x.sign,x.default_number,x.is_default,x.is_charge,x.is_estimate,x.is_workload,x.sort,x.doctor_advice,x.user_org_id,x.status,x.created_time,x.is_mark").Count(&total).Offset(offset).Limit(limit).Order("created_time desc").Find(&hisproject).Error
51
+	return hisproject, total, err
52
+}
53
+
54
+func GetProjectDetail(id int64) (models.XtHisProject, error) {
55
+	project := models.XtHisProject{}
56
+	err := XTReadDB().Model(&project).Where("id=? and status = 1", id).Find(&project).Error
57
+	return project, err
58
+}
59
+
60
+func UpdatedProject(id int64, pro *models.XtHisProject) error {
61
+
62
+	err := XTWriteDB().Model(&pro).Where("id=?", id).Updates(map[string]interface{}{"project_name": pro.ProjectName, "pinyin": pro.Pinyin, "wubi": pro.Pinyin, "price": pro.Price, "unit": pro.Unit, "cost_classify": pro.CostClassify, "executive_section": pro.ExecutiveSection, "medical_coverage": pro.MedicalCoverage, "statistical_classification": pro.StatisticalClassification, "disease_directory": pro.DiseaseDirectory, "is_record": pro.IsRecord, "medical_code": pro.MedicalCode, "tube_color": pro.TubeColor, "medical_status": pro.MedicalStatus, "remark": pro.Remark, "sign": pro.Sign, "default_number": pro.DefaultNumber, "is_default": pro.IsDefault, "is_charge": pro.IsCharge, "is_estimate": pro.IsEstimate, "is_workload": pro.IsWorkload, "sort": pro.Sort, "doctor_advice": pro.DoctorAdvice, "single_dose": pro.SingleDose, "execution_frequency": pro.ExecutionFrequency, "delivery_way": pro.DeliveryWay, "number_days": pro.NumberDays, "total": pro.Total, "updated_time": pro.UpdatedTime, "category": pro.Category, "specail_project": pro.SpecailProject, "social_security_directory_code": pro.SocialSecurityDirectoryCode, "record_date": pro.RecordDate}).Error
63
+	return err
64
+}
65
+
66
+func DeleteHisProject(id int64) error {
67
+	project := models.XtHisProject{}
68
+	err := XTWriteDB().Model(&project).Where("id=?", id).Updates(map[string]interface{}{"status": 0}).Error
69
+	return err
70
+}
71
+
72
+func GetHisProjectByNameOne(projectName string, orgid int64) (*models.XtHisProjectTeam, error) {
73
+
74
+	projectTeam := models.XtHisProjectTeam{}
75
+	err := XTReadDB().Model(&projectTeam).Where("project_team = ? and user_org_id = ? and status = 1", projectName, orgid).First(&projectTeam).Error
76
+	if err != nil {
77
+		if err == gorm.ErrRecordNotFound {
78
+			return nil, err
79
+		} else {
80
+			return nil, err
81
+		}
82
+	}
83
+	return &projectTeam, nil
84
+
85
+}
86
+
87
+func CreatedProjectTeam(team *models.XtHisProjectTeam) error {
88
+
89
+	err := XTWriteDB().Model(&team).Create(&team).Error
90
+	return err
91
+}
92
+
93
+func GetProjectTeamList(limit int64, page int64, orgid int64, keyword string) (projectTeam []*models.XtHisProjectTeam, total int64, err error) {
94
+	offset := (page - 1) * limit
95
+	likeKey := "%" + keyword + "%"
96
+	db := XTReadDB().Model(&projectTeam)
97
+	if len(keyword) > 0 {
98
+		db = db.Where("project_team like ?", likeKey)
99
+	}
100
+	err = db.Where("user_org_id = ? and status = 1", orgid).Count(&total).Offset(offset).Limit(limit).Order("created_time desc").Find(&projectTeam).Error
101
+	return projectTeam, total, err
102
+}
103
+
104
+func GetProjectTeamDetail(id int64) (models.XtHisProjectTeam, error) {
105
+
106
+	projectTeam := models.XtHisProjectTeam{}
107
+	err := XTReadDB().Model(&projectTeam).Where("id= ? and status = 1", id).Find(&projectTeam).Error
108
+	return projectTeam, err
109
+}
110
+
111
+func UpdatedProjectTeam(id int64, team *models.XtHisProjectTeam) error {
112
+
113
+	err := XTWriteDB().Model(&team).Where("id=? and status = 1", id).Updates(map[string]interface{}{"project_team": team.ProjectTeam, "price": team.Price, "pinyin": team.Pinyin, "wubi": team.Wubi, "tube_color": team.TubeColor, "team_type": team.TeamType, "remark": team.Remark, "project_id": team.ProjectId, "item_id": team.ItemId}).Error
114
+	return err
115
+}
116
+
117
+func DeleteProjectTeam(id int64) error {
118
+
119
+	team := models.XtHisProjectTeam{}
120
+	err := XTWriteDB().Model(&team).Where("id = ? and status = 1", id).Updates(map[string]interface{}{"status": 0}).Error
121
+	return err
122
+}
123
+
124
+func CreateDePartment(department *models.XtHisDepartment) error {
125
+
126
+	err := XTWriteDB().Model(&department).Create(&department).Error
127
+	return err
128
+}
129
+
130
+func GetDepartMentList(limit int64, page int64, orgid int64) (departMent []*models.XtHisDepartment, total int64, err error) {
131
+
132
+	offset := (page - 1) * limit
133
+	err = XTReadDB().Model(&departMent).Where("user_org_id = ? and status = 1", orgid).Count(&total).Offset(offset).Limit(limit).Order("created_time desc").Find(&departMent).Error
134
+	return departMent, total, err
135
+}
136
+
137
+func GetDepartMentDetail(id int64) (models.XtHisDepartment, error) {
138
+
139
+	department := models.XtHisDepartment{}
140
+	err := XTReadDB().Model(&department).Where("id=? and status = 1", id).Find(&department).Error
141
+	return department, err
142
+}
143
+
144
+func UpdatedDepartment(id int64, department *models.XtHisDepartment) error {
145
+
146
+	err := XTWriteDB().Model(&department).Where("id=? and status = 1", id).Updates(map[string]interface{}{"name": department.Name, "number": department.Number, "updated_time": time.Now().Unix()}).Error
147
+	return err
148
+}
149
+
150
+func DeleteDepartment(id int64) error {
151
+	department := models.XtHisDepartment{}
152
+	err := XTReadDB().Model(&department).Where("id=? and status = 1", id).Updates(map[string]interface{}{"status": 0}).Error
153
+	return err
154
+}
155
+
156
+func GetBloodPatientList(orgid int64, startime int64) (schedule []*models.SchedulesVm, err error) {
157
+
158
+	db := XTReadDB().Table("xt_schedule as x").Where("x.status = 1")
159
+	if orgid > 0 {
160
+		db = db.Where("x.user_org_id = ?", orgid)
161
+	}
162
+	if startime > 0 {
163
+		db = db.Where("x.schedule_date = ?", startime)
164
+	}
165
+	err = db.Select("x.id,x.user_org_id,x.patient_id,x.schedule_date,x.schedule_type,x.schedule_week,x.mode_id,p.name,p.id_card_no").Joins("left join xt_patients as p on p.id = x.patient_id").Scan(&schedule).Error
166
+	return schedule, err
167
+}
168
+
169
+func GetHisPatient(orgid int64, recorddate int64) (paitent []*models.HisPatient, err error) {
170
+
171
+	err = XTReadDB().Model(&paitent).Where("user_org_id = ?  and record_date = ? and status = 1", orgid, recorddate).Find(&paitent).Error
172
+	return paitent, err
173
+}
174
+
175
+func GetHisPrescriptionOther(orgid int64, recorddate int64) (prescription []*models.HisPrescriptionVm, err error) {
176
+
177
+	db := XTReadDB().Table("his_prescription as x").Where("x.status = 1")
178
+	if orgid > 0 {
179
+		db = db.Where("x.user_org_id = ?", orgid)
180
+	}
181
+	if recorddate > 0 {
182
+		db = db.Where("x.record_date = ? ", recorddate)
183
+	}
184
+	err = db.Select("x.id,x.user_org_id,x.record_date,x.patient_id,x.his_patient_id,x.number,x.type,x.doctor,x.creator,x.modifier,t.name").Joins("left join his_patient as t on t.id = x.his_patient_id").Scan(&prescription).Error
185
+	return prescription, err
186
+}
187
+
188
+func GetHisPrescriptionByPatientId(id int64, recordate int64) (prescription []*models.HisPrescription, err error) {
189
+
190
+	err = XTReadDB().Model(&prescription).Where("his_patient_id = ? and record_date = ? and status= 1", id, recordate).Find(&prescription).Error
191
+	return prescription, err
192
+}
193
+
194
+func CreateAdditionalCharge(charge *models.HisAdditionalCharge) error {
195
+
196
+	err = XTWriteDB().Model(&charge).Save(&charge).Error
197
+	return err
198
+}
199
+
200
+func GetTreatmentList(id int64, startime int64) (prescription []*models.HisPrescription, err error) {
201
+
202
+	err = XTReadDB().Model(&prescription).Where("id = ? and record_date = ? and status = 1", id, startime).Find(&prescription).Error
203
+	return prescription, err
204
+}
205
+
206
+//func GetAllProjectList(orgid int64) (project []*models.XtHisProject, err error) {
207
+//
208
+//	err = XTReadDB().Model(&project).Where("user_org_id = ? and status = 1", orgid).Find(&project).Error
209
+//	return project, err
210
+//}
211
+
212
+func CreateProjectList(list *models.XtHisProjectList) error {
213
+
214
+	err := XTWriteDB().Model(&list).Create(&list).Error
215
+	return err
216
+}
217
+
218
+func GetHisProjectListByOrgId(orgid int64) (projectlist []*models.HisProjectListVm, err error) {
219
+
220
+	db := XTReadDB().Table("xt_his_project_list as x").Where("x.status = 1")
221
+	if orgid > 0 {
222
+		db = db.Where("x.user_org_id = ? ", orgid)
223
+	}
224
+	err = db.Select("x.id,x.number,x.user_org_id,x.project_id,t.price,t.unit,t.cost_classify,t.project_name").Joins("left join xt_his_project as t on t.id = x.project_id").Scan(&projectlist).Error
225
+	return projectlist, err
226
+}
227
+
228
+func GetHisPatientInformation(id int64) (models.HisPatient, error) {
229
+
230
+	patient := models.HisPatient{}
231
+	err := XTReadDB().Model(&patient).Where("id= ? and status = 1", id).Find(&patient).Error
232
+	return patient, err
233
+}
234
+
235
+func DeleteProjectList(id int64) error {
236
+	list := models.XtHisProjectList{}
237
+	err := XTWriteDB().Model(&list).Where("id=? and status = 1", id).Updates(map[string]interface{}{"status": 0}).Error
238
+	return err
239
+}
240
+
241
+func GetHisProject(orgid int64) (project []*models.XtHisProject, err error) {
242
+
243
+	err = XTReadDB().Model(&project).Where("user_org_id = ? and status =1", orgid).Find(&project).Error
244
+	return project, err
245
+}
246
+
247
+func GetProjectTeam(ids []string, orgid int64) (project []*models.XtHisProject, err error) {
248
+
249
+	err = XTReadDB().Model(&project).Where("user_org_id = ? and id in (?)", orgid, ids).Find(&project).Error
250
+	return project, err
251
+}
252
+
253
+func GetAllDepartMent(orgid int64) (department []*models.XtHisDepartment, err error) {
254
+
255
+	err = XTReadDB().Model(&department).Where("user_org_id = ? and status =1", orgid).Find(&department).Error
256
+	return department, err
257
+}
258
+
259
+func CreateHisPatient(patient *models.XtHisPatient) error {
260
+
261
+	err := XTReadDB().Model(&patient).Create(&patient).Error
262
+	return err
263
+}
264
+
265
+func UpdateHisPrescriptionHisID(his_patient_id int64, patient_id int64, record_time int64, org_id int64) {
266
+	XTWriteDB().Model(&models.HisPrescription{}).Where("record_date = ? AND user_org_id = ? AND patient_id = ? AND his_patient_id = 0", record_time, org_id, patient_id).Updates(map[string]interface{}{"his_patient_id": his_patient_id})
267
+	XTWriteDB().Model(&models.HisPrescriptionInfo{}).Where("record_date = ? AND user_org_id = ? AND patient_id = ?  AND his_patient_id = 0", record_time, org_id, patient_id).Updates(map[string]interface{}{"his_patient_id": his_patient_id})
268
+
269
+	return
270
+}
271
+
272
+func UpdateHisPrescriptionHisIDTwo(his_patient_id int64, patient_id int64, record_time int64, org_id int64, start_time int64) {
273
+	XTWriteDB().Model(&models.HisPrescription{}).Where("record_date <= ? AND record_date >= ? AND user_org_id = ? AND patient_id = ? AND his_patient_id = 0 AND order_status <> 2", record_time, start_time, org_id, patient_id).Updates(map[string]interface{}{"his_patient_id": his_patient_id})
274
+	XTWriteDB().Model(&models.HisPrescriptionInfo{}).Where("record_date = ? AND user_org_id = ? AND patient_id = ? AND his_patient_id = 0 AND order_status <> 2", record_time, start_time, org_id, patient_id).Updates(map[string]interface{}{"his_patient_id": his_patient_id})
275
+	return
276
+}
277
+
278
+func GetBloodPatientByIdCard(idcard string, orgid int64) (*models.XtPatients, error) {
279
+	var patients models.XtPatients
280
+	var err error
281
+	err = XTReadDB().Model(&patients).Where("id_card_no = ? and user_org_id = ? and status = 1", idcard, orgid).Find(&patients).Error
282
+	if err != nil {
283
+		if err == gorm.ErrRecordNotFound {
284
+			return nil, err
285
+		} else {
286
+			return nil, err
287
+		}
288
+	}
289
+	return &patients, nil
290
+}
291
+
292
+func GetAllProjectTeam(orgid int64) (project []*models.XtHisProjectTeam, err error) {
293
+
294
+	err = XTReadDB().Model(&project).Where("user_org_id = ? and status = 1", orgid).Find(&project).Error
295
+	return project, err
296
+}
297
+
298
+func GetProjectListById(orgid int64, ids []string) (project []*models.XtHisProjectList, err error) {
299
+	err = XTReadDB().Model(&project).Preload("XtHisProject", "status = 1").Preload("GoodInfo", "status=1").Where("user_org_id = ? and id in (?)", orgid, ids).Find(&project).Error
300
+	return project, err
301
+}
302
+
303
+func GetHisPatientHistory(keyword string, startime int64, endtime int64, registtype int64, limit int64, page int64, orgid int64) (hisPatient []*models.XtHisPatient, total int64, err error) {
304
+	offset := (page - 1) * limit
305
+	likeKey := "%" + keyword + "%"
306
+	db := XTReadDB().Table("his_patient as x")
307
+	if len(keyword) > 0 {
308
+		db = db.Where("x.name like ?", likeKey)
309
+	}
310
+	if startime > 0 {
311
+		db = db.Where("x.record_date >= ?", startime)
312
+	}
313
+	if endtime > 0 {
314
+		db = db.Where("x.record_date<=?", endtime)
315
+	}
316
+	if registtype > 0 {
317
+		db = db.Where("x.register_type = ?", registtype)
318
+	}
319
+	if orgid > 0 {
320
+		db = db.Where("x.user_org_id = ?", orgid)
321
+	}
322
+	err = db.Select("x.id,x.balance_accounts_type,x.medical_insurance_number,x.name,x.gender,x.id_type,x.medical_treatment_type,x.birthday,x.record_date,x.age,x.phone_number,x.id_card_no,x.register_type,x.admin_user_id,x.departments,x.is_need_cost_of_production,x.register_cost,x.treatment_cost,x.cost_of_production,x.total,x.user_org_id,x.patient_id,x.number,x.is_return,x.doctor,x.ctime,x.social_type,x.phone,x.status").Count(&total).Offset(offset).Limit(limit).Order("x.id desc").Find(&hisPatient).Error
323
+	return hisPatient, total, err
324
+}
325
+
326
+func ChangePatient(id int64) error {
327
+	patient := models.XtHisPatient{}
328
+
329
+	err := XTWriteDB().Model(&patient).Where("id = ?", id).Updates(map[string]interface{}{"is_return": 2}).Error
330
+	return err
331
+}
332
+
333
+func GetHisPrescriptionTwo(patientid int64, orgid int64, recorddate int64) (*models.HisPrescription, error) {
334
+	prescription := models.HisPrescription{}
335
+	err := XTReadDB().Model(&prescription).Where("his_patient_id = ? and user_org_id = ? and record_date = ? and status = 1", patientid, orgid, recorddate).Find(&prescription).Error
336
+	if err != nil {
337
+		if err == gorm.ErrRecordNotFound {
338
+			return nil, err
339
+		} else {
340
+			return nil, err
341
+		}
342
+	}
343
+	return &prescription, nil
344
+}
345
+
346
+func UpdatedHisPatient(hispatientid int64, orgid int64, recorddate int64) error {
347
+	hisPatient := models.HisPatient{}
348
+	err := XTWriteDB().Model(&hisPatient).Where("id = ? and user_org_id = ? and record_date = ?", hispatientid, orgid, recorddate).Updates(map[string]interface{}{"is_return": 3}).Error
349
+	return err
350
+}
351
+
352
+func GetBloodPatientInfoById(patientid int64) (models.XtPatients, error) {
353
+
354
+	patients := models.XtPatients{}
355
+	err := XTReadDB().Model(&patients).Where("id = ? and status = 1", patientid).Find(&patients).Error
356
+	return patients, err
357
+}
358
+
359
+func GetPatientCaseHistory(patientid int64) (models.HisPatientCaseHistory, error) {
360
+
361
+	history := models.HisPatientCaseHistory{}
362
+	err := XTReadDB().Model(&history).Where("patient_id = ? and status = 1", patientid).Last(&history).Error
363
+	return history, err
364
+}
365
+
366
+func GetBloodPatientByPatient(id int64) (models.XtPatients, error) {
367
+
368
+	patients := models.XtPatients{}
369
+	err := XTReadDB().Model(&patients).Where("id = ? and status = 1", id).Find(&patients).Error
370
+	return patients, err
371
+}
372
+
373
+func GetHisPatientByIdTwo(patientid int64) (models.XtHisPatient, error) {
374
+
375
+	patient := models.XtHisPatient{}
376
+	err := XTReadDB().Model(&patient).Where("patient_id = ? and status=1", patientid).Find(&patient).Error
377
+	return patient, err
378
+}
379
+
380
+func GetHisPatientById(patientid int64) (models.VMHisPatient, error) {
381
+	patient := models.VMHisPatient{}
382
+	err := XTReadDB().Model(&patient).Where("patient_id = ? and status = 1", patientid).Find(&patient).Error
383
+	return patient, err
384
+}
385
+
386
+func GetTemplateDetail(id int64) (models.HisCaseHistoryTemplate, error) {
387
+
388
+	template := models.HisCaseHistoryTemplate{}
389
+	err := XTReadDB().Model(&template).Where("id= ? and status = 1", id).Find(&template).Error
390
+	return template, err
391
+}
392
+
393
+func UpdateCaseHistoryTemplate(tem *models.HisCaseHistoryTemplate, id int64) error {
394
+
395
+	err := XTWriteDB().Model(&tem).Where("id = ? ", id).Updates(map[string]interface{}{"history_of_present_illness": tem.HistoryOfPresentIllness, "past_history": tem.PastHistory, "chief_conplaint": tem.ChiefConplaint, "personal_history": tem.PersonalHistory, "family_history": tem.FamilyHistory, "diagnostic": tem.Diagnostic, "template_name": tem.TemplateName, "template_remark": tem.TemplateRemark, "modifier": tem.Modifier, "doctor_advice": tem.DoctorAdvice, "remark": tem.Remark}).Error
396
+	return err
397
+}
398
+
399
+func GetHistPatient(orgid int64, keyword string) (hisPatient []*models.HisPatient, err error) {
400
+	likeKey := "%" + keyword + "%"
401
+	err = XTReadDB().Model(&hisPatient).Where("user_org_id = ? and name like ?", orgid, likeKey).Find(&hisPatient).Error
402
+	return hisPatient, err
403
+}
404
+
405
+func GetDoctorAdvicePrint(his_patient_id int64, recorddate int64, schIDs []string, orgid int64) (prescription []*models.HisPrescription, err error) {
406
+
407
+	err = XTReadDB().Model(&prescription).Where("patient_id = ? and record_date = ? and id in(?) and  status = 1 ", his_patient_id, recorddate, schIDs).Preload("Patients", "status = 1 and user_org_id = ?", orgid).Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
408
+		return db.Where("status = 1 and user_org_id = ?", orgid).Preload("Drug", "status = 1")
409
+	}).Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
410
+		return db.Where("status = 1 AND user_org_id = ?", orgid).Preload("HisProject").Preload("GoodInfo", "status=1")
411
+	}).Preload("HisPrescriptionInfo", "status =1 and user_org_id = ?", orgid).Preload("HisAdditionalCharge", "status = 1 and user_org_id = ?", orgid).Find(&prescription).Error
412
+
413
+	return prescription, err
414
+}
415
+
416
+func GetProjectPrint(his_patient_id int64) (models.HisPrescriptionProject, error) {
417
+	project := models.HisPrescriptionProject{}
418
+	err := XTReadDB().Model(&project).Where("his_patient_id = ? and status = 1", his_patient_id).Find(&project).Error
419
+	return project, err
420
+}
421
+
422
+func GetHisTemplateId(templateid int64, orgid int64) (*models.XtHisTemplate, error) {
423
+
424
+	template := models.XtHisTemplate{}
425
+	err := XTReadDB().Model(&template).Where("template_id = ? and user_org_id = ? and status = 1", templateid, orgid).Find(&template).Error
426
+	if err != nil {
427
+		if err == gorm.ErrRecordNotFound {
428
+			return nil, err
429
+		} else {
430
+			return nil, err
431
+		}
432
+	}
433
+	return &template, nil
434
+}
435
+
436
+func CreateHisTemplate(template *models.XtHisTemplate) error {
437
+
438
+	err := XTWriteDB().Create(&template).Error
439
+	return err
440
+}
441
+
442
+func UpdateHisTemplate(template *models.XtHisTemplate) error {
443
+
444
+	err := XTWriteDB().Save(&template).Error
445
+	return err
446
+}
447
+
448
+func GetHisPrintTemplate(orgid int64) (models.XtHisTemplate, error) {
449
+
450
+	template := models.XtHisTemplate{}
451
+	err := XTReadDB().Model(&template).Where("user_org_id = ? and status = 1", orgid).Find(&template).Error
452
+	return template, err
453
+}
454
+
455
+func GetPrescriptionTemplate(templateid int64, orgid int64) (*models.XtHisAdviceTemplate, error) {
456
+
457
+	template := models.XtHisAdviceTemplate{}
458
+	err := XTReadDB().Model(&template).Where("template_id = ? and user_org_id = ? and status = 1", templateid, orgid).Find(&template).Error
459
+	if err != nil {
460
+		if err == gorm.ErrRecordNotFound {
461
+			return nil, err
462
+		} else {
463
+			return nil, err
464
+		}
465
+	}
466
+	return &template, nil
467
+}
468
+
469
+func CreatePrescriptionTemplate(template *models.XtHisAdviceTemplate) error {
470
+
471
+	err = XTWriteDB().Create(&template).Error
472
+	return err
473
+}
474
+
475
+func UpdatePrescriptionTemplate(template *models.XtHisAdviceTemplate) error {
476
+
477
+	err := XTWriteDB().Save(&template).Error
478
+	return err
479
+}
480
+
481
+func GetPrescriptionTemplateById(orgid int64) (models.XtHisAdviceTemplate, error) {
482
+
483
+	template := models.XtHisAdviceTemplate{}
484
+	err := XTReadDB().Model(&template).Where("user_org_id = ? and status = 1", orgid).Find(&template).Error
485
+	return template, err
486
+}
487
+
488
+func GetTreatPrintTemplate(templateid int64, orgid int64) (*models.XtHisTreatmentTemplate, error) {
489
+
490
+	template := models.XtHisTreatmentTemplate{}
491
+	err := XTReadDB().Model(&template).Where("template_id = ? and user_org_id = ? and status = 1", templateid, orgid).Find(&template).Error
492
+	if err != nil {
493
+		if err == gorm.ErrRecordNotFound {
494
+			return nil, err
495
+		} else {
496
+			return nil, err
497
+		}
498
+	}
499
+	return &template, nil
500
+}
501
+
502
+func CreateTreatPrintTemplate(template *models.XtHisTreatmentTemplate) error {
503
+
504
+	err := XTWriteDB().Create(&template).Error
505
+	return err
506
+}
507
+
508
+func UpdatedTreateTemplate(template *models.XtHisTreatmentTemplate) error {
509
+
510
+	err := XTWriteDB().Save(&template).Error
511
+	return err
512
+}
513
+
514
+func GetTreatTtreatPrintTemplate(orgid int64) (models.XtHisTreatmentTemplate, error) {
515
+	template := models.XtHisTreatmentTemplate{}
516
+	err := XTReadDB().Where("user_org_id = ? and status =1", orgid).Find(&template).Error
517
+	return template, err
518
+}
519
+
520
+func GetChargeTemplate(templateid int64, orgid int64) (*models.XtHisChargeTemplate, error) {
521
+
522
+	template := models.XtHisChargeTemplate{}
523
+	err := XTReadDB().Model(&template).Where("template_id = ? and user_org_id = ? and status = 1", templateid, orgid).Find(&template).Error
524
+	if err != nil {
525
+		if err == gorm.ErrRecordNotFound {
526
+			return nil, err
527
+		} else {
528
+			return nil, err
529
+		}
530
+	}
531
+	return &template, nil
532
+}
533
+
534
+func CreateChargePrintTemplate(template *models.XtHisChargeTemplate) error {
535
+
536
+	err := XTWriteDB().Create(&template).Error
537
+	return err
538
+}
539
+
540
+func UpdateChargePrintTemplate(template *models.XtHisChargeTemplate) error {
541
+
542
+	err := XTWriteDB().Save(&template).Error
543
+	return err
544
+}
545
+
546
+func GetChargePrintTemplate(orgid int64) (models.XtHisChargeTemplate, error) {
547
+	template := models.XtHisChargeTemplate{}
548
+	err := XTReadDB().Model(&template).Where("user_org_id = ? and status = 1", orgid).Find(&template).Error
549
+	return template, err
550
+}
551
+
552
+func GetDoctorProjectItem(patientid int64, record_date int64) (models.HisPrescriptionProject, error) {
553
+
554
+	project := models.HisPrescriptionProject{}
555
+	err := XTReadDB().Model(&project).Where("patient_id = ? and record_date = ? and status = 1", patientid, record_date).Preload("HisProject").Find(&project).Error
556
+	return project, err
557
+}
558
+
559
+func GetChargePrint(record int64, patient_id int64, user_org_id int64) (order XtHisOrder, err error) {
560
+
561
+	err = readDb.Model(&HisOrder{}).Where("status = 1 AND user_org_id = ? AND patient_id = ? AND settle_accounts_date=?", user_org_id, patient_id, record).
562
+		Preload("HisOrderInfo", "status = 1 AND user_org_id = ?", user_org_id).
563
+		Preload("HisPatient", "status = 1 AND user_org_id = ?", user_org_id).
564
+		Preload("HisPrescriptionInfo", "status = 1 AND user_org_id = ?", user_org_id).
565
+		Order("ctime desc").
566
+		Find(&order).Error
567
+	return
568
+
569
+}
570
+
571
+func GetLastPatient(orgid int64) (models.HisPatient, error) {
572
+
573
+	patient := models.HisPatient{}
574
+	err := XTReadDB().Model(&patient).Where("user_org_id = ? and status = 1", orgid).Last(&patient).Error
575
+	return patient, err
576
+}
577
+
578
+func UpdateHisPatient(id int64, patient models.HisPatient) error {
579
+
580
+	err := XTWriteDB().Model(&patient).Where("id = ? and status = 1", id).Update(map[string]interface{}{"number": patient.Number}).Error
581
+	return err
582
+}
583
+
584
+func GetTodaySchedulePatient(orgid int64, scheduledata int64) (schedule []*models.Schedules, err error) {
585
+
586
+	db := XTReadDB().Table("xt_schedule as x").Where("x.status = 1")
587
+	if orgid > 0 {
588
+		db = db.Where("x.user_org_id = ?", orgid)
589
+	}
590
+	if scheduledata > 0 {
591
+		db = db.Where("x.schedule_date = ?", scheduledata)
592
+	}
593
+
594
+	err = db.Select("x.id,x.patient_id,x.schedule_date,t.name").Joins("left join xt_patients as t on t.id = x.patient_id").Scan(&schedule).Error
595
+	return schedule, err
596
+}
597
+
598
+func GetPrscriptionInfo(patientid int64, recorddata int64) (info []*models.HisPrescriptionInfo, err error) {
599
+
600
+	err = XTReadDB().Model(&info).Where("patient_id = ? and status = 1 and record_date = ?", patientid, recorddata).Find(&info).Error
601
+	return info, err
602
+
603
+}
604
+
605
+func GetPrescriptionByPatientId(patient_id int64, startime int64, p_type int64) (prescription []*models.HisPrescription, err error) {
606
+	err = readDb.Model(&models.HisPrescription{}).
607
+		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
608
+			return db.Where("status = 1").Preload("XtHisAddtionConfig", "status=1")
609
+		}).
610
+		Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
611
+			return db.Where("status = 1 ").Preload("Drug", "status=1")
612
+		}).
613
+		Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
614
+			return db.Where("status = 1 ").Preload("HisProject").Preload("GoodInfo", "status=1")
615
+		}).
616
+		Where("patient_id = ? AND record_date =? AND p_type = ? AND status = 1", patient_id, startime, p_type).
617
+		Find(&prescription).Error
618
+	return
619
+}
620
+
621
+// func GetPrescriptionByPatientId(patient_id int64, startime int64, p_type int64) (prescritpion []*models.HisPrescription, err error) {
622
+// // 	err = XTReadDB().Model(&prescritpion).Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
623
+// // 		return db.Where("status = 1 and user_org_id = ?", orgid).Preload("Drug", "status = 1")
624
+// // }).Where("patient_id = ? AND record_date =? AND p_type = ? AND status = 1", patient_id, startime, p_type).Find(&prescritpion).Error
625
+// // 	return prescritpion, err
626
+// }
627
+
628
+func GetTodayHisPatient(recod_date int64, patientid int64, user_org_id int64) (*models.XtHisPatient, error) {
629
+
630
+	patient := models.XtHisPatient{}
631
+	err := XTReadDB().Model(&patient).Where("record_date = ? and patient_id = ? and user_org_id = ? and is_return = 1 and status = 1", recod_date, patientid, user_org_id).Find(&patient).Error
632
+	if err != nil {
633
+		if err == gorm.ErrRecordNotFound {
634
+			return nil, err
635
+		} else {
636
+			return nil, err
637
+		}
638
+	}
639
+	return &patient, nil
640
+}
641
+
642
+func CreateHisMedicalTemplate(template *models.XtHisMedicalTemplate) error {
643
+
644
+	err := XTWriteDB().Create(&template).Error
645
+	return err
646
+}
647
+
648
+func GetMedicalTemplateList(orgid int64) (template []*models.XtHisMedicalTemplate, err error) {
649
+
650
+	err = XTReadDB().Model(&template).Where("user_org_id =? and status = 1 and template_id = 1", orgid).Find(&template).Error
651
+	return template, err
652
+}
653
+
654
+func GetMedicalTemplateListOne(orgid int64) (template []*models.XtHisMedicalTemplate, err error) {
655
+
656
+	err = XTReadDB().Model(&template).Where("user_org_id =? and status = 1 and template_id = 2", orgid).Find(&template).Error
657
+	return template, err
658
+}
659
+
660
+func GetMedicalTemplateListTwo(orgid int64) (template []*models.XtHisMedicalTemplate, err error) {
661
+
662
+	err = XTReadDB().Model(&template).Where("user_org_id =? and status = 1 and template_id = 3", orgid).Find(&template).Error
663
+	return template, err
664
+}
665
+
666
+func GetMedicalTemplateListThree(orgid int64) (template []*models.XtHisMedicalTemplate, err error) {
667
+
668
+	err = XTReadDB().Model(&template).Where("user_org_id =? and status = 1 and template_id = 4", orgid).Find(&template).Error
669
+	return template, err
670
+}
671
+
672
+func GetMedicalTemplateListFour(orgid int64) (template []*models.XtHisMedicalTemplate, err error) {
673
+
674
+	err = XTReadDB().Model(&template).Where("user_org_id =? and status = 1 and template_id = 5", orgid).Find(&template).Error
675
+	return template, err
676
+}
677
+
678
+func GetMedicalTemplateListFive(orgid int64) (template []*models.XtHisMedicalTemplate, err error) {
679
+
680
+	err = XTReadDB().Model(&template).Where("user_org_id =? and status = 1 and template_id = 6", orgid).Find(&template).Error
681
+	return template, err
682
+}
683
+
684
+func GetMedicalTemplateListSix(orgid int64) (template []*models.XtHisMedicalTemplate, err error) {
685
+
686
+	err = XTReadDB().Model(&template).Where("user_org_id =? and status = 1 and template_id = 7", orgid).Find(&template).Error
687
+	return template, err
688
+}
689
+
690
+func GetMedicalTemplateListSeven(orgid int64) (template []*models.XtHisMedicalTemplate, err error) {
691
+
692
+	err = XTReadDB().Model(&template).Where("user_org_id =? and status = 1 and template_id = 8", orgid).Find(&template).Error
693
+	return template, err
694
+}
695
+
696
+func GetMainTemplateById(id int64) (models.XtHisMedicalTemplate, error) {
697
+
698
+	template := models.XtHisMedicalTemplate{}
699
+	err := XTReadDB().Model(&template).Where("id=? and status = 1", id).Find(&template).Error
700
+	return template, err
701
+}
702
+
703
+func UpdateMainTemplate(template *models.XtHisMedicalTemplate, id int64) error {
704
+
705
+	err := XTWriteDB().Model(&template).Where("id = ? and status = 1", id).Updates(map[string]interface{}{"title": template.Title, "content": template.Content, "remark": template.Remark, "mtime": time.Now().Unix()}).Error
706
+	return err
707
+}
708
+
709
+func DeleteMainTemplateById(id int64) error {
710
+
711
+	template := models.XtHisMedicalTemplate{}
712
+	err := XTWriteDB().Model(&template).Where("id = ? and status = 1", id).Updates(map[string]interface{}{"status": 0}).Error
713
+	return err
714
+
715
+}
716
+
717
+func GetProjectHisList(orgid int64) (hisProjectList []*models.XtHisProjectList, error error) {
718
+
719
+	error = XTReadDB().Model(&hisProjectList).Where("user_org_id = ? and status = 1", orgid).Group("project_id").Find(&hisProjectList).Error
720
+	return hisProjectList, error
721
+}
722
+
723
+func GetLastItem(orgid int64) (models.XtHisProjectList, error) {
724
+
725
+	list := models.XtHisProjectList{}
726
+	err := XTReadDB().Model(&list).Where("user_org_id = ? and status = 1", orgid).Last(&list).Error
727
+	return list, err
728
+}
729
+
730
+func SaveProjectTeam(team *models.XtHisProjectTeam) error {
731
+
732
+	err := XTWriteDB().Model(&team).Save(&team).Error
733
+	return err
734
+}
735
+
736
+func GetProjectHisListByIds(ids []string) (hisProjectList []*models.XtHisProjectList, error error) {
737
+	error = XTReadDB().Model(&hisProjectList).Preload("XtHisProject").Preload("GoodInfo", "status = 1").Where(" status = 1 and id in (?)", ids).Find(&hisProjectList).Error
738
+	return hisProjectList, error
739
+}
740
+
741
+func GetHisPatientByIdThree(id int64) (models.HisPatient, error) {
742
+	patient := models.HisPatient{}
743
+	err := XTReadDB().Model(&patient).Where("id = ? and status = 1", id).First(&patient).Error
744
+	return patient, err
745
+}
746
+
747
+func GetLastHisPatient(patient_id int64, org_id int64) (his models.HisPatient, err error) {
748
+	err = XTReadDB().Model(&models.HisPatient{}).Where("user_org_id = ? AND patient_id = ? and status = 1 AND patient_info <> ''", org_id, patient_id).First(&his).Error
749
+	return
750
+}

Diff onderdrukt omdat het te groot bestand
+ 2108 - 0
service/his_service.go


+ 37 - 0
service/home_service.go Bestand weergeven

@@ -0,0 +1,37 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_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
+}

+ 219 - 0
service/inspection_service.go Bestand weergeven

@@ -0,0 +1,219 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_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("created_time 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
+}
214
+
215
+func GetInspectionReferenceByOrgId(orgid int64) (insepciton []*models.XtInspectionReference, err error) {
216
+
217
+	err = readDb.Model(&insepciton).Where("org_id = ? and status = 1 and project_name = '传染病检查'", orgid).Find(&insepciton).Error
218
+	return insepciton, err
219
+}

+ 120 - 0
service/integration_service.go Bestand weergeven

@@ -0,0 +1,120 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_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
+}

+ 55 - 0
service/invoice_service.go Bestand weergeven

@@ -0,0 +1,55 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_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
+}

+ 246 - 0
service/login_service.go Bestand weergeven

@@ -0,0 +1,246 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_New/models"
5
+	"Xcx_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
+}

+ 370 - 0
service/manage_center_service.go Bestand weergeven

@@ -0,0 +1,370 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_New/models"
5
+	"github.com/jinzhu/gorm"
6
+	"time"
7
+)
8
+
9
+func GetDictionaryConfigList(orgID int64) (dataconfig interface{}, err error) {
10
+	var configList []*models.DictionaryDataconfig
11
+
12
+	err = readDb.Model(&models.DictionaryDataconfig{}).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
13
+	if err != nil {
14
+		return nil, err
15
+	}
16
+
17
+	// configResult := make([]*ConfigViewModel,0)
18
+	childConfig := make(map[int64][]*models.DictionaryDataconfig)
19
+	resultConfig := make(map[string][]*models.DictionaryConfigViewModel)
20
+	deleteSystemChilds := make([]*models.DictionaryDataconfig, 0)
21
+	editSystemChilds := make([]*models.DictionaryDataconfig, 0)
22
+	for _, config := range configList {
23
+		if config.Status == 1 && config.DeleteIdSystem > 0 {
24
+			editSystemChilds = append(editSystemChilds, config)
25
+		}
26
+
27
+		if config.Status == 0 && config.DeleteIdSystem > 0 {
28
+			deleteSystemChilds = append(deleteSystemChilds, config)
29
+		}
30
+	}
31
+	continueFlag := false
32
+	for _, config := range configList {
33
+		continueFlag = false
34
+		if config.ParentId == 0 {
35
+			newConfig := &models.DictionaryConfigViewModel{
36
+				ID:           config.ID,
37
+				ParentId:     config.ParentId,
38
+				Module:       config.Module,
39
+				OrgId:        config.OrgId,
40
+				Name:         config.Name,
41
+				FieldName:    config.FieldName,
42
+				Value:        config.Value,
43
+				CreateUserId: config.CreateUserId,
44
+				Status:       config.Status,
45
+				Remark:       config.Remark,
46
+				Title:        config.Title,
47
+				Content:      config.Content,
48
+			}
49
+			// configResult = append(configResult,newConfig)
50
+			result := resultConfig[config.Module]
51
+			if result == nil {
52
+				result = make([]*models.DictionaryConfigViewModel, 0)
53
+			}
54
+			for _, vm := range editSystemChilds {
55
+				if vm.DeleteIdSystem == config.ID {
56
+					continueFlag = true
57
+					break
58
+				}
59
+			}
60
+
61
+			for _, _vm := range deleteSystemChilds {
62
+				if _vm.DeleteIdSystem == config.ID {
63
+					continueFlag = true
64
+					break
65
+				}
66
+			}
67
+			if config.OrgId != 0 && config.Status == 0 && config.DeleteIdSystem > 0 {
68
+				continue
69
+			}
70
+			if continueFlag {
71
+				continue
72
+			}
73
+			result = append(result, newConfig)
74
+			resultConfig[config.Module] = result
75
+		} else {
76
+			childs := childConfig[config.ParentId]
77
+			if childs == nil {
78
+				childs = make([]*models.DictionaryDataconfig, 0)
79
+			}
80
+			continueFlag := false
81
+			for _, vm := range editSystemChilds {
82
+				if vm.DeleteIdSystem == config.ID {
83
+					continueFlag = true
84
+					break
85
+				}
86
+			}
87
+
88
+			for _, _vm := range deleteSystemChilds {
89
+				if _vm.DeleteIdSystem == config.ID {
90
+					continueFlag = true
91
+					break
92
+				}
93
+			}
94
+			if config.OrgId != 0 && config.Status == 0 && config.DeleteIdSystem > 0 {
95
+				continue
96
+			}
97
+			if continueFlag {
98
+				continue
99
+			}
100
+
101
+			childs = append(childs, config)
102
+			childConfig[config.ParentId] = childs
103
+		}
104
+	}
105
+
106
+	for _, vm := range resultConfig {
107
+		for _, _vm := range vm {
108
+			_vm.Childs = childConfig[_vm.ID]
109
+		}
110
+		// vm.Childs = childConfig[vm.ID]
111
+	}
112
+	return resultConfig, err
113
+}
114
+
115
+func CreateDictionaryConfig(dataconfig *models.DictionaryDataconfig) (err error) {
116
+	// readDb.Model(&models.Dataconfig{}).Where("module = ? and parent_id = 0 and org_id in (0,?)",dataconfig.Module,dataconfig.OrgId).Count(&total)
117
+	err = readDb.Create(&dataconfig).Error
118
+	return
119
+}
120
+
121
+func GetDictionaryChildValue(module string, parent_id int64, org_id int64) (value int) {
122
+	readDb.Model(&models.DictionaryDataconfig{}).Where("module=? and parent_id=? and org_id in (0,?)", module, parent_id, org_id).Count(&value)
123
+	return
124
+}
125
+
126
+func FindDictionaryConfigByTitle(module string, title string, org_id int64) (dataconfig models.DictionaryDataconfig, err error) {
127
+	err = readDb.Model(&models.DictionaryDataconfig{}).Where("module=? and title=? and org_id in (0,?) and status = 1", module, title, org_id).First(&dataconfig).Error
128
+	return
129
+}
130
+
131
+func UpdateDictionaryTemplate(dataconfig *models.DictionaryDataconfig) (err error) {
132
+	err = readDb.Model(&models.DictionaryDataconfig{}).Where("id =?", dataconfig.ID).Update(map[string]interface{}{"title": dataconfig.Title, "content": dataconfig.Content, "update_time": dataconfig.UpdatedTime, "remark": dataconfig.Remark}).Error
133
+	return
134
+}
135
+
136
+func UpdateDictionaryChildConfig(dataconfig *models.DictionaryDataconfig) (err error) {
137
+	err = readDb.Model(&models.DictionaryDataconfig{}).Where("id =?", dataconfig.ID).Update(map[string]interface{}{"name": dataconfig.Name, "update_time": dataconfig.UpdatedTime, "remark": dataconfig.Remark, "orders": dataconfig.Order, "code": dataconfig.Code}).Error
138
+	return
139
+}
140
+
141
+func DeleteDictionaryChildConfig(dataconfig *models.DictionaryDataconfig) (err error) {
142
+	err = readDb.Model(&models.DictionaryDataconfig{}).Where("id =?", dataconfig.ID).Update(map[string]interface{}{"status": dataconfig.Status, "update_time": dataconfig.UpdatedTime}).Error
143
+	return
144
+}
145
+
146
+func CreateBaseDrugLib(lib *models.BaseDrugLib) (err error) {
147
+	err = writeDb.Create(&lib).Error
148
+	return
149
+}
150
+
151
+func UpdateBaseDrugLib(lib *models.BaseDrugLib) (err error) {
152
+	err = writeDb.Save(lib).Error
153
+	return
154
+}
155
+
156
+func FindBaseDrugLibRecordCount(lib *models.BaseDrugLib) (count int64) {
157
+	readDb.Model(&models.BaseDrugLib{}).Where("org_id = ? AND drug_name = ? AND  drug_category = ? AND drug_spec=? AND drug_type=? AND status = 1", lib.OrgId, lib.DrugName, lib.DrugCategory, lib.DrugSpec, lib.DrugType).Count(&count)
158
+	return
159
+}
160
+
161
+func FindBaseDrugLibRecordCountOne(lib *models.BaseDrugLib) (count int64) {
162
+	readDb.Model(&models.BaseDrugLib{}).Where("org_id = ? and drug_name = ? and dose = ? and dose_unit = ? and min_number = ? and min_unit = ? and max_unit = ? and manufacturer = ? and status = 1", lib.OrgId, lib.DrugName, lib.Dose, lib.DoseUnit, lib.MinNumber, lib.MinUnit, lib.MaxUnit, lib.Manufacturer).Count(&count)
163
+	return
164
+}
165
+
166
+func FindAllDrugLibRecordTotal(org_id int64) (count int64) {
167
+	readDb.Model(&models.BaseDrugLib{}).Where("org_id = ? AND status = 1", org_id).Count(&count)
168
+	return
169
+}
170
+
171
+func FindBaseDrugLibRecord(org_id int64, id int64) (lib models.BaseDrugLib, err error) {
172
+	err = readDb.Model(&models.BaseDrugLib{}).Where("org_id = ? AND id = ? AND status = 1", org_id, id).First(&lib).Error
173
+	return
174
+}
175
+
176
+func GetBaseDrugLibList(org_id int64, keyword string, page int64, limit int64, is_use int64, is_charge int64, is_inject int64, manufacturer int64, isRecord int64) (list []*models.BaseDrugLib, total int64, err error) {
177
+
178
+	db := readDb.Model(&models.BaseDrugLib{}).Where("org_id = ?  AND status = 1", org_id)
179
+	if len(keyword) != 0 {
180
+		keyword = "%" + keyword + "%"
181
+		db = db.Where("drug_name Like ?", keyword)
182
+
183
+	}
184
+
185
+	if is_use != 0 {
186
+		if is_use == 1 {
187
+			db = db.Where("find_in_set('停用',drug_status) = 0")
188
+
189
+		} else {
190
+			db = db.Where("find_in_set('停用',drug_status) > 0")
191
+		}
192
+	}
193
+
194
+	if is_charge != 0 {
195
+		//db = db.Where("drug_name Like ?", keyword)
196
+		if is_charge == 1 {
197
+			db = db.Where("find_in_set('收费',drug_status) > 0")
198
+
199
+		} else {
200
+			db = db.Where("find_in_set('收费',drug_status) = 0")
201
+		}
202
+	}
203
+
204
+	if is_inject != 0 {
205
+		//db = db.Where("drug_name Like ?", keyword)
206
+		if is_inject == 1 {
207
+			db = db.Where("find_in_set('注射类',drug_status) > 0")
208
+
209
+		} else {
210
+			db = db.Where("find_in_set('注射类',drug_status) = 0")
211
+		}
212
+
213
+	}
214
+
215
+	if manufacturer > 0 {
216
+		db = db.Where("manufacturer = ?", manufacturer)
217
+	}
218
+	if isRecord > 0 {
219
+		db = db.Where("is_mark = ?", isRecord)
220
+	}
221
+	offset := (page - 1) * limit
222
+
223
+	err = db.Count(&total).Offset(offset).Limit(limit).Order("ctime desc").Find(&list).Error
224
+	return
225
+}
226
+
227
+func CreateMedicineInsurancePercentage(mip *models.MedicineInsurancePercentage) (err error) {
228
+	err = writeDb.Create(mip).Error
229
+	return
230
+}
231
+
232
+func CreateUnitSafeguard(dus *models.DrugUnitSafeguard) (err error) {
233
+	err = writeDb.Create(dus).Error
234
+	return
235
+}
236
+
237
+func AddSigleMZSick(dealer *models.OutpatientServiceSick) (error, *models.OutpatientServiceSick) {
238
+	err := writeDb.Create(&dealer).Error
239
+	return err, dealer
240
+}
241
+
242
+func ModifyMZSick(mesick *models.OutpatientServiceSick) error {
243
+	err := writeDb.Save(&mesick).Error
244
+
245
+	return err
246
+}
247
+
248
+func FindAllMZSickList(orgId int64, page int64, limit int64) (list []*models.OutpatientServiceSick, total int64, err error) {
249
+	offset := (page - 1) * limit
250
+	db := readDb.Model(&models.OutpatientServiceSick{})
251
+	db = db.Where("user_org_id = ? AND status = 1", orgId)
252
+	err = db.Count(&total).Offset(offset).Limit(limit).Order("ctime desc").Find(&list).Error
253
+	return
254
+}
255
+
256
+func DeleteMZSickById(id int64) error {
257
+	err := writeDb.Model(&models.OutpatientServiceSick{}).Where("id = ? AND status = 1", id).Updates(map[string]interface{}{"mtime": time.Now().Unix(), "status": 0}).Error
258
+	return err
259
+}
260
+
261
+func FindMZSickById(id int64) (*models.OutpatientServiceSick, error) {
262
+	dealer := &models.OutpatientServiceSick{}
263
+	err := readDb.Model(&models.OutpatientServiceSick{}).Where("id = ? AND status = 1", id).First(&dealer).Error
264
+	return dealer, err
265
+}
266
+
267
+func GetDrugWareoutInfo(id int64) (*models.XtDrugWarehouseInfo, error) {
268
+
269
+	info := models.XtDrugWarehouseInfo{}
270
+	err = XTReadDB().Model(&info).Where("drug_id = ? and status = 1", id).Find(&info).Error
271
+	if err == gorm.ErrRecordNotFound {
272
+		return nil, err
273
+	}
274
+	if err != nil {
275
+		return nil, err
276
+	}
277
+	return &info, nil
278
+}
279
+
280
+func GetDrugWareOutById(id int64) (*models.XtDrugWarehouseOutInfo, error) {
281
+
282
+	info := models.XtDrugWarehouseOutInfo{}
283
+	err := XTReadDB().Model(&info).Where("drug_id = ? and status = 1", id).Find(&info).Error
284
+	if err == gorm.ErrRecordNotFound {
285
+		return nil, err
286
+	}
287
+	if err != nil {
288
+		return nil, err
289
+	}
290
+	return &info, nil
291
+}
292
+
293
+func DeleteBaseDrugById(id int64) error {
294
+
295
+	drug := models.XtBaseDrug{}
296
+	err := XTWriteDB().Model(&drug).Where("id = ? and status = 1", id).Updates(map[string]interface{}{"status": 0}).Error
297
+	return err
298
+}
299
+
300
+func AddSigleAddition(dealer *models.XtHisAddtionConfig) (error, *models.XtHisAddtionConfig) {
301
+	err := writeDb.Create(&dealer).Error
302
+	return err, dealer
303
+}
304
+
305
+func ModifyAddition(mesick *models.XtHisAddtionConfig) error {
306
+	err := writeDb.Save(&mesick).Error
307
+
308
+	return err
309
+}
310
+
311
+func FindAllAdditionList(orgId int64, page int64, limit int64) (list []*models.XtHisAddtionConfig, total int64, err error) {
312
+	offset := (page - 1) * limit
313
+	db := readDb.Model(&models.XtHisAddtionConfig{})
314
+	db = db.Where("user_org_id = ? AND status = 1", orgId)
315
+	err = db.Count(&total).Offset(offset).Limit(limit).Order("ctime desc").Find(&list).Error
316
+	return
317
+}
318
+
319
+func DeleteAdditionById(id int64) error {
320
+	err := writeDb.Model(&models.XtHisAddtionConfig{}).Where("id = ? AND status = 1", id).Updates(map[string]interface{}{"mtime": time.Now().Unix(), "status": 0}).Error
321
+	return err
322
+}
323
+
324
+func FindAdditionById(id int64) (*models.XtHisAddtionConfig, error) {
325
+	dealer := &models.XtHisAddtionConfig{}
326
+	err := readDb.Model(&models.XtHisAddtionConfig{}).Where("id = ? AND status = 1", id).First(&dealer).Error
327
+	return dealer, err
328
+}
329
+
330
+func AddSigleDiagnose(dealer *models.HisXtDiagnoseConfig) (error, *models.HisXtDiagnoseConfig) {
331
+	err := writeDb.Create(&dealer).Error
332
+	return err, dealer
333
+}
334
+
335
+func ModifyDiagnose(mesick *models.HisXtDiagnoseConfig) error {
336
+	err := writeDb.Save(&mesick).Error
337
+
338
+	return err
339
+}
340
+
341
+func FindAllDiagnoseList(orgId int64, page int64, limit int64) (list []*models.HisXtDiagnoseConfig, total int64, err error) {
342
+	offset := (page - 1) * limit
343
+	db := readDb.Model(&models.HisXtDiagnoseConfig{})
344
+	db = db.Where("user_org_id = ? AND status = 1", orgId)
345
+	err = db.Count(&total).Offset(offset).Limit(limit).Order("ctime desc").Find(&list).Error
346
+	return
347
+}
348
+
349
+func DeleteDiagnoseById(id int64) error {
350
+	err := writeDb.Model(&models.HisXtDiagnoseConfig{}).Where("id = ? AND status = 1", id).Updates(map[string]interface{}{"mtime": time.Now().Unix(), "status": 0}).Error
351
+	return err
352
+}
353
+
354
+func FindDiagnoseById(id int64) (*models.HisXtDiagnoseConfig, error) {
355
+	dealer := &models.HisXtDiagnoseConfig{}
356
+	err := readDb.Model(&models.HisXtDiagnoseConfig{}).Where("id = ? AND status = 1", id).First(&dealer).Error
357
+	return dealer, err
358
+}
359
+
360
+func GetDoseCode(dose_id int64, user_org_id int64) (error, string) {
361
+	var data models.DictDataconfig
362
+	err := readDb.Model(&models.DictDataconfig{}).Where(" (user_org_id = ? Or user_org_id = 0) AND parent_id = 4 AND module = 'system' AND status = 1 AND value = ?", user_org_id, dose_id).First(&data).Error
363
+	return err, data.Code
364
+}
365
+
366
+func GetAllDrugList(orgid int64) (drug []*models.BaseDrugLib, err error) {
367
+
368
+	err = XTReadDB().Model(&drug).Where("org_id = ? and status = 1", orgid).Find(&drug).Error
369
+	return drug, err
370
+}

Diff onderdrukt omdat het te groot bestand
+ 1543 - 0
service/manage_service.go


+ 69 - 0
service/management_service/management_analyse_service.go Bestand weergeven

@@ -0,0 +1,69 @@
1
+package management_service
2
+
3
+import "Xcx_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
+}

+ 103 - 0
service/management_service/management_models.go Bestand weergeven

@@ -0,0 +1,103 @@
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
+}

Diff onderdrukt omdat het te groot bestand
+ 2263 - 0
service/mobile_dialysis_service.go


+ 144 - 0
service/new_sms_service.go Bestand weergeven

@@ -0,0 +1,144 @@
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
+	"Xcx_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
+}

+ 202 - 0
service/orginfo_service.go Bestand weergeven

@@ -0,0 +1,202 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_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
+}

+ 64 - 0
service/patient_dataconfig_service.go Bestand weergeven

@@ -0,0 +1,64 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_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
+}

+ 523 - 0
service/patient_schedule_template_service.go Bestand weergeven

@@ -0,0 +1,523 @@
1
+package service
2
+
3
+import (
4
+	"fmt"
5
+	"strings"
6
+	"time"
7
+
8
+	"Xcx_New/models"
9
+	"Xcx_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
+}

Diff onderdrukt omdat het te groot bestand
+ 1517 - 0
service/patient_service.go


Diff onderdrukt omdat het te groot bestand
+ 1809 - 0
service/patientmanage_service.go


+ 149 - 0
service/pay_service.go Bestand weergeven

@@ -0,0 +1,149 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_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
+}

+ 744 - 0
service/print_data_service/schedule_dialysis/print_schedule_dialysis_models.go Bestand weergeven

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

+ 255 - 0
service/print_data_service/schedule_dialysis/print_schedule_dialysis_service.go Bestand weergeven

@@ -0,0 +1,255 @@
1
+package schedule_dialysis
2
+
3
+import (
4
+	"Xcx_New/models"
5
+	p_service "Xcx_New/service"
6
+	"Xcx_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
+		Preload("HisAdvices", func(db *gorm.DB) *gorm.DB {
46
+			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").
47
+				Where("user_org_id = ? AND status = 1", orgID).
48
+				Order("start_time asc, groupno desc, advice_order desc, id asc")
49
+		}).
50
+		Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
51
+			return db.Where("user_org_id = ? AND status = 1", orgID).Preload("HisProject").Preload("GoodInfo", "status=1")
52
+		}).
53
+		Where("user_org_id = ? AND status = 1 AND id in (?)", orgID, schIDs).Order("schedule_date desc").
54
+		Find(&schedules).
55
+		Error
56
+	if err != nil {
57
+		return nil, err
58
+	}
59
+	for _, item := range schedules {
60
+		dialysis_count, _ := GetDialysisOrderCount(orgID, item.PatientID, item.ScheduleDate)
61
+		fmt.Println(dialysis_count)
62
+		item.Patient.TotalDialysis = dialysis_count
63
+		fmt.Println(item.Patient.TotalDialysis)
64
+
65
+	}
66
+	return schedules, nil
67
+}
68
+
69
+func GetMedicalStaffs(orgID int64, appID int64) ([]*MedicalStaffVM, error) {
70
+	var staffs []*MedicalStaffVM
71
+	db := p_service.UserReadDB()
72
+	// err := db.Table("sgj_user_admin_role as uar").
73
+	// 	Joins("JOIN sgj_user_admin as ua ON ua.id = uar.admin_user_id").
74
+	// 	Joins("LEFT JOIN sgj_user_admin_electronic_signature as es ON es.creator = uar.admin_user_id and es.status = 1").
75
+	// 	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).
76
+	// 	Where("uar.status = 1 and uar.org_id = ? and uar.app_id = ? and ua.status = 1", orgID, appID).
77
+	// 	Select("ua.id, uar.user_name as name, uar.user_type, es.url as es_url").
78
+	// 	Scan(&staffs).
79
+	// 	Error
80
+
81
+	err := db.Table("sgj_user_admin_electronic_signature").
82
+		Where("org_id=? and app_id=? and status=1", orgID, appID).
83
+		Select("creator as id, url as es_url").Scan(&staffs).Error
84
+
85
+	if err != nil {
86
+		return nil, err
87
+	}
88
+	return staffs, nil
89
+}
90
+
91
+type AdminUserList struct {
92
+	Id       int64  `json:"id"`
93
+	Name     string `json:"name"`
94
+	UserType int64  `json:"user_type"`
95
+}
96
+type AdminUserListTwo struct {
97
+	Id       int64  `json:"id"`
98
+	Name     string `json:"name"`
99
+	UserType int64  `json:"user_type"`
100
+	Url      string `json:"url"`
101
+}
102
+
103
+func GetAllAdminUsers(orgId int64, appid int64) (list []*AdminUserList, err error) {
104
+	db := p_service.UserReadDB()
105
+	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
106
+	return
107
+}
108
+
109
+func GetAllName(orgId int64, appid int64) (list []AdminUserListTwo, err error) {
110
+	db := p_service.UserReadDB()
111
+	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
112
+	return
113
+}
114
+
115
+func GetPatientCoursesRecords(orgID int64, id int64) (records models.PatientDiseaseCourse, err error) {
116
+	db := p_service.XTReadDB()
117
+	err = db.Model(&models.PatientDiseaseCourse{}).Where("org_id = ? and id = ? and status = 1", orgID, id).Find(&records).Error
118
+	return
119
+}
120
+
121
+func FindPatientWithDeviceById(orgID int64, patient_id int64, time int64) (patient models.SchedualPatient2, err error) {
122
+	db := p_service.XTReadDB()
123
+
124
+	err = db.Preload("DialysisSchedule", func(db *gorm.DB) *gorm.DB {
125
+		return db.Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
126
+			Preload("DeviceZone", "status = 1 AND org_id = ?", orgID).
127
+			Where("user_org_id = ? AND schedule_date = ? ", orgID, time)
128
+	}).Where("user_org_id=? and id = ? and status=1", orgID, patient_id).First(&patient).Error
129
+	return
130
+}
131
+
132
+func GetLastAfterWeight(orgID int64, patientID int64, maxDate int64) (*models.AssessmentAfterDislysis, error) {
133
+	var record models.AssessmentAfterDislysis
134
+	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
135
+	if err != nil {
136
+		if err == gorm.ErrRecordNotFound {
137
+			return nil, nil
138
+		} else {
139
+			return nil, err
140
+		}
141
+	}
142
+	return &record, nil
143
+}
144
+
145
+//func GetAllName(orgid int64,appid int64)(sign,err error){
146
+//
147
+//  p_service.XTReadDB().Model(&sign).Where("org_id = ? and app_id =? and status = 1")
148
+//
149
+//}
150
+
151
+func FindPrintStockGoodInfoByType(types int, startTime int64, end_time int64, orgId int64) (list []*models.StockInfo, err error) {
152
+	db := p_service.XTReadDB()
153
+	db = db.Model(&models.StockInfo{})
154
+	db = db.Where("xt_good_information.org_id = ? AND xt_good_information.status = 1", orgId)
155
+	if types == 1 {
156
+		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")
157
+		db = db.Preload("QueryWarehousingInfo", func(db *gorm.DB) *gorm.DB {
158
+			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)
159
+		})
160
+	} else if types == 2 {
161
+		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")
162
+		db = db.Preload("QuerySalesReturnInfo", func(db *gorm.DB) *gorm.DB {
163
+			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)
164
+		})
165
+
166
+	} else if types == 3 {
167
+		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")
168
+		db = db.Preload("QueryWarehouseOutInfo", func(db *gorm.DB) *gorm.DB {
169
+			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)
170
+		})
171
+
172
+	} else if types == 4 {
173
+
174
+		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")
175
+		db = db.Preload("QueryCancelStockInfo", func(db *gorm.DB) *gorm.DB {
176
+			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)
177
+		})
178
+
179
+	}
180
+	db = db.Preload("GoodsType", "org_id = ? AND status = 1", orgId)
181
+	err = db.Order("ctime desc").Find(&list).Error
182
+	return
183
+}
184
+
185
+func GetOrgInfoTemplate(orgID int64) (models.GobalTemplate, error) {
186
+
187
+	var templateInfo models.GobalTemplate
188
+	var err error
189
+	err = p_service.XTReadDB().Model(&models.GobalTemplate{}).Where("org_id=? and status=1", orgID).First(&templateInfo).Error
190
+	return templateInfo, err
191
+}
192
+
193
+func GetDialysisOrderCount(orgID int64, patient_id int64, recordDate int64) (count int64, err error) {
194
+	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
195
+	return
196
+}
197
+
198
+func GetOutStockTotalCountTwo(startime int64, endtime int64, orgid int64) (autoMatic []*models.NewXtAutomaticReduceDetail, err error) {
199
+
200
+	err = p_service.XTReadDB().Raw("SELECT good_id,SUM(b.count) as count FROM (SELECT DISTINCT x.patient_id,x.good_id,x.record_time,x.count FROM xt_automatic_reduce_detail as x WHERE x.org_id = ? and x.record_time >= ? and x.record_time<=? and `status` = 1)  as b GROUP BY good_id", orgid, startime, endtime).Scan(&autoMatic).Error
201
+
202
+	return autoMatic, err
203
+}
204
+
205
+func GetCoutWareseOutInfo(startime int64, endtime int64, orgid int64) (houseOutInfo []*models.VmWarehouseOutInfo, err error) {
206
+
207
+	db := p_service.XTReadDB().Table("xt_warehouse_out_info as x").Where("x.status  =1")
208
+	err = db.Select("x.good_id,Sum(x.count) as count,x.remark,x.price,x.org_id").Where("x.ctime >=? and x.ctime<=? and x.org_id = ?", startime, endtime, orgid).Group("x.good_id").Scan(&houseOutInfo).Error
209
+	return houseOutInfo, err
210
+}
211
+
212
+func GetGoodInfomationList(orgid int64) (goodInfo []*models.GoodInfo, err error) {
213
+
214
+	err = p_service.XTReadDB().Where("org_id = ? and status = 1", orgid).Find(&goodInfo).Error
215
+	return goodInfo, err
216
+}
217
+
218
+func GetWarehouseInfoGoodDetailPrintList(orgid int64, startime int64, endtime int64, limit int64, page int64) (info []*models.VmWarehousingInfo, err error) {
219
+	//offset := (page - 1) * limit
220
+	db := p_service.XTReadDB().Table("xt_warehouse_info as x").Where("x.status = 1")
221
+	table := p_service.XTReadDB().Table("xt_good_information as t").Where("t.status = 1")
222
+	fmt.Println(table)
223
+	if orgid > 0 {
224
+		db = db.Where("x.org_id = ?", orgid)
225
+	}
226
+	if startime > 0 {
227
+		db = db.Where("x.ctime>=?", startime)
228
+	}
229
+
230
+	if endtime > 0 {
231
+		db = db.Where("x.ctime<=?", endtime)
232
+	}
233
+
234
+	err = db.Select("x.id,x.warehousing_id,x.good_id,x.good_type_id,x.number,x.product_date,x.expiry_date,sum(x.warehousing_count) as warehousing_count,x.warehousing_unit,x.stock_count,x.price,x.total_price,x.dealer,x.manufacturer,x.remark,x.is_return,x.warehousing_order,x.type,x.license_number,t.good_name,t.specification_name,t.min_number,t.packing_unit").Joins("left join xt_good_information as t on t.id = x.good_id").Group("x.good_id").Scan(&info).Error
235
+	return info, err
236
+}
237
+
238
+func GetWarehouseOutInfoGoodDetailPrintList(orgid int64, startime int64, endtime int64, limit int64, page int64) (auto []*models.SgjAutomaticReduceDetail, err error) {
239
+
240
+	db := p_service.XTReadDB().Table("xt_automatic_reduce_detail as x").Where("x.status = 1")
241
+	table := p_service.XTReadDB().Table("xt_good_information as t").Where("t.status = 1")
242
+	fmt.Println(table)
243
+	if orgid > 0 {
244
+		db = db.Where("x.org_id = ?", orgid)
245
+	}
246
+	if startime > 0 {
247
+		db = db.Where("x.ctime >= ?", startime)
248
+	}
249
+	if endtime > 0 {
250
+		db = db.Where("x.ctime<=?", endtime)
251
+	}
252
+	err = db.Select("x.patient_id,x.record_time,x.good_id,sum(x.count) as count,t.good_name,t.specification_name,t.packing_unit,t.retail_price,t.packing_price").Joins("left join xt_good_information as t on t.id = x.good_id").Group("x.good_id").Scan(&auto).Error
253
+	return auto, err
254
+
255
+}

Diff onderdrukt omdat het te groot bestand
+ 1370 - 0
service/qcd_service.go


+ 20 - 0
service/redis.go Bestand weergeven

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

+ 34 - 0
service/regist_service.go Bestand weergeven

@@ -0,0 +1,34 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_New/enums"
5
+	"Xcx_New/models"
6
+	"Xcx_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
+}

+ 937 - 0
service/role_service.go Bestand weergeven

@@ -0,0 +1,937 @@
1
+package service
2
+
3
+import (
4
+	"database/sql"
5
+	"fmt"
6
+	"strconv"
7
+	"strings"
8
+	"time"
9
+
10
+	"Xcx_New/models"
11
+	"Xcx_New/utils"
12
+
13
+	"github.com/jinzhu/gorm"
14
+)
15
+
16
+func GetRoles(orgID int64, appID int64, page int, count int) ([]*models.Role, int, error) {
17
+	var roles []*models.Role
18
+	var totalCount int
19
+	err := readUserDb.Model(&models.Role{}).
20
+		Where("org_id = ? AND app_id = ?", orgID, appID).
21
+		Count(&totalCount).
22
+		Order("ctime asc").Limit(count).Offset((page - 1) * count).
23
+		Find(&roles).
24
+		Error
25
+	if err != nil {
26
+		if err == gorm.ErrRecordNotFound {
27
+			return make([]*models.Role, 0), 0, nil
28
+		} else {
29
+			return nil, 0, err
30
+		}
31
+	}
32
+	return roles, totalCount, nil
33
+}
34
+
35
+func GetAppRole(orgID int64, appID int64, adminUserID int64) (*models.App_Role, error) {
36
+	var appRole models.App_Role
37
+	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
38
+	if err != nil {
39
+		if err == gorm.ErrRecordNotFound {
40
+			return nil, nil
41
+		} else {
42
+			return nil, err
43
+		}
44
+	}
45
+	if len(appRole.RoleIds) > 0 {
46
+		role_ids := strings.Split(appRole.RoleIds, ",")
47
+		for _, item := range role_ids {
48
+			id, _ := strconv.ParseInt(item, 10, 64)
49
+			if id != 0 {
50
+				role, _ := GetRoleByRoleID(id)
51
+				if role != nil {
52
+					if role.IsSystem == 1 && role.RoleName == "子管理员" {
53
+						appRole.IsSubSuperAdmin = true
54
+					}
55
+				}
56
+			}
57
+		}
58
+	}
59
+
60
+	return &appRole, nil
61
+}
62
+
63
+func CreateRole(adminUserID int64, orgID int64, appID int64, name string, intro string) (*models.Role, error) {
64
+	role := models.Role{
65
+		RoleName:     name,
66
+		RoleIntro:    intro,
67
+		Creator:      adminUserID,
68
+		OrgId:        orgID,
69
+		AppId:        appID,
70
+		IsSuperAdmin: false,
71
+		Status:       1,
72
+		CreateTime:   time.Now().Unix(),
73
+		ModifyTime:   time.Now().Unix(),
74
+	}
75
+	tx := writeUserDb.Begin()
76
+	if err := tx.Create(&role).Error; err != nil {
77
+		tx.Rollback()
78
+		return nil, err
79
+	}
80
+	tx.Commit()
81
+	return &role, nil
82
+}
83
+
84
+func GetRoleByRoleID(roleID int64) (*models.Role, error) {
85
+	var role models.Role
86
+	err := readUserDb.Model(&models.Role{}).Where("id = ?", roleID).First(&role).Error
87
+	if err != nil {
88
+		if err == gorm.ErrRecordNotFound {
89
+			return nil, nil
90
+		}
91
+		return nil, err
92
+	} else {
93
+		return &role, nil
94
+	}
95
+}
96
+
97
+func ModifyRole(role *models.Role) error {
98
+	tx := writeUserDb.Begin()
99
+	if err := tx.Save(role).Error; err != nil {
100
+		tx.Rollback()
101
+		return err
102
+	}
103
+	return tx.Commit().Error
104
+}
105
+
106
+// 拥有xx角色的管理员的数量
107
+func RoleAdminUserCount(orgID int64, appID int64, roleID int64) (int, error) {
108
+	var count int
109
+	err := readUserDb.Model(models.App_Role{}).
110
+		Where("org_id = ? AND app_id = ? AND role_id = ? AND status = 1", orgID, appID, roleID).
111
+		Count(&count).
112
+		Error
113
+	if err != nil {
114
+		return 0, err
115
+	} else {
116
+		return count, nil
117
+	}
118
+}
119
+
120
+type AdminUserManageViewModel struct {
121
+	AdminUserId int    `gorm:"admin_user_id" json:"user_id"`
122
+	UserName    string `gorm:"user_name" json:"user_name"`
123
+	RoleName    string `gorm:"role_name" json:"role_name"`
124
+	UserTitle   int    `gorm:"user_title" json:"user_title"`
125
+	Ip          string `gorm:"ip" json:"ip"`
126
+	Ctime       int64  `gorm:"ctime" json:"last_login_time"`
127
+	Status      int    `gorm:"status" json:"status"`
128
+	Avatar      string `gorm:"avatar" json:"avatar"`
129
+	RoleIds     string `gorm:"role_ids" json:"role_ids"`
130
+	// LastLoginTimeStr string `gorm:"-" json:"last_login_time_formatted"`
131
+	TitleName       string `gorm:"-" json:"title_name"`
132
+	IsSubSuperAdmin bool   `gorm:"-" json:"is_sub_super_admin"`
133
+	//mobile          string `gorm:"-" json:"mobile"`
134
+	Sort     int `gorm:"sort" json:"sort"`
135
+	IsMark   int `gorm:"is_mark" json:"is_mark"`
136
+	UserType int `gorm:"user_type" json:"user_type"`
137
+}
138
+
139
+func GetAdminUsersAndLoginInfo(orgID int64, appID int64, page int, count int) ([]*AdminUserManageViewModel, int, error) {
140
+	if count <= 0 {
141
+		return []*AdminUserManageViewModel{}, 0, nil
142
+	}
143
+	if page < 1 {
144
+		page = 1
145
+	}
146
+	var viewModels []*AdminUserManageViewModel = make([]*AdminUserManageViewModel, 0)
147
+	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,u_a_r.is_mark,u_a_r.user_type 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()
148
+	defer rows.Close()
149
+	if err != nil {
150
+		if err == gorm.ErrRecordNotFound {
151
+			return viewModels, 0, nil
152
+		} else {
153
+			return nil, 0, err
154
+		}
155
+	}
156
+	for rows.Next() {
157
+		var viewModel AdminUserManageViewModel
158
+		readUserDb.ScanRows(rows, &viewModel)
159
+		title, _ := models.UserTitle[viewModel.UserTitle]
160
+		viewModel.TitleName = title
161
+		// if viewModel.Ctime == 0 {
162
+		// 	viewModel.LastLoginTimeStr = ""
163
+		// } else {
164
+		// 	loginTime := time.Unix(viewModel.Ctime, 0)
165
+		// 	viewModel.LastLoginTimeStr = loginTime.Format("2006-01-02 15:04")
166
+		// }
167
+		viewModels = append(viewModels, &viewModel)
168
+	}
169
+
170
+	for _, item := range viewModels {
171
+		if len(item.RoleIds) > 0 {
172
+			ids := strings.Split(item.RoleIds, ",")
173
+			for _, id := range ids {
174
+				id, _ := strconv.ParseInt(id, 10, 64)
175
+				if id != 0 {
176
+					role, _ := GetRoleByRoleID(id)
177
+					if role != nil {
178
+						if role.IsSystem == 1 && role.RoleName == "子管理员" {
179
+							item.IsSubSuperAdmin = true
180
+						}
181
+
182
+						if len(item.RoleName) == 0 {
183
+							item.RoleName = role.RoleName
184
+						} else {
185
+							item.RoleName = item.RoleName + "," + role.RoleName
186
+						}
187
+					}
188
+				}
189
+			}
190
+
191
+		}
192
+
193
+		//admin, _ := GetAdminUserByUserID(int64(item.AdminUserId))
194
+		//item.mobile = admin.Mobile
195
+
196
+	}
197
+
198
+	total := 0
199
+	//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)
200
+	return viewModels, total, nil
201
+}
202
+
203
+func GetValidRoleCount(orgID int64, appID int64, superAdminUserID int64) (int, error) {
204
+	var count int
205
+	err := readUserDb.Model(models.Role{}).
206
+		Where("org_id = ? AND app_id = ? AND creator = ? AND is_super_admin = 0 AND status = 1", orgID, appID, superAdminUserID).
207
+		Count(&count).
208
+		Error
209
+	if err != nil {
210
+		return 0, err
211
+	} else {
212
+		return count, nil
213
+	}
214
+}
215
+
216
+func GetAllValidRoles(orgID int64, appID int64) ([]*models.Role, error) {
217
+	var roles []*models.Role
218
+	err := readUserDb.Model(models.Role{}).
219
+		Where("org_id = ? AND app_id = ? AND status = 1", orgID, appID).
220
+		Order("number desc,ctime").
221
+		Find(&roles).
222
+		Error
223
+	if err != nil {
224
+		if err == gorm.ErrRecordNotFound {
225
+			return make([]*models.Role, 0), nil
226
+		} else {
227
+			return nil, err
228
+		}
229
+	}
230
+	return roles, nil
231
+}
232
+
233
+func IsRoleExist(orgID int64, appID int64, roleID int64) (bool, error) {
234
+	var count int
235
+	err := readUserDb.Model(models.Role{}).Where("org_id = ? AND app_id = ? AND id = ? AND status = 1", orgID, appID, roleID).Count(&count).Error
236
+	if err != nil {
237
+		return false, err
238
+	} else {
239
+		return count > 0, nil
240
+	}
241
+}
242
+
243
+type AdminUserEditViewModel struct {
244
+	AdminUserId int64  `gorm:"admin_user_id" json:"user_id"`
245
+	UserName    string `gorm:"user_name" json:"user_name"`
246
+	Mobile      string `gorm:"mobile" json:"mobile"`
247
+	UserType    int    `gorm:"user_type" json:"user_type"`
248
+	UserTitle   int    `gorm:"user_title" json:"user_title"`
249
+	Intro       string `gorm:"intro" json:"intro"`
250
+	RoleId      int64  `gorm:"role_id" json:"role_id"`
251
+}
252
+
253
+func GetGeneralAdminUser(orgID int64, appID int64, user_id int64) (*AdminUserEditViewModel, error) {
254
+	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()
255
+	defer rows.Close()
256
+	if err != nil {
257
+		if err == gorm.ErrRecordNotFound {
258
+			return nil, nil
259
+		} else {
260
+			return nil, err
261
+		}
262
+	}
263
+	if rows.Next() {
264
+		var viewModel AdminUserEditViewModel
265
+		err := readUserDb.ScanRows(rows, &viewModel)
266
+		if err != nil {
267
+			return nil, err
268
+		} else {
269
+			return &viewModel, nil
270
+		}
271
+	}
272
+	return nil, nil
273
+}
274
+
275
+func SaveAppRole(appRole *models.App_Role) error {
276
+	tx := writeUserDb.Begin()
277
+	if err := tx.Model(&models.App_Role{}).Save(appRole).Error; err != nil {
278
+		tx.Rollback()
279
+		return err
280
+	}
281
+	return tx.Commit().Error
282
+}
283
+
284
+func IsMobileDidUsedAtApp(orgID int64, appID int64, mobile string) (bool, error) {
285
+	var count int
286
+	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()
287
+	defer rows.Close()
288
+	if err != nil {
289
+		if err == gorm.ErrRecordNotFound {
290
+			return false, nil
291
+		} else {
292
+			return true, err
293
+		}
294
+	}
295
+	if rows.Next() {
296
+		rows.Scan(&count)
297
+		return count > 0, nil
298
+	}
299
+	return true, nil
300
+}
301
+
302
+func IsUserSuperAdminWithMobile(mobile string) (bool, error) {
303
+	var user models.AdminUser
304
+	err := readUserDb.Where("mobile = ?", mobile).First(&user).Error
305
+	if err != nil {
306
+		if err == gorm.ErrRecordNotFound {
307
+			return false, nil
308
+		} else {
309
+			return false, err
310
+		}
311
+	}
312
+	return user.IsSuperAdmin, nil
313
+}
314
+
315
+func CreateGeneralAdminUserOne(orgID int64, appID int64, mobile string, name string, userTitle string, roleIds string, user_type int, user_title int, department_id int64, deapartment_name string, sex int64, age int64, nation string, card_type int64, idCard string, education int64, studyMajorName string, workMajorName string, roletype int64, medicalCode string, doctorcode string, licensing int64, jobnumber string, prescriptionQualificationIdentification int64, identificationOutpatients int64, startime int64, medicalRangeCode int64, medicalLevel int64, medicalTypeJob int64, pharmacistRegistrationNumber string, doctorRangeCode int64, doctorLevel int64, doctorTypeJob int64, doctorNumber string, outpatientIllnessCategory string, isActive int64, activeStatus int64) (*models.AdminUser, string, error) {
316
+	now := time.Now().Unix()
317
+	tx := writeUserDb.Begin()
318
+	var adminUser models.AdminUser
319
+	err := readUserDb.Where("mobile = ? AND status = 1", mobile).First(&adminUser).Error
320
+	password := ""
321
+	if err != nil {
322
+		if err != gorm.ErrRecordNotFound {
323
+			return nil, "", err
324
+		} else {
325
+			password = utils.RandomNumberString(6)
326
+			adminUser.Mobile = mobile
327
+			adminUser.Password = utils.String2md5(password)
328
+			adminUser.IsSuperAdmin = false
329
+			adminUser.Status = 1
330
+			adminUser.CreateTime = now
331
+			adminUser.ModifyTime = now
332
+			if createErr := tx.Create(&adminUser).Error; createErr != nil {
333
+				tx.Rollback()
334
+				return nil, "", createErr
335
+			}
336
+		}
337
+	}
338
+	app_role := models.App_Role{
339
+		AdminUserId:                             adminUser.Id,
340
+		OrgId:                                   orgID,
341
+		AppId:                                   appID,
342
+		Avatar:                                  "",
343
+		UserName:                                name,
344
+		UserTitleName:                           userTitle,
345
+		UserTitle:                               int8(user_title),
346
+		UserType:                                int8(user_type),
347
+		Status:                                  1,
348
+		CreateTime:                              now,
349
+		ModifyTime:                              now,
350
+		RoleIds:                                 roleIds,
351
+		IsSort:                                  1,
352
+		Department:                              deapartment_name,
353
+		DepartmentId:                            department_id,
354
+		Sex:                                     sex,
355
+		Age:                                     age,
356
+		Nation:                                  nation,
357
+		CardType:                                card_type,
358
+		IdCard:                                  idCard,
359
+		Education:                               education,
360
+		StudyMajorName:                          studyMajorName,
361
+		WorkMajorName:                           workMajorName,
362
+		RoleType:                                roletype,
363
+		MedicalCode:                             medicalCode,
364
+		DoctorCode:                              doctorcode,
365
+		Licensing:                               licensing,
366
+		JobNumber:                               jobnumber,
367
+		PharmacistRegistrationNumber:            pharmacistRegistrationNumber,
368
+		IdentificationOutpatients:               identificationOutpatients,
369
+		StartTime:                               startime,
370
+		MedicalRangeCode:                        medicalRangeCode,
371
+		MedicalLevel:                            medicalLevel,
372
+		MedicalTypeJob:                          medicalTypeJob,
373
+		DoctorNumber:                            doctorNumber,
374
+		OutpatientIllnesscategory:               outpatientIllnessCategory,
375
+		IsActive:                                isActive,
376
+		ActiveStatus:                            activeStatus,
377
+		PrescriptionQualificationIdentification: prescriptionQualificationIdentification,
378
+		DoctorRangeCode:                         doctorRangeCode,
379
+		DoctorTypeJob:                           doctorTypeJob,
380
+		DoctorLevel:                             doctorLevel,
381
+	}
382
+	if createApp_RoleErr := tx.Create(&app_role).Error; createApp_RoleErr != nil {
383
+		tx.Rollback()
384
+		return nil, "", createApp_RoleErr
385
+	}
386
+
387
+	tx.Commit()
388
+	return &adminUser, password, nil
389
+}
390
+
391
+func CreateGeneralAdminUser(orgID int64, appID int64, mobile string, name string, userTitle string, roleIds string, user_type int, user_title int, department_id int64, deapartment_name string) (*models.AdminUser, string, error) {
392
+	now := time.Now().Unix()
393
+	tx := writeUserDb.Begin()
394
+	var adminUser models.AdminUser
395
+	err := readUserDb.Where("mobile = ? AND status = 1", mobile).First(&adminUser).Error
396
+	password := ""
397
+	if err != nil {
398
+		if err != gorm.ErrRecordNotFound {
399
+			return nil, "", err
400
+		} else {
401
+			password = utils.RandomNumberString(6)
402
+			adminUser.Mobile = mobile
403
+			adminUser.Password = utils.String2md5(password)
404
+			adminUser.IsSuperAdmin = false
405
+			adminUser.Status = 1
406
+			adminUser.CreateTime = now
407
+			adminUser.ModifyTime = now
408
+			if createErr := tx.Create(&adminUser).Error; createErr != nil {
409
+				tx.Rollback()
410
+				return nil, "", createErr
411
+			}
412
+		}
413
+	}
414
+	app_role := models.App_Role{
415
+		AdminUserId:   adminUser.Id,
416
+		OrgId:         orgID,
417
+		AppId:         appID,
418
+		Avatar:        "",
419
+		UserName:      name,
420
+		UserTitleName: userTitle,
421
+		UserTitle:     int8(user_title),
422
+		UserType:      int8(user_type),
423
+		Status:        1,
424
+		CreateTime:    now,
425
+		ModifyTime:    now,
426
+		RoleIds:       roleIds,
427
+		IsSort:        1,
428
+		Department:    deapartment_name,
429
+		DepartmentId:  department_id,
430
+	}
431
+	if createApp_RoleErr := tx.Create(&app_role).Error; createApp_RoleErr != nil {
432
+		tx.Rollback()
433
+		return nil, "", createApp_RoleErr
434
+	}
435
+
436
+	tx.Commit()
437
+	return &adminUser, password, nil
438
+}
439
+
440
+type PurviewTreeViewModel struct {
441
+	ID        int64                   `json:"id"`
442
+	PID       int64                   `json:"pid"`
443
+	Name      string                  `json:"name"`
444
+	Childs    []*PurviewTreeViewModel `json:"childs"`
445
+	Number    int64                   `json:"number"`
446
+	Url       string                  `json:"url"`
447
+	ParentUrl string                  `json:"parent_url"`
448
+}
449
+
450
+func GetAllGeneralPurviewVMsProcessed(module int) ([]*PurviewTreeViewModel, error) {
451
+	var originPurviews []*models.Purview
452
+	getPurviewErr := readUserDb.Model(models.Purview{}).Where("module = ? AND status = 1", module).Order("listorder asc").Order("id asc").Find(&originPurviews).Error
453
+	if getPurviewErr != nil {
454
+		return nil, getPurviewErr
455
+	}
456
+	// 加工这些规则:树形化
457
+	purviewVMs := make([]*PurviewTreeViewModel, 0)
458
+	pid_childs := make(map[int64][]*PurviewTreeViewModel)
459
+	for _, purview := range originPurviews {
460
+		// warning:下面这个算法只适用最多两层树形结构的菜单,对于两层以上的会丢失掉第三层及其以下的节点
461
+		// 因为取出 originPurviews 的时候已经排过序了,所以顶级节点肯定最先处理,不需要担心子节点比父节点先处理
462
+		pvm := &PurviewTreeViewModel{
463
+			ID:     purview.Id,
464
+			PID:    purview.Parentid,
465
+			Name:   purview.Name,
466
+			Number: 2,
467
+		}
468
+		if purview.Parentid == 0 {
469
+			purviewVMs = append(purviewVMs, pvm)
470
+		} else {
471
+			childs := pid_childs[purview.Parentid]
472
+			if childs == nil {
473
+				childs = make([]*PurviewTreeViewModel, 0)
474
+			}
475
+			childs = append(childs, pvm)
476
+			pid_childs[purview.Parentid] = childs
477
+		}
478
+	}
479
+
480
+	for _, vm := range purviewVMs {
481
+		vm.Childs = pid_childs[vm.ID]
482
+	}
483
+
484
+	return purviewVMs, nil
485
+}
486
+
487
+func GetAllGeneralFuncPurviewVMsProcessed() ([]*PurviewTreeViewModel, error) {
488
+	var originPurviews []*models.SgjUserOperatePurview
489
+	getPurviewErr := readUserDb.Model(models.SgjUserOperatePurview{}).Where(" status = 1").Order("number asc").Find(&originPurviews).Error
490
+	if getPurviewErr != nil {
491
+		return nil, getPurviewErr
492
+	}
493
+	// 加工这些规则:树形化
494
+	purviewVMs := make([]*PurviewTreeViewModel, 0)
495
+	for _, purview := range originPurviews {
496
+		// warning:下面这个算法只适用最多两层树形结构的菜单,对于两层以上的会丢失掉第三层及其以下的节点
497
+		// 因为取出 originPurviews 的时候已经排过序了,所以顶级节点肯定最先处理,不需要担心子节点比父节点先处理
498
+		pvm := &PurviewTreeViewModel{
499
+			ID:   purview.ID,
500
+			PID:  purview.Parentid,
501
+			Name: purview.Name,
502
+		}
503
+		purviewVMs = append(purviewVMs, pvm)
504
+
505
+	}
506
+
507
+	return purviewVMs, nil
508
+}
509
+
510
+func GetRolePurviewIds(roleID int64) (string, error) {
511
+	var rolePurview models.RolePurview
512
+	err := readUserDb.Where("role_id = ?", roleID).First(&rolePurview).Error
513
+	if err != nil {
514
+		if err == gorm.ErrRecordNotFound {
515
+			return "", nil
516
+		} else {
517
+			return "", err
518
+		}
519
+	}
520
+	return rolePurview.PurviewIds, nil
521
+}
522
+
523
+func SaveRolePurviewIds(orgID int64, appID int64, roleID int64, purviewIds string) error {
524
+	var rolePurview models.RolePurview
525
+	getRPErr := readUserDb.Where("org_id = ? AND app_id = ? AND role_id = ?", orgID, appID, roleID).First(&rolePurview).Error
526
+	if getRPErr != nil {
527
+		if getRPErr == gorm.ErrRecordNotFound {
528
+			rolePurview = models.RolePurview{
529
+				RoleId:     roleID,
530
+				OrgId:      orgID,
531
+				AppId:      appID,
532
+				Status:     1,
533
+				CreateTime: time.Now().Unix(),
534
+			}
535
+		} else {
536
+			return getRPErr
537
+		}
538
+	}
539
+	rolePurview.PurviewIds = purviewIds
540
+	rolePurview.ModifyTime = time.Now().Unix()
541
+	tx := writeUserDb.Begin()
542
+	if err := tx.Save(&rolePurview).Error; err != nil {
543
+		tx.Rollback()
544
+		return err
545
+	}
546
+	return tx.Commit().Error
547
+}
548
+
549
+func SaveFuncRolePurviewIds(orgID int64, appID int64, roleID int64, funcPurviewIds string) error {
550
+	var rolePurview models.SgjUserRoleFuncPurview
551
+	getRPErr := readUserDb.Where("org_id = ? AND app_id = ? AND role_id = ?", orgID, appID, roleID).First(&rolePurview).Error
552
+	if getRPErr != nil {
553
+		if getRPErr == gorm.ErrRecordNotFound {
554
+			rolePurview = models.SgjUserRoleFuncPurview{
555
+				RoleId: roleID,
556
+				OrgId:  orgID,
557
+				AppId:  appID,
558
+				Status: 1,
559
+				Ctime:  time.Now().Unix(),
560
+			}
561
+		} else {
562
+			return getRPErr
563
+		}
564
+	}
565
+	rolePurview.PurviewIds = funcPurviewIds
566
+	rolePurview.Mtime = time.Now().Unix()
567
+	tx := writeUserDb.Begin()
568
+	if err := tx.Save(&rolePurview).Error; err != nil {
569
+		tx.Rollback()
570
+		return err
571
+	}
572
+	return tx.Commit().Error
573
+}
574
+
575
+func ModifyAdminUserInfo(adminUserID int64, orgID int64, appID int64, name string, avatar string, newPassword string) error {
576
+	tx := writeUserDb.Begin()
577
+	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
578
+	if editInfoErr != nil {
579
+		tx.Rollback()
580
+		return editInfoErr
581
+	}
582
+	if len(newPassword) > 0 {
583
+		editPwdErr := tx.Exec("update sgj_user_admin set password = ?, mtime = ? where id = ?", newPassword, time.Now().Unix(), adminUserID).Error
584
+		if editPwdErr != nil {
585
+			tx.Rollback()
586
+			return editPwdErr
587
+		}
588
+	}
589
+	tx.Commit()
590
+	return nil
591
+}
592
+
593
+func GetOrgApp(orgID int64, app_type int) (*models.OrgApp, error) {
594
+	var apps models.OrgApp
595
+	err := readUserDb.Where("app_type = ? AND org_id = ? AND status = 1", app_type, orgID).First(&apps).Error
596
+	if err != nil {
597
+		return nil, err
598
+	}
599
+	return &apps, nil
600
+}
601
+
602
+func GetAllOrgValidRoles(orgID int64, isSubSuperAdmin bool) ([]*models.Role, error) {
603
+	var roles []*models.Role
604
+	db := readUserDb.Model(models.Org{})
605
+	if isSubSuperAdmin {
606
+		db = db.Where("role_name != '子管理员' AND is_system  != 1")
607
+	}
608
+	err := db.Where("org_id = ? AND status = 1", orgID).
609
+		Order("number desc,ctime").
610
+		Find(&roles).
611
+		Error
612
+	if err != nil {
613
+		if err == gorm.ErrRecordNotFound {
614
+			return make([]*models.Role, 0), nil
615
+		} else {
616
+			return nil, err
617
+		}
618
+	}
619
+	for _, item := range roles {
620
+		var total int64
621
+		readUserDb.Model(&models.App_Role{}).Where("org_id = ? AND find_in_set(?, role_ids)", orgID, item.Id).Count(&total)
622
+		item.StaffNumber = total
623
+	}
624
+	return roles, nil
625
+}
626
+
627
+func CreateUserRole(userRole *models.App_Role) (err error) {
628
+	err = writeUserDb.Create(&userRole).Error
629
+	return
630
+}
631
+
632
+func CreateOrgRole(role *models.Role) (err error) {
633
+	err = writeUserDb.Create(&role).Error
634
+	return
635
+}
636
+
637
+func GetRolePurview(roleID int64) (models.RolePurview, error) {
638
+	var rolePurviews models.RolePurview
639
+	var err error
640
+	err = readUserDb.Where("role_id = ?", roleID).First(&rolePurviews).Error
641
+	return rolePurviews, err
642
+}
643
+
644
+func GetFuncRolePurview(roleID int64) (models.SgjUserRoleFuncPurview, error) {
645
+	var rolePurviews models.SgjUserRoleFuncPurview
646
+	var err error
647
+	err = readUserDb.Where("role_id = ?", roleID).First(&rolePurviews).Error
648
+	return rolePurviews, err
649
+}
650
+
651
+func SaveRolePurview(purview *models.RolePurview) (err error) {
652
+	err = writeUserDb.Save(&purview).Error
653
+	return
654
+}
655
+
656
+func CreateRolePurview(purview *models.RolePurview) (err error) {
657
+	err = writeUserDb.Create(&purview).Error
658
+	return
659
+}
660
+
661
+func CreateFuncRolePurview(purview *models.SgjUserRoleFuncPurview) (err error) {
662
+	err = writeUserDb.Create(&purview).Error
663
+	return
664
+}
665
+
666
+func GetAllPurview(module int64, pid int64) ([]*models.Purview, error) {
667
+	var originPurviews []*models.Purview
668
+	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
669
+	return originPurviews, getPurviewErr
670
+}
671
+
672
+type NewAdminUserModel struct {
673
+	ID          int64  `gorm:"id" json:"id"`
674
+	AdminUserId int    `gorm:"admin_user_id" json:"user_id"`
675
+	UserName    string `gorm:"user_name" json:"user_name"`
676
+	UserTitle   int    `gorm:"user_title_name" json:"user_title_name"`
677
+	Ip          string `gorm:"ip" json:"ip"`
678
+	Ctime       int64  `gorm:"ctime" json:"last_login_time"`
679
+	Status      int    `gorm:"status" json:"status"`
680
+	Avatar      string `gorm:"avatar" json:"avatar"`
681
+	RoleIds     string `gorm:"role_ids" json:"role_ids"`
682
+	IsSubAdmin  bool   `gorm:"-" json:"is_sub_admin"`
683
+}
684
+
685
+func GetAllAdminUsersAndRole(orgID int64, appID int64, page int, count int) ([]*NewAdminUserModel, int, error) {
686
+	var viewModels []*NewAdminUserModel = make([]*NewAdminUserModel, 0)
687
+	var rows *sql.Rows
688
+	var err error
689
+	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()
690
+	defer rows.Close()
691
+	if err != nil {
692
+		if err == gorm.ErrRecordNotFound {
693
+			return viewModels, 0, nil
694
+		} else {
695
+			return nil, 0, err
696
+		}
697
+	}
698
+	for rows.Next() {
699
+		var viewModel NewAdminUserModel
700
+		readUserDb.ScanRows(rows, &viewModel)
701
+		viewModels = append(viewModels, &viewModel)
702
+	}
703
+
704
+	for _, items := range viewModels {
705
+		if len(items.RoleIds) > 0 {
706
+			ids := strings.Split(items.RoleIds, ",")
707
+			for _, ids := range ids {
708
+				id, _ := strconv.ParseInt(ids, 10, 64)
709
+				if id != 0 {
710
+					role, _ := GetRoleByRoleID(id)
711
+					if role != nil {
712
+						if role.IsSystem == 1 && role.RoleName == "子管理员" {
713
+							items.IsSubAdmin = true
714
+						}
715
+					}
716
+				}
717
+			}
718
+		}
719
+	}
720
+
721
+	total := 0
722
+	return viewModels, total, nil
723
+}
724
+
725
+func FindAdminUserByID(admin_user_id int64, org_id int64) (total int64, err error) {
726
+	err = readUserDb.Model(&models.App_Role{}).Where("admin_user_id = ? AND org_id = ?", admin_user_id, org_id).Count(&total).Error
727
+	return
728
+}
729
+
730
+func GetRoleAndPurviewById(role_id int64, org_id int64, app_id int64) (rolePurview models.RolePurview, err error) {
731
+	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
732
+	return
733
+}
734
+
735
+func SaveRole(role *models.Role) (err error) {
736
+	err = writeUserDb.Save(&role).Error
737
+	return
738
+}
739
+
740
+// 拥有xx角色的管理员的数量
741
+func RoleAdminUserCountTwo(orgID int64, appID int64, roleID int64) (int, error) {
742
+	var count int
743
+	err := readUserDb.Model(models.App_Role{}).
744
+		Where("org_id = ? AND app_id = ? AND find_in_set(?, role_ids)", orgID, appID, roleID).
745
+		Count(&count).
746
+		Error
747
+	if err != nil {
748
+		return 0, err
749
+	} else {
750
+		return count, nil
751
+	}
752
+}
753
+
754
+func FindAdminUserID(id int64) (role models.App_Role, err error) {
755
+	err = readUserDb.Model(&models.App_Role{}).Where("id = ?", id).First(&role).Error
756
+	return
757
+}
758
+
759
+func SaveAdminUser(role *models.App_Role) (err error) {
760
+	err = writeUserDb.Save(&role).Error
761
+	return
762
+}
763
+
764
+func GetFunctionPurview(pid int64) (purview []*models.SgjUserOperatePurview, err error) {
765
+	err = readUserDb.Model(&models.SgjUserOperatePurview{}).Where("status = 1  AND parentid = ?", pid).Order("number asc").Find(&purview).Error
766
+	return
767
+}
768
+
769
+func GetRoleFuncPurviewIds(roleID int64) (string, error) {
770
+	var rolePurview models.SgjUserRoleFuncPurview
771
+	err := readUserDb.Where("role_id = ?", roleID).First(&rolePurview).Error
772
+	if err != nil {
773
+		if err == gorm.ErrRecordNotFound {
774
+			return "", nil
775
+		} else {
776
+			return "", err
777
+		}
778
+	}
779
+	return rolePurview.PurviewIds, nil
780
+}
781
+
782
+func GetRoleFuncPurview(roleID int64) (rolePurviews models.SgjUserRoleFuncPurview, err error) {
783
+	err = readUserDb.Where("role_id = ?", roleID).First(&rolePurviews).Error
784
+	return
785
+}
786
+
787
+func SaveRoleFuncPurview(purview *models.SgjUserRoleFuncPurview) (err error) {
788
+	err = writeUserDb.Save(purview).Error
789
+	return
790
+}
791
+
792
+func GetUserAllRole(org_id int64, admin_user_id int64) (role models.App_Role, err error) {
793
+	err = readUserDb.Model(&models.App_Role{}).Where("status = 1 AND org_id = ? AND admin_user_id = ?", org_id, admin_user_id).First(&role).Error
794
+	return
795
+}
796
+
797
+func GetAllFunctionPurview() (purview []models.SgjUserOperatePurview, err error) {
798
+	err = readUserDb.Model(&models.SgjUserOperatePurview{}).Where("status = 1 ").Order("number asc").Find(&purview).Error
799
+	return
800
+}
801
+
802
+func FindErrorMsgByStr(str string) (string, error) {
803
+	var purview models.SgjUserOperatePurview
804
+	var err error
805
+	err = readUserDb.Model(&models.SgjUserOperatePurview{}).Where("find_in_set(?, urlfor)", str).First(&purview).Error
806
+	return purview.ErrorMsg, err
807
+
808
+}
809
+
810
+func GetNewAllOrgValidRoles(orgID int64) ([]*models.Role, error) {
811
+	var roles []*models.Role
812
+	db := readUserDb.Model(models.Org{})
813
+	err := db.Where("org_id = ? AND status = 1", orgID).
814
+		Order("number desc,ctime").
815
+		Find(&roles).
816
+		Error
817
+	if err != nil {
818
+		if err == gorm.ErrRecordNotFound {
819
+			return make([]*models.Role, 0), nil
820
+		} else {
821
+			return nil, err
822
+		}
823
+	}
824
+	for _, item := range roles {
825
+		var total int64
826
+		readUserDb.Model(&models.App_Role{}).Where("org_id = ? AND find_in_set(?, role_ids)", orgID, item.Id).Count(&total)
827
+		item.StaffNumber = total
828
+	}
829
+	return roles, nil
830
+}
831
+
832
+func FindRoleRecordByRoleName(name string, org_id int64) (total int64) {
833
+	readUserDb.Model(&models.Role{}).Where("status = 1 AND role_name = ? AND org_id = ?", name, org_id).Count(&total)
834
+	return
835
+}
836
+
837
+func FindAllFuncPurview(ids []string) (purview []*models.SgjUserOperatePurview, err error) {
838
+	err = readUserDb.Model(&models.SgjUserOperatePurview{}).Where("status = 1 AND id in (?)", ids).Order("number asc").Find(&purview).Error
839
+	return
840
+
841
+}
842
+
843
+func GetSystemPurview() (purview []*models.Purview, err error) {
844
+	err = readUserDb.Model(&models.Purview{}).Where("status = 1 AND module = 3 AND super_admin_exclusive = 1").Find(&purview).Error
845
+	return
846
+}
847
+
848
+func GetAllSystemPurview() (purview []*models.Purview, err error) {
849
+	err = readUserDb.Model(&models.Purview{}).Where("status = 1 AND module = 3 ").Find(&purview).Error
850
+	return
851
+}
852
+
853
+type Purview struct {
854
+	Id                  int64      `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id"`
855
+	Parentid            int64      `json:"pid"`                                                // 父级ID
856
+	Module              int8       `json:"module"`                                             // 所属应用类型 1.病友经营;2.科普号;3.血透经营;4.慢病管理;
857
+	Name                string     `json:"name"`                                               // 规则名称(也是菜单名)
858
+	Urlfor              string     `json:"urlfor"`                                             // 规则唯一英文标识,(Controller.Method)
859
+	MenuIconClass       string     `gorm:"menu_icon_class" json:"menu_icon_class"`             // 菜单图标的 css 样式
860
+	SuperAdminExclusive int8       `gorm:"super_admin_exclusive" json:"super_admin_exclusive"` // 是否为超级管理员专属 0否1是
861
+	Listorder           int        `json:"-"`                                                  // 排序ID
862
+	Status              int8       `json:"status"`                                             // 状态 0.无效 1.有效 2.禁用
863
+	CreateTime          int64      `gorm:"column:ctime" json:"-"`                              // 创建时间
864
+	ModifyTime          int64      `gorm:"column:mtime" json:"-"`                              // 修改时间
865
+	Purview             []*Purview `gorm:"ForeignKey:Parentid;AssociationForeignKey:ID" json:"sub_purview"`
866
+	IconUrl             string     `gorm:"column:icon_url" json:"icon_url" form:"icon_url"`
867
+	Desc                string     `gorm:"column:desc" json:"desc" form:"desc"`
868
+	ParentUrl           string     `gorm:"column:parent_url" json:"parent_url" form:"parent_url"`
869
+	Link                string     `gorm:"-" json:"link"`   // urlfor 解析后的链接
870
+	Childs              []*Purview `gorm:"-" json:"childs"` // 子节点
871
+}
872
+
873
+func (Purview) TableName() string {
874
+	return "sgj_user_purview"
875
+}
876
+
877
+func GetNewAllPurview(url string) ([]*Purview, error) {
878
+	var originPurviews []*Purview
879
+	getPurviewErr := readUserDb.Model(Purview{}).Preload("Purview", "status = 1").Where("parent_url = ? AND status = 1", url).Order("listorder asc").Order("id asc").Find(&originPurviews).Error
880
+	return originPurviews, getPurviewErr
881
+}
882
+
883
+func GetOtherNewAllPurview(url string) ([]*Purview, error) {
884
+	var originPurviews []*Purview
885
+	getPurviewErr := readUserDb.Model(Purview{}).Preload("Purview", func(db *gorm.DB) *gorm.DB {
886
+		return db.Preload("Purview", "status = 1").Where("status = 1")
887
+	}).Where("parent_url = ? AND status = 1", url).Order("listorder asc").Order("id asc").Find(&originPurviews).Error
888
+	return originPurviews, getPurviewErr
889
+}
890
+
891
+func GetAllFuncPurview() ([]*models.SgjUserOperatePurview, error) {
892
+	var originPurviews []*models.SgjUserOperatePurview
893
+	getPurviewErr := readUserDb.Model(&models.SgjUserOperatePurview{}).Where(" status = 1").Error
894
+	return originPurviews, getPurviewErr
895
+}
896
+
897
+func GetOtherAllGeneralPurviewVMsProcessed(url string) ([]*PurviewTreeViewModel, error, []*models.Purview) {
898
+	var originPurviews []*models.Purview
899
+	getPurviewErr := readUserDb.Model(Purview{}).Where("status = 1 AND parent_url = ?", url).Order("listorder asc").Order("id asc").Find(&originPurviews).Error
900
+	if getPurviewErr != nil {
901
+		return nil, getPurviewErr, nil
902
+	}
903
+	// 加工这些规则:树形化
904
+	purviewVMs := make([]*PurviewTreeViewModel, 0)
905
+	pid_childs := make(map[int64][]*PurviewTreeViewModel)
906
+	fmt.Println(originPurviews)
907
+	for _, purview := range originPurviews {
908
+		// warning:下面这个算法只适用最多两层树形结构的菜单,对于两层以上的会丢失掉第三层及其以下的节点
909
+		// 因为取出 originPurviews 的时候已经排过序了,所以顶级节点肯定最先处理,不需要担心子节点比父节点先处理
910
+		pvm := &PurviewTreeViewModel{
911
+			ID:        purview.Id,
912
+			PID:       purview.Parentid,
913
+			Name:      purview.Name,
914
+			Number:    2,
915
+			ParentUrl: purview.ParentUrl,
916
+			Url:       purview.Urlfor,
917
+		}
918
+		if purview.Parentid == 0 {
919
+
920
+			purviewVMs = append(purviewVMs, pvm)
921
+		} else {
922
+			childs := pid_childs[purview.Parentid]
923
+
924
+			if childs == nil {
925
+				childs = make([]*PurviewTreeViewModel, 0)
926
+			}
927
+			childs = append(childs, pvm)
928
+			pid_childs[purview.Parentid] = childs
929
+		}
930
+	}
931
+
932
+	for _, vm := range purviewVMs {
933
+		vm.Childs = pid_childs[vm.ID]
934
+	}
935
+
936
+	return purviewVMs, nil, originPurviews
937
+}

+ 977 - 0
service/schedule_service.go Bestand weergeven

@@ -0,0 +1,977 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_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).Order("").Find(&partitions).Error
17
+
18
+	return
19
+}
20
+
21
+func GetSchedulePartitionPanelOne(orgID int64, partionId int64) (partitions []*models.Partition, err error) {
22
+
23
+	if partionId > 0 {
24
+		err = readDb.Model(&models.DeviceZone{}).Preload("Jihaos", "org_id=? and status=1 and zone_id = ?", orgID, partionId).Where("org_id=? and status=1 and id = ?", orgID, partionId).Find(&partitions).Error
25
+	}
26
+	if partionId == 0 {
27
+		err = readDb.Model(&models.DeviceZone{}).Preload("Jihaos", "org_id=? and status=1", orgID).Where("org_id=? and status=1", orgID).Find(&partitions).Error
28
+	}
29
+
30
+	return
31
+}
32
+
33
+func GetSchedulePartitionPanelTwo(orgID int64, schIDs []string) (partitions []*models.Partition, err error) {
34
+
35
+	if len(schIDs) == 0 {
36
+		err = readDb.Model(&models.DeviceZone{}).Preload("Jihaos", "org_id=? and status=1", orgID).Where("org_id=? and status=1", orgID).Find(&partitions).Error
37
+	}
38
+	if len(schIDs) > 0 {
39
+		err = readDb.Model(&models.DeviceZone{}).Preload("Jihaos", "org_id=? and status=1 and zone_id in(?)", orgID, schIDs).Where("org_id=? and status=1 and id in(?)", orgID, schIDs).Find(&partitions).Error
40
+	}
41
+
42
+	return
43
+}
44
+
45
+func GetPatientWithScheduleAndSolution(orgID int64, keywords string, weekStart, weekEnd, schedule, contagion int64) (patients []*models.Patients, err error) {
46
+	db := readDb.Table("xt_patients as p").
47
+		Preload("DialysisSolutions", "user_org_id=? and initiate_mode=1 and affirm_state=1 and parent_id=0 and status=1", orgID).
48
+		Preload("Schedules", "user_org_id=? and schedule_date>=? and schedule_date<= ? and status=1", orgID, weekStart, weekEnd).
49
+		Preload("Contagions", "status=1").
50
+		Where("p.user_org_id=? and p.lapseto=1 and p.status=1", orgID)
51
+	if len(keywords) > 0 {
52
+		likeKey := "%" + keywords + "%"
53
+		db = db.Where("p.name LIKE ?", likeKey)
54
+	}
55
+
56
+	if schedule == 1 {
57
+		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())
58
+	} else if schedule == 2 {
59
+		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())
60
+	}
61
+	if contagion > 0 {
62
+		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())
63
+	}
64
+
65
+	err = db.Find(&patients).Error
66
+	return
67
+}
68
+
69
+func GetWeekSchedule(orgID int64, start, end int64) (schedules []*models.Schedule, err error) {
70
+
71
+	err = readDb.Table("xt_schedule as s").Preload("PatientInfectiousDiseases", "status = 1 ").
72
+		Joins("JOIN xt_patients as p ON p.id = s.patient_id").
73
+		Where("s.user_org_id=? and s.schedule_date>=? and s.schedule_date<=? and s.status=1", orgID, start, end).
74
+		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").
75
+		Order("updated_time asc").
76
+		Find(&schedules).Error
77
+	return
78
+}
79
+
80
+func GetWeekScheduleOne(orgID int64, start, end int64, partionid int64, scheduletype int64) (schedules []*models.Schedule, err error) {
81
+
82
+	db := readDb.Table("xt_schedule as s")
83
+	if partionid > 0 {
84
+		db = db.Where("s.partition_id = ?", partionid)
85
+	}
86
+	if scheduletype > 0 {
87
+		db = db.Where("s.schedule_type = ?", scheduletype)
88
+	}
89
+	err = db.Preload("PatientInfectiousDiseases", "status = 1 ").
90
+		Joins("JOIN xt_patients as p ON p.id = s.patient_id").
91
+		Where("s.user_org_id=? and s.schedule_date>=? and s.schedule_date<=? and s.status=1", orgID, start, end).
92
+		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").
93
+		Order("updated_time asc").
94
+		Find(&schedules).Error
95
+	return
96
+}
97
+
98
+func GetWeekScheduleTwo(orgID int64, start, end int64, schIds []string, scheduletype int64) (schedules []*models.Schedule, err error) {
99
+
100
+	db := readDb.Table("xt_schedule as s")
101
+	fmt.Println("schIds2222222")
102
+	if len(schIds) > 0 {
103
+		db = db.Where("s.partition_id in (?)", schIds)
104
+	}
105
+	if scheduletype > 0 {
106
+		db = db.Where("s.schedule_type = ?", scheduletype)
107
+	}
108
+	err = db.Preload("PatientInfectiousDiseases", "status = 1 ").
109
+		Joins("JOIN xt_patients as p ON p.id = s.patient_id").
110
+		Where("s.user_org_id=? and s.schedule_date>=? and s.schedule_date<=? and s.status=1", orgID, start, end).
111
+		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").
112
+		Order("updated_time asc").
113
+		Find(&schedules).Error
114
+	return
115
+}
116
+
117
+func GetDaySchedule(orgID, start, end, patientID int64) (schedule models.Schedule, err error) {
118
+	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
119
+	return
120
+}
121
+
122
+func GetDayScheduleTwo(orgID, start, patientID int64) (schedule models.Schedule, err error) {
123
+	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
124
+	return
125
+}
126
+
127
+func GetDayScheduleByBedid(orgID, start, bed_id int64, schedule_type int64) (schedule models.Schedule, err error) {
128
+	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
129
+	return
130
+}
131
+
132
+func GetPatientScheduleFormDay(orgID, start, end, patientID int64) (schedules []*models.PatientSchedule, err error) {
133
+
134
+	err = readDb.Table("xt_schedule as s").
135
+		Preload("DeviceZone", "org_id=? and status=1", orgID).
136
+		Preload("DeviceNumber", "org_id=? and status=1", orgID).
137
+		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).
138
+		Find(&schedules).Error
139
+
140
+	return
141
+}
142
+
143
+func GetNextSchedule(orgID, end, patientID int64) (schedules []*models.PatientSchedule, err error) {
144
+	err = readDb.Table("xt_schedule as s").
145
+		Preload("DeviceZone", "org_id=? and status=1", orgID).
146
+		Preload("DeviceNumber", "org_id=? and status=1", orgID).
147
+		Where("s.patient_id =? and s.user_org_id=? and s.schedule_date>=?  and s.status=1", patientID, orgID, end).
148
+		Find(&schedules).Error
149
+
150
+	return
151
+}
152
+
153
+func GetPointSchedule(orgID, scheduleDate, scheduleWeek, scheduleType, bedId int64) (schedule models.Schedule, err error) {
154
+	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
155
+
156
+	if err == gorm.ErrRecordNotFound {
157
+		err = nil
158
+		return
159
+	}
160
+	return
161
+}
162
+
163
+func CreateSchedule(m *models.Schedule) error {
164
+	return writeDb.Model(&models.Schedule{}).Create(&m).Error
165
+}
166
+
167
+func GetTodayScheduleIsExist(patientid int64, schedudate int64, orgid int64, mode_id int64, schedule_type int64) (*models.XtSchedule, error) {
168
+	var scheudle models.XtSchedule
169
+	var err error
170
+	err = XTReadDB().Model(&scheudle).Where("patient_id = ? and schedule_date= ? and user_org_id = ? and status = 1 and mode_id = ? and schedule_type = ?", patientid, schedudate, orgid, mode_id, schedule_type).Find(&scheudle).Error
171
+	if err == gorm.ErrRecordNotFound {
172
+		return nil, err
173
+	}
174
+	if err != nil {
175
+		return nil, err
176
+	}
177
+	return &scheudle, nil
178
+}
179
+
180
+func UpdateScheduleByOrgId(patientid int64, scheduledate int64, orgid int64, mode_id int64, schedule_type int64, sch *models.XtSchedule) error {
181
+	err := XTWriteDB().Model(&sch).Where("patient_id = ? and schedule_date= ? and user_org_id = ? and status = 1 and mode_id = ? and schedule_type = ?", patientid, scheduledate, orgid, mode_id, schedule_type).Updates(map[string]interface{}{"partition_id": sch.PartitionId, "bed_id": sch.BedId, "schedule_type": sch.ScheduleType, "schedule_week": sch.ScheduleWeek, "mode_id": sch.ModeId, "updated_time": time.Now().Unix()}).Error
182
+	return err
183
+}
184
+
185
+func GetSchedule(orgID, id int64) (*models.Schedule, error) {
186
+	var schedule models.Schedule
187
+	var err error
188
+	err = readDb.Model(&models.Schedule{}).Where("id = ? and user_org_id=? and status=1", id, orgID).First(&schedule).Error
189
+	if err != nil {
190
+		return nil, err
191
+	}
192
+	return &schedule, nil
193
+}
194
+
195
+func UpdateSchedule(m *models.Schedule) error {
196
+	return writeDb.Model(&models.Schedule{}).Save(&m).Error
197
+}
198
+
199
+func GetPatientScheduleFormToday(orgId, id, start int64) (schedules []*models.PatientSchedule, err error) {
200
+
201
+	err = readDb.Table("xt_schedule as s").
202
+		Preload("DeviceZone", "org_id=? and status=1", orgId).
203
+		Preload("DeviceNumber", "org_id=? and status=1", orgId).
204
+		Where("s.patient_id =? and s.user_org_id=? and s.schedule_date>=? and s.status=1", id, orgId, start).
205
+		Find(&schedules).Error
206
+
207
+	return
208
+}
209
+
210
+type WeekSchedulePrintVM struct {
211
+	ID             int64 `gorm:"column:id" json:"id"`
212
+	ZoneID         int64 `gorm:"column:partition_id" json:"zone_id"`
213
+	DeviceNumberID int64 `gorm:"column:bed_id" json:"device_number_id"`
214
+	PatientID      int64 `gorm:"column:patient_id" json:"patient_id"`
215
+	ScheduleDate   int64 `gorm:"column:schedule_date" json:"schedule_date"`
216
+	ScheduleType   int64 `gorm:"column:schedule_type" json:"schedule_type"`
217
+	ScheduleWeek   int64 `gorm:"column:schedule_week" json:"schedule_week"`
218
+	ModeID         int64 `gorm:"column:mode_id" json:"mode_id"`
219
+
220
+	Patient      *models.Patients      `gorm:"ForeignKey:PatientID" json:"patient"`
221
+	DeviceNumber *models.DeviceNumber  `gorm:"ForeignKey:DeviceNumberID" json:"device_number"`
222
+	Zone         *models.DeviceZone    `gorm:"ForeignKey:ZoneID" json:"zone"`
223
+	Mode         *models.TreatmentMode `gorm:"ForeignKey:ModeID" json:"mode"`
224
+}
225
+
226
+type PrintCount struct {
227
+	ScheduleType int64 `gorm:"column:schedule_type" json:"schedule_type"`
228
+	ScheduleWeek int64 `gorm:"column:schedule_week" json:"schedule_week"`
229
+	Count        int64
230
+}
231
+
232
+func GetPrinitWeekSchedules(orgID int64, start, end int64) ([]*WeekSchedulePrintVM, error) {
233
+	var schedules []*WeekSchedulePrintVM
234
+	err := readDb.Table("xt_schedule as s").
235
+		Preload("Patient", "status = 1 and user_org_id = ?", orgID).
236
+		Preload("DeviceNumber", "status = 1 and org_id = ?", orgID).
237
+		Preload("Zone", "status = 1 and org_id = ?", orgID).
238
+		Preload("Mode", "status = 1").
239
+		// Joins("JOIN xt_patients as p ON p.id = s.patient_id").
240
+		Where("s.user_org_id = ? and s.schedule_date >= ? and s.schedule_date <= ? and s.status = 1", orgID, start, end).
241
+		// 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").
242
+		Find(&schedules).Error
243
+	return schedules, err
244
+}
245
+
246
+func GetPrinitWeekTotal(orgid int64, startime int64, endtime int64) (print []*PrintCount, err error) {
247
+
248
+	db := XTReadDB().Table("xt_schedule as x").Where("x.status = 1")
249
+	if orgid > 0 {
250
+		db = db.Where("x.user_org_id = ?", orgid)
251
+	}
252
+	if startime > 0 {
253
+		db = db.Where("x.schedule_date >=?", startime)
254
+	}
255
+	if endtime > 0 {
256
+		db = db.Where("x.schedule_date <=?", endtime)
257
+	}
258
+	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
259
+	return print, err
260
+}
261
+
262
+func GetBloodPrintWeekTotal(orgid int64, startime int64, endtime int64) (print []*PrintCount, err error) {
263
+
264
+	db := XTReadDB().Table("xt_schedule as x").Where("x.status = 1")
265
+	if orgid > 0 {
266
+		db = db.Where("x.user_org_id = ?", orgid)
267
+	}
268
+	if startime > 0 {
269
+		db = db.Where("x.schedule_date >=?", startime)
270
+	}
271
+	if endtime > 0 {
272
+		db = db.Where("x.schedule_date <=?", endtime)
273
+	}
274
+	db = db.Where("x.mode_id = 2")
275
+	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
276
+	return print, err
277
+}
278
+
279
+func GetPerfusionWeekTotal(orgid int64, startime int64, endtime int64) (print []*PrintCount, err error) {
280
+
281
+	db := XTReadDB().Table("xt_schedule as x").Where("x.status = 1")
282
+	if orgid > 0 {
283
+		db = db.Where("x.user_org_id = ?", orgid)
284
+	}
285
+	if startime > 0 {
286
+		db = db.Where("x.schedule_date >=?", startime)
287
+	}
288
+	if endtime > 0 {
289
+		db = db.Where("x.schedule_date <=?", endtime)
290
+	}
291
+	db = db.Where("x.mode_id = 3")
292
+	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
293
+	return print, err
294
+}
295
+
296
+// func ExchangeScheduleTimeWithWeekSchedules(orgID int64, nextWeekSchs []*models.Schedule, nextTwoWeekSchs []*models.Schedule) error {
297
+// 	templateMode, getTemplateModeErr := GetOrgPatientScheduleTemplateMode(orgID)
298
+// 	if getTemplateModeErr != nil {
299
+// 		return getTemplateModeErr
300
+// 	}
301
+// 	if templateMode == nil {
302
+// 		return errors.New("模板模式不存在")
303
+// 	}
304
+
305
+// 	tx := writeDb.Begin()
306
+
307
+// 	updateTime := time.Now().Unix()
308
+
309
+// 	for _, sch := range nextWeekSchs {
310
+// 		sch.PatientInfectiousDiseases = nil
311
+
312
+// 		date := time.Unix(sch.ScheduleDate, 0)
313
+// 		sch.ScheduleDate = date.AddDate(0, 0, 7).Unix()
314
+// 		sch.UpdatedTime = updateTime
315
+
316
+// 		updateSchErr := tx.Save(sch).Error
317
+// 		if updateSchErr != nil {
318
+// 			tx.Rollback()
319
+// 			return updateSchErr
320
+// 		}
321
+// 	}
322
+
323
+// 	for _, sch := range nextTwoWeekSchs {
324
+// 		sch.PatientInfectiousDiseases = nil
325
+
326
+// 		date := time.Unix(sch.ScheduleDate, 0)
327
+// 		sch.ScheduleDate = date.AddDate(0, 0, -7).Unix()
328
+// 		sch.UpdatedTime = updateTime
329
+
330
+// 		updateSchErr := tx.Save(sch).Error
331
+// 		if updateSchErr != nil {
332
+// 			tx.Rollback()
333
+// 			return updateSchErr
334
+// 		}
335
+// 	}
336
+
337
+// 	templateMode.ModifyTime = updateTime
338
+// 	templateMode.ExecuteTimes += 1
339
+// 	updateModeErr := tx.Save(templateMode).Error
340
+// 	if updateModeErr != nil {
341
+// 		tx.Rollback()
342
+// 		return updateModeErr
343
+// 	}
344
+
345
+// 	tx.Commit()
346
+// 	return nil
347
+// }
348
+
349
+func GetSchedualPatientsByKeywordsAndWeek(keywords string, org_id int64, start_time int64, end_time int64) (schedule []*models.Schedule, err error) {
350
+	likeKey := "%" + keywords + "%"
351
+	err = readDb.
352
+		Table("xt_schedule as s").
353
+		Preload("PatientInfectiousDiseases", "status = 1 ").
354
+		Preload("DeviceZone", "status = 1 ").
355
+		Preload("DeviceNumber", "status = 1 ").
356
+		Preload("TreatmentMode", "status = 1 ").
357
+		Joins("JOIN xt_patients as p ON p.id = s.patient_id AND (p.name LIKE ? OR p.dialysis_no LIKE ?)", likeKey, likeKey).
358
+		Where("s.user_org_id=? and s.schedule_date >= ? and s.schedule_date <= ? and s.status=1", org_id, start_time, end_time).
359
+		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").
360
+		Order("schedule_date asc").
361
+		Find(&schedule).Error
362
+	return
363
+
364
+}
365
+
366
+func GetSchedualPatientsByKeywords(keywords string, org_id int64) (schedule []*models.Schedule, err error) {
367
+	likeKey := "%" + keywords + "%"
368
+
369
+	err = readDb.
370
+		Table("xt_schedule as s").
371
+		Preload("PatientInfectiousDiseases", "status = 1 ").
372
+		Preload("DeviceZone", "status = 1 ").
373
+		Preload("DeviceNumber", "status = 1 ").
374
+		Preload("TreatmentMode", "status = 1 ").
375
+		Joins("JOIN xt_patients as p ON p.id = s.patient_id AND (p.name LIKE ? OR p.dialysis_no LIKE ?)", likeKey, likeKey).
376
+		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).
377
+		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").
378
+		Order("schedule_date asc").
379
+		Find(&schedule).Error
380
+	return
381
+
382
+}
383
+
384
+func GetWeekDayScheduleTwo(orgID int64, scheduleDate int64, scheduleDates *time.Time, weektime int64) (schedules []*models.WeekSchedule, err error) {
385
+
386
+	db := readDb.Table("xt_schedule as s ").Where("s.status =1")
387
+	if orgID > 0 {
388
+		db = db.Where("s.user_org_id = ?", orgID)
389
+	}
390
+	if scheduleDate > 0 {
391
+		db = db.Where("s.schedule_date = ?", scheduleDate)
392
+
393
+	}
394
+	if weektime > 0 {
395
+		db = db.Where("s.schedule_type = ?", weektime)
396
+	}
397
+	err = db.
398
+		Preload("DeviceZone", "status = 1 ").
399
+		Preload("DeviceNumber", "status = 1 ").
400
+		Preload("DialysisPrescription", func(db *gorm.DB) *gorm.DB {
401
+			return db.Where("status = 1").Order("id asc")
402
+		}).
403
+		Joins("JOIN xt_patients as p ON p.id = s.patient_id").
404
+		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").
405
+		Order("s.partition_id asc").
406
+		Find(&schedules).Error
407
+
408
+	for _, item := range schedules {
409
+		_, config := FindDoctorAdviceRecordByOrgId(item.UserOrgId)
410
+		if config.IsOpenRemind > 0 {
411
+			//开启推送提醒逻辑    提交长期处方的时候,弹起长期医嘱推送
412
+			var advice_three []*models.DoctorAdvice
413
+			advices, _ := GetLastLongAdviceByGroupNoOther(item.UserOrgId, item.PatientId)
414
+			advices_two, _ := GetLastLongAdviceByGroupNoThreeOther(item.UserOrgId, item.PatientId)
415
+			for _, advice := range advices {
416
+				advice.IsCheck = 1
417
+				if advice.FrequencyType == 3 {
418
+					week := int(scheduleDates.Weekday())
419
+
420
+					switch week {
421
+					case 1:
422
+						if strings.Index(advice.WeekDay, "周一") > -1 {
423
+							advice_three = append(advice_three, advice)
424
+						}
425
+						break
426
+					case 2:
427
+						if strings.Index(advice.WeekDay, "周二") > -1 {
428
+							advice_three = append(advice_three, advice)
429
+						}
430
+						break
431
+					case 3:
432
+						if strings.Index(advice.WeekDay, "周三") > -1 {
433
+							advice_three = append(advice_three, advice)
434
+						}
435
+						break
436
+					case 4:
437
+						if strings.Index(advice.WeekDay, "周四") > -1 {
438
+							advice_three = append(advice_three, advice)
439
+						}
440
+						break
441
+					case 5:
442
+						if strings.Index(advice.WeekDay, "周五") > -1 {
443
+							advice_three = append(advice_three, advice)
444
+						}
445
+						break
446
+					case 6:
447
+						if strings.Index(advice.WeekDay, "周六") > -1 {
448
+							advice_three = append(advice_three, advice)
449
+						}
450
+						break
451
+					case 0:
452
+						if strings.Index(advice.WeekDay, "周日") > -1 {
453
+							advice_three = append(advice_three, advice)
454
+						}
455
+						break
456
+					}
457
+				} else if advice.FrequencyType == 1 {
458
+					advice_three = append(advice_three, advice)
459
+				}
460
+			}
461
+
462
+			for _, advice := range advices_two {
463
+				now := scheduleDates.Unix()
464
+				dayStr := strconv.FormatInt(advice.DayCount, 10)
465
+				dayStr2 := "-" + dayStr
466
+				count, _ := strconv.ParseInt(dayStr2, 10, 64)
467
+				oldTime := scheduleDates.AddDate(0, 0, int(count)).Unix()
468
+				advices, _ := FindAllDoctorAdviceByTimeOther(now, oldTime, item.PatientId, item.UserOrgId, advice.TemplateId)
469
+				if len(advices) == 0 {
470
+					advice_three = append(advice_three, advice)
471
+				}
472
+			}
473
+
474
+			item.DoctorAdvice = append(item.DoctorAdvice, advice_three...)
475
+		}
476
+	}
477
+	return
478
+}
479
+
480
+func GetWeekDaySchedule(orgID int64, scheduleDate int64, scheduleDates *time.Time) (schedules []*models.WeekSchedule, err error) {
481
+
482
+	err = readDb.
483
+		Table("xt_schedule as s").
484
+		Preload("DeviceZone", "status = 1 ").
485
+		Preload("DeviceNumber", "status = 1 ").
486
+		Preload("DialysisPrescription", func(db *gorm.DB) *gorm.DB {
487
+			return db.Where("status = 1").Order("id asc")
488
+		}).
489
+		Joins("JOIN xt_patients as p ON p.id = s.patient_id").
490
+		Where("s.user_org_id=? and s.schedule_date = ? and s.status=1", orgID, scheduleDate).
491
+		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").
492
+		Order("schedule_type").
493
+		Find(&schedules).Error
494
+
495
+	for _, item := range schedules {
496
+		_, config := FindDoctorAdviceRecordByOrgId(item.UserOrgId)
497
+		if config.IsOpenRemind > 0 {
498
+			//开启推送提醒逻辑    提交长期处方的时候,弹起长期医嘱推送
499
+			var advice_three []*models.DoctorAdvice
500
+			advices, _ := GetLastLongAdviceByGroupNoOther(item.UserOrgId, item.PatientId)
501
+			advices_two, _ := GetLastLongAdviceByGroupNoThreeOther(item.UserOrgId, item.PatientId)
502
+			for _, advice := range advices {
503
+				advice.IsCheck = 1
504
+				if advice.FrequencyType == 3 {
505
+					week := int(scheduleDates.Weekday())
506
+					fmt.Println(advice.WeekDay)
507
+					switch week {
508
+					case 1:
509
+						if strings.Index(advice.WeekDay, "周一") > -1 {
510
+							advice_three = append(advice_three, advice)
511
+						}
512
+						break
513
+					case 2:
514
+						if strings.Index(advice.WeekDay, "周二") > -1 {
515
+							advice_three = append(advice_three, advice)
516
+						}
517
+						break
518
+					case 3:
519
+						if strings.Index(advice.WeekDay, "周三") > -1 {
520
+							advice_three = append(advice_three, advice)
521
+						}
522
+						break
523
+					case 4:
524
+						if strings.Index(advice.WeekDay, "周四") > -1 {
525
+							advice_three = append(advice_three, advice)
526
+						}
527
+						break
528
+					case 5:
529
+						if strings.Index(advice.WeekDay, "周五") > -1 {
530
+							advice_three = append(advice_three, advice)
531
+						}
532
+						break
533
+					case 6:
534
+						if strings.Index(advice.WeekDay, "周六") > -1 {
535
+							advice_three = append(advice_three, advice)
536
+						}
537
+						break
538
+					case 0:
539
+						if strings.Index(advice.WeekDay, "周日") > -1 {
540
+							advice_three = append(advice_three, advice)
541
+						}
542
+						break
543
+					}
544
+				} else if advice.FrequencyType == 1 {
545
+					advice_three = append(advice_three, advice)
546
+				}
547
+			}
548
+
549
+			for _, advice := range advices_two {
550
+				now := scheduleDates.Unix()
551
+				dayStr := strconv.FormatInt(advice.DayCount, 10)
552
+				dayStr2 := "-" + dayStr
553
+				count, _ := strconv.ParseInt(dayStr2, 10, 64)
554
+				oldTime := scheduleDates.AddDate(0, 0, int(count)).Unix()
555
+				advices, _ := FindAllDoctorAdviceByTimeOther(now, oldTime, item.PatientId, item.UserOrgId, advice.TemplateId)
556
+				if len(advices) == 0 {
557
+					advice_three = append(advice_three, advice)
558
+				}
559
+			}
560
+
561
+			item.DoctorAdvice = append(item.DoctorAdvice, advice_three...)
562
+		}
563
+	}
564
+	return
565
+}
566
+
567
+func GetWeekDayScheduleById(orgid int64, scheduleDate int64, scheduleType int64, zone int64) (list []*models.VmSchedulesRemind, err error) {
568
+
569
+	db := XTReadDB().Table("xt_schedule as x").Where("x.status = 1")
570
+	if orgid > 0 {
571
+		db = db.Where("x.user_org_id = ?", orgid)
572
+	}
573
+	if scheduleDate > 0 {
574
+		db = db.Where("x.schedule_date = ?", scheduleDate)
575
+	}
576
+	if scheduleType > 0 {
577
+		db = db.Where("x.schedule_type = ?", scheduleType)
578
+	}
579
+	if zone > 0 {
580
+		db = db.Where("x.partition_id = ?", zone)
581
+	}
582
+
583
+	err = db.Select("x.id,x.user_org_id,x.partition_id,x.bed_id,x.patient_id,x.schedule_date,x.schedule_type,x.schedule_week,x.mode_id,x.is_export").Preload("XtPatients", "status = 1").Preload("DeviceZone", "status = 1").Preload("DeviceNumber", "status = 1").Preload("DialysisOrder", "status = 1").Preload("DoctorAdvice", func(db *gorm.DB) *gorm.DB {
584
+		return db.Where("status =1 and parent_id = 0").Preload("ChildDoctorAdvice", "status = 1")
585
+	}).Preload("HisDoctorAdviceInfo", "status = 1").Preload("DialysisPrescription", "status = 1").Preload("DialysisSolution", func(db *gorm.DB) *gorm.DB {
586
+		return db.Where("status =1").Order("id asc")
587
+	}).Find(&list).Error
588
+
589
+	return list, err
590
+}
591
+
592
+func GetWeekDayScheduleByIdThee(orgid int64, scheduleDate int64, scheduleType int64, zone []string) (list []*models.VmSchedulesRemind, err error) {
593
+
594
+	db := XTReadDB().Table("xt_schedule as x").Where("x.status = 1")
595
+	if orgid > 0 {
596
+		db = db.Where("x.user_org_id = ?", orgid)
597
+	}
598
+	if scheduleDate > 0 {
599
+		db = db.Where("x.schedule_date = ?", scheduleDate)
600
+	}
601
+	if scheduleType > 0 {
602
+		db = db.Where("x.schedule_type = ?", scheduleType)
603
+	}
604
+	if len(zone) > 0 {
605
+		db = db.Where("x.partition_id in (?)", zone)
606
+	}
607
+
608
+	err = db.Select("x.id,x.user_org_id,x.partition_id,x.bed_id,x.patient_id,x.schedule_date,x.schedule_type,x.schedule_week,x.mode_id,x.is_export").Preload("XtPatients", "status = 1").Preload("DeviceZone", "status = 1").Preload("DeviceNumber", "status = 1").Preload("DialysisOrder", "status = 1").Preload("DoctorAdvice", func(db *gorm.DB) *gorm.DB {
609
+		return db.Where("status =1 and parent_id = 0").Preload("ChildDoctorAdvice", "status = 1")
610
+	}).Preload("HisDoctorAdviceInfo", "status = 1").Preload("DialysisPrescription", "status = 1").Preload("DialysisSolution", func(db *gorm.DB) *gorm.DB {
611
+		return db.Where("status =1").Order("id asc")
612
+	}).Find(&list).Error
613
+
614
+	return list, err
615
+}
616
+
617
+func GetWeekDayScheduleByIdTwo(orgid int64, scheduleDate int64, scheduleType int64, startDate int64, zone []string) (list []*models.VmSchedulesRemind, err error) {
618
+
619
+	db := XTReadDB().Table("xt_schedule as x").Where("x.status = 1")
620
+	if orgid > 0 {
621
+		db = db.Where("x.user_org_id = ?", orgid)
622
+	}
623
+	if scheduleDate > 0 {
624
+		db = db.Where("x.schedule_date >=? and x.schedule_date<=?", startDate, scheduleDate)
625
+	}
626
+	if scheduleType > 0 {
627
+		db = db.Where("x.schedule_type = ?", scheduleType)
628
+	}
629
+	if len(zone) > 0 {
630
+		db = db.Where("x.partition_id in (?)", zone)
631
+	}
632
+
633
+	err = db.Select("x.id,x.user_org_id,x.partition_id,x.bed_id,x.patient_id,x.schedule_date,x.schedule_type,x.schedule_week,x.mode_id,x.is_export").Preload("XtPatients", "status = 1").Preload("DeviceZone", "status = 1").Preload("DeviceNumber", "status = 1").Preload("DialysisOrder", "status = 1").Preload("DoctorAdvice", func(db *gorm.DB) *gorm.DB {
634
+		return db.Where("status =1 and parent_id = 0").Preload("ChildDoctorAdvice", "status = 1")
635
+	}).Preload("HisDoctorAdviceInfo", "status = 1").Preload("DialysisPrescription", "status = 1").Preload("DialysisSolution", func(db *gorm.DB) *gorm.DB {
636
+		return db.Where("status =1").Order("id asc")
637
+	}).Find(&list).Error
638
+
639
+	return list, err
640
+}
641
+
642
+func RemoveRepeatedElement(arr []*models.DoctorAdvice) (newArr []*models.DoctorAdvice) {
643
+	newArr = make([]*models.DoctorAdvice, 0)
644
+	for i := 0; i < len(arr); i++ {
645
+		repeat := false
646
+		for j := i + 1; j < len(arr); j++ {
647
+			if arr[i].ID == arr[j].ID {
648
+				repeat = true
649
+				break
650
+			}
651
+		}
652
+		if !repeat {
653
+			newArr = append(newArr, arr[i])
654
+		}
655
+	}
656
+	return
657
+}
658
+
659
+func GetLastLongAdviceByGroupNoOther(orgId int64, patient_id int64) (advice []*models.DoctorAdvice, err error) {
660
+	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
661
+	return
662
+}
663
+
664
+func GetLastLongAdviceByGroupNoThreeOther(orgId int64, patient_id int64) (advice []*models.DoctorAdvice, err error) {
665
+	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
666
+	return
667
+}
668
+
669
+func FindAllDoctorAdviceByTimeOther(now int64, end int64, patient_id int64, orgId int64, temp_id string) (advice []*models.DoctorAdvice, err error) {
670
+	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
671
+	return
672
+}
673
+
674
+func FindSchPatientNameByName(name string, user_org_id int64) (patient []*models.Patients, err error) {
675
+	err = readDb.Model(&models.Patients{}).Where("user_org_id = ? AND name = ? AND status = 1", user_org_id, name).Find(&patient).Error
676
+	return
677
+}
678
+
679
+func UpdateScheduleStatus(date int64, org_id int64) (err error) {
680
+	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
681
+	return
682
+}
683
+
684
+func FindDeviceZoneByName(name string, org_id int64) (zone models.DeviceZone, err error) {
685
+	err = readDb.Model(&models.DeviceZone{}).Where("org_id = ? AND name = ? AND status = 1", org_id, name).First(&zone).Error
686
+	return
687
+}
688
+
689
+func FindDeviceByName(device_name string, org_id int64, zone_id int64) (devices []*models.DeviceNumber, err error) {
690
+	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
691
+	return
692
+}
693
+
694
+func FindSchedualExportLog(org_id int64, export_time int64) (errLogs []*models.ExportErrLog, err error) {
695
+	err = readDb.Model(&models.ExportErrLog{}).Where("user_org_id = ? AND export_time = ? AND log_type = 2", org_id, export_time).Find(&errLogs).Error
696
+	return
697
+}
698
+
699
+func FindDeviceByNameTwo(device_name string, org_id int64, zone_id int64) (devices []*models.DeviceNumber, err error) {
700
+	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
701
+	return
702
+}
703
+
704
+func UpdateScheduleTemplateStatus(org_id int64) (err error) {
705
+	err = readDb.Model(&models.PatientScheduleTemplateItem{}).Where("org_id = ? AND status = 1", org_id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
706
+	return
707
+}
708
+
709
+func CreateScheduleTemplate(m *models.PatientScheduleTemplateItem) error {
710
+	return writeDb.Model(&models.PatientScheduleTemplateItem{}).Create(&m).Error
711
+}
712
+
713
+func FindSchedualTemplateExportLog(org_id int64, export_time int64) (errLogs []*models.ExportErrLog, err error) {
714
+	err = readDb.Model(&models.ExportErrLog{}).Where("user_org_id = ? AND export_time = ? AND log_type = 3", org_id, export_time).Find(&errLogs).Error
715
+	return
716
+}
717
+
718
+func GetDialysisOrderByBedId(orgID, start, bed_id int64, schedule_type int64) (schedule models.DialysisOrder, err error) {
719
+	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
720
+	return
721
+}
722
+
723
+type VMDeviceNumber struct {
724
+	ID         int64             `gorm:"column:id" json:"id"`
725
+	OrgID      int64             `gorm:"column:org_id" json:"-"`
726
+	Number     string            `gorm:"column:number" json:"number"`
727
+	GroupID    int64             `gorm:"column:group_id" json:"group_id"`
728
+	ZoneID     int64             `gorm:"column:zone_id" json:"zone_id"`
729
+	Status     int8              `json:"-"`
730
+	CreateTime int64             `gorm:"column:ctime" json:"-"`
731
+	ModifyTime int64             `gorm:"column:mtime" json:"-"`
732
+	DeviceZone models.DeviceZone `json:"zone" gorm:"foreignkey:ID;AssociationForeignKey:ZoneID;"`
733
+}
734
+
735
+func (VMDeviceNumber) TableName() string {
736
+	return "xt_device_number"
737
+}
738
+
739
+type VMPatientScheduleTemplateItem struct {
740
+	ID             int64 `gorm:"column:id" json:"id" form:"id"`
741
+	OrgID          int64 `gorm:"column:org_id" json:"-" form:"org_id"`
742
+	TemplateID     int64 `gorm:"column:template_id" json:"template_id" form:"template_id"`
743
+	DeviceNumberID int64 `gorm:"column:device_number_id" json:"device_number_id" form:"device_number_id"`
744
+	PatientID      int64 `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
745
+	TreatMode      int64 `gorm:"column:treat_mode" json:"treat_mode" form:"treat_mode"` // 治疗模式
746
+	Weekday        int8  `gorm:"column  :weekday" json:"weekday" form:"weekday"`        // 周一-周日 1-7
747
+	TimeType       int8  `gorm:"column:time_type" json:"time_type" form:"time_type"`    // 上下晚 123
748
+	Status         int8  `gorm:"column:status" json:"status" form:"status"`
749
+	CreateTime     int64 `gorm:"column:ctime" json:"-" form:"ctime"`
750
+	ModifyTime     int64 `gorm:"column:mtime" json:"-" form:"mtime"`
751
+	IsExport       int64 `gorm:"column:is_export" json:"is_export" form:"is_export"`
752
+
753
+	Patient      string         `gorm:"-" json:"patient" form:"patient"`
754
+	DeviceNumber VMDeviceNumber `json:"number" gorm:"foreignkey:ID;AssociationForeignKey:DeviceNumberID;"`
755
+
756
+	PatientInfectiousDiseases []*models.InfectiousDiseases `json:"patient_contagions" gorm:"foreignkey:PatientId;AssociationForeignKey:PatientId;"`
757
+}
758
+
759
+func (VMPatientScheduleTemplateItem) TableName() string {
760
+	return "xt_patient_schedule_template_item"
761
+}
762
+
763
+func GetTemplateSchedualPatientsByKeywords(keywords string, org_id int64, template_id int64) (schedule []*VMPatientScheduleTemplateItem, err error) {
764
+	likeKey := "%" + keywords + "%"
765
+
766
+	err = readDb.
767
+		Table("xt_patient_schedule_template_item as s").
768
+		Preload("PatientInfectiousDiseases", "status = 1 ").
769
+		Preload("DeviceNumber", func(db *gorm.DB) *gorm.DB {
770
+			return db.Where("org_id = ? AND status = 1", org_id).Preload("DeviceZone", "org_id = ? AND status = 1", org_id)
771
+		}).
772
+		Joins("JOIN xt_patients as p ON p.id = s.patient_id AND (p.name LIKE ? OR p.dialysis_no LIKE ?)", likeKey, likeKey).
773
+		Where("s.template_id = ? AND s.org_id=?  and s.status=1", template_id, org_id).
774
+		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").
775
+		Order("weekday asc").
776
+		Find(&schedule).Error
777
+	return
778
+
779
+}
780
+
781
+func UpdateNewScheduleTemplateStatus(id int64, org_id int64) (err error) {
782
+	err = readDb.Model(&models.PatientScheduleTemplateItem{}).Where("org_id = ? AND id = ?", org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
783
+	return
784
+}
785
+
786
+func GetNextWeekDaySchedule(weektype int64, weektime int64, startime int64, endtime int64, orgID int64, zone []string) (schedules []*models.WeekSchedule, err error) {
787
+
788
+	db := readDb.Table("xt_schedule as s ").Where("s.status =1")
789
+	if orgID > 0 {
790
+		db = db.Where("s.user_org_id = ?", orgID)
791
+	}
792
+	if startime > 0 {
793
+		db = db.Where("s.schedule_date >= ?", startime)
794
+	}
795
+	if endtime > 0 {
796
+		db = db.Where("s.schedule_date <= ?", endtime)
797
+	}
798
+	if weektime > 0 {
799
+		db = db.Where("s.schedule_type = ?", weektime)
800
+	}
801
+	if weektype > 0 {
802
+		db = db.Where("s.schedule_week = ?", weektype)
803
+	}
804
+	if len(zone) > 0 {
805
+		db = db.Where("s.partition_id in (?)", zone)
806
+	}
807
+	err = db.
808
+		Preload("DeviceZone", "status = 1 ").
809
+		Preload("DeviceNumber", "status = 1 ").
810
+		Preload("DialysisPrescription", func(db *gorm.DB) *gorm.DB {
811
+			return db.Where("status = 1").Order("id asc")
812
+		}).Preload("DialysisSolution", func(db *gorm.DB) *gorm.DB {
813
+		return db.Where("status = 1").Order("id asc")
814
+	}).Preload("DoctorAdvice", func(db *gorm.DB) *gorm.DB {
815
+		return db.Where("status =1 and parent_id = 0").Preload("ChildDoctorAdvice", "status = 1")
816
+	}).Preload("HisDoctorAdviceInfo", "status = 1").Joins("JOIN xt_patients as p ON p.id = s.patient_id").
817
+		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").
818
+		Order("s.partition_id asc").
819
+		Find(&schedules).Error
820
+	return schedules, err
821
+}
822
+
823
+func GetThreeWeekList(startime int64, endtime int64, orgid int64, scheduletype int64, partionid int64) (schedule []*models.VmSchedule, err error) {
824
+
825
+	db := XTReadDB().Table("xt_schedule as x").Where("x.status =1")
826
+	if startime > 0 {
827
+		db = db.Where("x.schedule_date >=?", startime)
828
+	}
829
+	if endtime > 0 {
830
+		db = db.Where("x.schedule_date <=?", endtime)
831
+	}
832
+	if orgid > 0 {
833
+		db = db.Where("x.user_org_id = ?", orgid)
834
+	}
835
+	if scheduletype > 0 {
836
+		db = db.Where("x.schedule_type = ?", scheduletype)
837
+	}
838
+	if partionid > 0 {
839
+		db = db.Where("x.partition_id = ?", partionid)
840
+	}
841
+	err = db.Select("x.schedule_date,x.schedule_type,x.schedule_week,x.bed_id,x.partition_id,t.name,n.number,z.name").Joins("left join xt_patients as t on t.id = x.patient_id and t.user_org_id = ? and t.status = 1", orgid).Joins("left join xt_device_zone as z on z.id = x.partition_id and z.org_id = ? and z.status =1", orgid).Joins("left join xt_device_number as n on n.id = x.bed_id and n.org_id = ? and n.status =1", orgid).Scan(&schedule).Error
842
+
843
+	return schedule, err
844
+}
845
+
846
+func UpdatedDialysisPrescription(prescription *models.DialysisPrescription, recordDate int64, patientid int64, orgid int64) error {
847
+
848
+	err := XTWriteDB().Model(&prescription).Where("record_date = ? and patient_id = ? and user_org_id = ?", recordDate, patientid, orgid).Update(map[string]interface{}{"mode_id": prescription.ModeId, "updated_time": time.Now().Unix()}).Error
849
+	return err
850
+}
851
+
852
+func GetWeekSchedules(orgid int64, startime int64, endtime int64) (scheudle []*models.XtSchedule, err error) {
853
+
854
+	err = XTReadDB().Model(&scheudle).Where("user_org_id = ? and status = 1 and schedule_date>=? and schedule_date<=?", orgid, startime, endtime).Find(&scheudle).Error
855
+	return scheudle, err
856
+}
857
+
858
+func GetLastWeekSchedule(orgid int64, startime int64, endtime int64) (*models.XtSchedule, error) {
859
+	schedule := models.XtSchedule{}
860
+	err := XTReadDB().Where("user_org_id = ? and status =1 and schedule_date>=? and schedule_date<=?", orgid, startime, endtime).Find(&schedule).Error
861
+	if err == gorm.ErrRecordNotFound {
862
+		return nil, err
863
+	}
864
+	if err != nil {
865
+		return nil, err
866
+	}
867
+	return &schedule, nil
868
+}
869
+func AddPatientSchedule(schedule *models.XtSchedule) error {
870
+	utx := XTWriteDB().Begin()
871
+	err := utx.Create(&schedule).Error
872
+	utx.Commit()
873
+	return err
874
+}
875
+
876
+func UpdatePatientSchedule(orgid int64, startime int64, endtime int64) error {
877
+
878
+	schedule := models.XtSchedule{}
879
+	err := XTWriteDB().Model(&schedule).Where("user_org_id = ? and schedule_date>=? and schedule_date<=? and status =1", orgid, startime, endtime).Updates(map[string]interface{}{"status": 0}).Error
880
+	return err
881
+}
882
+
883
+func GetSettingById(id int64) (*models.XtRemindPrintSetting, error) {
884
+	setting := models.XtRemindPrintSetting{}
885
+	err := XTReadDB().Model(&setting).Where("id = ? and status = 1", id).Find(&setting).Error
886
+	if err == gorm.ErrRecordNotFound {
887
+		return nil, err
888
+	}
889
+	if err != nil {
890
+		return nil, err
891
+	}
892
+	return &setting, nil
893
+}
894
+
895
+func CreateSetting(setting *models.XtRemindPrintSetting) error {
896
+
897
+	err := XTReadDB().Create(&setting).Error
898
+	return err
899
+}
900
+
901
+func UpdatedRemindPrint(set *models.XtRemindPrintSetting, id int64) error {
902
+
903
+	err := XTWriteDB().Model(&set).Where("id = ? and status = 1", id).Updates(map[string]interface{}{"prescription_status": set.PrescriptionStatus, "week": set.Week, "name": set.Name, "zone": set.Zone, "classes": set.Classes, "number": set.Number, "mode": set.Mode, "dialyzers": set.Dialyzers, "perfusion_apparatus": set.PerfusionApparatus, "anticoagulant": set.Anticoagulant, "doctor_advice": set.DoctorAdvice, "anticoagulant_zongliang": set.AnticoagulantZongliang}).Error
904
+	return err
905
+}
906
+
907
+func GetRemindPrintList(id int64) (models.XtRemindPrintSetting, error) {
908
+
909
+	setting := models.XtRemindPrintSetting{}
910
+	err := XTReadDB().Model(&setting).Where("user_org_id = ? and status =1", id).Find(&setting).Error
911
+	return setting, err
912
+}
913
+
914
+func GetScheudleTemplateById(orgid int64) (*models.ScheduleTemplate, error) {
915
+
916
+	schedule := models.ScheduleTemplate{}
917
+	err := XTReadDB().Model(&schedule).Where("user_org_id = ? and status = 1", orgid).Find(&schedule).Error
918
+	if err == gorm.ErrRecordNotFound {
919
+		return nil, err
920
+	}
921
+	if err != nil {
922
+		return nil, err
923
+	}
924
+	return &schedule, nil
925
+}
926
+
927
+func CreateXtscheduleTemplate(template *models.ScheduleTemplate) error {
928
+
929
+	err := XTWriteDB().Create(&template).Error
930
+	return err
931
+}
932
+
933
+func UpdateXtScheduleTemplate(template *models.ScheduleTemplate, orgid int64) error {
934
+
935
+	err := XTWriteDB().Model(&template).Where("user_org_id = ? and status = 1", orgid).Updates(map[string]interface{}{"template_id": template.TemplateId}).Error
936
+	return err
937
+}
938
+
939
+func GetScheduleTemplate(orgid int64) (models.ScheduleTemplate, error) {
940
+
941
+	template := models.ScheduleTemplate{}
942
+	err := XTReadDB().Where("user_org_id = ? and status = 1", orgid).Find(&template).Error
943
+	return template, err
944
+}
945
+
946
+func GetDataPrintByOrgId(orgid int64) (*models.XtDataPrint, error) {
947
+
948
+	dataPrint := models.XtDataPrint{}
949
+
950
+	err := XTReadDB().Model(&dataPrint).Where("user_org_id = ? and status = 1", orgid).Find(&dataPrint).Error
951
+
952
+	if err == gorm.ErrRecordNotFound {
953
+		return nil, err
954
+	}
955
+	if err != nil {
956
+		return nil, err
957
+	}
958
+	return &dataPrint, nil
959
+}
960
+
961
+func CreateDataPrint(dataPrint *models.XtDataPrint) error {
962
+
963
+	err := XTWriteDB().Create(&dataPrint).Error
964
+	return err
965
+}
966
+
967
+func UpdteDataPrint(orgid int64, dataPrint *models.XtDataPrint) error {
968
+
969
+	err := XTWriteDB().Model(&dataPrint).Where("user_org_id = ? and status = 1", orgid).Updates(map[string]interface{}{"is_open": dataPrint.IsOpen}).Error
970
+	return err
971
+}
972
+
973
+func GetDataPrint(orgid int64) (models.XtDataPrint, error) {
974
+	dataPrint := models.XtDataPrint{}
975
+	err := XTReadDB().Model(&dataPrint).Where("user_org_id = ? and status = 1", orgid).Find(&dataPrint).Error
976
+	return dataPrint, err
977
+}

Diff onderdrukt omdat het te groot bestand
+ 1063 - 0
service/self_drug_service.go


+ 270 - 0
service/sign_weigh_service.go Bestand weergeven

@@ -0,0 +1,270 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_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
+}

+ 185 - 0
service/sms_service.go Bestand weergeven

@@ -0,0 +1,185 @@
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
+	"Xcx_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
+}

+ 73 - 0
service/statistics_service.go Bestand weergeven

@@ -0,0 +1,73 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_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
+}

Diff onderdrukt omdat het te groot bestand
+ 1882 - 0
service/statistics_service/index_evaluation_service.go


+ 195 - 0
service/statistics_service/index_models.go Bestand weergeven

@@ -0,0 +1,195 @@
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
+	ChangeNuserCount           int64 `gorm:"-" json:"change_nuser_count" `
142
+	DiffiCultPuntureNuserCount int64 `gorm:"-" json:"difficult_nuser_count" `
143
+	NewNuserCount              int64 `gorm:"-" json:"new_nuser_count" `
144
+	StartNuserCount            int64 `gorm:"-" json:"start_nuser_count" `
145
+
146
+	PRatio      string `gorm:"-" json:"p_ratio"`
147
+	CourseRatio string `gorm:"-" json:"course_ratio" `
148
+	RescueRatio string `gorm:"-" json:"rescue_ratio" `
149
+
150
+	PunctureRatio       string `gorm:"-" json:"puncture_ratio" `
151
+	ChangemedicineRatio string `gorm:"-" json:"change_medicine_ratio" `
152
+	CureRatio           string `gorm:"-" json:"cure_ratio" `
153
+	MissionRatio        string `gorm:"-" json:"mission_ratio" `
154
+
155
+	ChangeRatio         string `gorm:"-" json:"change_nurse_ratio" `
156
+	DiffiCultNuserRatio string `gorm:"-" json:"difficult_nurse_ratio" `
157
+	NewNuserRatio       string `gorm:"-" json:"new_nurse_ratio" `
158
+	StartNuserRatio     string `gorm:"-" json:"start_nurse_ratio" `
159
+}
160
+
161
+func (VMUserAdminRole) TableName() string {
162
+	return "sgj_user_admin_role"
163
+}
164
+
165
+type VMDeviceNumber struct {
166
+	ID      int64  `gorm:"column:id" json:"id" form:"id"`
167
+	OrgId   int64  `gorm:"column:org_id" json:"org_id" form:"org_id"`
168
+	Number  string `gorm:"column:number" json:"number" form:"number"`
169
+	GroupId int64  `gorm:"column:group_id" json:"group_id" form:"group_id"`
170
+	ZoneId  int64  `gorm:"column:zone_id" json:"zone_id" form:"zone_id"`
171
+	Status  int64  `gorm:"column:status" json:"status" form:"status"`
172
+	Ctime   int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
173
+	Mtime   int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
174
+}
175
+
176
+func (VMDeviceNumber) TableName() string {
177
+	return "xt_device_number"
178
+}
179
+
180
+type QualityControlStandard struct {
181
+	ID              int64  `gorm:"column:id" json:"id" form:"id"`
182
+	InspectionMajor int64  `gorm:"column:inspection_major" json:"inspection_major" form:"inspection_major"`
183
+	InspectionMinor int64  `gorm:"column:inspection_minor" json:"inspection_minor" form:"inspection_minor"`
184
+	MinRange        string `gorm:"column:min_range" json:"min_range" form:"min_range"`
185
+	LargeRange      string `gorm:"column:large_range" json:"large_range" form:"large_range"`
186
+	Sort            int64  `gorm:"column:sort" json:"sort" form:"sort"`
187
+	UserOrgId       int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
188
+	Status          int64  `gorm:"column:status" json:"status" form:"status"`
189
+	CreatedTime     int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
190
+	UpdatedTime     int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
191
+}
192
+
193
+func (QualityControlStandard) TableName() string {
194
+	return "xt_quality_control_standard"
195
+}

Diff onderdrukt omdat het te groot bestand
+ 4642 - 0
service/stock_service.go


+ 34 - 0
service/subscibe_service.go Bestand weergeven

@@ -0,0 +1,34 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_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
+}

+ 179 - 0
service/user_service.go Bestand weergeven

@@ -0,0 +1,179 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_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 GetAllAdminUsersTwo(orgId int64) (list []*AdminUserList, err error) {
59
+	//fmt.Println("orgid", orgId)
60
+	//fmt.Println("appid", appid)
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 ua.status=1", orgId).Select("ua.id, uar.user_name as name, uar.user_type").Scan(&list).Error
62
+	//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
63
+	return
64
+}
65
+
66
+func GetAdminUser(orgId, appid, id int64) (*AdminUserList, error) {
67
+	var err error
68
+	var user AdminUserList
69
+	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
70
+
71
+	if err == gorm.ErrRecordNotFound {
72
+		return nil, nil
73
+	}
74
+
75
+	if err != nil {
76
+		return nil, err
77
+	}
78
+	return &user, nil
79
+}
80
+
81
+func GetSgjUserByMobild(mobile string) (user models.SgjUser, err error) {
82
+	err = readUserDb.Model(&models.SgjUser{}).Where("mobile=?", mobile).First(&user).Error
83
+	return
84
+}
85
+
86
+func GetSgjCoustomerByMobile(orgId int64, mobile string) (*models.SgjCustomer, error) {
87
+	var c models.SgjCustomer
88
+	var err error
89
+	err = readUserDb.Model(&models.SgjCustomer{}).Where("user_org_id=? and mobile=?", orgId, mobile).First(&c).Error
90
+	return &c, err
91
+}
92
+
93
+func GetAllGeneralAdminUsers(orgId, appid int64) (users []AdminUserList, err error) {
94
+	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
95
+	return
96
+}
97
+
98
+func GetDryWeightByPatientId(patientid int64, orgid int64) (pre []*models.SgjPatientDryweight, err error) {
99
+
100
+	err = XTReadDB().Where("patient_id = ? AND user_org_id = ?", patientid, orgid).Last(&pre).Error
101
+	return pre, err
102
+}
103
+
104
+func GetAllDoctor(orgid int64, appid int64) (appRole []*models.App_Role, err error) {
105
+
106
+	err = UserReadDB().Where("org_id = ? AND app_id = ? AND status = ? AND  (user_type = ? OR user_type = ?) ", orgid, appid, 1, 2, 1).Find(&appRole).Error
107
+	return appRole, err
108
+}
109
+
110
+func GetAllDoctorThree(orgid int64) (appRole []*models.App_Role, err error) {
111
+	err = UserReadDB().Where("org_id = ? AND status = ? AND  (user_type = ? OR user_type = ?) ", orgid, 1, 2, 1).Find(&appRole).Error
112
+	return appRole, err
113
+}
114
+
115
+func QueryDryWeight(orgid int64, patientid int64) (*models.SgjPatientDryweight, error) {
116
+	var dryweight models.SgjPatientDryweight
117
+	var err error
118
+	err = XTReadDB().Where("user_org_id = ? AND patient_id = ?", orgid, patientid).Find(&dryweight).Error
119
+	if err == gorm.ErrRecordNotFound {
120
+
121
+		return nil, err
122
+	}
123
+	if err != nil {
124
+		return nil, err
125
+	}
126
+	return &dryweight, nil
127
+}
128
+
129
+func CreatePatientWeight(dryweight *models.SgjPatientDryweight) error {
130
+
131
+	err := XTWriteDB().Create(&dryweight).Error
132
+	return err
133
+}
134
+
135
+func GetLastData(orgid int64) (models.SgjPatientDryweight, error) {
136
+	dryweight := models.SgjPatientDryweight{}
137
+	err := XTReadDB().Where("user_org_id = ? AND status = ?", orgid, 1).Last(&dryweight).Error
138
+	return dryweight, err
139
+
140
+}
141
+
142
+func UpdateDialysisPrescription(patientid int64, orgid int64, dryweight float64, prescription models.PredialysisEvaluation) error {
143
+	fmt.Println("patientid", patientid)
144
+	fmt.Println("orgid", orgid)
145
+	fmt.Println("dryweight", dryweight)
146
+	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
147
+	fmt.Println("错误是设么", err)
148
+	return err
149
+}
150
+
151
+func GetAllData(orgid int64, id int64, page int64, limit int64) (dry []*models.XtPatientDryweight, total int64, err error) {
152
+	offset := (page - 1) * limit
153
+	table := XTReadDB().Table("sgj_users.sgj_user_admin_role AS a")
154
+	fmt.Println("table", table)
155
+	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
156
+	if err != nil {
157
+		return
158
+	}
159
+	return
160
+}
161
+
162
+func GetDryWeightDetailById(id int64) (models.SgjPatientDryweight, error) {
163
+
164
+	dryweight := models.SgjPatientDryweight{}
165
+	err := XTReadDB().Model(&dryweight).Where("id=? and status = 1", id).Find(&dryweight).Error
166
+	return dryweight, err
167
+}
168
+
169
+func ModifyDryWeightData(adjust *models.SgjPatientDryweight, id int64) error {
170
+
171
+	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
172
+	return err
173
+}
174
+
175
+func GetAllHisDoctor(orgid int64) (appRole []*models.App_Role, err error) {
176
+
177
+	err = UserReadDB().Where("org_id = ?  AND status = 1 AND  (user_type = ? OR user_type = ?) ", orgid, 2, 1).Find(&appRole).Error
178
+	return appRole, err
179
+}

+ 449 - 0
service/verify_login_token_service.go Bestand weergeven

@@ -0,0 +1,449 @@
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
+	"Xcx_New/models"
13
+	"Xcx_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
+}

+ 105 - 0
service/vm_service.go Bestand weergeven

@@ -0,0 +1,105 @@
1
+package service
2
+
3
+import (
4
+	"Xcx_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
+}

Diff onderdrukt omdat het te groot bestand
+ 2162 - 0
service/warhouse_service.go