dialysis_api_controller.go 152KB

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