pharmacy_service.go 85KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552
  1. package service
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "math"
  6. "strconv"
  7. "strings"
  8. "sync"
  9. "time"
  10. "XT_New/models"
  11. "XT_New/utils"
  12. "github.com/astaxie/beego/config"
  13. "github.com/astaxie/beego/context"
  14. "github.com/jinzhu/gorm"
  15. "golang.org/x/sync/errgroup"
  16. )
  17. func SaveErrs(org_id int64, input *context.BeegoInput, err error) {
  18. dataBody := make(map[string]interface{}, 0)
  19. json.Unmarshal(input.RequestBody, &dataBody)
  20. route := input.Context.Request.RequestURI
  21. parameter := MapToJson(dataBody)
  22. tmp := models.XtErrs{
  23. org_id,
  24. route,
  25. parameter,
  26. err.Error(),
  27. }
  28. XTWriteDB().Create(&tmp)
  29. }
  30. func SavePharmacy() (err error) {
  31. var advice_info []*models.HisDoctorAdviceInfo
  32. err = XTReadDB().Raw("select * from xt_doctor_advice where id > 21780 and id < 21790").Scan(&advice_info).Error
  33. if err != nil {
  34. return
  35. }
  36. return nil
  37. }
  38. // 查询药房中某一天的患者人数,is_medicine:0未发,1已发(改)
  39. func GetTodayPharmacy(stime, etime, orgid, is_medicine int64) (num int, err error) {
  40. //orgid = 9675
  41. InitDrugidIsNil(orgid, stime, etime)
  42. var tmp []*models.TmpTTT
  43. if is_medicine == 0 {
  44. err = XTReadDB().Raw("select distinct patient_id from his_doctor_advice_info where "+
  45. "status = 1 and advice_date >= ? and advice_date <= ? and user_org_id = ? and is_medicine = 0 and "+
  46. "drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1) "+
  47. "union "+
  48. "select distinct patient_id from xt_doctor_advice where "+
  49. "status = 1 and (advice_type = 2 or advice_type = 3) and advice_date >= ? and advice_date <= ? and user_org_id = ? and is_medicine = 0 and "+
  50. "drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1) ",
  51. stime, etime, orgid, orgid, stime, etime, orgid, orgid).Scan(&tmp).Error
  52. if err != nil {
  53. return
  54. }
  55. } else {
  56. err = XTReadDB().Raw("select distinct patient_id from his_doctor_advice_info where "+
  57. "status = 1 and advice_date >= ? and advice_date <= ? and user_org_id = ? and is_medicine = 1 and "+
  58. "drug_id in (select id from xt_base_drug where org_id = ? and status = 1) "+
  59. "union "+
  60. "select distinct patient_id from xt_doctor_advice where "+
  61. "status = 1 and (advice_type = 2 or advice_type = 3) and advice_date >= ? and advice_date <= ? and user_org_id = ? and is_medicine = 1 and "+
  62. "drug_id in (select id from xt_base_drug where org_id = ? and status = 1) ",
  63. stime, etime, orgid, orgid, stime, etime, orgid, orgid).Scan(&tmp).Error
  64. if err != nil {
  65. return
  66. }
  67. }
  68. return len(tmp), err
  69. }
  70. func GetTodayAdviceCount(stime, etime, orgid, is_medicine int64) (num int, err error) {
  71. //orgid = 9675
  72. InitDrugidIsNil(orgid, stime, etime)
  73. var tmp []*models.TmpTTT
  74. if is_medicine == 0 {
  75. err = XTReadDB().Raw("select * from his_doctor_advice_info where status= 1 and advice_date>=? and advice_date<=? and user_org_id=? and is_medicine=0 group by patient_id",
  76. stime, etime, orgid).Scan(&tmp).Error
  77. if err != nil {
  78. return
  79. }
  80. } else {
  81. err = XTReadDB().Raw("select * from his_doctor_advice_info where status= 1 and advice_date>=? and advice_date<=? and user_org_id=? and is_medicine=1 group by patient_id",
  82. stime, etime, orgid).Scan(&tmp).Error
  83. if err != nil {
  84. return
  85. }
  86. }
  87. return len(tmp), err
  88. }
  89. func GetPatientKeyWord(keywword string, org_id int64) (patient []*models.XtPatients, err error) {
  90. db := XTReadDB().Model(&patient).Where("status=1")
  91. likeKey := "%" + keywword + "%"
  92. if len(keywword) > 0 {
  93. db = db.Where("name like ? or first_letter like ?", likeKey, likeKey)
  94. }
  95. if org_id > 0 {
  96. db = db.Where("user_org_id = ?", org_id)
  97. }
  98. err = db.Find(&patient).Error
  99. return patient, err
  100. }
  101. func GetSchedulePatientId(start_time int64, end_time int64, org_id int64, class_type int64, partion_type int64, patientsId []int64) (schedule []*models.XtSchedules, err error) {
  102. db := XTReadDB().Model(&schedule).Where("status = 1")
  103. if start_time > 0 {
  104. db = db.Where("schedule_date >=?", start_time)
  105. }
  106. if end_time > 0 {
  107. db = db.Where("schedule_date <=?", end_time)
  108. }
  109. if org_id > 0 {
  110. db = db.Where("user_org_id = ?", org_id)
  111. }
  112. if class_type > 0 {
  113. db = db.Where("schedule_type =?", class_type)
  114. }
  115. if partion_type > 0 {
  116. db = db.Where("partition_id = ?", partion_type)
  117. }
  118. if len(patientsId) == 0 {
  119. db = db.Where("patient_id in(?)", patientsId)
  120. }
  121. if len(patientsId) > 0 {
  122. db = db.Where("patient_id in(?)", patientsId)
  123. }
  124. err = db.Find(&schedule).Error
  125. return schedule, err
  126. }
  127. func GetTodayAdviceCountOne(stime int64, etime int64, orgid int64, is_medicine int64, ids []int64) (advice []*models.HisDoctorAdviceInfo, err error) {
  128. db := XTReadDB().Model(&advice).Where("status=1 and is_medicine = ?", is_medicine)
  129. if stime > 0 {
  130. db = db.Where("advice_date>=?", stime)
  131. }
  132. if etime > 0 {
  133. db = db.Where("advice_date<=?", stime)
  134. }
  135. if orgid > 0 {
  136. db = db.Where("user_org_id = ?", orgid)
  137. }
  138. if len(ids) == 0 {
  139. db = db.Where("patient_id not in(?)", ids)
  140. }
  141. if len(ids) > 0 {
  142. db = db.Where("patient_id in(?)", ids)
  143. }
  144. err = db.Group("patient_id").Find(&advice).Error
  145. return advice, err
  146. }
  147. func GetTodayAdviceCountTwo(stime int64, etime int64, orgid int64, is_medicine int64) (advice []*models.HisDoctorAdviceInfo, err error) {
  148. db := XTReadDB().Model(&advice).Where("status=1 and is_medicine = ?", is_medicine)
  149. if stime > 0 {
  150. db = db.Where("advice_date>=?", stime)
  151. }
  152. if etime > 0 {
  153. db = db.Where("advice_date<=?", stime)
  154. }
  155. if orgid > 0 {
  156. db = db.Where("user_org_id = ?", orgid)
  157. }
  158. err = db.Preload("Patient", "user_org_id = ? and status=1", orgid).Group("patient_id").Find(&advice).Error
  159. return advice, err
  160. }
  161. func GetPatientAdviceScheduleByPatient(patient_id int64, user_org_id int64, advice_date int64) (list []*models.XtSchedule, err error) {
  162. err = XTReadDB().Where("patient_id= ? and user_org_id = ? and schedule_date = ? and status=1", patient_id, user_org_id, advice_date).Find(&list).Error
  163. return list, err
  164. }
  165. func GetPatientByAdviceId(patient_id int64) (models.TmpPatientOne, error) {
  166. patient := models.TmpPatientOne{}
  167. err = XTReadDB().Where("id = ?", patient_id).Find(&patient).Error
  168. return patient, err
  169. }
  170. // (改)
  171. func GetTodayDrug(stime, etime, orgid, is_medicine int64, keyword string) (list []*models.TmpPatient, err error) {
  172. InitDrugidIsNil(orgid, stime, etime)
  173. //病人
  174. var tmp []*models.TmpTTT
  175. //tmp := make([]string,0)
  176. if is_medicine == 0 {
  177. if keyword != "" {
  178. keyword = "%" + keyword + "%"
  179. err = XTReadDB().Raw("select a.* from(select distinct patient_id,dispensing_time from his_doctor_advice_info where "+
  180. "status = 1 and advice_date >= ? and advice_date <= ? and user_org_id = ? and is_medicine = ? and "+
  181. "patient_id in (select id from xt_patients where user_org_id = ? and name like ? or dialysis_no like ?) and "+
  182. "drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1) "+
  183. "union "+
  184. "select distinct patient_id,dispensing_time from xt_doctor_advice where "+
  185. "status = 1 and (advice_type = 2 or advice_type = 3) and advice_date >= ? and advice_date <= ? and user_org_id = ? and is_medicine = ? and "+
  186. "patient_id in (select id from xt_patients where user_org_id = ? and name like ? or dialysis_no like ?) and "+
  187. "drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1))a order by dispensing_time desc ",
  188. stime, etime, orgid, is_medicine, orgid, keyword, keyword, orgid, stime, etime, orgid, is_medicine, orgid, keyword, keyword, orgid).Scan(&tmp).Error
  189. } else {
  190. err = XTReadDB().Raw("select a.* from(select distinct patient_id,dispensing_time from his_doctor_advice_info where "+
  191. "status = 1 and advice_date >= ? and advice_date <= ? and user_org_id = ? and is_medicine = ? and "+
  192. "drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1) "+
  193. "union "+
  194. "select distinct patient_id,dispensing_time from xt_doctor_advice where "+
  195. "status = 1 and (advice_type = 2 or advice_type = 3) and advice_date >= ? and advice_date <= ? and user_org_id = ? and is_medicine = ? and "+
  196. "drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1))a order by dispensing_time desc",
  197. stime, etime, orgid, is_medicine, orgid, stime, etime, orgid, is_medicine, orgid).Scan(&tmp).Error
  198. }
  199. if err != nil {
  200. return
  201. }
  202. } else {
  203. if keyword != "" {
  204. keyword = "%" + keyword + "%"
  205. err = XTReadDB().Raw("select a.* from(select distinct patient_id,dispensing_time from his_doctor_advice_info where "+
  206. "status = 1 and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
  207. "patient_id in (select id from xt_patients where user_org_id = ? and name like ? or dialysis_no like ?) and "+
  208. "drug_id in (select id from xt_base_drug where org_id = ? and status = 1) "+
  209. "union "+
  210. "select distinct patient_id,dispensing_time from xt_doctor_advice where "+
  211. "status = 1 and (advice_type = 2 or advice_type = 3) and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
  212. "patient_id in (select id from xt_patients where user_org_id = ? and name like ? or dialysis_no like ?) and "+
  213. "drug_id in (select id from xt_base_drug where org_id = ? and status = 1))a order by dispensing_time desc ",
  214. stime, etime, orgid, is_medicine, orgid, keyword, keyword, orgid, stime, etime, orgid, is_medicine, orgid, keyword, keyword, orgid).Scan(&tmp).Error
  215. } else {
  216. err = XTReadDB().Raw("select a.* from(select distinct patient_id,dispensing_time from his_doctor_advice_info where "+
  217. "status = 1 and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
  218. "drug_id in (select id from xt_base_drug where org_id = ? and status = 1) "+
  219. "union "+
  220. "select distinct patient_id,dispensing_time from xt_doctor_advice where "+
  221. "status = 1 and (advice_type = 2 or advice_type = 3) and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
  222. "drug_id in (select id from xt_base_drug where org_id = ? and status = 1))a order by dispensing_time desc",
  223. stime, etime, orgid, is_medicine, orgid, stime, etime, orgid, is_medicine, orgid).Scan(&tmp).Error
  224. }
  225. if err != nil {
  226. return
  227. }
  228. }
  229. tmp_s := make([]int64, 0)
  230. s_map := make(map[int64]int64)
  231. for _, v := range tmp {
  232. if _, ok := s_map[v.PatientID]; !ok {
  233. s_map[v.PatientID] = v.PatientID
  234. tmp_s = append(tmp_s, v.PatientID)
  235. }
  236. }
  237. list, err = GetManyUsers(tmp_s)
  238. return
  239. }
  240. // 查询患者(改)
  241. func GetManyUsers(tmp []int64) (list []*models.TmpPatient, err error) {
  242. for i := 0; i < len(tmp); i++ {
  243. var tt models.Patients
  244. err = XTReadDB().Model(&models.Patients{}).Where("id = ?", tmp[i]).Find(&tt).Error
  245. tmp_list := &models.TmpPatient{
  246. PatientID: tt.ID,
  247. Name: tt.Name,
  248. DialysisNo: tt.DialysisNo,
  249. }
  250. list = append(list, tmp_list)
  251. }
  252. return
  253. }
  254. // 查询患者当天时间段中的药,is_medicine:0未发,1已发(改)
  255. func GetPatientMedication(orgid, patient_id, stime, etime, is_medicine int64) (pp []*models.PharmacyContent, err error) {
  256. InitDrugidIsNil(orgid, stime, etime)
  257. var tmp []*models.HisDoctorAdviceInfoL
  258. if orgid == 10375 {
  259. err = XTReadDB().Model(&models.HisDoctorAdviceInfoL{}).Where(
  260. "status = 1 and advice_date >= ? and advice_date <= ? and user_org_id = ? and patient_id = ? and drug_id in (select id from xt_base_drug where org_id = ?)", stime, etime, orgid, patient_id, orgid).Find(&tmp).Error
  261. if err != nil {
  262. return pp, err
  263. }
  264. for _, v := range tmp {
  265. pp = append(pp, &models.PharmacyContent{
  266. ID: v.ID,
  267. Name: v.AdviceName,
  268. SingleDosage: config.ToString(v.SingleDose) + v.SingleDoseUnit,
  269. Usage: v.DeliveryWay,
  270. Frequency: v.ExecutionFrequency,
  271. Days: config.ToString(v.Day) + "天",
  272. Total: config.ToString(v.PrescribingNumber) + v.PrescribingNumberUnit,
  273. Doctor: GetAdminUserName(v.AdviceDoctor, orgid), //开立医生
  274. DataSources: "his处方",
  275. Remarks: v.Remark, //备注
  276. DrugId: v.DrugId,
  277. Price: v.Price,
  278. DrugCode: v.DrugCode,
  279. ZeroFlag: config.ToString(v.ZeroFlag),
  280. })
  281. }
  282. var tmp_advice []*models.XtDoctorAdviceL
  283. if is_medicine == 0 {
  284. err = XTReadDB().Model(&models.XtDoctorAdviceL{}).Where(
  285. "status = 1 and (advice_type = 2 or advice_type = 3) and advice_date >= ? and advice_date <= ? and user_org_id = ? and patient_id = ? and is_medicine = ? and drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1)", stime, etime, orgid, patient_id, is_medicine, orgid).Find(&tmp_advice).Error
  286. if err != nil {
  287. return pp, err
  288. }
  289. } else {
  290. err = XTReadDB().Model(&models.XtDoctorAdviceL{}).Where(
  291. "status = 1 and (advice_type = 2 or advice_type = 3) and advice_date >= ? and advice_date <= ? and user_org_id = ? and patient_id = ? and is_medicine = ? and drug_id in (select id from xt_base_drug where org_id = ? and status = 1)", stime, etime, orgid, patient_id, is_medicine, orgid).Find(&tmp_advice).Error
  292. if err != nil {
  293. return pp, err
  294. }
  295. }
  296. for _, v := range tmp_advice {
  297. pp = append(pp, &models.PharmacyContent{
  298. ID: v.ID,
  299. Name: v.AdviceName,
  300. SingleDosage: config.ToString(v.SingleDose) + v.SingleDoseUnit,
  301. Usage: v.DeliveryWay,
  302. Frequency: v.ExecutionFrequency,
  303. Days: "-",
  304. Total: config.ToString(v.PrescribingNumber) + v.PrescribingNumberUnit,
  305. Doctor: GetAdminUserName(v.AdviceDoctor, orgid),
  306. DataSources: "临时医嘱",
  307. Remarks: v.Remark,
  308. DrugId: v.DrugId,
  309. DrugCode: v.DrugCode,
  310. })
  311. }
  312. return
  313. }
  314. if orgid != 10375 {
  315. if is_medicine == 0 {
  316. err = XTReadDB().Model(&models.HisDoctorAdviceInfoL{}).Where(
  317. "status = 1 and advice_date >= ? and advice_date <= ? and user_org_id = ? and patient_id = ? and is_medicine = ? and drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1)", stime, etime, orgid, patient_id, is_medicine, orgid).Find(&tmp).Error
  318. if err != nil {
  319. return pp, err
  320. }
  321. } else {
  322. err = XTReadDB().Model(&models.HisDoctorAdviceInfoL{}).Where(
  323. "status = 1 and advice_date >= ? and advice_date <= ? and user_org_id = ? and patient_id = ? and is_medicine = ? and drug_id in (select id from xt_base_drug where org_id = ? and status = 1)", stime, etime, orgid, patient_id, is_medicine, orgid).Find(&tmp).Error
  324. if err != nil {
  325. return pp, err
  326. }
  327. }
  328. for _, v := range tmp {
  329. pp = append(pp, &models.PharmacyContent{
  330. ID: v.ID,
  331. Name: v.AdviceName,
  332. SingleDosage: config.ToString(v.SingleDose) + v.SingleDoseUnit,
  333. Usage: v.DeliveryWay,
  334. Frequency: v.ExecutionFrequency,
  335. Days: config.ToString(v.Day) + "天",
  336. Total: config.ToString(v.PrescribingNumber) + v.PrescribingNumberUnit,
  337. Doctor: GetAdminUserName(v.AdviceDoctor, orgid), //开立医生
  338. DataSources: "his处方",
  339. Remarks: v.Remark, //备注
  340. DrugId: v.DrugId,
  341. ExecutionState: v.ExecutionState,
  342. ExecutionStaff: v.ExecutionStaff,
  343. ExecutionTime: v.ExecutionTime,
  344. Price: v.Price,
  345. DrugCode: v.DrugCode,
  346. ZeroFlag: config.ToString(v.ZeroFlag),
  347. })
  348. }
  349. var tmp_advice []*models.XtDoctorAdviceL
  350. if is_medicine == 0 {
  351. err = XTReadDB().Model(&models.XtDoctorAdviceL{}).Where(
  352. "status = 1 and (advice_type = 2 or advice_type = 3) and advice_date >= ? and advice_date <= ? and user_org_id = ? and patient_id = ? and is_medicine = ? and drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1)", stime, etime, orgid, patient_id, is_medicine, orgid).Find(&tmp_advice).Error
  353. if err != nil {
  354. return pp, err
  355. }
  356. } else {
  357. err = XTReadDB().Model(&models.XtDoctorAdviceL{}).Where(
  358. "status = 1 and (advice_type = 2 or advice_type = 3) and advice_date >= ? and advice_date <= ? and user_org_id = ? and patient_id = ? and is_medicine = ? and drug_id in (select id from xt_base_drug where org_id = ? and status = 1)", stime, etime, orgid, patient_id, is_medicine, orgid).Find(&tmp_advice).Error
  359. if err != nil {
  360. return pp, err
  361. }
  362. }
  363. for _, v := range tmp_advice {
  364. pp = append(pp, &models.PharmacyContent{
  365. ID: v.ID,
  366. Name: v.AdviceName,
  367. SingleDosage: config.ToString(v.SingleDose) + v.SingleDoseUnit,
  368. Usage: v.DeliveryWay,
  369. Frequency: v.ExecutionFrequency,
  370. Days: "-",
  371. Total: config.ToString(v.PrescribingNumber) + v.PrescribingNumberUnit,
  372. Doctor: GetAdminUserName(v.AdviceDoctor, orgid),
  373. DataSources: "临时医嘱",
  374. Remarks: v.Remark,
  375. DrugId: v.DrugId,
  376. ExecutionState: v.ExecutionState,
  377. ExecutionStaff: v.ExecutionStaff,
  378. ExecutionTime: v.ExecutionTime,
  379. DrugCode: v.DrugCode,
  380. //Price: v.Price,
  381. })
  382. }
  383. return
  384. }
  385. return
  386. }
  387. // 获取创建者姓名(改)
  388. func GetAdminUserName(doctor, orgid int64) string {
  389. var tmp models.VmUserAdminRole
  390. XTReadDB().Model(&models.VmUserAdminRole{}).Where("admin_user_id = ? and org_id = ? and status = 1", doctor, orgid).Find(&tmp)
  391. return tmp.UserName
  392. }
  393. // 查询该机构的药房配置,true: 通过药房发药,false:不通过药房发药。如果没有该机构的信息则生成一条数据
  394. func GetOrgIdPharmacyConfig(orgid int64) bool {
  395. var total int
  396. var tmp_pharmacy models.PharmacyConfig
  397. XTReadDB().Model(&models.PharmacyConfig{}).Where("user_org_id = ? and status = 1", orgid).Find(&tmp_pharmacy).Count(&total)
  398. if total > 0 {
  399. //有记录
  400. if tmp_pharmacy.IsOpen == 1 {
  401. return true
  402. } else {
  403. return false
  404. }
  405. } else {
  406. //没有记录生成一条
  407. tmp := models.PharmacyConfig{
  408. UserOrgId: orgid,
  409. IsOpen: 2,
  410. Status: 1,
  411. Ctime: time.Now().Unix(),
  412. Mtime: time.Now().Unix(),
  413. }
  414. XTWriteDB().Create(&tmp)
  415. return false
  416. }
  417. }
  418. // 修改该机构的药房配置
  419. func ModifyPharmacyConfig(orgid, isopen int64) (err error) {
  420. if isopen == 1 || isopen == 2 {
  421. err = XTWriteDB().Model(&models.PharmacyConfig{}).Where("user_org_id = ? and status = 1", orgid).Updates(map[string]interface{}{
  422. "mtime": time.Now().Unix(),
  423. "is_open": isopen,
  424. }).Error
  425. } else {
  426. err = fmt.Errorf("类型解析错误")
  427. }
  428. return
  429. }
  430. // 查询该药品是否通过药房发药.0否;1是
  431. func DrugAllocation(drug_id int64) (is_pharmacy int64, err error) {
  432. tmp := models.BaseDrugLib{}
  433. err = XTReadDB().Model(&models.BaseDrugLib{}).Where("id = ?", drug_id).Find(&tmp).Error
  434. return tmp.IsPharmacy, err
  435. }
  436. // 根据id查询该药是否发药
  437. func MedicineState(id int64) (is_medicine models.HisDoctorAdviceInfoL, err error) {
  438. tmp := models.HisDoctorAdviceInfoL{}
  439. err = XTReadDB().Model(&models.HisDoctorAdviceInfoL{}).Where("id = ?", id).Find(&tmp).Error
  440. return tmp, err
  441. }
  442. // 发药明细列表(
  443. func DispensingDetailsList(stime, etime, orgid, page, limit int64, keyword string) (dislist []*models.DispensingList, total int64, err error) {
  444. var fenye []*models.Pharmary //分页用的
  445. offset := (page - 1) * limit
  446. dbone := XTReadDB().Model(&models.Pharmary{}).Where("status = 1 and user_org_id = ? and record_date >= ? and record_date <= ?", orgid, stime, etime)
  447. if keyword != "" {
  448. var tmp_id []*models.TmpID
  449. keyword = "%" + keyword + "%"
  450. XTReadDB().Raw("select id from xt_patients where name like ? and user_org_id = ?", keyword, orgid).Scan(&tmp_id)
  451. tmp_ids := make([]int64, 0)
  452. for _, v := range tmp_id {
  453. tmp_ids = append(tmp_ids, v.Id)
  454. }
  455. dbone = dbone.Where("patient_id in (?)", tmp_ids)
  456. }
  457. //查询出分页用的数据
  458. err = dbone.Count(&total).Offset(offset).Order("mtime desc").Limit(limit).Find(&fenye).Error
  459. if err != nil {
  460. return
  461. }
  462. for _, v := range fenye {
  463. tmp_doctorid, tmp_doctorname, errs := GetDoctorIds(v.PatientId, v.RecordDate, orgid)
  464. if errs != nil {
  465. err = errs
  466. return
  467. }
  468. pat, _ := GetPatientName(v.PatientId)
  469. dislist = append(dislist, &models.DispensingList{
  470. PatientID: v.PatientId,
  471. Name: pat.Name,
  472. DoctorId: tmp_doctorid,
  473. DoctorName: tmp_doctorname,
  474. RecordTime: v.RecordDate,
  475. RecordDate: fmt.Sprintf(time.Unix(v.RecordDate, 0).Format("2006-01-02 15:04:05")),
  476. })
  477. }
  478. return
  479. }
  480. // 处方详情//////////////////////
  481. func PrescriptionDetails(patient_id, record_date, orgid int64) (pre []*models.PrescripDetails, err error) {
  482. var tmp []*models.HisDoctorAdviceInfoL
  483. err = XTReadDB().Model(&models.HisDoctorAdviceInfoL{}).Where(
  484. "status = 1 and patient_id = ? and user_org_id = ? and dispensing_time = ? and is_medicine = 1 and drug_id in (select id from xt_base_drug where org_id = ? and status = 1)", patient_id, orgid, record_date, orgid).Find(&tmp).Error
  485. if err != nil {
  486. return
  487. }
  488. for _, v := range tmp {
  489. pre = append(pre, &models.PrescripDetails{
  490. Drugname: v.AdviceName,
  491. SingleDosage: config.ToString(v.SingleDose) + v.SingleDoseUnit,
  492. Usage: v.DeliveryWay,
  493. Frequency: v.ExecutionFrequency,
  494. Days: config.ToString(v.Day) + "天",
  495. Total: config.ToString(v.PrescribingNumber) + v.PrescribingNumberUnit,
  496. UnitPrice: config.ToString(v.Price) + "元",
  497. Remarks: v.Remark,
  498. })
  499. }
  500. var tmp_advice []*models.XtDoctorAdviceL
  501. err = XTReadDB().Model(&models.XtDoctorAdviceL{}).Where(
  502. "status = 1 and (advice_type = 2 or advice_type = 3) and patient_id = ? and user_org_id = ? and dispensing_time = ? and is_medicine = 1 and drug_id in (select id from xt_base_drug where org_id = ? and status = 1)", patient_id, orgid, record_date, orgid).Find(&tmp_advice).Error
  503. if err != nil {
  504. return
  505. }
  506. for _, v := range tmp_advice {
  507. pre = append(pre, &models.PrescripDetails{
  508. Drugname: v.AdviceName,
  509. SingleDosage: config.ToString(v.SingleDose) + v.SingleDoseUnit,
  510. Usage: v.DeliveryWay,
  511. Frequency: v.ExecutionFrequency,
  512. Days: "-",
  513. Total: config.ToString(v.PrescribingNumber) + v.PrescribingNumberUnit,
  514. UnitPrice: "-",
  515. Remarks: v.Remark,
  516. })
  517. }
  518. return
  519. }
  520. // 查询病人的his id
  521. func GetHisID(prescription_id, orgid int64) (id int64) {
  522. var tmp models.HisPrintPrescription
  523. XTReadDB().Model(&models.HisPrintPrescription{}).Where("id = ?", prescription_id).Find(&tmp)
  524. var fin models.HisPrescriptionInfoTwo
  525. XTReadDB().Model(&models.HisPrescriptionInfoTwo{}).Where("prescription_number = ? and user_org_id = ?", tmp.PrescriptionNumber, orgid).Find(&fin)
  526. return fin.ID
  527. }
  528. // 根据药品id获取药品信息
  529. func GetDrugNameTX(id int64, tx *gorm.DB) (tmp models.SpBaseDrug, err error) {
  530. err = tx.Model(&models.SpBaseDrug{}).Where("id = ? and status = 1", id).Find(&tmp).Error
  531. return
  532. }
  533. func GetXtManufacturer(id int64, tx *gorm.DB) (name string, err error) {
  534. var tmp models.Manufacturer
  535. err = tx.Model(&models.Manufacturer{}).Where("id = ? and status = 1", id).Find(&tmp).Error
  536. name = tmp.ManufacturerName
  537. return
  538. }
  539. // 查询药品(使用keyword)
  540. func GetManyDrugs(orgid int64, keyword string) (map[int64]models.PharmacyBaseDrug, error) {
  541. var tmp []*models.PharmacyBaseDrug
  542. tt := make(map[int64]models.PharmacyBaseDrug)
  543. err := XTReadDB().Model(&models.PharmacyBaseDrug{}).Where(" org_id = ? ", orgid).Where(" drug_name like ? ", "%"+keyword+"%").Find(&tmp).Error
  544. for _, v := range tmp {
  545. tt[v.ID] = *v
  546. }
  547. return tt, err
  548. }
  549. // 查询(
  550. func GetTodayMedicine(stime, etime, orgid, is_medicine int64, keyword string) (finlly []*models.ListOfDrugs, err error) {
  551. InitDrugidIsNil(orgid, stime, etime)
  552. fmt.Println("startime==========================", stime)
  553. var tmp []*models.TmpLLL
  554. if is_medicine == 0 {
  555. if keyword != "" {
  556. keyword = "%" + keyword + "%"
  557. err = XTReadDB().Raw("select distinct drug_id from his_doctor_advice_info where "+
  558. "status = 1 and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
  559. "drug_id in (select id from xt_base_drug where org_id = ? and drug_name like ? and is_pharmacy = 1) "+
  560. "union "+
  561. "select distinct drug_id from xt_doctor_advice where "+
  562. "status = 1 and (advice_type = 2 or advice_type = 3) and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
  563. "drug_id in (select id from xt_base_drug where org_id = ? and drug_name like ? and is_pharmacy = 1)",
  564. stime, etime, orgid, is_medicine, orgid, keyword, stime, etime, orgid, is_medicine, orgid, keyword).Scan(&tmp).Error
  565. } else {
  566. err = XTReadDB().Raw("select distinct drug_id from his_doctor_advice_info where "+
  567. "status = 1 and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
  568. "drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1) "+
  569. "union "+
  570. "select distinct drug_id from xt_doctor_advice where "+
  571. "status = 1 and (advice_type = 2 or advice_type = 3) and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
  572. "drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1) ",
  573. stime, etime, orgid, is_medicine, orgid, stime, etime, orgid, is_medicine, orgid).Scan(&tmp).Error
  574. }
  575. if err != nil {
  576. return
  577. }
  578. } else {
  579. if keyword != "" {
  580. keyword = "%" + keyword + "%"
  581. err = XTReadDB().Raw("select distinct drug_id from his_doctor_advice_info where "+
  582. "status = 1 and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
  583. "drug_id in (select id from xt_base_drug where org_id = ? and drug_name like ? and is_pharmacy = 1) "+
  584. "union "+
  585. "select distinct drug_id from xt_doctor_advice where "+
  586. "status = 1 and (advice_type = 2 or advice_type = 3) and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
  587. "drug_id in (select id from xt_base_drug where org_id = ? and drug_name like ? and is_pharmacy = 1)",
  588. stime, etime, orgid, is_medicine, orgid, keyword, stime, etime, orgid, is_medicine, orgid, keyword).Scan(&tmp).Error
  589. } else {
  590. err = XTReadDB().Raw("select distinct drug_id from his_doctor_advice_info where "+
  591. "status = 1 and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
  592. "drug_id in (select id from xt_base_drug where org_id = ? and status = 1) "+
  593. "union "+
  594. "select distinct drug_id from xt_doctor_advice where "+
  595. "status = 1 and (advice_type = 2 or advice_type = 3) and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
  596. "drug_id in (select id from xt_base_drug where org_id = ? and status = 1) ",
  597. stime, etime, orgid, is_medicine, orgid, stime, etime, orgid, is_medicine, orgid).Scan(&tmp).Error
  598. }
  599. if err != nil {
  600. return
  601. }
  602. }
  603. for _, v := range tmp {
  604. name, specifications := FindDrugSpecifications(v.DrugId)
  605. number, errs := GetInventoryQuantity(orgid, v.DrugId)
  606. if errs != nil {
  607. err = errs
  608. return
  609. }
  610. finlly = append(finlly, &models.ListOfDrugs{
  611. ID: v.DrugId,
  612. Name: name,
  613. Specifications: specifications,
  614. Stock: number,
  615. })
  616. }
  617. return
  618. }
  619. // 根据药品id获取药品规格(
  620. func FindDrugSpecifications(id int64) (name, specifications string) {
  621. var tmp models.PharmacyBaseDrug
  622. XTReadDB().Model(&models.PharmacyBaseDrug{}).Where("id = ?", id).Find(&tmp)
  623. name = tmp.DrugName
  624. specifications = config.ToString(tmp.Dose) + tmp.DoseUnit + "*" + config.ToString(tmp.MinNumber) + tmp.MinUnit + "/" + config.ToString(tmp.MaxUnit)
  625. return
  626. }
  627. // 根据药品id获取当前药品出库仓库的库存数量
  628. func GetInventoryQuantity(orgid, drugid int64) (number string, err error) {
  629. //获取药品拆零数量
  630. var phar models.PharmacyBaseDrug
  631. XTReadDB().Model(&models.PharmacyBaseDrug{}).Where("id = ?", drugid).Find(&phar)
  632. min_number := phar.MinNumber
  633. if min_number == 0 {
  634. err = fmt.Errorf("药品拆零数量不能为零!")
  635. return
  636. }
  637. storeconfig, _ := FindStorehouseConfig(orgid)
  638. var tmp []models.SpDrugWarehouseInfo
  639. XTReadDB().Model(&models.SpDrugWarehouseInfo{}).Where("org_id = ? and drug_id = ? and storehouse_id = ? and status = 1", orgid, drugid, storeconfig.DrugStorehouseOut).Find(&tmp)
  640. max, min := int64(0), int64(0)
  641. for _, v := range tmp {
  642. max += v.StockMaxNumber
  643. min += v.StockMinNumber
  644. }
  645. max += min / min_number
  646. min = min % min_number
  647. if max != 0 {
  648. number = config.ToString(max) + phar.MaxUnit
  649. }
  650. if min != 0 {
  651. number = number + config.ToString(min) + phar.MinUnit
  652. }
  653. if number == "" {
  654. number = "0"
  655. }
  656. //number = config.ToString(max)+phar.MaxUnit+config.ToString(min)+phar.MinUnit
  657. return
  658. }
  659. // 获取该药品的病人信息(
  660. func FindMedicationList(orgid, drug_id, stime, etime, is_medicine int64) (pp []*models.PatientInformation, err error) { ///////////////
  661. InitDrugidIsNil(orgid, stime, etime)
  662. var tmp []*models.HisDoctorAdviceInfoL
  663. err = XTReadDB().Model(&models.HisDoctorAdviceInfoL{}).Where(
  664. "status = 1 and advice_date >= ? and advice_date <= ? and user_org_id = ? and drug_id = ? and is_medicine = ?", stime, etime, orgid, drug_id, is_medicine).Find(&tmp).Error
  665. if err != nil {
  666. return pp, err
  667. }
  668. for _, v := range tmp {
  669. pp = append(pp, &models.PatientInformation{
  670. Id: "h" + config.ToString(v.ID),
  671. Name: FindUserName(v.PatientId),
  672. PatientId: v.PatientId,
  673. SingleDosage: config.ToString(v.SingleDose) + v.SingleDoseUnit,
  674. Usage: v.DeliveryWay,
  675. Frequency: v.ExecutionFrequency,
  676. Days: config.ToString(v.Day) + "天",
  677. Total: config.ToString(v.PrescribingNumber) + v.PrescribingNumberUnit,
  678. DataSources: "his处方",
  679. People: GetUserAdminName(v.People, orgid), //领药人!!!!!!!!!!!!!!!!!!!!!!
  680. Quantity: int64(v.PrescribingNumber),
  681. Unit: v.PrescribingNumberUnit,
  682. DrugCode: v.DrugCode,
  683. ID: v.ID,
  684. })
  685. }
  686. var tmp_advice []*models.XtDoctorAdviceL
  687. err = XTReadDB().Model(&models.XtDoctorAdviceL{}).Where(
  688. "status = 1 and (advice_type = 2 or advice_type = 3) and advice_date >= ? and advice_date <= ? and user_org_id = ? and drug_id = ? and is_medicine = ?", stime, etime, orgid, drug_id, is_medicine).Find(&tmp_advice).Error
  689. if err != nil {
  690. return pp, err
  691. }
  692. for _, v := range tmp_advice {
  693. pp = append(pp, &models.PatientInformation{
  694. Id: "x" + config.ToString(v.ID),
  695. Name: FindUserName(v.PatientId),
  696. SingleDosage: config.ToString(v.SingleDose) + v.SingleDoseUnit,
  697. Usage: v.DeliveryWay,
  698. Frequency: v.ExecutionFrequency,
  699. Days: "",
  700. Total: config.ToString(v.PrescribingNumber) + v.PrescribingNumberUnit,
  701. DataSources: "临时医嘱",
  702. People: GetUserAdminName(v.People, orgid), //领药人
  703. Quantity: int64(v.PrescribingNumber),
  704. Unit: v.PrescribingNumberUnit,
  705. DrugCode: v.DrugCode,
  706. ID: v.ID,
  707. })
  708. }
  709. return
  710. }
  711. // 患者发药按钮点击(
  712. func DispensingMedicine(orgid, patient_id, stime, etime, creater int64) (err error) {
  713. //开事务
  714. tx := XTWriteDB().Begin()
  715. defer func() {
  716. if err != nil {
  717. utils.ErrorLog("事务失败,原因为: %v", err)
  718. tx.Rollback()
  719. } else {
  720. tx.Commit()
  721. }
  722. }()
  723. time_now := time.Now().Unix()
  724. var hids []*models.TmpID
  725. var xids []*models.TmpID
  726. err = tx.Raw("select id from his_doctor_advice_info where status = 1 and advice_date >= ? and advice_date <= ? "+
  727. "and user_org_id = ? and patient_id = ? and is_medicine = 0 and drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1) ", stime, etime, orgid, patient_id, orgid).Scan(&hids).Error
  728. if err != nil {
  729. return
  730. }
  731. hid := make([]int64, 0)
  732. for _, v := range hids {
  733. hid = append(hid, v.Id)
  734. }
  735. var advice_info []*models.HisDoctorAdviceInfo
  736. err = tx.Model(&models.HisDoctorAdviceInfo{}).Where("id in (?) and status = 1", hid).Find(&advice_info).Error
  737. if err != nil {
  738. return
  739. }
  740. if orgid != 10480 {
  741. for _, v := range advice_info {
  742. tmp_bool := IsPharmacyConfig(orgid)
  743. if tmp_bool {
  744. if PettyCash(v.DrugId) {
  745. continue
  746. }
  747. if orgid != 10217 && orgid != 10188 && orgid != 9671 && orgid != 10164 && orgid != 10387 && orgid != 10375 && orgid != 10480 {
  748. ////判断药品库存是否充足
  749. kou := FenDrugInventory(v, orgid)
  750. if !kou {
  751. err = fmt.Errorf(FindDrugsName(v.DrugId) + "库存不足")
  752. return
  753. }
  754. }
  755. //扣减库存
  756. err = FenStock(orgid, creater, v)
  757. if err != nil {
  758. err = fmt.Errorf("!:%v", err)
  759. return
  760. }
  761. }
  762. }
  763. }
  764. //修改状态
  765. errs := XTWriteDB().Model(&models.HisDoctorAdviceInfoL{}).Where("id in (?)", hid).Updates(map[string]interface{}{
  766. "is_medicine": 1,
  767. "people": 0,
  768. "dispensing_time": time_now,
  769. }).Error
  770. if errs != nil {
  771. return errs
  772. }
  773. err1 := ChangeHisPrescription(hid)
  774. if err1 != nil {
  775. return err1
  776. }
  777. //针对大丰响水
  778. if orgid != 10217 && orgid != 10188 && orgid != 9671 && orgid != 10164 && orgid != 10387 && orgid != 10375 && orgid != 10480 {
  779. err = tx.Raw("select id from xt_doctor_advice where status = 1 and (advice_type = 2 or advice_type = 3) and advice_date >= ? and advice_date <= ? and "+
  780. "user_org_id = ? and patient_id = ? and is_medicine = 0 and drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1)", stime, etime, orgid, patient_id, orgid).Scan(&xids).Error
  781. if err != nil {
  782. return
  783. }
  784. xid := make([]int64, 0)
  785. for _, v := range xids {
  786. xid = append(xid, v.Id)
  787. }
  788. var advice []*models.HisDoctorAdviceInfo
  789. err = tx.Raw("select * from xt_doctor_advice where id in (?) and status = 1", xid).Scan(&advice).Error
  790. if err != nil {
  791. return
  792. }
  793. for _, v := range advice {
  794. tmp_bool := IsPharmacyConfig(orgid)
  795. if tmp_bool {
  796. if PettyCash(v.DrugId) {
  797. continue
  798. }
  799. kou := FenDrugInventory(v, orgid)
  800. if !kou {
  801. err = fmt.Errorf(FindDrugsName(v.DrugId) + "库存不足")
  802. return
  803. }
  804. //扣减库存
  805. err = FenStock(orgid, creater, v)
  806. if err != nil {
  807. err = fmt.Errorf("!:%v", err)
  808. return
  809. }
  810. }
  811. }
  812. //修改状态
  813. errs1 := XTWriteDB().Model(&models.XtDoctorAdviceL{}).Where("id in (?)", xid).Updates(map[string]interface{}{
  814. "is_medicine": 1,
  815. "people": 0,
  816. "dispensing_time": time_now,
  817. "updated_time": time.Now().Unix(),
  818. }).Error
  819. if errs1 != nil {
  820. return errs1
  821. }
  822. }
  823. //生成明细记录
  824. tmp_ph := models.Pharmary{
  825. UserOrgId: orgid,
  826. PatientId: patient_id,
  827. Ctime: time.Now().Unix(),
  828. Mtime: time.Now().Unix(),
  829. Status: 1,
  830. RecordDate: time_now,
  831. }
  832. err = tx.Create(&tmp_ph).Error
  833. return
  834. }
  835. func DispensingMedicineOne(orgid, patient_id, stime, etime, creater int64) (err error) {
  836. //开事务
  837. tx := XTWriteDB().Begin()
  838. defer func() {
  839. if err != nil {
  840. utils.ErrorLog("事务失败,原因为: %v", err)
  841. tx.Rollback()
  842. } else {
  843. tx.Commit()
  844. }
  845. }()
  846. //查询当前患者未发药的列表
  847. adviceList, err := GetHisPatientNoMedical(orgid, patient_id, stime, etime)
  848. //发药
  849. if len(adviceList) > 0 {
  850. for _, item := range adviceList {
  851. if orgid != 10480 {
  852. pharmacyConfig := IsPharmacyConfig(orgid)
  853. if pharmacyConfig == true {
  854. //扣减库存
  855. err = HisFaDrugsDelivery(orgid, creater, item)
  856. if err != nil {
  857. err = fmt.Errorf("!:%v", err)
  858. return
  859. }
  860. }
  861. }
  862. //修改发药状态
  863. err = UpdateIsMedicalHisAdvice(item.ID)
  864. if err != nil {
  865. err = fmt.Errorf("!:%v", err)
  866. return
  867. }
  868. err = UpdateHisPrescription(item.PrescriptionId)
  869. if err != nil {
  870. err = fmt.Errorf("!:%v", err)
  871. return
  872. }
  873. //查询默认仓库
  874. storeHouseConfig, _ := GetAllStoreHouseConfig(orgid)
  875. //查询默认仓库剩余多少库存
  876. var sum_count int64
  877. stockInfo, _ := GetDrugAllStockInfo(storeHouseConfig.DrugStorehouseOut, orgid, item.DrugId)
  878. for _, its := range stockInfo {
  879. baseDrug, _ := GetBaseDrugMedical(its.DrugId)
  880. if its.MaxUnit == baseDrug.MaxUnit {
  881. its.StockMaxNumber = its.StockMaxNumber * baseDrug.MinNumber
  882. }
  883. sum_count += its.StockMaxNumber + its.StockMinNumber
  884. }
  885. UpdateBaseDrugSumTwo(item.DrugId, sum_count, orgid)
  886. //扣减库存
  887. UpdateDrugStockCount(item.DrugId, item.UserOrgId, storeHouseConfig.DrugStorehouseOut, sum_count)
  888. over, _ := FindOverCount(item.DrugId, item.UserOrgId, storeHouseConfig.DrugStorehouseOut)
  889. UpdateActOut(over.ID, over.SumInCount, over.FlushCount, over.SumCancelCount)
  890. }
  891. }
  892. advice, err := GetDocAdviceList(orgid, patient_id, stime, etime)
  893. //响水不走这里
  894. if orgid != 10188 && orgid != 10480 && orgid != 10217 {
  895. if len(advice) > 0 {
  896. for _, item := range advice {
  897. err = DrugsDelivery(item.UserOrgId, item.ExecutionStaff, item)
  898. //查询默认仓库
  899. storeHouseConfig, _ := GetAllStoreHouseConfig(orgid)
  900. //查询默认仓库剩余多少库存
  901. var sum_count int64
  902. stockInfo, _ := GetDrugAllStockInfo(storeHouseConfig.DrugStorehouseOut, orgid, item.DrugId)
  903. for _, its := range stockInfo {
  904. baseDrug, _ := GetBaseDrugMedical(its.DrugId)
  905. if its.MaxUnit == baseDrug.MaxUnit {
  906. its.StockMaxNumber = its.StockMaxNumber * baseDrug.MinNumber
  907. }
  908. sum_count += its.StockMaxNumber + its.StockMinNumber
  909. }
  910. UpdateBaseDrugSumTwo(item.DrugId, sum_count, orgid)
  911. //扣减库存
  912. UpdateDrugStockCount(item.DrugId, item.UserOrgId, storeHouseConfig.DrugStorehouseOut, sum_count)
  913. over, _ := FindOverCount(item.DrugId, item.UserOrgId, storeHouseConfig.DrugStorehouseOut)
  914. UpdateActOut(over.ID, over.SumInCount, over.FlushCount, over.SumCancelCount)
  915. if err != nil {
  916. err = fmt.Errorf("!:%v", err)
  917. return
  918. }
  919. err = UpdateIsAdvice(item.ID)
  920. if err != nil {
  921. err = fmt.Errorf("!:%v", err)
  922. return
  923. }
  924. }
  925. }
  926. }
  927. //生成明细记录
  928. tmp_ph := models.Pharmary{
  929. UserOrgId: orgid,
  930. PatientId: patient_id,
  931. Ctime: time.Now().Unix(),
  932. Mtime: time.Now().Unix(),
  933. Status: 1,
  934. RecordDate: time.Now().Unix(),
  935. }
  936. err = tx.Create(&tmp_ph).Error
  937. return
  938. }
  939. func GetHisPatientNoMedical(user_org_id int64, patient_id int64, startime int64, end_time int64) (advice []*models.HisDoctorAdviceInfo, err error) {
  940. err = XTReadDB().Where("user_org_id =? and patient_id = ? and advice_date>=? and advice_date<=? and is_medicine =0 and status=1", user_org_id, patient_id, startime, end_time).Find(&advice).Error
  941. return advice, err
  942. }
  943. func GetHisPatientNoMedicalOne(user_org_id int64, patient_id int64, drug_id int64, advice_date int64) (advice []*models.HisDoctorAdviceInfo, err error) {
  944. err = XTReadDB().Where("user_org_id =? and patient_id = ? and drug_id =? and advice_date=? and is_medicine =0 and status=1", user_org_id, patient_id, drug_id, advice_date).Find(&advice).Error
  945. return advice, err
  946. }
  947. func UpdateIsMedicalHisAdvice(id int64) (err error) {
  948. adviceInfo := models.HisDoctorAdviceInfo{}
  949. err = XTWriteDB().Model(&adviceInfo).Where("id =? and status =1", id).Update(map[string]interface{}{"is_medicine": 1, "dispensing_time": time.Now().Unix()}).Error
  950. return err
  951. }
  952. func UpdateHisPrescription(id int64) (err error) {
  953. prescriptionInfo := models.HisPrescription{}
  954. err = XTWriteDB().Model(&prescriptionInfo).Where("id = ? and status=1", id).Update(map[string]interface{}{"is_medicine": 1, "mtime": time.Now().Unix()}).Error
  955. return err
  956. }
  957. func GetDocAdviceList(user_org_id int64, patient_id int64, startime int64, end_time int64) (advice []*models.DoctorAdvice, err error) {
  958. err = XTReadDB().Where("user_org_id =? and patient_id = ? and advice_date>=? and advice_date<=? and is_medicine =0 and status=1", user_org_id, patient_id, startime, end_time).Find(&advice).Error
  959. return advice, err
  960. }
  961. func UpdateIsAdvice(id int64) (err error) {
  962. err = XTWriteDB().Model(&models.DoctorAdvice{}).Where("id = ? and status =1", id).Update(map[string]interface{}{"is_medicine": 1, "dispensing_time": time.Now().Unix()}).Error
  963. return err
  964. }
  965. // 患者退药按钮点击
  966. func DrugWithdrawal(orgid, patient_id, stime, etime, creater int64) (err error) {
  967. //开事务
  968. tx := XTWriteDB().Begin()
  969. defer func() {
  970. if err != nil {
  971. utils.ErrorLog("事务失败,原因为: %v", err)
  972. tx.Rollback()
  973. } else {
  974. tx.Commit()
  975. }
  976. }()
  977. map_time := make(map[int64]int64)
  978. var hids []*models.TmpID
  979. var xids []*models.TmpID
  980. //var hid,xid []int64//查询已发药的药品
  981. err = tx.Raw("select id,dispensing_time from his_doctor_advice_info where status = 1 and advice_date >= ? and advice_date <= ? "+
  982. "and user_org_id = ? and patient_id = ? and is_medicine = 1 and drug_id in (select id from xt_base_drug where org_id = ? and status = 1)", stime, etime, orgid, patient_id, orgid).Scan(&hids).Error
  983. if err != nil {
  984. return
  985. }
  986. hid := make([]int64, 0)
  987. for _, v := range hids {
  988. hid = append(hid, v.Id)
  989. map_time[v.DispensingTime] = v.DispensingTime
  990. }
  991. //修改状态
  992. errs := XTWriteDB().Model(&models.HisDoctorAdviceInfoL{}).Where("id in (?)", hid).Updates(map[string]interface{}{
  993. "is_medicine": 0,
  994. "people": creater,
  995. "dispensing_time": 0,
  996. }).Error
  997. if errs != nil {
  998. return errs
  999. }
  1000. err1 := ChangeHisPrescriptionT(hid)
  1001. if err1 != nil {
  1002. return err1
  1003. }
  1004. var advice_info []*models.HisDoctorAdviceInfo
  1005. err = tx.Model(&models.HisDoctorAdviceInfo{}).Where("id in (?) and status = 1", hid).Find(&advice_info).Error
  1006. if err != nil {
  1007. return
  1008. }
  1009. //针对阜阳经沃
  1010. if orgid != 10480 {
  1011. for _, v := range advice_info {
  1012. //扣减库存
  1013. if !IsPharmacyDelivery(v.DrugId, orgid) {
  1014. continue
  1015. }
  1016. err = DrugAutoAddCancelInfo(v, creater)
  1017. if err != nil {
  1018. err = fmt.Errorf("!:%v", err)
  1019. return
  1020. }
  1021. //drug, _ := FindBaseDrugLibRecordSeven(orgid, v.DrugId)
  1022. //查询默认仓库
  1023. storeHouseConfig, _ := GetAllStoreHouseConfig(orgid)
  1024. //查询默认仓库剩余多少库存
  1025. var sum_count int64
  1026. stockInfo, _ := GetDrugAllStockInfo(storeHouseConfig.DrugStorehouseOut, orgid, v.DrugId)
  1027. for _, its := range stockInfo {
  1028. baseDrug, _ := GetBaseDrugMedical(its.DrugId)
  1029. if its.MaxUnit == baseDrug.MaxUnit {
  1030. its.StockMaxNumber = its.StockMaxNumber * baseDrug.MinNumber
  1031. }
  1032. sum_count += its.StockMaxNumber + its.StockMinNumber
  1033. }
  1034. UpdateBaseDrugSumTwo(v.DrugId, sum_count, orgid)
  1035. //扣减库存
  1036. UpdateDrugStockCount(v.DrugId, v.UserOrgId, storeHouseConfig.DrugStorehouseOut, sum_count)
  1037. //退药
  1038. UpdateHisPrescriptionInfo(v.PatientId, v.AdviceDate, v.UserOrgId)
  1039. //退药
  1040. UpdateHisPrescriptionInfoOne(v.PatientId, v.AdviceDate, v.UserOrgId)
  1041. }
  1042. }
  1043. err = tx.Raw("select id,dispensing_time from xt_doctor_advice where status = 1 and (advice_type = 2 or advice_type = 3) and created_time >= ? and created_time <= ? and "+
  1044. "user_org_id = ? and patient_id = ? and is_medicine = 1 and drug_id in (select id from xt_base_drug where org_id = ? and status = 1)", stime, etime, orgid, patient_id, orgid).Scan(&xids).Error
  1045. if err != nil {
  1046. return
  1047. }
  1048. xid := make([]int64, 0)
  1049. for _, v := range xids {
  1050. xid = append(xid, v.Id)
  1051. map_time[v.DispensingTime] = v.DispensingTime
  1052. }
  1053. //修改状态
  1054. errs1 := XTWriteDB().Model(&models.XtDoctorAdviceL{}).Where("id in (?)", xid).Updates(map[string]interface{}{
  1055. "is_medicine": 0,
  1056. "people": creater,
  1057. "dispensing_time": 0,
  1058. "updated_time": time.Now().Unix(),
  1059. }).Error
  1060. if errs1 != nil {
  1061. return errs1
  1062. }
  1063. var advice []*models.HisDoctorAdviceInfo
  1064. err = tx.Raw("select * from xt_doctor_advice where id in (?) and status = 1", xid).Scan(&advice).Error
  1065. if err != nil {
  1066. return
  1067. }
  1068. if orgid != 10480 {
  1069. for _, v := range advice {
  1070. //扣减库存
  1071. if !IsPharmacyDelivery(v.DrugId, orgid) {
  1072. continue
  1073. }
  1074. err = DrugAutoAddCancelInfo(v, creater)
  1075. if err != nil {
  1076. err = fmt.Errorf("!:%v", err)
  1077. return
  1078. }
  1079. //查询默认仓库
  1080. storeHouseConfig, _ := GetAllStoreHouseConfig(orgid)
  1081. //查询默认仓库剩余多少库存
  1082. var sum_count int64
  1083. stockInfo, _ := GetDrugAllStockInfo(storeHouseConfig.DrugStorehouseOut, orgid, v.DrugId)
  1084. for _, its := range stockInfo {
  1085. baseDrug, _ := GetBaseDrugMedical(its.DrugId)
  1086. if its.MaxUnit == baseDrug.MaxUnit {
  1087. its.StockMaxNumber = its.StockMaxNumber * baseDrug.MinNumber
  1088. }
  1089. sum_count += its.StockMaxNumber + its.StockMinNumber
  1090. }
  1091. UpdateBaseDrugSumTwo(v.DrugId, sum_count, orgid)
  1092. //扣减库存
  1093. UpdateDrugStockCount(v.DrugId, v.UserOrgId, storeHouseConfig.DrugStorehouseOut, sum_count)
  1094. }
  1095. }
  1096. //删除掉发药明细
  1097. for k, _ := range map_time {
  1098. err = tx.Model(&models.Pharmary{}).Where("user_org_id = ? and record_date = ? and patient_id = ? ", orgid, k, patient_id).Updates(map[string]interface{}{
  1099. "status": 0,
  1100. "mtime": time.Now().Unix(),
  1101. }).Error
  1102. if err != nil {
  1103. return
  1104. }
  1105. }
  1106. return
  1107. }
  1108. // 获取患者名称
  1109. func FindUserName(patient_id int64) (name string) {
  1110. var tmp models.GetHisName
  1111. XTReadDB().Model(&models.GetHisName{}).Where("id = ?", patient_id).Find(&tmp)
  1112. name = tmp.Name
  1113. return
  1114. }
  1115. // 获取药品名称
  1116. func FindDrugsName(drug_id int64) (name string) {
  1117. var tmp models.Drug
  1118. XTReadDB().Model(&models.Drug{}).Where("id = ?", drug_id).Find(&tmp)
  1119. name = tmp.DrugName
  1120. return
  1121. }
  1122. // 药品发药按钮点击(
  1123. func MedicineDeparture(ids string, creater, orgid int64) (err error) {
  1124. //开事务
  1125. tx := XTWriteDB().Begin()
  1126. defer func() {
  1127. if err != nil {
  1128. utils.ErrorLog("事务失败,原因为: %v", err)
  1129. tx.Rollback()
  1130. } else {
  1131. tx.Commit()
  1132. }
  1133. }()
  1134. //处理下字符串
  1135. t_ids := ""
  1136. if ids[len(ids)-1] == 44 {
  1137. t_ids = ids[:len(ids)-1]
  1138. } else {
  1139. t_ids = ids
  1140. }
  1141. time_now := time.Now().Unix()
  1142. tmp_id := strings.Split(t_ids, ",")
  1143. var parameter string //测试
  1144. patient_id := make(map[int64]int64)
  1145. for _, v := range tmp_id {
  1146. front := v[:1]
  1147. after := v[1:]
  1148. if front == "h" {
  1149. var advice_info []*models.HisDoctorAdviceInfo
  1150. err = tx.Model(&models.HisDoctorAdviceInfo{}).Where("id = ? and status = 1", after).Find(&advice_info).Error
  1151. if err != nil {
  1152. return
  1153. }
  1154. for _, v := range advice_info {
  1155. if _, ok := patient_id[v.PatientId]; !ok {
  1156. patient_id[v.PatientId] = v.PatientId
  1157. }
  1158. tmp_bool := IsPharmacyConfig(orgid)
  1159. if tmp_bool {
  1160. if PettyCash(v.DrugId) {
  1161. continue
  1162. }
  1163. kou := FenDrugInventory(v, orgid)
  1164. if !kou {
  1165. err = fmt.Errorf(FindDrugsName(v.DrugId) + "库存不足")
  1166. tmp := models.XtErrs{
  1167. OrgId: orgid,
  1168. Route: "creater:" + config.ToString(creater),
  1169. Parameter: parameter,
  1170. Text_err: err.Error(),
  1171. }
  1172. XTWriteDB().Create(&tmp)
  1173. return
  1174. } else {
  1175. tmps, _ := json.Marshal(advice_info) //
  1176. parameter = parameter + string(tmps) //
  1177. }
  1178. //扣减库存
  1179. err = FenStock(orgid, creater, v)
  1180. if err != nil {
  1181. err = fmt.Errorf("!:%v", err)
  1182. return
  1183. }
  1184. }
  1185. }
  1186. //修改状态
  1187. errs := XTWriteDB().Model(&models.HisDoctorAdviceInfoL{}).Where("id = ?", after).Updates(map[string]interface{}{
  1188. "is_medicine": 1,
  1189. "people": creater,
  1190. "dispensing_time": time_now,
  1191. }).Error
  1192. if errs != nil {
  1193. return errs
  1194. }
  1195. err1 := ChangeHisPrescriptionid(after)
  1196. if err1 != nil {
  1197. return err1
  1198. }
  1199. } else {
  1200. var advice []*models.HisDoctorAdviceInfo
  1201. err = tx.Raw("select * from xt_doctor_advice where id = ? and status = 1 and (advice_type = 2 or advice_type = 3)", after).Scan(&advice).Error
  1202. if err != nil {
  1203. return
  1204. }
  1205. for _, v := range advice {
  1206. if _, ok := patient_id[v.PatientId]; !ok {
  1207. patient_id[v.PatientId] = v.PatientId
  1208. }
  1209. tmp_bool := IsPharmacyConfig(orgid)
  1210. if tmp_bool {
  1211. codeConfig, _ := GetDrugCodeConfig(orgid)
  1212. if codeConfig.IsOpen == 1 {
  1213. if v.DrugCode == "" || len(v.DrugCode) == 0 {
  1214. err = fmt.Errorf(FindDrugsName(v.DrugId) + "药品追溯码不能为空!")
  1215. return
  1216. }
  1217. }
  1218. if PettyCash(v.DrugId) {
  1219. continue
  1220. }
  1221. kou := FenDrugInventory(v, orgid)
  1222. if !kou {
  1223. err = fmt.Errorf(FindDrugsName(v.DrugId) + "库存不足")
  1224. tmp := models.XtErrs{
  1225. OrgId: orgid,
  1226. Route: "creater:" + config.ToString(creater),
  1227. Parameter: parameter,
  1228. Text_err: err.Error(),
  1229. }
  1230. XTWriteDB().Create(&tmp)
  1231. return
  1232. } else {
  1233. tmps, _ := json.Marshal(advice) //
  1234. parameter = parameter + string(tmps) //
  1235. }
  1236. //扣减库存
  1237. err = FenStock(orgid, creater, v)
  1238. if err != nil {
  1239. err = fmt.Errorf("!:%v", err)
  1240. return
  1241. }
  1242. }
  1243. }
  1244. //修改状态
  1245. errs1 := XTWriteDB().Model(&models.XtDoctorAdviceL{}).Where("id = ?", after).Updates(map[string]interface{}{
  1246. "is_medicine": 1,
  1247. "people": creater,
  1248. "dispensing_time": time_now,
  1249. "updated_time": time.Now().Unix(),
  1250. }).Error
  1251. if errs1 != nil {
  1252. return errs1
  1253. }
  1254. }
  1255. }
  1256. for _, v := range patient_id {
  1257. //生成明细记录
  1258. tmp_ph := models.Pharmary{
  1259. UserOrgId: orgid,
  1260. PatientId: v,
  1261. Ctime: time.Now().Unix(),
  1262. Mtime: time.Now().Unix(),
  1263. Status: 1,
  1264. RecordDate: time_now,
  1265. }
  1266. err = tx.Create(&tmp_ph).Error
  1267. if err != nil {
  1268. return err
  1269. }
  1270. }
  1271. return
  1272. }
  1273. // 获取领药人姓名(
  1274. func GetUserAdminName(id, orgID int64) string {
  1275. var tmp models.XTSgjUserAdminRole
  1276. XTReadDB().Model(&models.XTSgjUserAdminRole{}).Where("admin_user_id = ? and org_id = ?", id, orgID).Find(&tmp)
  1277. return tmp.UserName
  1278. }
  1279. // 根据id查询是否已发药,true已发药,false未发药gai
  1280. func GiveTheMedicine(id int64) bool {
  1281. var xue models.PharmacyDoctorAdvice
  1282. XTReadDB().Model(&models.PharmacyDoctorAdvice{}).Where("id = ?", id).Find(&xue)
  1283. if xue.IsMedicine == 1 {
  1284. return true
  1285. }
  1286. return false
  1287. }
  1288. // 查询改组中的药品是否包含已发药的,true已发药,false未发药
  1289. func GiveGroupMedicine(orgid, groupNo int64) bool {
  1290. var total int
  1291. XTReadDB().Model(&models.DoctorAdvice{}).Where("user_org_id = ? and groupno = ? and status = 1 and is_medicine = 1", orgid, groupNo).Count(&total)
  1292. if total > 0 {
  1293. return true
  1294. }
  1295. return false
  1296. }
  1297. // 查询处方中是否包含已发药的
  1298. func GiveChuMedicine(id int64) bool {
  1299. var total int
  1300. XTReadDB().Model(&models.HisDoctorAdviceInfoL{}).Where("prescription_id = ? and status = 1 and is_medicine = 1", id).Count(&total)
  1301. if total > 0 {
  1302. return true
  1303. }
  1304. return false
  1305. }
  1306. // 根据处方id查找该处方中是否存在已发药的药品
  1307. func IsChuIssuedDrugs(prescription_id int64) bool {
  1308. var total int
  1309. XTReadDB().Model(&models.HisDoctorAdviceInfoL{}).Where("prescription_id = ? and status = 1 and is_medicine = 1", prescription_id).Count(&total)
  1310. if total > 0 {
  1311. return true
  1312. }
  1313. return false
  1314. }
  1315. // 判断该药品是否通过药房管理出库,true是,false否
  1316. // id 药品id,org_id 机构id
  1317. func IsPharmacyDelivery(id, org_id int64) bool {
  1318. //判断药品是否通过药房管理
  1319. var total01 int
  1320. XTReadDB().Model(&models.PharmacyBaseDrug{}).Where("id = ? and is_pharmacy = 1", id).Count(&total01)
  1321. //判断该机构是否通过药房管理出库
  1322. var total02 int
  1323. XTReadDB().Model(&models.PharmacyConfig{}).Where("user_org_id = ? and is_open = 1", org_id).Count(&total02)
  1324. if total01 > 0 && total02 > 0 {
  1325. return true
  1326. }
  1327. return false
  1328. }
  1329. // 判断机构是否通过药房管理出库
  1330. func IsPharmacyConfig(orgid int64) (bo bool) {
  1331. var total int
  1332. XTReadDB().Model(&models.PharmacyConfig{}).Where("user_org_id = ? and is_open = 1 and status = 1", orgid).Count(&total)
  1333. if total > 0 {
  1334. return true
  1335. }
  1336. return false
  1337. }
  1338. // 根据患者id和发药时间,获取医生的id和姓名
  1339. func GetDoctorIds(id, recordtime, orgid int64) (doctor_id int64, doctor_name string, err error) {
  1340. var tmp []*models.TmpAdviceDoctor
  1341. //var tmp []int64
  1342. err = XTReadDB().Raw("select distinct advice_doctor from his_doctor_advice_info where "+
  1343. "status = 1 and dispensing_time = ? and user_org_id = ? and is_medicine = 1 and patient_id = ? and drug_id in (select id from xt_base_drug where org_id = ? and status = 1) "+
  1344. "union "+
  1345. "select distinct advice_doctor from xt_doctor_advice where "+
  1346. "status = 1 and (advice_type = 2 or advice_type = 3) and dispensing_time = ? and user_org_id = ? and is_medicine = 1 and patient_id = ? and drug_id in (select id from xt_base_drug where org_id = ? and status = 1) ",
  1347. recordtime, orgid, id, orgid, recordtime, orgid, id, orgid).Scan(&tmp).Error
  1348. if err != nil || len(tmp) == 0 {
  1349. return
  1350. }
  1351. doctor_id = tmp[0].AdviceDoctor
  1352. doctor_name = GetUserAdminName(doctor_id, orgid)
  1353. return
  1354. }
  1355. func MapToJson(param map[string]interface{}) string {
  1356. dataType, _ := json.Marshal(param)
  1357. dataString := string(dataType)
  1358. return dataString
  1359. }
  1360. // 封装扣减库存
  1361. func FenStock(orgid, creater int64, v *models.HisDoctorAdviceInfo) (err error) {
  1362. err = HisDrugsDelivery(orgid, creater, v)
  1363. if err != nil {
  1364. err = fmt.Errorf("!:%v", err)
  1365. return
  1366. }
  1367. //查询默认仓库
  1368. storeHouseConfig, _ := GetAllStoreHouseConfig(orgid)
  1369. //查询默认仓库剩余多少库存
  1370. var sum_count int64
  1371. stockInfo, _ := GetDrugAllStockInfo(storeHouseConfig.DrugStorehouseOut, orgid, v.DrugId)
  1372. for _, its := range stockInfo {
  1373. baseDrug, _ := GetBaseDrugMedical(its.DrugId)
  1374. if its.MaxUnit == baseDrug.MaxUnit {
  1375. its.StockMaxNumber = its.StockMaxNumber * baseDrug.MinNumber
  1376. }
  1377. sum_count += its.StockMaxNumber + its.StockMinNumber
  1378. }
  1379. UpdateBaseDrugSumTwo(v.DrugId, sum_count, orgid)
  1380. //扣减库存
  1381. UpdateDrugStockCount(v.DrugId, v.UserOrgId, storeHouseConfig.DrugStorehouseOut, sum_count)
  1382. over, _ := FindOverCount(v.DrugId, v.UserOrgId, storeHouseConfig.DrugStorehouseOut)
  1383. UpdateActOut(over.ID, over.SumInCount, over.FlushCount, over.SumCancelCount)
  1384. return
  1385. }
  1386. // 封装查询药品库存是否足够
  1387. func FenDrugInventory(item *models.HisDoctorAdviceInfo, orgid int64) bool {
  1388. var total int64
  1389. var prescribing_number_total int64
  1390. houseConfig, _ := GetAllStoreHouseConfig(orgid)
  1391. ////查询该药品是否有库存
  1392. list, _ := GetDrugTotalCountTwenty(item.DrugId, item.UserOrgId, houseConfig.DrugStorehouseOut)
  1393. ////查询改药品信息
  1394. medical, _ := GetBaseDrugMedical(item.DrugId)
  1395. ////判断单位是否相等
  1396. if medical.MaxUnit == item.PrescribingNumberUnit {
  1397. prescribingNumber_temp := strconv.FormatFloat(math.Abs(item.PrescribingNumber), 'f', 0, 64)
  1398. count, _ := strconv.ParseInt(prescribingNumber_temp, 10, 64)
  1399. //转化为最小单位
  1400. total = list.Count*medical.MinNumber + list.StockMinNumber
  1401. prescribing_number_total = count * medical.MinNumber
  1402. }
  1403. if medical.MinUnit == item.PrescribingNumberUnit {
  1404. prescribingNumber_temp := strconv.FormatFloat(math.Abs(item.PrescribingNumber), 'f', 0, 64)
  1405. count, _ := strconv.ParseInt(prescribingNumber_temp, 10, 64)
  1406. total = list.Count*medical.MinNumber + list.StockMinNumber
  1407. prescribing_number_total = count
  1408. }
  1409. if prescribing_number_total <= total {
  1410. //可以扣减
  1411. return true
  1412. } else {
  1413. //不可扣减
  1414. return false
  1415. }
  1416. }
  1417. func GetAdviceIds1(ids []string, orgid, execution_staff int64, thetime time.Time) (tmp []string, err error) {
  1418. var advice []*models.DoctorAdvice
  1419. err = readDb.Model(&models.DoctorAdvice{}).Where("id IN (?) AND status = 1", ids).Find(&advice).Error
  1420. if err != nil {
  1421. return
  1422. }
  1423. for _, v := range advice {
  1424. if !IsPharmacyDelivery(v.DrugId, orgid) {
  1425. tmp = append(tmp, config.ToString(v.ID))
  1426. } else {
  1427. err = XTWriteDB().Model(&models.DoctorAdvice{}).Where("id = ? ", v.ID).Updates(map[string]interface{}{
  1428. "execution_staff": execution_staff,
  1429. "execution_time": thetime.Unix(),
  1430. "updated_time": time.Now().Unix(),
  1431. }).Error
  1432. if err != nil {
  1433. return
  1434. }
  1435. }
  1436. }
  1437. return
  1438. }
  1439. func GetAdviceIds2(ids []string, orgid, execution_staff int64, thetime time.Time) (tmp []string, err error) {
  1440. var advice []*models.HisDoctorAdviceInfoL
  1441. err = readDb.Model(&models.HisDoctorAdviceInfoL{}).Where("id IN (?) AND status = 1", ids).Find(&advice).Error
  1442. if err != nil {
  1443. return
  1444. }
  1445. for _, v := range advice {
  1446. if !IsPharmacyDelivery(v.DrugId, orgid) {
  1447. tmp = append(tmp, config.ToString(v.ID))
  1448. } else {
  1449. err = XTWriteDB().Model(&models.HisDoctorAdviceInfoL{}).Where("id = ? ", v.ID).Updates(map[string]interface{}{
  1450. "execution_staff": execution_staff,
  1451. "execution_time": thetime.Unix(),
  1452. "updated_time": time.Now().Unix(),
  1453. }).Error
  1454. if err != nil {
  1455. return
  1456. }
  1457. }
  1458. }
  1459. return
  1460. }
  1461. func GetAdviceId1(id, orgid, execution_staff int64, thetime time.Time) (bo bool, err error) {
  1462. var advice models.DoctorAdvice
  1463. err = readDb.Model(&models.DoctorAdvice{}).Where("id = ? AND status = 1", id).Find(&advice).Error
  1464. if err != nil {
  1465. return false, err
  1466. }
  1467. if IsPharmacyDelivery(advice.DrugId, orgid) {
  1468. err = XTWriteDB().Model(&models.DoctorAdvice{}).Where("id = ? ", id).Updates(map[string]interface{}{
  1469. "execution_staff": execution_staff,
  1470. "execution_time": thetime.Unix(),
  1471. "updated_time": time.Now().Unix(),
  1472. }).Error
  1473. if err != nil {
  1474. return false, err
  1475. }
  1476. return true, err
  1477. }
  1478. return false, err
  1479. }
  1480. func GetAdviceId2(id, orgid, execution_staff int64, thetime time.Time) (bo bool, err error) {
  1481. var advice models.HisDoctorAdviceInfoL
  1482. err = readDb.Model(&models.HisDoctorAdviceInfoL{}).Where("id = ? AND status = 1", id).Find(&advice).Error
  1483. if err != nil {
  1484. return false, err
  1485. }
  1486. if IsPharmacyDelivery(advice.DrugId, orgid) {
  1487. err = XTWriteDB().Model(&models.HisDoctorAdviceInfoL{}).Where("id = ? ", id).Updates(map[string]interface{}{
  1488. "execution_staff": execution_staff,
  1489. "execution_time": thetime.Unix(),
  1490. "updated_time": time.Now().Unix(),
  1491. }).Error
  1492. if err != nil {
  1493. return false, err
  1494. }
  1495. return true, err
  1496. }
  1497. return false, err
  1498. }
  1499. // 判断药品是否零用
  1500. func PettyCash(id int64) bool {
  1501. drug := models.XtBaseDrug{}
  1502. XTReadDB().Model(&drug).Where("id = ? and status = 1", id).Find(&drug)
  1503. if drug.IsUse == 1 {
  1504. return true
  1505. }
  1506. return false
  1507. }
  1508. // 初始化
  1509. func InitDrugidIsNil(orgid, stime, etime int64) {
  1510. var advice []*models.DoctorAdvice
  1511. XTReadDB().Model(&models.DoctorAdvice{}).Where("drug_id = 0 and user_org_id = ? and status = 1 and created_time >= ? and created_time <= ?", orgid, stime, etime).Find(&advice)
  1512. for _, v := range advice {
  1513. XTWriteDB().Exec("update xt_doctor_advice set drug_id = (select id from xt_base_drug where drug_name = ? and org_id = ? and status = 1 limit 1) where id = ?", v.AdviceName, v.UserOrgId, v.ID)
  1514. }
  1515. }
  1516. // 改变处方状态(发药
  1517. func ChangeHisPrescription(tmp []int64) (err error) {
  1518. var advice_info []*models.HisDoctorAdviceInfo
  1519. err = XTReadDB().Model(&models.HisDoctorAdviceInfo{}).Where("id in (?) and status = 1", tmp).Find(&advice_info).Error
  1520. if err != nil {
  1521. if err == gorm.ErrRecordNotFound {
  1522. return nil
  1523. }
  1524. return
  1525. }
  1526. tmp_id := make(map[int64]int64)
  1527. for _, v := range advice_info {
  1528. tmp_id[v.PrescriptionId] = v.PrescriptionId
  1529. }
  1530. for k, _ := range tmp_id {
  1531. err = XTWriteDB().Model(&models.HisPrintPrescription{}).Where("id = ?", k).Updates(map[string]interface{}{
  1532. "is_medicine": 1,
  1533. "mtime": time.Now().Unix(),
  1534. }).Error
  1535. if err != nil {
  1536. return
  1537. }
  1538. }
  1539. return
  1540. }
  1541. // 改变处方状态(退药
  1542. func ChangeHisPrescriptionT(tmp []int64) (err error) {
  1543. var advice_info []*models.HisDoctorAdviceInfo
  1544. err = XTReadDB().Model(&models.HisDoctorAdviceInfo{}).Where("id in (?) and status = 1", tmp).Find(&advice_info).Error
  1545. if err != nil {
  1546. if err == gorm.ErrRecordNotFound {
  1547. return nil
  1548. }
  1549. return
  1550. }
  1551. tmp_id := make(map[int64]int64)
  1552. for _, v := range advice_info {
  1553. tmp_id[v.PrescriptionId] = v.PrescriptionId
  1554. }
  1555. for k, _ := range tmp_id {
  1556. var total int
  1557. //查询退药的
  1558. XTReadDB().Model(&models.HisDoctorAdviceInfo{}).Where("prescription_id = ? and status = 1 and is_medicine = 1", k).Count(&total)
  1559. if total == 0 {
  1560. err = XTWriteDB().Model(&models.HisPrintPrescription{}).Where("id = ?", k).Updates(map[string]interface{}{
  1561. "is_medicine": 0,
  1562. "mtime": time.Now().Unix(),
  1563. }).Error
  1564. if err != nil {
  1565. return
  1566. }
  1567. }
  1568. }
  1569. return
  1570. }
  1571. // 改变处方状态
  1572. func ChangeHisPrescriptionid(id string) (err error) {
  1573. var advice models.HisDoctorAdviceInfo
  1574. err = XTReadDB().Model(&models.HisDoctorAdviceInfo{}).Where("id = ? and status = 1", id).Find(&advice).Error
  1575. if err != nil {
  1576. if err == gorm.ErrRecordNotFound {
  1577. return nil
  1578. }
  1579. return
  1580. }
  1581. err = XTWriteDB().Model(&models.HisPrintPrescription{}).Where("id = ?", advice.PrescriptionId).Updates(map[string]interface{}{
  1582. "is_medicine": 1,
  1583. "mtime": time.Now().Unix(),
  1584. }).Error
  1585. if err != nil {
  1586. return
  1587. }
  1588. return
  1589. }
  1590. // 获取药品规格
  1591. func ReplacementDrugs(orgid int64, special bool) (list []*models.ReplacementDrugs, err error) {
  1592. var g errgroup.Group
  1593. var lib []*models.BaseDrugLib
  1594. var lock sync.Mutex
  1595. if special {
  1596. err = readDb.Model(&models.BaseDrugLib{}).Where("org_id = ? and drug_status not like '%停用%' AND status = 1 and is_special_diseases = 1", orgid).Find(&lib).Error
  1597. } else {
  1598. err = readDb.Model(&models.BaseDrugLib{}).Where("org_id = ? and drug_status not like '%停用%' AND status = 1 ", orgid).Find(&lib).Error
  1599. }
  1600. if err != nil {
  1601. return
  1602. }
  1603. for _, v := range lib {
  1604. v := v
  1605. g.Go(func() error {
  1606. var tmp models.Manufacturer
  1607. err := readDb.Model(&models.Manufacturer{}).Where("id = ?", v.Manufacturer).Find(&tmp).Error
  1608. if err != nil {
  1609. return err
  1610. }
  1611. lock.Lock()
  1612. if orgid == 10206 {
  1613. list = append(list, &models.ReplacementDrugs{
  1614. Id: v.ID,
  1615. Name: v.DrugName + " " + v.DrugSpec + " " + v.Number,
  1616. })
  1617. lock.Unlock()
  1618. } else {
  1619. list = append(list, &models.ReplacementDrugs{
  1620. Id: v.ID,
  1621. Name: v.DrugName + " " + v.Dose + v.DoseUnit + "*" + config.ToString(v.MinNumber) + v.MinUnit + "/" + v.MaxUnit + " " + tmp.ManufacturerName,
  1622. })
  1623. lock.Unlock()
  1624. }
  1625. return err
  1626. })
  1627. }
  1628. if errs := g.Wait(); errs != nil {
  1629. err = errs
  1630. return
  1631. }
  1632. return
  1633. }
  1634. // 获取药品规格,不考虑特殊病
  1635. func ReplacementDrugsT(orgid int64) (list []*models.ReplacementDrugs, err error) {
  1636. var lib []*models.BaseDrugLib
  1637. err = readDb.Model(&models.BaseDrugLib{}).Where("org_id = ? AND status = 1 and drug_status not like '%停用%' ", orgid).Find(&lib).Error
  1638. if err != nil {
  1639. return
  1640. }
  1641. for _, v := range lib {
  1642. if orgid == 10206 {
  1643. list = append(list, &models.ReplacementDrugs{
  1644. Id: v.ID,
  1645. Name: v.DrugName + " " + v.DrugSpec + " " + v.Number,
  1646. })
  1647. } else {
  1648. var tmp models.Manufacturer
  1649. err = readDb.Model(&models.Manufacturer{}).Where("id = ?", v.Manufacturer).Find(&tmp).Error
  1650. if err != nil {
  1651. return
  1652. }
  1653. list = append(list, &models.ReplacementDrugs{
  1654. Id: v.ID,
  1655. Name: v.DrugName + " " + v.Dose + v.DoseUnit + "*" + config.ToString(v.MinNumber) + v.MinUnit + "/" + v.PrescribingNumberUnit + " " + tmp.ManufacturerName,
  1656. })
  1657. }
  1658. }
  1659. return
  1660. }
  1661. // 根据药品id获取药品名字
  1662. func IdToDrugName(id int64) (name string) {
  1663. var lib models.BaseDrugLib
  1664. readDb.Model(&models.BaseDrugLib{}).Where("id = ?", id).Find(&lib)
  1665. return lib.DrugName
  1666. }
  1667. // 获取项目和耗材和套餐
  1668. func ProjectConsumables3(orgid int64) (list []*models.DropDownList, err error) {
  1669. var project []*models.XtHisProject
  1670. project, err = GetHisProject(orgid)
  1671. if err != nil {
  1672. return
  1673. }
  1674. for _, v := range project {
  1675. list = append(list, &models.DropDownList{
  1676. Id: "p" + config.ToString(v.ID),
  1677. Name: v.ProjectName,
  1678. })
  1679. }
  1680. var good []*models.GoodInfo
  1681. err = XTReadDB().Model(&models.GoodInfo{}).Where("org_id = ? and status = 1", orgid).Find(&good).Error
  1682. if err != nil {
  1683. return
  1684. }
  1685. for _, v := range good {
  1686. list = append(list, &models.DropDownList{
  1687. Id: "i" + config.ToString(v.ID),
  1688. Name: v.GoodName,
  1689. })
  1690. }
  1691. var team []*models.XtHisProjectTeam
  1692. team, err = GetAllProjectTeam(orgid)
  1693. if err != nil {
  1694. return
  1695. }
  1696. for _, v := range team {
  1697. list = append(list, &models.DropDownList{
  1698. Id: "h" + config.ToString(v.ID),
  1699. Name: v.ProjectTeam,
  1700. })
  1701. }
  1702. return
  1703. }
  1704. // 获取项目和耗材
  1705. func ProjectConsumables2(orgid int64, special bool) (list []*models.DropDownList, err error) {
  1706. var project []*models.XtHisProject
  1707. if special {
  1708. err = XTReadDB().Model(&project).Where("user_org_id = ? and medical_status != 1 and status = 1 and disease_directory = 1", orgid).Find(&project).Error
  1709. } else {
  1710. err = XTReadDB().Model(&project).Where("user_org_id = ? and medical_status != 1 and status = 1", orgid).Find(&project).Error
  1711. }
  1712. if err != nil {
  1713. return
  1714. }
  1715. for _, v := range project {
  1716. list = append(list, &models.DropDownList{
  1717. Id: "p" + config.ToString(v.ID),
  1718. Name: v.ProjectName,
  1719. })
  1720. }
  1721. var good []*models.GoodInfo
  1722. if special {
  1723. err = XTReadDB().Model(&models.GoodInfo{}).Where("org_id = ? and good_status not like '%停用%' and status = 1 and is_special_diseases = 1", orgid).Find(&good).Error
  1724. } else {
  1725. err = XTReadDB().Model(&models.GoodInfo{}).Where("org_id = ? and good_status not like '%停用%' and status = 1", orgid).Find(&good).Error
  1726. }
  1727. if err != nil {
  1728. return
  1729. }
  1730. for _, v := range good {
  1731. list = append(list, &models.DropDownList{
  1732. Id: "i" + config.ToString(v.ID),
  1733. Name: v.GoodName + " " + v.SpecificationName + " " + v.GoodNumber,
  1734. })
  1735. }
  1736. return
  1737. }
  1738. // 获取项目和耗材不考虑特殊病
  1739. func ProjectConsumables2T(orgid int64) (list []*models.DropDownList, err error) {
  1740. var project []*models.XtHisProject
  1741. err = XTReadDB().Model(&project).Where("user_org_id = ? and status = 1 and medical_status != 1", orgid).Find(&project).Error
  1742. if err != nil {
  1743. return
  1744. }
  1745. for _, v := range project {
  1746. list = append(list, &models.DropDownList{
  1747. Id: "p" + config.ToString(v.ID),
  1748. Name: v.ProjectName,
  1749. })
  1750. }
  1751. var good []*models.GoodInfo
  1752. err = XTReadDB().Model(&models.GoodInfo{}).Where("org_id = ? and status = 1 and good_status != 1", orgid).Find(&good).Error
  1753. if err != nil {
  1754. return
  1755. }
  1756. for _, v := range good {
  1757. list = append(list, &models.DropDownList{
  1758. Id: "i" + config.ToString(v.ID),
  1759. Name: v.GoodName + " " + v.SpecificationName + " " + v.GoodNumber,
  1760. })
  1761. }
  1762. return
  1763. }
  1764. // 查询药品
  1765. func FindPatientDrug(orgid, patient_id, drugid, mode int64) bool {
  1766. var total int
  1767. XTReadDB().Model(&models.HisPrescriptionAdviceTemplate{}).Where("user_org_id = ? and patient_id = ? and drug_id = ? and status = 1 and "+
  1768. "prescription_id in (select id from his_prescription_info_template where status = 1 and user_org_id = ? and type = 1 and p_template_id in ("+
  1769. "select id from his_prescription_template where status= 1 and user_org_id = ? and mode = ?))", orgid, patient_id, drugid, orgid, orgid, mode).Count(&total)
  1770. if total > 0 {
  1771. return true
  1772. }
  1773. return false
  1774. }
  1775. // 查询项目
  1776. func FindPatientXiang(orgid, patient_id, drugid, mode int64) bool {
  1777. var total int
  1778. XTReadDB().Model(&models.HisPrescriptionProjectTemplate{}).Where("user_org_id = ? and patient_id = ? and project_id = ? and status = 1 and type = 2 and "+
  1779. "prescription_id in (select id from his_prescription_info_template where status = 1 and user_org_id = ? and type = 2 and p_template_id in ("+
  1780. "select id from his_prescription_template where status= 1 and user_org_id = ? and mode = ?))", orgid, patient_id, drugid, orgid, orgid, mode).Count(&total)
  1781. if total > 0 {
  1782. return true
  1783. }
  1784. return false
  1785. }
  1786. // 查询耗材
  1787. func FindPatientXiang2(orgid, patient_id, drugid, mode int64) bool {
  1788. var total int
  1789. XTReadDB().Model(&models.HisPrescriptionProjectTemplate{}).Where("user_org_id = ? and patient_id = ? and project_id = ? and status = 1 and type = 3 and "+
  1790. "prescription_id in (select id from his_prescription_info_template where status = 1 and user_org_id = ? and type = 2 and p_template_id in ("+
  1791. "select id from his_prescription_template where status= 1 and user_org_id = ? and mode = ?))", orgid, patient_id, drugid, orgid, orgid, mode).Count(&total)
  1792. if total > 0 {
  1793. return true
  1794. }
  1795. return false
  1796. }
  1797. // types处方类型,1.药品 2.项目,model透析模式
  1798. func GetHisInfoTempalteId(model, orgid, types int64) (tp []int64) {
  1799. type tmpid struct {
  1800. Id int64
  1801. }
  1802. var tmp []*tmpid
  1803. XTReadDB().Raw("select id from his_prescription_info_template where status = 1 and user_org_id = ? and type = ? and p_template_id in ("+
  1804. "select id from his_prescription_template where status = 1 and user_org_id = ? and mode = ?)", orgid, types, orgid, model).Scan(&tmp)
  1805. for _, v := range tmp {
  1806. tp = append(tp, v.Id)
  1807. }
  1808. return
  1809. }
  1810. // 替换药品处方模板
  1811. func ReplaceDrugPrescriptionTemplate(orgid, patient_id, drugid int64, ids []int64, s models.HisPrescriptionAdviceTemplate, tx *gorm.DB) (err error) {
  1812. err = tx.Model(&models.HisPrescriptionAdviceTemplate{}).Where("user_org_id = ? and patient_id = ? and drug_id = ? and "+
  1813. "status = 1 and prescription_id in (?)", orgid, patient_id, drugid, ids).Updates(map[string]interface{}{
  1814. "drug_id": s.DrugId,
  1815. "advice_name": s.AdviceName,
  1816. "single_dose": s.SingleDose,
  1817. "single_dose_unit": s.SingleDoseUnit,
  1818. "delivery_way": s.DeliveryWay,
  1819. "execution_frequency": s.ExecutionFrequency,
  1820. "day": s.Day,
  1821. "prescribing_number": s.PrescribingNumber,
  1822. "prescribing_number_unit": s.PrescribingNumberUnit,
  1823. "price": s.Price,
  1824. "remark": s.Remark,
  1825. "updated_time": time.Now().Unix(),
  1826. }).Error
  1827. return err
  1828. }
  1829. // 替换项目模板
  1830. func ReplaceProjectPrescriptionTemplate(orgid, patient_id, drugid int64, ids []int64, s models.HisPrescriptionProjectTemplate, tx *gorm.DB) (err error) {
  1831. err = tx.Model(&models.HisPrescriptionProjectTemplate{}).Where("user_org_id = ? and patient_id = ? and project_id = ? and "+
  1832. "status = 1 and prescription_id in (?)", orgid, patient_id, drugid, ids).Updates(map[string]interface{}{
  1833. "project_id": s.ProjectId,
  1834. "type": s.Type,
  1835. "frequency_type": s.FrequencyType,
  1836. "day_count": s.DayCount,
  1837. "week_day": s.WeekDay,
  1838. "price": s.Price,
  1839. "count": s.Count,
  1840. "single_dose": s.SingleDose,
  1841. "delivery_way": s.DeliveryWay,
  1842. "execution_frequency": s.ExecutionFrequency,
  1843. "remark": s.Remark,
  1844. "day": s.Day,
  1845. "unit": s.Unit,
  1846. "mtime": time.Now().Unix(),
  1847. }).Error
  1848. return err
  1849. }
  1850. // 删除项目模板
  1851. func DeleteProjectTemplate(orgid, patient_id, drugid int64, ids []int64, tx *gorm.DB) (err error) {
  1852. err = tx.Model(&models.HisPrescriptionProjectTemplate{}).Where("user_org_id = ? and patient_id = ? and project_id = ? and "+
  1853. "prescription_id in (?)", orgid, patient_id, drugid, ids).Updates(map[string]interface{}{
  1854. "status": 0,
  1855. "mtime": time.Now().Unix(),
  1856. }).Error
  1857. return err
  1858. }
  1859. // 删除处方模板
  1860. func DeletePrescriptionTemplate(orgid, patient_id, drugid int64, ids []int64, tx *gorm.DB) (err error) {
  1861. err = tx.Model(&models.HisPrescriptionAdviceTemplate{}).Where("user_org_id = ? and patient_id = ? and drug_id = ? and "+
  1862. "prescription_id in (?)", orgid, patient_id, drugid, ids).Updates(map[string]interface{}{
  1863. "status": 0,
  1864. "updated_time": time.Now().Unix(),
  1865. }).Error
  1866. return err
  1867. }
  1868. // 根据透析模式和患者id获取该患者的处方内容
  1869. func PTemplateInformation(orgid, mode_id, patient_id int64) (tmp interface{}, err error) {
  1870. //获取处方id
  1871. var tt []*models.HisPrescriptionTemplate
  1872. err = XTReadDB().Raw("select id from his_prescription_template where status = 1 and user_org_id = ? and mode = ? and patient_id = ?", orgid, mode_id, patient_id).Scan(&tt).Error
  1873. if len(tt) > 1 {
  1874. err = fmt.Errorf("数据有误")
  1875. return
  1876. }
  1877. x := make(map[int64]string, 0) //项目
  1878. h := make(map[int64]string, 0) //耗材
  1879. for _, v := range tt {
  1880. var prescriptions []*models.HisPrescriptionInfoTemplateL
  1881. prescriptions, err = GetHisPrescriptionTemplateL(v.ID, orgid)
  1882. if err != nil {
  1883. return
  1884. }
  1885. for i := 0; i < len(prescriptions); i++ {
  1886. for j := 0; j < len(prescriptions[i].HisPrescriptionProjectTemplate); j++ {
  1887. if prescriptions[i].HisPrescriptionProjectTemplate[j].Type == 2 {
  1888. //项目
  1889. if v, ok := x[prescriptions[i].HisPrescriptionProjectTemplate[j].XtHisProject.StatisticalClassification]; ok {
  1890. prescriptions[i].HisPrescriptionProjectTemplate[j].XtHisProject.Translate = v
  1891. } else {
  1892. prescriptions[i].HisPrescriptionProjectTemplate[j].XtHisProject.Translate, err = TranslateZu(prescriptions[i].HisPrescriptionProjectTemplate[j].XtHisProject.StatisticalClassification, orgid, "统计分类")
  1893. if err != nil {
  1894. return
  1895. }
  1896. x[prescriptions[i].HisPrescriptionProjectTemplate[j].XtHisProject.StatisticalClassification] = prescriptions[i].HisPrescriptionProjectTemplate[j].XtHisProject.Translate
  1897. }
  1898. }
  1899. if prescriptions[i].HisPrescriptionProjectTemplate[j].Type == 3 {
  1900. //耗材
  1901. if v, ok := h[prescriptions[i].HisPrescriptionProjectTemplate[j].GoodInfo.GoodKind]; ok {
  1902. prescriptions[i].HisPrescriptionProjectTemplate[j].GoodInfo.Translate = v
  1903. } else {
  1904. prescriptions[i].HisPrescriptionProjectTemplate[j].GoodInfo.Translate = "耗材"
  1905. h[prescriptions[i].HisPrescriptionProjectTemplate[j].GoodInfo.GoodKind] = prescriptions[i].HisPrescriptionProjectTemplate[j].GoodInfo.Translate
  1906. }
  1907. }
  1908. }
  1909. }
  1910. tmp = prescriptions
  1911. }
  1912. return
  1913. }
  1914. func DeleteOne(types, id int64) (err error) {
  1915. if types == 1 {
  1916. //药品
  1917. err = XTWriteDB().Model(&models.HisPrescriptionAdviceTemplate{}).Where("id = ?", id).Updates(map[string]interface{}{
  1918. "status": 0,
  1919. "updated_time": time.Now().Unix(),
  1920. }).Error
  1921. if err != nil {
  1922. return
  1923. }
  1924. } else if types == 2 {
  1925. //项目
  1926. err = XTWriteDB().Model(&models.HisPrescriptionProjectTemplateL{}).Where("id = ?", id).Updates(map[string]interface{}{
  1927. "status": 0,
  1928. "mtime": time.Now().Unix(),
  1929. }).Error
  1930. if err != nil {
  1931. return
  1932. }
  1933. } else {
  1934. err = fmt.Errorf("参数错误")
  1935. return
  1936. }
  1937. return
  1938. }
  1939. // 收尾工作
  1940. func Scavenger(orgid int64) (err error) {
  1941. //开事务
  1942. tx := XTWriteDB().Begin()
  1943. defer func() {
  1944. if err != nil {
  1945. utils.ErrorLog("事务失败,原因为: %v", err)
  1946. tx.Rollback()
  1947. } else {
  1948. tx.Commit()
  1949. }
  1950. }()
  1951. //查询该机构的所有模板
  1952. var tmp1 []*models.HisPrescriptionTemplate
  1953. var tmp2 []*models.HisPrescriptionInfoTemplate
  1954. deltmp1 := make([]int64, 0) //清除的数据
  1955. deltmp2 := make([]int64, 0) //清除的数据
  1956. err = tx.Model(&models.HisPrescriptionTemplate{}).Where("user_org_id = ? and status = 1", orgid).Find(&tmp1).Error
  1957. if err != nil {
  1958. return
  1959. }
  1960. for _, v := range tmp1 {
  1961. var total1 int
  1962. tx.Model(&models.HisPrescriptionInfoTemplate{}).Where("user_org_id = ? and p_template_id = ? and status = 1", orgid, v.ID).Count(&total1)
  1963. if total1 == 0 {
  1964. deltmp1 = append(deltmp1, v.ID)
  1965. }
  1966. }
  1967. err = tx.Model(&models.HisPrescriptionInfoTemplate{}).Where("user_org_id = ? and status = 1", orgid).Find(&tmp2).Error
  1968. if err != nil {
  1969. return
  1970. }
  1971. for _, v := range tmp2 {
  1972. if v.Type == 1 {
  1973. var total2 int
  1974. tx.Model(&models.HisPrescriptionAdviceTemplate{}).Where("user_org_id = ? and prescription_id = ? and status = 1", orgid, v.ID).Count(&total2)
  1975. if total2 == 0 {
  1976. deltmp2 = append(deltmp2, v.ID)
  1977. }
  1978. }
  1979. if v.Type == 2 {
  1980. var total3 int
  1981. tx.Model(&models.HisPrescriptionProjectTemplate{}).Where("user_org_id = ? and prescription_id = ? and status = 1", orgid, v.ID).Count(&total3)
  1982. if total3 == 0 {
  1983. deltmp2 = append(deltmp2, v.ID)
  1984. }
  1985. }
  1986. }
  1987. //清除1
  1988. err = tx.Model(&models.HisPrescriptionTemplate{}).Where("id in (?)", deltmp1).Updates(map[string]interface{}{
  1989. "status": 0,
  1990. "mtime": time.Now().Unix(),
  1991. }).Error
  1992. if err != nil {
  1993. return
  1994. }
  1995. //清除1
  1996. err = tx.Model(&models.HisPrescriptionInfoTemplate{}).Where("id in (?)", deltmp2).Updates(map[string]interface{}{
  1997. "status": 0,
  1998. "mtime": time.Now().Unix(),
  1999. }).Error
  2000. if err != nil {
  2001. return
  2002. }
  2003. return
  2004. }
  2005. // 分区和收费(患者发药
  2006. func PartitionAndLayout(stime, etime, orgid, shift, partition int64, flist []*models.TmpPatient) (tmp []*models.TmpPatient, err error) {
  2007. //获取排班
  2008. var sch []*models.XtScheduleTwo
  2009. ma := make(map[int64]int64)
  2010. s := "user_org_id = ? and status = 1 and schedule_date >= ? and schedule_date <= ?"
  2011. if shift != 0 {
  2012. s = s + " and schedule_type = " + config.ToString(shift)
  2013. }
  2014. if partition != 0 {
  2015. s = s + " and partition_id = " + config.ToString(partition)
  2016. }
  2017. if shift == 0 && partition == 0 {
  2018. return flist, nil
  2019. }
  2020. err = XTReadDB().Model(&models.XtScheduleTwo{}).Where(s, orgid, stime, etime).Find(&sch).Error
  2021. if err != nil {
  2022. return
  2023. }
  2024. for _, v := range sch {
  2025. ma[v.PatientId] = v.PatientId
  2026. }
  2027. for _, v := range flist {
  2028. if _, ok := ma[v.PatientID]; ok {
  2029. tmp = append(tmp, v)
  2030. }
  2031. }
  2032. return
  2033. }
  2034. // 分区和收费(药品发药
  2035. func PartitionAndLayoutDrug(deliveryway string, stime, etime, orgid, shift, partition int64, flist []*models.PatientInformation) (tmp []*models.PatientInformation, err error) {
  2036. //获取排班
  2037. var sch []*models.XtScheduleTwo
  2038. ma := make(map[int64]int64)
  2039. s := "user_org_id = ? and status = 1 and schedule_date >= ? and schedule_date <= ?"
  2040. if shift != 0 {
  2041. s = s + " and schedule_type = " + config.ToString(shift)
  2042. }
  2043. if partition != 0 {
  2044. s = s + " and partition_id = " + config.ToString(partition)
  2045. }
  2046. if shift == 0 && partition == 0 {
  2047. for _, v := range flist {
  2048. ma[v.PatientId] = v.PatientId
  2049. }
  2050. for _, v := range flist {
  2051. if _, ok := ma[v.PatientId]; ok && (v.Usage == deliveryway || deliveryway == "全部") {
  2052. tmp = append(tmp, v)
  2053. }
  2054. }
  2055. return tmp, nil
  2056. }
  2057. err = XTWriteDB().Model(&models.XtScheduleTwo{}).Where(s, orgid, stime, etime).Find(&sch).Error
  2058. if err != nil {
  2059. return
  2060. }
  2061. for _, v := range sch {
  2062. ma[v.PatientId] = v.PatientId
  2063. }
  2064. for _, v := range flist {
  2065. if _, ok := ma[v.PatientId]; ok && (v.Usage == deliveryway || deliveryway == "全部") {
  2066. tmp = append(tmp, v)
  2067. }
  2068. }
  2069. return
  2070. }
  2071. // 给药途径
  2072. func Administration(deliveryway string, orgid int64, flist []*models.ListOfDrugs) (tmp []*models.ListOfDrugs, err error) {
  2073. //查询药品
  2074. var pp []*models.PharmacyBaseDrug
  2075. s := "org_id = ? and status = 1"
  2076. if deliveryway == "全部" {
  2077. tmp = flist
  2078. return
  2079. } else {
  2080. s = s + " and delivery_way = '" + deliveryway + "'"
  2081. }
  2082. err = XTReadDB().Model(&models.PharmacyBaseDrug{}).Where(s, orgid).Find(&pp).Error
  2083. if err != nil {
  2084. return
  2085. }
  2086. ma := make(map[int64]int64)
  2087. for _, v := range pp {
  2088. ma[v.ID] = v.ID
  2089. }
  2090. for _, v := range flist {
  2091. if _, ok := ma[v.ID]; ok {
  2092. tmp = append(tmp, v)
  2093. }
  2094. }
  2095. return
  2096. }
  2097. // 计算总量
  2098. func CalculateTheTotalAmount(tmp []*models.PatientInformation, drug_id int64) (total string, err error) {
  2099. //获取药品信息
  2100. var t models.SpBaseDrug
  2101. err = XTReadDB().Model(&models.SpBaseDrug{}).Where("id = ?", drug_id).Find(&t).Error
  2102. if err != nil {
  2103. return
  2104. }
  2105. terr, maxunit, minunit := int64(0), int64(0), int64(0) //terr异常的单位数量,maxunit包装单位数量,minunit拆零单位数量
  2106. minmunber := t.MinNumber //拆零数量
  2107. terrUnit := ""
  2108. for _, v := range tmp {
  2109. switch v.Unit {
  2110. case t.MaxUnit:
  2111. maxunit = maxunit + v.Quantity
  2112. case t.MinUnit:
  2113. minunit = minunit + v.Quantity
  2114. default:
  2115. terr = terr + v.Quantity
  2116. terrUnit = v.Unit
  2117. }
  2118. }
  2119. if minunit >= minmunber {
  2120. if minmunber == 0 {
  2121. err = fmt.Errorf("拆零数量不能为零")
  2122. return
  2123. }
  2124. maxunit = maxunit + minunit/minmunber
  2125. minunit = minunit % minmunber
  2126. }
  2127. if terr > 0 {
  2128. total = total + config.ToString(terr) + terrUnit
  2129. }
  2130. if maxunit > 0 {
  2131. total = total + config.ToString(maxunit) + t.MaxUnit
  2132. }
  2133. if minunit > 0 {
  2134. total = total + config.ToString(minunit) + t.MinUnit
  2135. }
  2136. return
  2137. }
  2138. func GetAllValidDeviceZones02(orgID int64) ([]*models.DeviceZone, error) {
  2139. var zones []*models.DeviceZone
  2140. err := readDb.Model(&models.DeviceZone{}).Where("org_id = ? and status = 1", orgID).Find(&zones).Error
  2141. if err != nil {
  2142. return nil, err
  2143. }
  2144. return zones, nil
  2145. }
  2146. func FindeHisAdviceDocAdvice(orgid int64, patient_id int64, stime int64, etime int64) (advice []*models.HisDoctorAdviceInfo, err error) {
  2147. db := XTReadDB().Model(&advice).Where("status= 1 and is_medicine = 0")
  2148. if orgid > 0 {
  2149. db = db.Where("user_org_id = ?", orgid)
  2150. }
  2151. if patient_id > 0 {
  2152. db = db.Where("patient_id = ?", patient_id)
  2153. }
  2154. if stime > 0 {
  2155. db = db.Where("advice_date >=?", stime)
  2156. }
  2157. if etime > 0 {
  2158. db = db.Where("advice_date<=?", etime)
  2159. }
  2160. err = db.Find(&advice).Error
  2161. return advice, err
  2162. }
  2163. func FindeHisAdviceDocAdviceOne(orgid int64, patient_id int64, drug_id int64, advice_date int64) (advice []*models.HisDoctorAdviceInfo, err error) {
  2164. db := XTReadDB().Model(&advice).Where("status= 1 and is_medicine = 0")
  2165. if orgid > 0 {
  2166. db = db.Where("user_org_id = ?", orgid)
  2167. }
  2168. if patient_id > 0 {
  2169. db = db.Where("patient_id = ?", patient_id)
  2170. }
  2171. if drug_id > 0 {
  2172. db = db.Where("drug_id =?", drug_id)
  2173. }
  2174. if advice_date > 0 {
  2175. db = db.Where("advice_date = ?", advice_date)
  2176. }
  2177. err = db.Find(&advice).Error
  2178. return advice, err
  2179. }
  2180. func GetFlow(drug_id int64, system_time int64, org_id int64, patient_id int64) (flow []*models.DrugFlow, err error) {
  2181. err = XTWriteDB().Where("drug_id = ? and system_time =? and user_org_id = ? and status = 1 and patient_id =?", drug_id, system_time, org_id, patient_id).Find(&flow).Error
  2182. return flow, err
  2183. }
  2184. func UpdateAdviceFlow(id int64) error {
  2185. err := XTWriteDB().Model(&models.HisDoctorAdviceInfo{}).Where("id = ? and status = 1 and is_medicine =0", id).Update(map[string]interface{}{"is_medicine": 1}).Error
  2186. return err
  2187. }
  2188. func UpdateHisPrescriptionInfo(patient_id int64, advice_date int64, user_org_id int64) error {
  2189. err = XTWriteDB().Model(&models.HisDoctorAdvice{}).Where("patient_id = ? and advice_date = ? and user_org_id= ? and status=1", patient_id, advice_date, user_org_id).Updates(map[string]interface{}{"is_medicine": 0}).Error
  2190. err = XTWriteDB().Model(&models.HisPrescription{}).Where("patient_id = ? and record_date = ? and user_org_id = ? and status=1", patient_id, advice_date, user_org_id).Updates(map[string]interface{}{"is_medicine": 0}).Error
  2191. return err
  2192. }
  2193. func UpdateHisPrescriptionInfoOne(patient_id int64, advice_date int64, user_org_id int64) error {
  2194. err = XTWriteDB().Model(&models.HisPrescription{}).Where("patient_id = ? and record_date = ? and user_org_id = ? and status=1", patient_id, advice_date, user_org_id).Updates(map[string]interface{}{"is_medicine": 0}).Error
  2195. return err
  2196. }
  2197. func GetHisPatientAdviceList(user_org_id int64, patient_id int64, start_time int64, end_time int64) (list []*models.HisDoctorAdvice, err error) {
  2198. err = XTReadDB().Model(&models.HisDoctorAdvice{}).Where("patient_id=? and advice_date=? and advice_date>=? and advice_date<=? and status=1 and user_org_id = ? and is_medicine =1", patient_id, start_time, end_time, user_org_id).Find(&list).Error
  2199. return list, err
  2200. }
  2201. func GetGoodInventoryList(keyword string, org_id int64) (good []*models.GoodInfoEight, err error) {
  2202. keyword = "%" + keyword + "%"
  2203. db := XTReadDB().Where("status=1")
  2204. if len(keyword) > 0 {
  2205. db = db.Where("good_name like ? or specification_name like ?", keyword, keyword)
  2206. }
  2207. if org_id > 0 {
  2208. db = db.Where("org_id = ?", org_id)
  2209. }
  2210. err = db.Order("id desc").Find(&good).Error
  2211. return good, err
  2212. }
  2213. func GetGoodInventoryByGoodId(id int64) (info []*models.XtWarehouseInfoEight, err error) {
  2214. err = XTReadDB().Where("good_id = ? and status=1 and is_check=1", id).Order("id desc").Find(&info).Error
  2215. return info, err
  2216. }
  2217. func GetInventoryWarehouseInfo(id int64) (models.XtWarehouseInfoEight, error) {
  2218. infoEight := models.XtWarehouseInfoEight{}
  2219. err := XTReadDB().Where("id = ? and status=1", id).Find(&id).Error
  2220. return infoEight, err
  2221. }
  2222. func UpdateWarehouseInfoById(last_stock_count int64, id int64) (models.WarehousingInfo, error) {
  2223. info := models.WarehousingInfo{}
  2224. err := XTWriteDB().Model(&info).Where("id = ? and status =1", id).Updates(map[string]interface{}{"stock_count": last_stock_count}).Error
  2225. return info, err
  2226. }
  2227. func ChangeHisDrugCode(id int64, drug_code string, user_org_id int64) (models.HisDoctorAdviceInfo, error) {
  2228. adviceInfo := models.HisDoctorAdviceInfo{}
  2229. err := XTWriteDB().Model(&adviceInfo).Where("id = ? and user_org_id = ? and status =1", id, user_org_id).Updates(map[string]interface{}{"drug_code": drug_code}).Error
  2230. fmt.Println("eeeeeeeeeeeeeeeeeeeeeeeeeeeeee", err)
  2231. return adviceInfo, err
  2232. }
  2233. func ChangeAdivceDrugCode(id int64, drug_code string, user_org_id int64) (models.DoctorAdvice, error) {
  2234. adviceInfo := models.DoctorAdvice{}
  2235. err := XTWriteDB().Model(&adviceInfo).Where("id = ? and user_org_id = ? and status =1", id, user_org_id).Updates(map[string]interface{}{"drug_code": drug_code}).Error
  2236. return adviceInfo, err
  2237. }
  2238. func ChangeAdivceZeroFlag(id int64, zero_flag int64, user_org_id int64) (models.HisDoctorAdviceInfo, error) {
  2239. adviceInfo := models.HisDoctorAdviceInfo{}
  2240. err := XTWriteDB().Model(&adviceInfo).Where("id = ? and user_org_id = ? and status =1", id, user_org_id).Updates(map[string]interface{}{"zero_flag": zero_flag}).Error
  2241. return adviceInfo, err
  2242. }
  2243. func DispensingMedicineTwo(orgid, patient_id, advice_date, drug_id, creater int64) (err error) {
  2244. //开事务
  2245. tx := XTWriteDB().Begin()
  2246. defer func() {
  2247. if err != nil {
  2248. utils.ErrorLog("事务失败,原因为: %v", err)
  2249. tx.Rollback()
  2250. } else {
  2251. tx.Commit()
  2252. }
  2253. }()
  2254. //查询当前患者未发药的列表
  2255. adviceList, err := GetHisPatientNoMedicalOne(orgid, patient_id, drug_id, advice_date)
  2256. //发药
  2257. if len(adviceList) > 0 {
  2258. for _, item := range adviceList {
  2259. pharmacyConfig := IsPharmacyConfig(orgid)
  2260. if pharmacyConfig == true {
  2261. //扣减库存
  2262. err = HisFaDrugsDelivery(orgid, creater, item)
  2263. if err != nil {
  2264. err = fmt.Errorf("!:%v", err)
  2265. return
  2266. }
  2267. }
  2268. //修改发药状态
  2269. err = UpdateIsMedicalHisAdvice(item.ID)
  2270. if err != nil {
  2271. err = fmt.Errorf("!:%v", err)
  2272. return
  2273. }
  2274. err = UpdateHisPrescription(item.PrescriptionId)
  2275. if err != nil {
  2276. err = fmt.Errorf("!:%v", err)
  2277. return
  2278. }
  2279. //查询默认仓库
  2280. storeHouseConfig, _ := GetAllStoreHouseConfig(orgid)
  2281. //查询默认仓库剩余多少库存
  2282. var sum_count int64
  2283. stockInfo, _ := GetDrugAllStockInfo(storeHouseConfig.DrugStorehouseOut, orgid, item.DrugId)
  2284. for _, its := range stockInfo {
  2285. baseDrug, _ := GetBaseDrugMedical(its.DrugId)
  2286. if its.MaxUnit == baseDrug.MaxUnit {
  2287. its.StockMaxNumber = its.StockMaxNumber * baseDrug.MinNumber
  2288. }
  2289. sum_count += its.StockMaxNumber + its.StockMinNumber
  2290. }
  2291. UpdateBaseDrugSumTwo(item.DrugId, sum_count, orgid)
  2292. //扣减库存
  2293. UpdateDrugStockCount(item.DrugId, item.UserOrgId, storeHouseConfig.DrugStorehouseOut, sum_count)
  2294. over, _ := FindOverCount(item.DrugId, item.UserOrgId, storeHouseConfig.DrugStorehouseOut)
  2295. UpdateActOut(over.ID, over.SumInCount, over.FlushCount, over.SumCancelCount)
  2296. }
  2297. }
  2298. //生成明细记录
  2299. tmp_ph := models.Pharmary{
  2300. UserOrgId: orgid,
  2301. PatientId: patient_id,
  2302. Ctime: time.Now().Unix(),
  2303. Mtime: time.Now().Unix(),
  2304. Status: 1,
  2305. RecordDate: time.Now().Unix(),
  2306. }
  2307. err = tx.Create(&tmp_ph).Error
  2308. return
  2309. }