dialysis_api_controller.go 162KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401
  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. difficult_puncture_nurse, _ := this.GetInt64("difficult_puncture_nurse")
  1326. new_fistula_nurse, _ := this.GetInt64("new_fistula_nurse")
  1327. if patientID <= 0 || len(recordDateStr) == 0 || nurseID <= 0 || bedID <= 0 {
  1328. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1329. return
  1330. }
  1331. startDate, parseStartDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", start_time)
  1332. if parseStartDateErr != nil {
  1333. this.ErrorLog("时间解析失败:%v", parseStartDateErr)
  1334. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1335. return
  1336. }
  1337. recordDate, parseErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1338. if parseErr != nil {
  1339. this.ErrorLog("时间解析失败:%v", parseErr)
  1340. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1341. return
  1342. }
  1343. adminUserInfo := this.GetMobileAdminUserInfo()
  1344. patient, getPatientErr := service.MobileGetPatientById(adminUserInfo.Org.Id, patientID)
  1345. if getPatientErr != nil {
  1346. this.ErrorLog("获取患者信息失败:%v", getPatientErr)
  1347. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1348. return
  1349. } else if patient == nil {
  1350. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1351. return
  1352. }
  1353. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  1354. if getNurseErr != nil {
  1355. this.ErrorLog("获取护士失败:%v", getNurseErr)
  1356. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1357. return
  1358. } else if nurse == nil {
  1359. this.ErrorLog("护士不存在")
  1360. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1361. return
  1362. }
  1363. nurse, getNurseErr = service.GetAdminUserByUserID(puncture_nurse)
  1364. if getNurseErr != nil {
  1365. this.ErrorLog("获取护士失败:%v", getNurseErr)
  1366. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1367. return
  1368. } else if nurse == nil {
  1369. this.ErrorLog("护士不存在")
  1370. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1371. return
  1372. }
  1373. deviceNumber, getDeviceNumberErr := service.GetDeviceNumberByID(adminUserInfo.Org.Id, bedID)
  1374. if getDeviceNumberErr != nil {
  1375. this.ErrorLog("获取床位号失败:%v", getDeviceNumberErr)
  1376. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1377. return
  1378. } else if deviceNumber == nil {
  1379. this.ErrorLog("床位号不存在")
  1380. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1381. return
  1382. }
  1383. dialysisRecord, getRecordErr := service.MobileGetDialysisRecord(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  1384. if getRecordErr != nil {
  1385. this.ErrorLog("获取透析记录失败:%v", getRecordErr)
  1386. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1387. return
  1388. } else if dialysisRecord != nil {
  1389. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatStart)
  1390. return
  1391. }
  1392. scheduleDateStart := startDate.Format("2006-01-02") + " 00:00:00"
  1393. scheduleDateEnd := startDate.Format("2006-01-02") + " 23:59:59"
  1394. timeLayout := "2006-01-02 15:04:05"
  1395. loc, _ := time.LoadLocation("Local")
  1396. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  1397. theEndTime, _ := time.ParseInLocation(timeLayout, scheduleDateEnd, loc)
  1398. schedulestartTime := theStartTime.Unix()
  1399. scheduleendTime := theEndTime.Unix()
  1400. template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  1401. //查询更改的机号,是否有人用了,如果只是排班了,但是没上机,直接替换,如果排班且上机了,就提示他无法上机
  1402. schedule, err := service.GetDayScheduleByBedid(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  1403. //查询该床位是否有人用了
  1404. order, order_err := service.GetDialysisOrderByBedId(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  1405. if err == gorm.ErrRecordNotFound { //空床位
  1406. // 修改了床位逻辑
  1407. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1408. if daySchedule.ID > 0 {
  1409. daySchedule.PartitionId = deviceNumber.ZoneID
  1410. daySchedule.BedId = bedID
  1411. daySchedule.ScheduleType = schedual_type
  1412. daySchedule.UpdatedTime = time.Now().Unix()
  1413. err := service.UpdateSchedule(&daySchedule)
  1414. if err != nil {
  1415. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1416. return
  1417. }
  1418. }
  1419. } else if err == nil {
  1420. if schedule.ID > 0 && schedule.DialysisOrder.ID == 0 { //有排班没上机记录
  1421. if order_err == nil {
  1422. if order.ID > 0 { //该机位被其他人占用了
  1423. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  1424. return
  1425. } else {
  1426. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1427. if daySchedule.ID > 0 {
  1428. daySchedule.PartitionId = deviceNumber.ZoneID
  1429. daySchedule.BedId = bedID
  1430. daySchedule.ScheduleType = schedual_type
  1431. daySchedule.UpdatedTime = time.Now().Unix()
  1432. err := service.UpdateSchedule(&daySchedule)
  1433. if err != nil {
  1434. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1435. return
  1436. }
  1437. }
  1438. }
  1439. } else if order_err == gorm.ErrRecordNotFound { //该床位没被占用
  1440. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1441. if daySchedule.ID > 0 {
  1442. daySchedule.PartitionId = deviceNumber.ZoneID
  1443. daySchedule.BedId = bedID
  1444. daySchedule.ScheduleType = schedual_type
  1445. daySchedule.UpdatedTime = time.Now().Unix()
  1446. err := service.UpdateSchedule(&daySchedule)
  1447. if err != nil {
  1448. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1449. return
  1450. }
  1451. }
  1452. }
  1453. } else if schedule.ID > 0 && schedule.DialysisOrder.ID > 0 { //有排班且有上机记录
  1454. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  1455. return
  1456. }
  1457. } else if err != nil {
  1458. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1459. return
  1460. }
  1461. dialysisRecord = &models.DialysisOrder{
  1462. DialysisDate: recordDate.Unix(),
  1463. UserOrgId: adminUserInfo.Org.Id,
  1464. PatientId: patientID,
  1465. Stage: 1,
  1466. BedID: bedID,
  1467. StartNurse: nurseID,
  1468. Status: 1,
  1469. StartTime: startDate.Unix(),
  1470. CreatedTime: time.Now().Unix(),
  1471. UpdatedTime: time.Now().Unix(),
  1472. PunctureNurse: puncture_nurse,
  1473. Creator: adminUserInfo.AdminUser.Id,
  1474. Modifier: adminUserInfo.AdminUser.Id,
  1475. SchedualType: schedual_type,
  1476. WashpipeNurse: washpipe_nurse,
  1477. ChangeNurse: change_nurse,
  1478. DifficultPunctureNurse: difficult_puncture_nurse,
  1479. NewFistulaNurse: new_fistula_nurse,
  1480. }
  1481. createErr := service.MobileCreateDialysisOrder(adminUserInfo.Org.Id, patientID, dialysisRecord)
  1482. newdialysisRecord, getRecordErr := service.MobileGetDialysisRecord(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  1483. var tempdispose string
  1484. // 只针对中能建
  1485. if blood_drawing > 0 && adminUserInfo.Org.Id == 9538 {
  1486. tempdispose = "引血" + strconv.FormatInt(blood_drawing, 10) + "ml/min"
  1487. }
  1488. var ultrafiltration_rate float64
  1489. _, prescription := service.FindDialysisPrescriptionByReordDate(patientID, schedulestartTime, adminUserInfo.Org.Id)
  1490. if prescription.ID > 0 {
  1491. if prescription.TargetUltrafiltration > 0 && prescription.DialysisDurationHour > 0 {
  1492. totalMin := prescription.DialysisDurationHour*60 + prescription.DialysisDurationMinute
  1493. if template.TemplateId == 6 || template.TemplateId == 32 { //adminUserInfo.Org.Id == 9538
  1494. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1000)
  1495. }
  1496. if template.TemplateId == 20 || template.TemplateId == 22 { //adminUserInfo.Org.Id == 9538
  1497. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60)
  1498. }
  1499. // 只针对方济医院
  1500. if template.TemplateId == 1 && adminUserInfo.Org.Id != 9849 {
  1501. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", prescription.TargetUltrafiltration/float64(totalMin)*60), 6)
  1502. ultrafiltration_rate = value
  1503. }
  1504. }
  1505. }
  1506. record := models.MonitoringRecord{
  1507. UserOrgId: adminUserInfo.Org.Id,
  1508. PatientId: patientID,
  1509. DialysisOrderId: dialysisRecord.ID,
  1510. MonitoringDate: schedulestartTime,
  1511. OperateTime: startDate.Unix(),
  1512. // MonitoringTime: recordTime,
  1513. MonitoringNurse: nurseID,
  1514. Dispose: tempdispose,
  1515. UltrafiltrationRate: ultrafiltration_rate,
  1516. UltrafiltrationVolume: 0,
  1517. Status: 1,
  1518. CreatedTime: time.Now().Unix(),
  1519. UpdatedTime: time.Now().Unix(),
  1520. }
  1521. //只针对广慈医院
  1522. if template.TemplateId == 26 || template.TemplateId == 25 || template.TemplateId == 28 || adminUserInfo.Org.Id == 9987 || adminUserInfo.Org.Id == 9526 || template.TemplateId == 32 {
  1523. // 查询病人是否有透前评估数据
  1524. befor, errcode := service.GetAssessmentBefor(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  1525. //如果有数据就插入
  1526. if errcode == nil {
  1527. record.SystolicBloodPressure = befor.SystolicBloodPressure
  1528. record.DiastolicBloodPressure = befor.DiastolicBloodPressure
  1529. record.BreathingRate = befor.BreathingRate
  1530. record.PulseFrequency = befor.PulseFrequency
  1531. record.Temperature = befor.Temperature
  1532. }
  1533. }
  1534. // 如果当天有插入数据,则不再往透析纪录里插入数据
  1535. if newdialysisRecord.ID > 0 {
  1536. err := service.CreateMonitor(&record)
  1537. if err != nil {
  1538. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeMonitorCreate)
  1539. return
  1540. }
  1541. }
  1542. go func() {
  1543. ssoDomain := beego.AppConfig.String("call_domain")
  1544. api := ssoDomain + "/index/uppatient"
  1545. values := make(url.Values)
  1546. values.Set("org_id", strconv.FormatInt(adminUserInfo.Org.Id, 10))
  1547. values.Set("admin_user_id", strconv.FormatInt(nurseID, 10))
  1548. values.Set("patient_id", strconv.FormatInt(patientID, 10))
  1549. values.Set("up_time", strconv.FormatInt(startDate.Unix(), 10))
  1550. http.PostForm(api, values)
  1551. }()
  1552. if createErr != nil {
  1553. this.ErrorLog("上机失败:%v", createErr)
  1554. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1555. return
  1556. }
  1557. this.ServeSuccessJSON(map[string]interface{}{
  1558. "dialysis_order": newdialysisRecord,
  1559. "monitor": record,
  1560. })
  1561. }
  1562. func (c *DialysisAPIController) PostSolution() {
  1563. id, _ := c.GetInt64("patient", 0)
  1564. recordDateStr := c.GetString("record_date")
  1565. if id <= 0 {
  1566. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1567. return
  1568. }
  1569. adminUserInfo := c.GetMobileAdminUserInfo()
  1570. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  1571. if patient.ID == 0 {
  1572. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1573. return
  1574. }
  1575. if len(recordDateStr) == 0 {
  1576. recordDateStr = time.Now().Format("2006-01-02")
  1577. }
  1578. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1579. if parseDateErr != nil {
  1580. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  1581. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1582. return
  1583. }
  1584. mode_id, _ := c.GetInt64("mode_id", 0)
  1585. dialysis_duration, _ := c.GetFloat("dialysis_duration", 0)
  1586. dialyzer, _ := c.GetInt64("dialyzer", 0)
  1587. perfusion_apparatus, _ := c.GetInt64("perfusion_apparatus", 0)
  1588. blood_flow_volume, _ := c.GetFloat("blood_flow_volume", 0)
  1589. dewater_amount, _ := c.GetFloat("dewater_amount", 0)
  1590. displace_liqui, _ := c.GetFloat("displace_liqui", 0)
  1591. replacement_way, _ := c.GetInt64("replacement_way", 0)
  1592. anticoagulant, _ := c.GetInt64("anticoagulant", 0)
  1593. anticoagulant_shouji, _ := c.GetFloat("anticoagulant_shouji", 0)
  1594. anticoagulant_weichi, _ := c.GetFloat("anticoagulant_weichi", 0)
  1595. anticoagulant_zongliang, _ := c.GetFloat("anticoagulant_zongliang", 0)
  1596. anticoagulant_gaimingcheng := c.GetString("anticoagulant_gaimingcheng")
  1597. anticoagulant_gaijiliang := c.GetString("anticoagulant_gaijiliang")
  1598. kalium, _ := c.GetFloat("kalium", 0)
  1599. sodium, _ := c.GetFloat("sodium", 0)
  1600. calcium, _ := c.GetFloat("calcium", 0)
  1601. bicarbonate, _ := c.GetFloat("bicarbonate", 0)
  1602. prescription_doctor, _ := c.GetInt64("prescription_doctor", 0)
  1603. dialyzerPerfusionApparatus := c.GetString("dialyzer_perfusion_apparatus")
  1604. glucose, _ := c.GetFloat("glucose", 0)
  1605. // dry_weight, _ := c.GetFloat("dry_weight", 0)
  1606. dialysate_flow, _ := c.GetFloat("dialysate_flow", 0)
  1607. dialysate_temperature, _ := c.GetFloat("dialysate_temperature", 0)
  1608. conductivity, _ := c.GetFloat("conductivity", 0)
  1609. remark := c.GetString("remark")
  1610. dialysisDurationHour, _ := c.GetInt64("dialysis_duration_hour", 0)
  1611. dialysisDurationMinute, _ := c.GetInt64("dialysis_duration_minute", 0)
  1612. targetUltrafiltration, _ := c.GetFloat("target_ultrafiltration", 0)
  1613. dialysateFormulation, _ := c.GetInt64("dialysate_formulation", 0)
  1614. body_fluid, _ := c.GetInt64("body_fluid", 0)
  1615. special_medicine, _ := c.GetInt64("special_medicine", 0)
  1616. special_medicine_other := c.GetString("special_medicine_other")
  1617. displace_liqui_part, _ := c.GetInt64("displace_liqui_part", 0)
  1618. displace_liqui_value, _ := c.GetFloat("displace_liqui_value", 0)
  1619. blood_access, _ := c.GetInt64("blood_access", 0)
  1620. ultrafiltration, _ := c.GetFloat("ultrafiltration", 0)
  1621. body_fluid_other := c.GetString("body_fluid_other")
  1622. replacement_total, _ := c.GetFloat("replacement_total", 0)
  1623. niprocart, _ := c.GetInt64("niprocart", 0)
  1624. jms, _ := c.GetInt64("jms", 0)
  1625. fistula_needle_set, _ := c.GetInt64("fistula_needle_set", 0)
  1626. fistula_needle_set_16, _ := c.GetInt64("fistula_needle_set_16", 0)
  1627. hemoperfusion, _ := c.GetInt64("hemoperfusion", 0)
  1628. dialyser_sterilised, _ := c.GetInt64("dialyser_sterilised", 0)
  1629. filtryzer, _ := c.GetInt64("filtryzer", 0)
  1630. target_ktv, _ := c.GetFloat("target_ktv", 0)
  1631. dialyzers, _ := c.GetInt64("dialyzers", 0)
  1632. injector, _ := c.GetInt64("injector", 0)
  1633. bloodlines, _ := c.GetInt64("bloodlines", 0)
  1634. tubing_hemodialysis, _ := c.GetInt64("tubing_hemodialysis", 0)
  1635. safe_package, _ := c.GetInt64("package", 0)
  1636. a_liquid, _ := c.GetInt64("a_liquid", 0)
  1637. anticoagulant_stop_time_hour, _ := c.GetInt64("anticoagulant_stop_time_hour", 0)
  1638. anticoagulant_stop_time_min, _ := c.GetInt64("anticoagulant_stop_time_min", 0)
  1639. blood := c.GetString("blood")
  1640. dialysis_dialyszers := c.GetString("dialysis_dialyszers")
  1641. dialysis_irrigation := c.GetString("dialysis_irrigation")
  1642. antioxidant_commodity_name := c.GetString("antioxidant_commodity_name")
  1643. if mode_id > 0 {
  1644. service.ModifyScheduleMode(mode_id, patient.ID, recordDate.Unix(), adminUserInfo.Org.Id)
  1645. }
  1646. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  1647. //
  1648. //if template.TemplateId == 2 || template.TemplateId == 6 {
  1649. // if appRole.UserType == 3 {
  1650. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1651. // if getPermissionErr != nil {
  1652. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1653. // return
  1654. // } else if headNursePermission == nil {
  1655. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  1656. // return
  1657. // }
  1658. // }
  1659. //}
  1660. prescription := models.DialysisPrescription{
  1661. UserOrgId: adminUserInfo.Org.Id,
  1662. PatientId: id,
  1663. RecordDate: recordDate.Unix(),
  1664. ModeId: mode_id,
  1665. DialysisDuration: dialysis_duration,
  1666. Dialyzer: dialyzer,
  1667. PerfusionApparatus: perfusion_apparatus,
  1668. BloodFlowVolume: blood_flow_volume,
  1669. DewaterAmount: dewater_amount,
  1670. DisplaceLiqui: displace_liqui,
  1671. ReplacementWay: replacement_way,
  1672. Anticoagulant: anticoagulant,
  1673. AnticoagulantShouji: anticoagulant_shouji,
  1674. AnticoagulantWeichi: anticoagulant_weichi,
  1675. AnticoagulantZongliang: anticoagulant_zongliang,
  1676. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  1677. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  1678. Kalium: kalium,
  1679. Sodium: sodium,
  1680. Calcium: calcium,
  1681. Bicarbonate: bicarbonate,
  1682. Glucose: glucose,
  1683. // DryWeight: dry_weight,
  1684. DialysateFlow: dialysate_flow,
  1685. DialysateTemperature: dialysate_temperature,
  1686. Conductivity: conductivity,
  1687. Remark: remark,
  1688. Status: 1,
  1689. CreatedTime: time.Now().Unix(),
  1690. UpdatedTime: time.Now().Unix(),
  1691. DialysisDurationMinute: dialysisDurationMinute,
  1692. DialysisDurationHour: dialysisDurationHour,
  1693. TargetUltrafiltration: targetUltrafiltration,
  1694. DialysateFormulation: dialysateFormulation,
  1695. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  1696. BodyFluid: body_fluid,
  1697. SpecialMedicine: special_medicine,
  1698. SpecialMedicineOther: special_medicine_other,
  1699. DisplaceLiquiPart: displace_liqui_part,
  1700. DisplaceLiquiValue: displace_liqui_value,
  1701. BloodAccess: blood_access,
  1702. Ultrafiltration: ultrafiltration,
  1703. BodyFluidOther: body_fluid_other,
  1704. ReplacementTotal: replacement_total,
  1705. Niprocart: niprocart,
  1706. Jms: jms,
  1707. FistulaNeedleSet: fistula_needle_set,
  1708. FistulaNeedleSet16: fistula_needle_set_16,
  1709. Hemoperfusion: hemoperfusion,
  1710. DialyserSterilised: dialyser_sterilised,
  1711. Filtryzer: filtryzer,
  1712. TargetKtv: target_ktv,
  1713. Dialyzers: dialyzers,
  1714. Injector: injector,
  1715. Bloodlines: bloodlines,
  1716. TubingHemodialysis: tubing_hemodialysis,
  1717. Package: safe_package,
  1718. ALiquid: a_liquid,
  1719. AnticoagulantStopTimeMin: anticoagulant_stop_time_min,
  1720. AnticoagulantStopTimeHour: anticoagulant_stop_time_hour,
  1721. Blood: blood,
  1722. DialysisDialyszers: dialysis_dialyszers,
  1723. DialysisIrrigation: dialysis_irrigation,
  1724. AntioxidantCommodityName: antioxidant_commodity_name,
  1725. }
  1726. _, dialysisPrescription := service.FindDialysisPrescriptionByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  1727. appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id, adminUserInfo.App.Id)
  1728. //
  1729. if appRole.UserType == 2 || appRole.UserType == 1 {
  1730. prescription_doctor = adminUserInfo.AdminUser.Id
  1731. prescription.PrescriptionDoctor = prescription_doctor
  1732. }
  1733. if dialysisPrescription.ID == 0 { //新增
  1734. prescription.Creater = adminUserInfo.AdminUser.Id
  1735. } else { //修改
  1736. if dialysisPrescription.Creater == 0 {
  1737. prescription.Creater = adminUserInfo.AdminUser.Id
  1738. } else {
  1739. prescription.Creater = dialysisPrescription.Creater
  1740. }
  1741. //if/**/
  1742. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  1743. //if dialysisPrescription.Creater != adminUserInfo.AdminUser.Id && dialysisPrescription.Creater > 0 {
  1744. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1745. // if getPermissionErr != nil {
  1746. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1747. // return
  1748. // } else if headNursePermission == nil {
  1749. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  1750. // return
  1751. // }
  1752. //}
  1753. //prescription.Creater = dialysisPrescription.Creater
  1754. prescription.CreatedTime = dialysisPrescription.CreatedTime
  1755. prescription.Modifier = adminUserInfo.AdminUser.Id
  1756. prescription.ID = dialysisPrescription.ID
  1757. }
  1758. solution := models.DialysisSolution{
  1759. RegistrarsId: adminUserInfo.AdminUser.Id,
  1760. UserOrgId: adminUserInfo.Org.Id,
  1761. Doctor: prescription_doctor,
  1762. PatientId: id,
  1763. ModeId: mode_id,
  1764. DialysisDuration: dialysis_duration,
  1765. PerfusionApparatus: perfusion_apparatus,
  1766. BloodFlowVolume: blood_flow_volume,
  1767. Dewater: dewater_amount,
  1768. DisplaceLiqui: displace_liqui,
  1769. ReplacementWay: replacement_way,
  1770. Anticoagulant: anticoagulant,
  1771. AnticoagulantShouji: anticoagulant_shouji,
  1772. AnticoagulantWeichi: anticoagulant_weichi,
  1773. AnticoagulantZongliang: anticoagulant_zongliang,
  1774. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  1775. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  1776. Kalium: kalium,
  1777. Sodium: sodium,
  1778. Calcium: calcium,
  1779. Bicarbonate: bicarbonate,
  1780. Glucose: glucose,
  1781. // DryWeight: dry_weight,
  1782. DialysateFlow: dialysate_flow,
  1783. DialysateTemperature: dialysate_temperature,
  1784. Conductivity: conductivity,
  1785. Remark: remark,
  1786. Status: 1,
  1787. CreatedTime: time.Now().Unix(),
  1788. UpdatedTime: time.Now().Unix(),
  1789. DialysisDurationMinute: dialysisDurationMinute,
  1790. DialysisDurationHour: dialysisDurationHour,
  1791. TargetUltrafiltration: targetUltrafiltration,
  1792. DialysateFormulation: dialysateFormulation,
  1793. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  1794. BodyFluid: body_fluid,
  1795. SpecialMedicine: special_medicine,
  1796. SpecialMedicineOther: special_medicine_other,
  1797. DisplaceLiquiPart: displace_liqui_part,
  1798. DisplaceLiquiValue: displace_liqui_value,
  1799. BloodAccess: blood_access,
  1800. Ultrafiltration: ultrafiltration,
  1801. BodyFluidOther: body_fluid_other,
  1802. ReplacementTotal: replacement_total,
  1803. TargetKtv: target_ktv,
  1804. }
  1805. service.SavePrescriptionAndCreateSolution(&solution, &prescription)
  1806. c.ServeSuccessJSON(map[string]interface{}{
  1807. "solution": &solution,
  1808. "prescription": &prescription,
  1809. })
  1810. }
  1811. func (c *DialysisAPIController) GetAcceptsAssessment() {
  1812. patient, _ := c.GetInt64("patient", 0)
  1813. adminUserInfo := c.GetMobileAdminUserInfo()
  1814. _, receiveTreatmentAsses := service.GetLastAcceptsAssessment(patient, adminUserInfo.Org.Id)
  1815. c.ServeSuccessJSON(map[string]interface{}{
  1816. "receiveTreatmentAsses": receiveTreatmentAsses,
  1817. })
  1818. }
  1819. func (this *DialysisAPIController) PostSignInfo() {
  1820. patientID, _ := this.GetInt64("patient_id")
  1821. recordDateStr := this.GetString("date")
  1822. if patientID <= 0 {
  1823. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1824. return
  1825. }
  1826. if len(recordDateStr) == 0 {
  1827. recordDateStr = time.Now().Format("2006-01-02")
  1828. }
  1829. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1830. if parseDateErr != nil {
  1831. this.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  1832. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1833. return
  1834. }
  1835. adminInfo := this.GetMobileAdminUserInfo()
  1836. err := service.UpDateDialysisPrescriptionDoctorSign(patientID, date.Unix(), adminInfo.Org.Id, adminInfo.AdminUser.Id)
  1837. if err != nil {
  1838. this.ErrorLog("签名失败:%v", err)
  1839. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1840. return
  1841. }
  1842. this.ServeSuccessJSON(map[string]interface{}{
  1843. "doctor_id": adminInfo.AdminUser.Id,
  1844. })
  1845. }
  1846. func (this *DialysisAPIController) GetLastMonitorRecord() {
  1847. patientID, _ := this.GetInt64("patient_id")
  1848. adminInfo := this.GetMobileAdminUserInfo()
  1849. record, _ := service.FindLastMonitorRecord(patientID, adminInfo.Org.Id)
  1850. this.ServeSuccessJSON(map[string]interface{}{
  1851. "monitor": record,
  1852. })
  1853. }
  1854. func (this *DialysisAPIController) GetLastMonitorRecordTody() {
  1855. thisTime := time.Now()
  1856. scheduleDateStart := thisTime.Format("2006-01-02") + " 00:00:00"
  1857. timeLayout := "2006-01-02 15:04:05"
  1858. loc, _ := time.LoadLocation("Local")
  1859. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  1860. theAssessmentDateTime := theStartTime.Unix()
  1861. patientID, _ := this.GetInt64("patient_id")
  1862. monitorDate, _ := this.GetInt64("monitoring_date", theAssessmentDateTime)
  1863. adminInfo := this.GetMobileAdminUserInfo()
  1864. record, _ := service.FindLastMonitorRecordToday(patientID, adminInfo.Org.Id, monitorDate)
  1865. fristrecord, _ := service.FindFirstMonitorRecordToday(patientID, adminInfo.Org.Id, monitorDate)
  1866. template, _ := service.GetOrgInfoTemplate(adminInfo.Org.Id)
  1867. var ultrafiltration_rate float64
  1868. _, prescription := service.FindDialysisPrescriptionByReordDate(patientID, theAssessmentDateTime, adminInfo.Org.Id)
  1869. if prescription.ID > 0 {
  1870. if prescription.TargetUltrafiltration > 0 && prescription.DialysisDurationHour > 0 {
  1871. totalMin := prescription.DialysisDurationHour*60 + prescription.DialysisDurationMinute
  1872. if template.TemplateId == 6 {
  1873. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1000)
  1874. record.UltrafiltrationRate = ultrafiltration_rate
  1875. }
  1876. if template.TemplateId == 20 || template.TemplateId == 22 || template.TemplateId == 32 || template.TemplateId == 34 {
  1877. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60)
  1878. record.UltrafiltrationRate = ultrafiltration_rate
  1879. }
  1880. // 只针对方济医院
  1881. if template.TemplateId == 1 && adminInfo.Org.Id != 9849 {
  1882. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", prescription.TargetUltrafiltration/float64(totalMin)*60), 6)
  1883. ultrafiltration_rate = value
  1884. record.UltrafiltrationRate = ultrafiltration_rate
  1885. }
  1886. }
  1887. }
  1888. // record.UltrafiltrationRate = ultrafiltration_rate
  1889. record.UltrafiltrationVolume = 0
  1890. 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
  1891. if ultrafiltration_rate > 0 {
  1892. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", float64(record.OperateTime+3600-fristrecord.OperateTime)/3600*ultrafiltration_rate), 6)
  1893. record.UltrafiltrationVolume = value
  1894. }
  1895. }
  1896. if template.TemplateId == 6 || template.TemplateId == 20 || template.TemplateId == 22 || template.TemplateId == 32 || template.TemplateId == 34 { //adminInfo.Org.Id == 9538
  1897. if ultrafiltration_rate > 0 && adminInfo.Org.Id != 9538 {
  1898. ultrafiltration_volume := math.Floor(float64(record.OperateTime+3600-fristrecord.OperateTime) / 3600 * ultrafiltration_rate)
  1899. record.UltrafiltrationVolume = ultrafiltration_volume
  1900. }
  1901. }
  1902. this.ServeSuccessJSON(map[string]interface{}{
  1903. "monitor": record,
  1904. })
  1905. }
  1906. func (this *DialysisAPIController) ModifyStartDialysisOrder() {
  1907. record_id, _ := this.GetInt64("id")
  1908. nurseID, _ := this.GetInt64("nurse")
  1909. puncture_nurse, _ := this.GetInt64("puncture_nurse")
  1910. bedID, _ := this.GetInt64("bed")
  1911. start_time := this.GetString("start_time")
  1912. schedual_type, _ := this.GetInt64("schedual_type")
  1913. washpipe_nurse, _ := this.GetInt64("washpipe_nurse")
  1914. change_nurse, _ := this.GetInt64("change_nurse")
  1915. difficult_puncture_nurse, _ := this.GetInt64("difficult_puncture_nurse")
  1916. new_fistula_nurse, _ := this.GetInt64("new_fistula_nurse")
  1917. if record_id == 0 {
  1918. this.ErrorLog("id:%v", record_id)
  1919. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1920. return
  1921. }
  1922. startDate, parseStartDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", start_time)
  1923. if parseStartDateErr != nil {
  1924. this.ErrorLog("时间解析失败:%v", parseStartDateErr)
  1925. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1926. return
  1927. }
  1928. adminUserInfo := this.GetMobileAdminUserInfo()
  1929. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  1930. if getNurseErr != nil {
  1931. this.ErrorLog("获取护士失败:%v", getNurseErr)
  1932. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1933. return
  1934. } else if nurse == nil {
  1935. this.ErrorLog("护士不存在")
  1936. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1937. return
  1938. }
  1939. nurse, getNurseErr = service.GetAdminUserByUserID(puncture_nurse)
  1940. if getNurseErr != nil {
  1941. this.ErrorLog("获取护士失败:%v", getNurseErr)
  1942. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1943. return
  1944. } else if nurse == nil {
  1945. this.ErrorLog("护士不存在")
  1946. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1947. return
  1948. }
  1949. deviceNumber, getDeviceNumberErr := service.GetDeviceNumberByID(adminUserInfo.Org.Id, bedID)
  1950. if getDeviceNumberErr != nil {
  1951. this.ErrorLog("获取床位号失败:%v", getDeviceNumberErr)
  1952. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1953. return
  1954. } else if deviceNumber == nil {
  1955. this.ErrorLog("床位号不存在")
  1956. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1957. return
  1958. }
  1959. _, tempDialysisRecord := service.FindDialysisOrderById(record_id)
  1960. //
  1961. //if tempDialysisRecord.Creator != adminUserInfo.AdminUser.Id {
  1962. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1963. // if getPermissionErr != nil {
  1964. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1965. // return
  1966. // } else if headNursePermission == nil {
  1967. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  1968. // return
  1969. // }
  1970. //}
  1971. scheduleDateStart := startDate.Format("2006-01-02") + " 00:00:00"
  1972. scheduleDateEnd := startDate.Format("2006-01-02") + " 23:59:59"
  1973. timeLayout := "2006-01-02 15:04:05"
  1974. loc, _ := time.LoadLocation("Local")
  1975. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  1976. theEndTime, _ := time.ParseInLocation(timeLayout, scheduleDateEnd, loc)
  1977. schedulestartTime := theStartTime.Unix()
  1978. scheduleendTime := theEndTime.Unix()
  1979. //查询更改的机号,是否有人用了,如果只是排班了,但是没上机,直接替换,如果排班且上机了,就提示他无法上机
  1980. schedule, err := service.GetDayScheduleByBedid(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  1981. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  1982. if daySchedule.BedId != bedID || daySchedule.ScheduleType != schedual_type {
  1983. if err == gorm.ErrRecordNotFound { //空床位
  1984. // 修改了床位逻辑
  1985. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  1986. if daySchedule.ID > 0 {
  1987. daySchedule.BedId = bedID
  1988. daySchedule.PartitionId = deviceNumber.ZoneID
  1989. daySchedule.ScheduleType = schedual_type
  1990. daySchedule.UpdatedTime = time.Now().Unix()
  1991. err := service.UpdateSchedule(&daySchedule)
  1992. if err != nil {
  1993. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1994. return
  1995. }
  1996. }
  1997. } else if err == nil {
  1998. if schedule.ID > 0 && schedule.DialysisOrder.ID == 0 { //有排班没上机记录
  1999. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  2000. if daySchedule.ID > 0 {
  2001. daySchedule.BedId = bedID
  2002. daySchedule.PartitionId = deviceNumber.ZoneID
  2003. daySchedule.ScheduleType = schedual_type
  2004. daySchedule.UpdatedTime = time.Now().Unix()
  2005. err := service.UpdateSchedule(&daySchedule)
  2006. if err != nil {
  2007. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2008. return
  2009. }
  2010. }
  2011. } else if schedule.ID > 0 && schedule.DialysisOrder.ID > 0 { //有排班且有上机记录
  2012. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  2013. return
  2014. }
  2015. } else if err != nil {
  2016. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2017. return
  2018. }
  2019. }
  2020. dialysisRecord := &models.DialysisOrder{
  2021. ID: record_id,
  2022. UserOrgId: adminUserInfo.Org.Id,
  2023. BedID: bedID,
  2024. StartNurse: nurseID,
  2025. StartTime: startDate.Unix(),
  2026. PunctureNurse: puncture_nurse,
  2027. Creator: adminUserInfo.AdminUser.Id,
  2028. Modifier: adminUserInfo.AdminUser.Id,
  2029. WashpipeNurse: washpipe_nurse,
  2030. SchedualType: schedual_type,
  2031. ChangeNurse: change_nurse,
  2032. DifficultPunctureNurse: difficult_puncture_nurse,
  2033. NewFistulaNurse: new_fistula_nurse,
  2034. }
  2035. updateErr := service.ModifyStartDialysisOrder(dialysisRecord)
  2036. if updateErr != nil {
  2037. this.ErrorLog("修改上机失败:%v", updateErr)
  2038. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2039. return
  2040. }
  2041. if updateErr == nil {
  2042. if tempDialysisRecord.Stage == 2 {
  2043. temp_time := (float64(tempDialysisRecord.EndTime) - float64(startDate.Unix())) / 3600
  2044. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  2045. fmt.Println(value)
  2046. a, b := math.Modf(value)
  2047. tempMinute, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  2048. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  2049. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", tempMinute*60), 10, 64)
  2050. updateAssessmentErr := service.UpdateAssessmentAfterDate(tempDialysisRecord.PatientId, tempDialysisRecord.UserOrgId, tempDialysisRecord.DialysisDate, hour, minute)
  2051. if updateAssessmentErr != nil {
  2052. utils.ErrorLog("%v", updateAssessmentErr)
  2053. }
  2054. }
  2055. }
  2056. _, dialysisRecords := service.FindDialysisOrderById(record_id)
  2057. this.ServeSuccessJSON(map[string]interface{}{
  2058. "dialysis_order": dialysisRecords,
  2059. })
  2060. }
  2061. func (c *DialysisAPIController) ModifyFinishDialysisOrder() {
  2062. record_id, _ := c.GetInt64("id")
  2063. nurseID, _ := c.GetInt64("nurse")
  2064. end_time := c.GetString("end_time")
  2065. if record_id <= 0 || nurseID <= 0 {
  2066. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2067. return
  2068. }
  2069. adminUserInfo := c.GetMobileAdminUserInfo()
  2070. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  2071. if getNurseErr != nil {
  2072. c.ErrorLog("获取护士失败:%v", getNurseErr)
  2073. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2074. return
  2075. } else if nurse == nil {
  2076. c.ErrorLog("护士不存在")
  2077. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2078. return
  2079. }
  2080. endDate, parseEndDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", end_time)
  2081. if parseEndDateErr != nil {
  2082. c.ErrorLog("日期(%v)解析错误:%v", end_time, parseEndDateErr)
  2083. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2084. return
  2085. }
  2086. _, tempDialysisRecords := service.FindDialysisOrderById(record_id)
  2087. //if tempDialysisRecords.FinishCreator != adminUserInfo.AdminUser.Id {
  2088. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  2089. // if getPermissionErr != nil {
  2090. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2091. // return
  2092. // } else if headNursePermission == nil {
  2093. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  2094. // return
  2095. // }
  2096. //}
  2097. dialysisRecord := &models.DialysisOrder{
  2098. ID: record_id,
  2099. UserOrgId: adminUserInfo.Org.Id,
  2100. EndTime: endDate.Unix(),
  2101. FinishNurse: nurseID,
  2102. FinishModifier: adminUserInfo.AdminUser.Id,
  2103. }
  2104. updateErr := service.ModifyFinishDialysisOrder(dialysisRecord)
  2105. if updateErr != nil {
  2106. c.ErrorLog("修改下机失败:%v", updateErr)
  2107. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2108. return
  2109. }
  2110. if updateErr == nil {
  2111. temp_time := (float64(endDate.Unix()) - float64(tempDialysisRecords.StartTime)) / 3600
  2112. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  2113. a, b := math.Modf(value)
  2114. tempMinute, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  2115. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  2116. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", tempMinute*60), 10, 64)
  2117. updateAssessmentErr := service.UpdateAssessmentAfterDate(tempDialysisRecords.PatientId, tempDialysisRecords.UserOrgId, tempDialysisRecords.DialysisDate, hour, minute)
  2118. if updateAssessmentErr != nil {
  2119. utils.ErrorLog("%v", updateAssessmentErr)
  2120. }
  2121. }
  2122. _, dialysisRecords := service.FindDialysisOrderById(record_id)
  2123. c.ServeSuccessJSON(map[string]interface{}{
  2124. "dialysis_order": dialysisRecords,
  2125. })
  2126. }
  2127. func (c *DialysisAPIController) GetLongAdvice() {
  2128. patient_id, _ := c.GetInt64("id")
  2129. adminUserInfo := c.GetMobileAdminUserInfo()
  2130. _, config := service.FindDoctorAdviceRecordByOrgId(adminUserInfo.Org.Id)
  2131. //patient, _ := service.FindPatientIsOpenRemindById(patient_id, adminUserInfo.Org.Id)
  2132. if config.IsOpenRemind == 0 { //针对老用户,即没开启推送功能,也没有 不开启推送功能,不做任何处理
  2133. c.ServeSuccessJSON(map[string]interface{}{
  2134. "status": "1",
  2135. })
  2136. return
  2137. } else { //开启推送提醒
  2138. //开启推送提醒逻辑 提交长期处方的时候,弹起长期医嘱推送
  2139. var advice_three []*models.DoctorAdvice
  2140. //groupNo := service.GetMaxLongAdviceGroupID(adminUserInfo.Org.Id, patient_id)
  2141. advices, err := service.GetLastLongAdviceByGroupNo(adminUserInfo.Org.Id, patient_id)
  2142. advices_two, err := service.GetLastLongAdviceByGroupNoThree(adminUserInfo.Org.Id, patient_id)
  2143. for _, advice := range advices {
  2144. if advice.FrequencyType == 3 {
  2145. t := time.Now()
  2146. week := int(t.Weekday())
  2147. fmt.Println(t.Weekday())
  2148. fmt.Println(week)
  2149. switch week {
  2150. case 1:
  2151. if strings.Index(advice.WeekDay, "周一") == -1 {
  2152. advice_three = append(advice_three, advice)
  2153. }
  2154. break
  2155. case 2:
  2156. if strings.Index(advice.WeekDay, "周二") == -1 {
  2157. advice_three = append(advice_three, advice)
  2158. }
  2159. break
  2160. case 3:
  2161. if strings.Index(advice.WeekDay, "周三") == -1 {
  2162. advice_three = append(advice_three, advice)
  2163. }
  2164. break
  2165. case 4:
  2166. if strings.Index(advice.WeekDay, "周四") == -1 {
  2167. advice_three = append(advice_three, advice)
  2168. }
  2169. break
  2170. case 5:
  2171. if strings.Index(advice.WeekDay, "周五") == -1 {
  2172. advice_three = append(advice_three, advice)
  2173. }
  2174. break
  2175. case 6:
  2176. if strings.Index(advice.WeekDay, "周六") == -1 {
  2177. advice_three = append(advice_three, advice)
  2178. }
  2179. break
  2180. case 0:
  2181. if strings.Index(advice.WeekDay, "周日") == -1 {
  2182. advice_three = append(advice_three, advice)
  2183. }
  2184. break
  2185. }
  2186. }
  2187. }
  2188. for _, advice := range advices_two {
  2189. p, _ := time.Parse("2006-01-02", time.Now().Format("2006-01-02"))
  2190. now := p.Unix()
  2191. dayStr := strconv.FormatInt(advice.DayCount, 10)
  2192. dayStr2 := "-" + dayStr
  2193. count, _ := strconv.ParseInt(dayStr2, 10, 64)
  2194. oldTime := time.Now().AddDate(0, 0, int(count)).Unix()
  2195. advices, _ := service.FindAllDoctorAdviceByTime(now, oldTime, patient_id, adminUserInfo.Org.Id, advice.TemplateId)
  2196. for _, ad := range advices {
  2197. advice_three = append(advice_three, ad)
  2198. }
  2199. }
  2200. if err == nil {
  2201. c.ServeSuccessJSON(map[string]interface{}{
  2202. "status": "2",
  2203. "advices": advices,
  2204. "advices_two": RemoveRepeatedElement(advice_three),
  2205. "is_open_remind": config.IsOpenRemind,
  2206. })
  2207. }
  2208. }
  2209. }
  2210. func RemoveRepeatedElement(arr []*models.DoctorAdvice) (newArr []*models.DoctorAdvice) {
  2211. newArr = make([]*models.DoctorAdvice, 0)
  2212. for i := 0; i < len(arr); i++ {
  2213. repeat := false
  2214. for j := i + 1; j < len(arr); j++ {
  2215. if arr[i].ID == arr[j].ID {
  2216. repeat = true
  2217. break
  2218. }
  2219. }
  2220. if !repeat {
  2221. newArr = append(newArr, arr[i])
  2222. }
  2223. }
  2224. return
  2225. }
  2226. func (c *DialysisAPIController) CreateRemindDoctorAdvice() {
  2227. patient, _ := c.GetInt64("id", 0)
  2228. groupNo, _ := c.GetInt64("groupno", 0)
  2229. if patient <= 0 {
  2230. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2231. return
  2232. }
  2233. adminUserInfo := c.GetMobileAdminUserInfo()
  2234. dataBody := make(map[string]interface{}, 0)
  2235. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  2236. if err != nil {
  2237. utils.ErrorLog(err.Error())
  2238. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2239. return
  2240. }
  2241. utils.ErrorLog("%v", dataBody)
  2242. timeLayout := "2006-01-02 15:04"
  2243. loc, _ := time.LoadLocation("Local")
  2244. timeLayout2 := "2006-01-02"
  2245. loc2, _ := time.LoadLocation("Local")
  2246. if dataBody["advice_type"] == nil || reflect.TypeOf(dataBody["advice_type"]).String() != "float64" {
  2247. utils.ErrorLog("advice_type")
  2248. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2249. return
  2250. }
  2251. adviceType := int64(2)
  2252. if dataBody["advice_date"] == nil || reflect.TypeOf(dataBody["advice_date"]).String() != "string" {
  2253. utils.ErrorLog("advice_date")
  2254. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2255. return
  2256. }
  2257. adviceDate, _ := dataBody["advice_date"].(string)
  2258. theTime, err := time.ParseInLocation(timeLayout2, adviceDate, loc2)
  2259. AdviceDate := theTime.Unix()
  2260. RecordDate := theTime.Unix()
  2261. if dataBody["start_time"] == nil || reflect.TypeOf(dataBody["start_time"]).String() != "string" {
  2262. utils.ErrorLog("start_time")
  2263. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2264. return
  2265. }
  2266. startTime, _ := dataBody["start_time"].(string)
  2267. if len(startTime) == 0 {
  2268. utils.ErrorLog("len(start_time) == 0")
  2269. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2270. return
  2271. }
  2272. theTime, err = time.ParseInLocation(timeLayout, startTime, loc)
  2273. if err != nil {
  2274. utils.ErrorLog(err.Error())
  2275. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2276. return
  2277. }
  2278. StartTime := theTime.Unix()
  2279. Remark := ""
  2280. if dataBody["remark"] != nil && reflect.TypeOf(dataBody["remark"]).String() == "string" {
  2281. remark, _ := dataBody["remark"].(string)
  2282. Remark = remark
  2283. }
  2284. var advices []*models.GroupAdvice
  2285. if dataBody["advices"] == nil || reflect.TypeOf(dataBody["advices"]).String() != "[]interface {}" {
  2286. utils.ErrorLog("advices")
  2287. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2288. return
  2289. }
  2290. adviceNames := dataBody["advices"].([]interface{})
  2291. for _, adviceNameMap := range adviceNames {
  2292. adviceNameM := adviceNameMap.(map[string]interface{})
  2293. var advice models.GroupAdvice
  2294. advice.Remark = Remark
  2295. advice.AdviceType = adviceType
  2296. advice.StartTime = StartTime
  2297. advice.AdviceDate = AdviceDate
  2298. advice.RecordDate = RecordDate
  2299. advice.Status = 1
  2300. advice.CreatedTime = time.Now().Unix()
  2301. advice.UpdatedTime = time.Now().Unix()
  2302. advice.StopState = 2
  2303. advice.ExecutionState = 2
  2304. advice.UserOrgId = adminUserInfo.Org.Id
  2305. advice.PatientId = patient
  2306. advice.AdviceDoctor = adminUserInfo.AdminUser.Id
  2307. if adviceNameM["advice_name"] == nil || reflect.TypeOf(adviceNameM["advice_name"]).String() != "string" {
  2308. utils.ErrorLog("advice_name")
  2309. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2310. return
  2311. }
  2312. adviceName, _ := adviceNameM["advice_name"].(string)
  2313. if len(adviceName) == 0 {
  2314. utils.ErrorLog("len(advice_name) == 0")
  2315. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2316. return
  2317. }
  2318. advice.AdviceName = adviceName
  2319. if adviceNameM["drug_spec"] != nil && reflect.TypeOf(adviceNameM["drug_spec"]).String() == "string" {
  2320. drugSpec, _ := strconv.ParseFloat(adviceNameM["drug_spec"].(string), 64)
  2321. advice.DrugSpec = drugSpec
  2322. }
  2323. if adviceNameM["advice_desc"] != nil && reflect.TypeOf(adviceNameM["advice_desc"]).String() == "string" {
  2324. adviceDesc, _ := adviceNameM["advice_desc"].(string)
  2325. advice.AdviceDesc = adviceDesc
  2326. }
  2327. if adviceNameM["drug_spec_unit"] != nil && reflect.TypeOf(adviceNameM["drug_spec_unit"]).String() == "string" {
  2328. drugSpecUnit, _ := adviceNameM["drug_spec_unit"].(string)
  2329. advice.DrugSpecUnit = drugSpecUnit
  2330. }
  2331. //if adviceNameM["single_dose"] != nil && reflect.TypeOf(adviceNameM["single_dose"]).String() == "string" {
  2332. // singleDose, _ := strconv.ParseFloat(adviceNameM["single_dose"].(string), 64)
  2333. // advice.SingleDose = singleDose
  2334. //}
  2335. if adviceNameM["single_dose"] != nil || reflect.TypeOf(adviceNameM["single_dose"]).String() == "float64" {
  2336. //single_dose := int64(adviceNameM["single_dose"].(float64))
  2337. advice.SingleDose = adviceNameM["single_dose"].(float64)
  2338. }
  2339. if adviceNameM["single_dose_unit"] != nil && reflect.TypeOf(adviceNameM["single_dose_unit"]).String() == "string" {
  2340. singleDoseUnit, _ := adviceNameM["single_dose_unit"].(string)
  2341. advice.SingleDoseUnit = singleDoseUnit
  2342. }
  2343. //if adviceNameM["prescribing_number"] != nil && reflect.TypeOf(adviceNameM["prescribing_number"]).String() == "string" {
  2344. // prescribingNumber, _ := strconv.ParseFloat(adviceNameM["prescribing_number"].(string), 64)
  2345. // advice.PrescribingNumber = prescribingNumber
  2346. //}
  2347. if adviceNameM["prescribing_number"] != nil || reflect.TypeOf(adviceNameM["prescribing_number"]).String() == "float64" {
  2348. //single_dose := int64(adviceNameM["single_dose"].(float64))
  2349. advice.PrescribingNumber = adviceNameM["prescribing_number"].(float64)
  2350. }
  2351. if adviceNameM["prescribing_number_unit"] != nil && reflect.TypeOf(adviceNameM["prescribing_number_unit"]).String() == "string" {
  2352. prescribingNumberUnit, _ := adviceNameM["prescribing_number_unit"].(string)
  2353. advice.PrescribingNumberUnit = prescribingNumberUnit
  2354. }
  2355. if adviceNameM["delivery_way"] != nil && reflect.TypeOf(adviceNameM["delivery_way"]).String() == "string" {
  2356. deliveryWay, _ := adviceNameM["delivery_way"].(string)
  2357. advice.DeliveryWay = deliveryWay
  2358. }
  2359. if adviceNameM["execution_frequency"] != nil && reflect.TypeOf(adviceNameM["execution_frequency"]).String() == "string" {
  2360. executionFrequency, _ := adviceNameM["execution_frequency"].(string)
  2361. advice.ExecutionFrequency = executionFrequency
  2362. }
  2363. if adviceNameM["frequency_type"] != nil || reflect.TypeOf(adviceNameM["frequency_type"]).String() == "float64" {
  2364. frequency_type := int64(adviceNameM["frequency_type"].(float64))
  2365. advice.FrequencyType = frequency_type
  2366. }
  2367. if adviceNameM["day_count"] != nil || reflect.TypeOf(adviceNameM["day_count"]).String() == "float64" {
  2368. day_count := int64(adviceNameM["day_count"].(float64))
  2369. advice.DayCount = day_count
  2370. }
  2371. if adviceNameM["week_day"] != nil && reflect.TypeOf(adviceNameM["week_day"]).String() == "string" {
  2372. week_day, _ := adviceNameM["week_day"].(string)
  2373. advice.WeekDay = week_day
  2374. }
  2375. if adviceNameM["way"] != nil || reflect.TypeOf(adviceNameM["way"]).String() == "float64" {
  2376. way := int64(adviceNameM["way"].(float64))
  2377. advice.Way = way
  2378. }
  2379. if adviceNameM["drug_id"] != nil || reflect.TypeOf(adviceNameM["drug_id"]).String() == "float64" {
  2380. drug_id := int64(adviceNameM["drug_id"].(float64))
  2381. advice.DrugId = drug_id
  2382. }
  2383. if adviceNameM["drug_name_id"] != nil || reflect.TypeOf(adviceNameM["drug_name_id"]).String() == "float64" {
  2384. drug_name_id := int64(adviceNameM["drug_name_id"].(float64))
  2385. advice.DrugNameId = drug_name_id
  2386. }
  2387. if adviceNameM["template_id"] != nil && reflect.TypeOf(adviceNameM["template_id"]).String() == "string" {
  2388. template_id, _ := adviceNameM["template_id"].(string)
  2389. advice.TemplateId = template_id
  2390. }
  2391. if adviceNameM["child"] != nil && reflect.TypeOf(adviceNameM["child"]).String() == "string" {
  2392. executionFrequency, _ := adviceNameM["execution_frequency"].(string)
  2393. advice.ExecutionFrequency = executionFrequency
  2394. }
  2395. if adviceNameM["child"] != nil && reflect.TypeOf(adviceNameM["child"]).String() == "[]interface {}" {
  2396. children := adviceNameM["child"].([]interface{})
  2397. if len(children) > 0 {
  2398. for _, childrenMap := range children {
  2399. childMap := childrenMap.(map[string]interface{})
  2400. var child models.GroupAdvice
  2401. child.Remark = Remark
  2402. child.AdviceType = adviceType
  2403. child.StartTime = StartTime
  2404. child.AdviceDate = AdviceDate
  2405. child.RecordDate = RecordDate
  2406. child.Status = 1
  2407. child.CreatedTime = time.Now().Unix()
  2408. child.UpdatedTime = time.Now().Unix()
  2409. child.StopState = 2
  2410. child.ExecutionState = 2
  2411. child.UserOrgId = adminUserInfo.Org.Id
  2412. child.PatientId = patient
  2413. child.AdviceDoctor = adminUserInfo.AdminUser.Id
  2414. if childMap["advice_name"] == nil || reflect.TypeOf(childMap["advice_name"]).String() != "string" {
  2415. utils.ErrorLog("child advice_name")
  2416. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2417. return
  2418. }
  2419. childAdviceName, _ := childMap["advice_name"].(string)
  2420. if len(childAdviceName) == 0 {
  2421. utils.ErrorLog("len(child advice_name) == 0")
  2422. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2423. return
  2424. }
  2425. child.AdviceName = childAdviceName
  2426. if childMap["advice_desc"] != nil && reflect.TypeOf(childMap["advice_desc"]).String() == "string" {
  2427. childAdviceDesc, _ := childMap["advice_desc"].(string)
  2428. child.AdviceDesc = childAdviceDesc
  2429. }
  2430. if childMap["drug_spec"] != nil && reflect.TypeOf(childMap["drug_spec"]).String() == "string" {
  2431. childDrugSpec, _ := strconv.ParseFloat(childMap["drug_spec"].(string), 64)
  2432. child.DrugSpec = childDrugSpec
  2433. }
  2434. if childMap["drug_spec_unit"] != nil && reflect.TypeOf(childMap["drug_spec_unit"]).String() == "string" {
  2435. childDrugSpecUnit, _ := childMap["drug_spec_unit"].(string)
  2436. child.DrugSpecUnit = childDrugSpecUnit
  2437. }
  2438. if childMap["single_dose"] != nil && reflect.TypeOf(childMap["single_dose"]).String() == "float64" {
  2439. child.SingleDose = childMap["single_dose"].(float64)
  2440. }
  2441. if childMap["single_dose_unit"] != nil && reflect.TypeOf(childMap["single_dose_unit"]).String() == "string" {
  2442. childSingleDoseUnit, _ := childMap["single_dose_unit"].(string)
  2443. child.SingleDoseUnit = childSingleDoseUnit
  2444. }
  2445. if childMap["prescribing_number"] != nil && reflect.TypeOf(childMap["prescribing_number"]).String() == "float64" {
  2446. child.PrescribingNumber = childMap["prescribing_number"].(float64)
  2447. }
  2448. if childMap["prescribing_number_unit"] != nil && reflect.TypeOf(childMap["prescribing_number_unit"]).String() == "string" {
  2449. childPrescribingNumberUnit, _ := childMap["prescribing_number_unit"].(string)
  2450. child.PrescribingNumberUnit = childPrescribingNumberUnit
  2451. }
  2452. child.DeliveryWay = advice.DeliveryWay
  2453. child.ExecutionFrequency = advice.ExecutionFrequency
  2454. advice.Children = append(advice.Children, &child)
  2455. }
  2456. }
  2457. }
  2458. advices = append(advices, &advice)
  2459. }
  2460. list, err := service.CreateMGroupAdvice(adminUserInfo.Org.Id, advices, groupNo)
  2461. if err != nil {
  2462. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateDoctorAdviceFail)
  2463. return
  2464. }
  2465. c.ServeSuccessJSON(map[string]interface{}{
  2466. "msg": "ok",
  2467. "advices": list,
  2468. })
  2469. return
  2470. }
  2471. func (c *DialysisAPIController) UploadDryWeight() {
  2472. patient_id, _ := c.GetInt64("id")
  2473. dry_weight, _ := c.GetFloat("dry_weight")
  2474. doctor_id, _ := c.GetInt64("doctor_id")
  2475. remark := c.GetString("remark")
  2476. adminUserInfo := c.GetMobileAdminUserInfo()
  2477. weightAdjust, err := service.FindLastDryWeightAdjust(adminUserInfo.Org.Id, patient_id)
  2478. if err == gorm.ErrRecordNotFound {
  2479. dryWeight := &models.SgjPatientDryweight{
  2480. PatientId: patient_id,
  2481. DryWeight: dry_weight,
  2482. Remakes: remark,
  2483. Ctime: time.Now().Unix(),
  2484. Mtime: time.Now().Unix(),
  2485. Creator: doctor_id,
  2486. Status: 1,
  2487. UserOrgId: adminUserInfo.Org.Id,
  2488. AdjustedValue: "/",
  2489. UserId: adminUserInfo.AdminUser.Id,
  2490. }
  2491. createErr := service.CreatePatientWeightAdjust(dryWeight)
  2492. if createErr == nil {
  2493. c.ServeSuccessJSON(map[string]interface{}{
  2494. "msg": "提交成功",
  2495. "weight": dryWeight,
  2496. })
  2497. }
  2498. } else {
  2499. dryWeight := &models.SgjPatientDryweight{
  2500. PatientId: patient_id,
  2501. DryWeight: dry_weight,
  2502. Remakes: remark,
  2503. Ctime: time.Now().Unix(),
  2504. Mtime: time.Now().Unix(),
  2505. Creator: doctor_id,
  2506. Status: 1,
  2507. UserOrgId: adminUserInfo.Org.Id,
  2508. AdjustedValue: "/",
  2509. UserId: adminUserInfo.AdminUser.Id,
  2510. }
  2511. var value float64
  2512. value = dry_weight - weightAdjust.DryWeight
  2513. if value < 0 {
  2514. dryWeight.AdjustedValue = strconv.FormatFloat(math.Abs(value), 'f', 1, 64) + "(下调)"
  2515. } else if value == 0 {
  2516. dryWeight.AdjustedValue = "/"
  2517. } else if value > 0 {
  2518. dryWeight.AdjustedValue = strconv.FormatFloat(value, 'f', 1, 64) + "(上调)"
  2519. }
  2520. createErr := service.CreatePatientWeightAdjust(dryWeight)
  2521. if createErr == nil {
  2522. c.ServeSuccessJSON(map[string]interface{}{
  2523. "msg": "提交成功",
  2524. "weight": dryWeight,
  2525. })
  2526. }
  2527. }
  2528. }
  2529. func (c *DialysisAPIController) GetSolution() {
  2530. patient_id, _ := c.GetInt64("patient_id")
  2531. mode_id, _ := c.GetInt64("mode_id")
  2532. adminUserInfo := c.GetMobileAdminUserInfo()
  2533. solution, err := service.MobileGetDialysisSolutionByModeId(adminUserInfo.Org.Id, patient_id, mode_id)
  2534. prescription, err := service.MobileGetLastDialysisPrescribeByModeId(adminUserInfo.Org.Id, patient_id, mode_id)
  2535. system_prescription, err := service.MobileGetSystemDialysisPrescribeByModeId(adminUserInfo.Org.Id, mode_id)
  2536. if err != nil {
  2537. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  2538. return
  2539. }
  2540. c.ServeSuccessJSON(map[string]interface{}{
  2541. "solution": solution,
  2542. "prescription": prescription,
  2543. "system_prescription": system_prescription,
  2544. })
  2545. }
  2546. func (c *DialysisAPIController) GetSchedule() {
  2547. schedual_type, _ := c.GetInt64("schedual_type")
  2548. adminUserInfo := c.GetMobileAdminUserInfo()
  2549. timeLayout := "2006-01-02 15:04:05"
  2550. date := time.Now().Format("2006-01-02") + " 00:00:00"
  2551. loc, _ := time.LoadLocation("Local")
  2552. theStartTime, _ := time.ParseInLocation(timeLayout, date, loc)
  2553. scheduleTime := theStartTime.Unix()
  2554. deviceNumber, _ := service.GetAllDeviceNumbers(adminUserInfo.Org.Id, scheduleTime, schedual_type)
  2555. c.ServeSuccessJSON(map[string]interface{}{
  2556. "number": deviceNumber,
  2557. })
  2558. }
  2559. func (c *DialysisAPIController) GetPatientId() {
  2560. id, _ := c.GetInt64("id")
  2561. patientId, _ := service.GetPatientId(id)
  2562. c.ServeSuccessJSON(map[string]interface{}{
  2563. "patient": patientId,
  2564. })
  2565. }
  2566. func (this *DialysisAPIController) GetDialysisSchedule() {
  2567. schedualDate := this.GetString("date")
  2568. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  2569. if parseDateErr != nil {
  2570. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2571. return
  2572. }
  2573. adminInfo := this.GetMobileAdminUserInfo()
  2574. orgID := adminInfo.Org.Id
  2575. redis := service.RedisClient()
  2576. defer redis.Close()
  2577. key := "scheduals_" + schedualDate + "_" + strconv.FormatInt(orgID, 10)
  2578. scheduals, _ := service.MobileGetDialysisScheduals(orgID, date.Unix(), 0)
  2579. if len(scheduals) > 0 {
  2580. //缓存数据
  2581. scheduals_json, err := json.Marshal(scheduals)
  2582. if err == nil {
  2583. redis.Set(key, scheduals_json, time.Second*30)
  2584. }
  2585. }
  2586. this.ServeSuccessJSON(map[string]interface{}{
  2587. "scheduals": scheduals,
  2588. })
  2589. }
  2590. func (this *DialysisAPIController) GetLastOrNextDoctorAdvice() {
  2591. change_type, _ := this.GetInt64("type", 0)
  2592. record_date := this.GetString("record_time")
  2593. patient_id, _ := this.GetInt64("patient_id", 0)
  2594. timeLayout := "2006-01-02"
  2595. loc, _ := time.LoadLocation("Local")
  2596. theAdviceRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  2597. record_time := theAdviceRecordTime.Unix()
  2598. adminUserInfo := this.GetMobileAdminUserInfo()
  2599. advices, sch, err := service.GetDoctorAdviceByType(change_type, record_time, adminUserInfo.Org.Id, patient_id)
  2600. if err == nil {
  2601. if len(advices) == 0 {
  2602. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDoctorAdviceEmpty)
  2603. return
  2604. } else {
  2605. this.ServeSuccessJSON(map[string]interface{}{
  2606. "advices": advices,
  2607. "schedule": sch,
  2608. })
  2609. return
  2610. }
  2611. } else {
  2612. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  2613. return
  2614. }
  2615. }
  2616. func (c *DialysisAPIController) CreateConsumables() {
  2617. record_date := c.GetString("record_time")
  2618. patient_id, _ := c.GetInt64("patient_id", 0)
  2619. adminUser := c.GetMobileAdminUserInfo()
  2620. timeLayout := "2006-01-02"
  2621. loc, _ := time.LoadLocation("Local")
  2622. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  2623. record_time := theRecordTime.Unix()
  2624. dataBody := make(map[string]interface{}, 0)
  2625. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  2626. if err != nil {
  2627. utils.ErrorLog(err.Error())
  2628. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2629. return
  2630. }
  2631. var beforePrepares []*models.DialysisBeforePrepare
  2632. var updateBeforePrepares []*models.DialysisBeforePrepare
  2633. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  2634. goods, _ := dataBody["goods"].([]interface{})
  2635. if len(goods) > 0 {
  2636. for _, item := range goods {
  2637. items := item.(map[string]interface{})
  2638. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  2639. utils.ErrorLog("good_id")
  2640. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2641. return
  2642. }
  2643. good_id := int64(items["good_id"].(float64))
  2644. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  2645. utils.ErrorLog("good_type_id")
  2646. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2647. return
  2648. }
  2649. good_type_id := int64(items["good_type_id"].(float64))
  2650. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  2651. utils.ErrorLog("count")
  2652. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2653. return
  2654. }
  2655. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  2656. //commdity_code := items["commdity_code"].(string)
  2657. //fmt.Println("新建22222222222222",commdity_code)
  2658. adminUser := c.GetMobileAdminUserInfo()
  2659. prepare := &models.DialysisBeforePrepare{
  2660. UserOrgId: adminUser.Org.Id,
  2661. PatientId: patient_id,
  2662. RecordDate: record_time,
  2663. GoodId: good_id,
  2664. GoodTypeId: good_type_id,
  2665. Count: count,
  2666. Ctime: time.Now().Unix(),
  2667. Mtime: time.Now().Unix(),
  2668. Creater: adminUser.AdminUser.Id,
  2669. Modifier: 0,
  2670. //CommdityCode:commdity_code,
  2671. }
  2672. record_count := service.FindDialysisBeforePrepare(prepare.PatientId, prepare.GoodId, prepare.GoodTypeId, adminUser.Org.Id, record_time)
  2673. if record_count == 0 {
  2674. beforePrepares = append(beforePrepares, prepare)
  2675. }
  2676. }
  2677. }
  2678. }
  2679. if len(beforePrepares) > 0 {
  2680. service.CreateDialysisBeforePrepare(beforePrepares)
  2681. }
  2682. var errs error
  2683. if dataBody["update_goods"] != nil && reflect.TypeOf(dataBody["update_goods"]).String() == "[]interface {}" {
  2684. goods, _ := dataBody["update_goods"].([]interface{})
  2685. if len(goods) > 0 {
  2686. for _, item := range goods {
  2687. items := item.(map[string]interface{})
  2688. if items["record_time"] == nil || reflect.TypeOf(items["record_time"]).String() != "float64" {
  2689. utils.ErrorLog("record_time")
  2690. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2691. return
  2692. }
  2693. record_time := int64(items["record_time"].(float64))
  2694. if items["id"] == nil || reflect.TypeOf(items["id"]).String() != "float64" {
  2695. utils.ErrorLog("id")
  2696. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2697. return
  2698. }
  2699. id := int64(items["id"].(float64))
  2700. if items["patient_id"] == nil || reflect.TypeOf(items["patient_id"]).String() != "float64" {
  2701. utils.ErrorLog("patient_id")
  2702. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2703. return
  2704. }
  2705. patient_id := int64(items["patient_id"].(float64))
  2706. if items["creater"] == nil || reflect.TypeOf(items["creater"]).String() != "float64" {
  2707. utils.ErrorLog("creater")
  2708. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2709. return
  2710. }
  2711. creater := int64(items["creater"].(float64))
  2712. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  2713. utils.ErrorLog("good_id")
  2714. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2715. return
  2716. }
  2717. good_id := int64(items["good_id"].(float64))
  2718. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  2719. utils.ErrorLog("good_type_id")
  2720. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2721. return
  2722. }
  2723. good_type_id := int64(items["good_type_id"].(float64))
  2724. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  2725. utils.ErrorLog("count")
  2726. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2727. return
  2728. }
  2729. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  2730. if items["ctime"] == nil || reflect.TypeOf(items["ctime"]).String() != "float64" {
  2731. utils.ErrorLog("ctime")
  2732. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2733. return
  2734. }
  2735. ctime := int64(items["ctime"].(float64))
  2736. //commdity_code := items["commdity_code"].(string)
  2737. //fmt.Println("commdityecode22222222222222222222",commdity_code)
  2738. prepare := &models.DialysisBeforePrepare{
  2739. ID: id,
  2740. UserOrgId: adminUser.Org.Id,
  2741. PatientId: patient_id,
  2742. RecordDate: record_time,
  2743. GoodId: good_id,
  2744. GoodTypeId: good_type_id,
  2745. Count: count,
  2746. Ctime: ctime,
  2747. Mtime: time.Now().Unix(),
  2748. Creater: creater,
  2749. Modifier: adminUser.AdminUser.Id,
  2750. Status: 1,
  2751. //CommdityCode: commdity_code,
  2752. }
  2753. updateBeforePrepares = append(updateBeforePrepares, prepare)
  2754. }
  2755. }
  2756. //去重
  2757. updateBeforePrepares = RemoveRepeatedGood(updateBeforePrepares)
  2758. if len(updateBeforePrepares) > 0 {
  2759. for _, item := range updateBeforePrepares {
  2760. errs = service.UpdateDialysisBeforePrepareTwo(item)
  2761. }
  2762. }
  2763. }
  2764. if errs == nil {
  2765. c.ServeSuccessJSON(map[string]interface{}{
  2766. "msg": "提交成功",
  2767. })
  2768. return
  2769. } else {
  2770. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  2771. return
  2772. }
  2773. }
  2774. func (c *DialysisAPIController) CreateStockOutInfo() {
  2775. patient_id, _ := c.GetInt64("patient_id", 0)
  2776. record_date := c.GetString("record_time")
  2777. if patient_id <= 0 {
  2778. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2779. return
  2780. }
  2781. adminInfo := c.GetMobileAdminUserInfo()
  2782. timeLayout := "2006-01-02"
  2783. loc, _ := time.LoadLocation("Local")
  2784. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  2785. record_time := theRecordTime.Unix()
  2786. consumables, _ := service.FindConsumablesByDate(adminInfo.Org.Id, patient_id, record_time)
  2787. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  2788. consumables = RemoveRepeatedGood(consumables)
  2789. if record.IsOpen == 1 {
  2790. out, err := service.FindStockOutByIsSys(adminInfo.Org.Id, 1, record_time)
  2791. if err == gorm.ErrRecordNotFound {
  2792. //没有记录,则创建出库单
  2793. timeStr := time.Now().Format("2006-01-02")
  2794. timeArr := strings.Split(timeStr, "-")
  2795. total, _ := service.FindAllWarehouseOut(adminInfo.Org.Id)
  2796. total = total + 1
  2797. warehousing_out_order := strconv.FormatInt(adminInfo.Org.Id, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  2798. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  2799. number = number + total
  2800. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  2801. creater := adminInfo.AdminUser.Id
  2802. warehouseOut := models.WarehouseOut{
  2803. WarehouseOutOrderNumber: warehousing_out_order,
  2804. OperationTime: time.Now().Unix(),
  2805. OrgId: adminInfo.Org.Id,
  2806. Creater: creater,
  2807. Ctime: time.Now().Unix(),
  2808. Status: 1,
  2809. WarehouseOutTime: record_time,
  2810. Dealer: 0,
  2811. Manufacturer: 0,
  2812. Type: 1,
  2813. IsSys: 1,
  2814. }
  2815. err := service.AddSigleWarehouseOut(&warehouseOut)
  2816. if err != nil {
  2817. utils.TraceLog("创建出库单失败 err = %v", err)
  2818. } else {
  2819. for _, item := range consumables {
  2820. if item.Count > 0 {
  2821. warehouseOutInfo := &models.WarehouseOutInfo{
  2822. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  2823. WarehouseOutId: warehouseOut.ID,
  2824. Status: 1,
  2825. Ctime: time.Now().Unix(),
  2826. Remark: "",
  2827. OrgId: adminInfo.Org.Id,
  2828. Type: 1,
  2829. Manufacturer: 0,
  2830. Dealer: 0,
  2831. IsSys: 1,
  2832. SysRecordTime: record_time,
  2833. GoodTypeId: item.GoodTypeId,
  2834. GoodId: item.GoodId,
  2835. }
  2836. warehouseOutInfo.Count = item.Count
  2837. stockInInfo, _ := service.FindLastStockInInfoRecord(item.GoodId, adminInfo.Org.Id)
  2838. warehouseOutInfo.Price = stockInInfo.Price
  2839. err := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  2840. if err == nil {
  2841. details := &models.AutomaticReduceDetail{
  2842. WarehouseOutId: warehouseOutInfo.ID,
  2843. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  2844. PatientId: patient_id,
  2845. Ctime: time.Now().Unix(),
  2846. Mtime: time.Now().Unix(),
  2847. Status: 1,
  2848. RecordTime: record_time,
  2849. OrgId: adminInfo.Org.Id,
  2850. GoodId: item.GoodId,
  2851. GoodTypeId: item.GoodTypeId,
  2852. Count: item.Count,
  2853. }
  2854. service.AddSigleAutoReduceRecordInfo(details)
  2855. }
  2856. }
  2857. }
  2858. }
  2859. } else if err == nil {
  2860. for _, item := range consumables {
  2861. outInfo, err := service.FindStockOutInfoByTypeId(adminInfo.Org.Id, item.GoodTypeId, item.GoodId, out.ID, out.WarehouseOutOrderNumber)
  2862. if err == gorm.ErrRecordNotFound {
  2863. warehouseOutInfo := &models.WarehouseOutInfo{
  2864. WarehouseOutOrderNumber: out.WarehouseOutOrderNumber,
  2865. WarehouseOutId: out.ID,
  2866. Status: 1,
  2867. Ctime: time.Now().Unix(),
  2868. Remark: "",
  2869. OrgId: adminInfo.Org.Id,
  2870. Type: 1,
  2871. Manufacturer: 0,
  2872. Dealer: 0,
  2873. IsSys: 1,
  2874. SysRecordTime: record_time,
  2875. }
  2876. stockInInfo, _ := service.FindLastStockInInfoRecord(item.GoodId, adminInfo.Org.Id)
  2877. warehouseOutInfo.Price = stockInInfo.Price
  2878. warehouseOutInfo.GoodId = item.GoodId
  2879. warehouseOutInfo.GoodTypeId = item.GoodTypeId
  2880. warehouseOutInfo.Count = item.Count
  2881. err := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  2882. if err == nil {
  2883. details := &models.AutomaticReduceDetail{
  2884. WarehouseOutId: warehouseOutInfo.ID,
  2885. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  2886. PatientId: patient_id,
  2887. Ctime: time.Now().Unix(),
  2888. Mtime: time.Now().Unix(),
  2889. Status: 1,
  2890. RecordTime: record_time,
  2891. OrgId: adminInfo.Org.Id,
  2892. GoodId: item.GoodId,
  2893. GoodTypeId: item.GoodTypeId,
  2894. Count: item.Count,
  2895. }
  2896. service.AddSigleAutoReduceRecordInfo(details)
  2897. }
  2898. } else if err == nil { //记录存在,则将增加数量
  2899. if outInfo.ID > 0 {
  2900. service.UpdateStockOutInfoCount2(adminInfo.Org.Id, outInfo.ID, item.Count)
  2901. }
  2902. count, _ := service.FindPatientAutomaticReduceRecord(adminInfo.Org.Id, record_time, item.GoodId, item.GoodTypeId, patient_id)
  2903. if count == 0 {
  2904. details := &models.AutomaticReduceDetail{
  2905. WarehouseOutId: outInfo.ID,
  2906. WarehouseOutOrderNumber: outInfo.WarehouseOutOrderNumber,
  2907. PatientId: patient_id,
  2908. Ctime: time.Now().Unix(),
  2909. Mtime: time.Now().Unix(),
  2910. Status: 1,
  2911. RecordTime: record_time,
  2912. OrgId: adminInfo.Org.Id,
  2913. GoodId: item.GoodId,
  2914. GoodTypeId: item.GoodTypeId,
  2915. Count: item.Count,
  2916. }
  2917. service.AddSigleAutoReduceRecordInfo(details)
  2918. } else if count == 1 {
  2919. service.UpdateUserInfoDetails(item.GoodTypeId, item.GoodId, record_time, adminInfo.Org.Id, patient_id, item.Count, &outInfo)
  2920. }
  2921. }
  2922. }
  2923. }
  2924. c.ServeSuccessJSON(map[string]interface{}{
  2925. "msg": "提交成功",
  2926. })
  2927. return
  2928. } else {
  2929. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeOpenStocktWrong)
  2930. return
  2931. }
  2932. }
  2933. func (c *DialysisAPIController) EditConsumables() {
  2934. patient_id, _ := c.GetInt64("patient_id", 0)
  2935. record_date := c.GetString("record_time")
  2936. if patient_id <= 0 {
  2937. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2938. return
  2939. }
  2940. adminInfo := c.GetMobileAdminUserInfo()
  2941. timeLayout := "2006-01-02"
  2942. loc, _ := time.LoadLocation("Local")
  2943. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  2944. record_time := theRecordTime.Unix()
  2945. dataBody := make(map[string]interface{}, 0)
  2946. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  2947. if err != nil {
  2948. utils.ErrorLog(err.Error())
  2949. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2950. return
  2951. }
  2952. var beforePrepares []*models.DialysisBeforePrepare
  2953. var newBeforePrepares []*models.DialysisBeforePrepare
  2954. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  2955. if record.IsOpen == 1 {
  2956. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  2957. goods, _ := dataBody["goods"].([]interface{})
  2958. if len(goods) > 0 {
  2959. for _, item := range goods {
  2960. items := item.(map[string]interface{})
  2961. if items["record_time"] == nil || reflect.TypeOf(items["record_time"]).String() != "float64" {
  2962. utils.ErrorLog("record_time")
  2963. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2964. return
  2965. }
  2966. record_time := int64(items["record_time"].(float64))
  2967. if items["id"] == nil || reflect.TypeOf(items["id"]).String() != "float64" {
  2968. utils.ErrorLog("id")
  2969. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2970. return
  2971. }
  2972. id := int64(items["id"].(float64))
  2973. if items["patient_id"] == nil || reflect.TypeOf(items["patient_id"]).String() != "float64" {
  2974. utils.ErrorLog("patient_id")
  2975. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2976. return
  2977. }
  2978. patient_id := int64(items["patient_id"].(float64))
  2979. if items["creater"] == nil || reflect.TypeOf(items["creater"]).String() != "float64" {
  2980. utils.ErrorLog("creater")
  2981. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2982. return
  2983. }
  2984. creater := int64(items["creater"].(float64))
  2985. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  2986. utils.ErrorLog("good_id")
  2987. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2988. return
  2989. }
  2990. good_id := int64(items["good_id"].(float64))
  2991. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  2992. utils.ErrorLog("good_type_id")
  2993. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2994. return
  2995. }
  2996. good_type_id := int64(items["good_type_id"].(float64))
  2997. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  2998. utils.ErrorLog("count")
  2999. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3000. return
  3001. }
  3002. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3003. if items["ctime"] == nil || reflect.TypeOf(items["ctime"]).String() != "float64" {
  3004. utils.ErrorLog("ctime")
  3005. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3006. return
  3007. }
  3008. ctime := int64(items["ctime"].(float64))
  3009. //commdity_code := items["commdity_code"].(string)
  3010. //fmt.Println("commdityecode22222222222222222222",commdity_code)
  3011. adminUser := c.GetMobileAdminUserInfo()
  3012. prepare := &models.DialysisBeforePrepare{
  3013. ID: id,
  3014. UserOrgId: adminUser.Org.Id,
  3015. PatientId: patient_id,
  3016. RecordDate: record_time,
  3017. GoodId: good_id,
  3018. GoodTypeId: good_type_id,
  3019. Count: count,
  3020. Ctime: ctime,
  3021. Mtime: time.Now().Unix(),
  3022. Creater: creater,
  3023. Modifier: adminUser.AdminUser.Id,
  3024. Status: 1,
  3025. //CommdityCode: commdity_code,
  3026. }
  3027. beforePrepares = append(beforePrepares, prepare)
  3028. }
  3029. }
  3030. }
  3031. consumables_source, _ := service.FindConsumablesByDate(adminInfo.Org.Id, patient_id, record_time)
  3032. if dataBody["new_goods"] != nil && reflect.TypeOf(dataBody["new_goods"]).String() == "[]interface {}" {
  3033. goods, _ := dataBody["new_goods"].([]interface{})
  3034. if len(goods) > 0 {
  3035. for _, item := range goods {
  3036. items := item.(map[string]interface{})
  3037. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  3038. utils.ErrorLog("good_id")
  3039. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3040. return
  3041. }
  3042. good_id := int64(items["good_id"].(float64))
  3043. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  3044. utils.ErrorLog("good_type_id")
  3045. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3046. return
  3047. }
  3048. good_type_id := int64(items["good_type_id"].(float64))
  3049. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  3050. utils.ErrorLog("count")
  3051. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3052. return
  3053. }
  3054. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3055. //commdity_code := items["commdity_code"].(string)
  3056. //fmt.Println("commdityecode22222222222222222222",commdity_code)
  3057. adminUser := c.GetMobileAdminUserInfo()
  3058. prepare := &models.DialysisBeforePrepare{
  3059. UserOrgId: adminUser.Org.Id,
  3060. PatientId: patient_id,
  3061. RecordDate: record_time,
  3062. GoodId: good_id,
  3063. GoodTypeId: good_type_id,
  3064. Count: count,
  3065. Ctime: time.Now().Unix(),
  3066. Mtime: time.Now().Unix(),
  3067. Creater: adminUser.AdminUser.Id,
  3068. Modifier: 0,
  3069. //CommdityCode:commdity_code,
  3070. }
  3071. newBeforePrepares = append(newBeforePrepares, prepare)
  3072. }
  3073. newBeforePrepares = RemoveRepeatedGood(newBeforePrepares)
  3074. }
  3075. service.CreateDialysisBeforePrepare(newBeforePrepares)
  3076. }
  3077. out, err := service.FindStockOutByIsSys(adminInfo.Org.Id, 1, record_time)
  3078. if err == gorm.ErrRecordNotFound {
  3079. //没有记录,则创建出库单
  3080. timeStr := time.Now().Format("2006-01-02")
  3081. timeArr := strings.Split(timeStr, "-")
  3082. total, _ := service.FindAllWarehouseOut(adminInfo.Org.Id)
  3083. total = total + 1
  3084. warehousing_out_order := strconv.FormatInt(adminInfo.Org.Id, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  3085. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  3086. number = number + total
  3087. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  3088. creater := adminInfo.AdminUser.Id
  3089. warehouseOut := models.WarehouseOut{
  3090. WarehouseOutOrderNumber: warehousing_out_order,
  3091. OperationTime: time.Now().Unix(),
  3092. OrgId: adminInfo.Org.Id,
  3093. Creater: creater,
  3094. Ctime: time.Now().Unix(),
  3095. Status: 1,
  3096. WarehouseOutTime: record_time,
  3097. Dealer: 0,
  3098. Manufacturer: 0,
  3099. Type: 1,
  3100. IsSys: 1,
  3101. }
  3102. err := service.AddSigleWarehouseOut(&warehouseOut)
  3103. if err != nil {
  3104. utils.TraceLog("创建出库单失败 err = %v", err)
  3105. } else {
  3106. for _, item := range beforePrepares {
  3107. if item.Count > 0 {
  3108. warehouseOutInfo := &models.WarehouseOutInfo{
  3109. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  3110. WarehouseOutId: warehouseOut.ID,
  3111. Count: 1,
  3112. Status: 1,
  3113. Ctime: time.Now().Unix(),
  3114. Remark: "",
  3115. OrgId: adminInfo.Org.Id,
  3116. Type: 1,
  3117. Manufacturer: 0,
  3118. Dealer: 0,
  3119. IsSys: 1,
  3120. SysRecordTime: record_time,
  3121. GoodTypeId: item.GoodTypeId,
  3122. GoodId: item.GoodId,
  3123. }
  3124. stockInInfo, _ := service.FindLastStockInInfoRecord(item.GoodId, adminInfo.Org.Id)
  3125. warehouseOutInfo.Price = stockInInfo.Price
  3126. err := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  3127. if err == nil {
  3128. details := &models.AutomaticReduceDetail{
  3129. WarehouseOutId: warehouseOutInfo.ID,
  3130. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  3131. PatientId: patient_id,
  3132. Ctime: time.Now().Unix(),
  3133. Mtime: time.Now().Unix(),
  3134. Status: 1,
  3135. RecordTime: record_time,
  3136. OrgId: adminInfo.Org.Id,
  3137. GoodId: item.GoodId,
  3138. GoodTypeId: item.GoodTypeId,
  3139. }
  3140. service.AddSigleAutoReduceRecordInfo(details)
  3141. }
  3142. }
  3143. }
  3144. }
  3145. } else if err == nil {
  3146. if len(newBeforePrepares) > 0 { //新增
  3147. for _, item := range newBeforePrepares {
  3148. outInfo, err := service.FindStockOutInfoByTypeId(adminInfo.Org.Id, item.GoodTypeId, item.GoodId, out.ID, out.WarehouseOutOrderNumber)
  3149. if err == gorm.ErrRecordNotFound {
  3150. warehouseOutInfo := &models.WarehouseOutInfo{
  3151. WarehouseOutOrderNumber: out.WarehouseOutOrderNumber,
  3152. WarehouseOutId: out.ID,
  3153. Status: 1,
  3154. Ctime: time.Now().Unix(),
  3155. Remark: "",
  3156. OrgId: adminInfo.Org.Id,
  3157. Type: 1,
  3158. Manufacturer: 0,
  3159. Dealer: 0,
  3160. IsSys: 1,
  3161. SysRecordTime: record_time,
  3162. }
  3163. stockInInfo, _ := service.FindLastStockInInfoRecord(item.GoodId, adminInfo.Org.Id)
  3164. warehouseOutInfo.Price = stockInInfo.Price
  3165. warehouseOutInfo.GoodId = item.GoodId
  3166. warehouseOutInfo.GoodTypeId = item.GoodTypeId
  3167. warehouseOutInfo.Count = item.Count
  3168. err := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  3169. if err == nil {
  3170. count, _ := service.FindPatientAutomaticReduceRecord(adminInfo.Org.Id, record_time, item.GoodId, item.GoodTypeId, patient_id)
  3171. if count == 0 {
  3172. details := &models.AutomaticReduceDetail{
  3173. WarehouseOutId: warehouseOutInfo.ID,
  3174. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  3175. PatientId: patient_id,
  3176. Ctime: time.Now().Unix(),
  3177. Mtime: time.Now().Unix(),
  3178. Status: 1,
  3179. RecordTime: record_time,
  3180. OrgId: adminInfo.Org.Id,
  3181. GoodId: item.GoodId,
  3182. GoodTypeId: item.GoodTypeId,
  3183. Count: item.Count,
  3184. }
  3185. service.AddSigleAutoReduceRecordInfo(details)
  3186. } else if count == 1 {
  3187. service.UpdateUserInfoDetails(item.GoodTypeId, item.GoodId, record_time, adminInfo.Org.Id, patient_id, item.Count, &outInfo)
  3188. }
  3189. }
  3190. } else if err == nil { //记录存在,则将加数量
  3191. if outInfo.ID > 0 {
  3192. service.UpdateStockOutInfoCount2(adminInfo.Org.Id, outInfo.ID, item.Count)
  3193. }
  3194. count, _ := service.FindPatientAutomaticReduceRecord(adminInfo.Org.Id, record_time, item.GoodId, item.GoodTypeId, patient_id)
  3195. if count == 0 {
  3196. details := &models.AutomaticReduceDetail{
  3197. WarehouseOutId: outInfo.ID,
  3198. WarehouseOutOrderNumber: outInfo.WarehouseOutOrderNumber,
  3199. PatientId: patient_id,
  3200. Ctime: time.Now().Unix(),
  3201. Mtime: time.Now().Unix(),
  3202. Status: 1,
  3203. RecordTime: record_time,
  3204. OrgId: adminInfo.Org.Id,
  3205. GoodId: item.GoodId,
  3206. GoodTypeId: item.GoodTypeId,
  3207. Count: item.Count,
  3208. }
  3209. service.AddSigleAutoReduceRecordInfo(details)
  3210. } else if count == 1 {
  3211. service.UpdateUserInfoDetails(item.GoodTypeId, item.GoodId, record_time, adminInfo.Org.Id, patient_id, item.Count, &outInfo)
  3212. }
  3213. //details := &models.AutomaticReduceDetail{
  3214. // WarehouseOutId: outInfo.ID,
  3215. // WarehouseOutOrderNumber: outInfo.WarehouseOutOrderNumber,
  3216. // PatientId: patient_id,
  3217. // Ctime: time.Now().Unix(),
  3218. // Mtime: time.Now().Unix(),
  3219. // Status: 1,
  3220. // RecordTime: record_time,
  3221. // OrgId: adminInfo.Org.Id,
  3222. // GoodId: item.GoodId,
  3223. // GoodTypeId: item.GoodTypeId,
  3224. // Count: item.Count,
  3225. //}
  3226. //service.AddSigleAutoReduceRecordInfo(details)
  3227. }
  3228. }
  3229. }
  3230. if len(beforePrepares) > 0 { //修改
  3231. for _, consumable := range consumables_source {
  3232. for _, before := range beforePrepares {
  3233. if consumable.GoodId == before.GoodId {
  3234. if consumable.Count != before.Count {
  3235. _, out := service.FindStockOutOrderNumberByTime(record_time, adminInfo.Org.Id)
  3236. //_, out := service.FindOldOrderInfoByGoodId(record_time, adminInfo.Org.Id)
  3237. //判断前端更改后的商品id的出库记录在数据库中是否存在
  3238. err, newOut := service.FindOrderInfoByGoodId(consumable.GoodTypeId, consumable.GoodId, out.WarehouseOutOrderNumber, adminInfo.Org.Id)
  3239. if err == gorm.ErrRecordNotFound { //不存在,则新增出库记录,并更改使用人商品信息
  3240. warehouseOutInfo := &models.WarehouseOutInfo{
  3241. WarehouseOutOrderNumber: out.WarehouseOutOrderNumber,
  3242. WarehouseOutId: out.ID,
  3243. Count: before.Count,
  3244. Status: 1,
  3245. Ctime: time.Now().Unix(),
  3246. Remark: "",
  3247. OrgId: adminInfo.Org.Id,
  3248. Type: 1,
  3249. Manufacturer: 0,
  3250. Dealer: 0,
  3251. IsSys: 1,
  3252. SysRecordTime: record_time,
  3253. }
  3254. stockInInfo, _ := service.FindLastStockInInfoRecord(before.GoodId, adminInfo.Org.Id)
  3255. warehouseOutInfo.Price = stockInInfo.Price
  3256. warehouseOutInfo.GoodId = before.GoodId
  3257. warehouseOutInfo.GoodTypeId = before.GoodTypeId
  3258. err := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  3259. if err == nil {
  3260. //可能存在商品使用人不存在的情况,需要先判断商品使用人是否存在
  3261. user, err := service.FindGoodUserById(before.GoodTypeId, before.GoodId, patient_id, adminInfo.Org.Id, record_time)
  3262. if err == gorm.ErrRecordNotFound {
  3263. details := &models.AutomaticReduceDetail{
  3264. WarehouseOutId: warehouseOutInfo.ID,
  3265. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  3266. PatientId: patient_id,
  3267. Ctime: time.Now().Unix(),
  3268. Mtime: time.Now().Unix(),
  3269. Status: 1,
  3270. RecordTime: record_time,
  3271. OrgId: adminInfo.Org.Id,
  3272. GoodId: consumable.GoodId,
  3273. GoodTypeId: consumable.GoodTypeId,
  3274. Count: before.Count,
  3275. }
  3276. service.AddSigleAutoReduceRecordInfo(details)
  3277. } else if err == nil {
  3278. if user.ID > 0 {
  3279. //service.UpdateOrderInfoDetails( consumable.GoodTypeId, consumable.GoodId, record_time, adminInfo.Org.Id, patient_id, a_liquid, warehouseOutInfo)
  3280. service.UpdateUserInfoDetails(consumable.GoodTypeId, consumable.GoodId, record_time, adminInfo.Org.Id, patient_id, before.Count, warehouseOutInfo)
  3281. }
  3282. }
  3283. }
  3284. } else if err == nil { //存在,则更改使用人商品信息
  3285. fmt.Println("333333333")
  3286. //处理原来的数据
  3287. if newOut.ID > 0 {
  3288. if consumable.Count > before.Count { // 减少
  3289. num := int64(0)
  3290. if consumable.Count-before.Count > 0 {
  3291. num = consumable.Count - before.Count
  3292. } else {
  3293. num = before.Count - consumable.Count
  3294. }
  3295. service.UpdateOrderCountSub(consumable.GoodTypeId, consumable.GoodId, out.WarehouseOutOrderNumber, adminInfo.Org.Id, num)
  3296. } else if consumable.Count < before.Count { //增加
  3297. service.UpdateOrderCountAdd(consumable.GoodTypeId, consumable.GoodId, out.WarehouseOutOrderNumber, adminInfo.Org.Id, before.Count-consumable.Count)
  3298. }
  3299. user, err := service.FindGoodUserById(consumable.GoodTypeId, consumable.GoodId, patient_id, adminInfo.Org.Id, record_time)
  3300. if err == gorm.ErrRecordNotFound {
  3301. details := &models.AutomaticReduceDetail{
  3302. WarehouseOutId: newOut.ID,
  3303. WarehouseOutOrderNumber: newOut.WarehouseOutOrderNumber,
  3304. PatientId: patient_id,
  3305. Ctime: time.Now().Unix(),
  3306. Mtime: time.Now().Unix(),
  3307. Status: 1,
  3308. RecordTime: record_time,
  3309. OrgId: adminInfo.Org.Id,
  3310. GoodId: consumable.GoodId,
  3311. GoodTypeId: consumable.GoodTypeId,
  3312. Count: before.Count,
  3313. }
  3314. service.AddSigleAutoReduceRecordInfo(details)
  3315. } else if err == nil {
  3316. if user.ID > 0 {
  3317. service.UpdateUserInfoDetails(consumable.GoodTypeId, consumable.GoodId, record_time, adminInfo.Org.Id, patient_id, before.Count, &newOut)
  3318. }
  3319. }
  3320. }
  3321. }
  3322. fmt.Println("444444444")
  3323. }
  3324. }
  3325. }
  3326. }
  3327. }
  3328. }
  3329. fmt.Println("655555555")
  3330. var errs error
  3331. if len(beforePrepares) > 0 {
  3332. for _, item := range beforePrepares {
  3333. errs = service.UpdateDialysisBeforePrepareTwo(item)
  3334. }
  3335. }
  3336. if errs == nil {
  3337. c.ServeSuccessJSON(map[string]interface{}{
  3338. "msg": "修改成功",
  3339. })
  3340. return
  3341. } else {
  3342. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3343. return
  3344. }
  3345. } else {
  3346. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  3347. goods, _ := dataBody["goods"].([]interface{})
  3348. if len(goods) > 0 {
  3349. for _, item := range goods {
  3350. items := item.(map[string]interface{})
  3351. if items["record_time"] == nil || reflect.TypeOf(items["record_time"]).String() != "float64" {
  3352. utils.ErrorLog("record_time")
  3353. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3354. return
  3355. }
  3356. record_time := int64(items["record_time"].(float64))
  3357. if items["id"] == nil || reflect.TypeOf(items["id"]).String() != "float64" {
  3358. utils.ErrorLog("id")
  3359. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3360. return
  3361. }
  3362. id := int64(items["id"].(float64))
  3363. if items["patient_id"] == nil || reflect.TypeOf(items["patient_id"]).String() != "float64" {
  3364. utils.ErrorLog("patient_id")
  3365. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3366. return
  3367. }
  3368. patient_id := int64(items["patient_id"].(float64))
  3369. if items["creater"] == nil || reflect.TypeOf(items["creater"]).String() != "float64" {
  3370. utils.ErrorLog("creater")
  3371. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3372. return
  3373. }
  3374. creater := int64(items["creater"].(float64))
  3375. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  3376. utils.ErrorLog("good_id")
  3377. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3378. return
  3379. }
  3380. good_id := int64(items["good_id"].(float64))
  3381. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  3382. utils.ErrorLog("good_type_id")
  3383. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3384. return
  3385. }
  3386. good_type_id := int64(items["good_type_id"].(float64))
  3387. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  3388. utils.ErrorLog("count")
  3389. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3390. return
  3391. }
  3392. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3393. if items["ctime"] == nil || reflect.TypeOf(items["ctime"]).String() != "float64" {
  3394. utils.ErrorLog("ctime")
  3395. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3396. return
  3397. }
  3398. ctime := int64(items["ctime"].(float64))
  3399. adminUser := c.GetMobileAdminUserInfo()
  3400. prepare := &models.DialysisBeforePrepare{
  3401. ID: id,
  3402. UserOrgId: adminUser.Org.Id,
  3403. PatientId: patient_id,
  3404. RecordDate: record_time,
  3405. GoodId: good_id,
  3406. GoodTypeId: good_type_id,
  3407. Count: count,
  3408. Ctime: ctime,
  3409. Mtime: time.Now().Unix(),
  3410. Creater: creater,
  3411. Modifier: adminUser.AdminUser.Id,
  3412. Status: 1,
  3413. }
  3414. beforePrepares = append(beforePrepares, prepare)
  3415. }
  3416. }
  3417. }
  3418. if dataBody["new_goods"] != nil && reflect.TypeOf(dataBody["new_goods"]).String() == "[]interface {}" {
  3419. goods, _ := dataBody["new_goods"].([]interface{})
  3420. if len(goods) > 0 {
  3421. for _, item := range goods {
  3422. items := item.(map[string]interface{})
  3423. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  3424. utils.ErrorLog("good_id")
  3425. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3426. return
  3427. }
  3428. good_id := int64(items["good_id"].(float64))
  3429. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  3430. utils.ErrorLog("good_type_id")
  3431. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3432. return
  3433. }
  3434. good_type_id := int64(items["good_type_id"].(float64))
  3435. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  3436. utils.ErrorLog("count")
  3437. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3438. return
  3439. }
  3440. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3441. adminUser := c.GetMobileAdminUserInfo()
  3442. prepare := &models.DialysisBeforePrepare{
  3443. UserOrgId: adminUser.Org.Id,
  3444. PatientId: patient_id,
  3445. RecordDate: record_time,
  3446. GoodId: good_id,
  3447. GoodTypeId: good_type_id,
  3448. Count: count,
  3449. Ctime: time.Now().Unix(),
  3450. Mtime: time.Now().Unix(),
  3451. Creater: adminUser.AdminUser.Id,
  3452. Modifier: 0,
  3453. }
  3454. newBeforePrepares = append(newBeforePrepares, prepare)
  3455. }
  3456. }
  3457. service.CreateDialysisBeforePrepare(newBeforePrepares)
  3458. }
  3459. var errs error
  3460. if len(beforePrepares) > 0 {
  3461. for _, item := range beforePrepares {
  3462. errs = service.UpdateDialysisBeforePrepareTwo(item)
  3463. }
  3464. }
  3465. if errs == nil {
  3466. c.ServeSuccessJSON(map[string]interface{}{
  3467. "msg": "修改成功",
  3468. })
  3469. return
  3470. } else {
  3471. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3472. return
  3473. }
  3474. }
  3475. }
  3476. func (c *DialysisAPIController) GetDialysisGoods() {
  3477. schedualDate := c.GetString("schedule_date")
  3478. schedule_type, _ := c.GetInt64("schedule_type")
  3479. partition_id, _ := c.GetInt64("partition_id")
  3480. page, _ := c.GetInt("page")
  3481. patient_id, _ := c.GetInt64("patient_id")
  3482. schedualEndDate := int64(0)
  3483. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  3484. if parseDateErr != nil && len(schedualDate) != 0 {
  3485. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3486. return
  3487. }
  3488. endDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", schedualDate+" 23:59:59")
  3489. if parseDateErr != nil && len(schedualDate) != 0 {
  3490. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3491. return
  3492. }
  3493. schedualEndDate = endDate.Unix()
  3494. adminUser := c.GetMobileAdminUserInfo()
  3495. _, err := service.FindStockOutByIsSys(adminUser.Org.Id, 1, date.Unix())
  3496. goodTypes, _ := service.FindAllGoodType(adminUser.Org.Id)
  3497. if err == gorm.ErrRecordNotFound {
  3498. dialysisGoods, _, total := service.MobileGetDialysisGoods(adminUser.Org.Id, date.Unix(), schedule_type, partition_id, page, 0, patient_id, "", schedualEndDate)
  3499. if patient_id != 0 {
  3500. for _, item := range dialysisGoods { //获取当天排班的每个患者的最后日期的库存使用情况
  3501. goodUser, _ := service.GetLastDialysisGoods(item.PatientId, adminUser.Org.Id, date.Unix())
  3502. lastGoodUserDetial, _ := service.GetLastDialysisBeforePrepare(item.PatientId, adminUser.Org.Id, date.Unix())
  3503. item.LastAutomaticReduceDetail = goodUser
  3504. item.LastDialysisBeforePrepare = lastGoodUserDetial
  3505. }
  3506. }
  3507. c.ServeSuccessJSON(map[string]interface{}{
  3508. "dialysis_goods": dialysisGoods,
  3509. "good_type": goodTypes,
  3510. "total": total,
  3511. })
  3512. return
  3513. } else if err == nil {
  3514. //获取当天排班的每个患者的库存使用情况
  3515. dialysisGoods, err, total := service.MobileGetDialysisGoods(adminUser.Org.Id, date.Unix(), schedule_type, partition_id, page, 0, patient_id, "", schedualEndDate)
  3516. if patient_id != 0 {
  3517. for _, item := range dialysisGoods { //获取当天排班的每个患者的最后日期的库存使用情况
  3518. goodUser, _ := service.GetLastDialysisGoods(item.PatientId, adminUser.Org.Id, date.Unix())
  3519. lastGoodUserDetial, _ := service.GetLastDialysisBeforePrepare(item.PatientId, adminUser.Org.Id, date.Unix())
  3520. fmt.Println(goodUser)
  3521. fmt.Println(lastGoodUserDetial)
  3522. item.LastAutomaticReduceDetail = goodUser
  3523. item.LastDialysisBeforePrepare = lastGoodUserDetial
  3524. }
  3525. }
  3526. if err == nil {
  3527. c.ServeSuccessJSON(map[string]interface{}{
  3528. "dialysis_goods": dialysisGoods,
  3529. "good_type": goodTypes,
  3530. "total": total,
  3531. })
  3532. return
  3533. } else {
  3534. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3535. return
  3536. }
  3537. } else if err != nil {
  3538. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3539. return
  3540. }
  3541. }
  3542. func (c *DialysisAPIController) GetDialysisGoodsStatistics() {
  3543. start_time := c.GetString("start_time")
  3544. end_time := c.GetString("end_time")
  3545. timeLayout := "2006-01-02"
  3546. loc, _ := time.LoadLocation("Local")
  3547. var theStartTime int64
  3548. if len(start_time) > 0 {
  3549. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  3550. if err != nil {
  3551. utils.ErrorLog(err.Error())
  3552. }
  3553. theStartTime = theTime.Unix()
  3554. }
  3555. var theEndtTime int64
  3556. if len(end_time) > 0 {
  3557. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
  3558. if err != nil {
  3559. utils.ErrorLog(err.Error())
  3560. }
  3561. theEndtTime = theTime.Unix()
  3562. }
  3563. adminUser := c.GetMobileAdminUserInfo()
  3564. outInfo, err := service.MobileGetGoodsStatistics(adminUser.Org.Id, theStartTime, theEndtTime)
  3565. stockCount, err := service.GetOutStockTotalCountOne(theStartTime, theEndtTime, adminUser.Org.Id)
  3566. if err == nil {
  3567. c.ServeSuccessJSON(map[string]interface{}{
  3568. "stock_out": outInfo,
  3569. "stockCount": stockCount,
  3570. })
  3571. return
  3572. } else {
  3573. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3574. return
  3575. }
  3576. }
  3577. func (c *DialysisAPIController) GetStockInGoodInfo() {
  3578. patient_id, _ := c.GetInt64("patient_id", 0)
  3579. record_time := c.GetString("record_time")
  3580. adminUser := c.GetMobileAdminUserInfo()
  3581. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", record_time)
  3582. if parseDateErr != nil && len(record_time) != 0 {
  3583. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3584. return
  3585. }
  3586. goodTypes, _ := service.FindAllGoodTypeOne(adminUser.Org.Id)
  3587. good_info, _ := service.FindAllGoodInfo(adminUser.Org.Id)
  3588. goodUser, _ := service.GetAllStockOutUserDetail(patient_id, adminUser.Org.Id, date.Unix())
  3589. lastGoodUserDetial, _ := service.GetLastDialysisGoods(patient_id, adminUser.Org.Id, date.Unix())
  3590. c.ServeSuccessJSON(map[string]interface{}{
  3591. "good_type": goodTypes,
  3592. "good_user": goodUser,
  3593. "good_info": good_info,
  3594. "last_good_user": lastGoodUserDetial,
  3595. })
  3596. return
  3597. }
  3598. func (c *DialysisAPIController) CreateOtherStockOutInfo() {
  3599. patient_id, _ := c.GetInt64("patient_id", 0)
  3600. record_date := c.GetString("record_time")
  3601. if patient_id <= 0 {
  3602. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3603. return
  3604. }
  3605. adminInfo := c.GetMobileAdminUserInfo()
  3606. timeLayout := "2006-01-02"
  3607. loc, _ := time.LoadLocation("Local")
  3608. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3609. record_time := theRecordTime.Unix()
  3610. dataBody := make(map[string]interface{}, 0)
  3611. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  3612. if err != nil {
  3613. utils.ErrorLog(err.Error())
  3614. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3615. return
  3616. }
  3617. var beforePrepares []*models.DialysisBeforePrepare
  3618. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  3619. goods, _ := dataBody["goods"].([]interface{})
  3620. if len(goods) > 0 {
  3621. for _, item := range goods {
  3622. items := item.(map[string]interface{})
  3623. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  3624. utils.ErrorLog("good_id")
  3625. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3626. return
  3627. }
  3628. good_id := int64(items["good_id"].(float64))
  3629. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  3630. utils.ErrorLog("good_type_id")
  3631. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3632. return
  3633. }
  3634. good_type_id := int64(items["good_type_id"].(float64))
  3635. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  3636. utils.ErrorLog("count")
  3637. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3638. return
  3639. }
  3640. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3641. adminUser := c.GetMobileAdminUserInfo()
  3642. prepare := &models.DialysisBeforePrepare{
  3643. UserOrgId: adminUser.Org.Id,
  3644. PatientId: patient_id,
  3645. RecordDate: record_time,
  3646. GoodId: good_id,
  3647. GoodTypeId: good_type_id,
  3648. Count: count,
  3649. Ctime: time.Now().Unix(),
  3650. Mtime: time.Now().Unix(),
  3651. Creater: adminUser.AdminUser.Id,
  3652. Modifier: 0,
  3653. }
  3654. record_count := service.FindDialysisBeforePrepare(prepare.PatientId, prepare.GoodId, prepare.GoodTypeId, adminUser.Org.Id, record_time)
  3655. if record_count == 0 {
  3656. beforePrepares = append(beforePrepares, prepare)
  3657. } else if record_count == 1 {
  3658. service.UpdateDialysisBeforePrepareTwo(prepare)
  3659. }
  3660. }
  3661. }
  3662. }
  3663. beforePrepares = RemoveRepeatedGood(beforePrepares)
  3664. if len(beforePrepares) > 0 {
  3665. service.CreateDialysisBeforePrepare(beforePrepares)
  3666. }
  3667. consumables, _ := service.FindConsumablesByDate(adminInfo.Org.Id, patient_id, record_time)
  3668. //去重
  3669. consumables = RemoveRepeatedGood(consumables)
  3670. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  3671. if record.IsOpen == 1 {
  3672. out, err := service.FindStockOutByIsSys(adminInfo.Org.Id, 1, record_time)
  3673. if err == gorm.ErrRecordNotFound {
  3674. //没有记录,则创建出库单
  3675. timeStr := time.Now().Format("2006-01-02")
  3676. timeArr := strings.Split(timeStr, "-")
  3677. total, _ := service.FindAllWarehouseOut(adminInfo.Org.Id)
  3678. total = total + 1
  3679. warehousing_out_order := strconv.FormatInt(adminInfo.Org.Id, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  3680. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  3681. number = number + total
  3682. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  3683. creater := adminInfo.AdminUser.Id
  3684. warehouseOut := models.WarehouseOut{
  3685. WarehouseOutOrderNumber: warehousing_out_order,
  3686. OperationTime: time.Now().Unix(),
  3687. OrgId: adminInfo.Org.Id,
  3688. Creater: creater,
  3689. Ctime: time.Now().Unix(),
  3690. Status: 1,
  3691. WarehouseOutTime: record_time,
  3692. Dealer: 0,
  3693. Manufacturer: 0,
  3694. Type: 1,
  3695. IsSys: 1,
  3696. }
  3697. err := service.AddSigleWarehouseOut(&warehouseOut)
  3698. if err != nil {
  3699. utils.TraceLog("创建出库单失败 err = %v", err)
  3700. } else {
  3701. for _, item := range consumables {
  3702. if item.Count > 0 {
  3703. warehouseOutInfo := &models.WarehouseOutInfo{
  3704. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  3705. WarehouseOutId: warehouseOut.ID,
  3706. Status: 1,
  3707. Ctime: time.Now().Unix(),
  3708. Remark: "",
  3709. OrgId: adminInfo.Org.Id,
  3710. Type: 1,
  3711. Manufacturer: 0,
  3712. Dealer: 0,
  3713. IsSys: 1,
  3714. SysRecordTime: record_time,
  3715. GoodTypeId: item.GoodTypeId,
  3716. GoodId: item.GoodId,
  3717. }
  3718. warehouseOutInfo.Count = item.Count
  3719. stockInInfo, _ := service.FindLastStockInInfoRecord(item.GoodId, adminInfo.Org.Id)
  3720. warehouseOutInfo.Price = stockInInfo.Price
  3721. err := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  3722. if err == nil {
  3723. details := &models.AutomaticReduceDetail{
  3724. WarehouseOutId: warehouseOutInfo.ID,
  3725. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  3726. PatientId: patient_id,
  3727. Ctime: time.Now().Unix(),
  3728. Mtime: time.Now().Unix(),
  3729. Status: 1,
  3730. RecordTime: record_time,
  3731. OrgId: adminInfo.Org.Id,
  3732. GoodId: item.GoodId,
  3733. GoodTypeId: item.GoodTypeId,
  3734. Count: item.Count,
  3735. }
  3736. service.AddSigleAutoReduceRecordInfo(details)
  3737. }
  3738. }
  3739. }
  3740. }
  3741. } else if err == nil {
  3742. for _, item := range consumables {
  3743. outInfo, err := service.FindStockOutInfoByTypeId(adminInfo.Org.Id, item.GoodTypeId, item.GoodId, out.ID, out.WarehouseOutOrderNumber)
  3744. if err == gorm.ErrRecordNotFound {
  3745. warehouseOutInfo := &models.WarehouseOutInfo{
  3746. WarehouseOutOrderNumber: out.WarehouseOutOrderNumber,
  3747. WarehouseOutId: out.ID,
  3748. Status: 1,
  3749. Ctime: time.Now().Unix(),
  3750. Remark: "",
  3751. OrgId: adminInfo.Org.Id,
  3752. Type: 1,
  3753. Manufacturer: 0,
  3754. Dealer: 0,
  3755. IsSys: 1,
  3756. SysRecordTime: record_time,
  3757. }
  3758. stockInInfo, _ := service.FindLastStockInInfoRecord(item.GoodId, adminInfo.Org.Id)
  3759. warehouseOutInfo.Price = stockInInfo.Price
  3760. warehouseOutInfo.GoodId = item.GoodId
  3761. warehouseOutInfo.GoodTypeId = item.GoodTypeId
  3762. warehouseOutInfo.Count = item.Count
  3763. err := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  3764. if err == nil {
  3765. details := &models.AutomaticReduceDetail{
  3766. WarehouseOutId: warehouseOutInfo.ID,
  3767. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  3768. PatientId: patient_id,
  3769. Ctime: time.Now().Unix(),
  3770. Mtime: time.Now().Unix(),
  3771. Status: 1,
  3772. RecordTime: record_time,
  3773. OrgId: adminInfo.Org.Id,
  3774. GoodId: item.GoodId,
  3775. GoodTypeId: item.GoodTypeId,
  3776. Count: item.Count,
  3777. }
  3778. service.AddSigleAutoReduceRecordInfo(details)
  3779. }
  3780. } else if err == nil { //记录存在,则将增加数量
  3781. if outInfo.ID > 0 {
  3782. service.UpdateStockOutInfoCount2(adminInfo.Org.Id, outInfo.ID, item.Count)
  3783. }
  3784. details := &models.AutomaticReduceDetail{
  3785. WarehouseOutId: outInfo.ID,
  3786. WarehouseOutOrderNumber: outInfo.WarehouseOutOrderNumber,
  3787. PatientId: patient_id,
  3788. Ctime: time.Now().Unix(),
  3789. Mtime: time.Now().Unix(),
  3790. Status: 1,
  3791. RecordTime: record_time,
  3792. OrgId: adminInfo.Org.Id,
  3793. GoodId: item.GoodId,
  3794. GoodTypeId: item.GoodTypeId,
  3795. Count: item.Count,
  3796. }
  3797. service.AddSigleAutoReduceRecordInfo(details)
  3798. }
  3799. }
  3800. }
  3801. c.ServeSuccessJSON(map[string]interface{}{
  3802. "msg": "提交成功",
  3803. })
  3804. return
  3805. } else {
  3806. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeOpenStocktWrong)
  3807. return
  3808. }
  3809. }
  3810. func RemoveRepeatedGood(arr []*models.DialysisBeforePrepare) (newArr []*models.DialysisBeforePrepare) {
  3811. newArr = make([]*models.DialysisBeforePrepare, 0)
  3812. for i := 0; i < len(arr); i++ {
  3813. repeat := false
  3814. for j := i + 1; j < len(arr); j++ {
  3815. if arr[i].GoodId == arr[j].GoodId && arr[i].GoodTypeId == arr[j].GoodTypeId {
  3816. repeat = true
  3817. break
  3818. }
  3819. }
  3820. if !repeat {
  3821. newArr = append(newArr, arr[i])
  3822. }
  3823. }
  3824. return
  3825. }
  3826. func (c *DialysisAPIController) GetAllDrug() {
  3827. patient_id, _ := c.GetInt64("patient_id", 0)
  3828. adminInfo := c.GetMobileAdminUserInfo()
  3829. _, drugStockConfig := service.FindDrugStockAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  3830. privateDrugConfig, _ := service.GetDrugSetByUserOrgId(adminInfo.Org.Id)
  3831. drugList, _ := service.GetAllBaseDrugLibList(adminInfo.Org.Id)
  3832. privateDrugList, _ := service.GetPrivateDrugList(patient_id, adminInfo.Org.Id)
  3833. c.ServeSuccessJSON(map[string]interface{}{
  3834. "base_drug_config": drugStockConfig,
  3835. "private_drug_config": privateDrugConfig,
  3836. "base_drug_list": drugList,
  3837. "private_drug_list": privateDrugList,
  3838. })
  3839. }
  3840. func RemoveRepeatedGoodTwo(arr []*models.DialysisBeforePrepare) (newArr []*models.DialysisBeforePrepare) {
  3841. newArr = make([]*models.DialysisBeforePrepare, 0)
  3842. for i := 0; i < len(arr); i++ {
  3843. repeat := false
  3844. for j := i + 1; j < len(arr); j++ {
  3845. if arr[i].GoodId == arr[j].GoodId {
  3846. repeat = true
  3847. break
  3848. }
  3849. }
  3850. if !repeat {
  3851. newArr = append(newArr, arr[i])
  3852. }
  3853. }
  3854. return
  3855. }
  3856. func (c *DialysisAPIController) GetDepartment() {
  3857. adminInfo := c.GetMobileAdminUserInfo()
  3858. departments, err := service.GetAllDepartMent(adminInfo.Org.Id)
  3859. if err == nil {
  3860. c.ServeSuccessJSON(map[string]interface{}{
  3861. "departments": departments,
  3862. })
  3863. } else {
  3864. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3865. return
  3866. }
  3867. }