dialysis_api_controller.go 163KB

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