pharmacy_service.go 84KB

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