patient_service.go 53KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331
  1. package service
  2. import (
  3. "XT_New/models"
  4. "strconv"
  5. "strings"
  6. "time"
  7. "fmt"
  8. "github.com/jinzhu/gorm"
  9. )
  10. //GetPatientList 返回患者的列表
  11. func GetPatientList(orgID int64, keywords string, page, limit, schedulType, bindingState, lapseto, source, startTime, endTime, contagion, reimbursementWay, isscheduling, isprescription int64, isStartTime, isEndTime bool) (patients []*models.Patients, total int64, err error) {
  12. db := readDb.Table("xt_patients as p").Where("p.status=1")
  13. if orgID > 0 {
  14. db = db.Where("p.user_org_id=?", orgID)
  15. }
  16. if len(keywords) > 0 {
  17. likeKey := "%" + keywords + "%"
  18. db = db.Where("p.name LIKE ? OR p.dialysis_no LIKE ?", likeKey, likeKey)
  19. }
  20. if schedulType > 0 {
  21. db = db.Joins("JOIN xt_schedule as s ON s.patient_id=p.id")
  22. db = db.Where("s.status=1 and s.schedule_type=?", schedulType)
  23. }
  24. if contagion > 0 {
  25. db = db.Joins("JOIN xt_patients_infectious_diseases as xpid ON xpid.patient_id=p.id")
  26. db = db.Where("xpid.disease_id=? and xpid.status=1", contagion)
  27. }
  28. if isscheduling == 1 {
  29. db = db.Where("EXISTS (?)", readDb.Table("xt_schedule as iss").Where("iss.patient_id=p.id and iss.status=1").QueryExpr())
  30. } else if isscheduling == 2 {
  31. db = db.Where("NOT EXISTS (?)", readDb.Table("xt_schedule as iss").Where("iss.patient_id=p.id and iss.status=1").QueryExpr())
  32. }
  33. if isprescription == 1 {
  34. db = db.Where("EXISTS (?)", readDb.Table("xt_dialysis_prescription as xdp").Where("xdp.patient_id=p.id and xdp.status=1").QueryExpr())
  35. } else if isprescription == 2 {
  36. db = db.Where("NOT EXISTS (?)", readDb.Table("xt_dialysis_prescription as xdp").Where("xdp.patient_id=p.id and xdp.status=1").QueryExpr())
  37. }
  38. if bindingState > 0 {
  39. db = db.Where("p.binding_state=?", bindingState)
  40. }
  41. if lapseto > 0 {
  42. db = db.Where("p.lapseto=?", lapseto)
  43. }
  44. if source > 0 {
  45. db = db.Where("p.source=?", source)
  46. }
  47. if reimbursementWay > 0 {
  48. db = db.Where("p.reimbursement_way_id = ?", reimbursementWay)
  49. }
  50. if isStartTime {
  51. db = db.Where("p.created_time>=?", startTime)
  52. }
  53. if isEndTime {
  54. db = db.Where("p.created_time<=?", endTime)
  55. }
  56. offset := (page - 1) * limit
  57. err = db.Order("p.id desc").Select(" p.id, p.user_org_id, p.user_id, 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.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,p.user_sys_before_count").Group("p.id").Count(&total).Offset(offset).Limit(limit).Find(&patients).Error
  58. return
  59. }
  60. //GetAllPatientList 返回全部患者的列表
  61. func GetAllPatientList(orgID int64) (patients []*models.Patients, total int64, err error) {
  62. db := readDb.Table("xt_patients as p").Where("p.user_org_id=? and p.status=1", orgID)
  63. err = db.Select(" p.id, p.user_org_id, p.user_id, 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.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").Count(&total).Find(&patients).Error
  64. return
  65. }
  66. func GetPatientCount(orgID int64) (total int64) {
  67. readDb.Model(&models.Patients{}).Where("user_org_id=? and status=1", orgID).Count(&total)
  68. return
  69. }
  70. func GetLapsetoPatientCount(orgID int64, lapseto int64) (total int64) {
  71. readDb.Model(&models.Patients{}).Where("user_org_id=? and lapseto=? and status=1", orgID, lapseto).Count(&total)
  72. return
  73. }
  74. func ChechLastDialysisNo(orgID int64) (dialysisNo int64) {
  75. var patient models.Patients
  76. err := readDb.Model(&models.Patients{}).Where("status=1 and user_org_id=?", orgID).Order("dialysis_no desc").First(&patient).Error
  77. if err != nil {
  78. return
  79. }
  80. if patient.ID == 0 {
  81. return
  82. }
  83. dialysisNo, _ = strconv.ParseInt(patient.DialysisNo, 10, 64)
  84. return
  85. }
  86. func FindPatientByDialysisNo(orgID int64, dialysisNo string) (patient models.Patients, err error) {
  87. err = readDb.Model(&models.Patients{}).Where("status=1 and user_org_id=? and dialysis_no=?", orgID, dialysisNo).First(&patient).Error
  88. return
  89. }
  90. func FindPatientByIdCardNo(orgID int64, idCardNo string) (patient models.Patients, err error) {
  91. err = readDb.Model(&models.Patients{}).Where("status=1 and user_org_id=? and id_card_no=?", orgID, idCardNo).First(&patient).Error
  92. return
  93. }
  94. func FindPatientByMobile(orgID int64, mobile string) (patient models.Patients, err error) {
  95. err = readDb.Model(&models.Patients{}).Where("phone=? and user_org_id=? and status=1", mobile, orgID).First(&patient).Error
  96. return
  97. }
  98. func FindPatientById(orgID int64, id int64) (patient models.Patients, err error) {
  99. err = readDb.Model(&models.Patients{}).Where("id = ? and user_org_id=? and status=1", id, orgID).First(&patient).Error
  100. return
  101. }
  102. func FindPatientByIdTwo(orgID int64, id int64) (patient models.XtPatientsNew, err error) {
  103. err = readDb.Model(&models.XtPatientsNew{}).Where("blood_id = ? and user_org_id = ? and status =1", id, orgID).First(&patient).Error
  104. return
  105. }
  106. func FindPatientByIdWithDiseases(orgID int64, id int64) (patient models.Patients, err error) {
  107. err = readDb.Model(&models.Patients{}).Preload("Contagions", "status = 1").Preload("Diseases", "status = 1").Where("id = ? and user_org_id=? and status=1", id, orgID).First(&patient).Error
  108. return
  109. }
  110. func FindPatientWithDeviceByNo(orgID int64, no string, time int64) (patient models.SchedualPatient2, err error) {
  111. err = readDb.Preload("DialysisSchedule", func(db *gorm.DB) *gorm.DB {
  112. return db.Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
  113. Preload("DeviceZone", "status = 1 AND org_id = ?", orgID).
  114. Where("user_org_id = ? AND schedule_date = ? ", orgID, time)
  115. }).Where("user_org_id=? and dialysis_no = ? and status=1", orgID, no).First(&patient).Error
  116. return
  117. }
  118. func CreatePatient(patient *models.Patients, contagions []int64, diseases []int64) (err error) {
  119. user, _ := GetSgjUserByMobild(patient.Phone)
  120. customer, _ := GetSgjCoustomerByMobile(patient.UserOrgId, patient.Phone)
  121. utx := writeDb.Begin()
  122. btx := writeUserDb.Begin()
  123. if user.ID == 0 {
  124. user.Mobile = patient.Phone
  125. user.Avatar = patient.Avatar
  126. user.AvatarThumb = patient.Avatar
  127. user.Birthday = patient.Birthday
  128. user.Username = patient.Name
  129. user.Gender = patient.Gender
  130. user.Sources = 11
  131. user.Introduce = patient.Remark
  132. user.Status = 1
  133. user.UpdatedTime = patient.UpdatedTime
  134. user.CreatedTime = patient.CreatedTime
  135. err = btx.Create(&user).Error
  136. if err != nil {
  137. utx.Rollback()
  138. btx.Rollback()
  139. return
  140. }
  141. }
  142. patient.UserId = user.ID
  143. if customer == nil {
  144. err = btx.Create(&models.SgjCustomer{
  145. UserOrgId: patient.UserOrgId,
  146. UserId: user.ID,
  147. Mobile: patient.Phone,
  148. Name: patient.Name,
  149. Gender: patient.Gender,
  150. Birthday: patient.Birthday,
  151. Sources: 11,
  152. Status: 1,
  153. CreatedTime: patient.CreatedTime,
  154. UpdatedTime: patient.UpdatedTime,
  155. Avatar: patient.Avatar,
  156. Remark: patient.Remark,
  157. }).Error
  158. if err != nil {
  159. utx.Rollback()
  160. btx.Rollback()
  161. return
  162. }
  163. }
  164. err = utx.Create(patient).Error
  165. if err != nil {
  166. utx.Rollback()
  167. btx.Rollback()
  168. return
  169. }
  170. var lapseto models.PatientLapseto
  171. lapseto.PatientId = patient.ID
  172. lapseto.LapsetoType = patient.Lapseto
  173. lapseto.CreatedTime = patient.CreatedTime
  174. lapseto.UpdatedTime = patient.CreatedTime
  175. lapseto.Status = 1
  176. lapseto.LapsetoTime = patient.CreatedTime
  177. err = utx.Create(&lapseto).Error
  178. if err != nil {
  179. utx.Rollback()
  180. btx.Rollback()
  181. return
  182. }
  183. if len(contagions) > 0 {
  184. thisSQL := "INSERT INTO xt_patients_infectious_diseases (patient_id, disease_id, status, created_time, updated_time) VALUES "
  185. insertParams := make([]string, 0)
  186. insertData := make([]interface{}, 0)
  187. for _, contagion := range contagions {
  188. insertParams = append(insertParams, "(?, ?, ?, ?, ?)")
  189. insertData = append(insertData, patient.ID)
  190. insertData = append(insertData, contagion)
  191. insertData = append(insertData, 1)
  192. insertData = append(insertData, patient.CreatedTime)
  193. insertData = append(insertData, patient.UpdatedTime)
  194. }
  195. thisSQL += strings.Join(insertParams, ", ")
  196. err = utx.Exec(thisSQL, insertData...).Error
  197. if err != nil {
  198. utx.Rollback()
  199. btx.Rollback()
  200. return
  201. }
  202. }
  203. if len(diseases) > 0 {
  204. thisSQL := "INSERT INTO xt_patients_chronic_diseases (patient_id, disease_id, status, created_time, updated_time) VALUES "
  205. insertParams := make([]string, 0)
  206. insertData := make([]interface{}, 0)
  207. for _, disease := range diseases {
  208. insertParams = append(insertParams, "(?, ?, ?, ?, ?)")
  209. insertData = append(insertData, patient.ID)
  210. insertData = append(insertData, disease)
  211. insertData = append(insertData, 1)
  212. insertData = append(insertData, patient.CreatedTime)
  213. insertData = append(insertData, patient.UpdatedTime)
  214. }
  215. thisSQL += strings.Join(insertParams, ", ")
  216. err = utx.Exec(thisSQL, insertData...).Error
  217. if err != nil {
  218. utx.Rollback()
  219. btx.Rollback()
  220. return
  221. }
  222. }
  223. utx.Commit()
  224. btx.Commit()
  225. return
  226. }
  227. func GetLastPatientData(orgid int64) (models.Patients, error) {
  228. patients := models.Patients{}
  229. err := XTReadDB().Model(&patients).Where("user_org_id = ? and status = 1", orgid).Last(&patients).Error
  230. return patients, err
  231. }
  232. func CreatePatientsNew(patientsNew *models.XtPatientsNew) error {
  233. err := XTWriteDB().Model(&patientsNew).Create(&patientsNew).Error
  234. return err
  235. }
  236. func EditPatientLapseto(patient *models.Patients, lapseto *models.PatientLapseto) (err error) {
  237. utx := writeDb.Begin()
  238. err = utx.Model(&models.Patients{}).Where("id=?", patient.ID).Update(map[string]interface{}{"Lapseto": patient.Lapseto}).Error
  239. if err != nil {
  240. utx.Rollback()
  241. return
  242. }
  243. err = utx.Create(lapseto).Error
  244. if err != nil {
  245. utx.Rollback()
  246. return
  247. }
  248. // 删除排班和排班模板信息
  249. if lapseto.LapsetoType == 2 {
  250. now := time.Now()
  251. deleteScheduleErr := utx.Model(&models.PatientSchedule{}).Where("patient_id = ? AND schedule_date >= ? AND status = 1", patient.ID, lapseto.LapsetoTime).Updates(map[string]interface{}{
  252. "status": 0,
  253. "updated_time": now.Unix(),
  254. }).Error
  255. if deleteScheduleErr != nil {
  256. utx.Rollback()
  257. err = deleteScheduleErr
  258. return
  259. }
  260. deleteSchTempItemErr := utx.Model(&models.PatientScheduleTemplateItem{}).Where("patient_id = ? AND status = 1", patient.ID).Updates(map[string]interface{}{
  261. "status": 0,
  262. "mtime": now.Unix(),
  263. }).Error
  264. if deleteSchTempItemErr != nil {
  265. utx.Rollback()
  266. err = deleteSchTempItemErr
  267. return
  268. }
  269. }
  270. utx.Commit()
  271. return
  272. }
  273. func UpdatePatient(patient *models.Patients, contagions []int64, diseases []int64) (err error) {
  274. // if len(contagions) > 0 || len(diseases) > 0 {
  275. utx := writeDb.Begin()
  276. err = utx.Save(patient).Error
  277. if err != nil {
  278. utx.Rollback()
  279. return
  280. }
  281. err = utx.Model(&models.InfectiousDiseases{}).Where("patient_id=?", patient.ID).Update(map[string]interface{}{"Status": 2, "UpdatedTime": patient.UpdatedTime}).Error
  282. fmt.Println("err", err)
  283. if err != nil {
  284. utx.Rollback()
  285. return
  286. }
  287. if len(contagions) > 0 {
  288. thisSQL := "INSERT INTO xt_patients_infectious_diseases (patient_id, disease_id, status, created_time, updated_time) VALUES "
  289. insertParams := make([]string, 0)
  290. insertData := make([]interface{}, 0)
  291. for _, contagion := range contagions {
  292. insertParams = append(insertParams, "(?, ?, ?, ?, ?)")
  293. insertData = append(insertData, patient.ID)
  294. insertData = append(insertData, contagion)
  295. insertData = append(insertData, 1)
  296. insertData = append(insertData, patient.CreatedTime)
  297. insertData = append(insertData, patient.UpdatedTime)
  298. }
  299. thisSQL += strings.Join(insertParams, ", ")
  300. err = utx.Exec(thisSQL, insertData...).Error
  301. if err != nil {
  302. utx.Rollback()
  303. return
  304. }
  305. }
  306. err = utx.Model(&models.ChronicDiseases{}).Where("patient_id=?", patient.ID).Update(map[string]interface{}{"Status": 2, "UpdatedTime": patient.UpdatedTime}).Error
  307. if err != nil {
  308. utx.Rollback()
  309. return
  310. }
  311. if len(diseases) > 0 {
  312. thisSQL := "INSERT INTO xt_patients_chronic_diseases (patient_id, disease_id, status, created_time, updated_time) VALUES "
  313. insertParams := make([]string, 0)
  314. insertData := make([]interface{}, 0)
  315. for _, disease := range diseases {
  316. insertParams = append(insertParams, "(?, ?, ?, ?, ?)")
  317. insertData = append(insertData, patient.ID)
  318. insertData = append(insertData, disease)
  319. insertData = append(insertData, 1)
  320. insertData = append(insertData, patient.CreatedTime)
  321. insertData = append(insertData, patient.UpdatedTime)
  322. }
  323. thisSQL += strings.Join(insertParams, ", ")
  324. err = utx.Exec(thisSQL, insertData...).Error
  325. if err != nil {
  326. utx.Rollback()
  327. return
  328. }
  329. }
  330. utx.Commit()
  331. // } else {
  332. // err = writeDb.Save(patient).Error
  333. // }
  334. return
  335. }
  336. func UpdatepatientTwo(patientsNew *models.XtPatientsNew, id int64) error {
  337. err := XTWriteDB().Model(&patientsNew).Where("blood_id = ?", id).Update(map[string]interface{}{"user_org_id": patientsNew.UserOrgId, "user_id": patientsNew.UserId, "avatar": patientsNew.Avatar, "patient_type": patientsNew.Avatar, "dialysis_no": patientsNew.DialysisNo, "admission_number": patientsNew.AdmissionNumber, "source": patientsNew.Source, "lapseto": patientsNew.Lapseto, "partition_id": patientsNew.PartitionId, "bed_id": patientsNew.BedId, "name": patientsNew.Name, "alias": patientsNew.Alias, "gender": patientsNew.Gender, "marital_status": patientsNew.MaritalStatus, "id_card_no": patientsNew.IdCardNo, "birthday": patientsNew.Birthday, "reimbursement_way_id": patientsNew.ReimbursementWayId, "health_care_type": patientsNew.HealthCareType, "health_care_no": patientsNew.HealthCareType, "health_care_due_date": patientsNew.HealthCareType, "height": patientsNew.Height, "blood_type": patientsNew.BloodType, "rh": patientsNew.Rh, "health_care_due_alert_date": patientsNew.HealthCareDueAlertDate, "education_level": patientsNew.EducationLevel, "profession": patientsNew.Profession, "phone": patientsNew.Phone, "home_telephone": patientsNew.HomeTelephone, "relative_phone": patientsNew.RelativePhone, "relative_relations": patientsNew.RelativeRelations, "home_address": patientsNew.HomeAddress, "work_unit": patientsNew.WorkUnit, "unit_address": patientsNew.UnitAddress, "children": patientsNew.Children, "receiving_date": patientsNew.ReceivingDate, "is_hospital_first_dialysis": patientsNew.IsHospitalFirstDialysis, "first_dialysis_date": patientsNew.FirstDialysisDate, "first_dialysis_hospital": patientsNew.FirstDialysisHospital, "predialysis_condition": patientsNew.PredialysisCondition, "pre_hospital_dialysis_frequency": patientsNew.PreHospitalDialysisFrequency, "pre_hospital_dialysis_times": patientsNew.PreHospitalDialysisFrequency, "hospital_first_dialysis_date": patientsNew.HospitalFirstDialysisDate, "induction_period": patientsNew.InductionPeriod, "initial_dialysis": patientsNew.InitialDialysis, "total_dialysis": patientsNew.TotalDialysis, "attending_doctor_id": patientsNew.AttendingDoctorId, "head_nurse_id": patientsNew.HeadNurseId, "evaluate": patientsNew.Evaluate, "diagnose": patientsNew.Diagnose, "remark": patientsNew.Remark, "registrars_id": patientsNew.RegistrarsId, "registrars": patientsNew.Registrars, "qr_code": patientsNew.QrCode, "binding_state": patientsNew.BindingState, "patient_complains": patientsNew.PatientComplains, "present_history": patientsNew.PresentHistory, "past_history": patientsNew.PastHistory, "temperature": patientsNew.Temperature,
  338. "pulse": patientsNew.Pulse, "respiratory": patientsNew.Respiratory, "sbp": patientsNew.Sbp, "dbp": patientsNew.Dbp, "nation": patientsNew.Nation, "native_place": patientsNew.NativePlace, "age": patientsNew.Age, "infectious_next_record_time": patientsNew.InfectiousNextRecordTime, "is_infectious": patientsNew.IsInfectious, "remind_cycle": patientsNew.RemindCycle, "response_result": patientsNew.ResponseResult, "is_open_remind": patientsNew.IsOpenRemind, "first_treatment_date": patientsNew.FirstTreatmentDate, "dialysis_age": patientsNew.DialysisAge, "expense_kind": patientsNew.ExpenseKind, "tell_phone": patientsNew.ExpenseKind, "contact_name": patientsNew.ContactName, "blood_patients": patientsNew.BloodPatients, "slow_patients": patientsNew.SlowPatients, "member_patients": patientsNew.MemberPatients, "ecommer_patients": patientsNew.EcommerPatients}).Error
  339. return err
  340. }
  341. func GetLastInfectionRecord(id int64, org_id int64, project_id int64, date int64) (inspection models.Inspection, err error) {
  342. err = readDb.Model(&models.Inspection{}).Where("patient_id=? and status=1 and org_id = ? and project_id = ? AND inspect_date = ? ", id, org_id, project_id, date).Last(&inspection).Error
  343. return
  344. }
  345. func GetAllInfectionRecord(date int64, org_id int64, patient_id int64, project_id int64) (inspection []*models.Inspection, err error) {
  346. err = readDb.Model(&models.Inspection{}).Where("patient_id=? and status=1 and org_id = ? and project_id = ? and inspect_date = ?", patient_id, org_id, project_id, date).Find(&inspection).Error
  347. return
  348. }
  349. func GetPatientDiseases(id int64) []int64 {
  350. var dis []models.ChronicDiseases
  351. ids := make([]int64, 0)
  352. err := readDb.Model(&models.ChronicDiseases{}).Where("patient_id=? and status=1", id).Find(&dis).Error
  353. if err != nil || len(dis) == 0 {
  354. return ids
  355. }
  356. for _, item := range dis {
  357. ids = append(ids, item.DiseaseId)
  358. }
  359. return ids
  360. }
  361. func GetPatientContagions(id int64) []int64 {
  362. var cis []models.InfectiousDiseases
  363. ids := make([]int64, 0)
  364. err := readDb.Model(&models.InfectiousDiseases{}).Where("patient_id=? and status=1", id).Find(&cis).Error
  365. if err != nil || len(cis) == 0 {
  366. return ids
  367. }
  368. for _, item := range cis {
  369. ids = append(ids, item.DiseaseId)
  370. }
  371. return ids
  372. }
  373. func FindPatientDialysisSolutionByMode(orgID int64, patientID, modeId int64) (solution models.DialysisSolution, err error) {
  374. err = readDb.Model(&models.DialysisSolution{}).Where("user_org_id=? and patient_id=? and mode_id=? and parent_id=0 and status=1", orgID, patientID, modeId).First(&solution).Error
  375. return
  376. }
  377. func FindPatientDialysisSolution(orgID int64, id int64) (solution models.DialysisSolution, err error) {
  378. err = readDb.Model(&models.DialysisSolution{}).Where("id = ? and status=1 and user_org_id=?", id, orgID).First(&solution).Error
  379. return
  380. }
  381. func FindPatientDialysisSolutionChild(orgID int64, id int64) (solution models.DialysisSolution, err error) {
  382. err = readDb.Model(&models.DialysisSolution{}).Where("parent_id = ? and status=1 and user_org_id=?", id, orgID).First(&solution).Error
  383. return
  384. }
  385. func CreatePatientDialysisSolution(solution *models.DialysisSolution) (err error) {
  386. err = writeDb.Create(solution).Error
  387. return
  388. }
  389. func UpdatePatientDialysisSolution(solution *models.DialysisSolution) (err error) {
  390. err = writeDb.Save(solution).Error
  391. return
  392. }
  393. //GetPatientDialysisSolutionList 返回患者透析方案的列表
  394. func GetPatientDialysisSolutionList(orgID int64, patientID int64, page, limit int64) (solutions []*models.DialysisSolution, total int64, err error) {
  395. offset := (page - 1) * limit
  396. db := readDb.Table("xt_dialysis_solution as ds").Where("ds.status=1")
  397. if orgID > 0 {
  398. db = db.Where("ds.user_org_id=?", orgID)
  399. }
  400. if patientID > 0 {
  401. db = db.Where("ds.patient_id=?", patientID)
  402. }
  403. db = db.Count(&total).Offset(offset).Limit(limit)
  404. err = db.Order("id desc").Find(&solutions).Error
  405. if err != nil {
  406. return
  407. }
  408. if len(solutions) > 0 {
  409. nilNameIds := make([]int64, 0)
  410. for _, solution := range solutions {
  411. if len(solution.ModeName) == 0 {
  412. nilNameIds = append(nilNameIds, solution.ModeId)
  413. }
  414. }
  415. if len(nilNameIds) > 0 {
  416. var modes []*models.TreatmentMode
  417. err = readDb.Model(&models.TreatmentMode{}).Where("id IN (?)", nilNameIds).Find(&modes).Error
  418. if err != nil {
  419. return
  420. }
  421. modesMap := make(map[int64]models.TreatmentMode, 0)
  422. for _, mode := range modes {
  423. modesMap[mode.ID] = *mode
  424. }
  425. for index, solution := range solutions {
  426. if _, exixt := modesMap[solution.ModeId]; exixt && len(solution.ModeName) == 0 {
  427. solutions[index].ModeName = modesMap[solution.ModeId].Name
  428. }
  429. }
  430. }
  431. }
  432. return
  433. }
  434. //GetPatientDryWeightAdjustList 返回患者调整干体重的列表
  435. func GetPatientDryWeightAdjustList(orgID int64, patientID int64, page int64, limit int64) (weights []*models.DryWeightAdjust, total int64, err error) {
  436. db := readDb.Table("xt_dry_weight_adjust as dwa").Where("dwa.status=1")
  437. if orgID > 0 {
  438. db = db.Where("dwa.user_org_id=?", orgID)
  439. }
  440. if patientID > 0 {
  441. db = db.Where("dwa.patient_id=?", patientID)
  442. }
  443. db = db.Select("dwa.id, dwa.user_org_id, dwa.patient_id, dwa.weight, dwa.adjusted_value, dwa.doctor, dwa.registrars_id, dwa.remark, dwa.status, dwa.created_time, dwa.updated_time").Count(&total).Order("id desc")
  444. if page > 0 && limit > 0 {
  445. offset := (page - 1) * limit
  446. db = db.Offset(offset).Limit(limit)
  447. }
  448. err = db.Find(&weights).Error
  449. return
  450. }
  451. func CreateDryWeightAdjust(m *models.DryWeightAdjust) (err error) {
  452. err = writeDb.Create(m).Error
  453. return
  454. }
  455. func FindPatientLastDryWeightAdjust(orgID int64, id int64) (weight models.DryWeightAdjust, err error) {
  456. err = readDb.Model(&models.DryWeightAdjust{}).Where("user_org_id=? and patient_id=? and status=1", orgID, id).Order("id desc").First(&weight).Error
  457. return
  458. }
  459. func CreateDoctorAdvice(m *models.DoctorAdvice) (err error) {
  460. return writeDb.Create(m).Error
  461. }
  462. func GetMaxAdviceGroupID(orgId int64) (group int64) {
  463. var advice models.DoctorAdvice
  464. err := readDb.Table("xt_doctor_advice").Where("user_org_id=?", orgId).Select("max(groupno) as groupno").First(&advice).Error
  465. if err != nil {
  466. fmt.Println(err)
  467. group = 0
  468. }
  469. group = advice.GroupNo
  470. return
  471. }
  472. func CreateGroupAdvice(orgId int64, group int64, advices []*models.GroupAdvice) (err error) {
  473. if group == 0 {
  474. group = GetMaxAdviceGroupID(orgId) + 1
  475. }
  476. tx := writeDb.Begin()
  477. defer func() {
  478. if r := recover(); r != nil {
  479. tx.Rollback()
  480. }
  481. }()
  482. for _, advice := range advices {
  483. advice.GroupNo = group
  484. if err = tx.Create(advice).Error; err != nil {
  485. tx.Rollback()
  486. return
  487. }
  488. }
  489. tx.Commit()
  490. return
  491. }
  492. func CreateMGroupAdvice(orgId int64, advices []*models.GroupAdvice, groupNo int64) (list []*models.GroupAdvice, err error) {
  493. if groupNo <= 0 {
  494. group := GetMaxAdviceGroupID(orgId)
  495. groupNo = group + 1
  496. }
  497. tx := writeDb.Begin()
  498. defer func() {
  499. if r := recover(); r != nil {
  500. tx.Rollback()
  501. }
  502. }()
  503. for _, advice := range advices {
  504. advice.GroupNo = groupNo
  505. if err = tx.Create(advice).Error; err != nil {
  506. tx.Rollback()
  507. return
  508. }
  509. list = append(list, advice)
  510. if len(advice.Children) > 0 {
  511. for _, child := range advice.Children {
  512. child.GroupNo = groupNo
  513. child.ParentId = advice.ID
  514. fmt.Println(child)
  515. if err = tx.Create(&child).Error; err != nil {
  516. tx.Rollback()
  517. return
  518. }
  519. list = append(list, child)
  520. }
  521. }
  522. }
  523. tx.Commit()
  524. return
  525. }
  526. func UpdateDoctorAdvice(m *models.DoctorAdvice) (err error) {
  527. return writeDb.Save(m).Error
  528. }
  529. func StopGroupAdvice(orgId int64, groupNo int64, m *models.DoctorAdvice) (err error) {
  530. err = writeDb.Model(&models.DoctorAdvice{}).Where("user_org_id=? and groupno=?", orgId, groupNo).Update(map[string]interface{}{"UpdatedTime": m.UpdatedTime, "StopState": 1, "StopReason": m.StopReason, "StopDoctor": m.StopDoctor, "StopTime": m.StopTime}).Error
  531. if err != nil {
  532. return
  533. }
  534. return
  535. }
  536. func StopDoctorAdvice(m *models.DoctorAdvice) (err error) {
  537. ut := writeDb.Begin()
  538. err = ut.Save(m).Error
  539. if err != nil {
  540. ut.Rollback()
  541. return
  542. }
  543. err = ut.Model(&models.DoctorAdvice{}).Where("parent_id=?", m.ID).Update(map[string]interface{}{"UpdatedTime": m.UpdatedTime, "StopState": 1, "StopReason": m.StopReason, "StopDoctor": m.StopDoctor, "StopTime": m.StopTime, "Modifier": m.Modifier}).Error
  544. if err != nil {
  545. ut.Rollback()
  546. return
  547. }
  548. ut.Commit()
  549. return
  550. }
  551. func DeleteSolution(m *models.DialysisSolution) (err error) {
  552. if m.ParentId > 0 {
  553. return writeDb.Save(m).Error
  554. } else {
  555. ut := writeDb.Begin()
  556. err = ut.Save(m).Error
  557. if err != nil {
  558. ut.Rollback()
  559. return
  560. }
  561. err = ut.Model(&models.DialysisSolution{}).Where("parent_id=?", m.ID).Update(map[string]interface{}{"UpdatedTime": m.UpdatedTime, "Status": 0}).Error
  562. if err != nil {
  563. ut.Rollback()
  564. return
  565. }
  566. ut.Commit()
  567. }
  568. return
  569. }
  570. func DeleteDoctorAdvice(m *models.DoctorAdvice) (err error) {
  571. if m.ParentId > 0 {
  572. return writeDb.Save(m).Error
  573. } else {
  574. ut := writeDb.Begin()
  575. err = ut.Save(m).Error
  576. if err != nil {
  577. ut.Rollback()
  578. return
  579. }
  580. err = ut.Model(&models.DoctorAdvice{}).Where("parent_id=?", m.ID).Update(map[string]interface{}{"UpdatedTime": m.UpdatedTime, "Status": 0, "Modifier": m.Modifier}).Error
  581. if err != nil {
  582. ut.Rollback()
  583. return
  584. }
  585. ut.Commit()
  586. }
  587. return
  588. }
  589. func DeleteGroupAdvice(orgId int64, groupNo int64, admin_user_id int64) (err error) {
  590. err = writeDb.Model(&models.DoctorAdvice{}).Where("user_org_id = ? and groupno = ?", orgId, groupNo).Update(map[string]interface{}{"UpdatedTime": time.Now().Unix(), "Status": 0, "Modifier": admin_user_id}).Error
  591. if err != nil {
  592. return
  593. }
  594. return
  595. }
  596. func FindDoctorAdvice(orgID, id int64) (advice models.DoctorAdvice, err error) {
  597. err = readDb.Model(&models.DoctorAdvice{}).Where("id = ? and user_org_id=? and status = 1", id, orgID).First(&advice).Error
  598. return
  599. }
  600. func FindDoctorAdviceByGroupNo(orgID, groupNo int64) (advice models.DoctorAdvice, err error) {
  601. err = readDb.Model(&models.DoctorAdvice{}).Where("groupno = ? and user_org_id=? and status = 1", groupNo, orgID).First(&advice).Error
  602. return
  603. }
  604. func GetDoctorAdviceList(orgID, patientID, advice_type, stop, start, end int64, keywords string) (advices []*models.DoctorAdvices, total int64, err error) {
  605. db := readDb.Table("xt_doctor_advice as x").Where("x.status = 1")
  606. table := UserReadDB().Table("sgj_user_admin_role as r")
  607. fmt.Print("table", table)
  608. if orgID > 0 {
  609. db = db.Where("x.user_org_id=?", orgID)
  610. }
  611. if patientID > 0 {
  612. db = db.Where("x.patient_id = ?", patientID)
  613. }
  614. if advice_type > 0 {
  615. db = db.Where("x.advice_type = ?", advice_type)
  616. } else if advice_type == 0 {
  617. db = db.Where("x.advice_type in (?)", []int{1, 3})
  618. }
  619. if stop == 1 {
  620. db = db.Where("(x.stop_state=? or x.execution_state=?)", stop, stop)
  621. } else if stop == 2 {
  622. db = db.Where("x.stop_state=? and x.execution_state=?", stop, stop)
  623. }
  624. if start != 0 {
  625. db = db.Where("x.start_time>=?", start)
  626. }
  627. if end != 0 {
  628. db = db.Where("start_time<=?", end)
  629. }
  630. if len(keywords) > 0 {
  631. likeKey := "%" + keywords + "%"
  632. db = db.Where("x.advice_name LIKE ?", likeKey)
  633. }
  634. err = db.Group("x.id").Count(&total).Select("x.id, x.user_org_id, x.patient_id, x.advice_type, x.advice_date, x.record_date, x.start_time, x.advice_name,x.advice_desc, x.reminder_date, x.drug_spec, x.drug_spec_unit, x.single_dose, x.single_dose_unit, x.prescribing_number, x.prescribing_number_unit, x.delivery_way, x.execution_frequency, x.advice_doctor, x.status, x.created_time,x.updated_time, x.advice_affirm, x.remark, x.stop_time, x.stop_reason, x.stop_doctor, x.stop_state, x.parent_id, x.execution_time, x.execution_staff, x.execution_state, x.checker, x.check_state, x.check_time, x.groupno,x.remind_type,x.frequency_type,x.day_count,x.week_day,x.parent_id,r.user_name, IF(x.parent_id > 0, x.parent_id, x.id) as advice_order").Joins("Left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.advice_doctor").Order("start_time desc, groupno desc, advice_order desc, id asc").Scan(&advices).Error
  635. fmt.Print("err", err)
  636. return
  637. }
  638. func GetDoctorAdviceListOne(orgID, patientID, advice_type, stop, start, end int64, keywords string, page int64, limit int64) (advices []*models.DoctorAdvices, total int64, err error) {
  639. db := readDb.Table("xt_doctor_advice as x").Where("x.status = 1")
  640. table := UserReadDB().Table("sgj_user_admin_role as r")
  641. fmt.Print("table", table)
  642. if orgID > 0 {
  643. db = db.Where("x.user_org_id=?", orgID)
  644. }
  645. if patientID > 0 {
  646. db = db.Where("x.patient_id = ?", patientID)
  647. }
  648. if advice_type == 1 && advice_type > 0 {
  649. db = db.Where("x.advice_type = ?", advice_type)
  650. }
  651. if advice_type == 3 && advice_type > 0 {
  652. db = db.Where("x.advice_type = 2 or x.advice_type = 3")
  653. }
  654. if stop == 1 {
  655. db = db.Where("(x.stop_state=? or x.execution_state=?)", stop, stop)
  656. } else if stop == 2 {
  657. db = db.Where("x.stop_state=? and x.execution_state=?", stop, stop)
  658. }
  659. if start != 0 {
  660. db = db.Where("x.start_time>=?", start)
  661. }
  662. if end != 0 {
  663. db = db.Where("start_time<=?", end)
  664. }
  665. if len(keywords) > 0 {
  666. likeKey := "%" + keywords + "%"
  667. db = db.Where("x.advice_name LIKE ?", likeKey)
  668. }
  669. offset := (page - 1) * limit
  670. err = db.Group("x.id").Count(&total).Offset(offset).Limit(limit).Select("x.id, x.user_org_id, x.patient_id, x.advice_type, x.advice_date, x.record_date, x.start_time, x.advice_name,x.advice_desc, x.reminder_date, x.drug_spec, x.drug_spec_unit, x.single_dose, x.single_dose_unit, x.prescribing_number, x.prescribing_number_unit, x.delivery_way, x.execution_frequency, x.advice_doctor, x.status, x.created_time,x.updated_time, x.advice_affirm, x.remark, x.stop_time, x.stop_reason, x.stop_doctor, x.stop_state, x.parent_id, x.execution_time, x.execution_staff, x.execution_state, x.checker, x.check_state, x.check_time, x.groupno,x.remind_type,x.frequency_type,x.day_count,x.week_day,x.parent_id,r.user_name, IF(x.parent_id > 0, x.parent_id, x.id) as advice_order").Joins("Left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.advice_doctor").Order("start_time desc, groupno desc, advice_order desc, id asc").Scan(&advices).Error
  671. fmt.Print("err", err)
  672. return
  673. }
  674. func GetDoctorAdviceListTwo(orgID int64, patientID int64, advice_type int64, stop int64, start int64, end int64, keywords string, limit int64, page int64) (advices []*models.DoctorAdvices, total int64, err error) {
  675. db := readDb.Table("xt_doctor_advice as x").Where("x.status = 1")
  676. table := UserReadDB().Table("sgj_user_admin_role as r")
  677. fmt.Println(table)
  678. if orgID > 0 {
  679. db = db.Where("x.user_org_id=?", orgID)
  680. }
  681. if patientID > 0 {
  682. db = db.Where("x.patient_id = ?", patientID)
  683. }
  684. if advice_type == 1 {
  685. db = db.Where("x.advice_type = ?", advice_type)
  686. }
  687. if advice_type == 3 {
  688. db = db.Where("x.advice_type <> 1")
  689. }
  690. if stop == 1 {
  691. db = db.Where("(x.stop_state=? or x.execution_state=?)", stop, stop)
  692. } else if stop == 2 {
  693. db = db.Where("x.stop_state=? and x.execution_state=?", stop, stop)
  694. }
  695. if start != 0 {
  696. db = db.Where("x.start_time>=?", start)
  697. }
  698. if end != 0 {
  699. db = db.Where("start_time<=?", end)
  700. }
  701. if len(keywords) > 0 {
  702. likeKey := "%" + keywords + "%"
  703. db = db.Where("x.advice_name LIKE ?", likeKey)
  704. }
  705. offset := (page - 1) * limit
  706. err = db.Order("x.start_time desc").Group("x.start_time").Count(&total).Offset(offset).Limit(limit).Select("x.id, x.user_org_id, x.patient_id, x.advice_type, x.advice_date, x.record_date, x.start_time, x.advice_name,x.advice_desc, x.reminder_date, x.drug_spec, x.drug_spec_unit, x.single_dose, x.single_dose_unit, x.prescribing_number, x.prescribing_number_unit, x.delivery_way, x.execution_frequency, x.advice_doctor, x.status, x.created_time,x.updated_time, x.advice_affirm, x.remark, x.stop_time, x.stop_reason, x.stop_doctor, x.stop_state, x.parent_id, x.execution_time, x.execution_staff, x.execution_state, x.checker, x.check_state, x.check_time, x.groupno,x.remind_type,x.frequency_type,x.day_count,x.week_day,x.parent_id,r.user_name, IF(x.parent_id > 0, x.parent_id, x.id) as advice_order").Joins("Left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.advice_doctor").Scan(&advices).Error
  707. fmt.Print("错误是什么", err)
  708. return
  709. }
  710. func GetDoctorAdvicePageList(orgID, patientID, advice_type, stop, start, end int64, keywords string, page, limit int64) (advices []*models.DoctorAdvice, total int64, err error) {
  711. offset := (page - 1) * limit
  712. db := readDb.Model(&models.DoctorAdvice{}).Where("status=1")
  713. if orgID > 0 {
  714. db = db.Where("user_org_id=?", orgID)
  715. }
  716. if patientID > 0 {
  717. db = db.Where("patient_id = ?", patientID)
  718. }
  719. if advice_type > 0 {
  720. db = db.Where("advice_type = ?", advice_type)
  721. }
  722. if stop == 1 {
  723. db = db.Where("(stop_state=? or execution_state=?) and parent_id=0", stop, stop)
  724. } else if stop == 2 {
  725. db = db.Where("stop_state=? and execution_state=?", stop, stop)
  726. }
  727. if start != 0 {
  728. db = db.Where("start_time>=?", start)
  729. }
  730. if end != 0 {
  731. db = db.Where("start_time<=?", end)
  732. }
  733. if len(keywords) > 0 {
  734. likeKey := "%" + keywords + "%"
  735. db = db.Where("advice_name LIKE ?", likeKey)
  736. }
  737. err = db.Count(&total).Select("id,user_org_id,patient_id,advice_type,advice_date,start_time,advice_name,advice_desc,reminder_date,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 IF(parent_id>0, parent_id, id) as advice_order").Order("advice_order desc, id").Offset(offset).Limit(limit).Scan(&advices).Error
  738. return
  739. }
  740. func CreateSubDoctorAdvice(advices []*models.DoctorAdvice) (err error) {
  741. if len(advices) > 0 {
  742. utx := writeDb.Begin()
  743. if len(advices) > 0 {
  744. thisSQL := "INSERT INTO xt_doctor_advice (single_dose_unit, prescribing_number, prescribing_number_unit, advice_name, advice_desc,single_dose,created_time,updated_time,patient_id,parent_id,user_org_id,record_date,advice_type,drug_spec_unit) VALUES "
  745. insertParams := make([]string, 0)
  746. insertData := make([]interface{}, 0)
  747. for _, advice := range advices {
  748. insertParams = append(insertParams, "(?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
  749. insertData = append(insertData, advice.SingleDoseUnit)
  750. insertData = append(insertData, advice.PrescribingNumber)
  751. insertData = append(insertData, advice.PrescribingNumberUnit)
  752. insertData = append(insertData, advice.AdviceName)
  753. insertData = append(insertData, advice.AdviceDesc)
  754. insertData = append(insertData, advice.SingleDose)
  755. insertData = append(insertData, advice.CreatedTime)
  756. insertData = append(insertData, advice.UpdatedTime)
  757. insertData = append(insertData, advice.PatientId)
  758. insertData = append(insertData, advice.ParentId)
  759. insertData = append(insertData, advice.UserOrgId)
  760. insertData = append(insertData, advice.RecordDate)
  761. insertData = append(insertData, 2)
  762. insertData = append(insertData, advice.DrugSpecUnit)
  763. }
  764. thisSQL += strings.Join(insertParams, ", ")
  765. err = utx.Exec(thisSQL, insertData...).Error
  766. if err != nil {
  767. utx.Rollback()
  768. return
  769. }
  770. }
  771. utx.Commit()
  772. }
  773. return
  774. }
  775. func GetPatientDialysisRecord(orgID, patientID int64, page, limit, start, end, mode_id int64) ([]*models.PatientDialysisRecord, int64, error) {
  776. offset := (page - 1) * limit
  777. var total int64
  778. var err error
  779. var orders []*models.PatientDialysisRecord
  780. // err = readDb.Table("xt_dialysis_order as do").
  781. // Preload("DialysisPrescription", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
  782. // Preload("PredialysisEvaluation", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
  783. // Preload("AssessmentAfterDislysis", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
  784. // Preload("TreatmentSummary", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
  785. // Joins("JOIN xt_schedule as s ON s.patient_id=? and FROM_UNIXTIME(s.schedule_date, '%Y-%m-%d')=FROM_UNIXTIME(do.dialysis_date, '%Y-%m-%d')", patientID).
  786. // Joins("JOIN xt_device_zone as dz ON dz.org_id = ? and dz.id=s.partition_id", orgID).
  787. // Where("do.patient_id=? and do.user_org_id=? and do.stage = 2 and do.status=1", patientID, orgID).Count(&total).Offset(offset).Limit(limit).Order("do.dialysis_date desc").Select(" do.id, do.dialysis_date, do.user_org_id, do.patient_id, do.prescription_id, do.stage, do.remark, do.status, do.created_time, do.updated_time, s.schedule_type, s.partition_id, dz.name as partition_name").Find(&orders).Error
  788. db := readDb.Table("xt_dialysis_order as do").
  789. Preload("DialysisPrescription", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
  790. Preload("PredialysisEvaluation", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
  791. Preload("DialysisPrescription", func(db *gorm.DB) *gorm.DB {
  792. return readDb.Where("patient_id=? and user_org_id=? and status=1", patientID, orgID).Preload("UserAdminRole", func(db *gorm.DB) *gorm.DB {
  793. return readUserDb.Where("status = 1")
  794. })
  795. }).
  796. Preload("AssessmentAfterDislysis", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
  797. Preload("TreatmentSummary", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
  798. Preload("Device", "org_id=? and status=1", orgID).
  799. Preload("UserAdminRole", func(db *gorm.DB) *gorm.DB {
  800. return readUserDb.Where("org_id=? and status = 1", orgID)
  801. }).
  802. Joins("JOIN xt_schedule as s ON s.patient_id=? and FROM_UNIXTIME(s.schedule_date, '%Y-%m-%d')=FROM_UNIXTIME(do.dialysis_date, '%Y-%m-%d')", patientID).
  803. Joins("JOIN xt_device_zone as dz ON dz.org_id = ? and dz.id=s.partition_id", orgID).
  804. Where("do.patient_id=? and do.user_org_id=? and do.stage = 2 and do.status=1", patientID, orgID).Group("s.schedule_date")
  805. if start != 0 {
  806. db = db.Where("do.dialysis_date>=?", start)
  807. }
  808. if end != 0 {
  809. db = db.Where("do.dialysis_date<=?", end)
  810. }
  811. if mode_id > 0 {
  812. db = db.Joins("JOIN xt_dialysis_prescription as dp ON dp.record_id=do.id")
  813. db = db.Where("dp.mode_id=?", mode_id)
  814. }
  815. err = db.Count(&total).Offset(offset).Limit(limit).Order("do.dialysis_date desc").Select("do.bed_id, do.id, do.dialysis_date, do.user_org_id, do.patient_id, do.prescription_id, do.stage, do.remark, do.status, do.created_time, do.updated_time,do.start_nurse,do.finish_nurse ,s.schedule_type, s.partition_id, dz.name as partition_name").Find(&orders).Error
  816. if len(orders) > 0 {
  817. ids := make([]int64, 0)
  818. for _, order := range orders {
  819. dialyzer := order.DialysisPrescription.Dialyzer
  820. ids = append(ids, dialyzer)
  821. }
  822. if len(ids) > 0 {
  823. var dialyzers []*models.DeviceNumber
  824. err = readDb.Model(&models.DeviceNumber{}).Where("id IN (?) and org_id=? and status=1", ids, orgID).Find(&dialyzers).Error
  825. if err != nil {
  826. return nil, 0, err
  827. }
  828. dialyzerMap := make(map[int64]models.DeviceNumber, 0)
  829. for _, item := range dialyzers {
  830. dialyzerMap[item.ID] = *item
  831. }
  832. for orderIndex, order := range orders {
  833. if _, exist := dialyzerMap[order.DialysisPrescription.Dialyzer]; exist {
  834. orders[orderIndex].DeviceNumber = dialyzerMap[order.DialysisPrescription.Dialyzer].Number
  835. }
  836. }
  837. }
  838. }
  839. return orders, total, err
  840. }
  841. func GetPatientTreatmentSummaryList(orgID, patientID, page, limit, start, end int64) (list []*models.TreatmentSummary, total int, err error) {
  842. offset := (page - 1) * limit
  843. fmt.Println(offset)
  844. fmt.Println(limit)
  845. db := readDb.Model(&models.TreatmentSummary{}).Where("user_org_id = ? and patient_id=?", orgID, patientID)
  846. if start != 0 {
  847. db = db.Where("assessment_date >= ?", start)
  848. }
  849. if end != 0 {
  850. db = db.Where("assessment_date <= ?", end)
  851. }
  852. db = db.Where("status=1")
  853. err = db.Count(&total).Offset(offset).Limit(limit).Order("assessment_date desc, id desc").Find(&list).Error
  854. return
  855. }
  856. func GetPatientScheduleList(orgID int64, patientID int64, page int64, limit int64, start int64) (schedules []*models.PatientSchedule, err error) {
  857. offset := (page - 1) * limit
  858. err = readDb.Table("xt_schedule as s").
  859. Preload("DeviceZone", "org_id=? and status=1", orgID).
  860. Preload("DeviceNumber", "org_id=? and status=1", orgID).
  861. Preload("TreatmentMode", "status=1").
  862. Where("s.patient_id =? and s.user_org_id=? and s.schedule_date>=? and s.status=1", patientID, orgID, start).
  863. Limit(limit).Offset(offset).Find(&schedules).Error
  864. return
  865. }
  866. func GetMonitorRecord(orgID int64, date int64, partition int64) ([]*models.MonitorDialysisSchedule, error) {
  867. var mds []*models.MonitorDialysisSchedule
  868. db := readDb.
  869. Model(&models.MonitorDialysisSchedule{}).
  870. Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
  871. Preload("DeviceZone", "status = 1 AND org_id = ?", orgID).
  872. Preload("TreatmentMode", "status = 1").
  873. Preload("Prescription", "status = 1 AND user_org_id = ?", orgID).
  874. Preload("AssessmentBeforeDislysis", "status = 1 AND user_org_id = ?", orgID).
  875. Preload("AssessmentAfterDislysis", "status = 1 AND user_org_id = ?", orgID).
  876. Preload("MonitoringRecord", "status = 1 AND user_org_id = ?", orgID).
  877. Preload("DialysisOrder", "status = 1 AND user_org_id = ?", orgID).
  878. Preload("DialysisOrder.DeviceNumber", "status = 1 AND org_id = ?", orgID).
  879. Preload("MonitorPatients", "status = 1 AND user_org_id = ?", orgID).
  880. Where("status = 1 AND user_org_id = ?", orgID)
  881. if date != 0 {
  882. db = db.Where("schedule_date = ? ", date)
  883. }
  884. if partition != 0 {
  885. db = db.Where("partition_id = ? ", partition)
  886. }
  887. err := db.Find(&mds).Error
  888. return mds, err
  889. }
  890. func MobileGetMonitorsWithPatient(orgID int64, keyword string, page int) ([]*models.MonitorDialysisSchedule, error) {
  891. var patients []*models.Patients
  892. 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
  893. if getPatientErr != nil {
  894. return nil, getPatientErr
  895. }
  896. patientIDs := make([]int64, len(patients))
  897. for index, patient := range patients {
  898. patientIDs[index] = patient.ID
  899. }
  900. db := readDb.
  901. Model(&models.MonitorDialysisSchedule{}).
  902. Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
  903. Preload("DeviceZone", "status = 1 AND org_id = ?", orgID).
  904. Preload("TreatmentMode", "status = 1").
  905. Preload("Prescription", "status = 1 AND user_org_id = ?", orgID).
  906. Preload("AssessmentBeforeDislysis", "status = 1 AND user_org_id = ?", orgID).
  907. Preload("AssessmentAfterDislysis", "status = 1 AND user_org_id = ?", orgID).
  908. Preload("MonitoringRecord", "status = 1 AND user_org_id = ?", orgID).
  909. Preload("DialysisOrder", "status = 1 AND user_org_id = ?", orgID).
  910. Preload("MonitorPatients", "status = 1 AND user_org_id = ?", orgID).
  911. Where("status = 1 AND user_org_id = ? AND patient_id in (?)", orgID, patientIDs)
  912. var schedules []*models.MonitorDialysisSchedule
  913. err := db.Offset(20 * (page - 1)).Limit(20).Order("schedule_date desc").Find(&schedules).Error
  914. return schedules, err
  915. }
  916. func GetPatientByKeyWord(orgID int64, keywords string) (patient []*models.Patients, err error) {
  917. db := readDb.Model(&models.Patients{}).Where("user_org_id=? and status=1", orgID)
  918. if len(keywords) > 0 {
  919. likekey := "%" + keywords + "%"
  920. err = db.Where("name LIKE ? OR dialysis_no LIKE ? ", likekey, likekey).Find(&patient).Error
  921. } else {
  922. err = db.Find(&patient).Error
  923. }
  924. return
  925. }
  926. func FindDoctorAdviceByGoroupNo(orgID int64, groupno int64) (advice models.DoctorAdvice, err error) {
  927. err = readDb.Model(&models.DoctorAdvice{}).Where("user_org_id=? AND groupno = ? AND status = 1", orgID, groupno).First(&advice).Error
  928. return
  929. }
  930. func FindOldDoctorAdvice(orgID int64, advice_id int64) (advice models.DoctorAdvice, err error) {
  931. err = readDb.Model(&models.DoctorAdvice{}).Where("id = ? AND user_org_id=? AND status = 1", advice_id, orgID).First(&advice).Error
  932. return
  933. }
  934. func UpdateAdviceGroupStartTime(orgID int64, groupNO int64, startTime int64, admin_user_id int64) error {
  935. now := time.Now().Unix()
  936. err := writeDb.Model(&models.DoctorAdvice{}).Where("user_org_id = ? AND status = 1 AND execution_state <> 1 AND check_state <> 1 AND groupno = ? AND admin_user_id = ?", orgID, groupNO, admin_user_id).Updates(map[string]interface{}{
  937. "start_time": startTime,
  938. "updated_time": now,
  939. "modifier": admin_user_id,
  940. }).Error
  941. return err
  942. }
  943. func QueryPatientById(id int64) *models.Patients {
  944. var pat models.Patients
  945. err := readDb.Model(&models.Patients{}).Where("id=?", id).First(&pat).Error
  946. if err != nil {
  947. }
  948. return &pat
  949. }
  950. func FindAllDoctorAdviceByGoroupNo(orgID int64, groupno int64) (advice []models.DoctorAdvice, err error) {
  951. err = readDb.Model(&models.DoctorAdvice{}).Where("user_org_id=? AND groupno = ? AND status = 1", orgID, groupno).Find(&advice).Error
  952. return
  953. }
  954. func FindDoctorAdviceByIds(orgID int64, ids []string) (advice []models.DoctorAdvice, err error) {
  955. err = readDb.Model(&models.DoctorAdvice{}).Where("id IN (?) AND user_org_id = ? AND status = 1", ids, orgID).Find(&advice).Error
  956. return
  957. }
  958. func BatchDeleteDoctorAdvice(ids []string, user_id int64) (err error) {
  959. ut := writeDb.Begin()
  960. err = ut.Model(&models.DoctorAdvice{}).Where("status = 1 AND id IN (?)", ids).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix(), "modifier": user_id}).Error
  961. if err != nil {
  962. ut.Rollback()
  963. return
  964. }
  965. err = ut.Model(&models.DoctorAdvice{}).Where("status = 1 AND parent_id IN (?)", ids).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix(), "modifier": user_id}).Error
  966. if err != nil {
  967. ut.Rollback()
  968. return
  969. }
  970. ut.Commit()
  971. return err
  972. }
  973. func FindAdviceByGoroupNo(orgID int64, groupno int64) (advice []models.DoctorAdvice, err error) {
  974. err = readDb.Model(&models.DoctorAdvice{}).Where("user_org_id=? AND groupno = ? AND status = 1 AND parent_id = 0", orgID, groupno).Find(&advice).Error
  975. return
  976. }
  977. func UpdateDoctorAdviceAndSubAdvice(m *models.DoctorAdvice) (err error) {
  978. ut := writeDb.Begin()
  979. err = ut.Save(m).Error
  980. if err != nil {
  981. ut.Rollback()
  982. return
  983. }
  984. err = ut.Model(&models.DoctorAdvice{}).Where("status = 1 AND parent_id IN (?)", m.ID).Updates(map[string]interface{}{"start_time": m.StartTime, "groupno": m.GroupNo, "mtime": time.Now().Unix()}).Error
  985. if err != nil {
  986. ut.Rollback()
  987. return
  988. }
  989. ut.Commit()
  990. return err
  991. }
  992. func GetAllWaitRemindPatient(org_id int64, page int64, limit int64) (total int64, patient []*models.Patients, err error) {
  993. type Total struct {
  994. Count int64
  995. }
  996. var totals Total
  997. offset := (page - 1) * limit
  998. err = readDb.Raw("select * from xt_patients where user_org_id = ? AND infectious_next_record_time > 0 AND status = 1 AND date_sub(DATE_FORMAT(date(from_unixtime(`xt_patients`.`infectious_next_record_time`)),'%Y-%m-%d'), interval 7 day) <= now() Order by infectious_next_record_time", org_id).Offset(offset).Limit(limit).Scan(&patient).Error
  999. readDb.Raw("select Count(id) as count from xt_patients where user_org_id = ? AND infectious_next_record_time > 0 AND status = 1 AND date_sub(DATE_FORMAT(date(from_unixtime(`xt_patients`.`infectious_next_record_time`)),'%Y-%m-%d'), interval 7 day) <= now() Order by infectious_next_record_time", org_id).Scan(&totals)
  1000. return totals.Count, patient, err
  1001. }
  1002. func UpdatePatientRemindStatus(patient_id int64, remind int64, org_id int64) (err error) {
  1003. err = writeDb.Model(&models.Patients{}).Where("status = 1 AND id = ? AND user_org_id = ?", patient_id, org_id).Updates(map[string]interface{}{"is_open_remind": remind}).Error
  1004. return
  1005. }
  1006. func CreatePatientWeightAdjust(m *models.SgjPatientDryweight) (err error) {
  1007. err = writeDb.Create(m).Error
  1008. return
  1009. }
  1010. func FindLastDryWeightAdjust(orgID int64, id int64) (weight models.SgjPatientDryweight, err error) {
  1011. err = readDb.Model(&models.SgjPatientDryweight{}).Where("user_org_id=? and patient_id=? and status=1", orgID, id).Order("id desc").First(&weight).Error
  1012. return
  1013. }
  1014. func GetSchedualPatientByKeyWord(orgID int64, keywords string, date int64) (patient []*models.Patients, err error) {
  1015. db := readDb.Model(&models.Patients{}).Where("user_org_id=? and status=1 and lapseto = 1 ", orgID)
  1016. if len(keywords) > 0 {
  1017. likekey := "%" + keywords + "%"
  1018. err = db.Where("(name LIKE ? OR dialysis_no LIKE ?) AND NOT EXISTS (Select * FROM `xt_dialysis_order` as d Where d.`dialysis_date` = ? AND d.`status` = 1 AND d.`patient_id` = xt_patients.id AND d.user_org_id = xt_patients.user_org_id)", likekey, likekey, date).Find(&patient).Error
  1019. } else {
  1020. err = db.Find(&patient).Error
  1021. }
  1022. return
  1023. }
  1024. func GetPatientScheduleOne(patientid int64, nowdate int64, orgid int64) (models.XtSchedule, error) {
  1025. schedule := models.XtSchedule{}
  1026. err := XTReadDB().Model(&schedule).Where("patient_id = ? and schedule_date = ? and user_org_id = ? and status =1", patientid, nowdate, orgid).Find(&schedule).Error
  1027. return schedule, err
  1028. }
  1029. func CreateExportPatient(patient *models.Patients, contagions []int64, org_creator int64) (err error) {
  1030. user, _ := GetSgjUserByMobild(patient.Phone)
  1031. customer, _ := GetSgjCoustomerByMobile(patient.UserOrgId, patient.Phone)
  1032. utx := writeDb.Begin()
  1033. btx := writeUserDb.Begin()
  1034. if user.ID == 0 {
  1035. user.Mobile = patient.Phone
  1036. user.Avatar = patient.Avatar
  1037. user.AvatarThumb = patient.Avatar
  1038. user.Birthday = patient.Birthday
  1039. user.Username = patient.Name
  1040. user.Gender = patient.Gender
  1041. user.Sources = 11
  1042. user.Introduce = patient.Remark
  1043. user.Status = 1
  1044. user.UpdatedTime = patient.UpdatedTime
  1045. user.CreatedTime = patient.CreatedTime
  1046. err = btx.Create(&user).Error
  1047. if err != nil {
  1048. utx.Rollback()
  1049. btx.Rollback()
  1050. return
  1051. }
  1052. }
  1053. patient.UserId = user.ID
  1054. if customer == nil {
  1055. err = btx.Create(&models.SgjCustomer{
  1056. UserOrgId: patient.UserOrgId,
  1057. UserId: user.ID,
  1058. Mobile: patient.Phone,
  1059. Name: patient.Name,
  1060. Gender: patient.Gender,
  1061. Birthday: patient.Birthday,
  1062. Sources: 11,
  1063. Status: 1,
  1064. CreatedTime: patient.CreatedTime,
  1065. UpdatedTime: patient.UpdatedTime,
  1066. Avatar: patient.Avatar,
  1067. Remark: patient.Remark,
  1068. }).Error
  1069. if err != nil {
  1070. utx.Rollback()
  1071. btx.Rollback()
  1072. return
  1073. }
  1074. }
  1075. err = utx.Create(patient).Error
  1076. if err != nil {
  1077. utx.Rollback()
  1078. btx.Rollback()
  1079. return
  1080. }
  1081. if patient.DryWeight > 0 {
  1082. var dryWeight models.SgjPatientDryweight
  1083. dryWeight.PatientId = patient.ID
  1084. dryWeight.UserOrgId = patient.UserOrgId
  1085. dryWeight.Status = 1
  1086. dryWeight.AdjustedValue = "/"
  1087. dryWeight.Creator = org_creator
  1088. dryWeight.UserId = org_creator
  1089. dryWeight.Ctime = time.Now().Unix()
  1090. dryWeight.Mtime = time.Now().Unix()
  1091. dryWeight.DryWeight = patient.DryWeight
  1092. dryWeight.Remakes = ""
  1093. err = utx.Create(&dryWeight).Error
  1094. }
  1095. var lapseto models.PatientLapseto
  1096. lapseto.PatientId = patient.ID
  1097. lapseto.LapsetoType = patient.Lapseto
  1098. lapseto.CreatedTime = patient.CreatedTime
  1099. lapseto.UpdatedTime = patient.CreatedTime
  1100. lapseto.Status = 1
  1101. lapseto.LapsetoTime = patient.CreatedTime
  1102. err = utx.Create(&lapseto).Error
  1103. if err != nil {
  1104. utx.Rollback()
  1105. btx.Rollback()
  1106. return
  1107. }
  1108. if len(contagions) > 0 {
  1109. thisSQL := "INSERT INTO xt_patients_infectious_diseases (patient_id, disease_id, status, created_time, updated_time) VALUES "
  1110. insertParams := make([]string, 0)
  1111. insertData := make([]interface{}, 0)
  1112. for _, contagion := range contagions {
  1113. insertParams = append(insertParams, "(?, ?, ?, ?, ?)")
  1114. insertData = append(insertData, patient.ID)
  1115. insertData = append(insertData, contagion)
  1116. insertData = append(insertData, 1)
  1117. insertData = append(insertData, patient.CreatedTime)
  1118. insertData = append(insertData, patient.UpdatedTime)
  1119. }
  1120. thisSQL += strings.Join(insertParams, ", ")
  1121. err = utx.Exec(thisSQL, insertData...).Error
  1122. if err != nil {
  1123. utx.Rollback()
  1124. btx.Rollback()
  1125. return
  1126. }
  1127. }
  1128. patientsNew := models.XtPatientsNew{
  1129. Name: patient.Name,
  1130. Gender: patient.Gender,
  1131. Phone: patient.Phone,
  1132. IdCardNo: patient.IdCardNo,
  1133. FirstDialysisDate: patient.FirstDialysisDate,
  1134. Source: patient.Source,
  1135. Lapseto: patient.Lapseto,
  1136. IsInfectious: patient.IsInfectious,
  1137. DialysisNo: patient.DialysisNo,
  1138. Height: patient.Height,
  1139. HomeAddress: patient.HomeAddress,
  1140. IsExcelExport: 1,
  1141. BloodPatients: 1,
  1142. Status: 1,
  1143. CreatedTime: time.Now().Unix(),
  1144. UserOrgId: patient.UserOrgId,
  1145. BloodId: patient.ID,
  1146. Avatar: "https://images.shengws.com/201809182128111.png",
  1147. }
  1148. err = utx.Create(&patientsNew).Error
  1149. if err != nil {
  1150. utx.Rollback()
  1151. btx.Rollback()
  1152. return
  1153. }
  1154. utx.Commit()
  1155. btx.Commit()
  1156. return
  1157. }
  1158. func FindPatientPhoneIsExist(phone string, org_id int64) (count int64) {
  1159. readDb.Model(&models.Patients{}).Where("user_org_id = ? AND phone = ? AND status = 1", org_id, phone).Count(&count)
  1160. return
  1161. }
  1162. func FindPatientIdCardNoIsExist(id_card_no string, org_id int64) (count int64) {
  1163. readDb.Model(&models.Patients{}).Where("user_org_id = ? AND id_card_no = ? AND status = 1", org_id, id_card_no).Count(&count)
  1164. return
  1165. }
  1166. func CreateExportErrLog(log *models.ExportErrLog) {
  1167. writeDb.Create(&log)
  1168. return
  1169. }
  1170. func FindPatientExportLog(org_id int64, export_time int64) (errLogs []*models.ExportErrLog, err error) {
  1171. err = readDb.Model(&models.ExportErrLog{}).Where("user_org_id = ? AND export_time = ? AND log_type = 1", org_id, export_time).Find(&errLogs).Error
  1172. return
  1173. }
  1174. func CreateExportLog(log *models.ExportLog) {
  1175. writeDb.Create(&log)
  1176. }
  1177. func UpdateDoctorEditAdvice(advice models.XtDoctorAdvice, orgid int64, groupno int64, date int64, patientid int64) error {
  1178. err := XTWriteDB().Model(&advice).Where("user_org_id = ? and groupno = ? and advice_date = ? and patient_id = ?", orgid, groupno, date, patientid).Update(map[string]interface{}{"start_time": advice.StartTime, "updated_time": advice.UpdatedTime}).Error
  1179. return err
  1180. }