dialysis_api_controller.go 241KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560
  1. package mobile_api_controllers
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/jinzhu/gorm"
  7. "reflect"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "XT_New/enums"
  12. "XT_New/models"
  13. "XT_New/service"
  14. "XT_New/utils"
  15. "github.com/astaxie/beego"
  16. "math"
  17. "net/http"
  18. "net/url"
  19. )
  20. // type DialysisTestAPIController struct {
  21. // MobileBaseAPIController
  22. // }
  23. // [get]/m/api/test
  24. // func (this *DialysisTestAPIController) Test() {
  25. // orgID := int64(3907)
  26. // now := time.Now()
  27. // nextWeek := now.AddDate(0, 0, 7)
  28. // nextWeekMon, nextWeekSun := utils.GetMondayAndSundayOfWeekDate(&nextWeek)
  29. // nextTwoWeek := now.AddDate(0, 0, 14)
  30. // nextTwoWeekMon, nextTwoWeekSun := utils.GetMondayAndSundayOfWeekDate(&nextTwoWeek)
  31. // nextWeekSchs, getNextWeekSchErr := service.GetWeekSchedule(orgID, nextWeekMon.Unix(), nextWeekSun.Unix())
  32. // nextTwoWeekSchs, getNextTwoWeekSchErr := service.GetWeekSchedule(orgID, nextTwoWeekMon.Unix(), nextTwoWeekSun.Unix())
  33. // if getNextWeekSchErr != nil || getNextTwoWeekSchErr != nil {
  34. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  35. // return
  36. // }
  37. // exchangeErr := service.ExchangeScheduleTimeWithWeekSchedules(orgID, nextWeekSchs, nextTwoWeekSchs)
  38. // if exchangeErr != nil {
  39. // this.ErrorLog("%v", exchangeErr)
  40. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  41. // return
  42. // }
  43. // this.ServeSuccessJSON(map[string]interface{}{
  44. // // "now": now,
  45. // // "next_week": nextWeek,f
  46. // // "next_week_mon": nextWeekMon,
  47. // // "next_week_sun": nextWeekSun,
  48. // // "next_two_week_mon": nextTwoWeekMon,
  49. // // "next_two_week_sun": nextTwoWeekSun,
  50. // "next_week_schs": nextWeekSchs,
  51. // "next_two_week_schs": nextTwoWeekSchs,
  52. // })
  53. // }
  54. type DialysisAPIController struct {
  55. MobileBaseAPIAuthController
  56. }
  57. // /m/api/scheduals [get]
  58. // @param type:int
  59. // @param date:string
  60. func (this *DialysisAPIController) Scheduals() {
  61. schedualType, _ := this.GetInt64("type")
  62. schedualDate := this.GetString("date")
  63. if schedualType != 0 && schedualType != 1 && schedualType != 2 && schedualType != 3 {
  64. schedualType = 0
  65. }
  66. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  67. if parseDateErr != nil {
  68. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  69. return
  70. }
  71. adminInfo := this.GetMobileAdminUserInfo()
  72. orgID := adminInfo.Org.Id
  73. redis := service.RedisClient()
  74. defer redis.Close()
  75. key := "scheduals_" + schedualDate + "_" + strconv.FormatInt(orgID, 10)
  76. fmt.Println("key22332323232232323", key)
  77. scheduals_json_str, _ := redis.Get(key).Result()
  78. redis.Set(key, "", time.Second)
  79. patients, _ := service.GetAllPatientListSix(orgID)
  80. if len(scheduals_json_str) == 0 { //没有到缓存数据,从数据库中获取数据,进行缓存到redis
  81. scheduals, err := service.MobileGetDialysisScheduals(orgID, date.Unix(), schedualType)
  82. if err != nil {
  83. this.ErrorLog("获取排班信息失败:%v", err)
  84. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  85. } else {
  86. if len(scheduals) > 0 {
  87. devices, _ := service.GetAllDevicetByListSix(orgID)
  88. advices, _ := service.GetAllAdvicestByList(orgID, date.Unix())
  89. prescriptions, _ := service.GetAllPrescriptionsByList(orgID, date.Unix())
  90. assessmentBefores, _ := service.GetAllAssessmentBeforesByList(orgID, date.Unix())
  91. dialysisOrders, _ := service.GetAllDialysisOrdersByList(orgID, date.Unix())
  92. treatmentSummarys, _ := service.GetAllTreatmentSummarysByList(orgID, date.Unix())
  93. AssessmentAfterDislysis, _ := service.GetAllAssessmentAfterDislysisByList(orgID, date.Unix())
  94. hisAdvices, _ := service.GetAllHisAdvicesByList(orgID, date.Unix())
  95. for key, item := range scheduals {
  96. // 获取患者信息
  97. for _, patient := range patients {
  98. if item.PatientId == patient.ID {
  99. scheduals[key].SchedualPatient = patient
  100. break
  101. }
  102. }
  103. // 床位信息
  104. for _, device := range devices {
  105. if item.BedId == device.ID {
  106. scheduals[key].DeviceNumber = device
  107. break
  108. }
  109. }
  110. // 医嘱信息
  111. scheduals[key].Advices = make([]models.VMDoctorAdviceForList, 0)
  112. for _, advice := range advices {
  113. if item.PatientId == advice.PatientId {
  114. scheduals[key].Advices = append(scheduals[key].Advices, advice)
  115. }
  116. }
  117. // 医嘱信息
  118. scheduals[key].HisAdvices = make([]service.VMHisDoctorAdviceInfo, 0)
  119. for _, hisAdvice := range hisAdvices {
  120. if item.PatientId == hisAdvice.PatientId {
  121. scheduals[key].HisAdvices = append(scheduals[key].HisAdvices, hisAdvice)
  122. }
  123. }
  124. // 医嘱信息
  125. for _, prescription := range prescriptions {
  126. if item.PatientId == prescription.PatientId {
  127. scheduals[key].Prescription = prescription
  128. break
  129. }
  130. }
  131. // 透前评估
  132. for _, assessmentBefore := range assessmentBefores {
  133. if item.PatientId == assessmentBefore.PatientId {
  134. scheduals[key].AssessmentBeforeDislysis = assessmentBefore
  135. break
  136. }
  137. }
  138. // 透析上下机
  139. for _, dialysisOrder := range dialysisOrders {
  140. if item.PatientId == dialysisOrder.PatientId {
  141. scheduals[key].DialysisOrder = dialysisOrder
  142. break
  143. }
  144. }
  145. // 治疗小节
  146. for _, afterDislysis := range AssessmentAfterDislysis {
  147. if item.PatientId == afterDislysis.PatientId {
  148. scheduals[key].AssessmentAfterDislysis = afterDislysis
  149. break
  150. }
  151. }
  152. // 透后评估
  153. for _, treatmentSummary := range treatmentSummarys {
  154. if item.PatientId == treatmentSummary.PatientId {
  155. scheduals[key].TreatmentSummary = treatmentSummary
  156. break
  157. }
  158. }
  159. }
  160. //缓存数据
  161. scheduals_json, err := json.Marshal(&scheduals)
  162. if err == nil {
  163. redis.Set(key, scheduals_json, time.Second*60)
  164. }
  165. }
  166. //获取今日所有的处方开的耗材
  167. _, configs := service.FindXTHisProjectByOrgId(orgID)
  168. project := make([]*models.HisPrescriptionProjectTwo, 0)
  169. if configs.ID > 0 && configs.IsOpen == 1 {
  170. project, _ = service.GetAllHisProjectPrescription(orgID, date.Unix())
  171. }
  172. this.ServeSuccessJSON(map[string]interface{}{
  173. "scheduals": scheduals,
  174. "project": project,
  175. })
  176. }
  177. } else { //缓存数据了数据,将redis缓存的json字符串转为map
  178. var dat []map[string]interface{}
  179. if err := json.Unmarshal([]byte(scheduals_json_str), &dat); err == nil {
  180. } else {
  181. }
  182. //获取今日所有的处方开的耗材
  183. _, configs := service.FindXTHisProjectByOrgId(orgID)
  184. project := make([]*models.HisPrescriptionProjectTwo, 0)
  185. if configs.ID > 0 && configs.IsOpen == 1 {
  186. project, _ = service.GetAllHisProjectPrescription(orgID, date.Unix())
  187. }
  188. //获取今日透析准备的数据
  189. //goodList, err := service.MobileGetDialysisGoodsSeven(orgID, date.Unix())
  190. //fmt.Println("goodlist23323232323233232332233223323233", goodList, err)
  191. //
  192. //list, err := service.MobileGetDialysisGoodsSix(orgID, date.Unix())
  193. //
  194. //for _, item := range goodList {
  195. // for _, it := range list {
  196. // if item.RecordDate == it.RecordDate && item.PatientId == it.PatientId {
  197. // item.Children = append(item.Children, it)
  198. // }
  199. // }
  200. //}
  201. //autoList, _ := service.GetMobileAutoReduce(orgID, date.Unix())
  202. this.ServeSuccessJSON(map[string]interface{}{
  203. "scheduals": dat,
  204. "redis": "true",
  205. "date": schedualDate,
  206. "project": project,
  207. //"goodList": goodList,
  208. //"autoList": autoList,
  209. })
  210. }
  211. }
  212. // /m/api/waiting_scheduals [get]
  213. // @param date:string
  214. func (this *DialysisAPIController) WaitingScheduals() {
  215. schedualDate := this.GetString("date")
  216. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  217. if parseDateErr != nil && len(schedualDate) != 0 {
  218. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  219. return
  220. }
  221. adminInfo := this.GetMobileAdminUserInfo()
  222. orgID := adminInfo.Org.Id
  223. redis := service.RedisClient()
  224. defer redis.Close()
  225. // cur_date := time.Now().Format("2006-01-02")
  226. key := "wait_scheduals_" + schedualDate + "_" + strconv.FormatInt(orgID, 10)
  227. wait_scheduals, _ := redis.Get(key).Result()
  228. if len(wait_scheduals) == 0 { //没有到缓存数据,从数据库中获取数据,进行缓存到redis
  229. scheduals, err := service.MobileGetWaitingScheduals(orgID, date.Unix())
  230. if err != nil {
  231. this.ErrorLog("获取排班信息失败:%v", err)
  232. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  233. } else {
  234. returnScheduals := make([]*service.MDialysisScheduleVM, 0, len(scheduals))
  235. for _, s := range scheduals {
  236. returnScheduals = append(returnScheduals, s)
  237. }
  238. if len(returnScheduals) > 0 {
  239. //缓存数据
  240. wait_scheduals_json, err := json.Marshal(scheduals)
  241. if err == nil {
  242. redis.Set(key, wait_scheduals_json, time.Second*30)
  243. }
  244. }
  245. this.ServeSuccessJSON(map[string]interface{}{
  246. "scheduals": scheduals,
  247. })
  248. }
  249. } else { //缓存数据了数据,将redis缓存的json字符串转为map
  250. var dat []map[string]interface{}
  251. if err := json.Unmarshal([]byte(wait_scheduals), &dat); err == nil {
  252. } else {
  253. }
  254. this.ServeSuccessJSON(map[string]interface{}{
  255. "scheduals": dat,
  256. "redis": "true",
  257. "date": schedualDate,
  258. })
  259. }
  260. }
  261. //else{
  262. // fmt.Println("33333333")
  263. //
  264. // scheduals, err := service.MobileGetWaitingScheduals(orgID, date.Unix())
  265. // if err != nil {
  266. // this.ErrorLog("获取排班信息失败:%v", err)
  267. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  268. // } else {
  269. // returnScheduals := make([]*service.MDialysisScheduleVM, 0, len(scheduals))
  270. // for _, s := range scheduals {
  271. //
  272. // returnScheduals = append(returnScheduals, s)
  273. // }
  274. //
  275. // this.ServeSuccessJSON(map[string]interface{}{
  276. // "scheduals": returnScheduals,
  277. // })
  278. // }
  279. //
  280. // }
  281. //if err == nil{
  282. //
  283. //
  284. //
  285. //
  286. //
  287. //}else{
  288. //}
  289. // /m/api/dialysis/record [get]
  290. // @param patient_id:int
  291. // @param date:string (yyyy-MM-dd)
  292. func (this *DialysisAPIController) DialysisRecord() {
  293. patientID, _ := this.GetInt64("patient_id")
  294. recordDateStr := this.GetString("date")
  295. if patientID <= 0 {
  296. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  297. return
  298. }
  299. if len(recordDateStr) == 0 {
  300. recordDateStr = time.Now().Format("2006-01-02")
  301. }
  302. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  303. if parseDateErr != nil {
  304. this.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  305. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  306. return
  307. }
  308. adminInfo := this.GetMobileAdminUserInfo()
  309. ch := make(chan struct{})
  310. count := 24 // count 表示活动的协程个数
  311. var patient models.Patients
  312. var receiverTreatmentAccess *models.ReceiveTreatmentAsses
  313. var predialysisEvaluation *models.PredialysisEvaluation
  314. var lastPredialysisEvaluation *models.PredialysisEvaluation
  315. var doctorAdvices []*models.DoctorAdvice
  316. var dialysisOrder *models.DialysisOrder
  317. var doubleCheck *models.DoubleCheck
  318. var monitorRecords []*models.MonitoringRecord
  319. var lastMonitorRecord *models.MonitoringRecord
  320. var assessmentAfterDislysis *models.AssessmentAfterDislysis
  321. var lastAssessmentAfterDislysis *models.AssessmentAfterDislysis
  322. var treatmentSummary *models.TreatmentSummary
  323. var dialysisPrescribe *models.DialysisPrescription
  324. var dialysisSolution *models.DialysisSolution
  325. var lastDialysisPrescribe *models.DialysisPrescription
  326. var systemDialysisPrescribe *models.SystemPrescription
  327. var is_project_open_config models.XtHisProjectConfig
  328. var projects []*models.HisPrescriptionProject
  329. var stockType []*models.GoodsTypeOne
  330. var prepare []*models.XtDialysisBeforePrepare
  331. var lastAssessment models.XtPatientVascularAccess
  332. var lastDryWeightDislysis *models.SgjPatientDryweight
  333. var gobalConfig models.GobalConfig
  334. var operators []*models.SgjUserAdminRoles
  335. // 先走redis,没有走数据库
  336. schedual, _ := service.MobileGetSchedualDetailOne(adminInfo.Org.Id, patientID, date.Unix())
  337. go func() {
  338. patient, _ = service.FindPatientByIdWithDiseases(adminInfo.Org.Id, patientID)
  339. ch <- struct{}{}
  340. }()
  341. go func() {
  342. receiverTreatmentAccess, _ = service.MobileGetReceiverTreatmentAccessRecord(adminInfo.Org.Id, patientID, date.Unix())
  343. ch <- struct{}{}
  344. }()
  345. go func() {
  346. predialysisEvaluation, _ = service.MobileGetPredialysisEvaluation(adminInfo.Org.Id, patientID, date.Unix())
  347. ch <- struct{}{}
  348. }()
  349. go func() {
  350. lastPredialysisEvaluation, _ = service.MobileGetLastTimePredialysisEvaluation(adminInfo.Org.Id, patientID, date.Unix())
  351. ch <- struct{}{}
  352. }()
  353. go func() {
  354. doctorAdvices, _ = service.MobileGetDoctorAdvicesByGroups(adminInfo.Org.Id, patientID, date.Unix())
  355. ch <- struct{}{}
  356. }()
  357. go func() {
  358. dialysisOrder, _ = service.MobileGetSchedualDialysisRecord(adminInfo.Org.Id, patientID, date.Unix())
  359. ch <- struct{}{}
  360. }()
  361. go func() {
  362. doubleCheck, _ = service.MobileGetDoubleCheck(adminInfo.Org.Id, patientID, date.Unix())
  363. ch <- struct{}{}
  364. }()
  365. go func() {
  366. monitorRecords, _ = service.MobileGetMonitorRecords(adminInfo.Org.Id, patientID, date.Unix())
  367. ch <- struct{}{}
  368. }()
  369. go func() {
  370. lastMonitorRecord, _ = service.MobileGetLastMonitorRecord(adminInfo.Org.Id, patientID, date.Unix())
  371. ch <- struct{}{}
  372. }()
  373. go func() {
  374. assessmentAfterDislysis, _ = service.MobileGetAssessmentAfterDislysis(adminInfo.Org.Id, patientID, date.Unix())
  375. ch <- struct{}{}
  376. }()
  377. go func() {
  378. lastAssessmentAfterDislysis, _ = service.MobileGetLastTimeAssessmentAfterDislysis(adminInfo.Org.Id, patientID, date.Unix())
  379. ch <- struct{}{}
  380. }()
  381. go func() {
  382. treatmentSummary, _ = service.MobileGetTreatmentSummary(adminInfo.Org.Id, patientID, date.Unix())
  383. ch <- struct{}{}
  384. }()
  385. go func() {
  386. dialysisPrescribe, _ = service.MobileGetDialysisPrescribeByModeId(adminInfo.Org.Id, patientID, date.Unix(), schedual.ModeId)
  387. ch <- struct{}{}
  388. }()
  389. go func() {
  390. dialysisSolution, _ = service.MobileGetDialysisSolutionByModeId(adminInfo.Org.Id, patientID, schedual.ModeId)
  391. ch <- struct{}{}
  392. }()
  393. go func() {
  394. lastDialysisPrescribe, _ = service.MobileGetLastDialysisPrescribeByModeIdSix(adminInfo.Org.Id, patientID, schedual.ModeId)
  395. ch <- struct{}{}
  396. }()
  397. go func() {
  398. systemDialysisPrescribe, _ = service.MobileGetSystemDialysisPrescribeByModeId(adminInfo.Org.Id, schedual.ModeId)
  399. ch <- struct{}{}
  400. }()
  401. go func() {
  402. // 先走redis,没有走数据库
  403. _, is_project_open_config = service.FindXTHisProjectByOrgId(adminInfo.Org.Id)
  404. ch <- struct{}{}
  405. }()
  406. go func() {
  407. // 先走redis,没有走数据库
  408. projects, _ = service.GetHisPrescriptionProjects(adminInfo.Org.Id, patientID, date.Unix())
  409. ch <- struct{}{}
  410. }()
  411. go func() {
  412. // // 先走redis,没有走数据库
  413. stockType, _ = service.GetStockType(adminInfo.Org.Id)
  414. ch <- struct{}{}
  415. }()
  416. go func() {
  417. // 先走redis,没有走数据库
  418. prepare, _ = service.GetDialyStockOut(adminInfo.Org.Id, date.Unix(), patientID)
  419. ch <- struct{}{}
  420. }()
  421. go func() {
  422. // //获取最后一次血管通路
  423. // 先走redis,没有走数据库
  424. lastAssessment, _ = service.GetLastPassWayAssessment(adminInfo.Org.Id, patientID)
  425. ch <- struct{}{}
  426. }()
  427. go func() {
  428. // 先走redis,没有走数据库
  429. lastDryWeightDislysis, _ = service.MobileGetLastDryWeight(adminInfo.Org.Id, patientID)
  430. ch <- struct{}{}
  431. }()
  432. go func() {
  433. // 先走redis,没有走数据库
  434. _, gobalConfig = service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  435. ch <- struct{}{}
  436. }()
  437. go func() {
  438. // 先走redis,没有走数据库
  439. operators, _ = service.GetAllStarfEs(adminInfo.Org.Id)
  440. ch <- struct{}{}
  441. }()
  442. for range ch {
  443. // 每次从ch中接收数据,表明一个活动的协程结束
  444. count--
  445. // 当所有活动的协程都结束时,关闭管道
  446. if count == 0 {
  447. close(ch)
  448. }
  449. }
  450. prescribeOne, _ := service.MobileGetDialysisPrescribeByModeIdOne(adminInfo.Org.Id, patientID, date.Unix())
  451. _, is_open_config := service.FindXTHisRecordByOrgId(adminInfo.Org.Id)
  452. _, is_project_open_config = service.FindXTHisProjectByOrgId(adminInfo.Org.Id)
  453. projects, _ = service.GetHisPrescriptionProjects(adminInfo.Org.Id, patientID, date.Unix())
  454. temp_team_projects, _ := service.GetHisPrescriptionTeamProjects(adminInfo.Org.Id, patientID, date.Unix())
  455. prescriptionConfig, _ := service.FindPrescriptionConfigById(adminInfo.Org.Id)
  456. var team_projects []*models.HisPrescriptionProject
  457. //var index int64 = 0
  458. for _, item := range temp_team_projects {
  459. //组套里面非检验项目的
  460. if item.HisProject.CostClassify != 3 {
  461. projects = append(projects, item)
  462. }
  463. //组套里面检验项目的
  464. if item.HisProject.CostClassify == 3 {
  465. team_projects = append(team_projects, item)
  466. }
  467. }
  468. team_projects = RemoveRepeatedCheckRecod(team_projects)
  469. stockType, _ = service.GetStockType(adminInfo.Org.Id)
  470. prepare, _ = service.GetDialyStockOut(adminInfo.Org.Id, date.Unix(), patientID)
  471. prescribeOne, _ = service.MobileGetDialysisPrescribeByModeIdOne(adminInfo.Org.Id, patientID, date.Unix())
  472. var his_advices []*models.HisDoctorAdviceInfo
  473. if is_open_config.IsOpen == 1 {
  474. // 先走redis,没有走数据库
  475. his_advices, _ = service.GetAllHisDoctorAdvice(adminInfo.Org.Id, patientID, date.Unix())
  476. }
  477. is_advice_open, _ := service.FindAdviceSettingById(adminInfo.Org.Id)
  478. if is_advice_open.IsAdviceOpen == 1 {
  479. his_advices, _ = service.GetAllHisDoctorAdvice(adminInfo.Org.Id, patientID, date.Unix())
  480. }
  481. fmt.Println("doctorAdvices23344334344433434334343434wode", doctorAdvices)
  482. returnData := map[string]interface{}{
  483. "patient": patient,
  484. "schedual": schedual,
  485. "prescription": dialysisPrescribe,
  486. "solution": dialysisSolution,
  487. "last_prescription": lastDialysisPrescribe,
  488. "receiver_treatment_access": receiverTreatmentAccess,
  489. "predialysis_evaluation": predialysisEvaluation,
  490. "doctor_advices": doctorAdvices,
  491. "double_check": doubleCheck,
  492. "assessment_after_dislysis": assessmentAfterDislysis,
  493. "treatment_summary": treatmentSummary,
  494. "monitor_records": monitorRecords,
  495. "dialysis_order": dialysisOrder,
  496. "operators": operators,
  497. "last_predialysis_evaluation": lastPredialysisEvaluation,
  498. "last_assessment_after_dislysis": lastAssessmentAfterDislysis,
  499. "last_monitor_record": lastMonitorRecord,
  500. "config": gobalConfig,
  501. "dry_weight": lastDryWeightDislysis,
  502. "system_prescription": systemDialysisPrescribe,
  503. "his_advices": his_advices,
  504. "is_open_config": is_open_config,
  505. "stockType": stockType,
  506. "prepare": prepare,
  507. "lastAssessment": lastAssessment,
  508. "prescribeOne": prescribeOne,
  509. "is_project_open_config": is_project_open_config,
  510. "project": projects,
  511. "team_projects": team_projects,
  512. "is_advice_open": is_advice_open,
  513. "prescription_open": prescriptionConfig.IsOpen,
  514. }
  515. this.ServeSuccessJSON(returnData)
  516. }
  517. func (c *DialysisAPIController) GetDialysisGlobalConfig() {
  518. adminInfo := c.GetMobileAdminUserInfo()
  519. adminUsers, _ := service.GetAllAdminUsers(adminInfo.Org.Id, adminInfo.App.Id)
  520. devices, _ := service.GetValidDevicesBy(adminInfo.Org.Id, 0, 0)
  521. device_numbers, _ := service.GetAllValidDeviceNumbers(adminInfo.Org.Id)
  522. returnData := map[string]interface{}{
  523. "admin_users": adminUsers,
  524. "devices": devices,
  525. "device_numbers": device_numbers,
  526. }
  527. c.ServeSuccessJSON(returnData)
  528. }
  529. func (c *DialysisAPIController) PostAtreatmentInfo() {
  530. id, _ := c.GetInt64("patient", 0)
  531. recordDateStr := c.GetString("record_date")
  532. propagandaAndEducationContent := c.GetString("propagandaAndEducationContent")
  533. summaryContent := c.GetString("summaryContent")
  534. changeMedicalNurseId, _ := c.GetInt64("changeMedicalNurse", 0)
  535. treatNurseId, _ := c.GetInt64("treatNurse", 0)
  536. checkStaffId, _ := c.GetInt64("checkStaff", 0)
  537. deboardNurseId, _ := c.GetInt64("deboardNurse", 0)
  538. treatDoctor, _ := c.GetInt64("treatDoctor", 0)
  539. nursingRecord := c.GetString("nursing_record")
  540. fmt.Println("护理记录", nursingRecord)
  541. specialRecord := c.GetString("special_record")
  542. fmt.Println("特殊记录", specialRecord)
  543. adminUserInfo := c.GetMobileAdminUserInfo()
  544. changeMedicalNurseId = adminUserInfo.AdminUser.Id
  545. checkStaffId = adminUserInfo.AdminUser.Id
  546. deboardNurseId = adminUserInfo.AdminUser.Id
  547. treatDoctor = adminUserInfo.AdminUser.Id
  548. if id <= 0 {
  549. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  550. return
  551. }
  552. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  553. if patient.ID == 0 {
  554. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  555. return
  556. }
  557. if len(recordDateStr) == 0 {
  558. recordDateStr = time.Now().Format("2006-01-02")
  559. }
  560. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  561. if parseDateErr != nil {
  562. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  563. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  564. return
  565. }
  566. summary := models.TreatmentSummary{
  567. UserOrgId: adminUserInfo.Org.Id,
  568. PatientId: id,
  569. AssessmentDate: recordDate.Unix(),
  570. Mission: propagandaAndEducationContent,
  571. DialysisSummary: summaryContent,
  572. SjNurse: changeMedicalNurseId,
  573. ZlNurse: treatNurseId,
  574. HdNurse: checkStaffId,
  575. XjNurse: deboardNurseId,
  576. ZlDoctor: treatDoctor,
  577. CreatedTime: time.Now().Unix(),
  578. Status: 1,
  579. NursingRecord: nursingRecord,
  580. SpecialRecord: specialRecord,
  581. }
  582. _, treatmentSummary := service.FindTreatmentSummaryByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  583. if treatmentSummary.ID == 0 { //新增
  584. summary.Creater = adminUserInfo.AdminUser.Id
  585. service.AddSigleSummaryRecord(&summary)
  586. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":treatment_summary"
  587. redis := service.RedisClient()
  588. //清空key 值
  589. redis.Set(key, "", time.Second)
  590. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":treatment_summarys_list_all"
  591. redis.Set(keyOne, "", time.Second)
  592. keyThree := "scheduals_" + recordDateStr + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  593. redis.Set(keyThree, "", time.Second)
  594. defer redis.Close()
  595. c.ServeSuccessJSON(map[string]interface{}{
  596. "summary": summary,
  597. })
  598. } else { //修改
  599. summary.Creater = treatmentSummary.Creater
  600. summary.CreatedTime = treatmentSummary.CreatedTime
  601. summary.Modifier = adminUserInfo.AdminUser.Id
  602. summary.ID = treatmentSummary.ID
  603. service.UpdateSummeRecord(&summary)
  604. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":treatment_summary"
  605. redis := service.RedisClient()
  606. //清空key 值
  607. redis.Set(key, "", time.Second)
  608. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":treatment_summarys_list_all"
  609. redis.Set(keyOne, "", time.Second)
  610. keyThree := "scheduals_" + recordDateStr + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  611. redis.Set(keyThree, "", time.Second)
  612. defer redis.Close()
  613. c.ServeSuccessJSON(map[string]interface{}{
  614. "summary": summary,
  615. })
  616. }
  617. }
  618. func (c *DialysisAPIController) PostDoubleCheck() {
  619. id, _ := c.GetInt64("patient", 0)
  620. recordDateStr := c.GetString("record_date")
  621. checkTimeStr := c.GetString("check_time")
  622. firstCheckTimeStr := c.GetString("first_check_time")
  623. creater, _ := c.GetInt64("creater", 0)
  624. modifier, _ := c.GetInt64("modifier", 0)
  625. dialysis_item_check, _ := c.GetInt64("dialysis_item_check", 0)
  626. dialysis_parameter_check, _ := c.GetInt64("dialysis_parameter_check", 0)
  627. vascular_access_verification, _ := c.GetInt64("vascular_access_verification", 0)
  628. pipeline_connection_check, _ := c.GetInt64("pipeline_connection_check", 0)
  629. dialysis_item_desc := c.GetString("dialysis_item_desc")
  630. dialysis_parameter_desc := c.GetString("dialysis_parameter_desc")
  631. vascular_access_desc := c.GetString("vascular_access_desc")
  632. pipeline_connection_desc := c.GetString("pipeline_connection_desc")
  633. collator, _ := c.GetInt64("collator", 0)
  634. employee_number := c.GetString("employee_number")
  635. if id <= 0 {
  636. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  637. return
  638. }
  639. adminUserInfo := c.GetMobileAdminUserInfo()
  640. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  641. if patient.ID == 0 {
  642. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  643. return
  644. }
  645. if adminUserInfo.Org.Id == 9671 || adminUserInfo.Org.Id == 9675 || adminUserInfo.Org.Id == 10340 {
  646. list, _ := service.GetRoleList(adminUserInfo.Org.Id, modifier)
  647. if employee_number != list.JobNumber {
  648. c.ServeFailJSONWithSGJErrorCode(enums.ErrorEmployeeNumber)
  649. return
  650. }
  651. }
  652. if len(recordDateStr) == 0 {
  653. recordDateStr = time.Now().Format("2006-01-02")
  654. }
  655. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  656. if parseDateErr != nil {
  657. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  658. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  659. return
  660. }
  661. var checkDate int64
  662. if len(checkTimeStr) == 0 {
  663. checkDate = 0
  664. } else {
  665. checkDateUnix, _ := utils.ParseTimeStringToTime("2006-01-02 15:04:05", checkTimeStr)
  666. checkDate = checkDateUnix.Unix()
  667. }
  668. var firstCheckDate int64
  669. if len(firstCheckTimeStr) == 0 {
  670. firstCheckDate = 0
  671. } else {
  672. firstCheckDateUnix, _ := utils.ParseTimeStringToTime("2006-01-02 15:04:05", firstCheckTimeStr)
  673. firstCheckDate = firstCheckDateUnix.Unix()
  674. }
  675. //now := time.Now()
  676. //year, month, day := now.Date()
  677. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  678. //todayTimeStamp := today_time.Unix()
  679. doubleCheck := models.DoubleCheck{
  680. UserOrgId: adminUserInfo.Org.Id,
  681. PatientId: id,
  682. DialysisItemCheck: dialysis_item_check,
  683. DialysisParameterCheck: dialysis_parameter_check,
  684. VascularAccessVerification: vascular_access_verification,
  685. PipelineConnectionCheck: pipeline_connection_check,
  686. DialysisItemDesc: dialysis_item_desc,
  687. DialysisParameterDesc: dialysis_parameter_desc,
  688. VascularAccessDesc: vascular_access_desc,
  689. PipelineConnectionDesc: pipeline_connection_desc,
  690. Collator: collator,
  691. Status: 1,
  692. CreatedTime: time.Now().Unix(),
  693. CheckDate: recordDate.Unix(),
  694. UpdatedTime: time.Now().Unix(),
  695. EmployeeNumber: employee_number,
  696. }
  697. _, check := service.FindDoubleCheckByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  698. if check.ID == 0 { //新增
  699. doubleCheck.FirstCheckTime = firstCheckDate
  700. doubleCheck.CheckTime = checkDate
  701. doubleCheck.Creater = creater
  702. doubleCheck.Modifier = modifier
  703. err := service.AddSigleDoubleCheck(&doubleCheck)
  704. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":double_check"
  705. redis := service.RedisClient()
  706. defer redis.Close()
  707. //清空key 值
  708. redis.Set(key, "", time.Second)
  709. if err == nil {
  710. c.ServeSuccessJSON(map[string]interface{}{
  711. "doubleCheck": &doubleCheck,
  712. })
  713. }
  714. } else { //修改
  715. doubleCheck.FirstCheckTime = firstCheckDate
  716. doubleCheck.CheckTime = checkDate
  717. doubleCheck.Creater = creater
  718. doubleCheck.Modifier = modifier
  719. doubleCheck.CreatedTime = check.CreatedTime
  720. doubleCheck.ID = check.ID
  721. doubleCheck.EmployeeNumber = employee_number
  722. err := service.UpdateDoubleCheck(&doubleCheck)
  723. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":double_check"
  724. redis := service.RedisClient()
  725. defer redis.Close()
  726. //清空key 值
  727. redis.Set(key, "", time.Second)
  728. if err == nil {
  729. c.ServeSuccessJSON(map[string]interface{}{
  730. "doubleCheck": &doubleCheck,
  731. })
  732. }
  733. }
  734. }
  735. func (c *DialysisAPIController) PostAcceptsAssessment() {
  736. id, _ := c.GetInt64("patient", 0)
  737. recordDateStr := c.GetString("record_date")
  738. way, _ := c.GetInt64("way", 0)
  739. consciousness, _ := c.GetInt64("consciousness", 0)
  740. appetite, _ := c.GetInt64("appetite", 0)
  741. condition, _ := c.GetInt64("condition", 0)
  742. posture, _ := c.GetInt64("posture")
  743. sick_condition, _ := c.GetInt64("sick_condition", 0)
  744. danger_level, _ := c.GetInt64("danger_level", 0)
  745. intake, _ := c.GetInt64("intake", 0)
  746. nutrition, _ := c.GetInt64("nutrition", 0)
  747. psychological_assessment, _ := c.GetInt64("psychological_assessment", 0)
  748. psychological_assessment_other := c.GetString("psychological_assessment_other")
  749. score := c.GetString("score")
  750. sick_condition_other := c.GetString("sick_condition_other")
  751. //precaution, _ := c.GetInt64("precaution", 0)
  752. precaution := c.GetString("precaution")
  753. precaution_other := c.GetString("precaution_other")
  754. psychological_other := c.GetString("psychological_other")
  755. admission_number := c.GetString("admission_number")
  756. tumble, _ := c.GetInt64("tumble")
  757. if id <= 0 {
  758. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  759. return
  760. }
  761. adminUserInfo := c.GetMobileAdminUserInfo()
  762. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  763. if patient.ID == 0 {
  764. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  765. return
  766. }
  767. //now := time.Now()
  768. //year, month, day := now.Date()
  769. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  770. //todayTimeStamp := today_time.Unix()
  771. if len(recordDateStr) == 0 {
  772. recordDateStr = time.Now().Format("2006-01-02")
  773. }
  774. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  775. if parseDateErr != nil {
  776. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  777. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  778. return
  779. }
  780. _, receiveTreatment := service.FindReceiveTreatmentAssesByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  781. receiveTreatmentAsses := models.ReceiveTreatmentAsses{
  782. UserOrgId: adminUserInfo.Org.Id,
  783. PatientId: id,
  784. RecordDate: recordDate.Unix(),
  785. Way: way,
  786. Consciousness: consciousness,
  787. Appetite: appetite,
  788. Condition: condition,
  789. SickCondition: sick_condition,
  790. DangerLevel: danger_level,
  791. Intake: intake,
  792. Nutrition: nutrition,
  793. PsychologicalAssessment: psychological_assessment,
  794. PsychologicalAssessmentOther: psychological_assessment_other,
  795. SickConditionOther: sick_condition_other,
  796. Posture: posture,
  797. CreatedTime: time.Now().Unix(),
  798. UpdateTime: time.Now().Unix(),
  799. Status: 1,
  800. Score: score,
  801. Precaution: precaution,
  802. PrecautionOther: precaution_other,
  803. PsychologicalOther: psychological_other,
  804. AdmissionNumber: admission_number,
  805. Tumble: tumble,
  806. }
  807. if receiveTreatment.ID == 0 { //新增
  808. receiveTreatmentAsses.Creater = adminUserInfo.AdminUser.Id
  809. err := service.AddSigleReceiveTreatmentAssesRecord(&receiveTreatmentAsses)
  810. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":receive_treatment_asses"
  811. redis := service.RedisClient()
  812. defer redis.Close()
  813. //清空key 值
  814. redis.Set(key, "", time.Second)
  815. if err == nil {
  816. c.ServeSuccessJSON(map[string]interface{}{
  817. "receiveTreatmentAsses": receiveTreatmentAsses,
  818. })
  819. }
  820. } else { //修改
  821. //if receiveTreatment.Creater != adminUserInfo.AdminUser.Id {
  822. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  823. // if getPermissionErr != nil {
  824. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  825. // return
  826. // } else if headNursePermission == nil {
  827. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  828. // return
  829. // }
  830. //}
  831. receiveTreatmentAsses.Creater = receiveTreatment.Creater
  832. receiveTreatmentAsses.CreatedTime = receiveTreatment.CreatedTime
  833. receiveTreatmentAsses.Modifier = adminUserInfo.AdminUser.Id
  834. receiveTreatmentAsses.ID = receiveTreatment.ID
  835. err := service.UpadateReceiveTreatmentAsses(&receiveTreatmentAsses)
  836. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":receive_treatment_asses"
  837. redis := service.RedisClient()
  838. defer redis.Close()
  839. //清空key 值
  840. redis.Set(key, "", time.Second)
  841. if err == nil {
  842. c.ServeSuccessJSON(map[string]interface{}{
  843. "receiveTreatmentAsses": receiveTreatmentAsses,
  844. })
  845. }
  846. }
  847. }
  848. func (c *DialysisAPIController) PostAssessmentAfterDislysis() {
  849. id, _ := c.GetInt64("patient", 0)
  850. recordDateStr := c.GetString("record_date")
  851. weightAfter, _ := c.GetFloat("weight_after", 0)
  852. additionalWeight, _ := c.GetFloat("additional_weight", 0)
  853. weightReduce, _ := c.GetFloat("weight_loss", 0)
  854. temperature, _ := c.GetFloat("temperature", 0)
  855. pulse_frequency, _ := c.GetFloat("pulse_frequency", 0)
  856. //breathing_rate, _ := c.GetFloat("breathing_rate", 0)
  857. breathing_rate := c.GetString("breathing_rate")
  858. systolic_blood_pressure, _ := c.GetFloat("systolic_blood_pressure", 0)
  859. //breathing_rate, _ := c.GetFloat("breathing_rate", 0)
  860. breathing_rate := c.GetString("breathing_rate")
  861. systolic_blood_pressure, _ := c.GetFloat("systolic_blood_pressure", 0)
  862. diastolic_blood_pressure, _ := c.GetFloat("diastolic_blood_pressure", 0)
  863. actual_ultrafiltration, _ := c.GetFloat("actual_ultrafiltration", 0)
  864. actual_displacement, _ := c.GetFloat("actual_displacement", 0)
  865. actualtreatHour, _ := c.GetInt64("actual_treatment_hour", 0)
  866. actualtreatmin, _ := c.GetInt64("actual_treatment_minute", 0)
  867. cruor := c.GetString("cruor")
  868. symptomsAfterDialysi := c.GetString("symptom_after_dialysis")
  869. internalFistula := c.GetString("internal_fistula")
  870. catheter := c.GetString("catheter")
  871. complications := c.GetString("complication")
  872. remark := c.GetString("remark")
  873. //dialysateVolume, _ := c.GetInt64("dialysis_intakes", 0)
  874. dialysis_intakes := c.GetString("dialysis_intakes")
  875. dialysateVolume, _ := strconv.ParseFloat(dialysis_intakes, 64)
  876. fmt.Println("dialysateVolumewode 23323233223232wode", dialysateVolume)
  877. dialysis_intakes_unit, _ := c.GetInt64("dialysis_intakes_unit", 0)
  878. blood_access_part_id, _ := c.GetInt64("blood_access_part_id", 0)
  879. blood_access_part_opera_id, _ := c.GetInt64("blood_access_part_opera_id", 0)
  880. puncturePointOozingBlood, _ := c.GetInt64("puncture_point_oozing_blood", 0)
  881. puncturePointHaematoma, _ := c.GetInt64("puncture_point_haematoma", 0)
  882. internalFistulaTremorAc, _ := c.GetInt64("internal_fistula_tremor_ac", 0)
  883. patientGose, _ := c.GetInt64("patient_gose", 0)
  884. inpatientDepartment := c.GetString("inpatient_department")
  885. observationContent := c.GetString("observation_content")
  886. observationContentOther := c.GetString("observation_content_other")
  887. dialysis_process, _ := c.GetInt64("dialysis_process", 0)
  888. in_advance_minute, _ := c.GetFloat("in_advance_minute", 0)
  889. in_advance_reason := c.GetString("in_advance_reason")
  890. hemostasis_minute, _ := c.GetInt64("hemostasis_minute", 0)
  891. hemostasis_opera, _ := c.GetInt64("hemostasis_opera", 0)
  892. tremor_noise, _ := c.GetInt64("tremor_noise", 0)
  893. disequilibrium_syndrome, _ := c.GetInt64("disequilibrium_syndrome", 0)
  894. disequilibrium_syndrome_option := c.GetString("disequilibrium_syndrome_option")
  895. arterial_tube, _ := c.GetInt64("arterial_tube", 0)
  896. intravenous_tube, _ := c.GetInt64("intravenous_tube", 0)
  897. dialyzer, _ := c.GetInt64("dialyzer", 0)
  898. in_advance_reason_other := c.GetString("in_advance_reason_other")
  899. is_eat, _ := c.GetInt64("is_eat", 0)
  900. cvc_a, _ := c.GetFloat("cvc_a", 0)
  901. cvc_v, _ := c.GetFloat("cvc_v", 0)
  902. channels, _ := c.GetInt64("channel", 0)
  903. return_blood, _ := c.GetInt64("return_blood", 0)
  904. rehydration_volume, _ := c.GetInt64("rehydration_volume", 0)
  905. dialysis_during, _ := c.GetInt64("dialysis_during", 0)
  906. stroke_volume, _ := c.GetInt64("stroke_volume", 0)
  907. blood_flow, _ := c.GetInt64("blood_flow", 0)
  908. //sealing_fluid_dispose, _ := c.GetInt64("sealing_fluid_dispose", 0)
  909. sealing_fluid_dispose := c.GetString("sealing_fluid_dispose")
  910. sealing_fluid_special := c.GetString("sealing_fluid_special")
  911. dosage_of_anticoagulants, _ := c.GetFloat("dosage_of_anticoagulants")
  912. supine_systolic_blood_pressure := c.GetString("supine_systolic_blood_pressure")
  913. setting_pressure := c.GetString("setting_pressure")
  914. supine_diastolic_blood_pressure := c.GetString("supine_diastolic_blood_pressure")
  915. diastolic_pressure := c.GetString("diastolic_pressure")
  916. other_complication := c.GetString("other_complication")
  917. ktv := c.GetString("ktv")
  918. urr := c.GetString("urr")
  919. hypertenison, _ := c.GetInt64("hypertenison")
  920. hypopiesia, _ := c.GetInt64("hypopiesia")
  921. leave_office_method, _ := c.GetInt64("leave_office_method")
  922. lapse, _ := c.GetInt64("lapse")
  923. consciousness, _ := c.GetInt64("consciousness")
  924. fallrisk, _ := c.GetInt64("fallrisk")
  925. machine_run := c.GetString("machine_run")
  926. after_urea := c.GetString("after_urea")
  927. pip_coagulation := c.GetString("pip_coagulation")
  928. accumulated_blood_volume := c.GetString("accumulated_blood_volume")
  929. if id <= 0 {
  930. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  931. return
  932. }
  933. adminUserInfo := c.GetMobileAdminUserInfo()
  934. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  935. if patient.ID == 0 {
  936. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  937. return
  938. }
  939. if len(recordDateStr) == 0 {
  940. recordDateStr = time.Now().Format("2006-01-02")
  941. }
  942. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  943. if parseDateErr != nil {
  944. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  945. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  946. return
  947. }
  948. //now := time.Now()
  949. //year, month, day := now.Date()
  950. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  951. //todayTimeStamp := today_time.Unix()
  952. //_, evaluation := service.FindPredialysisEvaluationByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  953. assessmentAfterDislysis := models.AssessmentAfterDislysis{
  954. UserOrgId: adminUserInfo.Org.Id,
  955. PatientId: id,
  956. AssessmentDate: recordDate.Unix(),
  957. Temperature: temperature,
  958. PulseFrequency: pulse_frequency,
  959. BreathingRate: breathing_rate,
  960. SystolicBloodPressure: systolic_blood_pressure,
  961. DiastolicBloodPressure: diastolic_blood_pressure,
  962. ActualUltrafiltration: actual_ultrafiltration,
  963. ActualDisplacement: actual_displacement,
  964. ActualTreatmentHour: actualtreatHour,
  965. ActualTreatmentMinute: actualtreatmin,
  966. WeightAfter: weightAfter,
  967. AdditionalWeight: additionalWeight,
  968. WeightLoss: weightReduce,
  969. Cruor: cruor,
  970. SymptomAfterDialysis: symptomsAfterDialysi,
  971. InternalFistula: internalFistula,
  972. Catheter: catheter,
  973. Complication: complications,
  974. DialysisIntakes: dialysateVolume,
  975. CreatedTime: time.Now().Unix(),
  976. Status: 1,
  977. Remark: remark,
  978. BloodAccessPartId: blood_access_part_id,
  979. BloodAccessPartOperaId: blood_access_part_opera_id,
  980. DialysisIntakesUnit: dialysis_intakes_unit,
  981. PuncturePointOozingBlood: puncturePointOozingBlood,
  982. PuncturePointHaematoma: puncturePointHaematoma,
  983. InternalFistulaTremorAc: internalFistulaTremorAc,
  984. PatientGose: patientGose,
  985. InpatientDepartment: inpatientDepartment,
  986. ObservationContent: observationContent,
  987. ObservationContentOther: observationContentOther,
  988. DialysisProcess: dialysis_process,
  989. InAdvanceMinute: in_advance_minute,
  990. InAdvanceReason: in_advance_reason,
  991. HemostasisMinute: hemostasis_minute,
  992. HemostasisOpera: hemostasis_opera,
  993. TremorNoise: tremor_noise,
  994. DisequilibriumSyndrome: disequilibrium_syndrome,
  995. DisequilibriumSyndromeOption: disequilibrium_syndrome_option,
  996. ArterialTube: arterial_tube,
  997. IntravenousTube: intravenous_tube,
  998. Dialyzer: dialyzer,
  999. InAdvanceReasonOther: in_advance_reason_other,
  1000. IsEat: is_eat,
  1001. CvcA: cvc_a,
  1002. CvcV: cvc_v,
  1003. Channel: channels,
  1004. ReturnBlood: return_blood,
  1005. RehydrationVolume: rehydration_volume,
  1006. DialysisDuring: dialysis_during,
  1007. StrokeVolume: stroke_volume,
  1008. BloodFlow: blood_flow,
  1009. SealingFluidDispose: sealing_fluid_dispose,
  1010. SealingFluidSpecial: sealing_fluid_special,
  1011. DosageOfAnticoagulants: dosage_of_anticoagulants,
  1012. SupineDiastolicBloodPressure: supine_diastolic_blood_pressure,
  1013. SupineSystolicBloodPressure: supine_systolic_blood_pressure,
  1014. SettingPressure: setting_pressure,
  1015. DiastolicPressure: diastolic_pressure,
  1016. OtherComplication: other_complication,
  1017. Ktv: ktv,
  1018. Urr: urr,
  1019. Hypopiesia: hypopiesia,
  1020. Hypertenison: hypertenison,
  1021. Lapse: lapse,
  1022. LeaveOfficeMethod: leave_office_method,
  1023. Consciousness: consciousness,
  1024. Fallrisk: fallrisk,
  1025. MachineRun: machine_run,
  1026. AfterUrea: after_urea,
  1027. PipCoagulation: pip_coagulation,
  1028. AccumulatedBloodVolume: accumulated_blood_volume,
  1029. }
  1030. appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id, adminUserInfo.App.Id)
  1031. _, assessmentAfter := service.FindAssessmentAfterDislysisByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  1032. if assessmentAfter.ID == 0 { //新增
  1033. if appRole.UserType == 2 || appRole.UserType == 1 {
  1034. assessmentAfterDislysis.AssessmentDoctor = adminUserInfo.AdminUser.Id
  1035. assessmentAfterDislysis.AssessmentTime = time.Now().Unix()
  1036. } else {
  1037. assessmentAfterDislysis.Creater = adminUserInfo.AdminUser.Id
  1038. }
  1039. err := service.AddSigleAssessmentAfterDislysisRecord(&assessmentAfterDislysis)
  1040. redis := service.RedisClient()
  1041. keyTwo := "scheduals_" + recordDateStr + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  1042. redis.Set(keyTwo, "", time.Second)
  1043. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_after_dislysis"
  1044. //清空key 值
  1045. redis.Set(key, "", time.Second)
  1046. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_after_dislysis_list_all"
  1047. redis.Set(keyOne, "", time.Second)
  1048. defer redis.Close()
  1049. if err == nil {
  1050. c.ServeSuccessJSON(map[string]interface{}{
  1051. "assessmentAfterDislysis": assessmentAfterDislysis,
  1052. })
  1053. }
  1054. } else { //修改
  1055. if appRole.UserType == 2 || appRole.UserType == 1 {
  1056. assessmentAfterDislysis.AssessmentDoctor = adminUserInfo.AdminUser.Id
  1057. assessmentAfterDislysis.AssessmentTime = time.Now().Unix()
  1058. } else {
  1059. assessmentAfterDislysis.Modifier = adminUserInfo.AdminUser.Id
  1060. if assessmentAfterDislysis.Creater == 0 {
  1061. assessmentAfterDislysis.Creater = adminUserInfo.AdminUser.Id
  1062. }
  1063. }
  1064. assessmentAfterDislysis.CreatedTime = assessmentAfter.CreatedTime
  1065. assessmentAfterDislysis.ID = assessmentAfter.ID
  1066. err := service.UpdateAssessmentAfterDislysisRecord(&assessmentAfterDislysis)
  1067. redis := service.RedisClient()
  1068. keyTwo := "scheduals_" + recordDateStr + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  1069. redis.Set(keyTwo, "", time.Second)
  1070. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_after_dislysis"
  1071. //清空key 值
  1072. redis.Set(key, "", time.Second)
  1073. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_after_dislysis_list_all"
  1074. redis.Set(keyOne, "", time.Second)
  1075. fmt.Println("err233332323232232323", err)
  1076. if err == nil {
  1077. c.ServeSuccessJSON(map[string]interface{}{
  1078. "assessmentAfterDislysis": assessmentAfterDislysis,
  1079. })
  1080. }
  1081. }
  1082. }
  1083. func (c *DialysisAPIController) PostDialysisPrescription() {
  1084. id, _ := c.GetInt64("patient", 0)
  1085. recordDateStr := c.GetString("record_date")
  1086. if id <= 0 {
  1087. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1088. return
  1089. }
  1090. adminUserInfo := c.GetMobileAdminUserInfo()
  1091. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  1092. if patient.ID == 0 {
  1093. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1094. return
  1095. }
  1096. if len(recordDateStr) == 0 {
  1097. recordDateStr = time.Now().Format("2006-01-02")
  1098. }
  1099. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1100. if parseDateErr != nil {
  1101. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  1102. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1103. return
  1104. }
  1105. mode_id, _ := c.GetInt64("mode_id", 0)
  1106. dialysis_duration, _ := c.GetFloat("dialysis_duration", 0)
  1107. dialyzer, _ := c.GetInt64("dialyzer", 0)
  1108. perfusion_apparatus, _ := c.GetInt64("perfusion_apparatus", 0)
  1109. blood_flow_volume, _ := c.GetFloat("blood_flow_volume", 0)
  1110. dewater_amount, _ := c.GetFloat("dewater_amount", 0)
  1111. displace_liqui, _ := c.GetFloat("displace_liqui", 0)
  1112. replacement_total, _ := c.GetFloat("replacement_total", 0)
  1113. replacement_way, _ := c.GetInt64("replacement_way", 0)
  1114. anticoagulant, _ := c.GetInt64("anticoagulant", 0)
  1115. anticoagulant_shouji, _ := c.GetFloat("anticoagulant_shouji", 0)
  1116. anticoagulant_weichi, _ := c.GetFloat("anticoagulant_weichi", 0)
  1117. anticoagulant_zongliang, _ := c.GetFloat("anticoagulant_zongliang", 0)
  1118. anticoagulant_gaimingcheng := c.GetString("anticoagulant_gaimingcheng")
  1119. anticoagulant_gaijiliang := c.GetString("anticoagulant_gaijiliang")
  1120. dialyzerPerfusionApparatus := c.GetString("dialyzer_perfusion_apparatus")
  1121. kalium, _ := c.GetFloat("kalium", 0)
  1122. sodium, _ := c.GetFloat("sodium", 0)
  1123. calcium, _ := c.GetFloat("calcium", 0)
  1124. bicarbonate, _ := c.GetFloat("bicarbonate", 0)
  1125. glucose, _ := c.GetFloat("glucose", 0)
  1126. // prescription_doctor, _ := c.GetInt64("prescription_doctor", 0)
  1127. // dry_weight, _ := c.GetFloat("dry_weight", 0)
  1128. dialysate_flow, _ := c.GetFloat("dialysate_flow", 0)
  1129. dialysate_temperature, _ := c.GetFloat("dialysate_temperature", 0)
  1130. conductivity, _ := c.GetFloat("conductivity", 0)
  1131. remark := c.GetString("remark")
  1132. dialysisDurationHour, _ := c.GetInt64("dialysis_duration_hour", 0)
  1133. dialysisDurationMinute, _ := c.GetInt64("dialysis_duration_minute", 0)
  1134. targetUltrafiltration, _ := c.GetFloat("target_ultrafiltration", 0)
  1135. dialysateFormulation, _ := c.GetInt64("dialysate_formulation", 0)
  1136. body_fluid, _ := c.GetInt64("body_fluid", 0)
  1137. special_medicine, _ := c.GetInt64("special_medicine", 0)
  1138. special_medicine_other := c.GetString("special_medicine_other")
  1139. displace_liqui_part, _ := c.GetInt64("displace_liqui_part", 0)
  1140. displace_liqui_value, _ := c.GetFloat("displace_liqui_value", 0)
  1141. blood_access, _ := c.GetInt64("blood_access", 0)
  1142. ultrafiltration, _ := c.GetFloat("ultrafiltration", 0)
  1143. body_fluid_other := c.GetString("body_fluid_other")
  1144. niprocart, _ := c.GetInt64("niprocart", 0)
  1145. jms, _ := c.GetInt64("jms", 0)
  1146. fistula_needle_set, _ := c.GetInt64("fistula_needle_set", 0)
  1147. fistula_needle_set_16, _ := c.GetInt64("fistula_needle_set_16", 0)
  1148. hemoperfusion, _ := c.GetInt64("hemoperfusion", 0)
  1149. dialyser_sterilised, _ := c.GetInt64("dialyser_sterilised", 0)
  1150. filtryzer, _ := c.GetInt64("filtryzer", 0)
  1151. target_ktv, _ := c.GetFloat("target_ktv", 0)
  1152. dialyzers, _ := c.GetInt64("dialyzers", 0)
  1153. injector, _ := c.GetInt64("injector", 0)
  1154. bloodlines, _ := c.GetInt64("bloodlines", 0)
  1155. tubing_hemodialysis, _ := c.GetInt64("tubing_hemodialysis", 0)
  1156. safe_package, _ := c.GetInt64("package", 0)
  1157. a_liquid, _ := c.GetInt64("a_liquid", 0)
  1158. pre_impulse, parseDateErr := c.GetFloat("pre_impulse", 0)
  1159. fmt.Println("预冲量", pre_impulse)
  1160. anticoagulant_stop_time_hour, _ := c.GetInt64("anticoagulant_stop_time_hour", 0)
  1161. anticoagulant_stop_time_min, _ := c.GetInt64("anticoagulant_stop_time_min", 0)
  1162. blood := c.GetString("blood")
  1163. dialysis_dialyszers := c.GetString("dialysis_dialyszers")
  1164. dialysis_irrigation := c.GetString("dialysis_irrigation")
  1165. antioxidant_commodity_name := c.GetString("antioxidant_commodity_name")
  1166. displace_speed := c.GetString("displace_speed")
  1167. illness, _ := c.GetInt64("illness")
  1168. amylaceum := c.GetString("amylaceum")
  1169. single_time := c.GetString("single_time")
  1170. single_water := c.GetString("single_water")
  1171. replacement_flow := c.GetString("replacement_flow")
  1172. plasma_separator := c.GetString("plasma_separator")
  1173. bilirubin_adsorption_column := c.GetString("bilirubin_adsorption_column")
  1174. oxygen_uptake, _ := c.GetInt64("oxygen_uptake")
  1175. oxygen_flow := c.GetString("oxygen_flow")
  1176. oxygen_time := c.GetString("oxygen_time")
  1177. hemodialysis_pipelines := c.GetString("hemodialysis_pipelines")
  1178. hemodialysis_pipelines_count, _ := c.GetFloat("hemodialysis_pipelines_count", 0)
  1179. puncture_needle := c.GetString("puncture_needle")
  1180. puncture_needle_count, _ := c.GetFloat("puncture_needle_count", 0)
  1181. epo := c.GetString("epo")
  1182. epo_count, _ := c.GetFloat("epo_count", 0)
  1183. max_ultrafiltration_rate, _ := c.GetFloat("max_ultrafiltration_rate")
  1184. appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id, adminUserInfo.App.Id)
  1185. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  1186. //
  1187. //if template.TemplateId == 2 || template.TemplateId == 6 {
  1188. // if appRole.UserType == 3 {
  1189. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1190. // if getPermissionErr != nil {
  1191. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1192. // return
  1193. // } else if headNursePermission == nil {
  1194. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePrescriptionPermissionDeniedModify)
  1195. // return
  1196. // }
  1197. // }
  1198. //}
  1199. //TODO 需要根据角色去判断
  1200. prescription := models.DialysisPrescription{
  1201. UserOrgId: adminUserInfo.Org.Id,
  1202. PatientId: id,
  1203. RecordDate: recordDate.Unix(),
  1204. ModeId: mode_id,
  1205. DialysisDuration: dialysis_duration,
  1206. Dialyzer: dialyzer,
  1207. PerfusionApparatus: perfusion_apparatus,
  1208. BloodFlowVolume: blood_flow_volume,
  1209. DewaterAmount: dewater_amount,
  1210. DisplaceLiqui: displace_liqui,
  1211. ReplacementWay: replacement_way,
  1212. Anticoagulant: anticoagulant,
  1213. AnticoagulantShouji: anticoagulant_shouji,
  1214. AnticoagulantWeichi: anticoagulant_weichi,
  1215. AnticoagulantZongliang: anticoagulant_zongliang,
  1216. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  1217. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  1218. Kalium: kalium,
  1219. Sodium: sodium,
  1220. Calcium: calcium,
  1221. Bicarbonate: bicarbonate,
  1222. Glucose: glucose,
  1223. // DryWeight: dry_weight,
  1224. DialysateFlow: dialysate_flow,
  1225. DialysateTemperature: dialysate_temperature,
  1226. // PrescriptionDoctor: prescription_doctor,
  1227. ReplacementTotal: replacement_total,
  1228. Conductivity: conductivity,
  1229. Remark: remark,
  1230. Status: 1,
  1231. CreatedTime: time.Now().Unix(),
  1232. UpdatedTime: time.Now().Unix(),
  1233. DialysisDurationMinute: dialysisDurationMinute,
  1234. DialysisDurationHour: dialysisDurationHour,
  1235. TargetUltrafiltration: targetUltrafiltration,
  1236. DialysateFormulation: dialysateFormulation,
  1237. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  1238. BodyFluid: body_fluid,
  1239. SpecialMedicine: special_medicine,
  1240. SpecialMedicineOther: special_medicine_other,
  1241. DisplaceLiquiPart: displace_liqui_part,
  1242. DisplaceLiquiValue: displace_liqui_value,
  1243. BloodAccess: blood_access,
  1244. Ultrafiltration: ultrafiltration,
  1245. BodyFluidOther: body_fluid_other,
  1246. Niprocart: niprocart,
  1247. Jms: jms,
  1248. FistulaNeedleSet: fistula_needle_set,
  1249. FistulaNeedleSet16: fistula_needle_set_16,
  1250. Hemoperfusion: hemoperfusion,
  1251. DialyserSterilised: dialyser_sterilised,
  1252. Filtryzer: filtryzer,
  1253. Dialyzers: dialyzers,
  1254. Injector: injector,
  1255. Bloodlines: bloodlines,
  1256. TubingHemodialysis: tubing_hemodialysis,
  1257. Package: safe_package,
  1258. ALiquid: a_liquid,
  1259. TargetKtv: target_ktv,
  1260. PreImpulse: pre_impulse,
  1261. AnticoagulantStopTimeHour: anticoagulant_stop_time_hour,
  1262. AnticoagulantStopTimeMin: anticoagulant_stop_time_min,
  1263. Blood: blood,
  1264. DialysisDialyszers: dialysis_dialyszers,
  1265. DialysisIrrigation: dialysis_irrigation,
  1266. AntioxidantCommodityName: antioxidant_commodity_name,
  1267. DisplaceSpeed: displace_speed,
  1268. Illness: illness,
  1269. Amylaceum: amylaceum,
  1270. SingleTime: single_time,
  1271. SingleWater: single_water,
  1272. ReplacementFlow: replacement_flow,
  1273. PlasmaSeparator: plasma_separator,
  1274. BilirubinAdsorptionColumn: bilirubin_adsorption_column,
  1275. OxygenUptake: oxygen_uptake,
  1276. OxygenFlow: oxygen_flow,
  1277. OxygenTime: oxygen_time,
  1278. HemodialysisPipelines: hemodialysis_pipelines,
  1279. HemodialysisPipelinesCount: hemodialysis_pipelines_count,
  1280. PunctureNeedle: puncture_needle,
  1281. PunctureNeedleCount: puncture_needle_count,
  1282. Epo: epo,
  1283. EpoCount: epo_count,
  1284. MaxUltrafiltrationRate: max_ultrafiltration_rate,
  1285. }
  1286. //查询最近透析准备表里是否存在 透析器 灌流器
  1287. //
  1288. //splitStr := strings.Split(dialysis_dialyszers, ",")
  1289. //
  1290. //splitIrrigation := strings.Split(dialysis_irrigation, ",")
  1291. //
  1292. //mation, _ := service.GetGoodInfoMation(adminUserInfo.Org.Id)
  1293. //if len(mation)>0{
  1294. // for _, item := range splitStr {
  1295. // for _,it := range mation{
  1296. // if(item == it.SpecificationName){
  1297. //
  1298. // //查询最近一次的透析器
  1299. // _, errcode := service.GetDialysisBeforePrepare(it.GoodTypeId, it.ID, adminUserInfo.Org.Id,id)
  1300. //
  1301. // if errcode == gorm.ErrRecordNotFound{
  1302. // //插入数据
  1303. // prepare := models.DialysisBeforePrepare{
  1304. // UserOrgId: adminUserInfo.Org.Id,
  1305. // PatientId: id,
  1306. // RecordDate: recordDate.Unix(),
  1307. // GoodTypeId: it.GoodTypeId,
  1308. // GoodId: it.ID,
  1309. // Count: 1,
  1310. // Ctime: time.Now().Unix(),
  1311. // Creater: adminUserInfo.AdminUser.Id,
  1312. // Status:1,
  1313. //
  1314. // }
  1315. // errcode := service.CreateDialysisBeforePrepareOne(&prepare)
  1316. // fmt.Println("",errcode)
  1317. // }
  1318. // }
  1319. // }
  1320. //
  1321. // }
  1322. //
  1323. // for _, item := range splitIrrigation {
  1324. // for _,it := range mation{
  1325. // if(item == it.SpecificationName){
  1326. // //查询最近一次的透析器
  1327. // _, errcode := service.GetDialysisBeforePrepare(it.GoodTypeId, it.ID, adminUserInfo.Org.Id,id)
  1328. // if errcode == gorm.ErrRecordNotFound{
  1329. // //插入数据
  1330. // prepare := models.DialysisBeforePrepare{
  1331. // UserOrgId: adminUserInfo.Org.Id,
  1332. // PatientId: id,
  1333. // RecordDate: recordDate.Unix(),
  1334. // GoodTypeId: it.GoodTypeId,
  1335. // GoodId: it.ID,
  1336. // Count: 1,
  1337. // Ctime: time.Now().Unix(),
  1338. // Creater: adminUserInfo.AdminUser.Id,
  1339. // Status:1,
  1340. //
  1341. // }
  1342. // errcode := service.CreateDialysisBeforePrepareOne(&prepare)
  1343. // fmt.Println(errcode)
  1344. // }
  1345. // }
  1346. // }
  1347. // }
  1348. //}
  1349. _, dialysisPrescription := service.FindDialysisPrescriptionByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  1350. if dialysisPrescription.ID == 0 { //新增
  1351. if appRole.UserType == 2 || appRole.UserType == 1 {
  1352. prescription.PrescriptionDoctor = adminUserInfo.AdminUser.Id
  1353. }
  1354. prescription.Creater = adminUserInfo.AdminUser.Id
  1355. //针对河间咸得
  1356. if adminUserInfo.Org.Id == 10164 || adminUserInfo.Org.Id == 10090 || adminUserInfo.Org.Id == 3877 {
  1357. if prescription.ModeId != 2 && prescription.ModeId != 5 && prescription.ModeId != 12 {
  1358. prescription.DisplaceLiquiPart = 0
  1359. prescription.DisplaceLiquiValue = 0
  1360. }
  1361. }
  1362. err := service.AddSigleRecord(&prescription)
  1363. //获取key,清空redis
  1364. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":" + strconv.FormatInt(mode_id, 10) + ":dialysis_prescribe"
  1365. redis := service.RedisClient()
  1366. //清空key 值
  1367. redis.Set(key, "", time.Second)
  1368. keyOne := "scheduals_" + recordDateStr + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  1369. //清空key 值
  1370. redis.Set(keyOne, "", time.Second)
  1371. keyTwo := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(mode_id, 10) + ":dialysis_solution"
  1372. //清空key 值
  1373. redis.Set(keyTwo, "", time.Second)
  1374. keySix := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":prescriptions_list_all"
  1375. redis.Set(keySix, "", time.Second)
  1376. keySeven := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":dialysis_prescribe_by_mode"
  1377. redis.Set(keySeven, "", time.Second)
  1378. if err == nil {
  1379. updateErr := service.UpdateScheduleModeId(patient.ID, adminUserInfo.Org.Id, recordDate.Unix(), mode_id)
  1380. keyThree := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(mode_id, 10) + ":dialysis_prescribe_by_mode"
  1381. //清空key 值
  1382. redis.Set(keyThree, "", time.Second)
  1383. keyFour := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(mode_id, 10) + ":system_dialysis_prescribe"
  1384. //清空key 值
  1385. redis.Set(keyFour, "", time.Second)
  1386. keyFive := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":schedual_detail"
  1387. redis.Set(keyFive, "", time.Second)
  1388. keySix := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":prescriptions_list_all"
  1389. redis.Set(keySix, "", time.Second)
  1390. keySeven := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":dialysis_prescribe_by_mode"
  1391. redis.Set(keySeven, "", time.Second)
  1392. keyOne := "scheduals_" + recordDateStr + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  1393. //清空key 值
  1394. redis.Set(keyOne, "", time.Second)
  1395. if updateErr != nil {
  1396. utils.ErrorLog("%v", updateErr)
  1397. }
  1398. defer redis.Close()
  1399. c.ServeSuccessJSON(map[string]interface{}{
  1400. "prescription": prescription,
  1401. })
  1402. }
  1403. } else { //修改
  1404. //if mode_id > 0 {
  1405. // service.ModifyScheduleMode(mode_id, patient.ID, recordDate.Unix(), adminUserInfo.Org.Id)
  1406. //}
  1407. //if template.TemplateId == 1 {
  1408. // if dialysisPrescription.Creater != adminUserInfo.AdminUser.Id && dialysisPrescription.Creater != 0 {
  1409. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1410. // if getPermissionErr != nil {
  1411. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1412. // return
  1413. // } else if headNursePermission == nil {
  1414. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePrescriptionPermissionDeniedModify)
  1415. // return
  1416. // }
  1417. // }
  1418. //}
  1419. prescription.CreatedTime = dialysisPrescription.CreatedTime
  1420. prescription.Modifier = adminUserInfo.AdminUser.Id
  1421. if appRole.UserType == 2 || appRole.UserType == 1 {
  1422. prescription_doctor := adminUserInfo.AdminUser.Id
  1423. prescription.PrescriptionDoctor = prescription_doctor
  1424. } else {
  1425. prescription.PrescriptionDoctor = dialysisPrescription.PrescriptionDoctor
  1426. }
  1427. if dialysisPrescription.Creater == 0 { //体重称
  1428. prescription.Creater = adminUserInfo.AdminUser.Id
  1429. } else {
  1430. prescription.Creater = dialysisPrescription.Creater
  1431. }
  1432. prescription.ID = dialysisPrescription.ID
  1433. err := service.UpDateDialysisPrescription(&prescription)
  1434. //获取key,清空redis
  1435. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":" + strconv.FormatInt(mode_id, 10) + ":dialysis_prescribe"
  1436. redis := service.RedisClient()
  1437. //清空key 值
  1438. redis.Set(key, "", time.Second)
  1439. keyOne := "scheduals_" + recordDateStr + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  1440. //清空key 值
  1441. redis.Set(keyOne, "", time.Second)
  1442. keySix := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":prescriptions_list_all"
  1443. redis.Set(keySix, "", time.Second)
  1444. keySeven := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":dialysis_prescribe_by_mode"
  1445. redis.Set(keySeven, "", time.Second)
  1446. if err == nil {
  1447. updateErr := service.UpdateScheduleModeId(patient.ID, adminUserInfo.Org.Id, recordDate.Unix(), mode_id)
  1448. keyOne := "scheduals_" + recordDateStr + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  1449. //清空key 值
  1450. redis.Set(keyOne, "", time.Second)
  1451. defer redis.Close()
  1452. if updateErr != nil {
  1453. utils.ErrorLog("%v", updateErr)
  1454. }
  1455. c.ServeSuccessJSON(map[string]interface{}{
  1456. "prescription": prescription,
  1457. })
  1458. }
  1459. }
  1460. }
  1461. func (c *DialysisAPIController) Finish() {
  1462. id, _ := c.GetInt64("patient", 0)
  1463. recordDateStr := c.GetString("record_date")
  1464. nurseID, _ := c.GetInt64("nurse")
  1465. end_time := c.GetString("end_time")
  1466. puncture_point_haematoma, _ := c.GetInt64("puncture_point_haematoma")
  1467. internal_fistula := c.GetString("blood_access_internal_fistula")
  1468. catheter := c.GetString("catheter")
  1469. cruor := c.GetString("cruor")
  1470. if id <= 0 || nurseID <= 0 {
  1471. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1472. return
  1473. }
  1474. adminUserInfo := c.GetMobileAdminUserInfo()
  1475. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  1476. if patient.ID == 0 {
  1477. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1478. return
  1479. }
  1480. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  1481. if getNurseErr != nil {
  1482. c.ErrorLog("获取护士失败:%v", getNurseErr)
  1483. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1484. return
  1485. } else if nurse == nil {
  1486. c.ErrorLog("护士不存在")
  1487. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1488. return
  1489. }
  1490. if len(recordDateStr) == 0 {
  1491. recordDateStr = time.Now().Format("2006-01-02")
  1492. }
  1493. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1494. if parseDateErr != nil {
  1495. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  1496. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1497. return
  1498. }
  1499. endDate, parseEndDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", end_time)
  1500. if parseEndDateErr != nil {
  1501. c.ErrorLog("日期(%v)解析错误:%v", end_time, parseEndDateErr)
  1502. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1503. return
  1504. }
  1505. //now := time.Now()
  1506. //year, month, day := now.Date()
  1507. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  1508. //todayTimeStamp := today_time.Unix()
  1509. // 获取当天的第一条透析纪录
  1510. fmonitorRecords, getMonitorRecordsErr := service.MobileGetMonitorRecordFirst(adminUserInfo.Org.Id, id, recordDate.Unix())
  1511. if getMonitorRecordsErr != nil {
  1512. c.ErrorLog("获取透析监测记录失败:%v", getMonitorRecordsErr)
  1513. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1514. return
  1515. }
  1516. // 获取当前的最后一条透析纪录
  1517. endmonitorRecords, getMonitorRecordsErr := service.MobileGetLastMonitorRecordOne(adminUserInfo.Org.Id, id, recordDate.Unix())
  1518. if getMonitorRecordsErr != nil {
  1519. c.ErrorLog("获取透析监测记录失败:%v", getMonitorRecordsErr)
  1520. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1521. return
  1522. }
  1523. fmt.Println(endmonitorRecords.UltrafiltrationVolume)
  1524. assessmentAfterDislysis, getAADErr := service.MobileGetAssessmentAfterDislysisOne(adminUserInfo.Org.Id, id, recordDate.Unix())
  1525. if getAADErr != nil {
  1526. c.ErrorLog("获取透后评估失败:%v", getAADErr)
  1527. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1528. return
  1529. }
  1530. lastAssessmentAfterDislysis, _ := service.MobileGetLastTimeAssessmentAfterDislysisOne(adminUserInfo.Org.Id, id, recordDate.Unix())
  1531. _, dialysisOrder := service.FindDialysisRecordById(adminUserInfo.Org.Id, id, recordDate.Unix())
  1532. var tempassessmentAfterDislysis models.AssessmentAfterDislysis
  1533. if assessmentAfterDislysis != nil {
  1534. tempassessmentAfterDislysis = *assessmentAfterDislysis
  1535. tempassessmentAfterDislysis.UpdatedTime = time.Now().Unix()
  1536. } else {
  1537. tempassessmentAfterDislysis.CreatedTime = time.Now().Unix()
  1538. tempassessmentAfterDislysis.AssessmentDate = recordDate.Unix()
  1539. tempassessmentAfterDislysis.Status = 1
  1540. tempassessmentAfterDislysis.PatientId = id
  1541. tempassessmentAfterDislysis.UserOrgId = adminUserInfo.Org.Id
  1542. }
  1543. //长沙南雅
  1544. if adminUserInfo.Org.Id == 9671 || adminUserInfo.Org.Id == 9675 || adminUserInfo.Org.Id == 10340 {
  1545. //获取最后一条透析处方数据
  1546. prescription, _ := service.GetLastDialysisPrescriptionByPatientIdTwo(adminUserInfo.Org.Id, id, recordDate.Unix())
  1547. evaluation, _ := service.MobileGetPredialysisEvaluationTwo(adminUserInfo.Org.Id, id, recordDate.Unix())
  1548. tempassessmentAfterDislysis.WeightAfter = evaluation.WeightBefore - prescription.TargetUltrafiltration
  1549. }
  1550. if dialysisOrder.Stage == 1 {
  1551. temp_time := (float64(endDate.Unix()) - float64(dialysisOrder.StartTime)) / 3600
  1552. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  1553. fmt.Println(value)
  1554. a, b := math.Modf(value)
  1555. c, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  1556. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  1557. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", c*60), 10, 64)
  1558. tempassessmentAfterDislysis.ActualTreatmentHour = hour
  1559. tempassessmentAfterDislysis.ActualTreatmentMinute = minute
  1560. }
  1561. if fmonitorRecords.ID > 0 && endmonitorRecords.ID > 0 {
  1562. //var num1 int64
  1563. //num1 = endmonitorRecords.OperateTime - fmonitorRecords.OperateTime
  1564. //fmt.Println(num1)
  1565. //sub := float64(num1 / 3600)
  1566. //fmt.Println(sub)
  1567. //tempassessmentAfterDislysis.ActualTreatmentHour = int64(math.Floor(sub))
  1568. //sub2 := float64(((endmonitorRecords.OperateTime - fmonitorRecords.OperateTime) % 3600) / 60)
  1569. //tempassessmentAfterDislysis.ActualTreatmentMinute = int64(math.Floor(sub2))
  1570. tempassessmentAfterDislysis.Temperature = endmonitorRecords.Temperature
  1571. tempassessmentAfterDislysis.PulseFrequency = endmonitorRecords.PulseFrequency
  1572. tempassessmentAfterDislysis.BreathingRate = endmonitorRecords.BreathingRate
  1573. tempassessmentAfterDislysis.SystolicBloodPressure = endmonitorRecords.SystolicBloodPressure
  1574. tempassessmentAfterDislysis.DiastolicBloodPressure = endmonitorRecords.DiastolicBloodPressure
  1575. tempassessmentAfterDislysis.ActualUltrafiltration = endmonitorRecords.UltrafiltrationVolume
  1576. tempassessmentAfterDislysis.ActualDisplacement = endmonitorRecords.DisplacementQuantity
  1577. }
  1578. if adminUserInfo.Org.Id == 10101 || adminUserInfo.Org.Id == 9671 || adminUserInfo.Org.Id == 3877 || adminUserInfo.Org.Id == 9675 || adminUserInfo.Org.Id == 10215 || adminUserInfo.Org.Id == 10233 || adminUserInfo.Org.Id == 10223 || adminUserInfo.Org.Id == 10243 || adminUserInfo.Org.Id == 10340 {
  1579. evaluation, _ := service.MobileGetPredialysisEvaluationOne(adminUserInfo.Org.Id, id, recordDate.Unix())
  1580. if evaluation.SystolicBloodPressure == 0 {
  1581. evaluation.SystolicBloodPressure = fmonitorRecords.SystolicBloodPressure
  1582. pre := models.PredialysisEvaluation{
  1583. SystolicBloodPressure: evaluation.SystolicBloodPressure,
  1584. }
  1585. fmt.Println("prew", pre)
  1586. getNurseErr := service.UpdatePredialysisEvaluation(&pre, evaluation.ID)
  1587. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_before_dislysis"
  1588. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_befores_list_all"
  1589. redis := service.RedisClient()
  1590. redis.Set(key, "", time.Second)
  1591. redis.Set(keyOne, "", time.Second)
  1592. defer redis.Close()
  1593. fmt.Println(getNurseErr)
  1594. }
  1595. if evaluation.DiastolicBloodPressure == 0 {
  1596. evaluation.DiastolicBloodPressure = fmonitorRecords.DiastolicBloodPressure
  1597. pres := models.PredialysisEvaluation{
  1598. DiastolicBloodPressure: evaluation.DiastolicBloodPressure,
  1599. }
  1600. getNurseErr := service.UpdatePredialysisEvaluationTwo(&pres, evaluation.ID)
  1601. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_before_dislysis"
  1602. redis := service.RedisClient()
  1603. redis.Set(key, "", time.Second)
  1604. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_befores_list_all"
  1605. redis.Set(keyOne, "", time.Second)
  1606. defer redis.Close()
  1607. fmt.Println(getNurseErr)
  1608. }
  1609. if evaluation.PulseFrequency == 0 {
  1610. evaluation.PulseFrequency = fmonitorRecords.PulseFrequency
  1611. press := models.PredialysisEvaluation{
  1612. PulseFrequency: evaluation.PulseFrequency,
  1613. }
  1614. getNurseErr := service.UpdatePredialysisEvaluationThree(&press, evaluation.ID)
  1615. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_before_dislysis"
  1616. redis := service.RedisClient()
  1617. redis.Set(key, "", time.Second)
  1618. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_befores_list_all"
  1619. redis.Set(keyOne, "", time.Second)
  1620. defer redis.Close()
  1621. fmt.Println(getNurseErr)
  1622. }
  1623. if evaluation.Temperature == 0 {
  1624. evaluation.Temperature = fmonitorRecords.Temperature
  1625. press := models.PredialysisEvaluation{
  1626. Temperature: evaluation.Temperature,
  1627. }
  1628. getNurseErr := service.UpdatePredialysisEvaluationFour(&press, evaluation.ID)
  1629. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_before_dislysis"
  1630. redis := service.RedisClient()
  1631. redis.Set(key, "", time.Second)
  1632. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_befores_list_all"
  1633. redis.Set(keyOne, "", time.Second)
  1634. defer redis.Close()
  1635. fmt.Println(getNurseErr)
  1636. }
  1637. }
  1638. if adminUserInfo.Org.Id == 9583 {
  1639. //获取透析处方的最后一条数据
  1640. diaPrescription, diaerr := service.GetLastDialysisPrescriptionByPatientId(adminUserInfo.Org.Id, id, recordDate.Unix())
  1641. if diaerr != nil {
  1642. c.ErrorLog("获取透析处方失败:%v", diaerr)
  1643. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1644. return
  1645. }
  1646. if diaPrescription.ID > 0 && adminUserInfo.Org.Id == 9583 {
  1647. tempassessmentAfterDislysis.ActualUltrafiltration = diaPrescription.TargetUltrafiltration
  1648. }
  1649. }
  1650. if endmonitorRecords.ID > 0 && adminUserInfo.Org.Id == 10101 {
  1651. tempassessmentAfterDislysis.ActualUltrafiltration = endmonitorRecords.UltrafiltrationVolume / 1000
  1652. }
  1653. if endmonitorRecords.ID > 0 && adminUserInfo.Org.Id == 10233 {
  1654. tempassessmentAfterDislysis.ActualUltrafiltration = endmonitorRecords.UltrafiltrationVolume / 1000
  1655. }
  1656. if endmonitorRecords.ID > 0 && adminUserInfo.Org.Id == 10060 {
  1657. tempassessmentAfterDislysis.ActualUltrafiltration = endmonitorRecords.UltrafiltrationVolume
  1658. }
  1659. if lastAssessmentAfterDislysis != nil {
  1660. tempassessmentAfterDislysis.BloodPressureType = lastAssessmentAfterDislysis.BloodPressureType
  1661. tempassessmentAfterDislysis.WeighingWay = lastAssessmentAfterDislysis.WeighingWay
  1662. tempassessmentAfterDislysis.Cruor = lastAssessmentAfterDislysis.Cruor
  1663. tempassessmentAfterDislysis.SymptomAfterDialysis = lastAssessmentAfterDislysis.SymptomAfterDialysis
  1664. tempassessmentAfterDislysis.InternalFistula = lastAssessmentAfterDislysis.InternalFistula
  1665. tempassessmentAfterDislysis.Catheter = lastAssessmentAfterDislysis.Catheter
  1666. tempassessmentAfterDislysis.Complication = lastAssessmentAfterDislysis.Complication
  1667. tempassessmentAfterDislysis.DialysisIntakes = lastAssessmentAfterDislysis.DialysisIntakes
  1668. tempassessmentAfterDislysis.DialysisIntakesFeed = lastAssessmentAfterDislysis.DialysisIntakesFeed
  1669. tempassessmentAfterDislysis.DialysisIntakesTransfusion = lastAssessmentAfterDislysis.DialysisIntakesTransfusion
  1670. tempassessmentAfterDislysis.DialysisIntakesBloodTransfusion = lastAssessmentAfterDislysis.DialysisIntakesBloodTransfusion
  1671. tempassessmentAfterDislysis.DialysisIntakesWashpipe = lastAssessmentAfterDislysis.DialysisIntakesWashpipe
  1672. tempassessmentAfterDislysis.BloodAccessPartId = lastAssessmentAfterDislysis.BloodAccessPartId
  1673. tempassessmentAfterDislysis.BloodAccessPartOperaId = lastAssessmentAfterDislysis.BloodAccessPartOperaId
  1674. tempassessmentAfterDislysis.PuncturePointOozingBlood = lastAssessmentAfterDislysis.PuncturePointOozingBlood
  1675. tempassessmentAfterDislysis.PuncturePointHaematoma = lastAssessmentAfterDislysis.PuncturePointHaematoma
  1676. tempassessmentAfterDislysis.InternalFistulaTremorAc = lastAssessmentAfterDislysis.InternalFistulaTremorAc
  1677. tempassessmentAfterDislysis.PatientGose = lastAssessmentAfterDislysis.PatientGose
  1678. tempassessmentAfterDislysis.InpatientDepartment = lastAssessmentAfterDislysis.InpatientDepartment
  1679. tempassessmentAfterDislysis.ObservationContent = lastAssessmentAfterDislysis.ObservationContent
  1680. tempassessmentAfterDislysis.ObservationContentOther = lastAssessmentAfterDislysis.ObservationContentOther
  1681. tempassessmentAfterDislysis.DryWeight = lastAssessmentAfterDislysis.DryWeight
  1682. tempassessmentAfterDislysis.DialysisProcess = lastAssessmentAfterDislysis.DialysisProcess
  1683. tempassessmentAfterDislysis.InAdvanceMinute = lastAssessmentAfterDislysis.InAdvanceMinute
  1684. tempassessmentAfterDislysis.InAdvanceReason = lastAssessmentAfterDislysis.InAdvanceReason
  1685. tempassessmentAfterDislysis.HemostasisMinute = lastAssessmentAfterDislysis.HemostasisMinute
  1686. tempassessmentAfterDislysis.HemostasisOpera = lastAssessmentAfterDislysis.HemostasisOpera
  1687. tempassessmentAfterDislysis.TremorNoise = lastAssessmentAfterDislysis.TremorNoise
  1688. tempassessmentAfterDislysis.DisequilibriumSyndrome = lastAssessmentAfterDislysis.DisequilibriumSyndrome
  1689. tempassessmentAfterDislysis.DisequilibriumSyndromeOption = lastAssessmentAfterDislysis.DisequilibriumSyndromeOption
  1690. tempassessmentAfterDislysis.ArterialTube = lastAssessmentAfterDislysis.ArterialTube
  1691. tempassessmentAfterDislysis.IntravenousTube = lastAssessmentAfterDislysis.IntravenousTube
  1692. tempassessmentAfterDislysis.Dialyzer = lastAssessmentAfterDislysis.Dialyzer
  1693. tempassessmentAfterDislysis.InAdvanceReasonOther = lastAssessmentAfterDislysis.InAdvanceReasonOther
  1694. tempassessmentAfterDislysis.IsEat = lastAssessmentAfterDislysis.IsEat
  1695. tempassessmentAfterDislysis.DialysisIntakesUnit = lastAssessmentAfterDislysis.DialysisIntakesUnit
  1696. tempassessmentAfterDislysis.CvcA = lastAssessmentAfterDislysis.CvcA
  1697. tempassessmentAfterDislysis.CvcV = lastAssessmentAfterDislysis.CvcV
  1698. tempassessmentAfterDislysis.Channel = lastAssessmentAfterDislysis.Channel
  1699. tempassessmentAfterDislysis.ReturnBlood = lastAssessmentAfterDislysis.ReturnBlood
  1700. tempassessmentAfterDislysis.RehydrationVolume = lastAssessmentAfterDislysis.RehydrationVolume
  1701. tempassessmentAfterDislysis.DialysisDuring = lastAssessmentAfterDislysis.DialysisDuring
  1702. tempassessmentAfterDislysis.StrokeVolume = lastAssessmentAfterDislysis.StrokeVolume
  1703. tempassessmentAfterDislysis.BloodFlow = lastAssessmentAfterDislysis.BloodFlow
  1704. tempassessmentAfterDislysis.SealingFluidDispose = lastAssessmentAfterDislysis.SealingFluidDispose
  1705. tempassessmentAfterDislysis.SealingFluidSpecial = lastAssessmentAfterDislysis.SealingFluidSpecial
  1706. }
  1707. err := service.UpdateAssessmentAfterDislysisRecord(&tempassessmentAfterDislysis)
  1708. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_after_dislysis"
  1709. redis := service.RedisClient()
  1710. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_after_dislysis_list_all"
  1711. redis.Set(keyOne, "", time.Second)
  1712. keyTwo := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_after_dislysis_last"
  1713. redis.Set(keyTwo, "", time.Second)
  1714. defer redis.Close()
  1715. //清空key 值
  1716. redis.Set(key, "", time.Second)
  1717. if err != nil {
  1718. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1719. return
  1720. }
  1721. if dialysisOrder == nil {
  1722. c.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderNoStart)
  1723. return
  1724. }
  1725. if dialysisOrder.Stage == 2 {
  1726. c.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderNoEND)
  1727. return
  1728. }
  1729. if dialysisOrder.Stage == 1 {
  1730. err := service.ModifyDialysisRecord(dialysisOrder.ID, nurseID, endDate.Unix(), adminUserInfo.AdminUser.Id, puncture_point_haematoma, internal_fistula, catheter, cruor)
  1731. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":dialysis_order"
  1732. redis := service.RedisClient()
  1733. defer redis.Close()
  1734. //清空key 值
  1735. redis.Set(key, "", time.Second)
  1736. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":dialysis_orders_list_all"
  1737. redis.Set(keyOne, "", time.Second)
  1738. //结束时候透析次数加1
  1739. service.UpdateSolutionByPatientId(id)
  1740. dialysisOrder.Stage = 2
  1741. dialysisOrder.FinishNurse = nurseID
  1742. dialysisOrder.FinishCreator = adminUserInfo.AdminUser.Id
  1743. dialysisOrder.FinishModifier = adminUserInfo.AdminUser.Id
  1744. dialysisOrder.EndTime = endDate.Unix()
  1745. go func() {
  1746. ssoDomain := beego.AppConfig.String("call_domain")
  1747. api := ssoDomain + "/index/downpatient"
  1748. values := make(url.Values)
  1749. values.Set("org_id", strconv.FormatInt(adminUserInfo.AdminUser.Id, 10))
  1750. values.Set("admin_user_id", strconv.FormatInt(nurseID, 10))
  1751. values.Set("patient_id", strconv.FormatInt(id, 10))
  1752. http.PostForm(api, values)
  1753. }()
  1754. if err == nil {
  1755. c.ServeSuccessJSON(map[string]interface{}{
  1756. "dialysisOrder": dialysisOrder,
  1757. "assessmentAfterDislysis": tempassessmentAfterDislysis,
  1758. })
  1759. } else {
  1760. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  1761. }
  1762. }
  1763. }
  1764. func (c *DialysisAPIController) GetAllZone() {
  1765. adminUserInfo := c.GetMobileAdminUserInfo()
  1766. err, zone := service.GetAllDeviceZone(adminUserInfo.Org.Id)
  1767. if err == nil {
  1768. c.ServeSuccessJSON(map[string]interface{}{
  1769. "zone": zone,
  1770. })
  1771. }
  1772. }
  1773. func (c *DialysisAPIController) GetSchedualPatientsList() {
  1774. adminUserInfo := c.GetMobileAdminUserInfo()
  1775. page, _ := c.GetInt64("page", 1)
  1776. limit, _ := c.GetInt64("limit", 10)
  1777. schedulType, _ := c.GetInt64("schedul_type", 0)
  1778. startTime, _ := c.GetInt64("schedul_time", 0)
  1779. partitionType, _ := c.GetInt64("partition_type", 0)
  1780. keywords := c.GetString("keywords")
  1781. dialysisSchedule, err := service.GetSchedualPatientList(adminUserInfo.Org.Id, startTime/1000, schedulType, partitionType, keywords, page, limit)
  1782. if err == nil {
  1783. c.ServeSuccessJSON(map[string]interface{}{
  1784. "schedule": dialysisSchedule,
  1785. })
  1786. }
  1787. return
  1788. }
  1789. // /m/api/dialysis/start [post]
  1790. // @param patient_id:int
  1791. // @param record_date:string 排班时间 (yyyy-mm-dd)
  1792. // @param nurse:int 上机护士
  1793. // @param bed:int 床位号
  1794. func (this *DialysisAPIController) StartDialysis() {
  1795. patientID, _ := this.GetInt64("patient_id")
  1796. recordDateStr := this.GetString("record_date")
  1797. nurseID, _ := this.GetInt64("nurse")
  1798. puncture_nurse, _ := this.GetInt64("puncture_nurse")
  1799. blood_drawing, _ := this.GetInt64("blood_drawing")
  1800. schedual_type, _ := this.GetInt64("schedual_type")
  1801. bedID, _ := this.GetInt64("bed")
  1802. start_time := this.GetString("start_time")
  1803. washpipe_nurse, _ := this.GetInt64("washpipe_nurse")
  1804. change_nurse, _ := this.GetInt64("change_nurse")
  1805. difficult_puncture_nurse, _ := this.GetInt64("difficult_puncture_nurse")
  1806. new_fistula_nurse, _ := this.GetInt64("new_fistula_nurse")
  1807. zone_id, _ := this.GetInt64("zone_id")
  1808. if patientID <= 0 || len(recordDateStr) == 0 || nurseID <= 0 || bedID <= 0 {
  1809. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1810. return
  1811. }
  1812. startDate, parseStartDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", start_time)
  1813. if parseStartDateErr != nil {
  1814. this.ErrorLog("时间解析失败:%v", parseStartDateErr)
  1815. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1816. return
  1817. }
  1818. recordDate, parseErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1819. if parseErr != nil {
  1820. this.ErrorLog("时间解析失败:%v", parseErr)
  1821. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1822. return
  1823. }
  1824. adminUserInfo := this.GetMobileAdminUserInfo()
  1825. patient, getPatientErr := service.MobileGetPatientById(adminUserInfo.Org.Id, patientID)
  1826. if getPatientErr != nil {
  1827. this.ErrorLog("获取患者信息失败:%v", getPatientErr)
  1828. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1829. return
  1830. } else if patient == nil {
  1831. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1832. return
  1833. }
  1834. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  1835. if getNurseErr != nil {
  1836. this.ErrorLog("获取护士失败:%v", getNurseErr)
  1837. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1838. return
  1839. } else if nurse == nil {
  1840. this.ErrorLog("护士不存在")
  1841. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1842. return
  1843. }
  1844. nurse, getNurseErr = service.GetAdminUserByUserID(puncture_nurse)
  1845. deviceNumber, getDeviceNumberErr := service.GetDeviceNumberByID(adminUserInfo.Org.Id, bedID)
  1846. if getDeviceNumberErr != nil {
  1847. this.ErrorLog("获取床位号失败:%v", getDeviceNumberErr)
  1848. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1849. return
  1850. } else if deviceNumber == nil {
  1851. this.ErrorLog("床位号不存在")
  1852. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1853. return
  1854. }
  1855. dialysisRecord, getRecordErr := service.MobileGetDialysisRecord(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  1856. if getRecordErr != nil {
  1857. this.ErrorLog("获取透析记录失败:%v", getRecordErr)
  1858. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1859. return
  1860. } else if dialysisRecord != nil {
  1861. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatStart)
  1862. return
  1863. }
  1864. scheduleDateStart := startDate.Format("2006-01-02") + " 00:00:00"
  1865. scheduleDateEnd := startDate.Format("2006-01-02") + " 23:59:59"
  1866. timeLayout := "2006-01-02 15:04:05"
  1867. loc, _ := time.LoadLocation("Local")
  1868. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  1869. theEndTime, _ := time.ParseInLocation(timeLayout, scheduleDateEnd, loc)
  1870. schedulestartTime := theStartTime.Unix()
  1871. scheduleendTime := theEndTime.Unix()
  1872. template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  1873. //查询更改的机号,是否有人用了,如果只是排班了,但是没上机,直接替换,如果排班且上机了,就提示他无法上机
  1874. schedule, err := service.GetDayScheduleByBedid(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  1875. //查询该床位是否有人用了
  1876. order, order_err := service.GetDialysisOrderByBedId(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  1877. if err == gorm.ErrRecordNotFound { //空床位
  1878. // 修改了床位逻辑
  1879. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1880. if daySchedule.ID > 0 {
  1881. daySchedule.PartitionId = deviceNumber.ZoneID
  1882. daySchedule.BedId = bedID
  1883. daySchedule.ScheduleType = schedual_type
  1884. daySchedule.UpdatedTime = time.Now().Unix()
  1885. xtSchedule := models.Schedule{
  1886. PartitionId: deviceNumber.ZoneID,
  1887. BedId: bedID,
  1888. ScheduleType: schedual_type,
  1889. UpdatedTime: time.Now().Unix(),
  1890. }
  1891. err := service.UpdateScheduleOne(daySchedule.ID, xtSchedule)
  1892. if err != nil {
  1893. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1894. return
  1895. }
  1896. }
  1897. } else if err == nil {
  1898. if schedule.ID > 0 && schedule.DialysisOrder.ID == 0 { //有排班没上机记录
  1899. if order_err == nil {
  1900. if order.ID > 0 { //该机位被其他人占用了
  1901. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  1902. return
  1903. } else {
  1904. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1905. if daySchedule.ID > 0 {
  1906. //daySchedule.PartitionId = deviceNumber.ZoneID
  1907. //daySchedule.BedId = bedID
  1908. //daySchedule.ScheduleType = schedual_type
  1909. //daySchedule.UpdatedTime = time.Now().Unix()
  1910. //err := service.UpdateSchedule(&daySchedule)
  1911. xtSchedule := models.Schedule{
  1912. PartitionId: deviceNumber.ZoneID,
  1913. BedId: bedID,
  1914. ScheduleType: schedual_type,
  1915. UpdatedTime: time.Now().Unix(),
  1916. }
  1917. err := service.UpdateScheduleOne(daySchedule.ID, xtSchedule)
  1918. if err != nil {
  1919. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1920. return
  1921. }
  1922. }
  1923. }
  1924. } else if order_err == gorm.ErrRecordNotFound { //该床位没被占用
  1925. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1926. if daySchedule.ID > 0 {
  1927. //daySchedule.PartitionId = deviceNumber.ZoneID
  1928. //daySchedule.BedId = bedID
  1929. //daySchedule.ScheduleType = schedual_type
  1930. //daySchedule.UpdatedTime = time.Now().Unix()
  1931. //err := service.UpdateSchedule(&daySchedule)
  1932. xtSchedule := models.Schedule{
  1933. PartitionId: deviceNumber.ZoneID,
  1934. BedId: bedID,
  1935. ScheduleType: schedual_type,
  1936. UpdatedTime: time.Now().Unix(),
  1937. }
  1938. err := service.UpdateScheduleOne(daySchedule.ID, xtSchedule)
  1939. if err != nil {
  1940. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1941. return
  1942. }
  1943. }
  1944. }
  1945. } else if schedule.ID > 0 && schedule.DialysisOrder.ID > 0 { //有排班且有上机记录
  1946. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  1947. return
  1948. }
  1949. } else if err != nil {
  1950. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1951. return
  1952. }
  1953. dialysisRecord = &models.DialysisOrder{
  1954. DialysisDate: recordDate.Unix(),
  1955. UserOrgId: adminUserInfo.Org.Id,
  1956. PatientId: patientID,
  1957. Stage: 1,
  1958. BedID: bedID,
  1959. StartNurse: nurseID,
  1960. Status: 1,
  1961. StartTime: startDate.Unix(),
  1962. CreatedTime: time.Now().Unix(),
  1963. UpdatedTime: time.Now().Unix(),
  1964. PunctureNurse: puncture_nurse,
  1965. Creator: adminUserInfo.AdminUser.Id,
  1966. Modifier: adminUserInfo.AdminUser.Id,
  1967. SchedualType: schedual_type,
  1968. WashpipeNurse: washpipe_nurse,
  1969. ChangeNurse: change_nurse,
  1970. DifficultPunctureNurse: difficult_puncture_nurse,
  1971. NewFistulaNurse: new_fistula_nurse,
  1972. ZoneId: zone_id,
  1973. }
  1974. //查询该床位是否有人用了
  1975. _, errorscode := service.GetDialysisOrderByBedId(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  1976. if errorscode == gorm.ErrRecordNotFound {
  1977. createErr := service.MobileCreateDialysisOrder(adminUserInfo.Org.Id, patientID, dialysisRecord)
  1978. redis := service.RedisClient()
  1979. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patientID, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":dialysis_order"
  1980. redis.Set(key, "", time.Second)
  1981. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":dialysis_orders_list_all"
  1982. //清空key 值
  1983. redis.Set(keyOne, "", time.Second)
  1984. keyTwo := "scheduals_" + recordDateStr + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  1985. //清空key 值
  1986. redis.Set(keyTwo, "", time.Second)
  1987. if createErr != nil {
  1988. this.ErrorLog("上机失败:%v", createErr)
  1989. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1990. return
  1991. }
  1992. }
  1993. newdialysisRecord, getRecordErr := service.MobileGetDialysisRecord(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  1994. var tempdispose string
  1995. // 只针对中能建
  1996. if blood_drawing > 0 && adminUserInfo.Org.Id == 9538 {
  1997. tempdispose = "引血" + strconv.FormatInt(blood_drawing, 10) + "ml/min"
  1998. }
  1999. if blood_drawing > 0 && adminUserInfo.Org.Id == 10318 {
  2000. tempdispose = "引血" + strconv.FormatInt(blood_drawing, 10) + "ml/min"
  2001. }
  2002. var ultrafiltration_rate float64
  2003. _, prescription := service.FindDialysisPrescriptionByReordDate(patientID, schedulestartTime, adminUserInfo.Org.Id)
  2004. //后期预增脱水量
  2005. _, evaluation := service.FindPredialysisEvaluationByReordDate(patientID, schedulestartTime, adminUserInfo.Org.Id)
  2006. if prescription.ID > 0 {
  2007. if prescription.TargetUltrafiltration > 0 && prescription.DialysisDurationHour > 0 {
  2008. totalMin := prescription.DialysisDurationHour*60 + prescription.DialysisDurationMinute
  2009. if (template.TemplateId == 6 || template.TemplateId == 32) && adminUserInfo.Org.Id != 9671 { //adminUserInfo.Org.Id == 9538
  2010. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1000)
  2011. }
  2012. //针对医师汇
  2013. if adminUserInfo.Org.Id == 10121 {
  2014. dehydration, _ := strconv.ParseFloat(evaluation.Dehydration, 64)
  2015. ultrafiltration_rate = math.Floor((prescription.TargetUltrafiltration + dehydration) / float64(totalMin) * 60 * 1000)
  2016. }
  2017. //针对通道
  2018. if adminUserInfo.Org.Id == 10234 {
  2019. ultrafiltration_rate = math.Floor((prescription.TargetUltrafiltration) / float64(totalMin) * 60 * 1000)
  2020. }
  2021. //针对监利大垸医院
  2022. if template.TemplateId == 41 {
  2023. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / float64(totalMin) * 1000)
  2024. }
  2025. //针对肇庆三鹤血液透析中心
  2026. if template.TemplateId == 43 {
  2027. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / float64(totalMin))
  2028. }
  2029. if template.TemplateId == 20 || template.TemplateId == 22 { //adminUserInfo.Org.Id == 9538
  2030. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60)
  2031. }
  2032. // 只针对方济医院
  2033. if template.TemplateId == 1 && adminUserInfo.Org.Id != 9849 {
  2034. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", prescription.TargetUltrafiltration/float64(totalMin)*60), 6)
  2035. ultrafiltration_rate = value
  2036. }
  2037. }
  2038. }
  2039. record := models.MonitoringRecord{
  2040. UserOrgId: adminUserInfo.Org.Id,
  2041. PatientId: patientID,
  2042. DialysisOrderId: dialysisRecord.ID,
  2043. MonitoringDate: schedulestartTime,
  2044. OperateTime: startDate.Unix(),
  2045. // MonitoringTime: recordTime,
  2046. MonitoringNurse: nurseID,
  2047. Dispose: tempdispose,
  2048. UltrafiltrationRate: ultrafiltration_rate,
  2049. UltrafiltrationVolume: 0,
  2050. Status: 1,
  2051. CreatedTime: time.Now().Unix(),
  2052. UpdatedTime: time.Now().Unix(),
  2053. }
  2054. //只针对广慈医院
  2055. if template.TemplateId == 26 || template.TemplateId == 25 || template.TemplateId == 28 || adminUserInfo.Org.Id == 9987 || adminUserInfo.Org.Id == 9526 || template.TemplateId == 32 || adminUserInfo.Org.Id == 9918 || adminUserInfo.Org.Id == 9671 || adminUserInfo.Org.Id == 3877 || adminUserInfo.Org.Id == 4 {
  2056. // 查询病人是否有透前评估数据
  2057. befor, errcode := service.GetAssessmentBefor(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  2058. //如果有数据就插入
  2059. if errcode == nil {
  2060. record.SystolicBloodPressure = befor.SystolicBloodPressure
  2061. record.DiastolicBloodPressure = befor.DiastolicBloodPressure
  2062. record.BreathingRate = befor.BreathingRate
  2063. record.PulseFrequency = befor.PulseFrequency
  2064. record.Temperature = befor.Temperature
  2065. }
  2066. }
  2067. // 如果当天有插入数据,则不再往透析纪录里插入数据
  2068. if newdialysisRecord.ID > 0 {
  2069. err := service.CreateMonitor(&record)
  2070. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patientID, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":monitor_records"
  2071. redis := service.RedisClient()
  2072. //清空key 值
  2073. redis.Set(key, "", time.Second)
  2074. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":monitor_record_list_all"
  2075. redis.Set(keyOne, "", time.Second)
  2076. defer redis.Close()
  2077. if err != nil {
  2078. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeMonitorCreate)
  2079. return
  2080. }
  2081. }
  2082. go func() {
  2083. ssoDomain := beego.AppConfig.String("call_domain")
  2084. api := ssoDomain + "/index/uppatient"
  2085. values := make(url.Values)
  2086. values.Set("org_id", strconv.FormatInt(adminUserInfo.Org.Id, 10))
  2087. values.Set("admin_user_id", strconv.FormatInt(nurseID, 10))
  2088. values.Set("patient_id", strconv.FormatInt(patientID, 10))
  2089. values.Set("up_time", strconv.FormatInt(startDate.Unix(), 10))
  2090. http.PostForm(api, values)
  2091. }()
  2092. this.ServeSuccessJSON(map[string]interface{}{
  2093. "dialysis_order": newdialysisRecord,
  2094. "monitor": record,
  2095. })
  2096. return
  2097. }
  2098. func (c *DialysisAPIController) PostSolution() {
  2099. id, _ := c.GetInt64("patient", 0)
  2100. recordDateStr := c.GetString("record_date")
  2101. if id <= 0 {
  2102. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2103. return
  2104. }
  2105. adminUserInfo := c.GetMobileAdminUserInfo()
  2106. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  2107. if patient.ID == 0 {
  2108. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  2109. return
  2110. }
  2111. if len(recordDateStr) == 0 {
  2112. recordDateStr = time.Now().Format("2006-01-02")
  2113. }
  2114. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  2115. if parseDateErr != nil {
  2116. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  2117. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2118. return
  2119. }
  2120. mode_id, _ := c.GetInt64("mode_id", 0)
  2121. dialysis_duration, _ := c.GetFloat("dialysis_duration", 0)
  2122. dialyzer, _ := c.GetInt64("dialyzer", 0)
  2123. perfusion_apparatus, _ := c.GetInt64("perfusion_apparatus", 0)
  2124. blood_flow_volume, _ := c.GetFloat("blood_flow_volume", 0)
  2125. dewater_amount, _ := c.GetFloat("dewater_amount", 0)
  2126. displace_liqui, _ := c.GetFloat("displace_liqui", 0)
  2127. replacement_way, _ := c.GetInt64("replacement_way", 0)
  2128. anticoagulant, _ := c.GetInt64("anticoagulant", 0)
  2129. anticoagulant_shouji, _ := c.GetFloat("anticoagulant_shouji", 0)
  2130. anticoagulant_weichi, _ := c.GetFloat("anticoagulant_weichi", 0)
  2131. anticoagulant_zongliang, _ := c.GetFloat("anticoagulant_zongliang", 0)
  2132. anticoagulant_gaimingcheng := c.GetString("anticoagulant_gaimingcheng")
  2133. anticoagulant_gaijiliang := c.GetString("anticoagulant_gaijiliang")
  2134. kalium, _ := c.GetFloat("kalium", 0)
  2135. sodium, _ := c.GetFloat("sodium", 0)
  2136. calcium, _ := c.GetFloat("calcium", 0)
  2137. bicarbonate, _ := c.GetFloat("bicarbonate", 0)
  2138. prescription_doctor, _ := c.GetInt64("prescription_doctor", 0)
  2139. dialyzerPerfusionApparatus := c.GetString("dialyzer_perfusion_apparatus")
  2140. glucose, _ := c.GetFloat("glucose", 0)
  2141. // dry_weight, _ := c.GetFloat("dry_weight", 0)
  2142. dialysate_flow, _ := c.GetFloat("dialysate_flow", 0)
  2143. dialysate_temperature, _ := c.GetFloat("dialysate_temperature", 0)
  2144. conductivity, _ := c.GetFloat("conductivity", 0)
  2145. remark := c.GetString("remark")
  2146. dialysisDurationHour, _ := c.GetInt64("dialysis_duration_hour", 0)
  2147. dialysisDurationMinute, _ := c.GetInt64("dialysis_duration_minute", 0)
  2148. targetUltrafiltration, _ := c.GetFloat("target_ultrafiltration", 0)
  2149. dialysateFormulation, _ := c.GetInt64("dialysate_formulation", 0)
  2150. body_fluid, _ := c.GetInt64("body_fluid", 0)
  2151. special_medicine, _ := c.GetInt64("special_medicine", 0)
  2152. special_medicine_other := c.GetString("special_medicine_other")
  2153. displace_liqui_part, _ := c.GetInt64("displace_liqui_part", 0)
  2154. displace_liqui_value, _ := c.GetFloat("displace_liqui_value", 0)
  2155. blood_access, _ := c.GetInt64("blood_access", 0)
  2156. ultrafiltration, _ := c.GetFloat("ultrafiltration", 0)
  2157. body_fluid_other := c.GetString("body_fluid_other")
  2158. replacement_total, _ := c.GetFloat("replacement_total", 0)
  2159. niprocart, _ := c.GetInt64("niprocart", 0)
  2160. jms, _ := c.GetInt64("jms", 0)
  2161. fistula_needle_set, _ := c.GetInt64("fistula_needle_set", 0)
  2162. fistula_needle_set_16, _ := c.GetInt64("fistula_needle_set_16", 0)
  2163. hemoperfusion, _ := c.GetInt64("hemoperfusion", 0)
  2164. dialyser_sterilised, _ := c.GetInt64("dialyser_sterilised", 0)
  2165. filtryzer, _ := c.GetInt64("filtryzer", 0)
  2166. target_ktv, _ := c.GetFloat("target_ktv", 0)
  2167. dialyzers, _ := c.GetInt64("dialyzers", 0)
  2168. injector, _ := c.GetInt64("injector", 0)
  2169. bloodlines, _ := c.GetInt64("bloodlines", 0)
  2170. tubing_hemodialysis, _ := c.GetInt64("tubing_hemodialysis", 0)
  2171. safe_package, _ := c.GetInt64("package", 0)
  2172. a_liquid, _ := c.GetInt64("a_liquid", 0)
  2173. anticoagulant_stop_time_hour, _ := c.GetInt64("anticoagulant_stop_time_hour", 0)
  2174. anticoagulant_stop_time_min, _ := c.GetInt64("anticoagulant_stop_time_min", 0)
  2175. blood := c.GetString("blood")
  2176. dialysis_dialyszers := c.GetString("dialysis_dialyszers")
  2177. dialysis_irrigation := c.GetString("dialysis_irrigation")
  2178. antioxidant_commodity_name := c.GetString("antioxidant_commodity_name")
  2179. displace_speed := c.GetString("displace_speed")
  2180. illness, _ := c.GetInt64("illness")
  2181. amylaceum := c.GetString("amylaceum")
  2182. single_time := c.GetString("single_time")
  2183. single_water := c.GetString("single_water")
  2184. replacement_flow := c.GetString("replacement_flow")
  2185. plasma_separator := c.GetString("plasma_separator")
  2186. bilirubin_adsorption_column := c.GetString("bilirubin_adsorption_column")
  2187. oxygen_uptake, _ := c.GetInt64("oxygen_uptake")
  2188. oxygen_flow := c.GetString("oxygen_flow")
  2189. oxygen_time := c.GetString("oxygen_time")
  2190. hemodialysis_pipelines := c.GetString("hemodialysis_pipelines")
  2191. hemodialysis_pipelines_count, _ := c.GetFloat("hemodialysis_pipelines_count", 0)
  2192. puncture_needle := c.GetString("puncture_needle")
  2193. puncture_needle_count, _ := c.GetFloat("puncture_needle_count", 0)
  2194. epo := c.GetString("epo")
  2195. epo_count, _ := c.GetFloat("epo_count", 0)
  2196. max_ultrafiltration_rate, _ := c.GetFloat("max_ultrafiltration_rate")
  2197. pre_impulse := c.GetString("pre_impulse")
  2198. impulse, _ := strconv.ParseFloat(pre_impulse, 64)
  2199. if mode_id > 0 {
  2200. service.ModifyScheduleMode(mode_id, patient.ID, recordDate.Unix(), adminUserInfo.Org.Id)
  2201. }
  2202. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  2203. //
  2204. //if template.TemplateId == 2 || template.TemplateId == 6 {
  2205. // if appRole.UserType == 3 {
  2206. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  2207. // if getPermissionErr != nil {
  2208. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2209. // return
  2210. // } else if headNursePermission == nil {
  2211. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  2212. // return
  2213. // }
  2214. // }
  2215. //}
  2216. prescription := models.DialysisPrescription{
  2217. UserOrgId: adminUserInfo.Org.Id,
  2218. PatientId: id,
  2219. RecordDate: recordDate.Unix(),
  2220. ModeId: mode_id,
  2221. DialysisDuration: dialysis_duration,
  2222. Dialyzer: dialyzer,
  2223. PerfusionApparatus: perfusion_apparatus,
  2224. BloodFlowVolume: blood_flow_volume,
  2225. DewaterAmount: dewater_amount,
  2226. DisplaceLiqui: displace_liqui,
  2227. ReplacementWay: replacement_way,
  2228. Anticoagulant: anticoagulant,
  2229. AnticoagulantShouji: anticoagulant_shouji,
  2230. AnticoagulantWeichi: anticoagulant_weichi,
  2231. AnticoagulantZongliang: anticoagulant_zongliang,
  2232. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  2233. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  2234. Kalium: kalium,
  2235. Sodium: sodium,
  2236. Calcium: calcium,
  2237. Bicarbonate: bicarbonate,
  2238. Glucose: glucose,
  2239. // DryWeight: dry_weight,
  2240. DialysateFlow: dialysate_flow,
  2241. DialysateTemperature: dialysate_temperature,
  2242. Conductivity: conductivity,
  2243. Remark: remark,
  2244. Status: 1,
  2245. CreatedTime: time.Now().Unix(),
  2246. UpdatedTime: time.Now().Unix(),
  2247. DialysisDurationMinute: dialysisDurationMinute,
  2248. DialysisDurationHour: dialysisDurationHour,
  2249. TargetUltrafiltration: targetUltrafiltration,
  2250. DialysateFormulation: dialysateFormulation,
  2251. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  2252. BodyFluid: body_fluid,
  2253. SpecialMedicine: special_medicine,
  2254. SpecialMedicineOther: special_medicine_other,
  2255. DisplaceLiquiPart: displace_liqui_part,
  2256. DisplaceLiquiValue: displace_liqui_value,
  2257. BloodAccess: blood_access,
  2258. Ultrafiltration: ultrafiltration,
  2259. BodyFluidOther: body_fluid_other,
  2260. ReplacementTotal: replacement_total,
  2261. Niprocart: niprocart,
  2262. Jms: jms,
  2263. FistulaNeedleSet: fistula_needle_set,
  2264. FistulaNeedleSet16: fistula_needle_set_16,
  2265. Hemoperfusion: hemoperfusion,
  2266. DialyserSterilised: dialyser_sterilised,
  2267. Filtryzer: filtryzer,
  2268. TargetKtv: target_ktv,
  2269. Dialyzers: dialyzers,
  2270. Injector: injector,
  2271. Bloodlines: bloodlines,
  2272. TubingHemodialysis: tubing_hemodialysis,
  2273. Package: safe_package,
  2274. ALiquid: a_liquid,
  2275. AnticoagulantStopTimeMin: anticoagulant_stop_time_min,
  2276. AnticoagulantStopTimeHour: anticoagulant_stop_time_hour,
  2277. Blood: blood,
  2278. DialysisDialyszers: dialysis_dialyszers,
  2279. DialysisIrrigation: dialysis_irrigation,
  2280. AntioxidantCommodityName: antioxidant_commodity_name,
  2281. DisplaceSpeed: displace_speed,
  2282. Illness: illness,
  2283. Amylaceum: amylaceum,
  2284. SingleWater: single_water,
  2285. SingleTime: single_time,
  2286. ReplacementFlow: replacement_flow,
  2287. PlasmaSeparator: plasma_separator,
  2288. BilirubinAdsorptionColumn: bilirubin_adsorption_column,
  2289. OxygenUptake: oxygen_uptake,
  2290. OxygenTime: oxygen_time,
  2291. OxygenFlow: oxygen_flow,
  2292. HemodialysisPipelines: hemodialysis_pipelines,
  2293. HemodialysisPipelinesCount: hemodialysis_pipelines_count,
  2294. PunctureNeedle: puncture_needle,
  2295. PunctureNeedleCount: puncture_needle_count,
  2296. Epo: epo,
  2297. EpoCount: epo_count,
  2298. MaxUltrafiltrationRate: max_ultrafiltration_rate,
  2299. PreImpulse: impulse,
  2300. }
  2301. _, dialysisPrescription := service.FindDialysisPrescriptionByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  2302. appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id, adminUserInfo.App.Id)
  2303. //
  2304. if appRole.UserType == 2 || appRole.UserType == 1 {
  2305. prescription_doctor = adminUserInfo.AdminUser.Id
  2306. prescription.PrescriptionDoctor = prescription_doctor
  2307. }
  2308. if dialysisPrescription.ID == 0 { //新增
  2309. prescription.Creater = adminUserInfo.AdminUser.Id
  2310. } else { //修改
  2311. if dialysisPrescription.Creater == 0 {
  2312. prescription.Creater = adminUserInfo.AdminUser.Id
  2313. } else {
  2314. prescription.Creater = dialysisPrescription.Creater
  2315. }
  2316. //if/**/
  2317. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  2318. //if dialysisPrescription.Creater != adminUserInfo.AdminUser.Id && dialysisPrescription.Creater > 0 {
  2319. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  2320. // if getPermissionErr != nil {
  2321. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2322. // return
  2323. // } else if headNursePermission == nil {
  2324. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  2325. // return
  2326. // }
  2327. //}
  2328. //prescription.Creater = dialysisPrescription.Creater
  2329. prescription.CreatedTime = dialysisPrescription.CreatedTime
  2330. prescription.Modifier = adminUserInfo.AdminUser.Id
  2331. prescription.ID = dialysisPrescription.ID
  2332. }
  2333. solution := models.DialysisSolution{
  2334. RegistrarsId: adminUserInfo.AdminUser.Id,
  2335. UserOrgId: adminUserInfo.Org.Id,
  2336. Doctor: prescription_doctor,
  2337. PatientId: id,
  2338. ModeId: mode_id,
  2339. DialysisDuration: dialysis_duration,
  2340. PerfusionApparatus: perfusion_apparatus,
  2341. BloodFlowVolume: blood_flow_volume,
  2342. Dewater: dewater_amount,
  2343. DisplaceLiqui: displace_liqui,
  2344. ReplacementWay: replacement_way,
  2345. Anticoagulant: anticoagulant,
  2346. AnticoagulantShouji: anticoagulant_shouji,
  2347. AnticoagulantWeichi: anticoagulant_weichi,
  2348. AnticoagulantZongliang: anticoagulant_zongliang,
  2349. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  2350. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  2351. Kalium: kalium,
  2352. Sodium: sodium,
  2353. Calcium: calcium,
  2354. Bicarbonate: bicarbonate,
  2355. Glucose: glucose,
  2356. // DryWeight: dry_weight,
  2357. DialysateFlow: dialysate_flow,
  2358. DialysateTemperature: dialysate_temperature,
  2359. Conductivity: conductivity,
  2360. Remark: remark,
  2361. Status: 1,
  2362. CreatedTime: time.Now().Unix(),
  2363. UpdatedTime: time.Now().Unix(),
  2364. DialysisDurationMinute: dialysisDurationMinute,
  2365. DialysisDurationHour: dialysisDurationHour,
  2366. TargetUltrafiltration: targetUltrafiltration,
  2367. DialysateFormulation: dialysateFormulation,
  2368. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  2369. BodyFluid: body_fluid,
  2370. SpecialMedicine: special_medicine,
  2371. SpecialMedicineOther: special_medicine_other,
  2372. DisplaceLiquiPart: displace_liqui_part,
  2373. DisplaceLiquiValue: displace_liqui_value,
  2374. BloodAccess: blood_access,
  2375. Ultrafiltration: ultrafiltration,
  2376. BodyFluidOther: body_fluid_other,
  2377. ReplacementTotal: replacement_total,
  2378. TargetKtv: target_ktv,
  2379. DialysisDialyszers: dialysis_dialyszers,
  2380. DialysisIrrigation: dialysis_irrigation,
  2381. HemodialysisPipelines: hemodialysis_pipelines,
  2382. HemodialysisPipelinesCount: hemodialysis_pipelines_count,
  2383. PunctureNeedle: puncture_needle,
  2384. PunctureNeedleCount: puncture_needle_count,
  2385. Epo: epo,
  2386. EpoCount: epo_count,
  2387. MaxUltrafiltrationRate: max_ultrafiltration_rate,
  2388. PreImpulse: impulse,
  2389. }
  2390. //针对河间咸的
  2391. if adminUserInfo.Org.Id == 10090 || adminUserInfo.Org.Id == 10164 || adminUserInfo.Org.Id == 3877 {
  2392. if solution.ModeId != 2 && solution.ModeId != 5 && solution.ModeId != 12 {
  2393. solution.DisplaceLiquiPart = 0
  2394. solution.DisplaceLiquiValue = 0
  2395. }
  2396. if prescription.ModeId != 2 && prescription.ModeId != 5 && prescription.ModeId != 12 {
  2397. prescription.DisplaceLiquiPart = 0
  2398. prescription.DisplaceLiquiValue = 0
  2399. }
  2400. }
  2401. service.SavePrescriptionAndCreateSolution(&solution, &prescription)
  2402. //获取最新1条
  2403. dialysisSolution, _ := service.GetLastPatientDialysisSolution(id, adminUserInfo.Org.Id)
  2404. //更新状态
  2405. service.UpdateDialysisSolutionStatusTwo(dialysisSolution.ID, dialysisSolution.ModeId, dialysisSolution.UserOrgId, dialysisSolution.PatientId)
  2406. //获取key,清空redis
  2407. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":" + strconv.FormatInt(mode_id, 10) + ":dialysis_prescribe"
  2408. redis := service.RedisClient()
  2409. defer redis.Close()
  2410. //清空key 值
  2411. redis.Set(key, "", time.Second)
  2412. //清空长期医嘱的key
  2413. soulution_key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(mode_id, 10) + ":dialysis_solution"
  2414. redis.Set(soulution_key, "", time.Second)
  2415. //查询最近透析准备表里是否存在 透析器 灌流器
  2416. keyOne := "scheduals_" + recordDateStr + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  2417. redis.Set(keyOne, "", time.Second)
  2418. keyTwo := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":schedual_detail"
  2419. redis.Set(keyTwo, "", time.Second)
  2420. keyThree := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":prescriptions_list_all"
  2421. redis.Set(keyThree, "", time.Second)
  2422. keyFour := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":dialysis_prescribe_by_mode"
  2423. redis.Set(keyFour, "", time.Second)
  2424. //splitStr := strings.Split(dialysis_dialyszers, ",")
  2425. //
  2426. //splitIrrigation := strings.Split(dialysis_irrigation, ",")
  2427. //
  2428. //mation, _ := service.GetGoodInfoMation(adminUserInfo.Org.Id)
  2429. //if len(mation)>0{
  2430. // for _, item := range splitStr {
  2431. // for _,it := range mation{
  2432. // if(item == it.SpecificationName){
  2433. //
  2434. // //查询最近一次的透析器
  2435. // _, errcode := service.GetDialysisBeforePrepare(it.GoodTypeId, it.ID, adminUserInfo.Org.Id,id)
  2436. //
  2437. // if errcode == gorm.ErrRecordNotFound{
  2438. // //插入数据
  2439. // prepare := models.DialysisBeforePrepare{
  2440. // UserOrgId: adminUserInfo.Org.Id,
  2441. // PatientId: id,
  2442. // RecordDate: recordDate.Unix(),
  2443. // GoodTypeId: it.GoodTypeId,
  2444. // GoodId: it.ID,
  2445. // Count: 1,
  2446. // Ctime: time.Now().Unix(),
  2447. // Creater: adminUserInfo.AdminUser.Id,
  2448. // Status:1,
  2449. //
  2450. // }
  2451. // errcode := service.CreateDialysisBeforePrepareOne(&prepare)
  2452. // fmt.Println("",errcode)
  2453. // }
  2454. // }
  2455. // }
  2456. //
  2457. // }
  2458. //
  2459. // for _, item := range splitIrrigation {
  2460. // for _,it := range mation{
  2461. // if(item == it.SpecificationName){
  2462. // //查询最近一次的透析器
  2463. // _, errcode := service.GetDialysisBeforePrepare(it.GoodTypeId, it.ID, adminUserInfo.Org.Id,id)
  2464. // if errcode == gorm.ErrRecordNotFound{
  2465. // //插入数据
  2466. // prepare := models.DialysisBeforePrepare{
  2467. // UserOrgId: adminUserInfo.Org.Id,
  2468. // PatientId: id,
  2469. // RecordDate: recordDate.Unix(),
  2470. // GoodTypeId: it.GoodTypeId,
  2471. // GoodId: it.ID,
  2472. // Count: 1,
  2473. // Ctime: time.Now().Unix(),
  2474. // Creater: adminUserInfo.AdminUser.Id,
  2475. // Status:1,
  2476. //
  2477. // }
  2478. // errcode := service.CreateDialysisBeforePrepareOne(&prepare)
  2479. // fmt.Println(errcode)
  2480. // }
  2481. // }
  2482. // }
  2483. // }
  2484. //}
  2485. c.ServeSuccessJSON(map[string]interface{}{
  2486. "solution": &solution,
  2487. "prescription": &prescription,
  2488. })
  2489. }
  2490. func (c *DialysisAPIController) GetAcceptsAssessment() {
  2491. patient, _ := c.GetInt64("patient", 0)
  2492. adminUserInfo := c.GetMobileAdminUserInfo()
  2493. _, receiveTreatmentAsses := service.GetLastAcceptsAssessment(patient, adminUserInfo.Org.Id)
  2494. c.ServeSuccessJSON(map[string]interface{}{
  2495. "receiveTreatmentAsses": receiveTreatmentAsses,
  2496. })
  2497. }
  2498. func (this *DialysisAPIController) PostSignInfo() {
  2499. patientID, _ := this.GetInt64("patient_id")
  2500. recordDateStr := this.GetString("date")
  2501. if patientID <= 0 {
  2502. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2503. return
  2504. }
  2505. if len(recordDateStr) == 0 {
  2506. recordDateStr = time.Now().Format("2006-01-02")
  2507. }
  2508. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  2509. if parseDateErr != nil {
  2510. this.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  2511. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2512. return
  2513. }
  2514. adminInfo := this.GetMobileAdminUserInfo()
  2515. err := service.UpDateDialysisPrescriptionDoctorSign(patientID, date.Unix(), adminInfo.Org.Id, adminInfo.AdminUser.Id)
  2516. if err != nil {
  2517. this.ErrorLog("签名失败:%v", err)
  2518. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2519. return
  2520. }
  2521. this.ServeSuccessJSON(map[string]interface{}{
  2522. "doctor_id": adminInfo.AdminUser.Id,
  2523. })
  2524. }
  2525. func (this *DialysisAPIController) GetLastMonitorRecord() {
  2526. patientID, _ := this.GetInt64("patient_id")
  2527. adminInfo := this.GetMobileAdminUserInfo()
  2528. record, _ := service.FindLastMonitorRecord(patientID, adminInfo.Org.Id)
  2529. this.ServeSuccessJSON(map[string]interface{}{
  2530. "monitor": record,
  2531. })
  2532. }
  2533. func (this *DialysisAPIController) GetLastMonitorRecordTody() {
  2534. thisTime := time.Now()
  2535. scheduleDateStart := thisTime.Format("2006-01-02") + " 00:00:00"
  2536. timeLayout := "2006-01-02 15:04:05"
  2537. loc, _ := time.LoadLocation("Local")
  2538. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  2539. theAssessmentDateTime := theStartTime.Unix()
  2540. patientID, _ := this.GetInt64("patient_id")
  2541. monitorDate, _ := this.GetInt64("monitoring_date", theAssessmentDateTime)
  2542. adminInfo := this.GetMobileAdminUserInfo()
  2543. record, _ := service.FindLastMonitorRecordToday(patientID, adminInfo.Org.Id, monitorDate)
  2544. fristrecord, _ := service.FindFirstMonitorRecordToday(patientID, adminInfo.Org.Id, monitorDate)
  2545. template, _ := service.GetOrgInfoTemplate(adminInfo.Org.Id)
  2546. var ultrafiltration_rate float64
  2547. _, prescription := service.FindDialysisPrescriptionByReordDate(patientID, theAssessmentDateTime, adminInfo.Org.Id)
  2548. _, evaluation := service.FindPredialysisEvaluationByReordDate(patientID, theAssessmentDateTime, adminInfo.Org.Id)
  2549. fmt.Println(evaluation)
  2550. if prescription.ID > 0 {
  2551. if prescription.TargetUltrafiltration > 0 && prescription.DialysisDurationHour > 0 {
  2552. totalMin := prescription.DialysisDurationHour*60 + prescription.DialysisDurationMinute
  2553. if template.TemplateId == 6 && adminInfo.Org.Id != 9538 {
  2554. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1000)
  2555. record.UltrafiltrationRate = ultrafiltration_rate
  2556. }
  2557. //if template.TemplateId == 6 && adminInfo.Org.Id ==9671{
  2558. // dehydration, _ := strconv.ParseFloat(evaluation.Dehydration, 64)
  2559. // ultrafiltration_rate = math.Floor((prescription.TargetUltrafiltration + dehydration) / float64(totalMin) * 60 * 1000)
  2560. // record.UltrafiltrationRate = ultrafiltration_rate
  2561. //}
  2562. if template.TemplateId == 32 || template.TemplateId == 34 || template.TemplateId == 36 {
  2563. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1)
  2564. record.UltrafiltrationRate = ultrafiltration_rate
  2565. }
  2566. if template.TemplateId == 20 || template.TemplateId == 22 {
  2567. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60)
  2568. record.UltrafiltrationRate = ultrafiltration_rate
  2569. }
  2570. // 只针对方济医院
  2571. if template.TemplateId == 1 && adminInfo.Org.Id != 9849 {
  2572. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", prescription.TargetUltrafiltration/float64(totalMin)*60), 6)
  2573. ultrafiltration_rate = value
  2574. record.UltrafiltrationRate = ultrafiltration_rate
  2575. }
  2576. fmt.Println("hhh23232323223232323323232323", template.TemplateId)
  2577. if template.TemplateId == 41 || template.TemplateId == 47 {
  2578. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / float64(totalMin) * 1000)
  2579. fmt.Println("prescritpin2332322323232323223", ultrafiltration_rate)
  2580. record.UltrafiltrationRate = ultrafiltration_rate
  2581. }
  2582. if template.TemplateId == 43 {
  2583. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / float64(totalMin))
  2584. record.UltrafiltrationRate = ultrafiltration_rate
  2585. }
  2586. if template.TemplateId == 46 || template.TemplateId == 54 {
  2587. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / float64(totalMin))
  2588. record.UltrafiltrationRate = ultrafiltration_rate
  2589. }
  2590. //if template.TemplateId == 47 {
  2591. // ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / float64(totalMin))
  2592. // record.UltrafiltrationRate = ultrafiltration_rate
  2593. //}
  2594. }
  2595. }
  2596. // record.UltrafiltrationRate = ultrafiltration_rate
  2597. record.UltrafiltrationVolume = 0
  2598. 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
  2599. if ultrafiltration_rate > 0 {
  2600. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", float64(record.OperateTime+3600-fristrecord.OperateTime)/3600*ultrafiltration_rate), 6)
  2601. record.UltrafiltrationVolume = value
  2602. }
  2603. }
  2604. if template.TemplateId == 6 || template.TemplateId == 20 || template.TemplateId == 22 || template.TemplateId == 32 || template.TemplateId == 34 || template.TemplateId == 36 || template.TemplateId == 41 || template.TemplateId == 43 || template.TemplateId == 47 || template.TemplateId == 54 { //adminInfo.Org.Id == 9538
  2605. if ultrafiltration_rate > 0 && adminInfo.Org.Id != 9538 {
  2606. ultrafiltration_volume := math.Floor(float64(record.OperateTime+3600-fristrecord.OperateTime) / 3600 * ultrafiltration_rate)
  2607. record.UltrafiltrationVolume = ultrafiltration_volume
  2608. }
  2609. }
  2610. if template.TemplateId == 47 || template.TemplateId == 54 {
  2611. record.DisplacementQuantity = record.DisplacementQuantity + record.DisplacementQuantity
  2612. }
  2613. this.ServeSuccessJSON(map[string]interface{}{
  2614. "monitor": record,
  2615. })
  2616. }
  2617. func (this *DialysisAPIController) ModifyStartDialysisOrder() {
  2618. record_id, _ := this.GetInt64("id")
  2619. nurseID, _ := this.GetInt64("nurse")
  2620. puncture_nurse, _ := this.GetInt64("puncture_nurse")
  2621. bedID, _ := this.GetInt64("bed")
  2622. start_time := this.GetString("start_time")
  2623. schedual_type, _ := this.GetInt64("schedual_type")
  2624. washpipe_nurse, _ := this.GetInt64("washpipe_nurse")
  2625. change_nurse, _ := this.GetInt64("change_nurse")
  2626. difficult_puncture_nurse, _ := this.GetInt64("difficult_puncture_nurse")
  2627. new_fistula_nurse, _ := this.GetInt64("new_fistula_nurse")
  2628. patient_id, _ := this.GetInt64("patient_id")
  2629. record_date, _ := this.GetInt64("record_date")
  2630. if record_id == 0 {
  2631. this.ErrorLog("id:%v", record_id)
  2632. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2633. return
  2634. }
  2635. startDate, parseStartDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", start_time)
  2636. if parseStartDateErr != nil {
  2637. this.ErrorLog("时间解析失败:%v", parseStartDateErr)
  2638. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2639. return
  2640. }
  2641. adminUserInfo := this.GetMobileAdminUserInfo()
  2642. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  2643. if getNurseErr != nil {
  2644. this.ErrorLog("获取护士失败:%v", getNurseErr)
  2645. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2646. return
  2647. } else if nurse == nil {
  2648. this.ErrorLog("护士不存在")
  2649. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2650. return
  2651. }
  2652. nurse, getNurseErr = service.GetAdminUserByUserID(puncture_nurse)
  2653. //if getNurseErr != nil {
  2654. // this.ErrorLog("获取护士失败:%v", getNurseErr)
  2655. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2656. // return
  2657. //} else if nurse == nil {
  2658. // this.ErrorLog("护士不存在")
  2659. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2660. // return
  2661. //}
  2662. deviceNumber, getDeviceNumberErr := service.GetDeviceNumberByID(adminUserInfo.Org.Id, bedID)
  2663. if getDeviceNumberErr != nil {
  2664. this.ErrorLog("获取床位号失败:%v", getDeviceNumberErr)
  2665. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2666. return
  2667. } else if deviceNumber == nil {
  2668. this.ErrorLog("床位号不存在")
  2669. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2670. return
  2671. }
  2672. _, tempDialysisRecord := service.FindDialysisOrderById(record_id)
  2673. //
  2674. //if tempDialysisRecord.Creator != adminUserInfo.AdminUser.Id {
  2675. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  2676. // if getPermissionErr != nil {
  2677. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2678. // return
  2679. // } else if headNursePermission == nil {
  2680. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  2681. // return
  2682. // }
  2683. //}
  2684. scheduleDateStart := startDate.Format("2006-01-02") + " 00:00:00"
  2685. scheduleDateEnd := startDate.Format("2006-01-02") + " 23:59:59"
  2686. timeLayout := "2006-01-02 15:04:05"
  2687. loc, _ := time.LoadLocation("Local")
  2688. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  2689. theEndTime, _ := time.ParseInLocation(timeLayout, scheduleDateEnd, loc)
  2690. schedulestartTime := theStartTime.Unix()
  2691. scheduleendTime := theEndTime.Unix()
  2692. //查询更改的机号,是否有人用了,如果只是排班了,但是没上机,直接替换,如果排班且上机了,就提示他无法上机
  2693. schedule, err := service.GetDayScheduleByBedid(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  2694. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  2695. if daySchedule.BedId != bedID || daySchedule.ScheduleType != schedual_type {
  2696. if err == gorm.ErrRecordNotFound { //空床位
  2697. // 修改了床位逻辑
  2698. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  2699. if daySchedule.ID > 0 {
  2700. //daySchedule.BedId = bedID
  2701. //daySchedule.PartitionId = deviceNumber.ZoneID
  2702. //daySchedule.ScheduleType = schedual_type
  2703. //daySchedule.UpdatedTime = time.Now().Unix()
  2704. //err := service.UpdateSchedule(&daySchedule)
  2705. xtSchedule := models.Schedule{
  2706. PartitionId: deviceNumber.ZoneID,
  2707. BedId: bedID,
  2708. ScheduleType: schedual_type,
  2709. UpdatedTime: time.Now().Unix(),
  2710. }
  2711. err := service.UpdateScheduleOne(daySchedule.ID, xtSchedule)
  2712. if err != nil {
  2713. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2714. return
  2715. }
  2716. }
  2717. } else if err == nil {
  2718. if schedule.ID > 0 && schedule.DialysisOrder.ID == 0 { //有排班没上机记录
  2719. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  2720. if daySchedule.ID > 0 {
  2721. //daySchedule.BedId = bedID
  2722. //daySchedule.PartitionId = deviceNumber.ZoneID
  2723. //
  2724. //daySchedule.ScheduleType = schedual_type
  2725. //daySchedule.UpdatedTime = time.Now().Unix()
  2726. //err := service.UpdateSchedule(&daySchedule)
  2727. xtSchedule := models.Schedule{
  2728. PartitionId: deviceNumber.ZoneID,
  2729. BedId: bedID,
  2730. ScheduleType: schedual_type,
  2731. UpdatedTime: time.Now().Unix(),
  2732. }
  2733. err := service.UpdateScheduleOne(daySchedule.ID, xtSchedule)
  2734. if err != nil {
  2735. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2736. return
  2737. }
  2738. }
  2739. } else if schedule.ID > 0 && schedule.DialysisOrder.ID > 0 { //有排班且有上机记录
  2740. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  2741. return
  2742. }
  2743. } else if err != nil {
  2744. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2745. return
  2746. }
  2747. }
  2748. dialysisRecord := &models.DialysisOrder{
  2749. ID: record_id,
  2750. UserOrgId: adminUserInfo.Org.Id,
  2751. BedID: bedID,
  2752. StartNurse: nurseID,
  2753. StartTime: startDate.Unix(),
  2754. PunctureNurse: puncture_nurse,
  2755. Creator: adminUserInfo.AdminUser.Id,
  2756. Modifier: adminUserInfo.AdminUser.Id,
  2757. WashpipeNurse: washpipe_nurse,
  2758. SchedualType: schedual_type,
  2759. ChangeNurse: change_nurse,
  2760. DifficultPunctureNurse: difficult_puncture_nurse,
  2761. NewFistulaNurse: new_fistula_nurse,
  2762. }
  2763. updateErr := service.ModifyStartDialysisOrder(dialysisRecord)
  2764. redis := service.RedisClient()
  2765. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":dialysis_order"
  2766. redis.Set(key, "", time.Second)
  2767. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":dialysis_orders_list_all"
  2768. //清空key 值
  2769. redis.Set(keyOne, "", time.Second)
  2770. scheduleDateStartOne := startDate.Format("2006-01-02")
  2771. keyTwo := "scheduals_" + scheduleDateStartOne + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  2772. redis.Set(keyTwo, "", time.Second)
  2773. keyThree := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":doctor_advices"
  2774. redis.Set(keyThree, "", time.Second)
  2775. keyFour := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":monitor_records"
  2776. redis.Set(keyFour, "", time.Second)
  2777. keyFive := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":patient_info"
  2778. redis.Set(keyFive, "", time.Second)
  2779. keySix := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":his_doctor_advice"
  2780. redis.Set(keySix, "", time.Second)
  2781. keySeven := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + ":device_list_all"
  2782. redis.Set(keySeven, "", time.Second)
  2783. if updateErr != nil {
  2784. this.ErrorLog("修改上机失败:%v", updateErr)
  2785. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2786. return
  2787. }
  2788. if updateErr == nil {
  2789. if tempDialysisRecord.Stage == 2 {
  2790. temp_time := (float64(tempDialysisRecord.EndTime) - float64(startDate.Unix())) / 3600
  2791. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  2792. fmt.Println(value)
  2793. a, b := math.Modf(value)
  2794. tempMinute, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  2795. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  2796. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", tempMinute*60), 10, 64)
  2797. updateAssessmentErr := service.UpdateAssessmentAfterDate(tempDialysisRecord.PatientId, tempDialysisRecord.UserOrgId, tempDialysisRecord.DialysisDate, hour, minute)
  2798. redis := service.RedisClient()
  2799. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":assessment_after_dislysis_list_all"
  2800. redis.Set(key, "", time.Second)
  2801. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecord.PatientId, 10) + ":" + strconv.FormatInt(record_date, 10) + ":assessment_after_dislysis"
  2802. redis.Set(keyOne, "", time.Second)
  2803. keySix := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":dialysis_orders_list_all"
  2804. //清空key 值
  2805. redis.Set(keySix, "", time.Second)
  2806. keySeven := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":monitor_records"
  2807. redis.Set(keySeven, "", time.Second)
  2808. redis.Close()
  2809. if updateAssessmentErr != nil {
  2810. utils.ErrorLog("%v", updateAssessmentErr)
  2811. }
  2812. }
  2813. }
  2814. _, dialysisRecords := service.FindDialysisOrderById(record_id)
  2815. this.ServeSuccessJSON(map[string]interface{}{
  2816. "dialysis_order": dialysisRecords,
  2817. })
  2818. }
  2819. func (c *DialysisAPIController) ModifyFinishDialysisOrder() {
  2820. record_id, _ := c.GetInt64("id")
  2821. nurseID, _ := c.GetInt64("nurse")
  2822. end_time := c.GetString("end_time")
  2823. puncture_point_haematoma, _ := c.GetInt64("puncture_point_haematoma")
  2824. blood_access_internal_fistula := c.GetString("blood_access_internal_fistula")
  2825. catheter := c.GetString("catheter")
  2826. cruor := c.GetString("cruor")
  2827. if record_id <= 0 || nurseID <= 0 {
  2828. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2829. return
  2830. }
  2831. adminUserInfo := c.GetMobileAdminUserInfo()
  2832. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  2833. if getNurseErr != nil {
  2834. c.ErrorLog("获取护士失败:%v", getNurseErr)
  2835. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2836. return
  2837. } else if nurse == nil {
  2838. c.ErrorLog("护士不存在")
  2839. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2840. return
  2841. }
  2842. endDate, parseEndDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", end_time)
  2843. if parseEndDateErr != nil {
  2844. c.ErrorLog("日期(%v)解析错误:%v", end_time, parseEndDateErr)
  2845. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2846. return
  2847. }
  2848. _, tempDialysisRecords := service.FindDialysisOrderById(record_id)
  2849. //if tempDialysisRecords.FinishCreator != adminUserInfo.AdminUser.Id {
  2850. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  2851. // if getPermissionErr != nil {
  2852. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2853. // return
  2854. // } else if headNursePermission == nil {
  2855. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  2856. // return
  2857. // }
  2858. //}
  2859. dialysisRecord := &models.DialysisOrder{
  2860. ID: record_id,
  2861. UserOrgId: adminUserInfo.Org.Id,
  2862. EndTime: endDate.Unix(),
  2863. FinishNurse: nurseID,
  2864. FinishModifier: adminUserInfo.AdminUser.Id,
  2865. PuncturePointHaematoma: puncture_point_haematoma,
  2866. BloodAccessInternalFistula: blood_access_internal_fistula,
  2867. Catheter: catheter,
  2868. Cruor: cruor,
  2869. }
  2870. updateErr := service.ModifyFinishDialysisOrder(dialysisRecord)
  2871. redis := service.RedisClient()
  2872. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.PatientId, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":dialysis_order"
  2873. //清空key 值
  2874. redis.Set(key, "", time.Second)
  2875. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":dialysis_orders_list_all"
  2876. //清空key 值
  2877. redis.Set(keyOne, "", time.Second)
  2878. keySeven := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.PatientId, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":monitor_records"
  2879. redis.Set(keySeven, "", time.Second)
  2880. redis.Close()
  2881. if updateErr != nil {
  2882. c.ErrorLog("修改下机失败:%v", updateErr)
  2883. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2884. return
  2885. }
  2886. if updateErr == nil {
  2887. temp_time := (float64(endDate.Unix()) - float64(tempDialysisRecords.StartTime)) / 3600
  2888. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  2889. a, b := math.Modf(value)
  2890. tempMinute, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  2891. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  2892. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", tempMinute*60), 10, 64)
  2893. updateAssessmentErr := service.UpdateAssessmentAfterDate(tempDialysisRecords.PatientId, tempDialysisRecords.UserOrgId, tempDialysisRecords.DialysisDate, hour, minute)
  2894. redis := service.RedisClient()
  2895. keyTen := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.PatientId, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":assessment_after_dislysis"
  2896. redis.Set(keyTen, "", time.Second)
  2897. keyTwo := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.PatientId, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":assessment_after_dislysis_last"
  2898. redis.Set(keyTwo, "", time.Second)
  2899. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":assessment_after_dislysis_list_all"
  2900. redis.Set(key, "", time.Second)
  2901. keyThree := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":dialysis_orders_list_all"
  2902. redis.Set(keyThree, "", time.Second)
  2903. keySeven := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.PatientId, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":monitor_records"
  2904. redis.Set(keySeven, "", time.Second)
  2905. defer redis.Close()
  2906. if updateAssessmentErr != nil {
  2907. utils.ErrorLog("%v", updateAssessmentErr)
  2908. }
  2909. }
  2910. _, dialysisRecords := service.FindDialysisOrderById(record_id)
  2911. c.ServeSuccessJSON(map[string]interface{}{
  2912. "dialysis_order": dialysisRecords,
  2913. })
  2914. }
  2915. func (c *DialysisAPIController) GetLongAdvice() {
  2916. patient_id, _ := c.GetInt64("id")
  2917. adminUserInfo := c.GetMobileAdminUserInfo()
  2918. _, config := service.FindDoctorAdviceRecordByOrgId(adminUserInfo.Org.Id)
  2919. _, hisConfig := service.FindXTHisRecordByOrgId(adminUserInfo.Org.Id)
  2920. is_advice_open, _ := service.FindAdviceSettingById(adminUserInfo.Org.Id)
  2921. prescription_open, _ := service.FindPrescriptionConfigById(adminUserInfo.Org.Id)
  2922. //patient, _ := service.FindPatientIsOpenRemindById(patient_id, adminUserInfo.Org.Id)
  2923. if config.IsOpenRemind == 0 { //针对老用户,即没开启推送功能,也没有 不开启推送功能,不做任何处理
  2924. c.ServeSuccessJSON(map[string]interface{}{
  2925. "status": "1",
  2926. })
  2927. return
  2928. } else { //开启推送提醒
  2929. //开启推送提醒逻辑 提交长期处方的时候,弹起长期医嘱推送
  2930. var advice_three []*models.DoctorAdvice
  2931. recordDateStr := time.Now().Format("2006-01-02")
  2932. recordDate, _ := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  2933. nowtime := recordDate.Unix()
  2934. //advices, err := service.GetLastLongAdviceByGroupNoOne(adminUserInfo.Org.Id, patient_id,nowtime)
  2935. //fmt.Println("advices232333232323323233232333223233232322332",advices)
  2936. //advices_two, err := service.GetLastLongAdviceByGroupNoFour(adminUserInfo.Org.Id, patient_id,nowtime)
  2937. advices, err := service.GetLastLongAdviceByGroupNo(adminUserInfo.Org.Id, patient_id, nowtime)
  2938. advices_two, err := service.GetLastLongAdviceByGroupNoThree(adminUserInfo.Org.Id, patient_id, nowtime)
  2939. for _, advice := range advices {
  2940. if advice.FrequencyType == 3 {
  2941. t := time.Now()
  2942. week := int(t.Weekday())
  2943. fmt.Println(t.Weekday())
  2944. fmt.Println(week)
  2945. switch week {
  2946. case 1:
  2947. if strings.Index(advice.WeekDay, "周一") == -1 {
  2948. advice_three = append(advice_three, advice)
  2949. }
  2950. break
  2951. case 2:
  2952. if strings.Index(advice.WeekDay, "周二") == -1 {
  2953. advice_three = append(advice_three, advice)
  2954. }
  2955. break
  2956. case 3:
  2957. if strings.Index(advice.WeekDay, "周三") == -1 {
  2958. advice_three = append(advice_three, advice)
  2959. }
  2960. break
  2961. case 4:
  2962. if strings.Index(advice.WeekDay, "周四") == -1 {
  2963. advice_three = append(advice_three, advice)
  2964. }
  2965. break
  2966. case 5:
  2967. if strings.Index(advice.WeekDay, "周五") == -1 {
  2968. advice_three = append(advice_three, advice)
  2969. }
  2970. break
  2971. case 6:
  2972. if strings.Index(advice.WeekDay, "周六") == -1 {
  2973. advice_three = append(advice_three, advice)
  2974. }
  2975. break
  2976. case 0:
  2977. if strings.Index(advice.WeekDay, "周日") == -1 {
  2978. advice_three = append(advice_three, advice)
  2979. }
  2980. break
  2981. }
  2982. }
  2983. }
  2984. for _, advice := range advices_two {
  2985. p, _ := time.Parse("2006-01-02", time.Now().Format("2006-01-02"))
  2986. now := p.Unix()
  2987. dayStr := strconv.FormatInt(advice.DayCount, 10)
  2988. dayStr2 := "-" + dayStr
  2989. count, _ := strconv.ParseInt(dayStr2, 10, 64)
  2990. oldTime := time.Now().AddDate(0, 0, int(count)).Unix()
  2991. advices, _ := service.FindAllDoctorAdviceByTime(now, oldTime, patient_id, adminUserInfo.Org.Id, advice.TemplateId)
  2992. for _, ad := range advices {
  2993. advice_three = append(advice_three, ad)
  2994. }
  2995. }
  2996. if err == nil {
  2997. c.ServeSuccessJSON(map[string]interface{}{
  2998. "status": "2",
  2999. "advices": advices,
  3000. "advices_two": RemoveRepeatedElement(advice_three),
  3001. "is_open_remind": config.IsOpenRemind,
  3002. "his_config_open": hisConfig.IsOpen,
  3003. "is_advice_open": is_advice_open.IsAdviceOpen,
  3004. "prescription_open": prescription_open.IsOpen,
  3005. })
  3006. }
  3007. }
  3008. }
  3009. func (c *DialysisAPIController) GetLongAdviceOne() {
  3010. patient_id, _ := c.GetInt64("id")
  3011. startTime := c.GetString("schedule_date")
  3012. timeLayout := "2006-01-02"
  3013. loc, _ := time.LoadLocation("Local")
  3014. var theStartTime int64
  3015. if len(startTime) > 0 {
  3016. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", startTime+" 00:00:00", loc)
  3017. if err != nil {
  3018. utils.ErrorLog(err.Error())
  3019. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3020. return
  3021. }
  3022. theStartTime = theTime.Unix()
  3023. }
  3024. adminUserInfo := c.GetMobileAdminUserInfo()
  3025. _, config := service.FindDoctorAdviceRecordByOrgId(adminUserInfo.Org.Id)
  3026. _, hisConfig := service.FindXTHisRecordByOrgId(adminUserInfo.Org.Id)
  3027. is_advice_open, _ := service.FindAdviceSettingById(adminUserInfo.Org.Id)
  3028. prescription_open, _ := service.FindPrescriptionConfigById(adminUserInfo.Org.Id)
  3029. //patient, _ := service.FindPatientIsOpenRemindById(patient_id, adminUserInfo.Org.Id)
  3030. if config.IsOpenRemind == 0 { //针对老用户,即没开启推送功能,也没有 不开启推送功能,不做任何处理
  3031. c.ServeSuccessJSON(map[string]interface{}{
  3032. "status": "1",
  3033. })
  3034. return
  3035. } else { //开启推送提醒
  3036. //开启推送提醒逻辑 提交长期处方的时候,弹起长期医嘱推送
  3037. var advice_three []*models.DoctorAdvice
  3038. fmt.Println("theStartTime23434343433434433443434343434334", theStartTime)
  3039. advices, err := service.GetLastLongAdviceByGroupNo(adminUserInfo.Org.Id, patient_id, theStartTime)
  3040. advices_two, err := service.GetLastLongAdviceByGroupNoThree(adminUserInfo.Org.Id, patient_id, theStartTime)
  3041. for _, advice := range advices {
  3042. if advice.FrequencyType == 3 {
  3043. t := time.Now()
  3044. week := int(t.Weekday())
  3045. fmt.Println(t.Weekday())
  3046. fmt.Println(week)
  3047. switch week {
  3048. case 1:
  3049. if strings.Index(advice.WeekDay, "周一") == -1 {
  3050. advice_three = append(advice_three, advice)
  3051. }
  3052. break
  3053. case 2:
  3054. if strings.Index(advice.WeekDay, "周二") == -1 {
  3055. advice_three = append(advice_three, advice)
  3056. }
  3057. break
  3058. case 3:
  3059. if strings.Index(advice.WeekDay, "周三") == -1 {
  3060. advice_three = append(advice_three, advice)
  3061. }
  3062. break
  3063. case 4:
  3064. if strings.Index(advice.WeekDay, "周四") == -1 {
  3065. advice_three = append(advice_three, advice)
  3066. }
  3067. break
  3068. case 5:
  3069. if strings.Index(advice.WeekDay, "周五") == -1 {
  3070. advice_three = append(advice_three, advice)
  3071. }
  3072. break
  3073. case 6:
  3074. if strings.Index(advice.WeekDay, "周六") == -1 {
  3075. advice_three = append(advice_three, advice)
  3076. }
  3077. break
  3078. case 0:
  3079. if strings.Index(advice.WeekDay, "周日") == -1 {
  3080. advice_three = append(advice_three, advice)
  3081. }
  3082. break
  3083. }
  3084. }
  3085. }
  3086. for _, advice := range advices_two {
  3087. p, _ := time.Parse("2006-01-02", time.Now().Format("2006-01-02"))
  3088. now := p.Unix()
  3089. dayStr := strconv.FormatInt(advice.DayCount, 10)
  3090. dayStr2 := "-" + dayStr
  3091. count, _ := strconv.ParseInt(dayStr2, 10, 64)
  3092. oldTime := time.Now().AddDate(0, 0, int(count)).Unix()
  3093. advices, _ := service.FindAllDoctorAdviceByTime(now, oldTime, patient_id, adminUserInfo.Org.Id, advice.TemplateId)
  3094. for _, ad := range advices {
  3095. advice_three = append(advice_three, ad)
  3096. }
  3097. }
  3098. if err == nil {
  3099. c.ServeSuccessJSON(map[string]interface{}{
  3100. "status": "2",
  3101. "advices": advices,
  3102. "advices_two": RemoveRepeatedElement(advice_three),
  3103. "is_open_remind": config.IsOpenRemind,
  3104. "his_config_open": hisConfig.IsOpen,
  3105. "is_advice_open": is_advice_open.IsAdviceOpen,
  3106. "prescription_open": prescription_open.IsOpen,
  3107. })
  3108. }
  3109. }
  3110. }
  3111. func RemoveRepeatedElement(arr []*models.DoctorAdvice) (newArr []*models.DoctorAdvice) {
  3112. newArr = make([]*models.DoctorAdvice, 0)
  3113. for i := 0; i < len(arr); i++ {
  3114. repeat := false
  3115. for j := i + 1; j < len(arr); j++ {
  3116. if arr[i].ID == arr[j].ID {
  3117. repeat = true
  3118. break
  3119. }
  3120. }
  3121. if !repeat {
  3122. newArr = append(newArr, arr[i])
  3123. }
  3124. }
  3125. return
  3126. }
  3127. func (c *DialysisAPIController) CreateRemindDoctorAdvice() {
  3128. patient, _ := c.GetInt64("id", 0)
  3129. groupNo, _ := c.GetInt64("groupno", 0)
  3130. if patient <= 0 {
  3131. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3132. return
  3133. }
  3134. adminUserInfo := c.GetMobileAdminUserInfo()
  3135. dataBody := make(map[string]interface{}, 0)
  3136. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  3137. if err != nil {
  3138. utils.ErrorLog(err.Error())
  3139. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3140. return
  3141. }
  3142. utils.ErrorLog("%v", dataBody)
  3143. timeLayout := "2006-01-02 15:04"
  3144. loc, _ := time.LoadLocation("Local")
  3145. timeLayout2 := "2006-01-02"
  3146. loc2, _ := time.LoadLocation("Local")
  3147. if dataBody["advice_type"] == nil || reflect.TypeOf(dataBody["advice_type"]).String() != "float64" {
  3148. utils.ErrorLog("advice_type")
  3149. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3150. return
  3151. }
  3152. adviceType := int64(2)
  3153. if dataBody["advice_date"] == nil || reflect.TypeOf(dataBody["advice_date"]).String() != "string" {
  3154. utils.ErrorLog("advice_date")
  3155. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3156. return
  3157. }
  3158. adviceDate, _ := dataBody["advice_date"].(string)
  3159. theTime, err := time.ParseInLocation(timeLayout2, adviceDate, loc2)
  3160. AdviceDate := theTime.Unix()
  3161. RecordDate := theTime.Unix()
  3162. if dataBody["start_time"] == nil || reflect.TypeOf(dataBody["start_time"]).String() != "string" {
  3163. utils.ErrorLog("start_time")
  3164. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3165. return
  3166. }
  3167. startTime, _ := dataBody["start_time"].(string)
  3168. if len(startTime) == 0 {
  3169. utils.ErrorLog("len(start_time) == 0")
  3170. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3171. return
  3172. }
  3173. theTime, err = time.ParseInLocation(timeLayout, startTime, loc)
  3174. if err != nil {
  3175. utils.ErrorLog(err.Error())
  3176. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3177. return
  3178. }
  3179. StartTime := theTime.Unix()
  3180. Remark := ""
  3181. if dataBody["remark"] != nil && reflect.TypeOf(dataBody["remark"]).String() == "string" {
  3182. remark, _ := dataBody["remark"].(string)
  3183. Remark = remark
  3184. }
  3185. var advices []*models.GroupAdvice
  3186. if dataBody["advices"] == nil || reflect.TypeOf(dataBody["advices"]).String() != "[]interface {}" {
  3187. utils.ErrorLog("advices")
  3188. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3189. return
  3190. }
  3191. adviceNames := dataBody["advices"].([]interface{})
  3192. for _, adviceNameMap := range adviceNames {
  3193. adviceNameM := adviceNameMap.(map[string]interface{})
  3194. var advice models.GroupAdvice
  3195. advice.Remark = Remark
  3196. advice.AdviceType = adviceType
  3197. advice.StartTime = StartTime
  3198. advice.AdviceDate = AdviceDate
  3199. advice.RecordDate = RecordDate
  3200. advice.Status = 1
  3201. advice.CreatedTime = time.Now().Unix()
  3202. advice.UpdatedTime = time.Now().Unix()
  3203. advice.StopState = 2
  3204. advice.ExecutionState = 2
  3205. advice.UserOrgId = adminUserInfo.Org.Id
  3206. advice.PatientId = patient
  3207. advice.AdviceDoctor = adminUserInfo.AdminUser.Id
  3208. if adviceNameM["advice_name"] == nil || reflect.TypeOf(adviceNameM["advice_name"]).String() != "string" {
  3209. utils.ErrorLog("advice_name")
  3210. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3211. return
  3212. }
  3213. adviceName, _ := adviceNameM["advice_name"].(string)
  3214. if len(adviceName) == 0 {
  3215. utils.ErrorLog("len(advice_name) == 0")
  3216. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3217. return
  3218. }
  3219. advice.AdviceName = adviceName
  3220. if adviceNameM["drug_spec"] != nil && reflect.TypeOf(adviceNameM["drug_spec"]).String() == "string" {
  3221. drugSpec, _ := strconv.ParseFloat(adviceNameM["drug_spec"].(string), 64)
  3222. advice.DrugSpec = drugSpec
  3223. }
  3224. if adviceNameM["advice_desc"] != nil && reflect.TypeOf(adviceNameM["advice_desc"]).String() == "string" {
  3225. adviceDesc, _ := adviceNameM["advice_desc"].(string)
  3226. advice.AdviceDesc = adviceDesc
  3227. }
  3228. if adviceNameM["drug_spec_unit"] != nil && reflect.TypeOf(adviceNameM["drug_spec_unit"]).String() == "string" {
  3229. drugSpecUnit, _ := adviceNameM["drug_spec_unit"].(string)
  3230. advice.DrugSpecUnit = drugSpecUnit
  3231. }
  3232. //if adviceNameM["single_dose"] != nil && reflect.TypeOf(adviceNameM["single_dose"]).String() == "string" {
  3233. // singleDose, _ := strconv.ParseFloat(adviceNameM["single_dose"].(string), 64)
  3234. // advice.SingleDose = singleDose
  3235. //}
  3236. if adviceNameM["single_dose"] != nil || reflect.TypeOf(adviceNameM["single_dose"]).String() == "float64" {
  3237. //single_dose := int64(adviceNameM["single_dose"].(float64))
  3238. advice.SingleDose = adviceNameM["single_dose"].(float64)
  3239. }
  3240. if adviceNameM["single_dose_unit"] != nil && reflect.TypeOf(adviceNameM["single_dose_unit"]).String() == "string" {
  3241. singleDoseUnit, _ := adviceNameM["single_dose_unit"].(string)
  3242. advice.SingleDoseUnit = singleDoseUnit
  3243. }
  3244. //if adviceNameM["prescribing_number"] != nil && reflect.TypeOf(adviceNameM["prescribing_number"]).String() == "string" {
  3245. // prescribingNumber, _ := strconv.ParseFloat(adviceNameM["prescribing_number"].(string), 64)
  3246. // advice.PrescribingNumber = prescribingNumber
  3247. //}
  3248. if adviceNameM["prescribing_number"] != nil || reflect.TypeOf(adviceNameM["prescribing_number"]).String() == "float64" {
  3249. //single_dose := int64(adviceNameM["single_dose"].(float64))
  3250. advice.PrescribingNumber = adviceNameM["prescribing_number"].(float64)
  3251. }
  3252. if adviceNameM["prescribing_number_unit"] != nil && reflect.TypeOf(adviceNameM["prescribing_number_unit"]).String() == "string" {
  3253. prescribingNumberUnit, _ := adviceNameM["prescribing_number_unit"].(string)
  3254. advice.PrescribingNumberUnit = prescribingNumberUnit
  3255. }
  3256. if adviceNameM["delivery_way"] != nil && reflect.TypeOf(adviceNameM["delivery_way"]).String() == "string" {
  3257. deliveryWay, _ := adviceNameM["delivery_way"].(string)
  3258. advice.DeliveryWay = deliveryWay
  3259. }
  3260. if adviceNameM["execution_frequency"] != nil && reflect.TypeOf(adviceNameM["execution_frequency"]).String() == "string" {
  3261. executionFrequency, _ := adviceNameM["execution_frequency"].(string)
  3262. advice.ExecutionFrequency = executionFrequency
  3263. }
  3264. if adviceNameM["frequency_type"] != nil || reflect.TypeOf(adviceNameM["frequency_type"]).String() == "float64" {
  3265. frequency_type := int64(adviceNameM["frequency_type"].(float64))
  3266. advice.FrequencyType = frequency_type
  3267. }
  3268. if adviceNameM["day_count"] != nil || reflect.TypeOf(adviceNameM["day_count"]).String() == "float64" {
  3269. day_count := int64(adviceNameM["day_count"].(float64))
  3270. advice.DayCount = day_count
  3271. }
  3272. if adviceNameM["week_day"] != nil && reflect.TypeOf(adviceNameM["week_day"]).String() == "string" {
  3273. week_day, _ := adviceNameM["week_day"].(string)
  3274. advice.WeekDay = week_day
  3275. }
  3276. if adviceNameM["way"] != nil || reflect.TypeOf(adviceNameM["way"]).String() == "float64" {
  3277. way := int64(adviceNameM["way"].(float64))
  3278. advice.Way = way
  3279. }
  3280. if adviceNameM["drug_id"] != nil || reflect.TypeOf(adviceNameM["drug_id"]).String() == "float64" {
  3281. drug_id := int64(adviceNameM["drug_id"].(float64))
  3282. advice.DrugId = drug_id
  3283. }
  3284. if adviceNameM["drug_name_id"] != nil || reflect.TypeOf(adviceNameM["drug_name_id"]).String() == "float64" {
  3285. drug_name_id := int64(adviceNameM["drug_name_id"].(float64))
  3286. advice.DrugNameId = drug_name_id
  3287. }
  3288. if adviceNameM["template_id"] != nil && reflect.TypeOf(adviceNameM["template_id"]).String() == "string" {
  3289. template_id, _ := adviceNameM["template_id"].(string)
  3290. advice.TemplateId = template_id
  3291. }
  3292. if adviceNameM["child"] != nil && reflect.TypeOf(adviceNameM["child"]).String() == "string" {
  3293. executionFrequency, _ := adviceNameM["execution_frequency"].(string)
  3294. advice.ExecutionFrequency = executionFrequency
  3295. }
  3296. if adviceNameM["child"] != nil && reflect.TypeOf(adviceNameM["child"]).String() == "[]interface {}" {
  3297. children := adviceNameM["child"].([]interface{})
  3298. if len(children) > 0 {
  3299. for _, childrenMap := range children {
  3300. childMap := childrenMap.(map[string]interface{})
  3301. var child models.GroupAdvice
  3302. child.Remark = Remark
  3303. child.AdviceType = adviceType
  3304. child.StartTime = StartTime
  3305. child.AdviceDate = AdviceDate
  3306. child.RecordDate = RecordDate
  3307. child.Status = 1
  3308. child.CreatedTime = time.Now().Unix()
  3309. child.UpdatedTime = time.Now().Unix()
  3310. child.StopState = 2
  3311. child.ExecutionState = 2
  3312. child.UserOrgId = adminUserInfo.Org.Id
  3313. child.PatientId = patient
  3314. child.AdviceDoctor = adminUserInfo.AdminUser.Id
  3315. if childMap["advice_name"] == nil || reflect.TypeOf(childMap["advice_name"]).String() != "string" {
  3316. utils.ErrorLog("child advice_name")
  3317. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3318. return
  3319. }
  3320. childAdviceName, _ := childMap["advice_name"].(string)
  3321. if len(childAdviceName) == 0 {
  3322. utils.ErrorLog("len(child advice_name) == 0")
  3323. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3324. return
  3325. }
  3326. child.AdviceName = childAdviceName
  3327. if childMap["advice_desc"] != nil && reflect.TypeOf(childMap["advice_desc"]).String() == "string" {
  3328. childAdviceDesc, _ := childMap["advice_desc"].(string)
  3329. child.AdviceDesc = childAdviceDesc
  3330. }
  3331. if childMap["drug_spec"] != nil && reflect.TypeOf(childMap["drug_spec"]).String() == "string" {
  3332. childDrugSpec, _ := strconv.ParseFloat(childMap["drug_spec"].(string), 64)
  3333. child.DrugSpec = childDrugSpec
  3334. }
  3335. if childMap["drug_spec_unit"] != nil && reflect.TypeOf(childMap["drug_spec_unit"]).String() == "string" {
  3336. childDrugSpecUnit, _ := childMap["drug_spec_unit"].(string)
  3337. child.DrugSpecUnit = childDrugSpecUnit
  3338. }
  3339. if childMap["single_dose"] != nil && reflect.TypeOf(childMap["single_dose"]).String() == "float64" {
  3340. child.SingleDose = childMap["single_dose"].(float64)
  3341. }
  3342. if childMap["single_dose_unit"] != nil && reflect.TypeOf(childMap["single_dose_unit"]).String() == "string" {
  3343. childSingleDoseUnit, _ := childMap["single_dose_unit"].(string)
  3344. child.SingleDoseUnit = childSingleDoseUnit
  3345. }
  3346. if childMap["prescribing_number"] != nil && reflect.TypeOf(childMap["prescribing_number"]).String() == "float64" {
  3347. child.PrescribingNumber = childMap["prescribing_number"].(float64)
  3348. }
  3349. if childMap["prescribing_number_unit"] != nil && reflect.TypeOf(childMap["prescribing_number_unit"]).String() == "string" {
  3350. childPrescribingNumberUnit, _ := childMap["prescribing_number_unit"].(string)
  3351. child.PrescribingNumberUnit = childPrescribingNumberUnit
  3352. }
  3353. child.DeliveryWay = advice.DeliveryWay
  3354. child.ExecutionFrequency = advice.ExecutionFrequency
  3355. advice.Children = append(advice.Children, &child)
  3356. }
  3357. }
  3358. }
  3359. temp_advice, _ := service.FindRemindAdvice(advice.UserOrgId, advice.AdviceName, advice.AdviceDesc, advice.TemplateId, advice.FrequencyType, patient, advice.RecordDate)
  3360. if temp_advice.ID == 0 {
  3361. advices = append(advices, &advice)
  3362. }
  3363. }
  3364. if len(advices) > 0 {
  3365. list, err := service.CreateMGroupAdvice(adminUserInfo.Org.Id, advices, groupNo)
  3366. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient, 10) + ":" + strconv.FormatInt(RecordDate, 10) + ":doctor_advices"
  3367. redis := service.RedisClient()
  3368. //清空key 值
  3369. redis.Set(key, "", time.Second)
  3370. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(AdviceDate, 10) + ":advice_list_all"
  3371. redis.Set(keyOne, "", time.Second)
  3372. keyThree := "scheduals_" + adviceDate + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  3373. defer redis.Close()
  3374. redis.Set(keyThree, "", time.Second)
  3375. if err != nil {
  3376. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateDoctorAdviceFail)
  3377. return
  3378. }
  3379. c.ServeSuccessJSON(map[string]interface{}{
  3380. "msg": "ok",
  3381. "advices": list,
  3382. })
  3383. } else {
  3384. c.ServeSuccessJSON(map[string]interface{}{
  3385. "msg": "ok",
  3386. })
  3387. }
  3388. return
  3389. }
  3390. func (c *DialysisAPIController) UploadDryWeight() {
  3391. patient_id, _ := c.GetInt64("id")
  3392. dry_weight, _ := c.GetFloat("dry_weight")
  3393. doctor_id, _ := c.GetInt64("doctor_id")
  3394. remark := c.GetString("remark")
  3395. adminUserInfo := c.GetMobileAdminUserInfo()
  3396. weightAdjust, err := service.FindLastDryWeightAdjust(adminUserInfo.Org.Id, patient_id)
  3397. if err == gorm.ErrRecordNotFound {
  3398. dryWeight := &models.SgjPatientDryweight{
  3399. PatientId: patient_id,
  3400. DryWeight: dry_weight,
  3401. Remakes: remark,
  3402. Ctime: time.Now().Unix(),
  3403. Mtime: time.Now().Unix(),
  3404. Creator: doctor_id,
  3405. Status: 1,
  3406. UserOrgId: adminUserInfo.Org.Id,
  3407. AdjustedValue: "/",
  3408. UserId: adminUserInfo.AdminUser.Id,
  3409. }
  3410. createErr := service.CreatePatientWeightAdjust(dryWeight)
  3411. redis := service.RedisClient()
  3412. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + ":assessment_befores_list_all"
  3413. redis.Set(keyOne, "", time.Second)
  3414. loc, _ := time.LoadLocation("Local")
  3415. nowTime := time.Now()
  3416. nowDay := nowTime.Format("2006-01-02")
  3417. dayTime, _ := time.ParseInLocation("2006-01-02 15:04:05", nowDay+" 00:00:00", loc)
  3418. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dayTime.Unix(), 10) + ":assessment_before_dislysis"
  3419. redis.Set(key, "", time.Second)
  3420. keyTwo := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":last_dry_weight"
  3421. redis.Set(keyTwo, "", time.Second)
  3422. redis.Close()
  3423. if createErr == nil {
  3424. c.ServeSuccessJSON(map[string]interface{}{
  3425. "msg": "提交成功",
  3426. "weight": dryWeight,
  3427. })
  3428. }
  3429. } else {
  3430. dryWeight := &models.SgjPatientDryweight{
  3431. PatientId: patient_id,
  3432. DryWeight: dry_weight,
  3433. Remakes: remark,
  3434. Ctime: time.Now().Unix(),
  3435. Mtime: time.Now().Unix(),
  3436. Creator: doctor_id,
  3437. Status: 1,
  3438. UserOrgId: adminUserInfo.Org.Id,
  3439. AdjustedValue: "/",
  3440. UserId: adminUserInfo.AdminUser.Id,
  3441. }
  3442. var value float64
  3443. value = dry_weight - weightAdjust.DryWeight
  3444. if value < 0 {
  3445. dryWeight.AdjustedValue = strconv.FormatFloat(math.Abs(value), 'f', 1, 64) + "(下调)"
  3446. } else if value == 0 {
  3447. dryWeight.AdjustedValue = "/"
  3448. } else if value > 0 {
  3449. dryWeight.AdjustedValue = strconv.FormatFloat(value, 'f', 1, 64) + "(上调)"
  3450. }
  3451. createErr := service.CreatePatientWeightAdjust(dryWeight)
  3452. redis := service.RedisClient()
  3453. loc, _ := time.LoadLocation("Local")
  3454. nowTime := time.Now()
  3455. nowDay := nowTime.Format("2006-01-02")
  3456. dayTime, _ := time.ParseInLocation("2006-01-02 15:04:05", nowDay+" 00:00:00", loc)
  3457. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(dayTime.Unix(), 10) + ":assessment_befores_list_all"
  3458. redis.Set(keyOne, "", time.Second)
  3459. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dayTime.Unix(), 10) + ":assessment_before_dislysis"
  3460. redis.Set(key, "", time.Second)
  3461. keyTwo := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":last_dry_weight"
  3462. redis.Set(keyTwo, "", time.Second)
  3463. redis.Close()
  3464. if createErr == nil {
  3465. c.ServeSuccessJSON(map[string]interface{}{
  3466. "msg": "提交成功",
  3467. "weight": dryWeight,
  3468. })
  3469. }
  3470. }
  3471. }
  3472. func (c *DialysisAPIController) GetSolution() {
  3473. patient_id, _ := c.GetInt64("patient_id")
  3474. mode_id, _ := c.GetInt64("mode_id")
  3475. adminUserInfo := c.GetMobileAdminUserInfo()
  3476. solution, err := service.MobileGetDialysisSolutionByModeIdSeven(adminUserInfo.Org.Id, patient_id, mode_id)
  3477. prescription, err := service.MobileGetLastDialysisPrescribeByModeIdSeven(adminUserInfo.Org.Id, patient_id, mode_id)
  3478. system_prescription, err := service.MobileGetSystemDialysisPrescribeByModeIdSeven(adminUserInfo.Org.Id, mode_id)
  3479. if err != nil {
  3480. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3481. return
  3482. }
  3483. c.ServeSuccessJSON(map[string]interface{}{
  3484. "solution": solution,
  3485. "prescription": prescription,
  3486. "system_prescription": system_prescription,
  3487. })
  3488. }
  3489. func (c *DialysisAPIController) GetSchedule() {
  3490. schedual_type, _ := c.GetInt64("schedual_type")
  3491. adminUserInfo := c.GetMobileAdminUserInfo()
  3492. //timeLayout := "2006-01-02 15:04:05"
  3493. //
  3494. //date := time.Now().Format("2006-01-02") + " 00:00:00"
  3495. //loc, _ := time.LoadLocation("Local")
  3496. //theStartTime, _ := time.ParseInLocation(timeLayout, date, loc)
  3497. //scheduleTime := theStartTime.Unix()
  3498. scheduleTime, _ := c.GetInt64("record_date")
  3499. deviceNumber, _ := service.GetAllDeviceNumbers(adminUserInfo.Org.Id, scheduleTime, schedual_type)
  3500. list, _ := service.GetAllBedNumberSeven(adminUserInfo.Org.Id)
  3501. c.ServeSuccessJSON(map[string]interface{}{
  3502. "number": deviceNumber,
  3503. "list": list,
  3504. })
  3505. }
  3506. func (c *DialysisAPIController) GetPatientId() {
  3507. id, _ := c.GetInt64("id")
  3508. //orgid := c.GetMobileAdminUserInfo().Org.Id
  3509. patientId, _ := service.GetPatientId(id)
  3510. //获取该患者的所有传染病
  3511. list, _ := service.GetPatientInfectious(id)
  3512. c.ServeSuccessJSON(map[string]interface{}{
  3513. "patient": patientId,
  3514. "infectioulist": list,
  3515. })
  3516. }
  3517. func (this *DialysisAPIController) GetDialysisSchedule() {
  3518. schedualDate := this.GetString("date")
  3519. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  3520. if parseDateErr != nil {
  3521. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3522. return
  3523. }
  3524. adminInfo := this.GetMobileAdminUserInfo()
  3525. orgID := adminInfo.Org.Id
  3526. redis := service.RedisClient()
  3527. defer redis.Close()
  3528. key := "scheduals_" + schedualDate + "_" + strconv.FormatInt(orgID, 10)
  3529. scheduals, _ := service.MobileGetDialysisScheduals(orgID, date.Unix(), 0)
  3530. if len(scheduals) > 0 {
  3531. //缓存数据
  3532. scheduals_json, err := json.Marshal(scheduals)
  3533. if err == nil {
  3534. redis.Set(key, scheduals_json, time.Second*30)
  3535. }
  3536. }
  3537. this.ServeSuccessJSON(map[string]interface{}{
  3538. "scheduals": scheduals,
  3539. })
  3540. }
  3541. func (this *DialysisAPIController) GetLastOrNextDoctorAdvice() {
  3542. change_type, _ := this.GetInt64("type", 0)
  3543. record_date := this.GetString("record_time")
  3544. patient_id, _ := this.GetInt64("patient_id", 0)
  3545. timeLayout := "2006-01-02"
  3546. loc, _ := time.LoadLocation("Local")
  3547. theAdviceRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3548. record_time := theAdviceRecordTime.Unix()
  3549. adminUserInfo := this.GetMobileAdminUserInfo()
  3550. advices, sch, err := service.GetDoctorAdviceByType(change_type, record_time, adminUserInfo.Org.Id, patient_id)
  3551. if err == nil {
  3552. if len(advices) == 0 {
  3553. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDoctorAdviceEmpty)
  3554. return
  3555. } else {
  3556. this.ServeSuccessJSON(map[string]interface{}{
  3557. "advices": advices,
  3558. "schedule": sch,
  3559. })
  3560. return
  3561. }
  3562. } else {
  3563. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3564. return
  3565. }
  3566. }
  3567. func (c *DialysisAPIController) CreateConsumables() {
  3568. record_date := c.GetString("record_time")
  3569. patient_id, _ := c.GetInt64("patient_id", 0)
  3570. active, _ := c.GetInt64("active")
  3571. adminUser := c.GetMobileAdminUserInfo()
  3572. timeLayout := "2006-01-02"
  3573. loc, _ := time.LoadLocation("Local")
  3574. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3575. record_time := theRecordTime.Unix()
  3576. dataBody := make(map[string]interface{}, 0)
  3577. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  3578. if err != nil {
  3579. utils.ErrorLog(err.Error())
  3580. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3581. return
  3582. }
  3583. houseConfig, _ := service.GetAllStoreHouseConfig(adminUser.Org.Id)
  3584. var beforePrepares []*models.DialysisBeforePrepareGoods
  3585. var newBeforePrepares []*models.NewDialysisBeforePrepareGoods
  3586. var dialysisBefor []*models.DialysisBeforePrepare
  3587. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  3588. goods, _ := dataBody["goods"].([]interface{})
  3589. if len(goods) > 0 {
  3590. for _, item := range goods {
  3591. items := item.(map[string]interface{})
  3592. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  3593. utils.ErrorLog("good_id")
  3594. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3595. return
  3596. }
  3597. good_id := int64(items["good_id"].(float64))
  3598. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  3599. utils.ErrorLog("good_type_id")
  3600. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3601. return
  3602. }
  3603. good_type_id := int64(items["good_type_id"].(float64))
  3604. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  3605. utils.ErrorLog("count")
  3606. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3607. return
  3608. }
  3609. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3610. commdity_code := items["commdity_code"].(string)
  3611. fmt.Println("commdity", commdity_code)
  3612. prepareGoods := &models.DialysisBeforePrepareGoods{
  3613. GoodTypeId: good_type_id,
  3614. GoodId: good_id,
  3615. Count: count,
  3616. StorehouseId: houseConfig.StorehouseOutInfo,
  3617. }
  3618. beforePrepares = append(beforePrepares, prepareGoods)
  3619. newPrepareGoods := &models.NewDialysisBeforePrepareGoods{
  3620. GoodTypeId: good_type_id,
  3621. GoodId: good_id,
  3622. Count: count,
  3623. StorehouseId: houseConfig.StorehouseOutInfo,
  3624. }
  3625. newBeforePrepares = append(newBeforePrepares, newPrepareGoods)
  3626. prepare := &models.DialysisBeforePrepare{
  3627. GoodTypeId: good_type_id,
  3628. GoodId: good_id,
  3629. Count: count,
  3630. PatientId: patient_id,
  3631. RecordDate: record_time,
  3632. UserOrgId: adminUser.Org.Id,
  3633. Status: 1,
  3634. Ctime: time.Now().Unix(),
  3635. Creater: adminUser.AdminUser.Id,
  3636. CommdityCode: commdity_code,
  3637. StorehouseId: houseConfig.StorehouseOutInfo,
  3638. }
  3639. dialysisBefor = append(dialysisBefor, prepare)
  3640. }
  3641. }
  3642. //查询是否有库存
  3643. for _, item := range dialysisBefor {
  3644. _, err := service.FindFirstWarehousingInfoByStock(item.GoodId, item.GoodTypeId, houseConfig.StorehouseOutInfo)
  3645. if err == gorm.ErrRecordNotFound {
  3646. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3647. c.ServeSuccessJSON(map[string]interface{}{
  3648. "message": "1",
  3649. "good_name": goodObj.GoodName,
  3650. "specification_name": goodObj.SpecificationName,
  3651. })
  3652. return
  3653. }
  3654. if err != nil {
  3655. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3656. c.ServeSuccessJSON(map[string]interface{}{
  3657. "message": "1",
  3658. "good_name": goodObj.GoodName,
  3659. "specification_name": goodObj.SpecificationName,
  3660. })
  3661. return
  3662. }
  3663. }
  3664. //新增
  3665. if active == 1 && len(goods) > 0 {
  3666. for _, item := range dialysisBefor {
  3667. dialyPrepareOne := models.DialysisBeforePrepare{
  3668. GoodTypeId: item.GoodTypeId,
  3669. GoodId: item.GoodId,
  3670. PatientId: item.PatientId,
  3671. RecordDate: item.RecordDate,
  3672. UserOrgId: item.UserOrgId,
  3673. Count: item.Count,
  3674. Ctime: time.Now().Unix(),
  3675. Creater: item.Creater,
  3676. CommdityCode: item.CommdityCode,
  3677. Status: 1,
  3678. StorehouseId: houseConfig.StorehouseOutInfo,
  3679. }
  3680. //先清除再插入
  3681. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3682. err = service.CreateDialysisBeforePrepareOne(&dialyPrepareOne)
  3683. //查询默认仓库
  3684. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminUser.Org.Id)
  3685. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminUser.Org.Id)
  3686. var total_count int64
  3687. for _, it := range stockList {
  3688. total_count += it.StockCount
  3689. }
  3690. //基础库插入数据
  3691. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminUser.Org.Id)
  3692. //更新库存
  3693. goodList, _ := service.GetSumGoodList(adminUser.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  3694. var flush_count int64
  3695. for _, it := range goodList {
  3696. flush_count += it.StockCount
  3697. }
  3698. service.UpdateSumGood(adminUser.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  3699. }
  3700. if err == nil {
  3701. c.ServeSuccessJSON(map[string]interface{}{
  3702. "msg": "保存成功",
  3703. "message": "2",
  3704. })
  3705. return
  3706. } else {
  3707. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3708. return
  3709. }
  3710. }
  3711. if len(beforePrepares) > 0 && active == 2 {
  3712. for _, item := range beforePrepares {
  3713. //1.查看该患者该耗材型号最后一次出库数量
  3714. goodInfo, _ := service.GetLastGoodListByPatientId(record_time, patient_id, item.GoodId, item.GoodTypeId)
  3715. //判断当前出库数量和最后一次出库数量的大小
  3716. //如果当前出库数量小于或等于最后一次出库数量 正常出库后 需要退库操作
  3717. if item.Count <= goodInfo.Count {
  3718. //退库
  3719. err = ConsumablesDeliveryTotalSeven(adminUser.Org.Id, patient_id, record_time, beforePrepares, adminUser.AdminUser.Id, item.Count)
  3720. //查询今日出库数据
  3721. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminUser.Org.Id, patient_id, record_time)
  3722. for _, it := range list {
  3723. prepare := models.DialysisBeforePrepare{
  3724. UserOrgId: it.OrgId,
  3725. PatientId: patient_id,
  3726. RecordDate: it.RecordTime,
  3727. GoodId: it.GoodId,
  3728. GoodTypeId: it.GoodTypeId,
  3729. Count: it.Count,
  3730. Ctime: time.Now().Unix(),
  3731. Creater: adminUser.AdminUser.Id,
  3732. Status: 1,
  3733. StorehouseId: houseConfig.StorehouseOutInfo,
  3734. }
  3735. //删除准备表数据
  3736. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3737. service.CreateDialysisBeforePrepareOne(&prepare)
  3738. }
  3739. }
  3740. var last_total int64
  3741. //如果当前出库数量大于 最后一次出库数量,那么则需要去查询当前批次耗材的库存是否足够
  3742. if item.Count >= goodInfo.Count {
  3743. //查询当前批次当前耗材最后一条出库数据
  3744. lastOutInfo, _ := service.GetLastWarehouOutInfoByPatientId(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3745. //计算当前出库和最后一次出库数据相差数据
  3746. last_total = item.Count - lastOutInfo.Count
  3747. //查询该批次剩余库存
  3748. lastInfo, _ := service.GetLastStockOut(lastOutInfo.WarehouseInfotId)
  3749. //比较剩余库存 和 当前相差的数量,库存剩余量大于则正常出库
  3750. if lastInfo.StockCount >= last_total {
  3751. err = ConsumablesDeliveryTotalSix(adminUser.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminUser.AdminUser.Id)
  3752. //查询今日出库数据
  3753. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminUser.Org.Id, patient_id, record_time)
  3754. for _, it := range list {
  3755. prepare := models.DialysisBeforePrepare{
  3756. UserOrgId: it.OrgId,
  3757. PatientId: patient_id,
  3758. RecordDate: it.RecordTime,
  3759. GoodId: it.GoodId,
  3760. GoodTypeId: it.GoodTypeId,
  3761. Count: it.Count,
  3762. Ctime: time.Now().Unix(),
  3763. Creater: adminUser.AdminUser.Id,
  3764. Status: 1,
  3765. StorehouseId: houseConfig.StorehouseOutInfo,
  3766. }
  3767. //删除准备表数据
  3768. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3769. service.CreateDialysisBeforePrepareOne(&prepare)
  3770. //查询默认仓库
  3771. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminUser.Org.Id)
  3772. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminUser.Org.Id)
  3773. var total_count int64
  3774. for _, it := range stockList {
  3775. total_count += it.StockCount
  3776. }
  3777. //基础库插入数据
  3778. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminUser.Org.Id)
  3779. goodList, _ := service.GetSumGoodList(adminUser.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  3780. var flush_count int64
  3781. for _, it := range goodList {
  3782. flush_count += it.StockCount
  3783. }
  3784. service.UpdateSumGood(adminUser.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  3785. }
  3786. }
  3787. //如果库存不够,则出库到下一个批次
  3788. if lastInfo.StockCount < last_total {
  3789. err = ConsumablesDeliveryTotalSix(adminUser.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminUser.AdminUser.Id)
  3790. //查询今日出库数据
  3791. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminUser.Org.Id, patient_id, record_time)
  3792. for _, it := range list {
  3793. prepare := models.DialysisBeforePrepare{
  3794. UserOrgId: it.OrgId,
  3795. PatientId: patient_id,
  3796. RecordDate: it.RecordTime,
  3797. GoodId: it.GoodId,
  3798. GoodTypeId: it.GoodTypeId,
  3799. Count: it.Count,
  3800. Ctime: time.Now().Unix(),
  3801. Creater: adminUser.AdminUser.Id,
  3802. Status: 1,
  3803. StorehouseId: houseConfig.StorehouseOutInfo,
  3804. }
  3805. //删除准备表数据
  3806. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3807. service.CreateDialysisBeforePrepareOne(&prepare)
  3808. //查询默认仓库
  3809. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminUser.Org.Id)
  3810. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminUser.Org.Id)
  3811. var total_count int64
  3812. for _, it := range stockList {
  3813. total_count += it.StockCount
  3814. }
  3815. //基础库插入数据
  3816. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminUser.Org.Id)
  3817. goodList, _ := service.GetSumGoodList(adminUser.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  3818. var flush_count int64
  3819. for _, it := range goodList {
  3820. flush_count += it.StockCount
  3821. }
  3822. service.UpdateSumGood(adminUser.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  3823. }
  3824. if err != nil {
  3825. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3826. c.ServeSuccessJSON(map[string]interface{}{
  3827. "message": "1",
  3828. "good_name": goodObj.GoodName,
  3829. "specification_name": goodObj.SpecificationName,
  3830. })
  3831. return
  3832. }
  3833. }
  3834. }
  3835. if err != nil {
  3836. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3837. c.ServeSuccessJSON(map[string]interface{}{
  3838. "message": "1",
  3839. "good_name": goodObj.GoodName,
  3840. "specification_name": goodObj.SpecificationName,
  3841. })
  3842. return
  3843. }
  3844. }
  3845. }
  3846. }
  3847. var errs error
  3848. if errs == nil {
  3849. c.ServeSuccessJSON(map[string]interface{}{
  3850. "msg": "提交成功",
  3851. "message": "2",
  3852. "good_name": "",
  3853. "specification_name": "",
  3854. })
  3855. return
  3856. } else {
  3857. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3858. return
  3859. }
  3860. }
  3861. func (c *DialysisAPIController) CreateStockOutInfo() {
  3862. patient_id, _ := c.GetInt64("patient_id", 0)
  3863. record_date := c.GetString("record_time")
  3864. if patient_id <= 0 {
  3865. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3866. return
  3867. }
  3868. adminInfo := c.GetMobileAdminUserInfo()
  3869. creator := c.GetMobileAdminUserInfo().AdminUser.Id
  3870. timeLayout := "2006-01-02"
  3871. loc, _ := time.LoadLocation("Local")
  3872. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3873. record_time := theRecordTime.Unix()
  3874. consumables, _ := service.FindConsumablesByDate(adminInfo.Org.Id, patient_id, record_time)
  3875. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  3876. //去重
  3877. consumables = RemoveRepeatedGood(consumables)
  3878. if record.IsOpen == 1 {
  3879. houseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  3880. //查询是否有库存
  3881. for _, item := range consumables {
  3882. warehouse, _ := service.FindFirstWarehousingInfoByStockTwo(item.GoodId, item.GoodTypeId, houseConfig.StorehouseOutInfo)
  3883. if item.Count > warehouse.Count {
  3884. goodErrcode := models.XtGoodErrcode{
  3885. UserOrgId: item.UserOrgId,
  3886. Errcode: "自动出库库存不足",
  3887. GoodId: item.GoodId,
  3888. Status: 1,
  3889. Ctime: time.Now().Unix(),
  3890. Mtime: 0,
  3891. Count: 0,
  3892. StockCount: 0,
  3893. Creater: creator,
  3894. BatchNumberId: warehouse.ID,
  3895. WarehouseOutId: 0,
  3896. }
  3897. service.CreateGoodErrcode(goodErrcode)
  3898. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3899. c.ServeSuccessJSON(map[string]interface{}{
  3900. "message": "1",
  3901. "good_name": goodObj.GoodName,
  3902. "specification_name": goodObj.SpecificationName,
  3903. })
  3904. return
  3905. }
  3906. }
  3907. //查询是否有出库单
  3908. out, err := service.FindStockOutByIsSys(adminInfo.Org.Id, 1, record_time)
  3909. if err == gorm.ErrRecordNotFound {
  3910. //没有记录,则创建出库单
  3911. timeStr := time.Now().Format("2006-01-02")
  3912. timeArr := strings.Split(timeStr, "-")
  3913. total, _ := service.FindAllWarehouseOut(adminInfo.Org.Id)
  3914. total = total + 1
  3915. warehousing_out_order := strconv.FormatInt(adminInfo.Org.Id, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  3916. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  3917. number = number + total
  3918. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  3919. creater := adminInfo.AdminUser.Id
  3920. warehouseOut := models.WarehouseOut{
  3921. WarehouseOutOrderNumber: warehousing_out_order,
  3922. OperationTime: time.Now().Unix(),
  3923. OrgId: adminInfo.Org.Id,
  3924. Creater: creater,
  3925. Ctime: time.Now().Unix(),
  3926. Status: 1,
  3927. WarehouseOutTime: record_time,
  3928. Dealer: 0,
  3929. Manufacturer: 0,
  3930. Type: 1,
  3931. IsSys: 1,
  3932. StorehouseId: houseConfig.StorehouseOutInfo,
  3933. IsCheck: 1,
  3934. }
  3935. err := service.AddSigleWarehouseOut(&warehouseOut)
  3936. if err != nil {
  3937. goodErrcode := models.XtGoodErrcode{
  3938. UserOrgId: adminInfo.Org.Id,
  3939. Errcode: "创建出库单失败",
  3940. GoodId: 0,
  3941. Status: 1,
  3942. Ctime: time.Now().Unix(),
  3943. Mtime: 0,
  3944. Count: 0,
  3945. StockCount: 0,
  3946. Creater: creator,
  3947. BatchNumberId: 0,
  3948. WarehouseOutId: 0,
  3949. }
  3950. service.CreateGoodErrcode(goodErrcode)
  3951. utils.TraceLog("创建出库单失败 err = %v", err)
  3952. } else {
  3953. for _, item := range consumables {
  3954. //出库
  3955. err := service.ConsumablesGoodDelivery(item.UserOrgId, patient_id, record_time, item, &warehouseOut, item.Count)
  3956. if err == nil {
  3957. goodErrcode := models.XtGoodErrcode{
  3958. UserOrgId: adminInfo.Org.Id,
  3959. Errcode: "自动出库接口报错",
  3960. GoodId: 0,
  3961. Status: 1,
  3962. Ctime: time.Now().Unix(),
  3963. Mtime: 0,
  3964. Count: 0,
  3965. StockCount: 0,
  3966. Creater: creator,
  3967. BatchNumberId: 0,
  3968. WarehouseOutId: 0,
  3969. }
  3970. service.CreateGoodErrcode(goodErrcode)
  3971. utils.TraceLog("创建出库单失败 err = %v", err)
  3972. }
  3973. //查询
  3974. //出库数量相加
  3975. errs := service.ModifyGoodSumCount(houseConfig.StorehouseOutInfo, item.Count, item.UserOrgId, item.GoodId)
  3976. if errs != nil {
  3977. goodErrcode := models.XtGoodErrcode{
  3978. UserOrgId: item.UserOrgId,
  3979. Errcode: "创建剩余库存字段报错",
  3980. GoodId: item.GoodId,
  3981. Status: 1,
  3982. Ctime: time.Now().Unix(),
  3983. Mtime: 0,
  3984. Count: 0,
  3985. StockCount: 0,
  3986. Creater: creater,
  3987. BatchNumberId: 0,
  3988. WarehouseOutId: 0,
  3989. }
  3990. service.CreateGoodErrcode(goodErrcode)
  3991. }
  3992. }
  3993. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  3994. if len(list) == 0 {
  3995. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3996. return
  3997. }
  3998. for _, item := range list {
  3999. prepare := models.DialysisBeforePrepare{
  4000. UserOrgId: adminInfo.Org.Id,
  4001. PatientId: patient_id,
  4002. RecordDate: record_time,
  4003. GoodId: item.GoodId,
  4004. GoodTypeId: item.GoodTypeId,
  4005. Count: item.Count,
  4006. Creater: adminInfo.AdminUser.Id,
  4007. Status: 1,
  4008. Ctime: time.Now().Unix(),
  4009. StorehouseId: houseConfig.StorehouseOutInfo,
  4010. }
  4011. //清空准备表数据
  4012. err := service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  4013. if err != nil {
  4014. goodErrcode := models.XtGoodErrcode{
  4015. UserOrgId: item.OrgId,
  4016. Errcode: "自动出库清空准备表数据报错",
  4017. GoodId: item.GoodId,
  4018. Status: 1,
  4019. Ctime: time.Now().Unix(),
  4020. Mtime: 0,
  4021. Count: 0,
  4022. StockCount: 0,
  4023. Creater: creater,
  4024. BatchNumberId: 0,
  4025. WarehouseOutId: 0,
  4026. }
  4027. service.CreateGoodErrcode(goodErrcode)
  4028. }
  4029. errs := service.CreateDialysisBeforePrepareOne(&prepare)
  4030. if errs != nil {
  4031. goodErrcode := models.XtGoodErrcode{
  4032. UserOrgId: item.OrgId,
  4033. Errcode: "自动出库创建准备表数据报错",
  4034. GoodId: item.GoodId,
  4035. Status: 1,
  4036. Ctime: time.Now().Unix(),
  4037. Mtime: 0,
  4038. Count: 0,
  4039. StockCount: 0,
  4040. Creater: creater,
  4041. BatchNumberId: 0,
  4042. WarehouseOutId: 0,
  4043. }
  4044. service.CreateGoodErrcode(goodErrcode)
  4045. }
  4046. //查询默认仓库
  4047. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4048. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  4049. var total_count int64
  4050. for _, it := range stockList {
  4051. total_count += it.StockCount
  4052. }
  4053. //基础库插入数据
  4054. errcodes := service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminInfo.Org.Id)
  4055. if errcodes != nil {
  4056. goodErrcode := models.XtGoodErrcode{
  4057. UserOrgId: item.OrgId,
  4058. Errcode: "自动出库基础库插入数据",
  4059. GoodId: item.GoodId,
  4060. Status: 1,
  4061. Ctime: time.Now().Unix(),
  4062. Mtime: 0,
  4063. Count: 0,
  4064. StockCount: 0,
  4065. Creater: creater,
  4066. BatchNumberId: 0,
  4067. WarehouseOutId: 0,
  4068. }
  4069. service.CreateGoodErrcode(goodErrcode)
  4070. }
  4071. goodList, _ := service.GetSumGoodList(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  4072. var flush_count int64
  4073. for _, it := range goodList {
  4074. flush_count += it.StockCount
  4075. }
  4076. errsss := service.UpdateSumGood(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  4077. if errsss != nil {
  4078. goodErrcode := models.XtGoodErrcode{
  4079. UserOrgId: item.OrgId,
  4080. Errcode: "自动出库剩余库存更新数据",
  4081. GoodId: item.GoodId,
  4082. Status: 1,
  4083. Ctime: time.Now().Unix(),
  4084. Mtime: 0,
  4085. Count: 0,
  4086. StockCount: 0,
  4087. Creater: creater,
  4088. BatchNumberId: 0,
  4089. WarehouseOutId: 0,
  4090. }
  4091. service.CreateGoodErrcode(goodErrcode)
  4092. }
  4093. }
  4094. }
  4095. //
  4096. } else if err == nil {
  4097. for _, item := range consumables {
  4098. //出库
  4099. err := service.ConsumablesGoodDelivery(item.UserOrgId, patient_id, record_time, item, &out, item.Count)
  4100. if err != nil {
  4101. goodErrcode := models.XtGoodErrcode{
  4102. UserOrgId: adminInfo.Org.Id,
  4103. Errcode: "自动出库接口报错",
  4104. GoodId: 0,
  4105. Status: 1,
  4106. Ctime: time.Now().Unix(),
  4107. Mtime: 0,
  4108. Count: 0,
  4109. StockCount: 0,
  4110. Creater: creator,
  4111. BatchNumberId: 0,
  4112. WarehouseOutId: 0,
  4113. }
  4114. service.CreateGoodErrcode(goodErrcode)
  4115. }
  4116. //出库数量相加
  4117. errss := service.ModifyGoodSumCount(houseConfig.StorehouseOutInfo, item.Count, item.UserOrgId, item.GoodId)
  4118. if errss != nil {
  4119. goodErrcode := models.XtGoodErrcode{
  4120. UserOrgId: item.UserOrgId,
  4121. Errcode: "创建剩余库存字段报错",
  4122. GoodId: item.GoodId,
  4123. Status: 1,
  4124. Ctime: time.Now().Unix(),
  4125. Mtime: time.Now().Unix(),
  4126. Count: 0,
  4127. StockCount: 0,
  4128. Creater: item.Creater,
  4129. BatchNumberId: 0,
  4130. WarehouseOutId: 0,
  4131. }
  4132. service.CreateGoodErrcode(goodErrcode)
  4133. }
  4134. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  4135. if len(list) == 0 {
  4136. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4137. return
  4138. }
  4139. for _, item := range list {
  4140. prepare := models.DialysisBeforePrepare{
  4141. UserOrgId: adminInfo.Org.Id,
  4142. PatientId: patient_id,
  4143. RecordDate: record_time,
  4144. GoodId: item.GoodId,
  4145. GoodTypeId: item.GoodTypeId,
  4146. Count: item.Count,
  4147. Creater: adminInfo.AdminUser.Id,
  4148. Status: 1,
  4149. Ctime: time.Now().Unix(),
  4150. StorehouseId: houseConfig.StorehouseOutInfo,
  4151. }
  4152. //清空准备表数据
  4153. errs := service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  4154. if errs != nil {
  4155. goodErrcode := models.XtGoodErrcode{
  4156. UserOrgId: adminInfo.Org.Id,
  4157. Errcode: "自动出库清空准备表数据报错",
  4158. GoodId: 0,
  4159. Status: 1,
  4160. Ctime: time.Now().Unix(),
  4161. Mtime: 0,
  4162. Count: 0,
  4163. StockCount: 0,
  4164. Creater: creator,
  4165. BatchNumberId: 0,
  4166. WarehouseOutId: 0,
  4167. }
  4168. service.CreateGoodErrcode(goodErrcode)
  4169. }
  4170. errcodes := service.CreateDialysisBeforePrepareOne(&prepare)
  4171. if errcodes != nil {
  4172. goodErrcode := models.XtGoodErrcode{
  4173. UserOrgId: adminInfo.Org.Id,
  4174. Errcode: "自动出库创建准备表数据报错",
  4175. GoodId: 0,
  4176. Status: 1,
  4177. Ctime: time.Now().Unix(),
  4178. Mtime: 0,
  4179. Count: 0,
  4180. StockCount: 0,
  4181. Creater: creator,
  4182. BatchNumberId: 0,
  4183. WarehouseOutId: 0,
  4184. }
  4185. service.CreateGoodErrcode(goodErrcode)
  4186. }
  4187. //查询默认仓库
  4188. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4189. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  4190. var total_count int64
  4191. for _, it := range stockList {
  4192. total_count += it.StockCount
  4193. }
  4194. //基础库插入数据
  4195. errcodes = service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminInfo.Org.Id)
  4196. if errcodes != nil {
  4197. goodErrcode := models.XtGoodErrcode{
  4198. UserOrgId: adminInfo.Org.Id,
  4199. Errcode: "自动出库基础库插入数据报错",
  4200. GoodId: 0,
  4201. Status: 1,
  4202. Ctime: time.Now().Unix(),
  4203. Mtime: 0,
  4204. Count: 0,
  4205. StockCount: 0,
  4206. Creater: creator,
  4207. BatchNumberId: 0,
  4208. WarehouseOutId: 0,
  4209. }
  4210. service.CreateGoodErrcode(goodErrcode)
  4211. }
  4212. goodList, _ := service.GetSumGoodList(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  4213. var flush_count int64
  4214. for _, it := range goodList {
  4215. flush_count += it.StockCount
  4216. }
  4217. errss := service.UpdateSumGood(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  4218. creater := c.GetMobileAdminUserInfo().AdminUser.Id
  4219. if errss != nil {
  4220. goodErrcode := models.XtGoodErrcode{
  4221. UserOrgId: item.OrgId,
  4222. Errcode: "自动出库剩余库存更新数据",
  4223. GoodId: item.GoodId,
  4224. Status: 1,
  4225. Ctime: time.Now().Unix(),
  4226. Mtime: 0,
  4227. Count: 0,
  4228. StockCount: 0,
  4229. Creater: creater,
  4230. BatchNumberId: 0,
  4231. WarehouseOutId: 0,
  4232. }
  4233. service.CreateGoodErrcode(goodErrcode)
  4234. }
  4235. }
  4236. }
  4237. }
  4238. c.ServeSuccessJSON(map[string]interface{}{
  4239. "msg": "提交成功",
  4240. "message": "2",
  4241. "good_name": "",
  4242. "specification_name": "",
  4243. })
  4244. return
  4245. } else {
  4246. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeOpenStocktWrong)
  4247. return
  4248. }
  4249. }
  4250. func (c *DialysisAPIController) EditConsumables() {
  4251. patient_id, _ := c.GetInt64("patient_id", 0)
  4252. record_date := c.GetString("record_time")
  4253. if patient_id <= 0 {
  4254. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4255. return
  4256. }
  4257. adminInfo := c.GetMobileAdminUserInfo()
  4258. timeLayout := "2006-01-02"
  4259. loc, _ := time.LoadLocation("Local")
  4260. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  4261. record_time := theRecordTime.Unix()
  4262. dataBody := make(map[string]interface{}, 0)
  4263. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  4264. if err != nil {
  4265. utils.ErrorLog(err.Error())
  4266. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4267. return
  4268. }
  4269. houseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4270. var beforePrepares []*models.DialysisBeforePrepareGoods
  4271. var newBeforePrepares []*models.NewDialysisBeforePrepareGoods
  4272. //判断是否开启自动出库
  4273. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  4274. if record.IsOpen == 1 {
  4275. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  4276. goods, _ := dataBody["goods"].([]interface{})
  4277. if len(goods) > 0 {
  4278. for _, item := range goods {
  4279. items := item.(map[string]interface{})
  4280. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  4281. utils.ErrorLog("good_id")
  4282. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4283. return
  4284. }
  4285. good_id := int64(items["good_id"].(float64))
  4286. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  4287. utils.ErrorLog("good_type_id")
  4288. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4289. return
  4290. }
  4291. good_type_id := int64(items["good_type_id"].(float64))
  4292. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  4293. utils.ErrorLog("count")
  4294. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4295. return
  4296. }
  4297. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  4298. commdity_code := items["commdity_code"].(string)
  4299. fmt.Println(commdity_code)
  4300. prepareGoods := &models.DialysisBeforePrepareGoods{
  4301. GoodTypeId: good_type_id,
  4302. GoodId: good_id,
  4303. Count: count,
  4304. StorehouseId: houseConfig.StorehouseOutInfo,
  4305. }
  4306. beforePrepares = append(beforePrepares, prepareGoods)
  4307. newPrepareGoods := &models.NewDialysisBeforePrepareGoods{
  4308. GoodTypeId: good_type_id,
  4309. GoodId: good_id,
  4310. Count: count,
  4311. StorehouseId: houseConfig.StorehouseOutInfo,
  4312. }
  4313. newBeforePrepares = append(newBeforePrepares, newPrepareGoods)
  4314. }
  4315. for _, item := range beforePrepares {
  4316. //1.查看该患者该耗材型号最后一次出库数量
  4317. goodInfo, _ := service.GetLastGoodListByPatientIdOne(record_time, patient_id, item.GoodId, item.GoodTypeId)
  4318. //判断当前出库数量和最后一次出库数量的大小
  4319. //如果当前出库数量小于最后一次出库数量 正常出库后 需要退库操作
  4320. if item.Count < goodInfo.Count {
  4321. //退库
  4322. err = ConsumablesDeliveryTotalSeven(adminInfo.Org.Id, patient_id, record_time, beforePrepares, adminInfo.AdminUser.Id, item.Count)
  4323. //查询默认仓库
  4324. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4325. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  4326. var total_count int64
  4327. for _, it := range stockList {
  4328. total_count += it.StockCount
  4329. }
  4330. //基础库插入数据
  4331. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminInfo.Org.Id)
  4332. //更新剩余库存
  4333. goodList, _ := service.GetSumGoodList(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  4334. var flush_count int64
  4335. for _, it := range goodList {
  4336. flush_count += it.StockCount
  4337. }
  4338. service.UpdateSumGood(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  4339. break
  4340. }
  4341. var last_total int64
  4342. //如果当前出库数量大于 最后一次出库数量,那么则需要去查询当前批次耗材的库存是否足够
  4343. if item.Count > goodInfo.Count {
  4344. //计算当前出库和最后一次出库数据相差数据
  4345. last_total = item.Count - goodInfo.Count
  4346. //查询该批次剩余库存
  4347. lastInfo, _ := service.GetLastStockOut(goodInfo.WarehouseInfotId)
  4348. if lastInfo.StockCount == 0 {
  4349. //查询该耗材的总库存
  4350. wareinfo, _ := service.GetStockGoodCount(item.GoodId)
  4351. if wareinfo.StockCount == 0 {
  4352. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  4353. c.ServeSuccessJSON(map[string]interface{}{
  4354. "message": "1",
  4355. "good_name": goodObj.GoodName,
  4356. "specification_name": goodObj.SpecificationName,
  4357. })
  4358. return
  4359. }
  4360. }
  4361. //比较剩余库存 和 当前相差的数量,库存剩余量大于则正常出库
  4362. //查询该耗材的总库存
  4363. wareinfo, _ := service.GetStockGoodCount(item.GoodId)
  4364. // 如果库存差大于剩余库存则提示库存不足
  4365. if last_total > wareinfo.StockCount {
  4366. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  4367. c.ServeSuccessJSON(map[string]interface{}{
  4368. "message": "1",
  4369. "good_name": goodObj.GoodName,
  4370. "specification_name": goodObj.SpecificationName,
  4371. })
  4372. return
  4373. } else {
  4374. //出库
  4375. err = ConsumablesDeliveryTotalSix(adminInfo.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminInfo.AdminUser.Id)
  4376. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4377. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  4378. var total_count int64
  4379. for _, it := range stockList {
  4380. total_count += it.StockCount
  4381. }
  4382. //基础库插入数据
  4383. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminInfo.Org.Id)
  4384. //剩余库存
  4385. goodList, _ := service.GetSumGoodList(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  4386. var flush_count int64
  4387. for _, it := range goodList {
  4388. flush_count += it.StockCount
  4389. }
  4390. service.UpdateSumGood(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  4391. break
  4392. }
  4393. }
  4394. }
  4395. //查询今日出库数据
  4396. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  4397. for _, it := range list {
  4398. prepare := models.DialysisBeforePrepare{
  4399. UserOrgId: it.OrgId,
  4400. PatientId: patient_id,
  4401. RecordDate: it.RecordTime,
  4402. GoodId: it.GoodId,
  4403. GoodTypeId: it.GoodTypeId,
  4404. Count: it.Count,
  4405. Ctime: time.Now().Unix(),
  4406. Creater: adminInfo.AdminUser.Id,
  4407. Status: 1,
  4408. StorehouseId: houseConfig.StorehouseOutInfo,
  4409. }
  4410. //删除准备表数据
  4411. service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, it.GoodId, it.GoodTypeId)
  4412. service.CreateDialysisBeforePrepareOne(&prepare)
  4413. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4414. stockList, _ := service.GetStockCountByGoodId(it.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  4415. var total_count int64
  4416. for _, it := range stockList {
  4417. total_count += it.StockCount
  4418. }
  4419. //基础库插入数据
  4420. service.UpdateGoodInfoReduceSumCount(it.GoodId, total_count, adminInfo.Org.Id)
  4421. goodList, _ := service.GetSumGoodList(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, it.GoodId)
  4422. var flush_count int64
  4423. for _, it := range goodList {
  4424. flush_count += it.StockCount
  4425. }
  4426. service.UpdateSumGood(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, it.GoodId, flush_count)
  4427. if err != nil {
  4428. goodObj, _ := service.GetGoodInformationByGoodId(it.GoodId)
  4429. c.ServeSuccessJSON(map[string]interface{}{
  4430. "message": "2",
  4431. "good_name": goodObj.GoodName,
  4432. "specification_name": goodObj.SpecificationName,
  4433. })
  4434. return
  4435. }
  4436. }
  4437. }
  4438. }
  4439. //更新自动出库的地方
  4440. var errs error
  4441. if errs == nil {
  4442. c.ServeSuccessJSON(map[string]interface{}{
  4443. "msg": "修改成功",
  4444. "message": "2",
  4445. "good_name": "",
  4446. "specification_name": "",
  4447. })
  4448. return
  4449. } else {
  4450. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4451. return
  4452. }
  4453. }
  4454. }
  4455. func (c *DialysisAPIController) GetDialysisGoods() {
  4456. schedualDate := c.GetString("schedule_date")
  4457. schedule_type, _ := c.GetInt64("schedule_type")
  4458. partition_id, _ := c.GetInt64("partition_id")
  4459. page, _ := c.GetInt("page")
  4460. patient_id, _ := c.GetInt64("patient_id")
  4461. schedualEndDate := int64(0)
  4462. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  4463. if parseDateErr != nil && len(schedualDate) != 0 {
  4464. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4465. return
  4466. }
  4467. endDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", schedualDate+" 23:59:59")
  4468. if parseDateErr != nil && len(schedualDate) != 0 {
  4469. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4470. return
  4471. }
  4472. schedualEndDate = endDate.Unix()
  4473. adminUser := c.GetMobileAdminUserInfo()
  4474. _, err := service.FindStockOutByIsSys(adminUser.Org.Id, 1, date.Unix())
  4475. goodTypes, _ := service.FindAllGoodType(adminUser.Org.Id)
  4476. project, _ := service.GetHisPrescriptionProject(adminUser.Org.Id, patient_id, date.Unix())
  4477. //获取当天该病人的透析处方
  4478. prescribe, parseDateErr := service.GetDialysisPrescribe(adminUser.Org.Id, patient_id, date.Unix())
  4479. good_info, _ := service.FindAllGoodInfo(adminUser.Org.Id)
  4480. if err == gorm.ErrRecordNotFound {
  4481. dialysisGoods, _, total := service.MobileGetDialysisGoods(adminUser.Org.Id, date.Unix(), schedule_type, partition_id, page, 0, patient_id, "", schedualEndDate)
  4482. warehouseOutList, _ := service.GetAllWarehouseOutSumList(patient_id, adminUser.Org.Id, date.Unix())
  4483. if patient_id != 0 {
  4484. for _, item := range dialysisGoods { //获取当天排班的每个患者的最后日期的库存使用情况
  4485. goodUser, _ := service.GetLastDialysisGoods(item.PatientId, adminUser.Org.Id, date.Unix())
  4486. lastGoodUserDetial, _ := service.GetLastDialysisBeforePrepare(item.PatientId, adminUser.Org.Id, date.Unix())
  4487. //获取患者总的出库数据
  4488. item.LastAutomaticReduceDetail = goodUser
  4489. item.LastDialysisBeforePrepare = lastGoodUserDetial
  4490. item.Project = project
  4491. }
  4492. }
  4493. c.ServeSuccessJSON(map[string]interface{}{
  4494. "dialysis_goods": dialysisGoods,
  4495. "good_type": goodTypes,
  4496. "total": total,
  4497. "prescribe": prescribe,
  4498. "good_info": good_info,
  4499. "warehouseOutList": warehouseOutList,
  4500. })
  4501. return
  4502. } else if err == nil {
  4503. //获取当天排班的每个患者的库存使用情况
  4504. dialysisGoods, err, total := service.MobileGetDialysisGoods(adminUser.Org.Id, date.Unix(), schedule_type, partition_id, page, 0, patient_id, "", schedualEndDate)
  4505. //获取患者总的出库数据
  4506. warehouseOutList, _ := service.GetAllWarehouseOutSumList(patient_id, adminUser.Org.Id, date.Unix())
  4507. if patient_id != 0 {
  4508. for _, item := range dialysisGoods { //获取当天排班的每个患者的最后日期的库存使用情况
  4509. goodUser, _ := service.GetLastDialysisGoods(item.PatientId, adminUser.Org.Id, date.Unix())
  4510. lastGoodUserDetial, _ := service.GetLastDialysisBeforePrepare(item.PatientId, adminUser.Org.Id, date.Unix())
  4511. item.Project = project
  4512. item.LastAutomaticReduceDetail = goodUser
  4513. item.LastDialysisBeforePrepare = lastGoodUserDetial
  4514. }
  4515. }
  4516. if err == nil {
  4517. c.ServeSuccessJSON(map[string]interface{}{
  4518. "dialysis_goods": dialysisGoods,
  4519. "good_type": goodTypes,
  4520. "total": total,
  4521. "prescribe": prescribe,
  4522. "good_info": good_info,
  4523. "project": project,
  4524. "warehouseOutList": warehouseOutList,
  4525. })
  4526. return
  4527. } else {
  4528. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4529. return
  4530. }
  4531. } else if err != nil {
  4532. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4533. return
  4534. }
  4535. }
  4536. func (c *DialysisAPIController) GetDialysisGoodsStatistics() {
  4537. start_time := c.GetString("start_time")
  4538. end_time := c.GetString("end_time")
  4539. timeLayout := "2006-01-02"
  4540. loc, _ := time.LoadLocation("Local")
  4541. var theStartTime int64
  4542. if len(start_time) > 0 {
  4543. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  4544. if err != nil {
  4545. utils.ErrorLog(err.Error())
  4546. }
  4547. theStartTime = theTime.Unix()
  4548. }
  4549. var theEndtTime int64
  4550. if len(end_time) > 0 {
  4551. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
  4552. if err != nil {
  4553. utils.ErrorLog(err.Error())
  4554. }
  4555. theEndtTime = theTime.Unix()
  4556. }
  4557. adminUser := c.GetMobileAdminUserInfo()
  4558. outInfo, err := service.MobileGetGoodsStatistics(adminUser.Org.Id, theStartTime, theEndtTime)
  4559. stockCount, err := service.GetOutStockTotalCountOne(theStartTime, theEndtTime, adminUser.Org.Id)
  4560. if err == nil {
  4561. c.ServeSuccessJSON(map[string]interface{}{
  4562. "stock_out": outInfo,
  4563. "stockCount": stockCount,
  4564. })
  4565. return
  4566. } else {
  4567. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4568. return
  4569. }
  4570. }
  4571. func (c *DialysisAPIController) GetStockInGoodInfo() {
  4572. patient_id, _ := c.GetInt64("patient_id", 0)
  4573. record_time := c.GetString("record_time")
  4574. adminUser := c.GetMobileAdminUserInfo()
  4575. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", record_time)
  4576. if parseDateErr != nil && len(record_time) != 0 {
  4577. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4578. return
  4579. }
  4580. goodTypes, _ := service.FindAllGoodTypeOne(adminUser.Org.Id)
  4581. good_info, _ := service.FindAllGoodInfo(adminUser.Org.Id)
  4582. goodUser, _ := service.GetAllStockOutUserDetail(patient_id, adminUser.Org.Id, date.Unix())
  4583. lastGoodUserDetial, _ := service.GetLastDialysisGoods(patient_id, adminUser.Org.Id, date.Unix())
  4584. project, _ := service.GetHisPrescriptionProject(adminUser.Org.Id, patient_id, date.Unix())
  4585. //获取今日患者的透析处方参数
  4586. prescribe, parseDateErr := service.GetDialysisPrescribe(adminUser.Org.Id, patient_id, date.Unix())
  4587. outInfo, _ := service.GetGoodWarehouseOutInfo(adminUser.Org.Id, patient_id, date.Unix())
  4588. c.ServeSuccessJSON(map[string]interface{}{
  4589. "good_type": goodTypes,
  4590. "good_user": goodUser,
  4591. "good_info": good_info,
  4592. "last_good_user": lastGoodUserDetial,
  4593. "project": project,
  4594. "prescription": prescribe,
  4595. "outInfo": outInfo,
  4596. })
  4597. return
  4598. }
  4599. func (c *DialysisAPIController) CreateOtherStockOutInfo() {
  4600. patient_id, _ := c.GetInt64("patient_id", 0)
  4601. record_date := c.GetString("record_time")
  4602. timeLayout := "2006-01-02"
  4603. loc, _ := time.LoadLocation("Local")
  4604. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  4605. record_time := theRecordTime.Unix()
  4606. adminInfo := c.GetMobileAdminUserInfo()
  4607. dataBody := make(map[string]interface{}, 0)
  4608. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  4609. if err != nil {
  4610. utils.ErrorLog(err.Error())
  4611. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4612. return
  4613. }
  4614. houseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4615. var beforePrepares []*models.DialysisBeforePrepareGoods
  4616. var newBeforePrepares []*models.NewDialysisBeforePrepareGoods
  4617. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  4618. goods, _ := dataBody["goods"].([]interface{})
  4619. if len(goods) > 0 {
  4620. for _, item := range goods {
  4621. items := item.(map[string]interface{})
  4622. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  4623. utils.ErrorLog("good_id")
  4624. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4625. return
  4626. }
  4627. good_id := int64(items["good_id"].(float64))
  4628. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  4629. utils.ErrorLog("good_type_id")
  4630. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4631. return
  4632. }
  4633. good_type_id := int64(items["good_type_id"].(float64))
  4634. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  4635. utils.ErrorLog("count")
  4636. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4637. return
  4638. }
  4639. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  4640. if items["project_id"] == nil || reflect.TypeOf(items["project_id"]).String() != "float64" {
  4641. utils.ErrorLog("project_id")
  4642. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4643. return
  4644. }
  4645. project_id := int64(items["project_id"].(float64))
  4646. prepare := &models.DialysisBeforePrepareGoods{
  4647. GoodId: good_id,
  4648. GoodTypeId: good_type_id,
  4649. Count: count,
  4650. ProjectId: project_id,
  4651. StorehouseId: houseConfig.StorehouseOutInfo,
  4652. }
  4653. beforePrepares = append(beforePrepares, prepare)
  4654. newPrepare := &models.NewDialysisBeforePrepareGoods{
  4655. GoodId: good_id,
  4656. GoodTypeId: good_type_id,
  4657. Count: count,
  4658. ProjectId: project_id,
  4659. StorehouseId: houseConfig.StorehouseOutInfo,
  4660. }
  4661. newBeforePrepares = append(newBeforePrepares, newPrepare)
  4662. }
  4663. }
  4664. }
  4665. //查询是否有库存
  4666. for _, item := range beforePrepares {
  4667. storeConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4668. warehouse, _ := service.FindFirstWarehousingInfoByStockTwo(item.GoodId, item.GoodTypeId, storeConfig.StorehouseOutInfo)
  4669. if item.Count > warehouse.Count {
  4670. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  4671. c.ServeSuccessJSON(map[string]interface{}{
  4672. "message": "1",
  4673. "good_name": goodObj.GoodName,
  4674. "specification_name": goodObj.SpecificationName,
  4675. })
  4676. return
  4677. }
  4678. }
  4679. //出库逻辑
  4680. err = service.ConsumablesDeliveryTotal(adminInfo.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminInfo.AdminUser.Id)
  4681. if err != nil {
  4682. utils.ErrorLog(err.Error())
  4683. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4684. return
  4685. }
  4686. //查询当天出库的数据
  4687. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  4688. for _, item := range list {
  4689. prepare := models.DialysisBeforePrepare{
  4690. UserOrgId: item.OrgId,
  4691. PatientId: item.PatientId,
  4692. RecordDate: item.RecordTime,
  4693. GoodId: item.GoodId,
  4694. GoodTypeId: item.GoodTypeId,
  4695. Count: item.Count,
  4696. Creater: adminInfo.AdminUser.Id,
  4697. Status: 1,
  4698. Ctime: time.Now().Unix(),
  4699. ProjectId: item.ProjectId,
  4700. StorehouseId: houseConfig.StorehouseOutInfo,
  4701. }
  4702. //清空准备表的数据
  4703. err = service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  4704. //插入准备表数据
  4705. service.CreateDialysisBeforePrepareOne(&prepare)
  4706. //查询默认仓库
  4707. //查询默认仓库
  4708. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4709. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  4710. var total_count int64
  4711. for _, it := range stockList {
  4712. total_count += it.StockCount
  4713. }
  4714. //基础库插入数据
  4715. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminInfo.Org.Id)
  4716. ////更新剩余库存
  4717. goodList, _ := service.GetSumGoodList(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  4718. var flush_count int64
  4719. for _, it := range goodList {
  4720. flush_count += it.StockCount
  4721. }
  4722. errs := service.UpdateSumGood(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  4723. if errs != nil {
  4724. goodErrcode := models.XtGoodErrcode{
  4725. UserOrgId: item.OrgId,
  4726. Errcode: "手动出库更新剩余出库失败",
  4727. GoodId: item.GoodId,
  4728. Status: 1,
  4729. Ctime: time.Now().Unix(),
  4730. Mtime: 0,
  4731. Count: 0,
  4732. StockCount: 0,
  4733. Creater: adminInfo.AdminUser.Id,
  4734. BatchNumberId: 0,
  4735. WarehouseOutId: 0,
  4736. }
  4737. service.CreateGoodErrcode(goodErrcode)
  4738. }
  4739. }
  4740. //更新自动出库的地方
  4741. var errs error
  4742. if errs == nil {
  4743. c.ServeSuccessJSON(map[string]interface{}{
  4744. "msg": "修改成功",
  4745. "message": "2",
  4746. "good_name": "",
  4747. "specification_name": "",
  4748. })
  4749. return
  4750. } else {
  4751. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4752. return
  4753. }
  4754. }
  4755. func RemoveRepeatedGood(arr []*models.DialysisBeforePrepare) (newArr []*models.DialysisBeforePrepare) {
  4756. newArr = make([]*models.DialysisBeforePrepare, 0)
  4757. for i := 0; i < len(arr); i++ {
  4758. repeat := false
  4759. for j := i + 1; j < len(arr); j++ {
  4760. if arr[i].GoodId == arr[j].GoodId && arr[i].GoodTypeId == arr[j].GoodTypeId {
  4761. repeat = true
  4762. break
  4763. }
  4764. }
  4765. if !repeat {
  4766. newArr = append(newArr, arr[i])
  4767. }
  4768. }
  4769. return
  4770. }
  4771. func (c *DialysisAPIController) GetAllDrug() {
  4772. patient_id, _ := c.GetInt64("patient_id", 0)
  4773. adminInfo := c.GetMobileAdminUserInfo()
  4774. _, drugStockConfig := service.FindDrugStockAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  4775. privateDrugConfig, _ := service.GetDrugSetByUserOrgId(adminInfo.Org.Id)
  4776. drugList, _ := service.GetAllBaseDrugLibList(adminInfo.Org.Id)
  4777. privateDrugList, _ := service.GetPrivateDrugList(patient_id, adminInfo.Org.Id)
  4778. c.ServeSuccessJSON(map[string]interface{}{
  4779. "base_drug_config": drugStockConfig,
  4780. "private_drug_config": privateDrugConfig,
  4781. "base_drug_list": drugList,
  4782. "private_drug_list": privateDrugList,
  4783. })
  4784. }
  4785. func RemoveRepeatedGoodTwo(arr []*models.DialysisBeforePrepare) (newArr []*models.DialysisBeforePrepare) {
  4786. newArr = make([]*models.DialysisBeforePrepare, 0)
  4787. for i := 0; i < len(arr); i++ {
  4788. repeat := false
  4789. for j := i + 1; j < len(arr); j++ {
  4790. if arr[i].GoodId == arr[j].GoodId {
  4791. repeat = true
  4792. break
  4793. }
  4794. }
  4795. if !repeat {
  4796. newArr = append(newArr, arr[i])
  4797. }
  4798. }
  4799. return
  4800. }
  4801. func (c *DialysisAPIController) GetDepartment() {
  4802. adminInfo := c.GetMobileAdminUserInfo()
  4803. departments, err := service.GetAllDepartMent(adminInfo.Org.Id)
  4804. if err == nil {
  4805. c.ServeSuccessJSON(map[string]interface{}{
  4806. "departments": departments,
  4807. })
  4808. } else {
  4809. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4810. return
  4811. }
  4812. }
  4813. func (c *DialysisAPIController) GetMobilePrintStockGood() {
  4814. types, _ := c.GetInt("type", 0)
  4815. start_time := c.GetString("start_time")
  4816. end_time := c.GetString("end_time")
  4817. orgId := c.GetMobileAdminUserInfo().Org.Id
  4818. timeLayout := "2006-01-02"
  4819. loc, _ := time.LoadLocation("Local")
  4820. var startTime int64
  4821. if len(start_time) > 0 {
  4822. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  4823. if err != nil {
  4824. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4825. return
  4826. }
  4827. startTime = theTime.Unix()
  4828. }
  4829. var endTime int64
  4830. if len(end_time) > 0 {
  4831. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
  4832. if err != nil {
  4833. utils.ErrorLog(err.Error())
  4834. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4835. return
  4836. }
  4837. endTime = theTime.Unix()
  4838. }
  4839. list, err := service.FindPrintStockGoodInfoByType(types, startTime, endTime, orgId)
  4840. stockTotal, err := service.GetOutStockTotalCountTwo(startTime, endTime, orgId)
  4841. if err != nil {
  4842. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  4843. } else {
  4844. c.ServeSuccessJSON(map[string]interface{}{
  4845. "list": list,
  4846. "type": types,
  4847. "stockTotal": stockTotal,
  4848. })
  4849. }
  4850. }
  4851. func (c *DialysisAPIController) BatchDeleteMonitor() {
  4852. ids := c.GetString("ids")
  4853. //patient_id, _ := c.GetInt64("patient_id")
  4854. //monitoring_date, _ := c.GetInt64("monitoring_date")
  4855. idArray := strings.Split(ids, ",")
  4856. err := service.BatchDeleteMonitor(idArray)
  4857. fmt.Print("err", err)
  4858. //orgid := c.GetMobileAdminUserInfo().Org.Id
  4859. //redis := service.RedisClient()
  4860. //key := strconv.FormatInt(orgid, 10) + ":" + ":monitor_record_list_all"
  4861. //redis.Set(key, "", time.Second)
  4862. //keyOne := strconv.FormatInt(orgid, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(monitoring_date, 10) + ":monitor_records"
  4863. //redis.Set(keyOne, "", time.Second)
  4864. //fmt.Println("keyo呢32332322332332232332",keyOne)
  4865. //redis.Close()
  4866. c.ServeSuccessJSON(map[string]interface{}{
  4867. "msg": "批量删除成功",
  4868. })
  4869. return
  4870. }
  4871. func (c *DialysisAPIController) GetPatientDialysisRecordList() {
  4872. id, _ := c.GetInt64("id")
  4873. timeLayout := "2006-01-02"
  4874. loc, _ := time.LoadLocation("Local")
  4875. start_time := time.Now().Format("2006-01-02")
  4876. startime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  4877. nowTime := time.Now()
  4878. endTime := nowTime.AddDate(-2, 0, 0)
  4879. endTimes := endTime.Format("2006-01-02")
  4880. endtime, _ := time.ParseInLocation(timeLayout+" 15:04:05", endTimes+" 00:00:00", loc)
  4881. list, _ := service.GetPatientDialysisRecordList(id, endtime.Unix(), startime.Unix())
  4882. fmt.Println("endtime232332322332322323232332", endTime.Unix())
  4883. c.ServeSuccessJSON(map[string]interface{}{
  4884. "list": list,
  4885. })
  4886. return
  4887. }
  4888. func (c *DialysisAPIController) BathDeleteAdviceList() {
  4889. dataBody := make(map[string]interface{}, 0)
  4890. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  4891. ids := c.GetString("ids")
  4892. idArray := strings.Split(ids, ",")
  4893. origin, _ := c.GetInt64("origin")
  4894. if origin == 1 {
  4895. err = service.BatchDeleteAdvice(idArray)
  4896. fmt.Print("err", err)
  4897. c.ServeSuccessJSON(map[string]interface{}{
  4898. "msg": "批量删除成功",
  4899. })
  4900. return
  4901. }
  4902. if origin == 2 {
  4903. service.BatchDeleteHisAdvice(idArray)
  4904. }
  4905. }
  4906. func (c *DialysisAPIController) UpdateAutoReduceDetail() {
  4907. good_id, _ := c.GetInt64("good_id")
  4908. count, _ := c.GetInt64("count")
  4909. record_time, _ := c.GetInt64("record_time")
  4910. patient_id, _ := c.GetInt64("patient_id")
  4911. detail, _ := service.UpdateAutoReduceDetail(good_id, count, record_time, patient_id)
  4912. c.ServeSuccessJSON(map[string]interface{}{
  4913. "detail": detail,
  4914. })
  4915. return
  4916. }
  4917. func (c *DialysisAPIController) DeleteAutoReduceDetail() {
  4918. good_id, _ := c.GetInt64("good_id")
  4919. record_time, _ := c.GetInt64("record_time")
  4920. patient_id, _ := c.GetInt64("patient_id")
  4921. service.DeleteDialysisBeforOne(good_id, record_time, patient_id)
  4922. err := service.DeleteAutoReduceDetail(good_id, record_time, patient_id)
  4923. fmt.Print("err", err)
  4924. c.ServeSuccessJSON(map[string]interface{}{
  4925. "msg": "批量删除成功",
  4926. })
  4927. return
  4928. }
  4929. func (c *DialysisAPIController) BatchAdviceCheck() {
  4930. ids := c.GetString("ids")
  4931. idArray := strings.Split(ids, ",")
  4932. creator, _ := c.GetInt64("creator")
  4933. origin, _ := c.GetInt64("origin")
  4934. if origin == 1 {
  4935. err := service.BatchAdviceCheck(idArray, creator)
  4936. fmt.Println(err)
  4937. list, _ := service.GetAdviceExecutionById(idArray)
  4938. c.ServeSuccessJSON(map[string]interface{}{
  4939. "list": list,
  4940. })
  4941. return
  4942. }
  4943. if origin == 2 {
  4944. service.BatchHisAdviceCheck(idArray, creator)
  4945. list, _ := service.GetHisAdviceExecutionById(idArray)
  4946. c.ServeSuccessJSON(map[string]interface{}{
  4947. "list": list,
  4948. })
  4949. return
  4950. }
  4951. }
  4952. func (c *DialysisAPIController) BatchAdviceExecution() {
  4953. ids := c.GetString("ids")
  4954. idArray := strings.Split(ids, ",")
  4955. executionTime := c.GetString("execution_time")
  4956. creator, _ := c.GetInt64("creator")
  4957. timeLayout := "2006-01-02 15:04:05"
  4958. loc, _ := time.LoadLocation("Local")
  4959. theTime, _ := time.ParseInLocation(timeLayout, executionTime, loc)
  4960. orgin, _ := c.GetInt64("origin")
  4961. if orgin == 1 {
  4962. err := service.BatchAdviceExecution(idArray, creator, theTime.Unix())
  4963. list, _ := service.GetAdviceExecutionById(idArray)
  4964. fmt.Println(err)
  4965. c.ServeSuccessJSON(map[string]interface{}{
  4966. "list": list,
  4967. })
  4968. return
  4969. }
  4970. if orgin == 2 {
  4971. err := service.BatchHisAdviceExecution(idArray, creator, theTime.Unix())
  4972. list, _ := service.GetHisAdviceExecutionById(idArray)
  4973. fmt.Println(err)
  4974. c.ServeSuccessJSON(map[string]interface{}{
  4975. "list": list,
  4976. })
  4977. return
  4978. }
  4979. }
  4980. func (c *DialysisAPIController) UpdateStockGoods() {
  4981. good_id, _ := c.GetInt64("good_id")
  4982. record_time, _ := c.GetInt64("record_time")
  4983. patient_id, _ := c.GetInt64("patient_id")
  4984. count, _ := c.GetInt64("count")
  4985. err := service.UpdateStockGoods(good_id, record_time, patient_id, count)
  4986. fmt.Print("err", err)
  4987. c.ServeSuccessJSON(map[string]interface{}{
  4988. "msg": "更新成功",
  4989. })
  4990. return
  4991. }
  4992. //当前数据比上一次出库数据少
  4993. func ConsumablesDeliveryTotalSeven(orgID int64, patient_id int64, record_time int64, goods []*models.DialysisBeforePrepareGoods, creater int64, count int64) (err error) {
  4994. //查询该患者当天已经出库的耗材信息
  4995. goods_yc, _ := service.FindConsumablesByDateThree(orgID, patient_id, record_time)
  4996. // 和新请求的出库数据进行对比,分出那些是继续出库的,那些是需要删除出库的
  4997. for i := len(goods_yc) - 1; i >= 0; i-- {
  4998. goods_yc_temp := goods_yc[i]
  4999. for j := len(goods) - 1; j >= 0; j-- {
  5000. goods_temp := goods[j]
  5001. // 已经出库和新请求出库都存在该耗材,则判断出库数量,分成是继续出库,还是删除出库
  5002. if goods_yc_temp.GoodTypeId == goods_temp.GoodTypeId && goods_yc_temp.GoodId == goods_temp.GoodId {
  5003. // 已经出库和新请求出库的出库数量一致,则清除两个结构体里的数据(既不出库,也不删除出库)
  5004. if goods_yc_temp.Count == goods_temp.Count {
  5005. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  5006. goods = append(goods[:j], goods[j+1:]...)
  5007. break
  5008. }
  5009. // 如果已经出库的数量 大于 新请求出库的数量,则代表需要删除出库
  5010. if goods_yc_temp.Count > goods_temp.Count {
  5011. temp_count := goods_yc_temp.Count - goods_temp.Count
  5012. goods_yc[i].Count = temp_count
  5013. goods = append(goods[:j], goods[j+1:]...)
  5014. break
  5015. }
  5016. // 如果已经出库的数量 小于 新请求出库的梳理,则代表需要增加出库
  5017. if goods_yc_temp.Count < goods_temp.Count {
  5018. temp_count := goods_temp.Count - goods_yc_temp.Count
  5019. goods[j].Count = temp_count
  5020. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  5021. break
  5022. }
  5023. }
  5024. }
  5025. }
  5026. // goods_yc 这个数据就是需要已经出库了,但是现在需要删除出库的耗材数据
  5027. // goods 这个数据就是需要出库的耗材的数据(新增的数据)
  5028. //退库
  5029. if len(goods_yc) > 0 {
  5030. for _, good_yc := range goods_yc {
  5031. out, _ := service.FindStockOutByIsSys(orgID, 1, record_time)
  5032. ConsumablesDeliveryDeleteNew(orgID, record_time, good_yc, &out, patient_id, creater, count)
  5033. }
  5034. }
  5035. return nil
  5036. }
  5037. //耗材出库删除
  5038. func ConsumablesDeliveryDeleteFour(orgID int64, record_time int64, good_yc *models.BloodAutomaticReduceDetail, warehouseOut *models.WarehouseOut, patient_id int64, creater int64, count int64) (err error) {
  5039. // 先根据相关信息查询当天该耗材的出库信息
  5040. warehouseOutInfos, err := service.FindStockOutInfoByStockTwo(orgID, good_yc.GoodTypeId, good_yc.GoodId, record_time, good_yc.PatientId)
  5041. if err != nil {
  5042. return err
  5043. }
  5044. var delete_count int64 = 0
  5045. delete_count = warehouseOutInfos.Count - count
  5046. houseConfig, _ := service.GetAllStoreHouseConfig(orgID)
  5047. // 在出库记录表里记录退库详情
  5048. warehouseOutInfo := &models.WarehouseOutInfo{
  5049. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  5050. WarehouseOutId: warehouseOut.ID,
  5051. Status: 1,
  5052. Ctime: time.Now().Unix(),
  5053. OrgId: orgID,
  5054. Type: 1,
  5055. IsSys: 1,
  5056. SysRecordTime: record_time,
  5057. GoodTypeId: good_yc.GoodTypeId,
  5058. GoodId: good_yc.GoodId,
  5059. PatientId: good_yc.PatientId,
  5060. ConsumableType: 2,
  5061. StorehouseId: houseConfig.StorehouseOutInfo,
  5062. IsCheck: 1,
  5063. }
  5064. warehouseOutInfo.Count = count
  5065. stockInInfo, _ := service.FindLastStockInInfoRecord(good_yc.GoodId, orgID)
  5066. warehouseOutInfo.Price = stockInInfo.Price
  5067. warehouseOutInfo.Dealer = stockInInfo.Dealer
  5068. warehouseOutInfo.Manufacturer = stockInInfo.Manufacturer
  5069. warehouseOutInfo.ExpiryDate = stockInInfo.ExpiryDate
  5070. warehouseOutInfo.ProductDate = stockInInfo.ProductDate
  5071. warehouseOutInfo.Number = warehouseOutInfos.Number
  5072. warehouseOutInfo.LicenseNumber = stockInInfo.LicenseNumber
  5073. warehouseOutInfo.WarehouseInfotId = stockInInfo.ID
  5074. //查找当天是否存在出库记录
  5075. _, errcod := service.GetWarehouseOutInfoIsExistOne(good_yc.GoodId, good_yc.PatientId, record_time, good_yc.ProjectId)
  5076. if errcod == gorm.ErrRecordNotFound {
  5077. errOne := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  5078. //插入详情明细表
  5079. stockFlow := models.VmStockFlow{
  5080. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  5081. WarehouseOutId: warehouseOut.ID,
  5082. GoodId: good_yc.GoodId,
  5083. Number: warehouseOutInfos.Number,
  5084. ProductDate: stockInInfo.ProductDate,
  5085. ExpireDate: stockInInfo.ExpiryDate,
  5086. Count: count,
  5087. Price: stockInInfo.Price,
  5088. Status: 1,
  5089. Ctime: time.Now().Unix(),
  5090. UserOrgId: good_yc.OrgId,
  5091. Manufacturer: stockInInfo.Manufacturer,
  5092. Dealer: stockInInfo.Dealer,
  5093. LicenseNumber: stockInInfo.LicenseNumber,
  5094. IsEdit: 2,
  5095. Creator: creater,
  5096. SystemTime: record_time,
  5097. ConsumableType: 3,
  5098. WarehousingDetailId: 0,
  5099. IsSys: 1,
  5100. UpdateCreator: creater,
  5101. PatientId: patient_id,
  5102. StorehouseId: houseConfig.StorehouseOutInfo,
  5103. }
  5104. exsit, errflow := service.GetStockFlowIsExsit(warehouseOutInfos.WarehouseInfotId, patient_id, record_time, good_yc.GoodId)
  5105. if errflow == gorm.ErrRecordNotFound {
  5106. //创建流水表
  5107. err := service.CreateStockFlowOne(stockFlow)
  5108. fmt.Println("err", err)
  5109. } else if errflow == nil {
  5110. //插入详情明细表
  5111. stockFlow := models.VmStockFlow{
  5112. ID: exsit.ID,
  5113. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  5114. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  5115. WarehouseOutId: warehouseOut.ID,
  5116. GoodId: good_yc.GoodId,
  5117. Number: warehouseOutInfos.Number,
  5118. ProductDate: stockInInfo.ProductDate,
  5119. ExpireDate: stockInInfo.ExpiryDate,
  5120. Count: exsit.Count - delete_count,
  5121. Price: stockInInfo.Price,
  5122. Status: 1,
  5123. Ctime: time.Now().Unix(),
  5124. UserOrgId: good_yc.OrgId,
  5125. Manufacturer: stockInInfo.Manufacturer,
  5126. Dealer: stockInInfo.Dealer,
  5127. LicenseNumber: stockInInfo.LicenseNumber,
  5128. IsEdit: 2,
  5129. Creator: creater,
  5130. SystemTime: record_time,
  5131. ConsumableType: 3,
  5132. WarehousingDetailId: 0,
  5133. IsSys: 1,
  5134. UpdateCreator: creater,
  5135. PatientId: patient_id,
  5136. StorehouseId: houseConfig.StorehouseOutInfo,
  5137. }
  5138. service.UpdatedStockFlowOne(stockFlow, warehouseOut.ID, patient_id, record_time, good_yc.GoodId)
  5139. }
  5140. if errOne != nil {
  5141. return errOne
  5142. }
  5143. } else if errcod == nil {
  5144. service.UpdatedWarehouseOutInfo(warehouseOutInfo, good_yc.GoodId, good_yc.PatientId, record_time, good_yc.ProjectId)
  5145. //插入详情明细表
  5146. stockFlow := models.VmStockFlow{
  5147. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  5148. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  5149. WarehouseOutId: warehouseOut.ID,
  5150. GoodId: good_yc.GoodId,
  5151. Number: warehouseOutInfos.Number,
  5152. ProductDate: stockInInfo.ProductDate,
  5153. ExpireDate: stockInInfo.ExpiryDate,
  5154. Count: count,
  5155. Price: stockInInfo.Price,
  5156. Status: 1,
  5157. Ctime: time.Now().Unix(),
  5158. UserOrgId: good_yc.OrgId,
  5159. Manufacturer: stockInInfo.Manufacturer,
  5160. Dealer: stockInInfo.Dealer,
  5161. LicenseNumber: stockInInfo.LicenseNumber,
  5162. IsEdit: 2,
  5163. Creator: creater,
  5164. SystemTime: record_time,
  5165. ConsumableType: 3,
  5166. WarehousingDetailId: 0,
  5167. IsSys: 1,
  5168. UpdateCreator: creater,
  5169. PatientId: patient_id,
  5170. ReturnCount: delete_count,
  5171. StorehouseId: houseConfig.StorehouseOutInfo,
  5172. }
  5173. exsit, errflows := service.GetStockFlowIsExsit(warehouseOutInfos.WarehouseInfotId, patient_id, record_time, good_yc.GoodId)
  5174. if errflows == gorm.ErrRecordNotFound {
  5175. //创建流水表
  5176. service.CreateStockFlowOne(stockFlow)
  5177. } else if errflows == nil {
  5178. stockFlow := models.VmStockFlow{
  5179. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  5180. ID: exsit.ID,
  5181. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  5182. WarehouseOutId: warehouseOut.ID,
  5183. GoodId: good_yc.GoodId,
  5184. Number: warehouseOutInfos.Number,
  5185. ProductDate: stockInInfo.ProductDate,
  5186. ExpireDate: stockInInfo.ExpiryDate,
  5187. Count: exsit.Count - delete_count,
  5188. Price: stockInInfo.Price,
  5189. Status: 1,
  5190. Ctime: time.Now().Unix(),
  5191. UserOrgId: good_yc.OrgId,
  5192. Manufacturer: stockInInfo.Manufacturer,
  5193. Dealer: stockInInfo.Dealer,
  5194. LicenseNumber: stockInInfo.LicenseNumber,
  5195. IsEdit: 2,
  5196. Creator: creater,
  5197. SystemTime: record_time,
  5198. ConsumableType: 3,
  5199. WarehousingDetailId: 0,
  5200. IsSys: 1,
  5201. UpdateCreator: creater,
  5202. PatientId: patient_id,
  5203. ReturnCount: delete_count,
  5204. StorehouseId: houseConfig.StorehouseOutInfo,
  5205. }
  5206. service.UpdatedStockFlowOne(stockFlow, warehouseOut.ID, patient_id, record_time, good_yc.GoodId)
  5207. }
  5208. }
  5209. //更改自动出库的表格
  5210. details := models.BloodAutomaticReduceDetail{
  5211. WarehouseOutId: warehouseOutInfo.ID,
  5212. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  5213. PatientId: patient_id,
  5214. Ctime: time.Now().Unix(),
  5215. Mtime: time.Now().Unix(),
  5216. Status: 1,
  5217. RecordTime: record_time,
  5218. OrgId: orgID,
  5219. GoodId: good_yc.GoodId,
  5220. GoodTypeId: good_yc.GoodTypeId,
  5221. Count: count,
  5222. StorehouseId: houseConfig.StorehouseOutInfo,
  5223. }
  5224. //查询当天耗材是否已经存在数据
  5225. _, errcode := service.GetAutoMaticReduceDetail(orgID, patient_id, record_time, good_yc.GoodId, good_yc.GoodTypeId)
  5226. if errcode == gorm.ErrRecordNotFound {
  5227. errTwo := service.CreateAutoReduceRecord(&details)
  5228. if errTwo != nil {
  5229. return errTwo
  5230. }
  5231. } else if errcode == nil {
  5232. service.DeleteAutoRedeceDetailTwo(orgID, patient_id, record_time, good_yc.GoodId, good_yc.GoodTypeId)
  5233. service.CreateAutoReduceRecord(&details)
  5234. }
  5235. service.ModifyGoodAddInformation(good_yc.GoodId, delete_count, good_yc.OrgId)
  5236. //增加出库库存数量
  5237. service.ModifyReduceGoodSumCount(houseConfig.StorehouseOutInfo, delete_count, good_yc.OrgId, good_yc.GoodId)
  5238. errOne := service.UpDateWarehouStockFlowByStockDelete(warehouseOutInfos.WarehouseInfotId, record_time, good_yc.GoodId, delete_count, good_yc.PatientId)
  5239. fmt.Println("errOne", errOne)
  5240. // 删除出库完成后,要增加对应批次的库存数量
  5241. errThree := service.UpDateWarehouseInfoByStockDelete(warehouseOutInfos.WarehouseInfotId, delete_count, patient_id, record_time, good_yc.GoodId)
  5242. if errThree != nil {
  5243. return errThree
  5244. }
  5245. if good_yc.Count == 0 {
  5246. return nil
  5247. } else {
  5248. return errors.New("退库和出库数据不匹配")
  5249. }
  5250. }
  5251. func ConsumablesDeliveryTotalSix(orgID int64, patient_id int64, record_time int64, goods []*models.DialysisBeforePrepareGoods, goodOne []*models.NewDialysisBeforePrepareGoods, creater int64) (err error) {
  5252. //查询该患者当天已经出库的耗材信息
  5253. goods_yc, _ := service.FindConsumablesByDateThree(orgID, patient_id, record_time)
  5254. // 和新请求的出库数据进行对比,分出那些是继续出库的,那些是需要删除出库的
  5255. for i := len(goods_yc) - 1; i >= 0; i-- {
  5256. goods_yc_temp := goods_yc[i]
  5257. for j := len(goods) - 1; j >= 0; j-- {
  5258. goods_temp := goods[j]
  5259. // 已经出库和新请求出库都存在该耗材,则判断出库数量,分成是继续出库,还是删除出库
  5260. if goods_yc_temp.GoodTypeId == goods_temp.GoodTypeId && goods_yc_temp.GoodId == goods_temp.GoodId {
  5261. // 已经出库和新请求出库的出库数量一致,则清除两个结构体里的数据(既不出库,也不删除出库)
  5262. if goods_yc_temp.Count == goods_temp.Count {
  5263. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  5264. goods = append(goods[:j], goods[j+1:]...)
  5265. break
  5266. }
  5267. // 如果已经出库的数量 大于 新请求出库的数量,则代表需要删除出库
  5268. if goods_yc_temp.Count > goods_temp.Count {
  5269. temp_count := goods_yc_temp.Count - goods_temp.Count
  5270. goods_yc[i].Count = temp_count
  5271. goods = append(goods[:j], goods[j+1:]...)
  5272. break
  5273. }
  5274. // 如果已经出库的数量 小于 新请求出库的梳理,则代表需要增加出库
  5275. if goods_yc_temp.Count < goods_temp.Count {
  5276. temp_count := goods_temp.Count - goods_yc_temp.Count
  5277. goods[j].Count = temp_count
  5278. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  5279. break
  5280. }
  5281. }
  5282. }
  5283. }
  5284. // goods_yc 这个数据就是需要已经出库了,但是现在需要删除出库的耗材数据
  5285. // goods 这个数据就是需要出库的耗材的数据(新增的数据)
  5286. if len(goods) > 0 {
  5287. out, err := service.FindStockOutByIsSys(orgID, 1, record_time)
  5288. houseConfig, _ := service.GetAllStoreHouseConfig(orgID)
  5289. if err == gorm.ErrRecordNotFound {
  5290. //没有记录,则创建出库单
  5291. timeStr := time.Now().Format("2006-01-02")
  5292. timeArr := strings.Split(timeStr, "-")
  5293. total, _ := service.FindAllWarehouseOut(orgID)
  5294. total = total + 1
  5295. warehousing_out_order := strconv.FormatInt(orgID, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  5296. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  5297. number = number + total
  5298. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  5299. warehouseOut := models.WarehouseOut{
  5300. WarehouseOutOrderNumber: warehousing_out_order,
  5301. OperationTime: time.Now().Unix(),
  5302. OrgId: orgID,
  5303. Creater: creater,
  5304. Ctime: time.Now().Unix(),
  5305. Status: 1,
  5306. WarehouseOutTime: record_time,
  5307. Dealer: 0,
  5308. Manufacturer: 0,
  5309. Type: 1,
  5310. IsSys: 1,
  5311. StorehouseId: houseConfig.StorehouseOutInfo,
  5312. IsCheck: 1,
  5313. }
  5314. err := service.AddSigleWarehouseOut(&warehouseOut)
  5315. if err != nil {
  5316. utils.TraceLog("创建出库单失败 err = %v", err)
  5317. return err
  5318. } else {
  5319. out = warehouseOut
  5320. }
  5321. }
  5322. for _, item := range goods {
  5323. var newCount int64 = 0
  5324. for _, it := range goodOne {
  5325. if item.GoodTypeId == it.GoodTypeId && item.GoodId == it.GoodId {
  5326. newCount = it.Count
  5327. }
  5328. }
  5329. prepare := models.DialysisBeforePrepare{
  5330. GoodTypeId: item.GoodTypeId,
  5331. GoodId: item.GoodId,
  5332. Count: item.Count,
  5333. StorehouseId: houseConfig.StorehouseOutInfo,
  5334. }
  5335. fmt.Println("出库数量23333333333333333333333332😯😯😯😯", prepare.Count)
  5336. service.ConsumablesGoodDelivery(orgID, patient_id, record_time, &prepare, &out, newCount)
  5337. //增加出库数量
  5338. service.ModifyGoodSumCount(houseConfig.StorehouseOutInfo, item.Count, orgID, item.GoodId)
  5339. }
  5340. }
  5341. if len(goods_yc) > 0 {
  5342. for _, good_yc := range goods_yc {
  5343. out, _ := service.FindStockOutByIsSys(orgID, 1, record_time)
  5344. ConsumablesDeliveryDeleteThree(orgID, record_time, good_yc, &out)
  5345. }
  5346. }
  5347. return nil
  5348. }
  5349. //耗材出库删除
  5350. func ConsumablesDeliveryDeleteThree(orgID int64, record_time int64, good_yc *models.BloodAutomaticReduceDetail, warehouseOut *models.WarehouseOut) (err error) {
  5351. // 先根据相关信息查询当天该耗材的出库信息
  5352. warehouseOutInfos, err := service.FindStockOutInfoByStockOne(orgID, good_yc.GoodTypeId, good_yc.GoodId, record_time)
  5353. if err != nil {
  5354. return err
  5355. }
  5356. var delete_count int64 = 0
  5357. for _, ware := range warehouseOutInfos {
  5358. // 判断当前出库的数据和删除出库数量
  5359. if good_yc.Count <= ware.Count {
  5360. delete_count = good_yc.Count
  5361. } else {
  5362. delete_count = ware.Count
  5363. }
  5364. // 在出库记录表里记录退库详情
  5365. warehouseOutInfo := &models.WarehouseOutInfo{
  5366. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  5367. WarehouseOutId: warehouseOut.ID,
  5368. Status: 1,
  5369. Ctime: time.Now().Unix(),
  5370. Remark: "",
  5371. OrgId: orgID,
  5372. Type: 1,
  5373. Manufacturer: 0,
  5374. Dealer: 0,
  5375. IsSys: 0,
  5376. SysRecordTime: record_time,
  5377. GoodTypeId: good_yc.GoodTypeId,
  5378. GoodId: good_yc.GoodId,
  5379. StorehouseId: warehouseOut.StorehouseId,
  5380. IsCheck: 1,
  5381. }
  5382. warehouseOutInfo.Count = delete_count
  5383. stockInInfo, _ := service.FindLastStockInInfoRecord(good_yc.GoodId, orgID)
  5384. warehouseOutInfo.Price = stockInInfo.Price
  5385. errOne := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  5386. if errOne != nil {
  5387. return errOne
  5388. }
  5389. // 删除出库完成后,要改变流水库存(有疑问)
  5390. errOne = service.UpDateWarehouStockFlowByStockDelete(ware.WarehouseInfotId, record_time, good_yc.GoodId, delete_count, good_yc.PatientId)
  5391. fmt.Println("errOne", errOne)
  5392. errThree := service.UpDateWarehouseInfoByStockDelete(ware.WarehouseInfotId, delete_count, good_yc.PatientId, record_time, good_yc.GoodId)
  5393. service.ModifyGoodAddInformation(good_yc.GoodId, delete_count, good_yc.OrgId)
  5394. //扣减出库数量
  5395. service.ModifyReduceGoodSumCount(warehouseOut.StorehouseId, good_yc.Count, good_yc.OrgId, good_yc.GoodId)
  5396. if errThree != nil {
  5397. return errThree
  5398. }
  5399. }
  5400. if good_yc.Count == 0 {
  5401. return nil
  5402. } else {
  5403. return errors.New("退库和出库数据不匹配")
  5404. }
  5405. }
  5406. func (this *DialysisAPIController) GetMobileScheduleList() {
  5407. limit, _ := this.GetInt64("limit")
  5408. page, _ := this.GetInt64("page")
  5409. type_options_visible, _ := this.GetInt64("type_options_visible")
  5410. sch_type_options_visible, _ := this.GetInt64("sch_type_options_visible")
  5411. zone_options_visible, _ := this.GetInt64("zone_options_visible")
  5412. fmt.Println(limit, page, type_options_visible, sch_type_options_visible, zone_options_visible)
  5413. }
  5414. func RemoveRepeatedCheckRecod(arr []*models.HisPrescriptionProject) (newArr []*models.HisPrescriptionProject) {
  5415. newArr = make([]*models.HisPrescriptionProject, 0)
  5416. for i := 0; i < len(arr); i++ {
  5417. repeat := false
  5418. for j := i + 1; j < len(arr); j++ {
  5419. if arr[i].TeamId == arr[j].TeamId {
  5420. repeat = true
  5421. break
  5422. }
  5423. }
  5424. if !repeat {
  5425. newArr = append(newArr, arr[i])
  5426. }
  5427. }
  5428. return
  5429. }
  5430. func (this *DialysisAPIController) GetRoleList() {
  5431. admin_user_id, _ := this.GetInt64("admin_user_id")
  5432. orgid := this.GetMobileAdminUserInfo().Org.Id
  5433. list, err := service.GetRoleList(orgid, admin_user_id)
  5434. fmt.Println(err)
  5435. this.ServeSuccessJSON(map[string]interface{}{
  5436. "list": list,
  5437. })
  5438. return
  5439. }
  5440. func ConsumablesDeliveryDeleteNew(orgID int64, record_time int64, good_yc *models.BloodAutomaticReduceDetail, warehouseOut *models.WarehouseOut, patient_id int64, creater int64, count int64) (err error) {
  5441. // 先根据相关信息查询当天该耗材的出库信息
  5442. warehouseOutInfos, err := service.FindStockOutInfoByStockTwo(orgID, good_yc.GoodTypeId, good_yc.GoodId, record_time, good_yc.PatientId)
  5443. if err != nil {
  5444. return err
  5445. }
  5446. var delete_count int64 = 0
  5447. delete_count = warehouseOutInfos.Count - count
  5448. houseConfig, _ := service.GetAllStoreHouseConfig(orgID)
  5449. // 删除出库完成后,要增加对应批次的库存数量
  5450. errThree := service.UpDateWarehouseInfoByStockDelete(warehouseOutInfos.WarehouseInfotId, delete_count, patient_id, record_time, good_yc.GoodId)
  5451. if errThree != nil {
  5452. return errThree
  5453. }
  5454. //增加退库数量
  5455. service.UpdateSumAddCancelCount(orgID, good_yc.GoodId, houseConfig.StorehouseOutInfo, delete_count)
  5456. //扣减出库数量鸡
  5457. service.ModifyAddGoodSumCount(houseConfig.StorehouseOutInfo, delete_count, orgID, good_yc.GoodId)
  5458. //查询剩余库存
  5459. goodList, _ := service.GetAllGoodSumCount(good_yc.GoodId, orgID)
  5460. var sum_count int64
  5461. for _, item := range goodList {
  5462. sum_count += item.StockCount
  5463. }
  5464. // 在出库记录表里记录退库详情
  5465. warehouseOutInfo := &models.WarehouseOutInfo{
  5466. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  5467. WarehouseOutId: warehouseOut.ID,
  5468. Status: 1,
  5469. Ctime: time.Now().Unix(),
  5470. OrgId: orgID,
  5471. Type: 1,
  5472. IsSys: 1,
  5473. SysRecordTime: record_time,
  5474. GoodTypeId: good_yc.GoodTypeId,
  5475. GoodId: good_yc.GoodId,
  5476. PatientId: good_yc.PatientId,
  5477. ConsumableType: 2,
  5478. StorehouseId: houseConfig.StorehouseOutInfo,
  5479. IsCheck: 1,
  5480. OverCount: sum_count,
  5481. }
  5482. warehouseOutInfo.Count = count
  5483. stockInInfo, _ := service.FindLastStockInInfoRecord(good_yc.GoodId, orgID)
  5484. warehouseOutInfo.Price = stockInInfo.Price
  5485. warehouseOutInfo.Dealer = stockInInfo.Dealer
  5486. warehouseOutInfo.Manufacturer = stockInInfo.Manufacturer
  5487. warehouseOutInfo.ExpiryDate = stockInInfo.ExpiryDate
  5488. warehouseOutInfo.ProductDate = stockInInfo.ProductDate
  5489. warehouseOutInfo.Number = warehouseOutInfos.Number
  5490. warehouseOutInfo.LicenseNumber = stockInInfo.LicenseNumber
  5491. warehouseOutInfo.WarehouseInfotId = stockInInfo.ID
  5492. //查找当天是否存在出库记录
  5493. _, errcod := service.GetWarehouseOutInfoIsExistOne(good_yc.GoodId, good_yc.PatientId, record_time, good_yc.ProjectId)
  5494. if errcod == gorm.ErrRecordNotFound {
  5495. errOne := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  5496. //插入详情明细表
  5497. if errOne != nil {
  5498. return errOne
  5499. }
  5500. //插入详情明细表
  5501. stockFlow := models.VmStockFlow{
  5502. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  5503. WarehouseOutId: warehouseOut.ID,
  5504. GoodId: good_yc.GoodId,
  5505. Number: warehouseOutInfos.Number,
  5506. ProductDate: stockInInfo.ProductDate,
  5507. ExpireDate: stockInInfo.ExpiryDate,
  5508. Count: count,
  5509. Price: stockInInfo.Price,
  5510. Status: 1,
  5511. Ctime: time.Now().Unix(),
  5512. UserOrgId: good_yc.OrgId,
  5513. Manufacturer: stockInInfo.Manufacturer,
  5514. Dealer: stockInInfo.Dealer,
  5515. LicenseNumber: stockInInfo.LicenseNumber,
  5516. IsEdit: 2,
  5517. Creator: creater,
  5518. SystemTime: record_time,
  5519. ConsumableType: 3,
  5520. WarehousingDetailId: 0,
  5521. IsSys: 1,
  5522. UpdateCreator: creater,
  5523. PatientId: patient_id,
  5524. StorehouseId: houseConfig.StorehouseOutInfo,
  5525. OverCount: sum_count,
  5526. ProjectId: good_yc.ProjectId,
  5527. }
  5528. err := service.CreateStockFlowOne(stockFlow)
  5529. fmt.Println("err", err)
  5530. } else if errcod == nil {
  5531. service.UpdatedWarehouseOutInfo(warehouseOutInfo, good_yc.GoodId, good_yc.PatientId, record_time, good_yc.ProjectId)
  5532. }
  5533. //创建退库单
  5534. operation_time := time.Now().Unix()
  5535. //创建退库单
  5536. timeStr := time.Now().Format("2006-01-02")
  5537. timeArr := strings.Split(timeStr, "-")
  5538. total, _ := service.FindAllCancelStockTotal(orgID)
  5539. total = total + 1
  5540. orderNumber := "CKTKD" + strconv.FormatInt(orgID, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000" + strconv.FormatInt(total, 10)
  5541. cancelStock := models.CancelStock{
  5542. OrderNumber: orderNumber,
  5543. OperaTime: operation_time,
  5544. OrgId: orgID,
  5545. Creater: warehouseOut.Creater,
  5546. Ctime: time.Now().Unix(),
  5547. Status: 1,
  5548. ReturnTime: record_time,
  5549. Type: 1,
  5550. StorehouseId: stockInInfo.StorehouseId,
  5551. IsCheck: 1,
  5552. }
  5553. _, msgerrkonde := service.GetCancelStockDetailByOrderNumberOne(record_time, orgID)
  5554. if msgerrkonde == gorm.ErrRecordNotFound {
  5555. service.AddSigleCancelStock(&cancelStock)
  5556. }
  5557. cancel, _ := service.GetLastCancelStockById(orgID)
  5558. manufacturer, _ := service.GetManufactureById(stockInInfo.Manufacturer)
  5559. deaerler, _ := service.GetDealerById(stockInInfo.Dealer)
  5560. cancelStockInfo := models.CancelStockInfo{
  5561. GoodId: stockInInfo.GoodId,
  5562. CancelStockId: cancel.ID,
  5563. GoodTypeId: stockInInfo.GoodTypeId,
  5564. Count: delete_count,
  5565. Price: stockInInfo.PackingPrice,
  5566. Total: 0,
  5567. ProductDate: stockInInfo.ProductDate,
  5568. ExpiryDate: stockInInfo.ExpiryDate,
  5569. Ctime: time.Now().Unix(),
  5570. Status: 1,
  5571. OrgId: orgID,
  5572. OrderNumber: cancel.OrderNumber,
  5573. Type: 0,
  5574. Dealer: deaerler.DealerName,
  5575. Manufacturer: manufacturer.ManufacturerName,
  5576. Number: stockInInfo.Number,
  5577. RegisterAccount: "",
  5578. Remark: "",
  5579. WarehouseInfoId: stockInInfo.ID,
  5580. PatientId: patient_id,
  5581. RecordDate: record_time,
  5582. StorehouseId: stockInInfo.StorehouseId,
  5583. IsCheck: 1,
  5584. }
  5585. service.CreateCancelStockInfoOne(&cancelStockInfo)
  5586. cancelInfo, _ := service.GetLastCancelStockInfoByGoodId(stockInInfo.GoodId)
  5587. flow := models.VmStockFlow{
  5588. WarehousingId: warehouseOutInfo.WarehouseInfotId,
  5589. GoodId: good_yc.GoodId,
  5590. Number: warehouseOutInfos.Number,
  5591. LicenseNumber: stockInInfo.LicenseNumber,
  5592. Count: delete_count,
  5593. UserOrgId: orgID,
  5594. PatientId: patient_id,
  5595. SystemTime: record_time,
  5596. ConsumableType: 7,
  5597. IsSys: 0,
  5598. WarehousingOrder: "",
  5599. WarehouseOutId: warehouseOutInfos.WarehouseOutId,
  5600. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  5601. IsEdit: 0,
  5602. CancelStockId: cancel.ID,
  5603. CancelOrderNumber: cancel.OrderNumber,
  5604. Manufacturer: manufacturer.ID,
  5605. Dealer: 0,
  5606. Creator: warehouseOut.Creater,
  5607. UpdateCreator: 0,
  5608. Status: 1,
  5609. Ctime: time.Now().Unix(),
  5610. Mtime: 0,
  5611. Price: stockInInfo.Price,
  5612. WarehousingDetailId: stockInInfo.ID,
  5613. WarehouseOutDetailId: warehouseOutInfos.ID,
  5614. CancelOutDetailId: cancelInfo.ID,
  5615. ProductDate: stockInInfo.ProductDate,
  5616. ExpireDate: stockInInfo.ExpiryDate,
  5617. StorehouseId: houseConfig.StorehouseOutInfo,
  5618. OverCount: sum_count,
  5619. }
  5620. service.CreateStockFlowOne(flow)
  5621. //更改自动出库的表格
  5622. details := models.BloodAutomaticReduceDetail{
  5623. WarehouseOutId: warehouseOutInfo.ID,
  5624. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  5625. PatientId: patient_id,
  5626. Ctime: time.Now().Unix(),
  5627. Mtime: time.Now().Unix(),
  5628. Status: 1,
  5629. RecordTime: record_time,
  5630. OrgId: orgID,
  5631. GoodId: good_yc.GoodId,
  5632. GoodTypeId: good_yc.GoodTypeId,
  5633. Count: count,
  5634. StorehouseId: houseConfig.StorehouseOutInfo,
  5635. }
  5636. //查询当天耗材是否已经存在数据
  5637. _, errcode := service.GetAutoMaticReduceDetail(orgID, patient_id, record_time, good_yc.GoodId, good_yc.GoodTypeId)
  5638. if errcode == gorm.ErrRecordNotFound {
  5639. errTwo := service.CreateAutoReduceRecord(&details)
  5640. if errTwo != nil {
  5641. return errTwo
  5642. }
  5643. } else if errcode == nil {
  5644. service.DeleteAutoRedeceDetailTwo(orgID, patient_id, record_time, good_yc.GoodId, good_yc.GoodTypeId)
  5645. service.CreateAutoReduceRecord(&details)
  5646. }
  5647. service.ModifyGoodAddInformation(good_yc.GoodId, delete_count, good_yc.OrgId)
  5648. //增加出库库存数量
  5649. //service.ModifyReduceGoodSumCount(houseConfig.StorehouseOutInfo,delete_count,good_yc.OrgId,good_yc.GoodId)
  5650. if good_yc.Count == 0 {
  5651. return nil
  5652. } else {
  5653. return errors.New("退库和出库数据不匹配")
  5654. }
  5655. }
  5656. func (this *DialysisAPIController) SavePatientSign() {
  5657. adminUserInfo := this.GetMobileAdminUserInfo()
  5658. patient_id, _ := this.GetInt64("patient_id")
  5659. dialysis_date, _ := this.GetInt64("dialysis_date")
  5660. orgid := adminUserInfo.Org.Id
  5661. var esdata models.DialysisOrder
  5662. var err error
  5663. if err = json.Unmarshal(this.Ctx.Input.RequestBody, &esdata); err != nil {
  5664. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  5665. return
  5666. }
  5667. esdata.Hash = esdata.Hash
  5668. esdata.Url = beego.AppConfig.String("qiniu_domain") + esdata.Hash
  5669. order := models.DialysisOrder{
  5670. Hash: esdata.Hash,
  5671. Url: esdata.Url,
  5672. }
  5673. err = service.UpdatePatientSign(patient_id, dialysis_date, order, orgid)
  5674. redis := service.RedisClient()
  5675. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":dialysis_order"
  5676. redis.Set(key, "", time.Second)
  5677. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":dialysis_orders_list_all"
  5678. //清空key 值
  5679. redis.Set(keyOne, "", time.Second)
  5680. //scheduleDateStartOne := startDate.Format("2006-01-02")
  5681. //keyTwo := "scheduals_" + scheduleDateStartOne + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  5682. //redis.Set(keyTwo, "", time.Second)
  5683. keyThree := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":doctor_advices"
  5684. redis.Set(keyThree, "", time.Second)
  5685. keyFour := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":monitor_records"
  5686. redis.Set(keyFour, "", time.Second)
  5687. keyFive := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":patient_info"
  5688. redis.Set(keyFive, "", time.Second)
  5689. keySix := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":his_doctor_advice"
  5690. redis.Set(keySix, "", time.Second)
  5691. keySeven := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + ":device_list_all"
  5692. redis.Set(keySeven, "", time.Second)
  5693. if err != nil {
  5694. fmt.Println(err)
  5695. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
  5696. return
  5697. }
  5698. this.ServeSuccessJSON(map[string]interface{}{
  5699. "electronic_signature": esdata,
  5700. })
  5701. }
  5702. func (this *DialysisAPIController) GetPatientSign() {
  5703. patient_id, _ := this.GetInt64("patient_id")
  5704. dialysis_date, _ := this.GetInt64("dialysis_date")
  5705. adminUserInfo := this.GetMobileAdminUserInfo()
  5706. orgId := adminUserInfo.Org.Id
  5707. dialysisOrder, err := service.GetPatientSign(patient_id, dialysis_date, orgId)
  5708. if err != nil {
  5709. fmt.Println(err)
  5710. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
  5711. return
  5712. }
  5713. this.ServeSuccessJSON(map[string]interface{}{
  5714. "dialysisOrder": dialysisOrder,
  5715. })
  5716. }