pharmacy_service.go 83KB

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