dialysis_api_controller.go 162KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395
  1. package mobile_api_controllers
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/jinzhu/gorm"
  6. "reflect"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "XT_New/enums"
  11. "XT_New/models"
  12. "XT_New/service"
  13. "XT_New/utils"
  14. "github.com/astaxie/beego"
  15. "math"
  16. "net/http"
  17. "net/url"
  18. )
  19. // type DialysisTestAPIController struct {
  20. // MobileBaseAPIController
  21. // }
  22. // [get]/m/api/test
  23. // func (this *DialysisTestAPIController) Test() {
  24. // orgID := int64(3907)
  25. // now := time.Now()
  26. // nextWeek := now.AddDate(0, 0, 7)
  27. // nextWeekMon, nextWeekSun := utils.GetMondayAndSundayOfWeekDate(&nextWeek)
  28. // nextTwoWeek := now.AddDate(0, 0, 14)
  29. // nextTwoWeekMon, nextTwoWeekSun := utils.GetMondayAndSundayOfWeekDate(&nextTwoWeek)
  30. // nextWeekSchs, getNextWeekSchErr := service.GetWeekSchedule(orgID, nextWeekMon.Unix(), nextWeekSun.Unix())
  31. // nextTwoWeekSchs, getNextTwoWeekSchErr := service.GetWeekSchedule(orgID, nextTwoWeekMon.Unix(), nextTwoWeekSun.Unix())
  32. // if getNextWeekSchErr != nil || getNextTwoWeekSchErr != nil {
  33. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  34. // return
  35. // }
  36. // exchangeErr := service.ExchangeScheduleTimeWithWeekSchedules(orgID, nextWeekSchs, nextTwoWeekSchs)
  37. // if exchangeErr != nil {
  38. // this.ErrorLog("%v", exchangeErr)
  39. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  40. // return
  41. // }
  42. // this.ServeSuccessJSON(map[string]interface{}{
  43. // // "now": now,
  44. // // "next_week": nextWeek,f
  45. // // "next_week_mon": nextWeekMon,
  46. // // "next_week_sun": nextWeekSun,
  47. // // "next_two_week_mon": nextTwoWeekMon,
  48. // // "next_two_week_sun": nextTwoWeekSun,
  49. // "next_week_schs": nextWeekSchs,
  50. // "next_two_week_schs": nextTwoWeekSchs,
  51. // })
  52. // }
  53. type DialysisAPIController struct {
  54. MobileBaseAPIAuthController
  55. }
  56. // /m/api/scheduals [get]
  57. // @param type:int
  58. // @param date:string
  59. func (this *DialysisAPIController) Scheduals() {
  60. schedualType, _ := this.GetInt64("type")
  61. schedualDate := this.GetString("date")
  62. if schedualType != 0 && schedualType != 1 && schedualType != 2 && schedualType != 3 {
  63. schedualType = 0
  64. }
  65. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  66. if parseDateErr != nil {
  67. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  68. return
  69. }
  70. adminInfo := this.GetMobileAdminUserInfo()
  71. orgID := adminInfo.Org.Id
  72. redis := service.RedisClient()
  73. defer redis.Close()
  74. // cur_date := time.Now().Format("2006-01-02")
  75. key := "scheduals_" + schedualDate + "_" + strconv.FormatInt(orgID, 10)
  76. scheduals_json_str, _ := redis.Get(key).Result()
  77. if len(scheduals_json_str) == 0 { //没有到缓存数据,从数据库中获取数据,进行缓存到redis
  78. scheduals, err := service.MobileGetDialysisScheduals(orgID, date.Unix(), schedualType)
  79. if err != nil {
  80. this.ErrorLog("获取排班信息失败:%v", err)
  81. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  82. } else {
  83. if len(scheduals) > 0 {
  84. //缓存数据
  85. scheduals_json, err := json.Marshal(scheduals)
  86. if err == nil {
  87. redis.Set(key, scheduals_json, time.Second*30)
  88. }
  89. }
  90. this.ServeSuccessJSON(map[string]interface{}{
  91. "scheduals": scheduals,
  92. })
  93. }
  94. } else { //缓存数据了数据,将redis缓存的json字符串转为map
  95. var dat []map[string]interface{}
  96. if err := json.Unmarshal([]byte(scheduals_json_str), &dat); err == nil {
  97. } else {
  98. }
  99. this.ServeSuccessJSON(map[string]interface{}{
  100. "scheduals": dat,
  101. "redis": "true",
  102. "date": schedualDate,
  103. })
  104. }
  105. }
  106. // /m/api/waiting_scheduals [get]
  107. // @param date:string
  108. func (this *DialysisAPIController) WaitingScheduals() {
  109. schedualDate := this.GetString("date")
  110. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  111. if parseDateErr != nil && len(schedualDate) != 0 {
  112. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  113. return
  114. }
  115. adminInfo := this.GetMobileAdminUserInfo()
  116. orgID := adminInfo.Org.Id
  117. redis := service.RedisClient()
  118. defer redis.Close()
  119. // cur_date := time.Now().Format("2006-01-02")
  120. key := "wait_scheduals_" + schedualDate + "_" + strconv.FormatInt(orgID, 10)
  121. wait_scheduals, _ := redis.Get(key).Result()
  122. if len(wait_scheduals) == 0 { //没有到缓存数据,从数据库中获取数据,进行缓存到redis
  123. scheduals, err := service.MobileGetWaitingScheduals(orgID, date.Unix())
  124. if err != nil {
  125. this.ErrorLog("获取排班信息失败:%v", err)
  126. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  127. } else {
  128. returnScheduals := make([]*service.MDialysisScheduleVM, 0, len(scheduals))
  129. for _, s := range scheduals {
  130. returnScheduals = append(returnScheduals, s)
  131. }
  132. if len(returnScheduals) > 0 {
  133. //缓存数据
  134. wait_scheduals_json, err := json.Marshal(scheduals)
  135. if err == nil {
  136. redis.Set(key, wait_scheduals_json, time.Second*30)
  137. }
  138. }
  139. this.ServeSuccessJSON(map[string]interface{}{
  140. "scheduals": scheduals,
  141. })
  142. }
  143. } else { //缓存数据了数据,将redis缓存的json字符串转为map
  144. var dat []map[string]interface{}
  145. if err := json.Unmarshal([]byte(wait_scheduals), &dat); err == nil {
  146. } else {
  147. }
  148. this.ServeSuccessJSON(map[string]interface{}{
  149. "scheduals": dat,
  150. "redis": "true",
  151. "date": schedualDate,
  152. })
  153. }
  154. }
  155. //else{
  156. // fmt.Println("33333333")
  157. //
  158. // scheduals, err := service.MobileGetWaitingScheduals(orgID, date.Unix())
  159. // if err != nil {
  160. // this.ErrorLog("获取排班信息失败:%v", err)
  161. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  162. // } else {
  163. // returnScheduals := make([]*service.MDialysisScheduleVM, 0, len(scheduals))
  164. // for _, s := range scheduals {
  165. //
  166. // returnScheduals = append(returnScheduals, s)
  167. // }
  168. //
  169. // this.ServeSuccessJSON(map[string]interface{}{
  170. // "scheduals": returnScheduals,
  171. // })
  172. // }
  173. //
  174. // }
  175. //if err == nil{
  176. //
  177. //
  178. //
  179. //
  180. //
  181. //}else{
  182. //}
  183. // /m/api/dialysis/record [get]
  184. // @param patient_id:int
  185. // @param date:string (yyyy-MM-dd)
  186. func (this *DialysisAPIController) DialysisRecord() {
  187. patientID, _ := this.GetInt64("patient_id")
  188. recordDateStr := this.GetString("date")
  189. if patientID <= 0 {
  190. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  191. return
  192. }
  193. if len(recordDateStr) == 0 {
  194. recordDateStr = time.Now().Format("2006-01-02")
  195. }
  196. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  197. if parseDateErr != nil {
  198. this.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  199. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  200. return
  201. }
  202. adminInfo := this.GetMobileAdminUserInfo()
  203. patient, getPatientErr := service.MobileGetPatientDetail(adminInfo.Org.Id, patientID)
  204. if getPatientErr != nil {
  205. this.ErrorLog("获取患者信息失败:%v", getPatientErr)
  206. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  207. return
  208. } else if patient == nil {
  209. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  210. return
  211. }
  212. schedual, getSchedualErr := service.MobileGetSchedualDetail(adminInfo.Org.Id, patientID, date.Unix())
  213. if getSchedualErr != nil {
  214. this.ErrorLog("获取患者排班信息失败:%v", getSchedualErr)
  215. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  216. return
  217. }
  218. receiverTreatmentAccess, getRTARErr := service.MobileGetReceiverTreatmentAccessRecord(adminInfo.Org.Id, patientID, date.Unix())
  219. if getRTARErr != nil {
  220. this.ErrorLog("获取接诊评估失败:%v", getRTARErr)
  221. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  222. return
  223. }
  224. predialysisEvaluation, getPEErr := service.MobileGetPredialysisEvaluation(adminInfo.Org.Id, patientID, date.Unix())
  225. if getPEErr != nil {
  226. this.ErrorLog("获取透前评估失败:%v", getPEErr)
  227. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  228. return
  229. }
  230. lastPredialysisEvaluation, getLPEErr := service.MobileGetLastTimePredialysisEvaluation(adminInfo.Org.Id, patientID, date.Unix())
  231. if getLPEErr != nil {
  232. this.ErrorLog("获取上一次透前评估失败:%v", getLPEErr)
  233. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  234. return
  235. }
  236. doctorAdvices, getDoctorAdvicesErr := service.MobileGetDoctorAdvicesByGroups(adminInfo.Org.Id, patientID, date.Unix())
  237. if getDoctorAdvicesErr != nil {
  238. this.ErrorLog("获取临时医嘱失败:%v", getDoctorAdvicesErr)
  239. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  240. return
  241. }
  242. dialysisOrder, getDialysisOrderErr := service.MobileGetSchedualDialysisRecord(adminInfo.Org.Id, patientID, date.Unix())
  243. if getDialysisOrderErr != nil {
  244. this.ErrorLog("获取透析记录失败:%v", getDialysisOrderErr)
  245. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  246. return
  247. }
  248. doubleCheck, getDoubleCheckErr := service.MobileGetDoubleCheck(adminInfo.Org.Id, patientID, date.Unix())
  249. if getDoubleCheckErr != nil {
  250. this.ErrorLog("获取双人核对记录失败:%v", getDoubleCheckErr)
  251. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  252. return
  253. }
  254. monitorRecords, getMonitorRecordsErr := service.MobileGetMonitorRecords(adminInfo.Org.Id, patientID, date.Unix())
  255. if getMonitorRecordsErr != nil {
  256. this.ErrorLog("获取透析监测记录失败:%v", getMonitorRecordsErr)
  257. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  258. return
  259. }
  260. var lastMonitorRecord *models.MonitoringRecord
  261. lastMonitorRecord, getLastErr := service.MobileGetLastMonitorRecord(adminInfo.Org.Id, patientID, date.Unix())
  262. if getLastErr != nil {
  263. this.ErrorLog("获取上一次透析的监测记录失败:%v", getLastErr)
  264. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  265. return
  266. }
  267. assessmentAfterDislysis, getAADErr := service.MobileGetAssessmentAfterDislysis(adminInfo.Org.Id, patientID, date.Unix())
  268. if getAADErr != nil {
  269. this.ErrorLog("获取透后评估失败:%v", getAADErr)
  270. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  271. return
  272. }
  273. lastAssessmentAfterDislysis, getLAADErr := service.MobileGetLastTimeAssessmentAfterDislysis(adminInfo.Org.Id, patientID, date.Unix())
  274. if getLAADErr != nil {
  275. this.ErrorLog("获取上一次透后评估失败:%v", getLAADErr)
  276. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  277. return
  278. }
  279. treatmentSummary, getTreatmentSummaryErr := service.MobileGetTreatmentSummary(adminInfo.Org.Id, patientID, date.Unix())
  280. if getTreatmentSummaryErr != nil {
  281. this.ErrorLog("获取治疗小结失败:%v", getTreatmentSummaryErr)
  282. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  283. return
  284. }
  285. dialysisPrescribe, _ := service.MobileGetDialysisPrescribeByModeId(adminInfo.Org.Id, patientID, date.Unix(), schedual.ModeId)
  286. //if getDialysisPrescribeErr != nil {
  287. // this.ErrorLog("获取透析处方失败:%v", getDialysisPrescribeErr)
  288. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  289. // return
  290. //}
  291. dialysisSolution, _ := service.MobileGetDialysisSolutionByModeId(adminInfo.Org.Id, patientID, schedual.ModeId)
  292. //if getDialysisSolutionErr != nil {
  293. // this.ErrorLog("获取透析方案失败:%v", getDialysisSolutionErr)
  294. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  295. // return
  296. //}
  297. lastDialysisPrescribe, _ := service.MobileGetLastDialysisPrescribeByModeId(adminInfo.Org.Id, patientID, schedual.ModeId)
  298. //fmt.Println("上次透析处方",lastDialysisPrescribe.DialyzerPerfusionApparatus)
  299. //if getDialysisPrescribeErr != nil {
  300. // this.ErrorLog("获取透析处方失败:%v", getDialysisPrescribeErr)
  301. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  302. // return
  303. //}
  304. //获取系统透析处方模版
  305. systemDialysisPrescribe, _ := service.MobileGetSystemDialysisPrescribeByModeId(adminInfo.Org.Id, schedual.ModeId)
  306. //if getSystemDialysisPrescribeErr != nil {
  307. // this.ErrorLog("获取系统透析处方失败:%v", getSystemDialysisPrescribeErr)
  308. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  309. // return
  310. //}
  311. //dialysisSolution, getDialysisSolutionErr := service.MobileGetDialysisSolution(adminInfo.Org.Id, patientID)
  312. //operators, _ := service.GetAllAdminUserES(adminInfo.Org.Id, adminInfo.App.Id)
  313. _, is_open_config := service.FindXTHisRecordByOrgId(adminInfo.Org.Id)
  314. stockType, _ := service.GetStockType(adminInfo.Org.Id)
  315. prepare, _ := service.GetDialyStockOut(adminInfo.Org.Id, date.Unix(), patientID)
  316. var his_advices []*models.HisDoctorAdviceInfo
  317. if is_open_config.IsOpen == 1 {
  318. his_advices, _ = service.GetAllHisDoctorAdvice(adminInfo.Org.Id, patientID, date.Unix())
  319. }
  320. if getLPEErr != nil {
  321. this.ErrorLog("获取上一次透前评估失败:%v", getLPEErr)
  322. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  323. return
  324. }
  325. lastDryWeightDislysis, getDryErr := service.MobileGetLastDryWeight(adminInfo.Org.Id, patientID)
  326. if getDryErr != nil {
  327. this.ErrorLog("获取最后一条干体重失败:%v", getDryErr)
  328. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  329. return
  330. }
  331. //headNurses, _ := service.GetAllSpecialPermissionAdminUsersWithoutStatus(adminInfo.Org.Id, adminInfo.App.Id, models.SpecialPermissionTypeHeadNurse)
  332. _, gobalConfig := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  333. //goodTypes, _ := service.FindAllGoodTypeByType(1) //查出所有库存配置的系统类型
  334. //goodInfos, _ := service.FindAllGoodInfo(adminInfo.Org.Id) //查出所有库存配置的系统类型
  335. operators, _ := service.GetAllStarfEs(adminInfo.Org.Id)
  336. //consumables, _ := service.FindConsumablesByDate(adminInfo.Org.Id, patientID, date.Unix())
  337. //lastConsumables, _ := service.FindConsumablesByDate(adminInfo.Org.Id, patientID, date.Unix())
  338. returnData := map[string]interface{}{
  339. "patient": patient,
  340. "schedual": schedual,
  341. "prescription": dialysisPrescribe,
  342. "solution": dialysisSolution,
  343. "last_prescription": lastDialysisPrescribe,
  344. "receiver_treatment_access": receiverTreatmentAccess,
  345. "predialysis_evaluation": predialysisEvaluation,
  346. "doctor_advices": doctorAdvices,
  347. "double_check": doubleCheck,
  348. "assessment_after_dislysis": assessmentAfterDislysis,
  349. "treatment_summary": treatmentSummary,
  350. "monitor_records": monitorRecords,
  351. "dialysis_order": dialysisOrder,
  352. "operators": operators,
  353. "last_predialysis_evaluation": lastPredialysisEvaluation,
  354. "last_assessment_after_dislysis": lastAssessmentAfterDislysis,
  355. "last_monitor_record": lastMonitorRecord,
  356. "config": gobalConfig,
  357. "dry_weight": lastDryWeightDislysis,
  358. "system_prescription": systemDialysisPrescribe,
  359. "his_advices": his_advices,
  360. "is_open_config": is_open_config,
  361. "stockType": stockType,
  362. "prepare": prepare,
  363. }
  364. this.ServeSuccessJSON(returnData)
  365. }
  366. func (c *DialysisAPIController) GetDialysisGlobalConfig() {
  367. adminInfo := c.GetMobileAdminUserInfo()
  368. adminUsers, _ := service.GetAllAdminUsers(adminInfo.Org.Id, adminInfo.App.Id)
  369. devices, _ := service.GetValidDevicesBy(adminInfo.Org.Id, 0, 0)
  370. device_numbers, _ := service.GetAllValidDeviceNumbers(adminInfo.Org.Id)
  371. returnData := map[string]interface{}{
  372. "admin_users": adminUsers,
  373. "devices": devices,
  374. "device_numbers": device_numbers,
  375. }
  376. c.ServeSuccessJSON(returnData)
  377. }
  378. func (c *DialysisAPIController) PostAtreatmentInfo() {
  379. id, _ := c.GetInt64("patient", 0)
  380. recordDateStr := c.GetString("record_date")
  381. propagandaAndEducationContent := c.GetString("propagandaAndEducationContent")
  382. summaryContent := c.GetString("summaryContent")
  383. changeMedicalNurseId, _ := c.GetInt64("changeMedicalNurse", 0)
  384. treatNurseId, _ := c.GetInt64("treatNurse", 0)
  385. checkStaffId, _ := c.GetInt64("checkStaff", 0)
  386. deboardNurseId, _ := c.GetInt64("deboardNurse", 0)
  387. treatDoctor, _ := c.GetInt64("treatDoctor", 0)
  388. nursingRecord := c.GetString("nursing_record")
  389. fmt.Println("护理记录", nursingRecord)
  390. specialRecord := c.GetString("special_record")
  391. fmt.Println("特殊记录", specialRecord)
  392. adminUserInfo := c.GetMobileAdminUserInfo()
  393. changeMedicalNurseId = adminUserInfo.AdminUser.Id
  394. checkStaffId = adminUserInfo.AdminUser.Id
  395. deboardNurseId = adminUserInfo.AdminUser.Id
  396. treatDoctor = adminUserInfo.AdminUser.Id
  397. if id <= 0 {
  398. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  399. return
  400. }
  401. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  402. if patient.ID == 0 {
  403. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  404. return
  405. }
  406. if len(recordDateStr) == 0 {
  407. recordDateStr = time.Now().Format("2006-01-02")
  408. }
  409. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  410. if parseDateErr != nil {
  411. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  412. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  413. return
  414. }
  415. //now := time.Now()
  416. //year, month, day := now.Date()
  417. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  418. //todayTimeStamp := today_time.Unix()
  419. summary := models.TreatmentSummary{
  420. UserOrgId: adminUserInfo.Org.Id,
  421. PatientId: id,
  422. AssessmentDate: recordDate.Unix(),
  423. Mission: propagandaAndEducationContent,
  424. DialysisSummary: summaryContent,
  425. SjNurse: changeMedicalNurseId,
  426. ZlNurse: treatNurseId,
  427. HdNurse: checkStaffId,
  428. XjNurse: deboardNurseId,
  429. ZlDoctor: treatDoctor,
  430. CreatedTime: time.Now().Unix(),
  431. Status: 1,
  432. NursingRecord: nursingRecord,
  433. SpecialRecord: specialRecord,
  434. }
  435. _, treatmentSummary := service.FindTreatmentSummaryByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  436. if treatmentSummary.ID == 0 { //新增
  437. summary.Creater = adminUserInfo.AdminUser.Id
  438. service.AddSigleSummaryRecord(&summary)
  439. c.ServeSuccessJSON(map[string]interface{}{
  440. "summary": summary,
  441. })
  442. } else { //修改
  443. //if treatmentSummary.Creater != adminUserInfo.AdminUser.Id {
  444. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  445. // if getPermissionErr != nil {
  446. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  447. // return
  448. // } else if headNursePermission == nil {
  449. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  450. // return
  451. // }
  452. //}
  453. summary.Creater = treatmentSummary.Creater
  454. summary.CreatedTime = treatmentSummary.CreatedTime
  455. summary.Modifier = adminUserInfo.AdminUser.Id
  456. summary.ID = treatmentSummary.ID
  457. service.UpdateSummeRecord(&summary)
  458. c.ServeSuccessJSON(map[string]interface{}{
  459. "summary": summary,
  460. })
  461. }
  462. }
  463. func (c *DialysisAPIController) PostDoubleCheck() {
  464. id, _ := c.GetInt64("patient", 0)
  465. recordDateStr := c.GetString("record_date")
  466. checkTimeStr := c.GetString("check_time")
  467. firstCheckTimeStr := c.GetString("first_check_time")
  468. creater, _ := c.GetInt64("creater", 0)
  469. modifier, _ := c.GetInt64("modifier", 0)
  470. dialysis_item_check, _ := c.GetInt64("dialysis_item_check", 0)
  471. dialysis_parameter_check, _ := c.GetInt64("dialysis_parameter_check", 0)
  472. vascular_access_verification, _ := c.GetInt64("vascular_access_verification", 0)
  473. pipeline_connection_check, _ := c.GetInt64("pipeline_connection_check", 0)
  474. dialysis_item_desc := c.GetString("dialysis_item_desc")
  475. dialysis_parameter_desc := c.GetString("dialysis_parameter_desc")
  476. vascular_access_desc := c.GetString("vascular_access_desc")
  477. pipeline_connection_desc := c.GetString("pipeline_connection_desc")
  478. collator, _ := c.GetInt64("collator", 0)
  479. if id <= 0 {
  480. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  481. return
  482. }
  483. adminUserInfo := c.GetMobileAdminUserInfo()
  484. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  485. if patient.ID == 0 {
  486. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  487. return
  488. }
  489. if len(recordDateStr) == 0 {
  490. recordDateStr = time.Now().Format("2006-01-02")
  491. }
  492. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  493. if parseDateErr != nil {
  494. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  495. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  496. return
  497. }
  498. var checkDate int64
  499. if len(checkTimeStr) == 0 {
  500. checkDate = 0
  501. } else {
  502. checkDateUnix, _ := utils.ParseTimeStringToTime("2006-01-02 15:04:05", checkTimeStr)
  503. checkDate = checkDateUnix.Unix()
  504. }
  505. var firstCheckDate int64
  506. if len(firstCheckTimeStr) == 0 {
  507. firstCheckDate = 0
  508. } else {
  509. firstCheckDateUnix, _ := utils.ParseTimeStringToTime("2006-01-02 15:04:05", firstCheckTimeStr)
  510. firstCheckDate = firstCheckDateUnix.Unix()
  511. }
  512. //now := time.Now()
  513. //year, month, day := now.Date()
  514. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  515. //todayTimeStamp := today_time.Unix()
  516. doubleCheck := models.DoubleCheck{
  517. UserOrgId: adminUserInfo.Org.Id,
  518. PatientId: id,
  519. DialysisItemCheck: dialysis_item_check,
  520. DialysisParameterCheck: dialysis_parameter_check,
  521. VascularAccessVerification: vascular_access_verification,
  522. PipelineConnectionCheck: pipeline_connection_check,
  523. DialysisItemDesc: dialysis_item_desc,
  524. DialysisParameterDesc: dialysis_parameter_desc,
  525. VascularAccessDesc: vascular_access_desc,
  526. PipelineConnectionDesc: pipeline_connection_desc,
  527. Collator: collator,
  528. Status: 1,
  529. CreatedTime: time.Now().Unix(),
  530. CheckDate: recordDate.Unix(),
  531. UpdatedTime: time.Now().Unix(),
  532. }
  533. _, check := service.FindDoubleCheckByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  534. if check.ID == 0 { //新增
  535. doubleCheck.FirstCheckTime = firstCheckDate
  536. doubleCheck.CheckTime = checkDate
  537. doubleCheck.Creater = creater
  538. doubleCheck.Modifier = modifier
  539. err := service.AddSigleDoubleCheck(&doubleCheck)
  540. if err == nil {
  541. c.ServeSuccessJSON(map[string]interface{}{
  542. "doubleCheck": &doubleCheck,
  543. })
  544. }
  545. } else { //修改
  546. doubleCheck.FirstCheckTime = firstCheckDate
  547. doubleCheck.CheckTime = checkDate
  548. doubleCheck.Creater = creater
  549. doubleCheck.Modifier = modifier
  550. doubleCheck.CreatedTime = check.CreatedTime
  551. doubleCheck.ID = check.ID
  552. err := service.UpdateDoubleCheck(&doubleCheck)
  553. if err == nil {
  554. c.ServeSuccessJSON(map[string]interface{}{
  555. "doubleCheck": &doubleCheck,
  556. })
  557. }
  558. }
  559. }
  560. func (c *DialysisAPIController) PostAcceptsAssessment() {
  561. id, _ := c.GetInt64("patient", 0)
  562. recordDateStr := c.GetString("record_date")
  563. way, _ := c.GetInt64("way", 0)
  564. consciousness, _ := c.GetInt64("consciousness", 0)
  565. appetite, _ := c.GetInt64("appetite", 0)
  566. condition, _ := c.GetInt64("condition", 0)
  567. posture, _ := c.GetInt64("posture")
  568. sick_condition, _ := c.GetInt64("sick_condition", 0)
  569. danger_level, _ := c.GetInt64("danger_level", 0)
  570. intake, _ := c.GetInt64("intake", 0)
  571. nutrition, _ := c.GetInt64("nutrition", 0)
  572. psychological_assessment, _ := c.GetInt64("psychological_assessment", 0)
  573. psychological_assessment_other := c.GetString("psychological_assessment_other")
  574. score := c.GetString("score")
  575. sick_condition_other := c.GetString("sick_condition_other")
  576. //precaution, _ := c.GetInt64("precaution", 0)
  577. precaution := c.GetString("precaution")
  578. precaution_other := c.GetString("precaution_other")
  579. psychological_other := c.GetString("psychological_other")
  580. admission_number := c.GetString("admission_number")
  581. if id <= 0 {
  582. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  583. return
  584. }
  585. adminUserInfo := c.GetMobileAdminUserInfo()
  586. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  587. if patient.ID == 0 {
  588. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  589. return
  590. }
  591. //now := time.Now()
  592. //year, month, day := now.Date()
  593. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  594. //todayTimeStamp := today_time.Unix()
  595. if len(recordDateStr) == 0 {
  596. recordDateStr = time.Now().Format("2006-01-02")
  597. }
  598. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  599. if parseDateErr != nil {
  600. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  601. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  602. return
  603. }
  604. _, receiveTreatment := service.FindReceiveTreatmentAssesByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  605. receiveTreatmentAsses := models.ReceiveTreatmentAsses{
  606. UserOrgId: adminUserInfo.Org.Id,
  607. PatientId: id,
  608. RecordDate: recordDate.Unix(),
  609. Way: way,
  610. Consciousness: consciousness,
  611. Appetite: appetite,
  612. Condition: condition,
  613. SickCondition: sick_condition,
  614. DangerLevel: danger_level,
  615. Intake: intake,
  616. Nutrition: nutrition,
  617. PsychologicalAssessment: psychological_assessment,
  618. PsychologicalAssessmentOther: psychological_assessment_other,
  619. SickConditionOther: sick_condition_other,
  620. Posture: posture,
  621. CreatedTime: time.Now().Unix(),
  622. UpdateTime: time.Now().Unix(),
  623. Status: 1,
  624. Score: score,
  625. Precaution: precaution,
  626. PrecautionOther: precaution_other,
  627. PsychologicalOther: psychological_other,
  628. AdmissionNumber: admission_number,
  629. }
  630. if receiveTreatment.ID == 0 { //新增
  631. receiveTreatmentAsses.Creater = adminUserInfo.AdminUser.Id
  632. err := service.AddSigleReceiveTreatmentAssesRecord(&receiveTreatmentAsses)
  633. if err == nil {
  634. c.ServeSuccessJSON(map[string]interface{}{
  635. "receiveTreatmentAsses": receiveTreatmentAsses,
  636. })
  637. }
  638. } else { //修改
  639. //if receiveTreatment.Creater != adminUserInfo.AdminUser.Id {
  640. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  641. // if getPermissionErr != nil {
  642. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  643. // return
  644. // } else if headNursePermission == nil {
  645. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  646. // return
  647. // }
  648. //}
  649. receiveTreatmentAsses.Creater = receiveTreatment.Creater
  650. receiveTreatmentAsses.CreatedTime = receiveTreatment.CreatedTime
  651. receiveTreatmentAsses.Modifier = adminUserInfo.AdminUser.Id
  652. receiveTreatmentAsses.ID = receiveTreatment.ID
  653. err := service.UpadateReceiveTreatmentAsses(&receiveTreatmentAsses)
  654. if err == nil {
  655. c.ServeSuccessJSON(map[string]interface{}{
  656. "receiveTreatmentAsses": receiveTreatmentAsses,
  657. })
  658. }
  659. }
  660. }
  661. func (c *DialysisAPIController) PostAssessmentAfterDislysis() {
  662. id, _ := c.GetInt64("patient", 0)
  663. recordDateStr := c.GetString("record_date")
  664. weightAfter, _ := c.GetFloat("weight_after", 0)
  665. additionalWeight, _ := c.GetFloat("additional_weight", 0)
  666. weightReduce, _ := c.GetFloat("weight_loss", 0)
  667. temperature, _ := c.GetFloat("temperature", 0)
  668. pulse_frequency, _ := c.GetFloat("pulse_frequency", 0)
  669. breathing_rate, _ := c.GetFloat("breathing_rate", 0)
  670. systolic_blood_pressure, _ := c.GetFloat("systolic_blood_pressure", 0)
  671. diastolic_blood_pressure, _ := c.GetFloat("diastolic_blood_pressure", 0)
  672. actual_ultrafiltration, _ := c.GetFloat("actual_ultrafiltration", 0)
  673. actual_displacement, _ := c.GetFloat("actual_displacement", 0)
  674. actualtreatHour, _ := c.GetInt64("actual_treatment_hour", 0)
  675. actualtreatmin, _ := c.GetInt64("actual_treatment_minute", 0)
  676. cruor := c.GetString("cruor")
  677. symptomsAfterDialysi := c.GetString("symptom_after_dialysis")
  678. internalFistula := c.GetString("internal_fistula")
  679. catheter := c.GetString("catheter")
  680. complications := c.GetString("complication")
  681. remark := c.GetString("remark")
  682. dialysateVolume, _ := c.GetInt64("dialysis_intakes", 0)
  683. dialysis_intakes_unit, _ := c.GetInt64("dialysis_intakes_unit", 0)
  684. blood_access_part_id, _ := c.GetInt64("blood_access_part_id", 0)
  685. blood_access_part_opera_id, _ := c.GetInt64("blood_access_part_opera_id", 0)
  686. puncturePointOozingBlood, _ := c.GetInt64("puncture_point_oozing_blood", 0)
  687. puncturePointHaematoma, _ := c.GetInt64("puncture_point_haematoma", 0)
  688. internalFistulaTremorAc, _ := c.GetInt64("internal_fistula_tremor_ac", 0)
  689. patientGose, _ := c.GetInt64("patient_gose", 0)
  690. inpatientDepartment := c.GetString("inpatient_department")
  691. observationContent := c.GetString("observation_content")
  692. observationContentOther := c.GetString("observation_content_other")
  693. dialysis_process, _ := c.GetInt64("dialysis_process", 0)
  694. in_advance_minute, _ := c.GetFloat("in_advance_minute", 0)
  695. in_advance_reason := c.GetString("in_advance_reason")
  696. hemostasis_minute, _ := c.GetInt64("hemostasis_minute", 0)
  697. hemostasis_opera, _ := c.GetInt64("hemostasis_opera", 0)
  698. tremor_noise, _ := c.GetInt64("tremor_noise", 0)
  699. disequilibrium_syndrome, _ := c.GetInt64("disequilibrium_syndrome", 0)
  700. disequilibrium_syndrome_option := c.GetString("disequilibrium_syndrome_option")
  701. arterial_tube, _ := c.GetInt64("arterial_tube", 0)
  702. intravenous_tube, _ := c.GetInt64("intravenous_tube", 0)
  703. dialyzer, _ := c.GetInt64("dialyzer", 0)
  704. in_advance_reason_other := c.GetString("in_advance_reason_other")
  705. is_eat, _ := c.GetInt64("is_eat", 0)
  706. cvc_a, _ := c.GetFloat("cvc_a", 0)
  707. cvc_v, _ := c.GetFloat("cvc_v", 0)
  708. channels, _ := c.GetInt64("channel", 0)
  709. return_blood, _ := c.GetInt64("return_blood", 0)
  710. rehydration_volume, _ := c.GetInt64("rehydration_volume", 0)
  711. dialysis_during, _ := c.GetInt64("dialysis_during", 0)
  712. stroke_volume, _ := c.GetInt64("stroke_volume", 0)
  713. blood_flow, _ := c.GetInt64("blood_flow", 0)
  714. //sealing_fluid_dispose, _ := c.GetInt64("sealing_fluid_dispose", 0)
  715. sealing_fluid_dispose := c.GetString("sealing_fluid_dispose")
  716. sealing_fluid_special := c.GetString("sealing_fluid_special")
  717. dosage_of_anticoagulants, _ := c.GetFloat("dosage_of_anticoagulants")
  718. supine_systolic_blood_pressure := c.GetString("supine_systolic_blood_pressure")
  719. setting_pressure := c.GetString("setting_pressure")
  720. supine_diastolic_blood_pressure := c.GetString("supine_diastolic_blood_pressure")
  721. diastolic_pressure := c.GetString("diastolic_pressure")
  722. other_complication := c.GetString("other_complication")
  723. if id <= 0 {
  724. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  725. return
  726. }
  727. adminUserInfo := c.GetMobileAdminUserInfo()
  728. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  729. if patient.ID == 0 {
  730. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  731. return
  732. }
  733. if len(recordDateStr) == 0 {
  734. recordDateStr = time.Now().Format("2006-01-02")
  735. }
  736. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  737. if parseDateErr != nil {
  738. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  739. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  740. return
  741. }
  742. //now := time.Now()
  743. //year, month, day := now.Date()
  744. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  745. //todayTimeStamp := today_time.Unix()
  746. //_, evaluation := service.FindPredialysisEvaluationByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  747. assessmentAfterDislysis := models.AssessmentAfterDislysis{
  748. UserOrgId: adminUserInfo.Org.Id,
  749. PatientId: id,
  750. AssessmentDate: recordDate.Unix(),
  751. Temperature: temperature,
  752. PulseFrequency: pulse_frequency,
  753. BreathingRate: breathing_rate,
  754. SystolicBloodPressure: systolic_blood_pressure,
  755. DiastolicBloodPressure: diastolic_blood_pressure,
  756. ActualUltrafiltration: actual_ultrafiltration,
  757. ActualDisplacement: actual_displacement,
  758. ActualTreatmentHour: actualtreatHour,
  759. ActualTreatmentMinute: actualtreatmin,
  760. WeightAfter: weightAfter,
  761. AdditionalWeight: additionalWeight,
  762. WeightLoss: weightReduce,
  763. Cruor: cruor,
  764. SymptomAfterDialysis: symptomsAfterDialysi,
  765. InternalFistula: internalFistula,
  766. Catheter: catheter,
  767. Complication: complications,
  768. DialysisIntakes: dialysateVolume,
  769. CreatedTime: time.Now().Unix(),
  770. Status: 1,
  771. Remark: remark,
  772. BloodAccessPartId: blood_access_part_id,
  773. BloodAccessPartOperaId: blood_access_part_opera_id,
  774. DialysisIntakesUnit: dialysis_intakes_unit,
  775. PuncturePointOozingBlood: puncturePointOozingBlood,
  776. PuncturePointHaematoma: puncturePointHaematoma,
  777. InternalFistulaTremorAc: internalFistulaTremorAc,
  778. PatientGose: patientGose,
  779. InpatientDepartment: inpatientDepartment,
  780. ObservationContent: observationContent,
  781. ObservationContentOther: observationContentOther,
  782. DialysisProcess: dialysis_process,
  783. InAdvanceMinute: in_advance_minute,
  784. InAdvanceReason: in_advance_reason,
  785. HemostasisMinute: hemostasis_minute,
  786. HemostasisOpera: hemostasis_opera,
  787. TremorNoise: tremor_noise,
  788. DisequilibriumSyndrome: disequilibrium_syndrome,
  789. DisequilibriumSyndromeOption: disequilibrium_syndrome_option,
  790. ArterialTube: arterial_tube,
  791. IntravenousTube: intravenous_tube,
  792. Dialyzer: dialyzer,
  793. InAdvanceReasonOther: in_advance_reason_other,
  794. IsEat: is_eat,
  795. CvcA: cvc_a,
  796. CvcV: cvc_v,
  797. Channel: channels,
  798. ReturnBlood: return_blood,
  799. RehydrationVolume: rehydration_volume,
  800. DialysisDuring: dialysis_during,
  801. StrokeVolume: stroke_volume,
  802. BloodFlow: blood_flow,
  803. SealingFluidDispose: sealing_fluid_dispose,
  804. SealingFluidSpecial: sealing_fluid_special,
  805. DosageOfAnticoagulants: dosage_of_anticoagulants,
  806. SupineDiastolicBloodPressure: supine_diastolic_blood_pressure,
  807. SupineSystolicBloodPressure: supine_systolic_blood_pressure,
  808. SettingPressure: setting_pressure,
  809. DiastolicPressure: diastolic_pressure,
  810. OtherComplication: other_complication,
  811. }
  812. appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id, adminUserInfo.App.Id)
  813. _, assessmentAfter := service.FindAssessmentAfterDislysisByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  814. if assessmentAfter.ID == 0 { //新增
  815. if appRole.UserType == 2 || appRole.UserType == 1 {
  816. assessmentAfterDislysis.AssessmentDoctor = adminUserInfo.AdminUser.Id
  817. assessmentAfterDislysis.AssessmentTime = time.Now().Unix()
  818. } else {
  819. assessmentAfterDislysis.Creater = adminUserInfo.AdminUser.Id
  820. }
  821. err := service.AddSigleAssessmentAfterDislysisRecord(&assessmentAfterDislysis)
  822. if err == nil {
  823. c.ServeSuccessJSON(map[string]interface{}{
  824. "assessmentAfterDislysis": assessmentAfterDislysis,
  825. })
  826. }
  827. } else { //修改
  828. if appRole.UserType == 2 || appRole.UserType == 1 {
  829. assessmentAfterDislysis.AssessmentDoctor = adminUserInfo.AdminUser.Id
  830. assessmentAfterDislysis.AssessmentTime = time.Now().Unix()
  831. } else {
  832. assessmentAfterDislysis.Modifier = adminUserInfo.AdminUser.Id
  833. if assessmentAfterDislysis.Creater == 0 {
  834. assessmentAfterDislysis.Creater = adminUserInfo.AdminUser.Id
  835. }
  836. }
  837. assessmentAfterDislysis.CreatedTime = assessmentAfter.CreatedTime
  838. assessmentAfterDislysis.ID = assessmentAfter.ID
  839. err := service.UpdateAssessmentAfterDislysisRecord(&assessmentAfterDislysis)
  840. if err == nil {
  841. c.ServeSuccessJSON(map[string]interface{}{
  842. "assessmentAfterDislysis": assessmentAfterDislysis,
  843. })
  844. }
  845. }
  846. }
  847. func (c *DialysisAPIController) PostDialysisPrescription() {
  848. id, _ := c.GetInt64("patient", 0)
  849. recordDateStr := c.GetString("record_date")
  850. if id <= 0 {
  851. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  852. return
  853. }
  854. adminUserInfo := c.GetMobileAdminUserInfo()
  855. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  856. if patient.ID == 0 {
  857. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  858. return
  859. }
  860. if len(recordDateStr) == 0 {
  861. recordDateStr = time.Now().Format("2006-01-02")
  862. }
  863. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  864. if parseDateErr != nil {
  865. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  866. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  867. return
  868. }
  869. mode_id, _ := c.GetInt64("mode_id", 0)
  870. dialysis_duration, _ := c.GetFloat("dialysis_duration", 0)
  871. dialyzer, _ := c.GetInt64("dialyzer", 0)
  872. perfusion_apparatus, _ := c.GetInt64("perfusion_apparatus", 0)
  873. blood_flow_volume, _ := c.GetFloat("blood_flow_volume", 0)
  874. dewater_amount, _ := c.GetFloat("dewater_amount", 0)
  875. displace_liqui, _ := c.GetFloat("displace_liqui", 0)
  876. replacement_total, _ := c.GetFloat("replacement_total", 0)
  877. replacement_way, _ := c.GetInt64("replacement_way", 0)
  878. anticoagulant, _ := c.GetInt64("anticoagulant", 0)
  879. anticoagulant_shouji, _ := c.GetFloat("anticoagulant_shouji", 0)
  880. anticoagulant_weichi, _ := c.GetFloat("anticoagulant_weichi", 0)
  881. anticoagulant_zongliang, _ := c.GetFloat("anticoagulant_zongliang", 0)
  882. anticoagulant_gaimingcheng := c.GetString("anticoagulant_gaimingcheng")
  883. anticoagulant_gaijiliang := c.GetString("anticoagulant_gaijiliang")
  884. dialyzerPerfusionApparatus := c.GetString("dialyzer_perfusion_apparatus")
  885. kalium, _ := c.GetFloat("kalium", 0)
  886. sodium, _ := c.GetFloat("sodium", 0)
  887. calcium, _ := c.GetFloat("calcium", 0)
  888. bicarbonate, _ := c.GetFloat("bicarbonate", 0)
  889. glucose, _ := c.GetFloat("glucose", 0)
  890. // prescription_doctor, _ := c.GetInt64("prescription_doctor", 0)
  891. // dry_weight, _ := c.GetFloat("dry_weight", 0)
  892. dialysate_flow, _ := c.GetFloat("dialysate_flow", 0)
  893. dialysate_temperature, _ := c.GetFloat("dialysate_temperature", 0)
  894. conductivity, _ := c.GetFloat("conductivity", 0)
  895. remark := c.GetString("remark")
  896. dialysisDurationHour, _ := c.GetInt64("dialysis_duration_hour", 0)
  897. dialysisDurationMinute, _ := c.GetInt64("dialysis_duration_minute", 0)
  898. targetUltrafiltration, _ := c.GetFloat("target_ultrafiltration", 0)
  899. dialysateFormulation, _ := c.GetInt64("dialysate_formulation", 0)
  900. body_fluid, _ := c.GetInt64("body_fluid", 0)
  901. special_medicine, _ := c.GetInt64("special_medicine", 0)
  902. special_medicine_other := c.GetString("special_medicine_other")
  903. displace_liqui_part, _ := c.GetInt64("displace_liqui_part", 0)
  904. displace_liqui_value, _ := c.GetFloat("displace_liqui_value", 0)
  905. blood_access, _ := c.GetInt64("blood_access", 0)
  906. ultrafiltration, _ := c.GetFloat("ultrafiltration", 0)
  907. body_fluid_other := c.GetString("body_fluid_other")
  908. niprocart, _ := c.GetInt64("niprocart", 0)
  909. jms, _ := c.GetInt64("jms", 0)
  910. fistula_needle_set, _ := c.GetInt64("fistula_needle_set", 0)
  911. fistula_needle_set_16, _ := c.GetInt64("fistula_needle_set_16", 0)
  912. hemoperfusion, _ := c.GetInt64("hemoperfusion", 0)
  913. dialyser_sterilised, _ := c.GetInt64("dialyser_sterilised", 0)
  914. filtryzer, _ := c.GetInt64("filtryzer", 0)
  915. target_ktv, _ := c.GetFloat("target_ktv", 0)
  916. dialyzers, _ := c.GetInt64("dialyzers", 0)
  917. injector, _ := c.GetInt64("injector", 0)
  918. bloodlines, _ := c.GetInt64("bloodlines", 0)
  919. tubing_hemodialysis, _ := c.GetInt64("tubing_hemodialysis", 0)
  920. safe_package, _ := c.GetInt64("package", 0)
  921. a_liquid, _ := c.GetInt64("a_liquid", 0)
  922. pre_impulse, parseDateErr := c.GetFloat("pre_impulse", 0)
  923. fmt.Println("预冲量====", pre_impulse)
  924. anticoagulant_stop_time_hour, _ := c.GetInt64("anticoagulant_stop_time_hour", 0)
  925. anticoagulant_stop_time_min, _ := c.GetInt64("anticoagulant_stop_time_min", 0)
  926. blood := c.GetString("blood")
  927. dialysis_dialyszers := c.GetString("dialysis_dialyszers")
  928. dialysis_irrigation := c.GetString("dialysis_irrigation")
  929. antioxidant_commodity_name := c.GetString("antioxidant_commodity_name")
  930. appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id, adminUserInfo.App.Id)
  931. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  932. //
  933. //if template.TemplateId == 2 || template.TemplateId == 6 {
  934. // if appRole.UserType == 3 {
  935. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  936. // if getPermissionErr != nil {
  937. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  938. // return
  939. // } else if headNursePermission == nil {
  940. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePrescriptionPermissionDeniedModify)
  941. // return
  942. // }
  943. // }
  944. //}
  945. //TODO 需要根据角色去判断
  946. prescription := models.DialysisPrescription{
  947. UserOrgId: adminUserInfo.Org.Id,
  948. PatientId: id,
  949. RecordDate: recordDate.Unix(),
  950. ModeId: mode_id,
  951. DialysisDuration: dialysis_duration,
  952. Dialyzer: dialyzer,
  953. PerfusionApparatus: perfusion_apparatus,
  954. BloodFlowVolume: blood_flow_volume,
  955. DewaterAmount: dewater_amount,
  956. DisplaceLiqui: displace_liqui,
  957. ReplacementWay: replacement_way,
  958. Anticoagulant: anticoagulant,
  959. AnticoagulantShouji: anticoagulant_shouji,
  960. AnticoagulantWeichi: anticoagulant_weichi,
  961. AnticoagulantZongliang: anticoagulant_zongliang,
  962. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  963. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  964. Kalium: kalium,
  965. Sodium: sodium,
  966. Calcium: calcium,
  967. Bicarbonate: bicarbonate,
  968. Glucose: glucose,
  969. // DryWeight: dry_weight,
  970. DialysateFlow: dialysate_flow,
  971. DialysateTemperature: dialysate_temperature,
  972. // PrescriptionDoctor: prescription_doctor,
  973. ReplacementTotal: replacement_total,
  974. Conductivity: conductivity,
  975. Remark: remark,
  976. Status: 1,
  977. CreatedTime: time.Now().Unix(),
  978. UpdatedTime: time.Now().Unix(),
  979. DialysisDurationMinute: dialysisDurationMinute,
  980. DialysisDurationHour: dialysisDurationHour,
  981. TargetUltrafiltration: targetUltrafiltration,
  982. DialysateFormulation: dialysateFormulation,
  983. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  984. BodyFluid: body_fluid,
  985. SpecialMedicine: special_medicine,
  986. SpecialMedicineOther: special_medicine_other,
  987. DisplaceLiquiPart: displace_liqui_part,
  988. DisplaceLiquiValue: displace_liqui_value,
  989. BloodAccess: blood_access,
  990. Ultrafiltration: ultrafiltration,
  991. BodyFluidOther: body_fluid_other,
  992. Niprocart: niprocart,
  993. Jms: jms,
  994. FistulaNeedleSet: fistula_needle_set,
  995. FistulaNeedleSet16: fistula_needle_set_16,
  996. Hemoperfusion: hemoperfusion,
  997. DialyserSterilised: dialyser_sterilised,
  998. Filtryzer: filtryzer,
  999. Dialyzers: dialyzers,
  1000. Injector: injector,
  1001. Bloodlines: bloodlines,
  1002. TubingHemodialysis: tubing_hemodialysis,
  1003. Package: safe_package,
  1004. ALiquid: a_liquid,
  1005. TargetKtv: target_ktv,
  1006. PreImpulse: pre_impulse,
  1007. AnticoagulantStopTimeHour: anticoagulant_stop_time_hour,
  1008. AnticoagulantStopTimeMin: anticoagulant_stop_time_min,
  1009. Blood: blood,
  1010. DialysisDialyszers: dialysis_dialyszers,
  1011. DialysisIrrigation: dialysis_irrigation,
  1012. AntioxidantCommodityName: antioxidant_commodity_name,
  1013. }
  1014. _, dialysisPrescription := service.FindDialysisPrescriptionByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  1015. if dialysisPrescription.ID == 0 { //新增
  1016. //if mode_id > 0 {
  1017. // //service.ModifyScheduleMode(mode_id, patient.ID, recordDate.Unix(), adminUserInfo.Org.Id)
  1018. //}
  1019. if appRole.UserType == 2 || appRole.UserType == 1 {
  1020. prescription.PrescriptionDoctor = adminUserInfo.AdminUser.Id
  1021. }
  1022. prescription.Creater = adminUserInfo.AdminUser.Id
  1023. err := service.AddSigleRecord(&prescription)
  1024. if err == nil {
  1025. updateErr := service.UpdateScheduleModeId(patient.ID, adminUserInfo.Org.Id, recordDate.Unix(), mode_id)
  1026. if updateErr != nil {
  1027. utils.ErrorLog("%v", updateErr)
  1028. }
  1029. c.ServeSuccessJSON(map[string]interface{}{
  1030. "prescription": prescription,
  1031. })
  1032. }
  1033. } else { //修改
  1034. //if mode_id > 0 {
  1035. // service.ModifyScheduleMode(mode_id, patient.ID, recordDate.Unix(), adminUserInfo.Org.Id)
  1036. //}
  1037. //if template.TemplateId == 1 {
  1038. // if dialysisPrescription.Creater != adminUserInfo.AdminUser.Id && dialysisPrescription.Creater != 0 {
  1039. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1040. // if getPermissionErr != nil {
  1041. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1042. // return
  1043. // } else if headNursePermission == nil {
  1044. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePrescriptionPermissionDeniedModify)
  1045. // return
  1046. // }
  1047. // }
  1048. //}
  1049. prescription.CreatedTime = dialysisPrescription.CreatedTime
  1050. prescription.Modifier = adminUserInfo.AdminUser.Id
  1051. if appRole.UserType == 2 || appRole.UserType == 1 {
  1052. prescription_doctor := adminUserInfo.AdminUser.Id
  1053. prescription.PrescriptionDoctor = prescription_doctor
  1054. } else {
  1055. prescription.PrescriptionDoctor = dialysisPrescription.PrescriptionDoctor
  1056. }
  1057. if dialysisPrescription.Creater == 0 { //体重称
  1058. prescription.Creater = adminUserInfo.AdminUser.Id
  1059. } else {
  1060. prescription.Creater = dialysisPrescription.Creater
  1061. }
  1062. prescription.ID = dialysisPrescription.ID
  1063. err := service.UpDateDialysisPrescription(&prescription)
  1064. if err == nil {
  1065. updateErr := service.UpdateScheduleModeId(patient.ID, adminUserInfo.Org.Id, recordDate.Unix(), mode_id)
  1066. if updateErr != nil {
  1067. utils.ErrorLog("%v", updateErr)
  1068. }
  1069. c.ServeSuccessJSON(map[string]interface{}{
  1070. "prescription": prescription,
  1071. })
  1072. }
  1073. }
  1074. }
  1075. func (c *DialysisAPIController) Finish() {
  1076. id, _ := c.GetInt64("patient", 0)
  1077. recordDateStr := c.GetString("record_date")
  1078. nurseID, _ := c.GetInt64("nurse")
  1079. end_time := c.GetString("end_time")
  1080. if id <= 0 || nurseID <= 0 {
  1081. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1082. return
  1083. }
  1084. adminUserInfo := c.GetMobileAdminUserInfo()
  1085. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  1086. if patient.ID == 0 {
  1087. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1088. return
  1089. }
  1090. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  1091. if getNurseErr != nil {
  1092. c.ErrorLog("获取护士失败:%v", getNurseErr)
  1093. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1094. return
  1095. } else if nurse == nil {
  1096. c.ErrorLog("护士不存在")
  1097. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1098. return
  1099. }
  1100. if len(recordDateStr) == 0 {
  1101. recordDateStr = time.Now().Format("2006-01-02")
  1102. }
  1103. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1104. if parseDateErr != nil {
  1105. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  1106. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1107. return
  1108. }
  1109. endDate, parseEndDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", end_time)
  1110. if parseEndDateErr != nil {
  1111. c.ErrorLog("日期(%v)解析错误:%v", end_time, parseEndDateErr)
  1112. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1113. return
  1114. }
  1115. //now := time.Now()
  1116. //year, month, day := now.Date()
  1117. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  1118. //todayTimeStamp := today_time.Unix()
  1119. // 获取当天的第一条透析纪录
  1120. fmonitorRecords, getMonitorRecordsErr := service.MobileGetMonitorRecordFirst(adminUserInfo.Org.Id, id, recordDate.Unix())
  1121. if getMonitorRecordsErr != nil {
  1122. c.ErrorLog("获取透析监测记录失败:%v", getMonitorRecordsErr)
  1123. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1124. return
  1125. }
  1126. // 获取当前的最后一条透析纪录
  1127. endmonitorRecords, getMonitorRecordsErr := service.MobileGetLastMonitorRecord(adminUserInfo.Org.Id, id, recordDate.Unix())
  1128. if getMonitorRecordsErr != nil {
  1129. c.ErrorLog("获取透析监测记录失败:%v", getMonitorRecordsErr)
  1130. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1131. return
  1132. }
  1133. fmt.Println(endmonitorRecords.UltrafiltrationVolume)
  1134. assessmentAfterDislysis, getAADErr := service.MobileGetAssessmentAfterDislysis(adminUserInfo.Org.Id, id, recordDate.Unix())
  1135. if getAADErr != nil {
  1136. c.ErrorLog("获取透后评估失败:%v", getAADErr)
  1137. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1138. return
  1139. }
  1140. lastAssessmentAfterDislysis, _ := service.MobileGetLastTimeAssessmentAfterDislysis(adminUserInfo.Org.Id, id, recordDate.Unix())
  1141. _, dialysisOrder := service.FindDialysisRecordById(adminUserInfo.Org.Id, id, recordDate.Unix())
  1142. var tempassessmentAfterDislysis models.AssessmentAfterDislysis
  1143. if assessmentAfterDislysis != nil {
  1144. tempassessmentAfterDislysis = *assessmentAfterDislysis
  1145. tempassessmentAfterDislysis.UpdatedTime = time.Now().Unix()
  1146. } else {
  1147. tempassessmentAfterDislysis.CreatedTime = time.Now().Unix()
  1148. tempassessmentAfterDislysis.AssessmentDate = recordDate.Unix()
  1149. tempassessmentAfterDislysis.Status = 1
  1150. tempassessmentAfterDislysis.PatientId = id
  1151. tempassessmentAfterDislysis.UserOrgId = adminUserInfo.Org.Id
  1152. }
  1153. if dialysisOrder.Stage == 1 {
  1154. temp_time := (float64(endDate.Unix()) - float64(dialysisOrder.StartTime)) / 3600
  1155. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  1156. fmt.Println(value)
  1157. a, b := math.Modf(value)
  1158. c, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  1159. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  1160. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", c*60), 10, 64)
  1161. fmt.Println(hour)
  1162. fmt.Println(minute)
  1163. tempassessmentAfterDislysis.ActualTreatmentHour = hour
  1164. tempassessmentAfterDislysis.ActualTreatmentMinute = minute
  1165. }
  1166. if fmonitorRecords.ID > 0 && endmonitorRecords.ID > 0 {
  1167. //var num1 int64
  1168. //num1 = endmonitorRecords.OperateTime - fmonitorRecords.OperateTime
  1169. //fmt.Println(num1)
  1170. //sub := float64(num1 / 3600)
  1171. //fmt.Println(sub)
  1172. //tempassessmentAfterDislysis.ActualTreatmentHour = int64(math.Floor(sub))
  1173. //sub2 := float64(((endmonitorRecords.OperateTime - fmonitorRecords.OperateTime) % 3600) / 60)
  1174. //tempassessmentAfterDislysis.ActualTreatmentMinute = int64(math.Floor(sub2))
  1175. tempassessmentAfterDislysis.Temperature = endmonitorRecords.Temperature
  1176. tempassessmentAfterDislysis.PulseFrequency = endmonitorRecords.PulseFrequency
  1177. tempassessmentAfterDislysis.BreathingRate = endmonitorRecords.BreathingRate
  1178. tempassessmentAfterDislysis.SystolicBloodPressure = endmonitorRecords.SystolicBloodPressure
  1179. tempassessmentAfterDislysis.DiastolicBloodPressure = endmonitorRecords.DiastolicBloodPressure
  1180. tempassessmentAfterDislysis.ActualUltrafiltration = endmonitorRecords.UltrafiltrationVolume
  1181. tempassessmentAfterDislysis.ActualDisplacement = endmonitorRecords.DisplacementQuantity
  1182. }
  1183. if adminUserInfo.Org.Id == 9583 {
  1184. //获取透析处方的最后一条数据
  1185. diaPrescription, diaerr := service.GetLastDialysisPrescriptionByPatientId(adminUserInfo.Org.Id, id, recordDate.Unix())
  1186. if diaerr != nil {
  1187. c.ErrorLog("获取透析处方失败:%v", diaerr)
  1188. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1189. return
  1190. }
  1191. if diaPrescription.ID > 0 && adminUserInfo.Org.Id == 9583 {
  1192. tempassessmentAfterDislysis.ActualUltrafiltration = diaPrescription.TargetUltrafiltration
  1193. }
  1194. }
  1195. if lastAssessmentAfterDislysis != nil {
  1196. tempassessmentAfterDislysis.BloodPressureType = lastAssessmentAfterDislysis.BloodPressureType
  1197. tempassessmentAfterDislysis.WeighingWay = lastAssessmentAfterDislysis.WeighingWay
  1198. tempassessmentAfterDislysis.Cruor = lastAssessmentAfterDislysis.Cruor
  1199. tempassessmentAfterDislysis.SymptomAfterDialysis = lastAssessmentAfterDislysis.SymptomAfterDialysis
  1200. tempassessmentAfterDislysis.InternalFistula = lastAssessmentAfterDislysis.InternalFistula
  1201. tempassessmentAfterDislysis.Catheter = lastAssessmentAfterDislysis.Catheter
  1202. tempassessmentAfterDislysis.Complication = lastAssessmentAfterDislysis.Complication
  1203. tempassessmentAfterDislysis.DialysisIntakes = lastAssessmentAfterDislysis.DialysisIntakes
  1204. tempassessmentAfterDislysis.DialysisIntakesFeed = lastAssessmentAfterDislysis.DialysisIntakesFeed
  1205. tempassessmentAfterDislysis.DialysisIntakesTransfusion = lastAssessmentAfterDislysis.DialysisIntakesTransfusion
  1206. tempassessmentAfterDislysis.DialysisIntakesBloodTransfusion = lastAssessmentAfterDislysis.DialysisIntakesBloodTransfusion
  1207. tempassessmentAfterDislysis.DialysisIntakesWashpipe = lastAssessmentAfterDislysis.DialysisIntakesWashpipe
  1208. tempassessmentAfterDislysis.BloodAccessPartId = lastAssessmentAfterDislysis.BloodAccessPartId
  1209. tempassessmentAfterDislysis.BloodAccessPartOperaId = lastAssessmentAfterDislysis.BloodAccessPartOperaId
  1210. tempassessmentAfterDislysis.PuncturePointOozingBlood = lastAssessmentAfterDislysis.PuncturePointOozingBlood
  1211. tempassessmentAfterDislysis.PuncturePointHaematoma = lastAssessmentAfterDislysis.PuncturePointHaematoma
  1212. tempassessmentAfterDislysis.InternalFistulaTremorAc = lastAssessmentAfterDislysis.InternalFistulaTremorAc
  1213. tempassessmentAfterDislysis.PatientGose = lastAssessmentAfterDislysis.PatientGose
  1214. tempassessmentAfterDislysis.InpatientDepartment = lastAssessmentAfterDislysis.InpatientDepartment
  1215. tempassessmentAfterDislysis.ObservationContent = lastAssessmentAfterDislysis.ObservationContent
  1216. tempassessmentAfterDislysis.ObservationContentOther = lastAssessmentAfterDislysis.ObservationContentOther
  1217. tempassessmentAfterDislysis.DryWeight = lastAssessmentAfterDislysis.DryWeight
  1218. tempassessmentAfterDislysis.DialysisProcess = lastAssessmentAfterDislysis.DialysisProcess
  1219. tempassessmentAfterDislysis.InAdvanceMinute = lastAssessmentAfterDislysis.InAdvanceMinute
  1220. tempassessmentAfterDislysis.InAdvanceReason = lastAssessmentAfterDislysis.InAdvanceReason
  1221. tempassessmentAfterDislysis.HemostasisMinute = lastAssessmentAfterDislysis.HemostasisMinute
  1222. tempassessmentAfterDislysis.HemostasisOpera = lastAssessmentAfterDislysis.HemostasisOpera
  1223. tempassessmentAfterDislysis.TremorNoise = lastAssessmentAfterDislysis.TremorNoise
  1224. tempassessmentAfterDislysis.DisequilibriumSyndrome = lastAssessmentAfterDislysis.DisequilibriumSyndrome
  1225. tempassessmentAfterDislysis.DisequilibriumSyndromeOption = lastAssessmentAfterDislysis.DisequilibriumSyndromeOption
  1226. tempassessmentAfterDislysis.ArterialTube = lastAssessmentAfterDislysis.ArterialTube
  1227. tempassessmentAfterDislysis.IntravenousTube = lastAssessmentAfterDislysis.IntravenousTube
  1228. tempassessmentAfterDislysis.Dialyzer = lastAssessmentAfterDislysis.Dialyzer
  1229. tempassessmentAfterDislysis.InAdvanceReasonOther = lastAssessmentAfterDislysis.InAdvanceReasonOther
  1230. tempassessmentAfterDislysis.IsEat = lastAssessmentAfterDislysis.IsEat
  1231. tempassessmentAfterDislysis.DialysisIntakesUnit = lastAssessmentAfterDislysis.DialysisIntakesUnit
  1232. tempassessmentAfterDislysis.CvcA = lastAssessmentAfterDislysis.CvcA
  1233. tempassessmentAfterDislysis.CvcV = lastAssessmentAfterDislysis.CvcV
  1234. tempassessmentAfterDislysis.Channel = lastAssessmentAfterDislysis.Channel
  1235. tempassessmentAfterDislysis.ReturnBlood = lastAssessmentAfterDislysis.ReturnBlood
  1236. tempassessmentAfterDislysis.RehydrationVolume = lastAssessmentAfterDislysis.RehydrationVolume
  1237. tempassessmentAfterDislysis.DialysisDuring = lastAssessmentAfterDislysis.DialysisDuring
  1238. tempassessmentAfterDislysis.StrokeVolume = lastAssessmentAfterDislysis.StrokeVolume
  1239. tempassessmentAfterDislysis.BloodFlow = lastAssessmentAfterDislysis.BloodFlow
  1240. tempassessmentAfterDislysis.SealingFluidDispose = lastAssessmentAfterDislysis.SealingFluidDispose
  1241. tempassessmentAfterDislysis.SealingFluidSpecial = lastAssessmentAfterDislysis.SealingFluidSpecial
  1242. }
  1243. err := service.UpdateAssessmentAfterDislysisRecord(&tempassessmentAfterDislysis)
  1244. if err != nil {
  1245. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1246. return
  1247. }
  1248. if dialysisOrder == nil {
  1249. c.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderNoStart)
  1250. return
  1251. }
  1252. if dialysisOrder.Stage == 2 {
  1253. c.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderNoEND)
  1254. return
  1255. }
  1256. if dialysisOrder.Stage == 1 {
  1257. err := service.ModifyDialysisRecord(dialysisOrder.ID, nurseID, endDate.Unix(), adminUserInfo.AdminUser.Id)
  1258. //结束时候透析次数加1
  1259. service.UpdateSolutionByPatientId(id)
  1260. dialysisOrder.Stage = 2
  1261. dialysisOrder.FinishNurse = nurseID
  1262. dialysisOrder.FinishCreator = adminUserInfo.AdminUser.Id
  1263. dialysisOrder.FinishModifier = adminUserInfo.AdminUser.Id
  1264. dialysisOrder.EndTime = endDate.Unix()
  1265. go func() {
  1266. ssoDomain := beego.AppConfig.String("call_domain")
  1267. api := ssoDomain + "/index/downpatient"
  1268. values := make(url.Values)
  1269. values.Set("org_id", strconv.FormatInt(adminUserInfo.AdminUser.Id, 10))
  1270. values.Set("admin_user_id", strconv.FormatInt(nurseID, 10))
  1271. values.Set("patient_id", strconv.FormatInt(id, 10))
  1272. http.PostForm(api, values)
  1273. }()
  1274. if err == nil {
  1275. c.ServeSuccessJSON(map[string]interface{}{
  1276. "dialysisOrder": dialysisOrder,
  1277. "assessmentAfterDislysis": tempassessmentAfterDislysis,
  1278. })
  1279. } else {
  1280. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  1281. }
  1282. }
  1283. }
  1284. func (c *DialysisAPIController) GetAllZone() {
  1285. adminUserInfo := c.GetMobileAdminUserInfo()
  1286. err, zone := service.GetAllDeviceZone(adminUserInfo.Org.Id)
  1287. if err == nil {
  1288. c.ServeSuccessJSON(map[string]interface{}{
  1289. "zone": zone,
  1290. })
  1291. }
  1292. }
  1293. func (c *DialysisAPIController) GetSchedualPatientsList() {
  1294. adminUserInfo := c.GetMobileAdminUserInfo()
  1295. page, _ := c.GetInt64("page", 1)
  1296. limit, _ := c.GetInt64("limit", 10)
  1297. schedulType, _ := c.GetInt64("schedul_type", 0)
  1298. startTime, _ := c.GetInt64("schedul_time", 0)
  1299. partitionType, _ := c.GetInt64("partition_type", 0)
  1300. keywords := c.GetString("keywords")
  1301. dialysisSchedule, err := service.GetSchedualPatientList(adminUserInfo.Org.Id, startTime/1000, schedulType, partitionType, keywords, page, limit)
  1302. if err == nil {
  1303. c.ServeSuccessJSON(map[string]interface{}{
  1304. "schedule": dialysisSchedule,
  1305. })
  1306. }
  1307. return
  1308. }
  1309. // /m/api/dialysis/start [post]
  1310. // @param patient_id:int
  1311. // @param record_date:string 排班时间 (yyyy-mm-dd)
  1312. // @param nurse:int 上机护士
  1313. // @param bed:int 床位号
  1314. func (this *DialysisAPIController) StartDialysis() {
  1315. patientID, _ := this.GetInt64("patient_id")
  1316. recordDateStr := this.GetString("record_date")
  1317. nurseID, _ := this.GetInt64("nurse")
  1318. puncture_nurse, _ := this.GetInt64("puncture_nurse")
  1319. blood_drawing, _ := this.GetInt64("blood_drawing")
  1320. schedual_type, _ := this.GetInt64("schedual_type")
  1321. bedID, _ := this.GetInt64("bed")
  1322. start_time := this.GetString("start_time")
  1323. washpipe_nurse, _ := this.GetInt64("washpipe_nurse")
  1324. change_nurse, _ := this.GetInt64("change_nurse")
  1325. if patientID <= 0 || len(recordDateStr) == 0 || nurseID <= 0 || bedID <= 0 {
  1326. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1327. return
  1328. }
  1329. startDate, parseStartDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", start_time)
  1330. if parseStartDateErr != nil {
  1331. this.ErrorLog("时间解析失败:%v", parseStartDateErr)
  1332. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1333. return
  1334. }
  1335. recordDate, parseErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1336. if parseErr != nil {
  1337. this.ErrorLog("时间解析失败:%v", parseErr)
  1338. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1339. return
  1340. }
  1341. adminUserInfo := this.GetMobileAdminUserInfo()
  1342. patient, getPatientErr := service.MobileGetPatientById(adminUserInfo.Org.Id, patientID)
  1343. if getPatientErr != nil {
  1344. this.ErrorLog("获取患者信息失败:%v", getPatientErr)
  1345. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1346. return
  1347. } else if patient == nil {
  1348. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1349. return
  1350. }
  1351. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  1352. if getNurseErr != nil {
  1353. this.ErrorLog("获取护士失败:%v", getNurseErr)
  1354. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1355. return
  1356. } else if nurse == nil {
  1357. this.ErrorLog("护士不存在")
  1358. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1359. return
  1360. }
  1361. nurse, getNurseErr = service.GetAdminUserByUserID(puncture_nurse)
  1362. if getNurseErr != nil {
  1363. this.ErrorLog("获取护士失败:%v", getNurseErr)
  1364. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1365. return
  1366. } else if nurse == nil {
  1367. this.ErrorLog("护士不存在")
  1368. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1369. return
  1370. }
  1371. deviceNumber, getDeviceNumberErr := service.GetDeviceNumberByID(adminUserInfo.Org.Id, bedID)
  1372. if getDeviceNumberErr != nil {
  1373. this.ErrorLog("获取床位号失败:%v", getDeviceNumberErr)
  1374. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1375. return
  1376. } else if deviceNumber == nil {
  1377. this.ErrorLog("床位号不存在")
  1378. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1379. return
  1380. }
  1381. dialysisRecord, getRecordErr := service.MobileGetDialysisRecord(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  1382. if getRecordErr != nil {
  1383. this.ErrorLog("获取透析记录失败:%v", getRecordErr)
  1384. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1385. return
  1386. } else if dialysisRecord != nil {
  1387. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatStart)
  1388. return
  1389. }
  1390. scheduleDateStart := startDate.Format("2006-01-02") + " 00:00:00"
  1391. scheduleDateEnd := startDate.Format("2006-01-02") + " 23:59:59"
  1392. timeLayout := "2006-01-02 15:04:05"
  1393. loc, _ := time.LoadLocation("Local")
  1394. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  1395. theEndTime, _ := time.ParseInLocation(timeLayout, scheduleDateEnd, loc)
  1396. schedulestartTime := theStartTime.Unix()
  1397. scheduleendTime := theEndTime.Unix()
  1398. template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  1399. //查询更改的机号,是否有人用了,如果只是排班了,但是没上机,直接替换,如果排班且上机了,就提示他无法上机
  1400. schedule, err := service.GetDayScheduleByBedid(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  1401. //查询该床位是否有人用了
  1402. order, order_err := service.GetDialysisOrderByBedId(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  1403. if err == gorm.ErrRecordNotFound { //空床位
  1404. // 修改了床位逻辑
  1405. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1406. if daySchedule.ID > 0 {
  1407. daySchedule.PartitionId = deviceNumber.ZoneID
  1408. daySchedule.BedId = bedID
  1409. daySchedule.ScheduleType = schedual_type
  1410. daySchedule.UpdatedTime = time.Now().Unix()
  1411. err := service.UpdateSchedule(&daySchedule)
  1412. if err != nil {
  1413. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1414. return
  1415. }
  1416. }
  1417. } else if err == nil {
  1418. if schedule.ID > 0 && schedule.DialysisOrder.ID == 0 { //有排班没上机记录
  1419. if order_err == nil {
  1420. if order.ID > 0 { //该机位被其他人占用了
  1421. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  1422. return
  1423. } else {
  1424. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1425. if daySchedule.ID > 0 {
  1426. daySchedule.PartitionId = deviceNumber.ZoneID
  1427. daySchedule.BedId = bedID
  1428. daySchedule.ScheduleType = schedual_type
  1429. daySchedule.UpdatedTime = time.Now().Unix()
  1430. err := service.UpdateSchedule(&daySchedule)
  1431. if err != nil {
  1432. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1433. return
  1434. }
  1435. }
  1436. }
  1437. } else if order_err == gorm.ErrRecordNotFound { //该床位没被占用
  1438. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1439. if daySchedule.ID > 0 {
  1440. daySchedule.PartitionId = deviceNumber.ZoneID
  1441. daySchedule.BedId = bedID
  1442. daySchedule.ScheduleType = schedual_type
  1443. daySchedule.UpdatedTime = time.Now().Unix()
  1444. err := service.UpdateSchedule(&daySchedule)
  1445. if err != nil {
  1446. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1447. return
  1448. }
  1449. }
  1450. }
  1451. } else if schedule.ID > 0 && schedule.DialysisOrder.ID > 0 { //有排班且有上机记录
  1452. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  1453. return
  1454. }
  1455. } else if err != nil {
  1456. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1457. return
  1458. }
  1459. dialysisRecord = &models.DialysisOrder{
  1460. DialysisDate: recordDate.Unix(),
  1461. UserOrgId: adminUserInfo.Org.Id,
  1462. PatientId: patientID,
  1463. Stage: 1,
  1464. BedID: bedID,
  1465. StartNurse: nurseID,
  1466. Status: 1,
  1467. StartTime: startDate.Unix(),
  1468. CreatedTime: time.Now().Unix(),
  1469. UpdatedTime: time.Now().Unix(),
  1470. PunctureNurse: puncture_nurse,
  1471. Creator: adminUserInfo.AdminUser.Id,
  1472. Modifier: adminUserInfo.AdminUser.Id,
  1473. SchedualType: schedual_type,
  1474. WashpipeNurse: washpipe_nurse,
  1475. ChangeNurse: change_nurse,
  1476. }
  1477. createErr := service.MobileCreateDialysisOrder(adminUserInfo.Org.Id, patientID, dialysisRecord)
  1478. newdialysisRecord, getRecordErr := service.MobileGetDialysisRecord(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  1479. var tempdispose string
  1480. // 只针对中能建
  1481. if blood_drawing > 0 && adminUserInfo.Org.Id == 9538 {
  1482. tempdispose = "引血" + strconv.FormatInt(blood_drawing, 10) + "ml/min"
  1483. }
  1484. var ultrafiltration_rate float64
  1485. _, prescription := service.FindDialysisPrescriptionByReordDate(patientID, schedulestartTime, adminUserInfo.Org.Id)
  1486. if prescription.ID > 0 {
  1487. if prescription.TargetUltrafiltration > 0 && prescription.DialysisDurationHour > 0 {
  1488. totalMin := prescription.DialysisDurationHour*60 + prescription.DialysisDurationMinute
  1489. if template.TemplateId == 6 || template.TemplateId == 32 { //adminUserInfo.Org.Id == 9538
  1490. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1000)
  1491. }
  1492. if template.TemplateId == 20 || template.TemplateId == 22 { //adminUserInfo.Org.Id == 9538
  1493. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60)
  1494. }
  1495. // 只针对方济医院
  1496. if template.TemplateId == 1 && adminUserInfo.Org.Id != 9849 {
  1497. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", prescription.TargetUltrafiltration/float64(totalMin)*60), 6)
  1498. ultrafiltration_rate = value
  1499. }
  1500. }
  1501. }
  1502. record := models.MonitoringRecord{
  1503. UserOrgId: adminUserInfo.Org.Id,
  1504. PatientId: patientID,
  1505. DialysisOrderId: dialysisRecord.ID,
  1506. MonitoringDate: schedulestartTime,
  1507. OperateTime: startDate.Unix(),
  1508. // MonitoringTime: recordTime,
  1509. MonitoringNurse: nurseID,
  1510. Dispose: tempdispose,
  1511. UltrafiltrationRate: ultrafiltration_rate,
  1512. UltrafiltrationVolume: 0,
  1513. Status: 1,
  1514. CreatedTime: time.Now().Unix(),
  1515. UpdatedTime: time.Now().Unix(),
  1516. }
  1517. //只针对广慈医院
  1518. if template.TemplateId == 26 || template.TemplateId == 25 || template.TemplateId == 28 || adminUserInfo.Org.Id == 9987 || adminUserInfo.Org.Id == 9526 || template.TemplateId == 32 {
  1519. // 查询病人是否有透前评估数据
  1520. befor, errcode := service.GetAssessmentBefor(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  1521. //如果有数据就插入
  1522. if errcode == nil {
  1523. record.SystolicBloodPressure = befor.SystolicBloodPressure
  1524. record.DiastolicBloodPressure = befor.DiastolicBloodPressure
  1525. record.BreathingRate = befor.BreathingRate
  1526. record.PulseFrequency = befor.PulseFrequency
  1527. record.Temperature = befor.Temperature
  1528. }
  1529. }
  1530. // 如果当天有插入数据,则不再往透析纪录里插入数据
  1531. if newdialysisRecord.ID > 0 {
  1532. err := service.CreateMonitor(&record)
  1533. if err != nil {
  1534. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeMonitorCreate)
  1535. return
  1536. }
  1537. }
  1538. go func() {
  1539. ssoDomain := beego.AppConfig.String("call_domain")
  1540. api := ssoDomain + "/index/uppatient"
  1541. values := make(url.Values)
  1542. values.Set("org_id", strconv.FormatInt(adminUserInfo.Org.Id, 10))
  1543. values.Set("admin_user_id", strconv.FormatInt(nurseID, 10))
  1544. values.Set("patient_id", strconv.FormatInt(patientID, 10))
  1545. values.Set("up_time", strconv.FormatInt(startDate.Unix(), 10))
  1546. http.PostForm(api, values)
  1547. }()
  1548. if createErr != nil {
  1549. this.ErrorLog("上机失败:%v", createErr)
  1550. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1551. return
  1552. }
  1553. this.ServeSuccessJSON(map[string]interface{}{
  1554. "dialysis_order": newdialysisRecord,
  1555. "monitor": record,
  1556. })
  1557. }
  1558. func (c *DialysisAPIController) PostSolution() {
  1559. id, _ := c.GetInt64("patient", 0)
  1560. recordDateStr := c.GetString("record_date")
  1561. if id <= 0 {
  1562. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1563. return
  1564. }
  1565. adminUserInfo := c.GetMobileAdminUserInfo()
  1566. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  1567. if patient.ID == 0 {
  1568. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1569. return
  1570. }
  1571. if len(recordDateStr) == 0 {
  1572. recordDateStr = time.Now().Format("2006-01-02")
  1573. }
  1574. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1575. if parseDateErr != nil {
  1576. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  1577. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1578. return
  1579. }
  1580. mode_id, _ := c.GetInt64("mode_id", 0)
  1581. dialysis_duration, _ := c.GetFloat("dialysis_duration", 0)
  1582. dialyzer, _ := c.GetInt64("dialyzer", 0)
  1583. perfusion_apparatus, _ := c.GetInt64("perfusion_apparatus", 0)
  1584. blood_flow_volume, _ := c.GetFloat("blood_flow_volume", 0)
  1585. dewater_amount, _ := c.GetFloat("dewater_amount", 0)
  1586. displace_liqui, _ := c.GetFloat("displace_liqui", 0)
  1587. replacement_way, _ := c.GetInt64("replacement_way", 0)
  1588. anticoagulant, _ := c.GetInt64("anticoagulant", 0)
  1589. anticoagulant_shouji, _ := c.GetFloat("anticoagulant_shouji", 0)
  1590. anticoagulant_weichi, _ := c.GetFloat("anticoagulant_weichi", 0)
  1591. anticoagulant_zongliang, _ := c.GetFloat("anticoagulant_zongliang", 0)
  1592. anticoagulant_gaimingcheng := c.GetString("anticoagulant_gaimingcheng")
  1593. anticoagulant_gaijiliang := c.GetString("anticoagulant_gaijiliang")
  1594. kalium, _ := c.GetFloat("kalium", 0)
  1595. sodium, _ := c.GetFloat("sodium", 0)
  1596. calcium, _ := c.GetFloat("calcium", 0)
  1597. bicarbonate, _ := c.GetFloat("bicarbonate", 0)
  1598. prescription_doctor, _ := c.GetInt64("prescription_doctor", 0)
  1599. dialyzerPerfusionApparatus := c.GetString("dialyzer_perfusion_apparatus")
  1600. glucose, _ := c.GetFloat("glucose", 0)
  1601. // dry_weight, _ := c.GetFloat("dry_weight", 0)
  1602. dialysate_flow, _ := c.GetFloat("dialysate_flow", 0)
  1603. dialysate_temperature, _ := c.GetFloat("dialysate_temperature", 0)
  1604. conductivity, _ := c.GetFloat("conductivity", 0)
  1605. remark := c.GetString("remark")
  1606. dialysisDurationHour, _ := c.GetInt64("dialysis_duration_hour", 0)
  1607. dialysisDurationMinute, _ := c.GetInt64("dialysis_duration_minute", 0)
  1608. targetUltrafiltration, _ := c.GetFloat("target_ultrafiltration", 0)
  1609. dialysateFormulation, _ := c.GetInt64("dialysate_formulation", 0)
  1610. body_fluid, _ := c.GetInt64("body_fluid", 0)
  1611. special_medicine, _ := c.GetInt64("special_medicine", 0)
  1612. special_medicine_other := c.GetString("special_medicine_other")
  1613. displace_liqui_part, _ := c.GetInt64("displace_liqui_part", 0)
  1614. displace_liqui_value, _ := c.GetFloat("displace_liqui_value", 0)
  1615. blood_access, _ := c.GetInt64("blood_access", 0)
  1616. ultrafiltration, _ := c.GetFloat("ultrafiltration", 0)
  1617. body_fluid_other := c.GetString("body_fluid_other")
  1618. replacement_total, _ := c.GetFloat("replacement_total", 0)
  1619. niprocart, _ := c.GetInt64("niprocart", 0)
  1620. jms, _ := c.GetInt64("jms", 0)
  1621. fistula_needle_set, _ := c.GetInt64("fistula_needle_set", 0)
  1622. fistula_needle_set_16, _ := c.GetInt64("fistula_needle_set_16", 0)
  1623. hemoperfusion, _ := c.GetInt64("hemoperfusion", 0)
  1624. dialyser_sterilised, _ := c.GetInt64("dialyser_sterilised", 0)
  1625. filtryzer, _ := c.GetInt64("filtryzer", 0)
  1626. target_ktv, _ := c.GetFloat("target_ktv", 0)
  1627. dialyzers, _ := c.GetInt64("dialyzers", 0)
  1628. injector, _ := c.GetInt64("injector", 0)
  1629. bloodlines, _ := c.GetInt64("bloodlines", 0)
  1630. tubing_hemodialysis, _ := c.GetInt64("tubing_hemodialysis", 0)
  1631. safe_package, _ := c.GetInt64("package", 0)
  1632. a_liquid, _ := c.GetInt64("a_liquid", 0)
  1633. anticoagulant_stop_time_hour, _ := c.GetInt64("anticoagulant_stop_time_hour", 0)
  1634. anticoagulant_stop_time_min, _ := c.GetInt64("anticoagulant_stop_time_min", 0)
  1635. blood := c.GetString("blood")
  1636. dialysis_dialyszers := c.GetString("dialysis_dialyszers")
  1637. dialysis_irrigation := c.GetString("dialysis_irrigation")
  1638. antioxidant_commodity_name := c.GetString("antioxidant_commodity_name")
  1639. if mode_id > 0 {
  1640. service.ModifyScheduleMode(mode_id, patient.ID, recordDate.Unix(), adminUserInfo.Org.Id)
  1641. }
  1642. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  1643. //
  1644. //if template.TemplateId == 2 || template.TemplateId == 6 {
  1645. // if appRole.UserType == 3 {
  1646. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1647. // if getPermissionErr != nil {
  1648. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1649. // return
  1650. // } else if headNursePermission == nil {
  1651. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  1652. // return
  1653. // }
  1654. // }
  1655. //}
  1656. prescription := models.DialysisPrescription{
  1657. UserOrgId: adminUserInfo.Org.Id,
  1658. PatientId: id,
  1659. RecordDate: recordDate.Unix(),
  1660. ModeId: mode_id,
  1661. DialysisDuration: dialysis_duration,
  1662. Dialyzer: dialyzer,
  1663. PerfusionApparatus: perfusion_apparatus,
  1664. BloodFlowVolume: blood_flow_volume,
  1665. DewaterAmount: dewater_amount,
  1666. DisplaceLiqui: displace_liqui,
  1667. ReplacementWay: replacement_way,
  1668. Anticoagulant: anticoagulant,
  1669. AnticoagulantShouji: anticoagulant_shouji,
  1670. AnticoagulantWeichi: anticoagulant_weichi,
  1671. AnticoagulantZongliang: anticoagulant_zongliang,
  1672. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  1673. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  1674. Kalium: kalium,
  1675. Sodium: sodium,
  1676. Calcium: calcium,
  1677. Bicarbonate: bicarbonate,
  1678. Glucose: glucose,
  1679. // DryWeight: dry_weight,
  1680. DialysateFlow: dialysate_flow,
  1681. DialysateTemperature: dialysate_temperature,
  1682. Conductivity: conductivity,
  1683. Remark: remark,
  1684. Status: 1,
  1685. CreatedTime: time.Now().Unix(),
  1686. UpdatedTime: time.Now().Unix(),
  1687. DialysisDurationMinute: dialysisDurationMinute,
  1688. DialysisDurationHour: dialysisDurationHour,
  1689. TargetUltrafiltration: targetUltrafiltration,
  1690. DialysateFormulation: dialysateFormulation,
  1691. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  1692. BodyFluid: body_fluid,
  1693. SpecialMedicine: special_medicine,
  1694. SpecialMedicineOther: special_medicine_other,
  1695. DisplaceLiquiPart: displace_liqui_part,
  1696. DisplaceLiquiValue: displace_liqui_value,
  1697. BloodAccess: blood_access,
  1698. Ultrafiltration: ultrafiltration,
  1699. BodyFluidOther: body_fluid_other,
  1700. ReplacementTotal: replacement_total,
  1701. Niprocart: niprocart,
  1702. Jms: jms,
  1703. FistulaNeedleSet: fistula_needle_set,
  1704. FistulaNeedleSet16: fistula_needle_set_16,
  1705. Hemoperfusion: hemoperfusion,
  1706. DialyserSterilised: dialyser_sterilised,
  1707. Filtryzer: filtryzer,
  1708. TargetKtv: target_ktv,
  1709. Dialyzers: dialyzers,
  1710. Injector: injector,
  1711. Bloodlines: bloodlines,
  1712. TubingHemodialysis: tubing_hemodialysis,
  1713. Package: safe_package,
  1714. ALiquid: a_liquid,
  1715. AnticoagulantStopTimeMin: anticoagulant_stop_time_min,
  1716. AnticoagulantStopTimeHour: anticoagulant_stop_time_hour,
  1717. Blood: blood,
  1718. DialysisDialyszers: dialysis_dialyszers,
  1719. DialysisIrrigation: dialysis_irrigation,
  1720. AntioxidantCommodityName: antioxidant_commodity_name,
  1721. }
  1722. _, dialysisPrescription := service.FindDialysisPrescriptionByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  1723. appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id, adminUserInfo.App.Id)
  1724. //
  1725. if appRole.UserType == 2 || appRole.UserType == 1 {
  1726. prescription_doctor = adminUserInfo.AdminUser.Id
  1727. prescription.PrescriptionDoctor = prescription_doctor
  1728. }
  1729. if dialysisPrescription.ID == 0 { //新增
  1730. prescription.Creater = adminUserInfo.AdminUser.Id
  1731. } else { //修改
  1732. if dialysisPrescription.Creater == 0 {
  1733. prescription.Creater = adminUserInfo.AdminUser.Id
  1734. } else {
  1735. prescription.Creater = dialysisPrescription.Creater
  1736. }
  1737. //if/**/
  1738. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  1739. //if dialysisPrescription.Creater != adminUserInfo.AdminUser.Id && dialysisPrescription.Creater > 0 {
  1740. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1741. // if getPermissionErr != nil {
  1742. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1743. // return
  1744. // } else if headNursePermission == nil {
  1745. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  1746. // return
  1747. // }
  1748. //}
  1749. //prescription.Creater = dialysisPrescription.Creater
  1750. prescription.CreatedTime = dialysisPrescription.CreatedTime
  1751. prescription.Modifier = adminUserInfo.AdminUser.Id
  1752. prescription.ID = dialysisPrescription.ID
  1753. }
  1754. solution := models.DialysisSolution{
  1755. RegistrarsId: adminUserInfo.AdminUser.Id,
  1756. UserOrgId: adminUserInfo.Org.Id,
  1757. Doctor: prescription_doctor,
  1758. PatientId: id,
  1759. ModeId: mode_id,
  1760. DialysisDuration: dialysis_duration,
  1761. PerfusionApparatus: perfusion_apparatus,
  1762. BloodFlowVolume: blood_flow_volume,
  1763. Dewater: dewater_amount,
  1764. DisplaceLiqui: displace_liqui,
  1765. ReplacementWay: replacement_way,
  1766. Anticoagulant: anticoagulant,
  1767. AnticoagulantShouji: anticoagulant_shouji,
  1768. AnticoagulantWeichi: anticoagulant_weichi,
  1769. AnticoagulantZongliang: anticoagulant_zongliang,
  1770. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  1771. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  1772. Kalium: kalium,
  1773. Sodium: sodium,
  1774. Calcium: calcium,
  1775. Bicarbonate: bicarbonate,
  1776. Glucose: glucose,
  1777. // DryWeight: dry_weight,
  1778. DialysateFlow: dialysate_flow,
  1779. DialysateTemperature: dialysate_temperature,
  1780. Conductivity: conductivity,
  1781. Remark: remark,
  1782. Status: 1,
  1783. CreatedTime: time.Now().Unix(),
  1784. UpdatedTime: time.Now().Unix(),
  1785. DialysisDurationMinute: dialysisDurationMinute,
  1786. DialysisDurationHour: dialysisDurationHour,
  1787. TargetUltrafiltration: targetUltrafiltration,
  1788. DialysateFormulation: dialysateFormulation,
  1789. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  1790. BodyFluid: body_fluid,
  1791. SpecialMedicine: special_medicine,
  1792. SpecialMedicineOther: special_medicine_other,
  1793. DisplaceLiquiPart: displace_liqui_part,
  1794. DisplaceLiquiValue: displace_liqui_value,
  1795. BloodAccess: blood_access,
  1796. Ultrafiltration: ultrafiltration,
  1797. BodyFluidOther: body_fluid_other,
  1798. ReplacementTotal: replacement_total,
  1799. TargetKtv: target_ktv,
  1800. }
  1801. service.SavePrescriptionAndCreateSolution(&solution, &prescription)
  1802. c.ServeSuccessJSON(map[string]interface{}{
  1803. "solution": &solution,
  1804. "prescription": &prescription,
  1805. })
  1806. }
  1807. func (c *DialysisAPIController) GetAcceptsAssessment() {
  1808. patient, _ := c.GetInt64("patient", 0)
  1809. adminUserInfo := c.GetMobileAdminUserInfo()
  1810. _, receiveTreatmentAsses := service.GetLastAcceptsAssessment(patient, adminUserInfo.Org.Id)
  1811. c.ServeSuccessJSON(map[string]interface{}{
  1812. "receiveTreatmentAsses": receiveTreatmentAsses,
  1813. })
  1814. }
  1815. func (this *DialysisAPIController) PostSignInfo() {
  1816. patientID, _ := this.GetInt64("patient_id")
  1817. recordDateStr := this.GetString("date")
  1818. if patientID <= 0 {
  1819. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1820. return
  1821. }
  1822. if len(recordDateStr) == 0 {
  1823. recordDateStr = time.Now().Format("2006-01-02")
  1824. }
  1825. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1826. if parseDateErr != nil {
  1827. this.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  1828. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1829. return
  1830. }
  1831. adminInfo := this.GetMobileAdminUserInfo()
  1832. err := service.UpDateDialysisPrescriptionDoctorSign(patientID, date.Unix(), adminInfo.Org.Id, adminInfo.AdminUser.Id)
  1833. if err != nil {
  1834. this.ErrorLog("签名失败:%v", err)
  1835. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1836. return
  1837. }
  1838. this.ServeSuccessJSON(map[string]interface{}{
  1839. "doctor_id": adminInfo.AdminUser.Id,
  1840. })
  1841. }
  1842. func (this *DialysisAPIController) GetLastMonitorRecord() {
  1843. patientID, _ := this.GetInt64("patient_id")
  1844. adminInfo := this.GetMobileAdminUserInfo()
  1845. record, _ := service.FindLastMonitorRecord(patientID, adminInfo.Org.Id)
  1846. this.ServeSuccessJSON(map[string]interface{}{
  1847. "monitor": record,
  1848. })
  1849. }
  1850. func (this *DialysisAPIController) GetLastMonitorRecordTody() {
  1851. thisTime := time.Now()
  1852. scheduleDateStart := thisTime.Format("2006-01-02") + " 00:00:00"
  1853. timeLayout := "2006-01-02 15:04:05"
  1854. loc, _ := time.LoadLocation("Local")
  1855. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  1856. theAssessmentDateTime := theStartTime.Unix()
  1857. patientID, _ := this.GetInt64("patient_id")
  1858. monitorDate, _ := this.GetInt64("monitoring_date", theAssessmentDateTime)
  1859. adminInfo := this.GetMobileAdminUserInfo()
  1860. record, _ := service.FindLastMonitorRecordToday(patientID, adminInfo.Org.Id, monitorDate)
  1861. fristrecord, _ := service.FindFirstMonitorRecordToday(patientID, adminInfo.Org.Id, monitorDate)
  1862. template, _ := service.GetOrgInfoTemplate(adminInfo.Org.Id)
  1863. var ultrafiltration_rate float64
  1864. _, prescription := service.FindDialysisPrescriptionByReordDate(patientID, theAssessmentDateTime, adminInfo.Org.Id)
  1865. if prescription.ID > 0 {
  1866. fmt.Println("444444444")
  1867. if prescription.TargetUltrafiltration > 0 && prescription.DialysisDurationHour > 0 {
  1868. fmt.Println("4444444445555")
  1869. totalMin := prescription.DialysisDurationHour*60 + prescription.DialysisDurationMinute
  1870. if template.TemplateId == 6 || template.TemplateId == 32 {
  1871. fmt.Println("12222222")
  1872. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1000)
  1873. record.UltrafiltrationRate = ultrafiltration_rate
  1874. }
  1875. if template.TemplateId == 20 || template.TemplateId == 22 {
  1876. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60)
  1877. record.UltrafiltrationRate = ultrafiltration_rate
  1878. }
  1879. // 只针对方济医院
  1880. if template.TemplateId == 1 && adminInfo.Org.Id != 9849 {
  1881. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", prescription.TargetUltrafiltration/float64(totalMin)*60), 6)
  1882. ultrafiltration_rate = value
  1883. record.UltrafiltrationRate = ultrafiltration_rate
  1884. }
  1885. }
  1886. }
  1887. // record.UltrafiltrationRate = ultrafiltration_rate
  1888. record.UltrafiltrationVolume = 0
  1889. if template.TemplateId == 1 && adminInfo.Org.Id != 9849 { //adminInfo.Org.Id == 3907 || adminInfo.Org.Id == 4 || adminInfo.Org.Id == 12 || adminInfo.Org.Id == 13 || adminInfo.Org.Id == 9535adminInfo.Org.Id == 3907 || adminInfo.Org.Id == 4 || adminInfo.Org.Id == 12 || adminInfo.Org.Id == 13 || adminInfo.Org.Id == 9535
  1890. if ultrafiltration_rate > 0 {
  1891. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", float64(record.OperateTime+3600-fristrecord.OperateTime)/3600*ultrafiltration_rate), 6)
  1892. record.UltrafiltrationVolume = value
  1893. }
  1894. }
  1895. if template.TemplateId == 6 || template.TemplateId == 20 || template.TemplateId == 22 || template.TemplateId == 32 { //adminInfo.Org.Id == 9538
  1896. if ultrafiltration_rate > 0 && adminInfo.Org.Id != 9538 {
  1897. ultrafiltration_volume := math.Floor(float64(record.OperateTime+3600-fristrecord.OperateTime) / 3600 * ultrafiltration_rate)
  1898. record.UltrafiltrationVolume = ultrafiltration_volume
  1899. }
  1900. }
  1901. this.ServeSuccessJSON(map[string]interface{}{
  1902. "monitor": record,
  1903. })
  1904. }
  1905. func (this *DialysisAPIController) ModifyStartDialysisOrder() {
  1906. record_id, _ := this.GetInt64("id")
  1907. nurseID, _ := this.GetInt64("nurse")
  1908. puncture_nurse, _ := this.GetInt64("puncture_nurse")
  1909. bedID, _ := this.GetInt64("bed")
  1910. start_time := this.GetString("start_time")
  1911. schedual_type, _ := this.GetInt64("schedual_type")
  1912. washpipe_nurse, _ := this.GetInt64("washpipe_nurse")
  1913. change_nurse, _ := this.GetInt64("change_nurse")
  1914. if record_id == 0 {
  1915. this.ErrorLog("id:%v", record_id)
  1916. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1917. return
  1918. }
  1919. startDate, parseStartDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", start_time)
  1920. if parseStartDateErr != nil {
  1921. this.ErrorLog("时间解析失败:%v", parseStartDateErr)
  1922. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1923. return
  1924. }
  1925. adminUserInfo := this.GetMobileAdminUserInfo()
  1926. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  1927. if getNurseErr != nil {
  1928. this.ErrorLog("获取护士失败:%v", getNurseErr)
  1929. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1930. return
  1931. } else if nurse == nil {
  1932. this.ErrorLog("护士不存在")
  1933. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1934. return
  1935. }
  1936. nurse, getNurseErr = service.GetAdminUserByUserID(puncture_nurse)
  1937. if getNurseErr != nil {
  1938. this.ErrorLog("获取护士失败:%v", getNurseErr)
  1939. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1940. return
  1941. } else if nurse == nil {
  1942. this.ErrorLog("护士不存在")
  1943. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1944. return
  1945. }
  1946. deviceNumber, getDeviceNumberErr := service.GetDeviceNumberByID(adminUserInfo.Org.Id, bedID)
  1947. if getDeviceNumberErr != nil {
  1948. this.ErrorLog("获取床位号失败:%v", getDeviceNumberErr)
  1949. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1950. return
  1951. } else if deviceNumber == nil {
  1952. this.ErrorLog("床位号不存在")
  1953. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1954. return
  1955. }
  1956. _, tempDialysisRecord := service.FindDialysisOrderById(record_id)
  1957. //
  1958. //if tempDialysisRecord.Creator != adminUserInfo.AdminUser.Id {
  1959. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1960. // if getPermissionErr != nil {
  1961. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1962. // return
  1963. // } else if headNursePermission == nil {
  1964. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  1965. // return
  1966. // }
  1967. //}
  1968. scheduleDateStart := startDate.Format("2006-01-02") + " 00:00:00"
  1969. scheduleDateEnd := startDate.Format("2006-01-02") + " 23:59:59"
  1970. timeLayout := "2006-01-02 15:04:05"
  1971. loc, _ := time.LoadLocation("Local")
  1972. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  1973. theEndTime, _ := time.ParseInLocation(timeLayout, scheduleDateEnd, loc)
  1974. schedulestartTime := theStartTime.Unix()
  1975. scheduleendTime := theEndTime.Unix()
  1976. //查询更改的机号,是否有人用了,如果只是排班了,但是没上机,直接替换,如果排班且上机了,就提示他无法上机
  1977. schedule, err := service.GetDayScheduleByBedid(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  1978. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  1979. if daySchedule.BedId != bedID || daySchedule.ScheduleType != schedual_type {
  1980. if err == gorm.ErrRecordNotFound { //空床位
  1981. // 修改了床位逻辑
  1982. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  1983. if daySchedule.ID > 0 {
  1984. daySchedule.BedId = bedID
  1985. daySchedule.PartitionId = deviceNumber.ZoneID
  1986. daySchedule.ScheduleType = schedual_type
  1987. daySchedule.UpdatedTime = time.Now().Unix()
  1988. err := service.UpdateSchedule(&daySchedule)
  1989. if err != nil {
  1990. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1991. return
  1992. }
  1993. }
  1994. } else if err == nil {
  1995. if schedule.ID > 0 && schedule.DialysisOrder.ID == 0 { //有排班没上机记录
  1996. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  1997. if daySchedule.ID > 0 {
  1998. daySchedule.BedId = bedID
  1999. daySchedule.PartitionId = deviceNumber.ZoneID
  2000. daySchedule.ScheduleType = schedual_type
  2001. daySchedule.UpdatedTime = time.Now().Unix()
  2002. err := service.UpdateSchedule(&daySchedule)
  2003. if err != nil {
  2004. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2005. return
  2006. }
  2007. }
  2008. } else if schedule.ID > 0 && schedule.DialysisOrder.ID > 0 { //有排班且有上机记录
  2009. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  2010. return
  2011. }
  2012. } else if err != nil {
  2013. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2014. return
  2015. }
  2016. }
  2017. dialysisRecord := &models.DialysisOrder{
  2018. ID: record_id,
  2019. UserOrgId: adminUserInfo.Org.Id,
  2020. BedID: bedID,
  2021. StartNurse: nurseID,
  2022. StartTime: startDate.Unix(),
  2023. PunctureNurse: puncture_nurse,
  2024. Creator: adminUserInfo.AdminUser.Id,
  2025. Modifier: adminUserInfo.AdminUser.Id,
  2026. WashpipeNurse: washpipe_nurse,
  2027. SchedualType: schedual_type,
  2028. ChangeNurse: change_nurse,
  2029. }
  2030. updateErr := service.ModifyStartDialysisOrder(dialysisRecord)
  2031. if updateErr != nil {
  2032. this.ErrorLog("修改上机失败:%v", updateErr)
  2033. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2034. return
  2035. }
  2036. if updateErr == nil {
  2037. if tempDialysisRecord.Stage == 2 {
  2038. temp_time := (float64(tempDialysisRecord.EndTime) - float64(startDate.Unix())) / 3600
  2039. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  2040. fmt.Println(value)
  2041. a, b := math.Modf(value)
  2042. tempMinute, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  2043. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  2044. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", tempMinute*60), 10, 64)
  2045. updateAssessmentErr := service.UpdateAssessmentAfterDate(tempDialysisRecord.PatientId, tempDialysisRecord.UserOrgId, tempDialysisRecord.DialysisDate, hour, minute)
  2046. if updateAssessmentErr != nil {
  2047. utils.ErrorLog("%v", updateAssessmentErr)
  2048. }
  2049. }
  2050. }
  2051. _, dialysisRecords := service.FindDialysisOrderById(record_id)
  2052. this.ServeSuccessJSON(map[string]interface{}{
  2053. "dialysis_order": dialysisRecords,
  2054. })
  2055. }
  2056. func (c *DialysisAPIController) ModifyFinishDialysisOrder() {
  2057. record_id, _ := c.GetInt64("id")
  2058. nurseID, _ := c.GetInt64("nurse")
  2059. end_time := c.GetString("end_time")
  2060. if record_id <= 0 || nurseID <= 0 {
  2061. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2062. return
  2063. }
  2064. adminUserInfo := c.GetMobileAdminUserInfo()
  2065. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  2066. if getNurseErr != nil {
  2067. c.ErrorLog("获取护士失败:%v", getNurseErr)
  2068. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2069. return
  2070. } else if nurse == nil {
  2071. c.ErrorLog("护士不存在")
  2072. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2073. return
  2074. }
  2075. endDate, parseEndDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", end_time)
  2076. if parseEndDateErr != nil {
  2077. c.ErrorLog("日期(%v)解析错误:%v", end_time, parseEndDateErr)
  2078. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2079. return
  2080. }
  2081. _, tempDialysisRecords := service.FindDialysisOrderById(record_id)
  2082. //if tempDialysisRecords.FinishCreator != adminUserInfo.AdminUser.Id {
  2083. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  2084. // if getPermissionErr != nil {
  2085. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2086. // return
  2087. // } else if headNursePermission == nil {
  2088. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  2089. // return
  2090. // }
  2091. //}
  2092. dialysisRecord := &models.DialysisOrder{
  2093. ID: record_id,
  2094. UserOrgId: adminUserInfo.Org.Id,
  2095. EndTime: endDate.Unix(),
  2096. FinishNurse: nurseID,
  2097. FinishModifier: adminUserInfo.AdminUser.Id,
  2098. }
  2099. updateErr := service.ModifyFinishDialysisOrder(dialysisRecord)
  2100. if updateErr != nil {
  2101. c.ErrorLog("修改下机失败:%v", updateErr)
  2102. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2103. return
  2104. }
  2105. if updateErr == nil {
  2106. temp_time := (float64(endDate.Unix()) - float64(tempDialysisRecords.StartTime)) / 3600
  2107. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  2108. a, b := math.Modf(value)
  2109. tempMinute, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  2110. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  2111. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", tempMinute*60), 10, 64)
  2112. updateAssessmentErr := service.UpdateAssessmentAfterDate(tempDialysisRecords.PatientId, tempDialysisRecords.UserOrgId, tempDialysisRecords.DialysisDate, hour, minute)
  2113. if updateAssessmentErr != nil {
  2114. utils.ErrorLog("%v", updateAssessmentErr)
  2115. }
  2116. }
  2117. _, dialysisRecords := service.FindDialysisOrderById(record_id)
  2118. c.ServeSuccessJSON(map[string]interface{}{
  2119. "dialysis_order": dialysisRecords,
  2120. })
  2121. }
  2122. func (c *DialysisAPIController) GetLongAdvice() {
  2123. patient_id, _ := c.GetInt64("id")
  2124. adminUserInfo := c.GetMobileAdminUserInfo()
  2125. _, config := service.FindDoctorAdviceRecordByOrgId(adminUserInfo.Org.Id)
  2126. //patient, _ := service.FindPatientIsOpenRemindById(patient_id, adminUserInfo.Org.Id)
  2127. if config.IsOpenRemind == 0 { //针对老用户,即没开启推送功能,也没有 不开启推送功能,不做任何处理
  2128. c.ServeSuccessJSON(map[string]interface{}{
  2129. "status": "1",
  2130. })
  2131. return
  2132. } else { //开启推送提醒
  2133. //开启推送提醒逻辑 提交长期处方的时候,弹起长期医嘱推送
  2134. var advice_three []*models.DoctorAdvice
  2135. //groupNo := service.GetMaxLongAdviceGroupID(adminUserInfo.Org.Id, patient_id)
  2136. advices, err := service.GetLastLongAdviceByGroupNo(adminUserInfo.Org.Id, patient_id)
  2137. advices_two, err := service.GetLastLongAdviceByGroupNoThree(adminUserInfo.Org.Id, patient_id)
  2138. for _, advice := range advices {
  2139. if advice.FrequencyType == 3 {
  2140. t := time.Now()
  2141. week := int(t.Weekday())
  2142. fmt.Println(t.Weekday())
  2143. fmt.Println(week)
  2144. switch week {
  2145. case 1:
  2146. if strings.Index(advice.WeekDay, "周一") == -1 {
  2147. advice_three = append(advice_three, advice)
  2148. }
  2149. break
  2150. case 2:
  2151. if strings.Index(advice.WeekDay, "周二") == -1 {
  2152. advice_three = append(advice_three, advice)
  2153. }
  2154. break
  2155. case 3:
  2156. if strings.Index(advice.WeekDay, "周三") == -1 {
  2157. advice_three = append(advice_three, advice)
  2158. }
  2159. break
  2160. case 4:
  2161. if strings.Index(advice.WeekDay, "周四") == -1 {
  2162. advice_three = append(advice_three, advice)
  2163. }
  2164. break
  2165. case 5:
  2166. if strings.Index(advice.WeekDay, "周五") == -1 {
  2167. advice_three = append(advice_three, advice)
  2168. }
  2169. break
  2170. case 6:
  2171. if strings.Index(advice.WeekDay, "周六") == -1 {
  2172. advice_three = append(advice_three, advice)
  2173. }
  2174. break
  2175. case 0:
  2176. if strings.Index(advice.WeekDay, "周日") == -1 {
  2177. advice_three = append(advice_three, advice)
  2178. }
  2179. break
  2180. }
  2181. }
  2182. }
  2183. for _, advice := range advices_two {
  2184. p, _ := time.Parse("2006-01-02", time.Now().Format("2006-01-02"))
  2185. now := p.Unix()
  2186. dayStr := strconv.FormatInt(advice.DayCount, 10)
  2187. dayStr2 := "-" + dayStr
  2188. count, _ := strconv.ParseInt(dayStr2, 10, 64)
  2189. oldTime := time.Now().AddDate(0, 0, int(count)).Unix()
  2190. advices, _ := service.FindAllDoctorAdviceByTime(now, oldTime, patient_id, adminUserInfo.Org.Id, advice.TemplateId)
  2191. for _, ad := range advices {
  2192. advice_three = append(advice_three, ad)
  2193. }
  2194. }
  2195. if err == nil {
  2196. c.ServeSuccessJSON(map[string]interface{}{
  2197. "status": "2",
  2198. "advices": advices,
  2199. "advices_two": RemoveRepeatedElement(advice_three),
  2200. "is_open_remind": config.IsOpenRemind,
  2201. })
  2202. }
  2203. }
  2204. }
  2205. func RemoveRepeatedElement(arr []*models.DoctorAdvice) (newArr []*models.DoctorAdvice) {
  2206. newArr = make([]*models.DoctorAdvice, 0)
  2207. for i := 0; i < len(arr); i++ {
  2208. repeat := false
  2209. for j := i + 1; j < len(arr); j++ {
  2210. if arr[i].ID == arr[j].ID {
  2211. repeat = true
  2212. break
  2213. }
  2214. }
  2215. if !repeat {
  2216. newArr = append(newArr, arr[i])
  2217. }
  2218. }
  2219. return
  2220. }
  2221. func (c *DialysisAPIController) CreateRemindDoctorAdvice() {
  2222. patient, _ := c.GetInt64("id", 0)
  2223. groupNo, _ := c.GetInt64("groupno", 0)
  2224. if patient <= 0 {
  2225. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2226. return
  2227. }
  2228. adminUserInfo := c.GetMobileAdminUserInfo()
  2229. dataBody := make(map[string]interface{}, 0)
  2230. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  2231. if err != nil {
  2232. utils.ErrorLog(err.Error())
  2233. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2234. return
  2235. }
  2236. utils.ErrorLog("%v", dataBody)
  2237. timeLayout := "2006-01-02 15:04"
  2238. loc, _ := time.LoadLocation("Local")
  2239. timeLayout2 := "2006-01-02"
  2240. loc2, _ := time.LoadLocation("Local")
  2241. if dataBody["advice_type"] == nil || reflect.TypeOf(dataBody["advice_type"]).String() != "float64" {
  2242. utils.ErrorLog("advice_type")
  2243. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2244. return
  2245. }
  2246. adviceType := int64(2)
  2247. if dataBody["advice_date"] == nil || reflect.TypeOf(dataBody["advice_date"]).String() != "string" {
  2248. utils.ErrorLog("advice_date")
  2249. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2250. return
  2251. }
  2252. adviceDate, _ := dataBody["advice_date"].(string)
  2253. theTime, err := time.ParseInLocation(timeLayout2, adviceDate, loc2)
  2254. AdviceDate := theTime.Unix()
  2255. RecordDate := theTime.Unix()
  2256. if dataBody["start_time"] == nil || reflect.TypeOf(dataBody["start_time"]).String() != "string" {
  2257. utils.ErrorLog("start_time")
  2258. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2259. return
  2260. }
  2261. startTime, _ := dataBody["start_time"].(string)
  2262. if len(startTime) == 0 {
  2263. utils.ErrorLog("len(start_time) == 0")
  2264. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2265. return
  2266. }
  2267. theTime, err = time.ParseInLocation(timeLayout, startTime, loc)
  2268. if err != nil {
  2269. utils.ErrorLog(err.Error())
  2270. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2271. return
  2272. }
  2273. StartTime := theTime.Unix()
  2274. Remark := ""
  2275. if dataBody["remark"] != nil && reflect.TypeOf(dataBody["remark"]).String() == "string" {
  2276. remark, _ := dataBody["remark"].(string)
  2277. Remark = remark
  2278. }
  2279. var advices []*models.GroupAdvice
  2280. if dataBody["advices"] == nil || reflect.TypeOf(dataBody["advices"]).String() != "[]interface {}" {
  2281. utils.ErrorLog("advices")
  2282. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2283. return
  2284. }
  2285. adviceNames := dataBody["advices"].([]interface{})
  2286. for _, adviceNameMap := range adviceNames {
  2287. adviceNameM := adviceNameMap.(map[string]interface{})
  2288. var advice models.GroupAdvice
  2289. advice.Remark = Remark
  2290. advice.AdviceType = adviceType
  2291. advice.StartTime = StartTime
  2292. advice.AdviceDate = AdviceDate
  2293. advice.RecordDate = RecordDate
  2294. advice.Status = 1
  2295. advice.CreatedTime = time.Now().Unix()
  2296. advice.UpdatedTime = time.Now().Unix()
  2297. advice.StopState = 2
  2298. advice.ExecutionState = 2
  2299. advice.UserOrgId = adminUserInfo.Org.Id
  2300. advice.PatientId = patient
  2301. advice.AdviceDoctor = adminUserInfo.AdminUser.Id
  2302. if adviceNameM["advice_name"] == nil || reflect.TypeOf(adviceNameM["advice_name"]).String() != "string" {
  2303. utils.ErrorLog("advice_name")
  2304. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2305. return
  2306. }
  2307. adviceName, _ := adviceNameM["advice_name"].(string)
  2308. if len(adviceName) == 0 {
  2309. utils.ErrorLog("len(advice_name) == 0")
  2310. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2311. return
  2312. }
  2313. advice.AdviceName = adviceName
  2314. if adviceNameM["drug_spec"] != nil && reflect.TypeOf(adviceNameM["drug_spec"]).String() == "string" {
  2315. drugSpec, _ := strconv.ParseFloat(adviceNameM["drug_spec"].(string), 64)
  2316. advice.DrugSpec = drugSpec
  2317. }
  2318. if adviceNameM["advice_desc"] != nil && reflect.TypeOf(adviceNameM["advice_desc"]).String() == "string" {
  2319. adviceDesc, _ := adviceNameM["advice_desc"].(string)
  2320. advice.AdviceDesc = adviceDesc
  2321. }
  2322. if adviceNameM["drug_spec_unit"] != nil && reflect.TypeOf(adviceNameM["drug_spec_unit"]).String() == "string" {
  2323. drugSpecUnit, _ := adviceNameM["drug_spec_unit"].(string)
  2324. advice.DrugSpecUnit = drugSpecUnit
  2325. }
  2326. //if adviceNameM["single_dose"] != nil && reflect.TypeOf(adviceNameM["single_dose"]).String() == "string" {
  2327. // singleDose, _ := strconv.ParseFloat(adviceNameM["single_dose"].(string), 64)
  2328. // advice.SingleDose = singleDose
  2329. //}
  2330. if adviceNameM["single_dose"] != nil || reflect.TypeOf(adviceNameM["single_dose"]).String() == "float64" {
  2331. //single_dose := int64(adviceNameM["single_dose"].(float64))
  2332. advice.SingleDose = adviceNameM["single_dose"].(float64)
  2333. }
  2334. if adviceNameM["single_dose_unit"] != nil && reflect.TypeOf(adviceNameM["single_dose_unit"]).String() == "string" {
  2335. singleDoseUnit, _ := adviceNameM["single_dose_unit"].(string)
  2336. advice.SingleDoseUnit = singleDoseUnit
  2337. }
  2338. //if adviceNameM["prescribing_number"] != nil && reflect.TypeOf(adviceNameM["prescribing_number"]).String() == "string" {
  2339. // prescribingNumber, _ := strconv.ParseFloat(adviceNameM["prescribing_number"].(string), 64)
  2340. // advice.PrescribingNumber = prescribingNumber
  2341. //}
  2342. if adviceNameM["prescribing_number"] != nil || reflect.TypeOf(adviceNameM["prescribing_number"]).String() == "float64" {
  2343. //single_dose := int64(adviceNameM["single_dose"].(float64))
  2344. advice.PrescribingNumber = adviceNameM["prescribing_number"].(float64)
  2345. }
  2346. if adviceNameM["prescribing_number_unit"] != nil && reflect.TypeOf(adviceNameM["prescribing_number_unit"]).String() == "string" {
  2347. prescribingNumberUnit, _ := adviceNameM["prescribing_number_unit"].(string)
  2348. advice.PrescribingNumberUnit = prescribingNumberUnit
  2349. }
  2350. if adviceNameM["delivery_way"] != nil && reflect.TypeOf(adviceNameM["delivery_way"]).String() == "string" {
  2351. deliveryWay, _ := adviceNameM["delivery_way"].(string)
  2352. advice.DeliveryWay = deliveryWay
  2353. }
  2354. if adviceNameM["execution_frequency"] != nil && reflect.TypeOf(adviceNameM["execution_frequency"]).String() == "string" {
  2355. executionFrequency, _ := adviceNameM["execution_frequency"].(string)
  2356. advice.ExecutionFrequency = executionFrequency
  2357. }
  2358. if adviceNameM["frequency_type"] != nil || reflect.TypeOf(adviceNameM["frequency_type"]).String() == "float64" {
  2359. frequency_type := int64(adviceNameM["frequency_type"].(float64))
  2360. advice.FrequencyType = frequency_type
  2361. }
  2362. if adviceNameM["day_count"] != nil || reflect.TypeOf(adviceNameM["day_count"]).String() == "float64" {
  2363. day_count := int64(adviceNameM["day_count"].(float64))
  2364. advice.DayCount = day_count
  2365. }
  2366. if adviceNameM["week_day"] != nil && reflect.TypeOf(adviceNameM["week_day"]).String() == "string" {
  2367. week_day, _ := adviceNameM["week_day"].(string)
  2368. advice.WeekDay = week_day
  2369. }
  2370. if adviceNameM["way"] != nil || reflect.TypeOf(adviceNameM["way"]).String() == "float64" {
  2371. way := int64(adviceNameM["way"].(float64))
  2372. advice.Way = way
  2373. }
  2374. if adviceNameM["drug_id"] != nil || reflect.TypeOf(adviceNameM["drug_id"]).String() == "float64" {
  2375. drug_id := int64(adviceNameM["drug_id"].(float64))
  2376. advice.DrugId = drug_id
  2377. }
  2378. if adviceNameM["drug_name_id"] != nil || reflect.TypeOf(adviceNameM["drug_name_id"]).String() == "float64" {
  2379. drug_name_id := int64(adviceNameM["drug_name_id"].(float64))
  2380. advice.DrugNameId = drug_name_id
  2381. }
  2382. if adviceNameM["template_id"] != nil && reflect.TypeOf(adviceNameM["template_id"]).String() == "string" {
  2383. template_id, _ := adviceNameM["template_id"].(string)
  2384. advice.TemplateId = template_id
  2385. }
  2386. if adviceNameM["child"] != nil && reflect.TypeOf(adviceNameM["child"]).String() == "string" {
  2387. executionFrequency, _ := adviceNameM["execution_frequency"].(string)
  2388. advice.ExecutionFrequency = executionFrequency
  2389. }
  2390. if adviceNameM["child"] != nil && reflect.TypeOf(adviceNameM["child"]).String() == "[]interface {}" {
  2391. children := adviceNameM["child"].([]interface{})
  2392. if len(children) > 0 {
  2393. for _, childrenMap := range children {
  2394. childMap := childrenMap.(map[string]interface{})
  2395. var child models.GroupAdvice
  2396. child.Remark = Remark
  2397. child.AdviceType = adviceType
  2398. child.StartTime = StartTime
  2399. child.AdviceDate = AdviceDate
  2400. child.RecordDate = RecordDate
  2401. child.Status = 1
  2402. child.CreatedTime = time.Now().Unix()
  2403. child.UpdatedTime = time.Now().Unix()
  2404. child.StopState = 2
  2405. child.ExecutionState = 2
  2406. child.UserOrgId = adminUserInfo.Org.Id
  2407. child.PatientId = patient
  2408. child.AdviceDoctor = adminUserInfo.AdminUser.Id
  2409. if childMap["advice_name"] == nil || reflect.TypeOf(childMap["advice_name"]).String() != "string" {
  2410. utils.ErrorLog("child advice_name")
  2411. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2412. return
  2413. }
  2414. childAdviceName, _ := childMap["advice_name"].(string)
  2415. if len(childAdviceName) == 0 {
  2416. utils.ErrorLog("len(child advice_name) == 0")
  2417. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2418. return
  2419. }
  2420. child.AdviceName = childAdviceName
  2421. if childMap["advice_desc"] != nil && reflect.TypeOf(childMap["advice_desc"]).String() == "string" {
  2422. childAdviceDesc, _ := childMap["advice_desc"].(string)
  2423. child.AdviceDesc = childAdviceDesc
  2424. }
  2425. if childMap["drug_spec"] != nil && reflect.TypeOf(childMap["drug_spec"]).String() == "string" {
  2426. childDrugSpec, _ := strconv.ParseFloat(childMap["drug_spec"].(string), 64)
  2427. child.DrugSpec = childDrugSpec
  2428. }
  2429. if childMap["drug_spec_unit"] != nil && reflect.TypeOf(childMap["drug_spec_unit"]).String() == "string" {
  2430. childDrugSpecUnit, _ := childMap["drug_spec_unit"].(string)
  2431. child.DrugSpecUnit = childDrugSpecUnit
  2432. }
  2433. if childMap["single_dose"] != nil && reflect.TypeOf(childMap["single_dose"]).String() == "float64" {
  2434. child.SingleDose = childMap["single_dose"].(float64)
  2435. }
  2436. if childMap["single_dose_unit"] != nil && reflect.TypeOf(childMap["single_dose_unit"]).String() == "string" {
  2437. childSingleDoseUnit, _ := childMap["single_dose_unit"].(string)
  2438. child.SingleDoseUnit = childSingleDoseUnit
  2439. }
  2440. if childMap["prescribing_number"] != nil && reflect.TypeOf(childMap["prescribing_number"]).String() == "float64" {
  2441. child.PrescribingNumber = childMap["prescribing_number"].(float64)
  2442. }
  2443. if childMap["prescribing_number_unit"] != nil && reflect.TypeOf(childMap["prescribing_number_unit"]).String() == "string" {
  2444. childPrescribingNumberUnit, _ := childMap["prescribing_number_unit"].(string)
  2445. child.PrescribingNumberUnit = childPrescribingNumberUnit
  2446. }
  2447. child.DeliveryWay = advice.DeliveryWay
  2448. child.ExecutionFrequency = advice.ExecutionFrequency
  2449. advice.Children = append(advice.Children, &child)
  2450. }
  2451. }
  2452. }
  2453. advices = append(advices, &advice)
  2454. }
  2455. list, err := service.CreateMGroupAdvice(adminUserInfo.Org.Id, advices, groupNo)
  2456. if err != nil {
  2457. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateDoctorAdviceFail)
  2458. return
  2459. }
  2460. c.ServeSuccessJSON(map[string]interface{}{
  2461. "msg": "ok",
  2462. "advices": list,
  2463. })
  2464. return
  2465. }
  2466. func (c *DialysisAPIController) UploadDryWeight() {
  2467. patient_id, _ := c.GetInt64("id")
  2468. dry_weight, _ := c.GetFloat("dry_weight")
  2469. doctor_id, _ := c.GetInt64("doctor_id")
  2470. remark := c.GetString("remark")
  2471. adminUserInfo := c.GetMobileAdminUserInfo()
  2472. weightAdjust, err := service.FindLastDryWeightAdjust(adminUserInfo.Org.Id, patient_id)
  2473. if err == gorm.ErrRecordNotFound {
  2474. dryWeight := &models.SgjPatientDryweight{
  2475. PatientId: patient_id,
  2476. DryWeight: dry_weight,
  2477. Remakes: remark,
  2478. Ctime: time.Now().Unix(),
  2479. Mtime: time.Now().Unix(),
  2480. Creator: doctor_id,
  2481. Status: 1,
  2482. UserOrgId: adminUserInfo.Org.Id,
  2483. AdjustedValue: "/",
  2484. UserId: adminUserInfo.AdminUser.Id,
  2485. }
  2486. createErr := service.CreatePatientWeightAdjust(dryWeight)
  2487. if createErr == nil {
  2488. c.ServeSuccessJSON(map[string]interface{}{
  2489. "msg": "提交成功",
  2490. "weight": dryWeight,
  2491. })
  2492. }
  2493. } else {
  2494. dryWeight := &models.SgjPatientDryweight{
  2495. PatientId: patient_id,
  2496. DryWeight: dry_weight,
  2497. Remakes: remark,
  2498. Ctime: time.Now().Unix(),
  2499. Mtime: time.Now().Unix(),
  2500. Creator: doctor_id,
  2501. Status: 1,
  2502. UserOrgId: adminUserInfo.Org.Id,
  2503. AdjustedValue: "/",
  2504. UserId: adminUserInfo.AdminUser.Id,
  2505. }
  2506. var value float64
  2507. value = dry_weight - weightAdjust.DryWeight
  2508. if value < 0 {
  2509. dryWeight.AdjustedValue = strconv.FormatFloat(math.Abs(value), 'f', 1, 64) + "(下调)"
  2510. } else if value == 0 {
  2511. dryWeight.AdjustedValue = "/"
  2512. } else if value > 0 {
  2513. dryWeight.AdjustedValue = strconv.FormatFloat(value, 'f', 1, 64) + "(上调)"
  2514. }
  2515. createErr := service.CreatePatientWeightAdjust(dryWeight)
  2516. if createErr == nil {
  2517. c.ServeSuccessJSON(map[string]interface{}{
  2518. "msg": "提交成功",
  2519. "weight": dryWeight,
  2520. })
  2521. }
  2522. }
  2523. }
  2524. func (c *DialysisAPIController) GetSolution() {
  2525. patient_id, _ := c.GetInt64("patient_id")
  2526. mode_id, _ := c.GetInt64("mode_id")
  2527. adminUserInfo := c.GetMobileAdminUserInfo()
  2528. solution, err := service.MobileGetDialysisSolutionByModeId(adminUserInfo.Org.Id, patient_id, mode_id)
  2529. prescription, err := service.MobileGetLastDialysisPrescribeByModeId(adminUserInfo.Org.Id, patient_id, mode_id)
  2530. system_prescription, err := service.MobileGetSystemDialysisPrescribeByModeId(adminUserInfo.Org.Id, mode_id)
  2531. if err != nil {
  2532. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  2533. return
  2534. }
  2535. c.ServeSuccessJSON(map[string]interface{}{
  2536. "solution": solution,
  2537. "prescription": prescription,
  2538. "system_prescription": system_prescription,
  2539. })
  2540. }
  2541. func (c *DialysisAPIController) GetSchedule() {
  2542. schedual_type, _ := c.GetInt64("schedual_type")
  2543. adminUserInfo := c.GetMobileAdminUserInfo()
  2544. timeLayout := "2006-01-02 15:04:05"
  2545. date := time.Now().Format("2006-01-02") + " 00:00:00"
  2546. loc, _ := time.LoadLocation("Local")
  2547. theStartTime, _ := time.ParseInLocation(timeLayout, date, loc)
  2548. scheduleTime := theStartTime.Unix()
  2549. deviceNumber, _ := service.GetAllDeviceNumbers(adminUserInfo.Org.Id, scheduleTime, schedual_type)
  2550. c.ServeSuccessJSON(map[string]interface{}{
  2551. "number": deviceNumber,
  2552. })
  2553. }
  2554. func (c *DialysisAPIController) GetPatientId() {
  2555. id, _ := c.GetInt64("id")
  2556. patientId, _ := service.GetPatientId(id)
  2557. c.ServeSuccessJSON(map[string]interface{}{
  2558. "patient": patientId,
  2559. })
  2560. }
  2561. func (this *DialysisAPIController) GetDialysisSchedule() {
  2562. schedualDate := this.GetString("date")
  2563. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  2564. if parseDateErr != nil {
  2565. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2566. return
  2567. }
  2568. adminInfo := this.GetMobileAdminUserInfo()
  2569. orgID := adminInfo.Org.Id
  2570. redis := service.RedisClient()
  2571. defer redis.Close()
  2572. key := "scheduals_" + schedualDate + "_" + strconv.FormatInt(orgID, 10)
  2573. scheduals, _ := service.MobileGetDialysisScheduals(orgID, date.Unix(), 0)
  2574. if len(scheduals) > 0 {
  2575. //缓存数据
  2576. scheduals_json, err := json.Marshal(scheduals)
  2577. if err == nil {
  2578. redis.Set(key, scheduals_json, time.Second*30)
  2579. }
  2580. }
  2581. this.ServeSuccessJSON(map[string]interface{}{
  2582. "scheduals": scheduals,
  2583. })
  2584. }
  2585. func (this *DialysisAPIController) GetLastOrNextDoctorAdvice() {
  2586. change_type, _ := this.GetInt64("type", 0)
  2587. record_date := this.GetString("record_time")
  2588. patient_id, _ := this.GetInt64("patient_id", 0)
  2589. timeLayout := "2006-01-02"
  2590. loc, _ := time.LoadLocation("Local")
  2591. theAdviceRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  2592. record_time := theAdviceRecordTime.Unix()
  2593. adminUserInfo := this.GetMobileAdminUserInfo()
  2594. advices, sch, err := service.GetDoctorAdviceByType(change_type, record_time, adminUserInfo.Org.Id, patient_id)
  2595. if err == nil {
  2596. if len(advices) == 0 {
  2597. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDoctorAdviceEmpty)
  2598. return
  2599. } else {
  2600. this.ServeSuccessJSON(map[string]interface{}{
  2601. "advices": advices,
  2602. "schedule": sch,
  2603. })
  2604. return
  2605. }
  2606. } else {
  2607. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  2608. return
  2609. }
  2610. }
  2611. func (c *DialysisAPIController) CreateConsumables() {
  2612. record_date := c.GetString("record_time")
  2613. patient_id, _ := c.GetInt64("patient_id", 0)
  2614. adminUser := c.GetMobileAdminUserInfo()
  2615. timeLayout := "2006-01-02"
  2616. loc, _ := time.LoadLocation("Local")
  2617. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  2618. record_time := theRecordTime.Unix()
  2619. dataBody := make(map[string]interface{}, 0)
  2620. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  2621. if err != nil {
  2622. utils.ErrorLog(err.Error())
  2623. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2624. return
  2625. }
  2626. var beforePrepares []*models.DialysisBeforePrepare
  2627. var updateBeforePrepares []*models.DialysisBeforePrepare
  2628. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  2629. goods, _ := dataBody["goods"].([]interface{})
  2630. if len(goods) > 0 {
  2631. for _, item := range goods {
  2632. items := item.(map[string]interface{})
  2633. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  2634. utils.ErrorLog("good_id")
  2635. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2636. return
  2637. }
  2638. good_id := int64(items["good_id"].(float64))
  2639. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  2640. utils.ErrorLog("good_type_id")
  2641. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2642. return
  2643. }
  2644. good_type_id := int64(items["good_type_id"].(float64))
  2645. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  2646. utils.ErrorLog("count")
  2647. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2648. return
  2649. }
  2650. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  2651. //commdity_code := items["commdity_code"].(string)
  2652. //fmt.Println("新建22222222222222",commdity_code)
  2653. adminUser := c.GetMobileAdminUserInfo()
  2654. prepare := &models.DialysisBeforePrepare{
  2655. UserOrgId: adminUser.Org.Id,
  2656. PatientId: patient_id,
  2657. RecordDate: record_time,
  2658. GoodId: good_id,
  2659. GoodTypeId: good_type_id,
  2660. Count: count,
  2661. Ctime: time.Now().Unix(),
  2662. Mtime: time.Now().Unix(),
  2663. Creater: adminUser.AdminUser.Id,
  2664. Modifier: 0,
  2665. //CommdityCode:commdity_code,
  2666. }
  2667. record_count := service.FindDialysisBeforePrepare(prepare.PatientId, prepare.GoodId, prepare.GoodTypeId, adminUser.Org.Id, record_time)
  2668. if record_count == 0 {
  2669. beforePrepares = append(beforePrepares, prepare)
  2670. }
  2671. }
  2672. }
  2673. }
  2674. if len(beforePrepares) > 0 {
  2675. service.CreateDialysisBeforePrepare(beforePrepares)
  2676. }
  2677. var errs error
  2678. if dataBody["update_goods"] != nil && reflect.TypeOf(dataBody["update_goods"]).String() == "[]interface {}" {
  2679. goods, _ := dataBody["update_goods"].([]interface{})
  2680. if len(goods) > 0 {
  2681. for _, item := range goods {
  2682. items := item.(map[string]interface{})
  2683. if items["record_time"] == nil || reflect.TypeOf(items["record_time"]).String() != "float64" {
  2684. utils.ErrorLog("record_time")
  2685. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2686. return
  2687. }
  2688. record_time := int64(items["record_time"].(float64))
  2689. if items["id"] == nil || reflect.TypeOf(items["id"]).String() != "float64" {
  2690. utils.ErrorLog("id")
  2691. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2692. return
  2693. }
  2694. id := int64(items["id"].(float64))
  2695. if items["patient_id"] == nil || reflect.TypeOf(items["patient_id"]).String() != "float64" {
  2696. utils.ErrorLog("patient_id")
  2697. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2698. return
  2699. }
  2700. patient_id := int64(items["patient_id"].(float64))
  2701. if items["creater"] == nil || reflect.TypeOf(items["creater"]).String() != "float64" {
  2702. utils.ErrorLog("creater")
  2703. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2704. return
  2705. }
  2706. creater := int64(items["creater"].(float64))
  2707. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  2708. utils.ErrorLog("good_id")
  2709. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2710. return
  2711. }
  2712. good_id := int64(items["good_id"].(float64))
  2713. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  2714. utils.ErrorLog("good_type_id")
  2715. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2716. return
  2717. }
  2718. good_type_id := int64(items["good_type_id"].(float64))
  2719. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  2720. utils.ErrorLog("count")
  2721. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2722. return
  2723. }
  2724. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  2725. if items["ctime"] == nil || reflect.TypeOf(items["ctime"]).String() != "float64" {
  2726. utils.ErrorLog("ctime")
  2727. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2728. return
  2729. }
  2730. ctime := int64(items["ctime"].(float64))
  2731. //commdity_code := items["commdity_code"].(string)
  2732. //fmt.Println("commdityecode22222222222222222222",commdity_code)
  2733. prepare := &models.DialysisBeforePrepare{
  2734. ID: id,
  2735. UserOrgId: adminUser.Org.Id,
  2736. PatientId: patient_id,
  2737. RecordDate: record_time,
  2738. GoodId: good_id,
  2739. GoodTypeId: good_type_id,
  2740. Count: count,
  2741. Ctime: ctime,
  2742. Mtime: time.Now().Unix(),
  2743. Creater: creater,
  2744. Modifier: adminUser.AdminUser.Id,
  2745. Status: 1,
  2746. //CommdityCode: commdity_code,
  2747. }
  2748. updateBeforePrepares = append(updateBeforePrepares, prepare)
  2749. }
  2750. }
  2751. //去重
  2752. updateBeforePrepares = RemoveRepeatedGood(updateBeforePrepares)
  2753. if len(updateBeforePrepares) > 0 {
  2754. for _, item := range updateBeforePrepares {
  2755. errs = service.UpdateDialysisBeforePrepareTwo(item)
  2756. }
  2757. }
  2758. }
  2759. if errs == nil {
  2760. c.ServeSuccessJSON(map[string]interface{}{
  2761. "msg": "提交成功",
  2762. })
  2763. return
  2764. } else {
  2765. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  2766. return
  2767. }
  2768. }
  2769. func (c *DialysisAPIController) CreateStockOutInfo() {
  2770. patient_id, _ := c.GetInt64("patient_id", 0)
  2771. record_date := c.GetString("record_time")
  2772. if patient_id <= 0 {
  2773. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2774. return
  2775. }
  2776. adminInfo := c.GetMobileAdminUserInfo()
  2777. timeLayout := "2006-01-02"
  2778. loc, _ := time.LoadLocation("Local")
  2779. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  2780. record_time := theRecordTime.Unix()
  2781. consumables, _ := service.FindConsumablesByDate(adminInfo.Org.Id, patient_id, record_time)
  2782. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  2783. consumables = RemoveRepeatedGood(consumables)
  2784. if record.IsOpen == 1 {
  2785. out, err := service.FindStockOutByIsSys(adminInfo.Org.Id, 1, record_time)
  2786. if err == gorm.ErrRecordNotFound {
  2787. //没有记录,则创建出库单
  2788. timeStr := time.Now().Format("2006-01-02")
  2789. timeArr := strings.Split(timeStr, "-")
  2790. total, _ := service.FindAllWarehouseOut(adminInfo.Org.Id)
  2791. total = total + 1
  2792. warehousing_out_order := strconv.FormatInt(adminInfo.Org.Id, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  2793. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  2794. number = number + total
  2795. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  2796. creater := adminInfo.AdminUser.Id
  2797. warehouseOut := models.WarehouseOut{
  2798. WarehouseOutOrderNumber: warehousing_out_order,
  2799. OperationTime: time.Now().Unix(),
  2800. OrgId: adminInfo.Org.Id,
  2801. Creater: creater,
  2802. Ctime: time.Now().Unix(),
  2803. Status: 1,
  2804. WarehouseOutTime: record_time,
  2805. Dealer: 0,
  2806. Manufacturer: 0,
  2807. Type: 1,
  2808. IsSys: 1,
  2809. }
  2810. err := service.AddSigleWarehouseOut(&warehouseOut)
  2811. if err != nil {
  2812. utils.TraceLog("创建出库单失败 err = %v", err)
  2813. } else {
  2814. for _, item := range consumables {
  2815. if item.Count > 0 {
  2816. warehouseOutInfo := &models.WarehouseOutInfo{
  2817. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  2818. WarehouseOutId: warehouseOut.ID,
  2819. Status: 1,
  2820. Ctime: time.Now().Unix(),
  2821. Remark: "",
  2822. OrgId: adminInfo.Org.Id,
  2823. Type: 1,
  2824. Manufacturer: 0,
  2825. Dealer: 0,
  2826. IsSys: 1,
  2827. SysRecordTime: record_time,
  2828. GoodTypeId: item.GoodTypeId,
  2829. GoodId: item.GoodId,
  2830. }
  2831. warehouseOutInfo.Count = item.Count
  2832. stockInInfo, _ := service.FindLastStockInInfoRecord(item.GoodId, adminInfo.Org.Id)
  2833. warehouseOutInfo.Price = stockInInfo.Price
  2834. err := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  2835. if err == nil {
  2836. details := &models.AutomaticReduceDetail{
  2837. WarehouseOutId: warehouseOutInfo.ID,
  2838. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  2839. PatientId: patient_id,
  2840. Ctime: time.Now().Unix(),
  2841. Mtime: time.Now().Unix(),
  2842. Status: 1,
  2843. RecordTime: record_time,
  2844. OrgId: adminInfo.Org.Id,
  2845. GoodId: item.GoodId,
  2846. GoodTypeId: item.GoodTypeId,
  2847. Count: item.Count,
  2848. }
  2849. service.AddSigleAutoReduceRecordInfo(details)
  2850. }
  2851. }
  2852. }
  2853. }
  2854. } else if err == nil {
  2855. for _, item := range consumables {
  2856. outInfo, err := service.FindStockOutInfoByTypeId(adminInfo.Org.Id, item.GoodTypeId, item.GoodId, out.ID, out.WarehouseOutOrderNumber)
  2857. if err == gorm.ErrRecordNotFound {
  2858. warehouseOutInfo := &models.WarehouseOutInfo{
  2859. WarehouseOutOrderNumber: out.WarehouseOutOrderNumber,
  2860. WarehouseOutId: out.ID,
  2861. Status: 1,
  2862. Ctime: time.Now().Unix(),
  2863. Remark: "",
  2864. OrgId: adminInfo.Org.Id,
  2865. Type: 1,
  2866. Manufacturer: 0,
  2867. Dealer: 0,
  2868. IsSys: 1,
  2869. SysRecordTime: record_time,
  2870. }
  2871. stockInInfo, _ := service.FindLastStockInInfoRecord(item.GoodId, adminInfo.Org.Id)
  2872. warehouseOutInfo.Price = stockInInfo.Price
  2873. warehouseOutInfo.GoodId = item.GoodId
  2874. warehouseOutInfo.GoodTypeId = item.GoodTypeId
  2875. warehouseOutInfo.Count = item.Count
  2876. err := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  2877. if err == nil {
  2878. details := &models.AutomaticReduceDetail{
  2879. WarehouseOutId: warehouseOutInfo.ID,
  2880. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  2881. PatientId: patient_id,
  2882. Ctime: time.Now().Unix(),
  2883. Mtime: time.Now().Unix(),
  2884. Status: 1,
  2885. RecordTime: record_time,
  2886. OrgId: adminInfo.Org.Id,
  2887. GoodId: item.GoodId,
  2888. GoodTypeId: item.GoodTypeId,
  2889. Count: item.Count,
  2890. }
  2891. service.AddSigleAutoReduceRecordInfo(details)
  2892. }
  2893. } else if err == nil { //记录存在,则将增加数量
  2894. if outInfo.ID > 0 {
  2895. service.UpdateStockOutInfoCount2(adminInfo.Org.Id, outInfo.ID, item.Count)
  2896. }
  2897. count, _ := service.FindPatientAutomaticReduceRecord(adminInfo.Org.Id, record_time, item.GoodId, item.GoodTypeId, patient_id)
  2898. if count == 0 {
  2899. details := &models.AutomaticReduceDetail{
  2900. WarehouseOutId: outInfo.ID,
  2901. WarehouseOutOrderNumber: outInfo.WarehouseOutOrderNumber,
  2902. PatientId: patient_id,
  2903. Ctime: time.Now().Unix(),
  2904. Mtime: time.Now().Unix(),
  2905. Status: 1,
  2906. RecordTime: record_time,
  2907. OrgId: adminInfo.Org.Id,
  2908. GoodId: item.GoodId,
  2909. GoodTypeId: item.GoodTypeId,
  2910. Count: item.Count,
  2911. }
  2912. service.AddSigleAutoReduceRecordInfo(details)
  2913. } else if count == 1 {
  2914. service.UpdateUserInfoDetails(item.GoodTypeId, item.GoodId, record_time, adminInfo.Org.Id, patient_id, item.Count, &outInfo)
  2915. }
  2916. }
  2917. }
  2918. }
  2919. c.ServeSuccessJSON(map[string]interface{}{
  2920. "msg": "提交成功",
  2921. })
  2922. return
  2923. } else {
  2924. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeOpenStocktWrong)
  2925. return
  2926. }
  2927. }
  2928. func (c *DialysisAPIController) EditConsumables() {
  2929. patient_id, _ := c.GetInt64("patient_id", 0)
  2930. record_date := c.GetString("record_time")
  2931. if patient_id <= 0 {
  2932. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2933. return
  2934. }
  2935. adminInfo := c.GetMobileAdminUserInfo()
  2936. timeLayout := "2006-01-02"
  2937. loc, _ := time.LoadLocation("Local")
  2938. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  2939. record_time := theRecordTime.Unix()
  2940. dataBody := make(map[string]interface{}, 0)
  2941. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  2942. if err != nil {
  2943. utils.ErrorLog(err.Error())
  2944. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2945. return
  2946. }
  2947. var beforePrepares []*models.DialysisBeforePrepare
  2948. var newBeforePrepares []*models.DialysisBeforePrepare
  2949. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  2950. if record.IsOpen == 1 {
  2951. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  2952. goods, _ := dataBody["goods"].([]interface{})
  2953. if len(goods) > 0 {
  2954. for _, item := range goods {
  2955. items := item.(map[string]interface{})
  2956. if items["record_time"] == nil || reflect.TypeOf(items["record_time"]).String() != "float64" {
  2957. utils.ErrorLog("record_time")
  2958. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2959. return
  2960. }
  2961. record_time := int64(items["record_time"].(float64))
  2962. if items["id"] == nil || reflect.TypeOf(items["id"]).String() != "float64" {
  2963. utils.ErrorLog("id")
  2964. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2965. return
  2966. }
  2967. id := int64(items["id"].(float64))
  2968. if items["patient_id"] == nil || reflect.TypeOf(items["patient_id"]).String() != "float64" {
  2969. utils.ErrorLog("patient_id")
  2970. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2971. return
  2972. }
  2973. patient_id := int64(items["patient_id"].(float64))
  2974. if items["creater"] == nil || reflect.TypeOf(items["creater"]).String() != "float64" {
  2975. utils.ErrorLog("creater")
  2976. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2977. return
  2978. }
  2979. creater := int64(items["creater"].(float64))
  2980. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  2981. utils.ErrorLog("good_id")
  2982. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2983. return
  2984. }
  2985. good_id := int64(items["good_id"].(float64))
  2986. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  2987. utils.ErrorLog("good_type_id")
  2988. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2989. return
  2990. }
  2991. good_type_id := int64(items["good_type_id"].(float64))
  2992. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  2993. utils.ErrorLog("count")
  2994. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2995. return
  2996. }
  2997. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  2998. if items["ctime"] == nil || reflect.TypeOf(items["ctime"]).String() != "float64" {
  2999. utils.ErrorLog("ctime")
  3000. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3001. return
  3002. }
  3003. ctime := int64(items["ctime"].(float64))
  3004. //commdity_code := items["commdity_code"].(string)
  3005. //fmt.Println("commdityecode22222222222222222222",commdity_code)
  3006. adminUser := c.GetMobileAdminUserInfo()
  3007. prepare := &models.DialysisBeforePrepare{
  3008. ID: id,
  3009. UserOrgId: adminUser.Org.Id,
  3010. PatientId: patient_id,
  3011. RecordDate: record_time,
  3012. GoodId: good_id,
  3013. GoodTypeId: good_type_id,
  3014. Count: count,
  3015. Ctime: ctime,
  3016. Mtime: time.Now().Unix(),
  3017. Creater: creater,
  3018. Modifier: adminUser.AdminUser.Id,
  3019. Status: 1,
  3020. //CommdityCode: commdity_code,
  3021. }
  3022. beforePrepares = append(beforePrepares, prepare)
  3023. }
  3024. }
  3025. }
  3026. consumables_source, _ := service.FindConsumablesByDate(adminInfo.Org.Id, patient_id, record_time)
  3027. if dataBody["new_goods"] != nil && reflect.TypeOf(dataBody["new_goods"]).String() == "[]interface {}" {
  3028. goods, _ := dataBody["new_goods"].([]interface{})
  3029. if len(goods) > 0 {
  3030. for _, item := range goods {
  3031. items := item.(map[string]interface{})
  3032. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  3033. utils.ErrorLog("good_id")
  3034. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3035. return
  3036. }
  3037. good_id := int64(items["good_id"].(float64))
  3038. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  3039. utils.ErrorLog("good_type_id")
  3040. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3041. return
  3042. }
  3043. good_type_id := int64(items["good_type_id"].(float64))
  3044. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  3045. utils.ErrorLog("count")
  3046. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3047. return
  3048. }
  3049. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3050. //commdity_code := items["commdity_code"].(string)
  3051. //fmt.Println("commdityecode22222222222222222222",commdity_code)
  3052. adminUser := c.GetMobileAdminUserInfo()
  3053. prepare := &models.DialysisBeforePrepare{
  3054. UserOrgId: adminUser.Org.Id,
  3055. PatientId: patient_id,
  3056. RecordDate: record_time,
  3057. GoodId: good_id,
  3058. GoodTypeId: good_type_id,
  3059. Count: count,
  3060. Ctime: time.Now().Unix(),
  3061. Mtime: time.Now().Unix(),
  3062. Creater: adminUser.AdminUser.Id,
  3063. Modifier: 0,
  3064. //CommdityCode:commdity_code,
  3065. }
  3066. newBeforePrepares = append(newBeforePrepares, prepare)
  3067. }
  3068. newBeforePrepares = RemoveRepeatedGood(newBeforePrepares)
  3069. }
  3070. service.CreateDialysisBeforePrepare(newBeforePrepares)
  3071. }
  3072. out, err := service.FindStockOutByIsSys(adminInfo.Org.Id, 1, record_time)
  3073. if err == gorm.ErrRecordNotFound {
  3074. //没有记录,则创建出库单
  3075. timeStr := time.Now().Format("2006-01-02")
  3076. timeArr := strings.Split(timeStr, "-")
  3077. total, _ := service.FindAllWarehouseOut(adminInfo.Org.Id)
  3078. total = total + 1
  3079. warehousing_out_order := strconv.FormatInt(adminInfo.Org.Id, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  3080. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  3081. number = number + total
  3082. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  3083. creater := adminInfo.AdminUser.Id
  3084. warehouseOut := models.WarehouseOut{
  3085. WarehouseOutOrderNumber: warehousing_out_order,
  3086. OperationTime: time.Now().Unix(),
  3087. OrgId: adminInfo.Org.Id,
  3088. Creater: creater,
  3089. Ctime: time.Now().Unix(),
  3090. Status: 1,
  3091. WarehouseOutTime: record_time,
  3092. Dealer: 0,
  3093. Manufacturer: 0,
  3094. Type: 1,
  3095. IsSys: 1,
  3096. }
  3097. err := service.AddSigleWarehouseOut(&warehouseOut)
  3098. if err != nil {
  3099. utils.TraceLog("创建出库单失败 err = %v", err)
  3100. } else {
  3101. for _, item := range beforePrepares {
  3102. if item.Count > 0 {
  3103. warehouseOutInfo := &models.WarehouseOutInfo{
  3104. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  3105. WarehouseOutId: warehouseOut.ID,
  3106. Count: 1,
  3107. Status: 1,
  3108. Ctime: time.Now().Unix(),
  3109. Remark: "",
  3110. OrgId: adminInfo.Org.Id,
  3111. Type: 1,
  3112. Manufacturer: 0,
  3113. Dealer: 0,
  3114. IsSys: 1,
  3115. SysRecordTime: record_time,
  3116. GoodTypeId: item.GoodTypeId,
  3117. GoodId: item.GoodId,
  3118. }
  3119. stockInInfo, _ := service.FindLastStockInInfoRecord(item.GoodId, adminInfo.Org.Id)
  3120. warehouseOutInfo.Price = stockInInfo.Price
  3121. err := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  3122. if err == nil {
  3123. details := &models.AutomaticReduceDetail{
  3124. WarehouseOutId: warehouseOutInfo.ID,
  3125. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  3126. PatientId: patient_id,
  3127. Ctime: time.Now().Unix(),
  3128. Mtime: time.Now().Unix(),
  3129. Status: 1,
  3130. RecordTime: record_time,
  3131. OrgId: adminInfo.Org.Id,
  3132. GoodId: item.GoodId,
  3133. GoodTypeId: item.GoodTypeId,
  3134. }
  3135. service.AddSigleAutoReduceRecordInfo(details)
  3136. }
  3137. }
  3138. }
  3139. }
  3140. } else if err == nil {
  3141. if len(newBeforePrepares) > 0 { //新增
  3142. for _, item := range newBeforePrepares {
  3143. outInfo, err := service.FindStockOutInfoByTypeId(adminInfo.Org.Id, item.GoodTypeId, item.GoodId, out.ID, out.WarehouseOutOrderNumber)
  3144. if err == gorm.ErrRecordNotFound {
  3145. warehouseOutInfo := &models.WarehouseOutInfo{
  3146. WarehouseOutOrderNumber: out.WarehouseOutOrderNumber,
  3147. WarehouseOutId: out.ID,
  3148. Status: 1,
  3149. Ctime: time.Now().Unix(),
  3150. Remark: "",
  3151. OrgId: adminInfo.Org.Id,
  3152. Type: 1,
  3153. Manufacturer: 0,
  3154. Dealer: 0,
  3155. IsSys: 1,
  3156. SysRecordTime: record_time,
  3157. }
  3158. stockInInfo, _ := service.FindLastStockInInfoRecord(item.GoodId, adminInfo.Org.Id)
  3159. warehouseOutInfo.Price = stockInInfo.Price
  3160. warehouseOutInfo.GoodId = item.GoodId
  3161. warehouseOutInfo.GoodTypeId = item.GoodTypeId
  3162. warehouseOutInfo.Count = item.Count
  3163. err := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  3164. if err == nil {
  3165. count, _ := service.FindPatientAutomaticReduceRecord(adminInfo.Org.Id, record_time, item.GoodId, item.GoodTypeId, patient_id)
  3166. if count == 0 {
  3167. details := &models.AutomaticReduceDetail{
  3168. WarehouseOutId: warehouseOutInfo.ID,
  3169. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  3170. PatientId: patient_id,
  3171. Ctime: time.Now().Unix(),
  3172. Mtime: time.Now().Unix(),
  3173. Status: 1,
  3174. RecordTime: record_time,
  3175. OrgId: adminInfo.Org.Id,
  3176. GoodId: item.GoodId,
  3177. GoodTypeId: item.GoodTypeId,
  3178. Count: item.Count,
  3179. }
  3180. service.AddSigleAutoReduceRecordInfo(details)
  3181. } else if count == 1 {
  3182. service.UpdateUserInfoDetails(item.GoodTypeId, item.GoodId, record_time, adminInfo.Org.Id, patient_id, item.Count, &outInfo)
  3183. }
  3184. }
  3185. } else if err == nil { //记录存在,则将加数量
  3186. if outInfo.ID > 0 {
  3187. service.UpdateStockOutInfoCount2(adminInfo.Org.Id, outInfo.ID, item.Count)
  3188. }
  3189. count, _ := service.FindPatientAutomaticReduceRecord(adminInfo.Org.Id, record_time, item.GoodId, item.GoodTypeId, patient_id)
  3190. if count == 0 {
  3191. details := &models.AutomaticReduceDetail{
  3192. WarehouseOutId: outInfo.ID,
  3193. WarehouseOutOrderNumber: outInfo.WarehouseOutOrderNumber,
  3194. PatientId: patient_id,
  3195. Ctime: time.Now().Unix(),
  3196. Mtime: time.Now().Unix(),
  3197. Status: 1,
  3198. RecordTime: record_time,
  3199. OrgId: adminInfo.Org.Id,
  3200. GoodId: item.GoodId,
  3201. GoodTypeId: item.GoodTypeId,
  3202. Count: item.Count,
  3203. }
  3204. service.AddSigleAutoReduceRecordInfo(details)
  3205. } else if count == 1 {
  3206. service.UpdateUserInfoDetails(item.GoodTypeId, item.GoodId, record_time, adminInfo.Org.Id, patient_id, item.Count, &outInfo)
  3207. }
  3208. //details := &models.AutomaticReduceDetail{
  3209. // WarehouseOutId: outInfo.ID,
  3210. // WarehouseOutOrderNumber: outInfo.WarehouseOutOrderNumber,
  3211. // PatientId: patient_id,
  3212. // Ctime: time.Now().Unix(),
  3213. // Mtime: time.Now().Unix(),
  3214. // Status: 1,
  3215. // RecordTime: record_time,
  3216. // OrgId: adminInfo.Org.Id,
  3217. // GoodId: item.GoodId,
  3218. // GoodTypeId: item.GoodTypeId,
  3219. // Count: item.Count,
  3220. //}
  3221. //service.AddSigleAutoReduceRecordInfo(details)
  3222. }
  3223. }
  3224. }
  3225. if len(beforePrepares) > 0 { //修改
  3226. for _, consumable := range consumables_source {
  3227. for _, before := range beforePrepares {
  3228. if consumable.GoodId == before.GoodId {
  3229. if consumable.Count != before.Count {
  3230. _, out := service.FindStockOutOrderNumberByTime(record_time, adminInfo.Org.Id)
  3231. //_, out := service.FindOldOrderInfoByGoodId(record_time, adminInfo.Org.Id)
  3232. //判断前端更改后的商品id的出库记录在数据库中是否存在
  3233. err, newOut := service.FindOrderInfoByGoodId(consumable.GoodTypeId, consumable.GoodId, out.WarehouseOutOrderNumber, adminInfo.Org.Id)
  3234. if err == gorm.ErrRecordNotFound { //不存在,则新增出库记录,并更改使用人商品信息
  3235. warehouseOutInfo := &models.WarehouseOutInfo{
  3236. WarehouseOutOrderNumber: out.WarehouseOutOrderNumber,
  3237. WarehouseOutId: out.ID,
  3238. Count: before.Count,
  3239. Status: 1,
  3240. Ctime: time.Now().Unix(),
  3241. Remark: "",
  3242. OrgId: adminInfo.Org.Id,
  3243. Type: 1,
  3244. Manufacturer: 0,
  3245. Dealer: 0,
  3246. IsSys: 1,
  3247. SysRecordTime: record_time,
  3248. }
  3249. stockInInfo, _ := service.FindLastStockInInfoRecord(before.GoodId, adminInfo.Org.Id)
  3250. warehouseOutInfo.Price = stockInInfo.Price
  3251. warehouseOutInfo.GoodId = before.GoodId
  3252. warehouseOutInfo.GoodTypeId = before.GoodTypeId
  3253. err := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  3254. if err == nil {
  3255. //可能存在商品使用人不存在的情况,需要先判断商品使用人是否存在
  3256. user, err := service.FindGoodUserById(before.GoodTypeId, before.GoodId, patient_id, adminInfo.Org.Id, record_time)
  3257. if err == gorm.ErrRecordNotFound {
  3258. details := &models.AutomaticReduceDetail{
  3259. WarehouseOutId: warehouseOutInfo.ID,
  3260. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  3261. PatientId: patient_id,
  3262. Ctime: time.Now().Unix(),
  3263. Mtime: time.Now().Unix(),
  3264. Status: 1,
  3265. RecordTime: record_time,
  3266. OrgId: adminInfo.Org.Id,
  3267. GoodId: consumable.GoodId,
  3268. GoodTypeId: consumable.GoodTypeId,
  3269. Count: before.Count,
  3270. }
  3271. service.AddSigleAutoReduceRecordInfo(details)
  3272. } else if err == nil {
  3273. if user.ID > 0 {
  3274. //service.UpdateOrderInfoDetails( consumable.GoodTypeId, consumable.GoodId, record_time, adminInfo.Org.Id, patient_id, a_liquid, warehouseOutInfo)
  3275. service.UpdateUserInfoDetails(consumable.GoodTypeId, consumable.GoodId, record_time, adminInfo.Org.Id, patient_id, before.Count, warehouseOutInfo)
  3276. }
  3277. }
  3278. }
  3279. } else if err == nil { //存在,则更改使用人商品信息
  3280. fmt.Println("333333333")
  3281. //处理原来的数据
  3282. if newOut.ID > 0 {
  3283. if consumable.Count > before.Count { // 减少
  3284. num := int64(0)
  3285. if consumable.Count-before.Count > 0 {
  3286. num = consumable.Count - before.Count
  3287. } else {
  3288. num = before.Count - consumable.Count
  3289. }
  3290. service.UpdateOrderCountSub(consumable.GoodTypeId, consumable.GoodId, out.WarehouseOutOrderNumber, adminInfo.Org.Id, num)
  3291. } else if consumable.Count < before.Count { //增加
  3292. service.UpdateOrderCountAdd(consumable.GoodTypeId, consumable.GoodId, out.WarehouseOutOrderNumber, adminInfo.Org.Id, before.Count-consumable.Count)
  3293. }
  3294. user, err := service.FindGoodUserById(consumable.GoodTypeId, consumable.GoodId, patient_id, adminInfo.Org.Id, record_time)
  3295. if err == gorm.ErrRecordNotFound {
  3296. details := &models.AutomaticReduceDetail{
  3297. WarehouseOutId: newOut.ID,
  3298. WarehouseOutOrderNumber: newOut.WarehouseOutOrderNumber,
  3299. PatientId: patient_id,
  3300. Ctime: time.Now().Unix(),
  3301. Mtime: time.Now().Unix(),
  3302. Status: 1,
  3303. RecordTime: record_time,
  3304. OrgId: adminInfo.Org.Id,
  3305. GoodId: consumable.GoodId,
  3306. GoodTypeId: consumable.GoodTypeId,
  3307. Count: before.Count,
  3308. }
  3309. service.AddSigleAutoReduceRecordInfo(details)
  3310. } else if err == nil {
  3311. if user.ID > 0 {
  3312. service.UpdateUserInfoDetails(consumable.GoodTypeId, consumable.GoodId, record_time, adminInfo.Org.Id, patient_id, before.Count, &newOut)
  3313. }
  3314. }
  3315. }
  3316. }
  3317. fmt.Println("444444444")
  3318. }
  3319. }
  3320. }
  3321. }
  3322. }
  3323. }
  3324. fmt.Println("655555555")
  3325. var errs error
  3326. if len(beforePrepares) > 0 {
  3327. for _, item := range beforePrepares {
  3328. errs = service.UpdateDialysisBeforePrepareTwo(item)
  3329. }
  3330. }
  3331. if errs == nil {
  3332. c.ServeSuccessJSON(map[string]interface{}{
  3333. "msg": "修改成功",
  3334. })
  3335. return
  3336. } else {
  3337. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3338. return
  3339. }
  3340. } else {
  3341. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  3342. goods, _ := dataBody["goods"].([]interface{})
  3343. if len(goods) > 0 {
  3344. for _, item := range goods {
  3345. items := item.(map[string]interface{})
  3346. if items["record_time"] == nil || reflect.TypeOf(items["record_time"]).String() != "float64" {
  3347. utils.ErrorLog("record_time")
  3348. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3349. return
  3350. }
  3351. record_time := int64(items["record_time"].(float64))
  3352. if items["id"] == nil || reflect.TypeOf(items["id"]).String() != "float64" {
  3353. utils.ErrorLog("id")
  3354. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3355. return
  3356. }
  3357. id := int64(items["id"].(float64))
  3358. if items["patient_id"] == nil || reflect.TypeOf(items["patient_id"]).String() != "float64" {
  3359. utils.ErrorLog("patient_id")
  3360. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3361. return
  3362. }
  3363. patient_id := int64(items["patient_id"].(float64))
  3364. if items["creater"] == nil || reflect.TypeOf(items["creater"]).String() != "float64" {
  3365. utils.ErrorLog("creater")
  3366. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3367. return
  3368. }
  3369. creater := int64(items["creater"].(float64))
  3370. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  3371. utils.ErrorLog("good_id")
  3372. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3373. return
  3374. }
  3375. good_id := int64(items["good_id"].(float64))
  3376. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  3377. utils.ErrorLog("good_type_id")
  3378. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3379. return
  3380. }
  3381. good_type_id := int64(items["good_type_id"].(float64))
  3382. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  3383. utils.ErrorLog("count")
  3384. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3385. return
  3386. }
  3387. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3388. if items["ctime"] == nil || reflect.TypeOf(items["ctime"]).String() != "float64" {
  3389. utils.ErrorLog("ctime")
  3390. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3391. return
  3392. }
  3393. ctime := int64(items["ctime"].(float64))
  3394. adminUser := c.GetMobileAdminUserInfo()
  3395. prepare := &models.DialysisBeforePrepare{
  3396. ID: id,
  3397. UserOrgId: adminUser.Org.Id,
  3398. PatientId: patient_id,
  3399. RecordDate: record_time,
  3400. GoodId: good_id,
  3401. GoodTypeId: good_type_id,
  3402. Count: count,
  3403. Ctime: ctime,
  3404. Mtime: time.Now().Unix(),
  3405. Creater: creater,
  3406. Modifier: adminUser.AdminUser.Id,
  3407. Status: 1,
  3408. }
  3409. beforePrepares = append(beforePrepares, prepare)
  3410. }
  3411. }
  3412. }
  3413. if dataBody["new_goods"] != nil && reflect.TypeOf(dataBody["new_goods"]).String() == "[]interface {}" {
  3414. goods, _ := dataBody["new_goods"].([]interface{})
  3415. if len(goods) > 0 {
  3416. for _, item := range goods {
  3417. items := item.(map[string]interface{})
  3418. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  3419. utils.ErrorLog("good_id")
  3420. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3421. return
  3422. }
  3423. good_id := int64(items["good_id"].(float64))
  3424. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  3425. utils.ErrorLog("good_type_id")
  3426. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3427. return
  3428. }
  3429. good_type_id := int64(items["good_type_id"].(float64))
  3430. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  3431. utils.ErrorLog("count")
  3432. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3433. return
  3434. }
  3435. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3436. adminUser := c.GetMobileAdminUserInfo()
  3437. prepare := &models.DialysisBeforePrepare{
  3438. UserOrgId: adminUser.Org.Id,
  3439. PatientId: patient_id,
  3440. RecordDate: record_time,
  3441. GoodId: good_id,
  3442. GoodTypeId: good_type_id,
  3443. Count: count,
  3444. Ctime: time.Now().Unix(),
  3445. Mtime: time.Now().Unix(),
  3446. Creater: adminUser.AdminUser.Id,
  3447. Modifier: 0,
  3448. }
  3449. newBeforePrepares = append(newBeforePrepares, prepare)
  3450. }
  3451. }
  3452. service.CreateDialysisBeforePrepare(newBeforePrepares)
  3453. }
  3454. var errs error
  3455. if len(beforePrepares) > 0 {
  3456. for _, item := range beforePrepares {
  3457. errs = service.UpdateDialysisBeforePrepareTwo(item)
  3458. }
  3459. }
  3460. if errs == nil {
  3461. c.ServeSuccessJSON(map[string]interface{}{
  3462. "msg": "修改成功",
  3463. })
  3464. return
  3465. } else {
  3466. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3467. return
  3468. }
  3469. }
  3470. }
  3471. func (c *DialysisAPIController) GetDialysisGoods() {
  3472. schedualDate := c.GetString("schedule_date")
  3473. schedule_type, _ := c.GetInt64("schedule_type")
  3474. partition_id, _ := c.GetInt64("partition_id")
  3475. page, _ := c.GetInt("page")
  3476. patient_id, _ := c.GetInt64("patient_id")
  3477. schedualEndDate := int64(0)
  3478. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  3479. if parseDateErr != nil && len(schedualDate) != 0 {
  3480. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3481. return
  3482. }
  3483. endDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", schedualDate+" 23:59:59")
  3484. if parseDateErr != nil && len(schedualDate) != 0 {
  3485. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3486. return
  3487. }
  3488. schedualEndDate = endDate.Unix()
  3489. adminUser := c.GetMobileAdminUserInfo()
  3490. _, err := service.FindStockOutByIsSys(adminUser.Org.Id, 1, date.Unix())
  3491. goodTypes, _ := service.FindAllGoodType(adminUser.Org.Id)
  3492. if err == gorm.ErrRecordNotFound {
  3493. dialysisGoods, _, total := service.MobileGetDialysisGoods(adminUser.Org.Id, date.Unix(), schedule_type, partition_id, page, 0, patient_id, "", schedualEndDate)
  3494. if patient_id != 0 {
  3495. for _, item := range dialysisGoods { //获取当天排班的每个患者的最后日期的库存使用情况
  3496. goodUser, _ := service.GetLastDialysisGoods(item.PatientId, adminUser.Org.Id, date.Unix())
  3497. lastGoodUserDetial, _ := service.GetLastDialysisBeforePrepare(item.PatientId, adminUser.Org.Id, date.Unix())
  3498. item.LastAutomaticReduceDetail = goodUser
  3499. item.LastDialysisBeforePrepare = lastGoodUserDetial
  3500. }
  3501. }
  3502. c.ServeSuccessJSON(map[string]interface{}{
  3503. "dialysis_goods": dialysisGoods,
  3504. "good_type": goodTypes,
  3505. "total": total,
  3506. })
  3507. return
  3508. } else if err == nil {
  3509. //获取当天排班的每个患者的库存使用情况
  3510. dialysisGoods, err, total := service.MobileGetDialysisGoods(adminUser.Org.Id, date.Unix(), schedule_type, partition_id, page, 0, patient_id, "", schedualEndDate)
  3511. if patient_id != 0 {
  3512. for _, item := range dialysisGoods { //获取当天排班的每个患者的最后日期的库存使用情况
  3513. goodUser, _ := service.GetLastDialysisGoods(item.PatientId, adminUser.Org.Id, date.Unix())
  3514. lastGoodUserDetial, _ := service.GetLastDialysisBeforePrepare(item.PatientId, adminUser.Org.Id, date.Unix())
  3515. fmt.Println(goodUser)
  3516. fmt.Println(lastGoodUserDetial)
  3517. item.LastAutomaticReduceDetail = goodUser
  3518. item.LastDialysisBeforePrepare = lastGoodUserDetial
  3519. }
  3520. }
  3521. if err == nil {
  3522. c.ServeSuccessJSON(map[string]interface{}{
  3523. "dialysis_goods": dialysisGoods,
  3524. "good_type": goodTypes,
  3525. "total": total,
  3526. })
  3527. return
  3528. } else {
  3529. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3530. return
  3531. }
  3532. } else if err != nil {
  3533. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3534. return
  3535. }
  3536. }
  3537. func (c *DialysisAPIController) GetDialysisGoodsStatistics() {
  3538. start_time := c.GetString("start_time")
  3539. end_time := c.GetString("end_time")
  3540. timeLayout := "2006-01-02"
  3541. loc, _ := time.LoadLocation("Local")
  3542. var theStartTime int64
  3543. if len(start_time) > 0 {
  3544. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  3545. if err != nil {
  3546. utils.ErrorLog(err.Error())
  3547. }
  3548. theStartTime = theTime.Unix()
  3549. }
  3550. var theEndtTime int64
  3551. if len(end_time) > 0 {
  3552. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
  3553. if err != nil {
  3554. utils.ErrorLog(err.Error())
  3555. }
  3556. theEndtTime = theTime.Unix()
  3557. }
  3558. adminUser := c.GetMobileAdminUserInfo()
  3559. outInfo, err := service.MobileGetGoodsStatistics(adminUser.Org.Id, theStartTime, theEndtTime)
  3560. stockCount, err := service.GetOutStockTotalCountOne(theStartTime, theEndtTime, adminUser.Org.Id)
  3561. if err == nil {
  3562. c.ServeSuccessJSON(map[string]interface{}{
  3563. "stock_out": outInfo,
  3564. "stockCount": stockCount,
  3565. })
  3566. return
  3567. } else {
  3568. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3569. return
  3570. }
  3571. }
  3572. func (c *DialysisAPIController) GetStockInGoodInfo() {
  3573. patient_id, _ := c.GetInt64("patient_id", 0)
  3574. record_time := c.GetString("record_time")
  3575. adminUser := c.GetMobileAdminUserInfo()
  3576. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", record_time)
  3577. if parseDateErr != nil && len(record_time) != 0 {
  3578. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3579. return
  3580. }
  3581. goodTypes, _ := service.FindAllGoodTypeOne(adminUser.Org.Id)
  3582. good_info, _ := service.FindAllGoodInfo(adminUser.Org.Id)
  3583. goodUser, _ := service.GetAllStockOutUserDetail(patient_id, adminUser.Org.Id, date.Unix())
  3584. lastGoodUserDetial, _ := service.GetLastDialysisGoods(patient_id, adminUser.Org.Id, date.Unix())
  3585. c.ServeSuccessJSON(map[string]interface{}{
  3586. "good_type": goodTypes,
  3587. "good_user": goodUser,
  3588. "good_info": good_info,
  3589. "last_good_user": lastGoodUserDetial,
  3590. })
  3591. return
  3592. }
  3593. func (c *DialysisAPIController) CreateOtherStockOutInfo() {
  3594. patient_id, _ := c.GetInt64("patient_id", 0)
  3595. record_date := c.GetString("record_time")
  3596. if patient_id <= 0 {
  3597. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3598. return
  3599. }
  3600. adminInfo := c.GetMobileAdminUserInfo()
  3601. timeLayout := "2006-01-02"
  3602. loc, _ := time.LoadLocation("Local")
  3603. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3604. record_time := theRecordTime.Unix()
  3605. dataBody := make(map[string]interface{}, 0)
  3606. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  3607. if err != nil {
  3608. utils.ErrorLog(err.Error())
  3609. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3610. return
  3611. }
  3612. var beforePrepares []*models.DialysisBeforePrepare
  3613. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  3614. goods, _ := dataBody["goods"].([]interface{})
  3615. if len(goods) > 0 {
  3616. for _, item := range goods {
  3617. items := item.(map[string]interface{})
  3618. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  3619. utils.ErrorLog("good_id")
  3620. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3621. return
  3622. }
  3623. good_id := int64(items["good_id"].(float64))
  3624. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  3625. utils.ErrorLog("good_type_id")
  3626. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3627. return
  3628. }
  3629. good_type_id := int64(items["good_type_id"].(float64))
  3630. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  3631. utils.ErrorLog("count")
  3632. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3633. return
  3634. }
  3635. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3636. adminUser := c.GetMobileAdminUserInfo()
  3637. prepare := &models.DialysisBeforePrepare{
  3638. UserOrgId: adminUser.Org.Id,
  3639. PatientId: patient_id,
  3640. RecordDate: record_time,
  3641. GoodId: good_id,
  3642. GoodTypeId: good_type_id,
  3643. Count: count,
  3644. Ctime: time.Now().Unix(),
  3645. Mtime: time.Now().Unix(),
  3646. Creater: adminUser.AdminUser.Id,
  3647. Modifier: 0,
  3648. }
  3649. record_count := service.FindDialysisBeforePrepare(prepare.PatientId, prepare.GoodId, prepare.GoodTypeId, adminUser.Org.Id, record_time)
  3650. if record_count == 0 {
  3651. beforePrepares = append(beforePrepares, prepare)
  3652. } else if record_count == 1 {
  3653. service.UpdateDialysisBeforePrepareTwo(prepare)
  3654. }
  3655. }
  3656. }
  3657. }
  3658. beforePrepares = RemoveRepeatedGood(beforePrepares)
  3659. if len(beforePrepares) > 0 {
  3660. service.CreateDialysisBeforePrepare(beforePrepares)
  3661. }
  3662. consumables, _ := service.FindConsumablesByDate(adminInfo.Org.Id, patient_id, record_time)
  3663. //去重
  3664. consumables = RemoveRepeatedGood(consumables)
  3665. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  3666. if record.IsOpen == 1 {
  3667. out, err := service.FindStockOutByIsSys(adminInfo.Org.Id, 1, record_time)
  3668. if err == gorm.ErrRecordNotFound {
  3669. //没有记录,则创建出库单
  3670. timeStr := time.Now().Format("2006-01-02")
  3671. timeArr := strings.Split(timeStr, "-")
  3672. total, _ := service.FindAllWarehouseOut(adminInfo.Org.Id)
  3673. total = total + 1
  3674. warehousing_out_order := strconv.FormatInt(adminInfo.Org.Id, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  3675. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  3676. number = number + total
  3677. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  3678. creater := adminInfo.AdminUser.Id
  3679. warehouseOut := models.WarehouseOut{
  3680. WarehouseOutOrderNumber: warehousing_out_order,
  3681. OperationTime: time.Now().Unix(),
  3682. OrgId: adminInfo.Org.Id,
  3683. Creater: creater,
  3684. Ctime: time.Now().Unix(),
  3685. Status: 1,
  3686. WarehouseOutTime: record_time,
  3687. Dealer: 0,
  3688. Manufacturer: 0,
  3689. Type: 1,
  3690. IsSys: 1,
  3691. }
  3692. err := service.AddSigleWarehouseOut(&warehouseOut)
  3693. if err != nil {
  3694. utils.TraceLog("创建出库单失败 err = %v", err)
  3695. } else {
  3696. for _, item := range consumables {
  3697. if item.Count > 0 {
  3698. warehouseOutInfo := &models.WarehouseOutInfo{
  3699. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  3700. WarehouseOutId: warehouseOut.ID,
  3701. Status: 1,
  3702. Ctime: time.Now().Unix(),
  3703. Remark: "",
  3704. OrgId: adminInfo.Org.Id,
  3705. Type: 1,
  3706. Manufacturer: 0,
  3707. Dealer: 0,
  3708. IsSys: 1,
  3709. SysRecordTime: record_time,
  3710. GoodTypeId: item.GoodTypeId,
  3711. GoodId: item.GoodId,
  3712. }
  3713. warehouseOutInfo.Count = item.Count
  3714. stockInInfo, _ := service.FindLastStockInInfoRecord(item.GoodId, adminInfo.Org.Id)
  3715. warehouseOutInfo.Price = stockInInfo.Price
  3716. err := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  3717. if err == nil {
  3718. details := &models.AutomaticReduceDetail{
  3719. WarehouseOutId: warehouseOutInfo.ID,
  3720. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  3721. PatientId: patient_id,
  3722. Ctime: time.Now().Unix(),
  3723. Mtime: time.Now().Unix(),
  3724. Status: 1,
  3725. RecordTime: record_time,
  3726. OrgId: adminInfo.Org.Id,
  3727. GoodId: item.GoodId,
  3728. GoodTypeId: item.GoodTypeId,
  3729. Count: item.Count,
  3730. }
  3731. service.AddSigleAutoReduceRecordInfo(details)
  3732. }
  3733. }
  3734. }
  3735. }
  3736. } else if err == nil {
  3737. for _, item := range consumables {
  3738. outInfo, err := service.FindStockOutInfoByTypeId(adminInfo.Org.Id, item.GoodTypeId, item.GoodId, out.ID, out.WarehouseOutOrderNumber)
  3739. if err == gorm.ErrRecordNotFound {
  3740. warehouseOutInfo := &models.WarehouseOutInfo{
  3741. WarehouseOutOrderNumber: out.WarehouseOutOrderNumber,
  3742. WarehouseOutId: out.ID,
  3743. Status: 1,
  3744. Ctime: time.Now().Unix(),
  3745. Remark: "",
  3746. OrgId: adminInfo.Org.Id,
  3747. Type: 1,
  3748. Manufacturer: 0,
  3749. Dealer: 0,
  3750. IsSys: 1,
  3751. SysRecordTime: record_time,
  3752. }
  3753. stockInInfo, _ := service.FindLastStockInInfoRecord(item.GoodId, adminInfo.Org.Id)
  3754. warehouseOutInfo.Price = stockInInfo.Price
  3755. warehouseOutInfo.GoodId = item.GoodId
  3756. warehouseOutInfo.GoodTypeId = item.GoodTypeId
  3757. warehouseOutInfo.Count = item.Count
  3758. err := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  3759. if err == nil {
  3760. details := &models.AutomaticReduceDetail{
  3761. WarehouseOutId: warehouseOutInfo.ID,
  3762. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  3763. PatientId: patient_id,
  3764. Ctime: time.Now().Unix(),
  3765. Mtime: time.Now().Unix(),
  3766. Status: 1,
  3767. RecordTime: record_time,
  3768. OrgId: adminInfo.Org.Id,
  3769. GoodId: item.GoodId,
  3770. GoodTypeId: item.GoodTypeId,
  3771. Count: item.Count,
  3772. }
  3773. service.AddSigleAutoReduceRecordInfo(details)
  3774. }
  3775. } else if err == nil { //记录存在,则将增加数量
  3776. if outInfo.ID > 0 {
  3777. service.UpdateStockOutInfoCount2(adminInfo.Org.Id, outInfo.ID, item.Count)
  3778. }
  3779. details := &models.AutomaticReduceDetail{
  3780. WarehouseOutId: outInfo.ID,
  3781. WarehouseOutOrderNumber: outInfo.WarehouseOutOrderNumber,
  3782. PatientId: patient_id,
  3783. Ctime: time.Now().Unix(),
  3784. Mtime: time.Now().Unix(),
  3785. Status: 1,
  3786. RecordTime: record_time,
  3787. OrgId: adminInfo.Org.Id,
  3788. GoodId: item.GoodId,
  3789. GoodTypeId: item.GoodTypeId,
  3790. Count: item.Count,
  3791. }
  3792. service.AddSigleAutoReduceRecordInfo(details)
  3793. }
  3794. }
  3795. }
  3796. c.ServeSuccessJSON(map[string]interface{}{
  3797. "msg": "提交成功",
  3798. })
  3799. return
  3800. } else {
  3801. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeOpenStocktWrong)
  3802. return
  3803. }
  3804. }
  3805. func RemoveRepeatedGood(arr []*models.DialysisBeforePrepare) (newArr []*models.DialysisBeforePrepare) {
  3806. newArr = make([]*models.DialysisBeforePrepare, 0)
  3807. for i := 0; i < len(arr); i++ {
  3808. repeat := false
  3809. for j := i + 1; j < len(arr); j++ {
  3810. if arr[i].GoodId == arr[j].GoodId && arr[i].GoodTypeId == arr[j].GoodTypeId {
  3811. repeat = true
  3812. break
  3813. }
  3814. }
  3815. if !repeat {
  3816. newArr = append(newArr, arr[i])
  3817. }
  3818. }
  3819. return
  3820. }
  3821. func (c *DialysisAPIController) GetAllDrug() {
  3822. patient_id, _ := c.GetInt64("patient_id", 0)
  3823. adminInfo := c.GetMobileAdminUserInfo()
  3824. _, drugStockConfig := service.FindDrugStockAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  3825. privateDrugConfig, _ := service.GetDrugSetByUserOrgId(adminInfo.Org.Id)
  3826. drugList, _ := service.GetAllBaseDrugLibList(adminInfo.Org.Id)
  3827. privateDrugList, _ := service.GetPrivateDrugList(patient_id, adminInfo.Org.Id)
  3828. c.ServeSuccessJSON(map[string]interface{}{
  3829. "base_drug_config": drugStockConfig,
  3830. "private_drug_config": privateDrugConfig,
  3831. "base_drug_list": drugList,
  3832. "private_drug_list": privateDrugList,
  3833. })
  3834. }
  3835. func RemoveRepeatedGoodTwo(arr []*models.DialysisBeforePrepare) (newArr []*models.DialysisBeforePrepare) {
  3836. newArr = make([]*models.DialysisBeforePrepare, 0)
  3837. for i := 0; i < len(arr); i++ {
  3838. repeat := false
  3839. for j := i + 1; j < len(arr); j++ {
  3840. if arr[i].GoodId == arr[j].GoodId {
  3841. repeat = true
  3842. break
  3843. }
  3844. }
  3845. if !repeat {
  3846. newArr = append(newArr, arr[i])
  3847. }
  3848. }
  3849. return
  3850. }
  3851. func (c *DialysisAPIController) GetDepartment() {
  3852. adminInfo := c.GetMobileAdminUserInfo()
  3853. departments, err := service.GetAllDepartMent(adminInfo.Org.Id)
  3854. if err == nil {
  3855. c.ServeSuccessJSON(map[string]interface{}{
  3856. "departments": departments,
  3857. })
  3858. } else {
  3859. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3860. return
  3861. }
  3862. }