dialysis_api_controller.go 241KB

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