dialysis_api_controller.go 284KB

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