pharmacy_service.go 84KB

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