dialysis_api_controller.go 289KB

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