dialysis_api_controller.go 292KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876
  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. //下机完自动消毒,针对长沙南雅
  1804. if dialysisOrder.Stage == 1 {
  1805. if adminUserInfo.Org.Id == 9671 || adminUserInfo.Org.Id == 10340 {
  1806. //根据床位号获取设备型号
  1807. unitType, _ := service.GetUnitType(dialysisOrder.BedID, dialysisOrder.UserOrgId)
  1808. //查询使用消毒最后一条消毒记录
  1809. _, err := service.GetLaseDeviceInfomation(dialysisOrder.UserOrgId, dialysisOrder.BedID, dialysisOrder.DialysisDate, dialysisOrder.SchedualType)
  1810. fmt.Println("err", err)
  1811. if err == gorm.ErrRecordNotFound {
  1812. //查找排班
  1813. scheduleByPatient, _ := service.GetScheduleByPatient(dialysisOrder.PatientId, dialysisOrder.DialysisDate, dialysisOrder.UserOrgId)
  1814. //查询改设备是否有消毒计划
  1815. plan, errcode := service.GetDisInfectionTime(dialysisOrder.UserOrgId, unitType.UnitType, dialysisOrder.SchedualType, scheduleByPatient.ScheduleWeek)
  1816. //根据床位号获取设备id
  1817. addmacher, _ := service.GetEquimentIDTwo(dialysisOrder.BedID, dialysisOrder.UserOrgId)
  1818. //查询病人信息
  1819. patients, _ := service.GetPatientInfoMation(dialysisOrder.PatientId)
  1820. var con = ""
  1821. if patients.IsInfectious == 0 {
  1822. con = ""
  1823. }
  1824. if patients.IsInfectious == 1 {
  1825. con = "无"
  1826. }
  1827. if patients.IsInfectious == 2 {
  1828. con = "有"
  1829. }
  1830. //如果没有消毒计划,去查询该设备的上次消毒时间
  1831. if errcode == gorm.ErrRecordNotFound {
  1832. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  1833. return
  1834. }
  1835. if errcode == nil {
  1836. var end_time int64
  1837. end_time = endDate.Unix() + plan.DisinfecTime*60
  1838. //新增消毒
  1839. information := models.DeviceInformation{
  1840. Date: dialysisOrder.DialysisDate,
  1841. Zone: dialysisOrder.ZoneId,
  1842. Class: dialysisOrder.SchedualType,
  1843. BedNumber: dialysisOrder.BedID,
  1844. PatientId: dialysisOrder.PatientId,
  1845. DialysisMode: scheduleByPatient.ModeId,
  1846. LongTime: strconv.FormatInt(plan.DisinfecTime, 10),
  1847. Disinfection: 1,
  1848. DialysisConcentration: 1,
  1849. DisinfectionStatus: 1,
  1850. Move: 1,
  1851. UserOrgId: dialysisOrder.UserOrgId,
  1852. DisinfectType: plan.Way,
  1853. DisinfectantType: plan.MachineDisinfectant,
  1854. FluidPath: plan.DisinfectanWay, //液路消毒方式
  1855. Disinfectant: plan.Disinfectant,
  1856. Ctime: time.Now().Unix(),
  1857. Status: 1,
  1858. SignName: dialysisOrder.FinishNurse,
  1859. EquimentId: addmacher.ID,
  1860. DisinfectionResidue: 2,
  1861. Bed: addmacher.BedNumber,
  1862. StartTime: dialysisOrder.StartTime,
  1863. EndTime: dialysisOrder.EndTime,
  1864. Contagion: con,
  1865. WeightLoss: 0,
  1866. Hyperfiltratio: 0,
  1867. DialysisHour: "",
  1868. MachineRun: 1,
  1869. DisinfecStartime: endDate.Unix(),
  1870. DisinfecEndtime: end_time,
  1871. }
  1872. err := service.CreateInformationTwo(&information)
  1873. fmt.Println("报错", err)
  1874. }
  1875. }
  1876. }
  1877. }
  1878. if dialysisOrder.Stage == 1 {
  1879. err := service.ModifyDialysisRecord(dialysisOrder.ID, nurseID, endDate.Unix(), adminUserInfo.AdminUser.Id, puncture_point_haematoma, internal_fistula, catheter, cruor, mission)
  1880. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":dialysis_order"
  1881. redis := service.RedisClient()
  1882. defer redis.Close()
  1883. //清空key 值
  1884. redis.Set(key, "", time.Second)
  1885. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":dialysis_orders_list_all"
  1886. redis.Set(keyOne, "", time.Second)
  1887. //结束时候透析次数加1
  1888. service.UpdateSolutionByPatientId(id)
  1889. dialysisOrder.Stage = 2
  1890. dialysisOrder.FinishNurse = nurseID
  1891. dialysisOrder.FinishCreator = adminUserInfo.AdminUser.Id
  1892. dialysisOrder.FinishModifier = adminUserInfo.AdminUser.Id
  1893. dialysisOrder.EndTime = endDate.Unix()
  1894. go func() {
  1895. ssoDomain := beego.AppConfig.String("call_domain")
  1896. api := ssoDomain + "/index/downpatient"
  1897. values := make(url.Values)
  1898. values.Set("org_id", strconv.FormatInt(adminUserInfo.AdminUser.Id, 10))
  1899. values.Set("admin_user_id", strconv.FormatInt(nurseID, 10))
  1900. values.Set("patient_id", strconv.FormatInt(id, 10))
  1901. http.PostForm(api, values)
  1902. }()
  1903. if err == nil {
  1904. c.ServeSuccessJSON(map[string]interface{}{
  1905. "dialysisOrder": dialysisOrder,
  1906. "assessmentAfterDislysis": tempassessmentAfterDislysis,
  1907. })
  1908. } else {
  1909. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  1910. }
  1911. }
  1912. }
  1913. func (c *DialysisAPIController) GetAllZone() {
  1914. adminUserInfo := c.GetMobileAdminUserInfo()
  1915. err, zone := service.GetAllDeviceZone(adminUserInfo.Org.Id)
  1916. if err == nil {
  1917. c.ServeSuccessJSON(map[string]interface{}{
  1918. "zone": zone,
  1919. })
  1920. }
  1921. }
  1922. func (c *DialysisAPIController) GetSchedualPatientsList() {
  1923. adminUserInfo := c.GetMobileAdminUserInfo()
  1924. page, _ := c.GetInt64("page", 1)
  1925. limit, _ := c.GetInt64("limit", 10)
  1926. schedulType, _ := c.GetInt64("schedul_type", 0)
  1927. startTime, _ := c.GetInt64("schedul_time", 0)
  1928. partitionType, _ := c.GetInt64("partition_type", 0)
  1929. keywords := c.GetString("keywords")
  1930. dialysisSchedule, err := service.GetSchedualPatientList(adminUserInfo.Org.Id, startTime/1000, schedulType, partitionType, keywords, page, limit)
  1931. if err == nil {
  1932. c.ServeSuccessJSON(map[string]interface{}{
  1933. "schedule": dialysisSchedule,
  1934. })
  1935. }
  1936. return
  1937. }
  1938. // /m/api/dialysis/start [post]
  1939. // @param patient_id:int
  1940. // @param record_date:string 排班时间 (yyyy-mm-dd)
  1941. // @param nurse:int 上机护士
  1942. // @param bed:int 床位号
  1943. func (this *DialysisAPIController) StartDialysis() {
  1944. patientID, _ := this.GetInt64("patient_id")
  1945. recordDateStr := this.GetString("record_date")
  1946. nurseID, _ := this.GetInt64("nurse")
  1947. puncture_nurse, _ := this.GetInt64("puncture_nurse")
  1948. blood_drawing, _ := this.GetInt64("blood_drawing")
  1949. schedual_type, _ := this.GetInt64("schedual_type")
  1950. bedID, _ := this.GetInt64("bed")
  1951. start_time := this.GetString("start_time")
  1952. washpipe_nurse, _ := this.GetInt64("washpipe_nurse")
  1953. change_nurse, _ := this.GetInt64("change_nurse")
  1954. difficult_puncture_nurse, _ := this.GetInt64("difficult_puncture_nurse")
  1955. new_fistula_nurse, _ := this.GetInt64("new_fistula_nurse")
  1956. quality_nurse_id, _ := this.GetInt64("quality_nurse_id")
  1957. puncture_needle := this.GetString("puncture_needle")
  1958. puncture_way := this.GetString("puncture_way")
  1959. dialysis_dialyszers := this.GetString("dialysis_dialyszers")
  1960. dialysis_irrigation := this.GetString("dialysis_irrigation")
  1961. blood_access_id, _ := this.GetInt64("blood_access_id")
  1962. zone_id, _ := this.GetInt64("zone_id")
  1963. elecsign := this.GetString("url")
  1964. nuclein_date_str := this.GetString("nuclein_date_str")
  1965. schedule_remark := this.GetString("schedule_remark")
  1966. order_remark := this.GetString("order_remark")
  1967. catheter_operation := this.GetString("catheter_operation")
  1968. if patientID <= 0 || len(recordDateStr) == 0 || nurseID <= 0 || bedID <= 0 {
  1969. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1970. return
  1971. }
  1972. startDate, parseStartDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", start_time)
  1973. if parseStartDateErr != nil {
  1974. this.ErrorLog("时间解析失败:%v", parseStartDateErr)
  1975. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1976. return
  1977. }
  1978. recordDate, parseErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1979. if parseErr != nil {
  1980. this.ErrorLog("时间解析失败:%v", parseErr)
  1981. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1982. return
  1983. }
  1984. adminUserInfo := this.GetMobileAdminUserInfo()
  1985. patient, getPatientErr := service.MobileGetPatientById(adminUserInfo.Org.Id, patientID)
  1986. if getPatientErr != nil {
  1987. this.ErrorLog("获取患者信息失败:%v", getPatientErr)
  1988. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1989. return
  1990. } else if patient == nil {
  1991. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1992. return
  1993. }
  1994. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  1995. if getNurseErr != nil {
  1996. this.ErrorLog("获取护士失败:%v", getNurseErr)
  1997. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1998. return
  1999. } else if nurse == nil {
  2000. this.ErrorLog("护士不存在")
  2001. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2002. return
  2003. }
  2004. nurse, getNurseErr = service.GetAdminUserByUserID(puncture_nurse)
  2005. deviceNumber, getDeviceNumberErr := service.GetDeviceNumberByID(adminUserInfo.Org.Id, bedID)
  2006. if getDeviceNumberErr != nil {
  2007. this.ErrorLog("获取床位号失败:%v", getDeviceNumberErr)
  2008. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2009. return
  2010. } else if deviceNumber == nil {
  2011. this.ErrorLog("床位号不存在")
  2012. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2013. return
  2014. }
  2015. dialysisRecord, getRecordErr := service.MobileGetDialysisRecord(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  2016. if getRecordErr != nil {
  2017. this.ErrorLog("获取透析记录失败:%v", getRecordErr)
  2018. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2019. return
  2020. } else if dialysisRecord != nil {
  2021. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatStart)
  2022. return
  2023. }
  2024. scheduleDateStart := startDate.Format("2006-01-02") + " 00:00:00"
  2025. scheduleDateEnd := startDate.Format("2006-01-02") + " 23:59:59"
  2026. timeLayout := "2006-01-02 15:04:05"
  2027. loc, _ := time.LoadLocation("Local")
  2028. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  2029. theEndTime, _ := time.ParseInLocation(timeLayout, scheduleDateEnd, loc)
  2030. schedulestartTime := theStartTime.Unix()
  2031. scheduleendTime := theEndTime.Unix()
  2032. var theNucleinDate int64
  2033. timeLayoutOne := "2006-01-02"
  2034. if len(nuclein_date_str) > 0 {
  2035. theTime, err := time.ParseInLocation(timeLayoutOne+" 15:04:05", nuclein_date_str+" 00:00:00", loc)
  2036. if err != nil {
  2037. utils.ErrorLog(err.Error())
  2038. }
  2039. theNucleinDate = theTime.Unix()
  2040. }
  2041. template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  2042. //查询更改的机号,是否有人用了,如果只是排班了,但是没上机,直接替换,如果排班且上机了,就提示他无法上机
  2043. //sch, _ := service.GetSourceSch(adminUserInfo.Org.Id, patientID, scheduleendTime)
  2044. schedule, err := service.GetDayScheduleByBedid(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  2045. //查询该床位是否有人用了
  2046. order, _ := service.GetDialysisOrderByBedIdTwo(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  2047. if err == gorm.ErrRecordNotFound { //空床位
  2048. // 修改了床位逻辑
  2049. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  2050. if daySchedule.ID > 0 {
  2051. daySchedule.PartitionId = deviceNumber.ZoneID
  2052. daySchedule.BedId = bedID
  2053. daySchedule.ScheduleType = schedual_type
  2054. daySchedule.UpdatedTime = time.Now().Unix()
  2055. xtSchedule := models.Schedule{
  2056. PartitionId: deviceNumber.ZoneID,
  2057. BedId: bedID,
  2058. ScheduleType: schedual_type,
  2059. UpdatedTime: time.Now().Unix(),
  2060. }
  2061. err := service.UpdateScheduleOne(daySchedule.ID, xtSchedule)
  2062. if err != nil {
  2063. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2064. return
  2065. }
  2066. }
  2067. } else if err == nil {
  2068. if schedule.ID > 0 && schedule.DialysisOrder.ID == 0 { //有排班没上机记录
  2069. if order.ID > 0 { //该机位被其他人占用了
  2070. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  2071. return
  2072. } else { //2022-11-04 更变需求,如果改床位有排班,但是没上机,则进行互换床位操作
  2073. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  2074. if daySchedule.ID > 0 {
  2075. //daySchedule.PartitionId = deviceNumber.ZoneID
  2076. //daySchedule.BedId = bedID
  2077. //daySchedule.ScheduleType = schedual_type
  2078. //daySchedule.UpdatedTime = time.Now().Unix()
  2079. //err := service.UpdateSchedule(&daySchedule)
  2080. //xtSchedule := models.Schedule{
  2081. // PartitionId: deviceNumber.ZoneID,
  2082. // BedId: bedID,
  2083. // ScheduleType: schedual_type,
  2084. // UpdatedTime: time.Now().Unix(),
  2085. //}
  2086. //err := service.UpdateScheduleOne(daySchedule.ID, xtSchedule)
  2087. service.UpdateScheduleTwo(daySchedule, schedule)
  2088. }
  2089. }
  2090. } else if schedule.ID > 0 && schedule.DialysisOrder.ID > 0 { //有排班且有上机记录
  2091. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  2092. return
  2093. }
  2094. //else if order.ID == 0 { //该床位没被占用
  2095. // daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  2096. // if daySchedule.ID > 0 {
  2097. // //daySchedule.PartitionId = deviceNumber.ZoneID
  2098. // //daySchedule.BedId = bedID
  2099. // //daySchedule.ScheduleType = schedual_type
  2100. // //daySchedule.UpdatedTime = time.Now().Unix()
  2101. // //err := service.UpdateSchedule(&daySchedule)
  2102. // xtSchedule := models.Schedule{
  2103. // PartitionId: deviceNumber.ZoneID,
  2104. // BedId: bedID,
  2105. // ScheduleType: schedual_type,
  2106. // UpdatedTime: time.Now().Unix(),
  2107. // }
  2108. // err := service.UpdateScheduleOne(daySchedule.ID, xtSchedule)
  2109. // if err != nil {
  2110. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2111. // return
  2112. // }
  2113. // }
  2114. //}
  2115. //}
  2116. } else if err != nil {
  2117. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2118. return
  2119. }
  2120. dialysisRecord = &models.DialysisOrder{
  2121. DialysisDate: recordDate.Unix(),
  2122. UserOrgId: adminUserInfo.Org.Id,
  2123. PatientId: patientID,
  2124. Stage: 1,
  2125. BedID: bedID,
  2126. StartNurse: nurseID,
  2127. Status: 1,
  2128. StartTime: startDate.Unix(),
  2129. CreatedTime: time.Now().Unix(),
  2130. UpdatedTime: time.Now().Unix(),
  2131. PunctureNurse: puncture_nurse,
  2132. Creator: adminUserInfo.AdminUser.Id,
  2133. Modifier: adminUserInfo.AdminUser.Id,
  2134. SchedualType: schedual_type,
  2135. WashpipeNurse: washpipe_nurse,
  2136. ChangeNurse: change_nurse,
  2137. DifficultPunctureNurse: difficult_puncture_nurse,
  2138. NewFistulaNurse: new_fistula_nurse,
  2139. ZoneId: zone_id,
  2140. QualityNurseId: quality_nurse_id,
  2141. PunctureNeedle: puncture_needle,
  2142. PunctureWay: puncture_way,
  2143. DialysisIrrigation: dialysis_irrigation,
  2144. DialysisDialyszers: dialysis_dialyszers,
  2145. BloodAccessId: blood_access_id,
  2146. Url: elecsign,
  2147. NucleinDate: theNucleinDate,
  2148. ScheduleRemark: schedule_remark,
  2149. OrderRemark: order_remark,
  2150. CatheterOperation: catheter_operation,
  2151. }
  2152. //查询该床位是否有人用了
  2153. _, errorscode := service.GetDialysisOrderByBedId(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  2154. if errorscode == gorm.ErrRecordNotFound {
  2155. createErr := service.MobileCreateDialysisOrder(adminUserInfo.Org.Id, patientID, dialysisRecord)
  2156. service.UpdateMobilePatient(adminUserInfo.Org.Id, patientID, schedule_remark)
  2157. if adminUserInfo.Org.Id != 10101 && adminUserInfo.Org.Id != 10445 && adminUserInfo.Org.Id != 3877 && adminUserInfo.Org.Id != 10345 {
  2158. //统计该患者总次数
  2159. dialysisCount, _ := service.GetDialysisTotalCount(adminUserInfo.Org.Id, patientID)
  2160. service.UpdateDialysisOrder(patientID, recordDate.Unix(), adminUserInfo.Org.Id, dialysisCount.Count)
  2161. }
  2162. if adminUserInfo.Org.Id == 10101 || adminUserInfo.Org.Id == 10445 || adminUserInfo.Org.Id == 3877 || adminUserInfo.Org.Id == 10345 {
  2163. //统计该患者总次数
  2164. dialysisCount, _ := service.GetDialysisTotalCountOne(adminUserInfo.Org.Id, patientID)
  2165. service.UpdateDialysisOrder(patientID, recordDate.Unix(), adminUserInfo.Org.Id, dialysisCount.Count)
  2166. }
  2167. redis := service.RedisClient()
  2168. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patientID, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":dialysis_order"
  2169. redis.Set(key, "", time.Second)
  2170. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":dialysis_orders_list_all"
  2171. //清空key 值
  2172. redis.Set(keyOne, "", time.Second)
  2173. keyTwo := "scheduals_" + recordDateStr + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  2174. //清空key 值
  2175. redis.Set(keyTwo, "", time.Second)
  2176. if createErr != nil {
  2177. this.ErrorLog("上机失败:%v", createErr)
  2178. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2179. return
  2180. }
  2181. }
  2182. newdialysisRecord, getRecordErr := service.MobileGetDialysisRecord(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  2183. var tempdispose string
  2184. // 只针对中能建
  2185. if blood_drawing > 0 && adminUserInfo.Org.Id == 9538 {
  2186. tempdispose = "引血" + strconv.FormatInt(blood_drawing, 10) + "ml/min"
  2187. }
  2188. if blood_drawing > 0 && adminUserInfo.Org.Id == 10318 {
  2189. tempdispose = "引血" + strconv.FormatInt(blood_drawing, 10) + "ml/min"
  2190. }
  2191. var ultrafiltration_rate float64
  2192. _, prescription := service.FindDialysisPrescriptionByReordDate(patientID, schedulestartTime, adminUserInfo.Org.Id)
  2193. //后期预增脱水量
  2194. _, evaluation := service.FindPredialysisEvaluationByReordDate(patientID, schedulestartTime, adminUserInfo.Org.Id)
  2195. if prescription.ID > 0 {
  2196. if prescription.TargetUltrafiltration > 0 && prescription.DialysisDurationHour > 0 {
  2197. totalMin := prescription.DialysisDurationHour*60 + prescription.DialysisDurationMinute
  2198. if (template.TemplateId == 6 || template.TemplateId == 32) && adminUserInfo.Org.Id != 9671 { //adminUserInfo.Org.Id == 9538
  2199. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1000)
  2200. }
  2201. //针对医师汇
  2202. if adminUserInfo.Org.Id == 10121 {
  2203. dehydration, _ := strconv.ParseFloat(evaluation.Dehydration, 64)
  2204. ultrafiltration_rate = math.Floor((prescription.TargetUltrafiltration + dehydration) / float64(totalMin) * 60 * 1000)
  2205. }
  2206. //针对通道
  2207. if adminUserInfo.Org.Id == 10234 {
  2208. ultrafiltration_rate = math.Floor((prescription.TargetUltrafiltration) / float64(totalMin) * 60 * 1000)
  2209. }
  2210. //针对监利大垸医院
  2211. if template.TemplateId == 41 {
  2212. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / float64(totalMin) * 1000)
  2213. }
  2214. //针对肇庆三鹤血液透析中心
  2215. if template.TemplateId == 43 || adminUserInfo.Org.Id == 10432 || adminUserInfo.Org.Id == 10441 || adminUserInfo.Org.Id == 10445 {
  2216. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / float64(totalMin))
  2217. }
  2218. if template.TemplateId == 20 || template.TemplateId == 22 { //adminUserInfo.Org.Id == 9538
  2219. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60)
  2220. }
  2221. // 只针对方济医院
  2222. if template.TemplateId == 1 && adminUserInfo.Org.Id != 9849 {
  2223. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", prescription.TargetUltrafiltration/float64(totalMin)*60), 6)
  2224. ultrafiltration_rate = value
  2225. }
  2226. }
  2227. }
  2228. record := models.MonitoringRecord{
  2229. UserOrgId: adminUserInfo.Org.Id,
  2230. PatientId: patientID,
  2231. DialysisOrderId: dialysisRecord.ID,
  2232. MonitoringDate: schedulestartTime,
  2233. OperateTime: startDate.Unix(),
  2234. // MonitoringTime: recordTime,
  2235. MonitoringNurse: nurseID,
  2236. Dispose: tempdispose,
  2237. UltrafiltrationRate: ultrafiltration_rate,
  2238. UltrafiltrationVolume: 0,
  2239. Status: 1,
  2240. CreatedTime: time.Now().Unix(),
  2241. UpdatedTime: time.Now().Unix(),
  2242. }
  2243. //只针对广慈医院
  2244. 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 {
  2245. // 查询病人是否有透前评估数据
  2246. befor, errcode := service.GetAssessmentBefor(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  2247. //如果有数据就插入
  2248. if errcode == nil {
  2249. record.SystolicBloodPressure = befor.SystolicBloodPressure
  2250. record.DiastolicBloodPressure = befor.DiastolicBloodPressure
  2251. record.BreathingRate = befor.BreathingRate
  2252. record.PulseFrequency = befor.PulseFrequency
  2253. record.Temperature = befor.Temperature
  2254. }
  2255. }
  2256. // 如果当天有插入数据,则不再往透析纪录里插入数据
  2257. if newdialysisRecord.ID > 0 {
  2258. if adminUserInfo.Org.Id == 10340 || adminUserInfo.Org.Id == 9675 {
  2259. record.Temperature = 36.5
  2260. record.ArterialPressure = -100
  2261. record.DialysateTemperature = 36.5
  2262. record.Conductivity = 14
  2263. record.BreathingRate = "20"
  2264. record.VenousPressure = 80
  2265. record.TransmembranePressure = 60
  2266. }
  2267. //针对新化博翔
  2268. if adminUserInfo.Org.Id == 9671 || adminUserInfo.Org.Id == 10447 {
  2269. record.BloodOxygenSaturation = "99"
  2270. record.Conductivity = 14
  2271. record.DialysateTemperature = 36.5
  2272. record.BreathingRate = "20"
  2273. }
  2274. //针对兰溪人民医院的需求
  2275. if adminUserInfo.Org.Id == 10430 || adminUserInfo.Org.Id == 9671 {
  2276. befor, _ := service.GetAssessmentBeforThrity(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  2277. record.SystolicBloodPressure = befor.SystolicBloodPressure
  2278. record.DiastolicBloodPressure = befor.DiastolicBloodPressure
  2279. record.Temperature = befor.Temperature
  2280. record.PulseFrequency = befor.PulseFrequency
  2281. record.BreathingRate = befor.BreathingRate
  2282. }
  2283. //新化博翔
  2284. if adminUserInfo.Org.Id == 10447 {
  2285. befor, _ := service.GetAssessmentBeforThrity(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  2286. record.SystolicBloodPressure = befor.SystolicBloodPressure
  2287. record.DiastolicBloodPressure = befor.DiastolicBloodPressure
  2288. record.BreathingRate = befor.BreathingRate
  2289. }
  2290. if adminUserInfo.Org.Id == 9829 {
  2291. record.PulseFrequency = 80
  2292. record.Temperature = 36.5
  2293. }
  2294. err := service.CreateMonitor(&record)
  2295. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patientID, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":monitor_records"
  2296. redis := service.RedisClient()
  2297. //清空key 值
  2298. redis.Set(key, "", time.Second)
  2299. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":monitor_record_list_all"
  2300. redis.Set(keyOne, "", time.Second)
  2301. defer redis.Close()
  2302. if err != nil {
  2303. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeMonitorCreate)
  2304. return
  2305. }
  2306. }
  2307. go func() {
  2308. ssoDomain := beego.AppConfig.String("call_domain")
  2309. api := ssoDomain + "/index/uppatient"
  2310. values := make(url.Values)
  2311. values.Set("org_id", strconv.FormatInt(adminUserInfo.Org.Id, 10))
  2312. values.Set("admin_user_id", strconv.FormatInt(nurseID, 10))
  2313. values.Set("patient_id", strconv.FormatInt(patientID, 10))
  2314. values.Set("up_time", strconv.FormatInt(startDate.Unix(), 10))
  2315. http.PostForm(api, values)
  2316. }()
  2317. this.ServeSuccessJSON(map[string]interface{}{
  2318. "dialysis_order": newdialysisRecord,
  2319. "monitor": record,
  2320. })
  2321. return
  2322. }
  2323. func (c *DialysisAPIController) PostSolution() {
  2324. id, _ := c.GetInt64("patient", 0)
  2325. recordDateStr := c.GetString("record_date")
  2326. if id <= 0 {
  2327. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2328. return
  2329. }
  2330. adminUserInfo := c.GetMobileAdminUserInfo()
  2331. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  2332. if patient.ID == 0 {
  2333. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  2334. return
  2335. }
  2336. if len(recordDateStr) == 0 {
  2337. recordDateStr = time.Now().Format("2006-01-02")
  2338. }
  2339. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  2340. if parseDateErr != nil {
  2341. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  2342. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2343. return
  2344. }
  2345. mode_id, _ := c.GetInt64("mode_id", 0)
  2346. dialysis_duration, _ := c.GetFloat("dialysis_duration", 0)
  2347. dialyzer, _ := c.GetInt64("dialyzer", 0)
  2348. perfusion_apparatus, _ := c.GetInt64("perfusion_apparatus", 0)
  2349. blood_flow_volume, _ := c.GetFloat("blood_flow_volume", 0)
  2350. dewater_amount, _ := c.GetFloat("dewater_amount", 0)
  2351. displace_liqui, _ := c.GetFloat("displace_liqui", 0)
  2352. replacement_way, _ := c.GetInt64("replacement_way", 0)
  2353. anticoagulant, _ := c.GetInt64("anticoagulant", 0)
  2354. anticoagulant_shouji, _ := c.GetFloat("anticoagulant_shouji", 0)
  2355. anticoagulant_weichi, _ := c.GetFloat("anticoagulant_weichi", 0)
  2356. anticoagulant_zongliang, _ := c.GetFloat("anticoagulant_zongliang", 0)
  2357. anticoagulant_gaimingcheng := c.GetString("anticoagulant_gaimingcheng")
  2358. anticoagulant_gaijiliang := c.GetString("anticoagulant_gaijiliang")
  2359. kalium, _ := c.GetFloat("kalium", 0)
  2360. sodium, _ := c.GetFloat("sodium", 0)
  2361. calcium, _ := c.GetFloat("calcium", 0)
  2362. bicarbonate, _ := c.GetFloat("bicarbonate", 0)
  2363. prescription_doctor, _ := c.GetInt64("prescription_doctor", 0)
  2364. dialyzerPerfusionApparatus := c.GetString("dialyzer_perfusion_apparatus")
  2365. glucose, _ := c.GetFloat("glucose", 0)
  2366. // dry_weight, _ := c.GetFloat("dry_weight", 0)
  2367. dialysate_flow, _ := c.GetFloat("dialysate_flow", 0)
  2368. dialysate_temperature, _ := c.GetFloat("dialysate_temperature", 0)
  2369. conductivity, _ := c.GetFloat("conductivity", 0)
  2370. remark := c.GetString("remark")
  2371. dialysisDurationHour, _ := c.GetInt64("dialysis_duration_hour", 0)
  2372. dialysisDurationMinute, _ := c.GetInt64("dialysis_duration_minute", 0)
  2373. targetUltrafiltration, _ := c.GetFloat("target_ultrafiltration", 0)
  2374. dialysateFormulation, _ := c.GetInt64("dialysate_formulation", 0)
  2375. body_fluid, _ := c.GetInt64("body_fluid", 0)
  2376. special_medicine, _ := c.GetInt64("special_medicine", 0)
  2377. special_medicine_other := c.GetString("special_medicine_other")
  2378. displace_liqui_part, _ := c.GetInt64("displace_liqui_part", 0)
  2379. displace_liqui_value, _ := c.GetFloat("displace_liqui_value", 0)
  2380. blood_access, _ := c.GetInt64("blood_access", 0)
  2381. ultrafiltration, _ := c.GetFloat("ultrafiltration", 0)
  2382. body_fluid_other := c.GetString("body_fluid_other")
  2383. replacement_total, _ := c.GetFloat("replacement_total", 0)
  2384. niprocart, _ := c.GetInt64("niprocart", 0)
  2385. jms, _ := c.GetInt64("jms", 0)
  2386. fistula_needle_set, _ := c.GetInt64("fistula_needle_set", 0)
  2387. fistula_needle_set_16, _ := c.GetInt64("fistula_needle_set_16", 0)
  2388. hemoperfusion, _ := c.GetInt64("hemoperfusion", 0)
  2389. dialyser_sterilised, _ := c.GetInt64("dialyser_sterilised", 0)
  2390. filtryzer, _ := c.GetInt64("filtryzer", 0)
  2391. target_ktv, _ := c.GetFloat("target_ktv", 0)
  2392. dialyzers, _ := c.GetInt64("dialyzers", 0)
  2393. injector, _ := c.GetInt64("injector", 0)
  2394. bloodlines, _ := c.GetInt64("bloodlines", 0)
  2395. tubing_hemodialysis, _ := c.GetInt64("tubing_hemodialysis", 0)
  2396. safe_package, _ := c.GetInt64("package", 0)
  2397. a_liquid, _ := c.GetInt64("a_liquid", 0)
  2398. anticoagulant_stop_time_hour, _ := c.GetInt64("anticoagulant_stop_time_hour", 0)
  2399. anticoagulant_stop_time_min, _ := c.GetInt64("anticoagulant_stop_time_min", 0)
  2400. blood := c.GetString("blood")
  2401. dialysis_dialyszers := c.GetString("dialysis_dialyszers")
  2402. dialysis_irrigation := c.GetString("dialysis_irrigation")
  2403. antioxidant_commodity_name := c.GetString("antioxidant_commodity_name")
  2404. displace_speed := c.GetString("displace_speed")
  2405. illness, _ := c.GetInt64("illness")
  2406. amylaceum := c.GetString("amylaceum")
  2407. single_time := c.GetString("single_time")
  2408. single_water := c.GetString("single_water")
  2409. replacement_flow := c.GetString("replacement_flow")
  2410. plasma_separator := c.GetString("plasma_separator")
  2411. bilirubin_adsorption_column := c.GetString("bilirubin_adsorption_column")
  2412. oxygen_uptake, _ := c.GetInt64("oxygen_uptake")
  2413. oxygen_flow := c.GetString("oxygen_flow")
  2414. oxygen_time := c.GetString("oxygen_time")
  2415. hemodialysis_pipelines := c.GetString("hemodialysis_pipelines")
  2416. hemodialysis_pipelines_count, _ := c.GetFloat("hemodialysis_pipelines_count", 0)
  2417. puncture_needle := c.GetString("puncture_needle")
  2418. puncture_needle_count, _ := c.GetFloat("puncture_needle_count", 0)
  2419. epo := c.GetString("epo")
  2420. epo_count, _ := c.GetFloat("epo_count", 0)
  2421. max_ultrafiltration_rate, _ := c.GetFloat("max_ultrafiltration_rate")
  2422. pre_impulse := c.GetString("pre_impulse")
  2423. impulse, _ := strconv.ParseFloat(pre_impulse, 64)
  2424. admin_user_id, _ := c.GetInt64("admin_user_id")
  2425. is_water := c.GetString("is_water")
  2426. add_amount, _ := c.GetFloat("add_amount")
  2427. reduce_amount, _ := c.GetFloat("reduce_amount")
  2428. var is_war int64
  2429. if is_water == "是" {
  2430. is_war = 1
  2431. }
  2432. if is_water == "否" {
  2433. is_war = 2
  2434. }
  2435. if is_water == "请选择" {
  2436. is_war = 0
  2437. }
  2438. drhy_water := c.GetString("drhy_water")
  2439. dry_water_hour := c.GetString("dry_water_hour")
  2440. water_machine := c.GetString("water_machine")
  2441. dialysis_remark := c.GetString("dialysis_remark")
  2442. if mode_id > 0 {
  2443. var str string
  2444. //查找该机构用的是什么透析器
  2445. filedConfig, _ := service.GetFiledConfig(adminUserInfo.Org.Id)
  2446. if filedConfig.ID > 0 {
  2447. str = dialyzerPerfusionApparatus
  2448. } else {
  2449. str = dialysis_dialyszers + "/" + dialysis_irrigation
  2450. }
  2451. service.ModifyScheduleMode(mode_id, patient.ID, recordDate.Unix(), adminUserInfo.Org.Id, str)
  2452. }
  2453. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  2454. //
  2455. //if template.TemplateId == 2 || template.TemplateId == 6 {
  2456. // if appRole.UserType == 3 {
  2457. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  2458. // if getPermissionErr != nil {
  2459. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2460. // return
  2461. // } else if headNursePermission == nil {
  2462. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  2463. // return
  2464. // }
  2465. // }
  2466. //}
  2467. prescription := models.DialysisPrescription{
  2468. UserOrgId: adminUserInfo.Org.Id,
  2469. PatientId: id,
  2470. RecordDate: recordDate.Unix(),
  2471. ModeId: mode_id,
  2472. DialysisDuration: dialysis_duration,
  2473. Dialyzer: dialyzer,
  2474. PerfusionApparatus: perfusion_apparatus,
  2475. BloodFlowVolume: blood_flow_volume,
  2476. DewaterAmount: dewater_amount,
  2477. DisplaceLiqui: displace_liqui,
  2478. ReplacementWay: replacement_way,
  2479. Anticoagulant: anticoagulant,
  2480. AnticoagulantShouji: anticoagulant_shouji,
  2481. AnticoagulantWeichi: anticoagulant_weichi,
  2482. AnticoagulantZongliang: anticoagulant_zongliang,
  2483. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  2484. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  2485. Kalium: kalium,
  2486. Sodium: sodium,
  2487. Calcium: calcium,
  2488. Bicarbonate: bicarbonate,
  2489. Glucose: glucose,
  2490. // DryWeight: dry_weight,
  2491. DialysateFlow: dialysate_flow,
  2492. DialysateTemperature: dialysate_temperature,
  2493. Conductivity: conductivity,
  2494. Remark: remark,
  2495. Status: 1,
  2496. CreatedTime: time.Now().Unix(),
  2497. UpdatedTime: time.Now().Unix(),
  2498. DialysisDurationMinute: dialysisDurationMinute,
  2499. DialysisDurationHour: dialysisDurationHour,
  2500. TargetUltrafiltration: targetUltrafiltration,
  2501. DialysateFormulation: dialysateFormulation,
  2502. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  2503. BodyFluid: body_fluid,
  2504. SpecialMedicine: special_medicine,
  2505. SpecialMedicineOther: special_medicine_other,
  2506. DisplaceLiquiPart: displace_liqui_part,
  2507. DisplaceLiquiValue: displace_liqui_value,
  2508. BloodAccess: blood_access,
  2509. Ultrafiltration: ultrafiltration,
  2510. BodyFluidOther: body_fluid_other,
  2511. ReplacementTotal: replacement_total,
  2512. Niprocart: niprocart,
  2513. Jms: jms,
  2514. FistulaNeedleSet: fistula_needle_set,
  2515. FistulaNeedleSet16: fistula_needle_set_16,
  2516. Hemoperfusion: hemoperfusion,
  2517. DialyserSterilised: dialyser_sterilised,
  2518. Filtryzer: filtryzer,
  2519. TargetKtv: target_ktv,
  2520. Dialyzers: dialyzers,
  2521. Injector: injector,
  2522. Bloodlines: bloodlines,
  2523. TubingHemodialysis: tubing_hemodialysis,
  2524. Package: safe_package,
  2525. ALiquid: a_liquid,
  2526. AnticoagulantStopTimeMin: anticoagulant_stop_time_min,
  2527. AnticoagulantStopTimeHour: anticoagulant_stop_time_hour,
  2528. Blood: blood,
  2529. DialysisDialyszers: dialysis_dialyszers,
  2530. DialysisIrrigation: dialysis_irrigation,
  2531. AntioxidantCommodityName: antioxidant_commodity_name,
  2532. DisplaceSpeed: displace_speed,
  2533. Illness: illness,
  2534. Amylaceum: amylaceum,
  2535. SingleWater: single_water,
  2536. SingleTime: single_time,
  2537. ReplacementFlow: replacement_flow,
  2538. PlasmaSeparator: plasma_separator,
  2539. BilirubinAdsorptionColumn: bilirubin_adsorption_column,
  2540. OxygenUptake: oxygen_uptake,
  2541. OxygenTime: oxygen_time,
  2542. OxygenFlow: oxygen_flow,
  2543. HemodialysisPipelines: hemodialysis_pipelines,
  2544. HemodialysisPipelinesCount: hemodialysis_pipelines_count,
  2545. PunctureNeedle: puncture_needle,
  2546. PunctureNeedleCount: puncture_needle_count,
  2547. Epo: epo,
  2548. EpoCount: epo_count,
  2549. MaxUltrafiltrationRate: max_ultrafiltration_rate,
  2550. PreImpulse: impulse,
  2551. AdminUserId: admin_user_id,
  2552. IsWater: is_war,
  2553. DrhyWater: drhy_water,
  2554. DryWaterHour: dry_water_hour,
  2555. WaterMachine: water_machine,
  2556. AddAmount: add_amount,
  2557. ReduceAmount: reduce_amount,
  2558. DialysisRemark: dialysis_remark,
  2559. }
  2560. _, dialysisPrescription := service.FindDialysisPrescriptionByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  2561. appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id, adminUserInfo.App.Id)
  2562. //
  2563. if appRole.UserType == 2 || appRole.UserType == 1 {
  2564. prescription_doctor = adminUserInfo.AdminUser.Id
  2565. prescription.PrescriptionDoctor = prescription_doctor
  2566. }
  2567. if dialysisPrescription.ID == 0 { //新增
  2568. prescription.Creater = adminUserInfo.AdminUser.Id
  2569. } else { //修改
  2570. if dialysisPrescription.Creater == 0 {
  2571. prescription.Creater = adminUserInfo.AdminUser.Id
  2572. } else {
  2573. prescription.Creater = dialysisPrescription.Creater
  2574. }
  2575. //if/**/
  2576. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  2577. //if dialysisPrescription.Creater != adminUserInfo.AdminUser.Id && dialysisPrescription.Creater > 0 {
  2578. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  2579. // if getPermissionErr != nil {
  2580. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2581. // return
  2582. // } else if headNursePermission == nil {
  2583. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  2584. // return
  2585. // }
  2586. //}
  2587. //prescription.Creater = dialysisPrescription.Creater
  2588. prescription.CreatedTime = dialysisPrescription.CreatedTime
  2589. prescription.Modifier = adminUserInfo.AdminUser.Id
  2590. prescription.ID = dialysisPrescription.ID
  2591. }
  2592. solution := models.DialysisSolution{
  2593. RegistrarsId: adminUserInfo.AdminUser.Id,
  2594. UserOrgId: adminUserInfo.Org.Id,
  2595. Doctor: prescription_doctor,
  2596. PatientId: id,
  2597. ModeId: mode_id,
  2598. DialysisDuration: dialysis_duration,
  2599. PerfusionApparatus: perfusion_apparatus,
  2600. BloodFlowVolume: blood_flow_volume,
  2601. Dewater: dewater_amount,
  2602. DisplaceLiqui: displace_liqui,
  2603. ReplacementWay: replacement_way,
  2604. Anticoagulant: anticoagulant,
  2605. AnticoagulantShouji: anticoagulant_shouji,
  2606. AnticoagulantWeichi: anticoagulant_weichi,
  2607. AnticoagulantZongliang: anticoagulant_zongliang,
  2608. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  2609. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  2610. Kalium: kalium,
  2611. Sodium: sodium,
  2612. Calcium: calcium,
  2613. Bicarbonate: bicarbonate,
  2614. Glucose: glucose,
  2615. // DryWeight: dry_weight,
  2616. DialysateFlow: dialysate_flow,
  2617. DialysateTemperature: dialysate_temperature,
  2618. Conductivity: conductivity,
  2619. Remark: remark,
  2620. Status: 1,
  2621. CreatedTime: time.Now().Unix(),
  2622. UpdatedTime: time.Now().Unix(),
  2623. DialysisDurationMinute: dialysisDurationMinute,
  2624. DialysisDurationHour: dialysisDurationHour,
  2625. TargetUltrafiltration: targetUltrafiltration,
  2626. DialysateFormulation: dialysateFormulation,
  2627. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  2628. BodyFluid: body_fluid,
  2629. SpecialMedicine: special_medicine,
  2630. SpecialMedicineOther: special_medicine_other,
  2631. DisplaceLiquiPart: displace_liqui_part,
  2632. DisplaceLiquiValue: displace_liqui_value,
  2633. BloodAccess: blood_access,
  2634. Ultrafiltration: ultrafiltration,
  2635. BodyFluidOther: body_fluid_other,
  2636. ReplacementTotal: replacement_total,
  2637. TargetKtv: target_ktv,
  2638. DialysisDialyszers: dialysis_dialyszers,
  2639. DialysisIrrigation: dialysis_irrigation,
  2640. HemodialysisPipelines: hemodialysis_pipelines,
  2641. HemodialysisPipelinesCount: hemodialysis_pipelines_count,
  2642. PunctureNeedle: puncture_needle,
  2643. PunctureNeedleCount: puncture_needle_count,
  2644. Epo: epo,
  2645. EpoCount: epo_count,
  2646. MaxUltrafiltrationRate: max_ultrafiltration_rate,
  2647. PreImpulse: impulse,
  2648. SolutionStatus: 1,
  2649. DialysisRemark: dialysis_remark,
  2650. }
  2651. //针对河间咸的
  2652. if adminUserInfo.Org.Id == 10090 || adminUserInfo.Org.Id == 10164 || adminUserInfo.Org.Id == 3877 {
  2653. if solution.ModeId != 2 && solution.ModeId != 5 && solution.ModeId != 12 {
  2654. solution.DisplaceLiquiPart = 0
  2655. solution.DisplaceLiquiValue = 0
  2656. }
  2657. if prescription.ModeId != 2 && prescription.ModeId != 5 && prescription.ModeId != 12 {
  2658. prescription.DisplaceLiquiPart = 0
  2659. prescription.DisplaceLiquiValue = 0
  2660. }
  2661. }
  2662. service.SavePrescriptionAndCreateSolution(&solution, &prescription)
  2663. //获取最新1条
  2664. dialysisSolution, _ := service.GetLastPatientDialysisSolution(id, adminUserInfo.Org.Id)
  2665. //更新状态
  2666. service.UpdateDialysisSolutionStatusTwo(dialysisSolution.ID, dialysisSolution.ModeId, dialysisSolution.UserOrgId, dialysisSolution.PatientId)
  2667. //获取key,清空redis
  2668. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":" + strconv.FormatInt(mode_id, 10) + ":dialysis_prescribe"
  2669. redis := service.RedisClient()
  2670. defer redis.Close()
  2671. //清空key 值
  2672. redis.Set(key, "", time.Second)
  2673. //清空长期医嘱的key
  2674. soulution_key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(mode_id, 10) + ":dialysis_solution"
  2675. redis.Set(soulution_key, "", time.Second)
  2676. //查询最近透析准备表里是否存在 透析器 灌流器
  2677. keyOne := "scheduals_" + recordDateStr + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  2678. redis.Set(keyOne, "", time.Second)
  2679. keyTwo := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":schedual_detail"
  2680. redis.Set(keyTwo, "", time.Second)
  2681. keyThree := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":prescriptions_list_all"
  2682. redis.Set(keyThree, "", time.Second)
  2683. keyFour := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":dialysis_prescribe_by_mode"
  2684. redis.Set(keyFour, "", time.Second)
  2685. //splitStr := strings.Split(dialysis_dialyszers, ",")
  2686. //
  2687. //splitIrrigation := strings.Split(dialysis_irrigation, ",")
  2688. //
  2689. //mation, _ := service.GetGoodInfoMation(adminUserInfo.Org.Id)
  2690. //if len(mation)>0{
  2691. // for _, item := range splitStr {
  2692. // for _,it := range mation{
  2693. // if(item == it.SpecificationName){
  2694. //
  2695. // //查询最近一次的透析器
  2696. // _, errcode := service.GetDialysisBeforePrepare(it.GoodTypeId, it.ID, adminUserInfo.Org.Id,id)
  2697. //
  2698. // if errcode == gorm.ErrRecordNotFound{
  2699. // //插入数据
  2700. // prepare := models.DialysisBeforePrepare{
  2701. // UserOrgId: adminUserInfo.Org.Id,
  2702. // PatientId: id,
  2703. // RecordDate: recordDate.Unix(),
  2704. // GoodTypeId: it.GoodTypeId,
  2705. // GoodId: it.ID,
  2706. // Count: 1,
  2707. // Ctime: time.Now().Unix(),
  2708. // Creater: adminUserInfo.AdminUser.Id,
  2709. // Status:1,
  2710. //
  2711. // }
  2712. // errcode := service.CreateDialysisBeforePrepareOne(&prepare)
  2713. // fmt.Println("",errcode)
  2714. // }
  2715. // }
  2716. // }
  2717. //
  2718. // }
  2719. //
  2720. // for _, item := range splitIrrigation {
  2721. // for _,it := range mation{
  2722. // if(item == it.SpecificationName){
  2723. // //查询最近一次的透析器
  2724. // _, errcode := service.GetDialysisBeforePrepare(it.GoodTypeId, it.ID, adminUserInfo.Org.Id,id)
  2725. // if errcode == gorm.ErrRecordNotFound{
  2726. // //插入数据
  2727. // prepare := models.DialysisBeforePrepare{
  2728. // UserOrgId: adminUserInfo.Org.Id,
  2729. // PatientId: id,
  2730. // RecordDate: recordDate.Unix(),
  2731. // GoodTypeId: it.GoodTypeId,
  2732. // GoodId: it.ID,
  2733. // Count: 1,
  2734. // Ctime: time.Now().Unix(),
  2735. // Creater: adminUserInfo.AdminUser.Id,
  2736. // Status:1,
  2737. //
  2738. // }
  2739. // errcode := service.CreateDialysisBeforePrepareOne(&prepare)
  2740. // fmt.Println(errcode)
  2741. // }
  2742. // }
  2743. // }
  2744. // }
  2745. //}
  2746. c.ServeSuccessJSON(map[string]interface{}{
  2747. "solution": &solution,
  2748. "prescription": &prescription,
  2749. })
  2750. }
  2751. func (c *DialysisAPIController) GetAcceptsAssessment() {
  2752. patient, _ := c.GetInt64("patient", 0)
  2753. adminUserInfo := c.GetMobileAdminUserInfo()
  2754. _, receiveTreatmentAsses := service.GetLastAcceptsAssessment(patient, adminUserInfo.Org.Id)
  2755. c.ServeSuccessJSON(map[string]interface{}{
  2756. "receiveTreatmentAsses": receiveTreatmentAsses,
  2757. })
  2758. }
  2759. func (this *DialysisAPIController) PostSignInfo() {
  2760. patientID, _ := this.GetInt64("patient_id")
  2761. recordDateStr := this.GetString("date")
  2762. if patientID <= 0 {
  2763. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2764. return
  2765. }
  2766. if len(recordDateStr) == 0 {
  2767. recordDateStr = time.Now().Format("2006-01-02")
  2768. }
  2769. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  2770. if parseDateErr != nil {
  2771. this.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  2772. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2773. return
  2774. }
  2775. adminInfo := this.GetMobileAdminUserInfo()
  2776. err := service.UpDateDialysisPrescriptionDoctorSign(patientID, date.Unix(), adminInfo.Org.Id, adminInfo.AdminUser.Id)
  2777. if err != nil {
  2778. this.ErrorLog("签名失败:%v", err)
  2779. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2780. return
  2781. }
  2782. this.ServeSuccessJSON(map[string]interface{}{
  2783. "doctor_id": adminInfo.AdminUser.Id,
  2784. })
  2785. }
  2786. func (this *DialysisAPIController) GetLastMonitorRecord() {
  2787. patientID, _ := this.GetInt64("patient_id")
  2788. adminInfo := this.GetMobileAdminUserInfo()
  2789. record, _ := service.FindLastMonitorRecord(patientID, adminInfo.Org.Id)
  2790. this.ServeSuccessJSON(map[string]interface{}{
  2791. "monitor": record,
  2792. })
  2793. }
  2794. func (this *DialysisAPIController) GetLastMonitorRecordTody() {
  2795. thisTime := time.Now()
  2796. scheduleDateStart := thisTime.Format("2006-01-02") + " 00:00:00"
  2797. timeLayout := "2006-01-02 15:04:05"
  2798. loc, _ := time.LoadLocation("Local")
  2799. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  2800. theAssessmentDateTime := theStartTime.Unix()
  2801. patientID, _ := this.GetInt64("patient_id")
  2802. monitorDate, _ := this.GetInt64("monitoring_date", theAssessmentDateTime)
  2803. adminInfo := this.GetMobileAdminUserInfo()
  2804. record, _ := service.FindLastMonitorRecordToday(patientID, adminInfo.Org.Id, monitorDate)
  2805. fristrecord, _ := service.FindFirstMonitorRecordToday(patientID, adminInfo.Org.Id, monitorDate)
  2806. template, _ := service.GetOrgInfoTemplate(adminInfo.Org.Id)
  2807. var ultrafiltration_rate float64
  2808. _, prescription := service.FindDialysisPrescriptionByReordDate(patientID, theAssessmentDateTime, adminInfo.Org.Id)
  2809. _, evaluation := service.FindPredialysisEvaluationByReordDate(patientID, theAssessmentDateTime, adminInfo.Org.Id)
  2810. fmt.Println(evaluation)
  2811. if prescription.ID > 0 {
  2812. if prescription.TargetUltrafiltration > 0 && prescription.DialysisDurationHour > 0 {
  2813. totalMin := prescription.DialysisDurationHour*60 + prescription.DialysisDurationMinute
  2814. if template.TemplateId == 6 && adminInfo.Org.Id != 9538 {
  2815. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1000)
  2816. record.UltrafiltrationRate = ultrafiltration_rate
  2817. }
  2818. if template.TemplateId == 32 || template.TemplateId == 34 || template.TemplateId == 36 {
  2819. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1)
  2820. record.UltrafiltrationRate = ultrafiltration_rate
  2821. }
  2822. if template.TemplateId == 20 || template.TemplateId == 22 {
  2823. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60)
  2824. record.UltrafiltrationRate = ultrafiltration_rate
  2825. }
  2826. // 只针对方济医院
  2827. if template.TemplateId == 1 && adminInfo.Org.Id != 9849 {
  2828. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", prescription.TargetUltrafiltration/float64(totalMin)*60), 6)
  2829. ultrafiltration_rate = value
  2830. record.UltrafiltrationRate = ultrafiltration_rate
  2831. }
  2832. if template.TemplateId == 41 || template.TemplateId == 47 {
  2833. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / float64(totalMin) * 1000)
  2834. record.UltrafiltrationRate = ultrafiltration_rate
  2835. }
  2836. if template.TemplateId == 43 {
  2837. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / float64(totalMin))
  2838. record.UltrafiltrationRate = ultrafiltration_rate
  2839. }
  2840. if template.TemplateId == 46 || template.TemplateId == 54 {
  2841. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / float64(totalMin))
  2842. record.UltrafiltrationRate = ultrafiltration_rate
  2843. }
  2844. 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 {
  2845. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / 1000 / float64(totalMin) * 1000)
  2846. record.UltrafiltrationRate = ultrafiltration_rate
  2847. }
  2848. //if template.TemplateId == 47 {
  2849. // ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / float64(totalMin))
  2850. // record.UltrafiltrationRate = ultrafiltration_rate
  2851. //}
  2852. }
  2853. }
  2854. // record.UltrafiltrationRate = ultrafiltration_rate
  2855. record.UltrafiltrationVolume = 0
  2856. 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
  2857. if ultrafiltration_rate > 0 {
  2858. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", float64(record.OperateTime+3600-fristrecord.OperateTime)/3600*ultrafiltration_rate), 6)
  2859. record.UltrafiltrationVolume = value
  2860. }
  2861. }
  2862. 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
  2863. if ultrafiltration_rate > 0 && adminInfo.Org.Id != 9538 {
  2864. ultrafiltration_volume := math.Floor(float64(record.OperateTime+3600-fristrecord.OperateTime) / 3600 * ultrafiltration_rate)
  2865. record.UltrafiltrationVolume = ultrafiltration_volume
  2866. }
  2867. }
  2868. //长沙南雅
  2869. 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 {
  2870. if ultrafiltration_rate > 0 {
  2871. ultrafiltration_volume := math.Floor(float64(record.OperateTime+3600-fristrecord.OperateTime) / 3600 * ultrafiltration_rate)
  2872. record.UltrafiltrationVolume = ultrafiltration_volume
  2873. }
  2874. }
  2875. if template.TemplateId == 47 || template.TemplateId == 54 {
  2876. record.DisplacementQuantity = record.DisplacementQuantity + record.DisplacementQuantity
  2877. }
  2878. this.ServeSuccessJSON(map[string]interface{}{
  2879. "monitor": record,
  2880. })
  2881. }
  2882. func (this *DialysisAPIController) ModifyStartDialysisOrder() {
  2883. record_id, _ := this.GetInt64("id")
  2884. nurseID, _ := this.GetInt64("nurse")
  2885. puncture_nurse, _ := this.GetInt64("puncture_nurse")
  2886. bedID, _ := this.GetInt64("bed")
  2887. start_time := this.GetString("start_time")
  2888. schedual_type, _ := this.GetInt64("schedual_type")
  2889. washpipe_nurse, _ := this.GetInt64("washpipe_nurse")
  2890. change_nurse, _ := this.GetInt64("change_nurse")
  2891. difficult_puncture_nurse, _ := this.GetInt64("difficult_puncture_nurse")
  2892. new_fistula_nurse, _ := this.GetInt64("new_fistula_nurse")
  2893. quality_nurse_id, _ := this.GetInt64("quality_nurse_id")
  2894. patient_id, _ := this.GetInt64("patient_id")
  2895. record_date, _ := this.GetInt64("record_date")
  2896. puncture_needle := this.GetString("puncture_needle")
  2897. puncture_way := this.GetString("puncture_way")
  2898. dialysis_dialyszers := this.GetString("dialysis_dialyszers")
  2899. dialysis_irrigation := this.GetString("dialysis_irrigation")
  2900. blood_access_id, _ := this.GetInt64("blood_access_id")
  2901. nuclein_date_str := this.GetString("nuclein_date_str")
  2902. order_remark := this.GetString("order_remark")
  2903. schedule_remark := this.GetString("schedule_remark")
  2904. catheter_operation := this.GetString("catheter_operation")
  2905. if record_id == 0 {
  2906. this.ErrorLog("id:%v", record_id)
  2907. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2908. return
  2909. }
  2910. startDate, parseStartDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", start_time)
  2911. if parseStartDateErr != nil {
  2912. this.ErrorLog("时间解析失败:%v", parseStartDateErr)
  2913. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2914. return
  2915. }
  2916. adminUserInfo := this.GetMobileAdminUserInfo()
  2917. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  2918. if getNurseErr != nil {
  2919. this.ErrorLog("获取护士失败:%v", getNurseErr)
  2920. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2921. return
  2922. } else if nurse == nil {
  2923. this.ErrorLog("护士不存在")
  2924. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2925. return
  2926. }
  2927. nurse, getNurseErr = service.GetAdminUserByUserID(puncture_nurse)
  2928. //if getNurseErr != nil {
  2929. // this.ErrorLog("获取护士失败:%v", getNurseErr)
  2930. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2931. // return
  2932. //} else if nurse == nil {
  2933. // this.ErrorLog("护士不存在")
  2934. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2935. // return
  2936. //}
  2937. deviceNumber, getDeviceNumberErr := service.GetDeviceNumberByID(adminUserInfo.Org.Id, bedID)
  2938. if getDeviceNumberErr != nil {
  2939. this.ErrorLog("获取床位号失败:%v", getDeviceNumberErr)
  2940. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2941. return
  2942. } else if deviceNumber == nil {
  2943. this.ErrorLog("床位号不存在")
  2944. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2945. return
  2946. }
  2947. _, tempDialysisRecord := service.FindDialysisOrderById(record_id)
  2948. //
  2949. //if tempDialysisRecord.Creator != adminUserInfo.AdminUser.Id {
  2950. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  2951. // if getPermissionErr != nil {
  2952. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2953. // return
  2954. // } else if headNursePermission == nil {
  2955. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  2956. // return
  2957. // }
  2958. //}
  2959. scheduleDateStart := startDate.Format("2006-01-02") + " 00:00:00"
  2960. scheduleDateEnd := startDate.Format("2006-01-02") + " 23:59:59"
  2961. timeLayout := "2006-01-02 15:04:05"
  2962. loc, _ := time.LoadLocation("Local")
  2963. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  2964. theEndTime, _ := time.ParseInLocation(timeLayout, scheduleDateEnd, loc)
  2965. schedulestartTime := theStartTime.Unix()
  2966. scheduleendTime := theEndTime.Unix()
  2967. var theNucleinDate int64
  2968. timeLayoutOne := "2006-01-02"
  2969. if len(nuclein_date_str) > 0 {
  2970. theTime, err := time.ParseInLocation(timeLayoutOne+" 15:04:05", nuclein_date_str+" 00:00:00", loc)
  2971. if err != nil {
  2972. utils.ErrorLog(err.Error())
  2973. }
  2974. theNucleinDate = theTime.Unix()
  2975. }
  2976. //查询更改的机号,是否有人用了,如果只是排班了,但是没上机,直接替换,如果排班且上机了,就提示他无法上机
  2977. schedule, err := service.GetDayScheduleByBedid(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  2978. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  2979. if daySchedule.BedId != bedID || daySchedule.ScheduleType != schedual_type {
  2980. if err == gorm.ErrRecordNotFound { //空床位
  2981. // 修改了床位逻辑
  2982. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  2983. if daySchedule.ID > 0 {
  2984. //daySchedule.BedId = bedID
  2985. //daySchedule.PartitionId = deviceNumber.ZoneID
  2986. //daySchedule.ScheduleType = schedual_type
  2987. //daySchedule.UpdatedTime = time.Now().Unix()
  2988. //err := service.UpdateSchedule(&daySchedule)
  2989. xtSchedule := models.Schedule{
  2990. PartitionId: deviceNumber.ZoneID,
  2991. BedId: bedID,
  2992. ScheduleType: schedual_type,
  2993. UpdatedTime: time.Now().Unix(),
  2994. }
  2995. err := service.UpdateScheduleOne(daySchedule.ID, xtSchedule)
  2996. if err != nil {
  2997. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2998. return
  2999. }
  3000. }
  3001. } else if err == nil {
  3002. if schedule.ID > 0 && schedule.DialysisOrder.ID == 0 { //有排班没上机记录
  3003. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  3004. if daySchedule.ID > 0 {
  3005. //daySchedule.BedId = bedID
  3006. //daySchedule.PartitionId = deviceNumber.ZoneID
  3007. //
  3008. //daySchedule.ScheduleType = schedual_type
  3009. //daySchedule.UpdatedTime = time.Now().Unix()
  3010. //err := service.UpdateSchedule(&daySchedule)
  3011. xtSchedule := models.Schedule{
  3012. PartitionId: deviceNumber.ZoneID,
  3013. BedId: bedID,
  3014. ScheduleType: schedual_type,
  3015. UpdatedTime: time.Now().Unix(),
  3016. }
  3017. err := service.UpdateScheduleOne(daySchedule.ID, xtSchedule)
  3018. if err != nil {
  3019. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  3020. return
  3021. }
  3022. }
  3023. } else if schedule.ID > 0 && schedule.DialysisOrder.ID > 0 { //有排班且有上机记录
  3024. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  3025. return
  3026. }
  3027. } else if err != nil {
  3028. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  3029. return
  3030. }
  3031. }
  3032. dialysisRecord := &models.DialysisOrder{
  3033. ID: record_id,
  3034. UserOrgId: adminUserInfo.Org.Id,
  3035. BedID: bedID,
  3036. StartNurse: nurseID,
  3037. StartTime: startDate.Unix(),
  3038. PunctureNurse: puncture_nurse,
  3039. Creator: adminUserInfo.AdminUser.Id,
  3040. Modifier: adminUserInfo.AdminUser.Id,
  3041. WashpipeNurse: washpipe_nurse,
  3042. SchedualType: schedual_type,
  3043. ChangeNurse: change_nurse,
  3044. DifficultPunctureNurse: difficult_puncture_nurse,
  3045. NewFistulaNurse: new_fistula_nurse,
  3046. QualityNurseId: quality_nurse_id,
  3047. PunctureNeedle: puncture_needle,
  3048. PunctureWay: puncture_way,
  3049. DialysisDialyszers: dialysis_dialyszers,
  3050. DialysisIrrigation: dialysis_irrigation,
  3051. BloodAccessId: blood_access_id,
  3052. NucleinDate: theNucleinDate,
  3053. OrderRemark: order_remark,
  3054. ScheduleRemark: schedule_remark,
  3055. CatheterOperation: catheter_operation,
  3056. }
  3057. //修改床位号需要重新消毒
  3058. if adminUserInfo.Org.Id == 9671 || adminUserInfo.Org.Id == 10340 || adminUserInfo.Org.Id == 10445 {
  3059. service.UpdateDeviceInformation(tempDialysisRecord.PatientId, tempDialysisRecord.DialysisDate)
  3060. }
  3061. updateErr := service.ModifyStartDialysisOrder(dialysisRecord)
  3062. order, _ := service.GetLastPatientOrder(record_id)
  3063. service.UpdateMobilePatient(adminUserInfo.Org.Id, order.PatientId, schedule_remark)
  3064. redis := service.RedisClient()
  3065. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":dialysis_order"
  3066. redis.Set(key, "", time.Second)
  3067. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":dialysis_orders_list_all"
  3068. //清空key 值
  3069. redis.Set(keyOne, "", time.Second)
  3070. scheduleDateStartOne := startDate.Format("2006-01-02")
  3071. keyTwo := "scheduals_" + scheduleDateStartOne + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  3072. redis.Set(keyTwo, "", time.Second)
  3073. keyThree := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":doctor_advices"
  3074. redis.Set(keyThree, "", time.Second)
  3075. keyFour := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":monitor_records"
  3076. redis.Set(keyFour, "", time.Second)
  3077. keyFive := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":patient_info"
  3078. redis.Set(keyFive, "", time.Second)
  3079. keySix := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":his_doctor_advice"
  3080. redis.Set(keySix, "", time.Second)
  3081. keySeven := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + ":device_list_all"
  3082. redis.Set(keySeven, "", time.Second)
  3083. if updateErr != nil {
  3084. this.ErrorLog("修改上机失败:%v", updateErr)
  3085. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  3086. return
  3087. }
  3088. if updateErr == nil {
  3089. if tempDialysisRecord.Stage == 2 {
  3090. temp_time := (float64(tempDialysisRecord.EndTime) - float64(startDate.Unix())) / 3600
  3091. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  3092. fmt.Println(value)
  3093. a, b := math.Modf(value)
  3094. tempMinute, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  3095. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  3096. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", tempMinute*60), 10, 64)
  3097. updateAssessmentErr := service.UpdateAssessmentAfterDate(tempDialysisRecord.PatientId, tempDialysisRecord.UserOrgId, tempDialysisRecord.DialysisDate, hour, minute)
  3098. redis := service.RedisClient()
  3099. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":assessment_after_dislysis_list_all"
  3100. redis.Set(key, "", time.Second)
  3101. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecord.PatientId, 10) + ":" + strconv.FormatInt(record_date, 10) + ":assessment_after_dislysis"
  3102. redis.Set(keyOne, "", time.Second)
  3103. keySix := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":dialysis_orders_list_all"
  3104. //清空key 值
  3105. redis.Set(keySix, "", time.Second)
  3106. keySeven := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":monitor_records"
  3107. redis.Set(keySeven, "", time.Second)
  3108. redis.Close()
  3109. if updateAssessmentErr != nil {
  3110. utils.ErrorLog("%v", updateAssessmentErr)
  3111. }
  3112. }
  3113. }
  3114. _, dialysisRecords := service.FindDialysisOrderById(record_id)
  3115. this.ServeSuccessJSON(map[string]interface{}{
  3116. "dialysis_order": dialysisRecords,
  3117. })
  3118. }
  3119. func (c *DialysisAPIController) ModifyFinishDialysisOrder() {
  3120. record_id, _ := c.GetInt64("id")
  3121. nurseID, _ := c.GetInt64("nurse")
  3122. end_time := c.GetString("end_time")
  3123. puncture_point_haematoma, _ := c.GetInt64("puncture_point_haematoma")
  3124. blood_access_internal_fistula := c.GetString("blood_access_internal_fistula")
  3125. catheter := c.GetString("catheter")
  3126. cruor := c.GetString("cruor")
  3127. mission := c.GetString("mission")
  3128. if record_id <= 0 || nurseID <= 0 {
  3129. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3130. return
  3131. }
  3132. adminUserInfo := c.GetMobileAdminUserInfo()
  3133. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  3134. if getNurseErr != nil {
  3135. c.ErrorLog("获取护士失败:%v", getNurseErr)
  3136. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  3137. return
  3138. } else if nurse == nil {
  3139. c.ErrorLog("护士不存在")
  3140. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3141. return
  3142. }
  3143. endDate, parseEndDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", end_time)
  3144. if parseEndDateErr != nil {
  3145. c.ErrorLog("日期(%v)解析错误:%v", end_time, parseEndDateErr)
  3146. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3147. return
  3148. }
  3149. _, tempDialysisRecords := service.FindDialysisOrderById(record_id)
  3150. //if tempDialysisRecords.FinishCreator != adminUserInfo.AdminUser.Id {
  3151. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  3152. // if getPermissionErr != nil {
  3153. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  3154. // return
  3155. // } else if headNursePermission == nil {
  3156. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  3157. // return
  3158. // }
  3159. //}
  3160. dialysisRecord := &models.DialysisOrder{
  3161. ID: record_id,
  3162. UserOrgId: adminUserInfo.Org.Id,
  3163. EndTime: endDate.Unix(),
  3164. FinishNurse: nurseID,
  3165. FinishModifier: adminUserInfo.AdminUser.Id,
  3166. PuncturePointHaematoma: puncture_point_haematoma,
  3167. BloodAccessInternalFistula: blood_access_internal_fistula,
  3168. Catheter: catheter,
  3169. Cruor: cruor,
  3170. Mission: mission,
  3171. }
  3172. updateErr := service.ModifyFinishDialysisOrder(dialysisRecord)
  3173. redis := service.RedisClient()
  3174. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.PatientId, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":dialysis_order"
  3175. //清空key 值
  3176. redis.Set(key, "", time.Second)
  3177. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":dialysis_orders_list_all"
  3178. //清空key 值
  3179. redis.Set(keyOne, "", time.Second)
  3180. keySeven := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.PatientId, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":monitor_records"
  3181. redis.Set(keySeven, "", time.Second)
  3182. redis.Close()
  3183. if updateErr != nil {
  3184. c.ErrorLog("修改下机失败:%v", updateErr)
  3185. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  3186. return
  3187. }
  3188. if updateErr == nil {
  3189. temp_time := (float64(endDate.Unix()) - float64(tempDialysisRecords.StartTime)) / 3600
  3190. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  3191. a, b := math.Modf(value)
  3192. tempMinute, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  3193. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  3194. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", tempMinute*60), 10, 64)
  3195. updateAssessmentErr := service.UpdateAssessmentAfterDate(tempDialysisRecords.PatientId, tempDialysisRecords.UserOrgId, tempDialysisRecords.DialysisDate, hour, minute)
  3196. redis := service.RedisClient()
  3197. keyTen := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.PatientId, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":assessment_after_dislysis"
  3198. redis.Set(keyTen, "", time.Second)
  3199. keyTwo := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.PatientId, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":assessment_after_dislysis_last"
  3200. redis.Set(keyTwo, "", time.Second)
  3201. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":assessment_after_dislysis_list_all"
  3202. redis.Set(key, "", time.Second)
  3203. keyThree := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":dialysis_orders_list_all"
  3204. redis.Set(keyThree, "", time.Second)
  3205. keySeven := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.PatientId, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":monitor_records"
  3206. redis.Set(keySeven, "", time.Second)
  3207. defer redis.Close()
  3208. if updateAssessmentErr != nil {
  3209. utils.ErrorLog("%v", updateAssessmentErr)
  3210. }
  3211. }
  3212. _, dialysisRecords := service.FindDialysisOrderById(record_id)
  3213. c.ServeSuccessJSON(map[string]interface{}{
  3214. "dialysis_order": dialysisRecords,
  3215. })
  3216. }
  3217. func (c *DialysisAPIController) GetLongAdvice() {
  3218. patient_id, _ := c.GetInt64("id")
  3219. adminUserInfo := c.GetMobileAdminUserInfo()
  3220. _, config := service.FindDoctorAdviceRecordByOrgId(adminUserInfo.Org.Id)
  3221. _, hisConfig := service.FindXTHisRecordByOrgId(adminUserInfo.Org.Id)
  3222. is_advice_open, _ := service.FindAdviceSettingById(adminUserInfo.Org.Id)
  3223. prescription_open, _ := service.FindPrescriptionConfigById(adminUserInfo.Org.Id)
  3224. //patient, _ := service.FindPatientIsOpenRemindById(patient_id, adminUserInfo.Org.Id)
  3225. if config.IsOpenRemind == 0 { //针对老用户,即没开启推送功能,也没有 不开启推送功能,不做任何处理
  3226. c.ServeSuccessJSON(map[string]interface{}{
  3227. "status": "1",
  3228. })
  3229. return
  3230. } else { //开启推送提醒
  3231. //开启推送提醒逻辑 提交长期处方的时候,弹起长期医嘱推送
  3232. var advice_three []*models.DoctorAdvice
  3233. recordDateStr := time.Now().Format("2006-01-02")
  3234. recordDate, _ := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  3235. nowtime := recordDate.Unix()
  3236. //advices, err := service.GetLastLongAdviceByGroupNoOne(adminUserInfo.Org.Id, patient_id,nowtime)
  3237. //fmt.Println("advices232333232323323233232333223233232322332",advices)
  3238. //advices_two, err := service.GetLastLongAdviceByGroupNoFour(adminUserInfo.Org.Id, patient_id,nowtime)
  3239. advices, err := service.GetLastLongAdviceByGroupNo(adminUserInfo.Org.Id, patient_id, nowtime)
  3240. advices_two, err := service.GetLastLongAdviceByGroupNoThree(adminUserInfo.Org.Id, patient_id, nowtime)
  3241. for _, advice := range advices {
  3242. if advice.FrequencyType == 3 {
  3243. t := time.Now()
  3244. week := int(t.Weekday())
  3245. fmt.Println(t.Weekday())
  3246. fmt.Println(week)
  3247. switch week {
  3248. case 1:
  3249. if strings.Index(advice.WeekDay, "周一") == -1 {
  3250. advice_three = append(advice_three, advice)
  3251. }
  3252. break
  3253. case 2:
  3254. if strings.Index(advice.WeekDay, "周二") == -1 {
  3255. advice_three = append(advice_three, advice)
  3256. }
  3257. break
  3258. case 3:
  3259. if strings.Index(advice.WeekDay, "周三") == -1 {
  3260. advice_three = append(advice_three, advice)
  3261. }
  3262. break
  3263. case 4:
  3264. if strings.Index(advice.WeekDay, "周四") == -1 {
  3265. advice_three = append(advice_three, advice)
  3266. }
  3267. break
  3268. case 5:
  3269. if strings.Index(advice.WeekDay, "周五") == -1 {
  3270. advice_three = append(advice_three, advice)
  3271. }
  3272. break
  3273. case 6:
  3274. if strings.Index(advice.WeekDay, "周六") == -1 {
  3275. advice_three = append(advice_three, advice)
  3276. }
  3277. break
  3278. case 0:
  3279. if strings.Index(advice.WeekDay, "周日") == -1 {
  3280. advice_three = append(advice_three, advice)
  3281. }
  3282. break
  3283. }
  3284. }
  3285. }
  3286. for _, advice := range advices_two {
  3287. p, _ := time.Parse("2006-01-02", time.Now().Format("2006-01-02"))
  3288. now := p.Unix()
  3289. dayStr := strconv.FormatInt(advice.DayCount, 10)
  3290. dayStr2 := "-" + dayStr
  3291. count, _ := strconv.ParseInt(dayStr2, 10, 64)
  3292. oldTime := time.Now().AddDate(0, 0, int(count)).Unix()
  3293. advices, _ := service.FindAllDoctorAdviceByTime(now, oldTime, patient_id, adminUserInfo.Org.Id, advice.TemplateId)
  3294. for _, ad := range advices {
  3295. advice_three = append(advice_three, ad)
  3296. }
  3297. }
  3298. if err == nil {
  3299. c.ServeSuccessJSON(map[string]interface{}{
  3300. "status": "2",
  3301. "advices": advices,
  3302. "advices_two": RemoveRepeatedElement(advice_three),
  3303. "is_open_remind": config.IsOpenRemind,
  3304. "his_config_open": hisConfig.IsOpen,
  3305. "is_advice_open": is_advice_open.IsAdviceOpen,
  3306. "prescription_open": prescription_open.IsOpen,
  3307. })
  3308. }
  3309. }
  3310. }
  3311. func (c *DialysisAPIController) GetLongAdviceOne() {
  3312. patient_id, _ := c.GetInt64("id")
  3313. startTime := c.GetString("schedule_date")
  3314. timeLayout := "2006-01-02"
  3315. loc, _ := time.LoadLocation("Local")
  3316. var theStartTime int64
  3317. if len(startTime) > 0 {
  3318. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", startTime+" 00:00:00", loc)
  3319. if err != nil {
  3320. utils.ErrorLog(err.Error())
  3321. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3322. return
  3323. }
  3324. theStartTime = theTime.Unix()
  3325. }
  3326. adminUserInfo := c.GetMobileAdminUserInfo()
  3327. _, config := service.FindDoctorAdviceRecordByOrgId(adminUserInfo.Org.Id)
  3328. _, hisConfig := service.FindXTHisRecordByOrgId(adminUserInfo.Org.Id)
  3329. is_advice_open, _ := service.FindAdviceSettingById(adminUserInfo.Org.Id)
  3330. prescription_open, _ := service.FindPrescriptionConfigById(adminUserInfo.Org.Id)
  3331. //patient, _ := service.FindPatientIsOpenRemindById(patient_id, adminUserInfo.Org.Id)
  3332. if config.IsOpenRemind == 0 { //针对老用户,即没开启推送功能,也没有 不开启推送功能,不做任何处理
  3333. c.ServeSuccessJSON(map[string]interface{}{
  3334. "status": "1",
  3335. })
  3336. return
  3337. } else { //开启推送提醒
  3338. //开启推送提醒逻辑 提交长期处方的时候,弹起长期医嘱推送
  3339. var advice_three []*models.DoctorAdvice
  3340. //fmt.Println("theStartTime23434343433434433443434343434334", theStartTime)
  3341. advices, err := service.GetLastLongAdviceByGroupNo(adminUserInfo.Org.Id, patient_id, theStartTime)
  3342. advices_two, err := service.GetLastLongAdviceByGroupNoThree(adminUserInfo.Org.Id, patient_id, theStartTime)
  3343. for _, advice := range advices {
  3344. if advice.FrequencyType == 3 {
  3345. t := time.Now()
  3346. week := int(t.Weekday())
  3347. fmt.Println(t.Weekday())
  3348. fmt.Println(week)
  3349. switch week {
  3350. case 1:
  3351. if strings.Index(advice.WeekDay, "周一") == -1 {
  3352. advice_three = append(advice_three, advice)
  3353. }
  3354. break
  3355. case 2:
  3356. if strings.Index(advice.WeekDay, "周二") == -1 {
  3357. advice_three = append(advice_three, advice)
  3358. }
  3359. break
  3360. case 3:
  3361. if strings.Index(advice.WeekDay, "周三") == -1 {
  3362. advice_three = append(advice_three, advice)
  3363. }
  3364. break
  3365. case 4:
  3366. if strings.Index(advice.WeekDay, "周四") == -1 {
  3367. advice_three = append(advice_three, advice)
  3368. }
  3369. break
  3370. case 5:
  3371. if strings.Index(advice.WeekDay, "周五") == -1 {
  3372. advice_three = append(advice_three, advice)
  3373. }
  3374. break
  3375. case 6:
  3376. if strings.Index(advice.WeekDay, "周六") == -1 {
  3377. advice_three = append(advice_three, advice)
  3378. }
  3379. break
  3380. case 0:
  3381. if strings.Index(advice.WeekDay, "周日") == -1 {
  3382. advice_three = append(advice_three, advice)
  3383. }
  3384. break
  3385. }
  3386. }
  3387. }
  3388. for _, advice := range advices_two {
  3389. p, _ := time.Parse("2006-01-02", time.Now().Format("2006-01-02"))
  3390. now := p.Unix()
  3391. dayStr := strconv.FormatInt(advice.DayCount, 10)
  3392. dayStr2 := "-" + dayStr
  3393. count, _ := strconv.ParseInt(dayStr2, 10, 64)
  3394. oldTime := time.Now().AddDate(0, 0, int(count)).Unix()
  3395. advices, _ := service.FindAllDoctorAdviceByTime(now, oldTime, patient_id, adminUserInfo.Org.Id, advice.TemplateId)
  3396. for _, ad := range advices {
  3397. advice_three = append(advice_three, ad)
  3398. }
  3399. }
  3400. if err == nil {
  3401. c.ServeSuccessJSON(map[string]interface{}{
  3402. "status": "2",
  3403. "advices": advices,
  3404. "advices_two": RemoveRepeatedElement(advice_three),
  3405. "is_open_remind": config.IsOpenRemind,
  3406. "his_config_open": hisConfig.IsOpen,
  3407. "is_advice_open": is_advice_open.IsAdviceOpen,
  3408. "prescription_open": prescription_open.IsOpen,
  3409. })
  3410. }
  3411. }
  3412. }
  3413. func RemoveRepeatedElement(arr []*models.DoctorAdvice) (newArr []*models.DoctorAdvice) {
  3414. newArr = make([]*models.DoctorAdvice, 0)
  3415. for i := 0; i < len(arr); i++ {
  3416. repeat := false
  3417. for j := i + 1; j < len(arr); j++ {
  3418. if arr[i].ID == arr[j].ID {
  3419. repeat = true
  3420. break
  3421. }
  3422. }
  3423. if !repeat {
  3424. newArr = append(newArr, arr[i])
  3425. }
  3426. }
  3427. return
  3428. }
  3429. func (c *DialysisAPIController) CreateRemindDoctorAdvice() {
  3430. patient, _ := c.GetInt64("id", 0)
  3431. groupNo, _ := c.GetInt64("groupno", 0)
  3432. if patient <= 0 {
  3433. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3434. return
  3435. }
  3436. adminUserInfo := c.GetMobileAdminUserInfo()
  3437. dataBody := make(map[string]interface{}, 0)
  3438. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  3439. if err != nil {
  3440. utils.ErrorLog(err.Error())
  3441. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3442. return
  3443. }
  3444. utils.ErrorLog("%v", dataBody)
  3445. timeLayout := "2006-01-02 15:04"
  3446. loc, _ := time.LoadLocation("Local")
  3447. timeLayout2 := "2006-01-02"
  3448. loc2, _ := time.LoadLocation("Local")
  3449. if dataBody["advice_type"] == nil || reflect.TypeOf(dataBody["advice_type"]).String() != "float64" {
  3450. utils.ErrorLog("advice_type")
  3451. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3452. return
  3453. }
  3454. adviceType := int64(2)
  3455. if dataBody["advice_date"] == nil || reflect.TypeOf(dataBody["advice_date"]).String() != "string" {
  3456. utils.ErrorLog("advice_date")
  3457. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3458. return
  3459. }
  3460. adviceDate, _ := dataBody["advice_date"].(string)
  3461. theTime, err := time.ParseInLocation(timeLayout2, adviceDate, loc2)
  3462. AdviceDate := theTime.Unix()
  3463. RecordDate := theTime.Unix()
  3464. if dataBody["start_time"] == nil || reflect.TypeOf(dataBody["start_time"]).String() != "string" {
  3465. utils.ErrorLog("start_time")
  3466. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3467. return
  3468. }
  3469. startTime, _ := dataBody["start_time"].(string)
  3470. if len(startTime) == 0 {
  3471. utils.ErrorLog("len(start_time) == 0")
  3472. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3473. return
  3474. }
  3475. theTime, err = time.ParseInLocation(timeLayout, startTime, loc)
  3476. if err != nil {
  3477. utils.ErrorLog(err.Error())
  3478. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3479. return
  3480. }
  3481. StartTime := theTime.Unix()
  3482. Remark := ""
  3483. if dataBody["remark"] != nil && reflect.TypeOf(dataBody["remark"]).String() == "string" {
  3484. remark, _ := dataBody["remark"].(string)
  3485. Remark = remark
  3486. }
  3487. var advices []*models.GroupAdvice
  3488. if dataBody["advices"] == nil || reflect.TypeOf(dataBody["advices"]).String() != "[]interface {}" {
  3489. utils.ErrorLog("advices")
  3490. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3491. return
  3492. }
  3493. adviceNames := dataBody["advices"].([]interface{})
  3494. for _, adviceNameMap := range adviceNames {
  3495. adviceNameM := adviceNameMap.(map[string]interface{})
  3496. var advice models.GroupAdvice
  3497. advice.Remark = Remark
  3498. advice.AdviceType = adviceType
  3499. advice.StartTime = StartTime
  3500. advice.AdviceDate = AdviceDate
  3501. advice.RecordDate = RecordDate
  3502. advice.Status = 1
  3503. advice.CreatedTime = time.Now().Unix()
  3504. advice.UpdatedTime = time.Now().Unix()
  3505. advice.StopState = 2
  3506. advice.ExecutionState = 2
  3507. advice.UserOrgId = adminUserInfo.Org.Id
  3508. advice.PatientId = patient
  3509. advice.AdviceDoctor = adminUserInfo.AdminUser.Id
  3510. advice.IsSettle = 2
  3511. if adviceNameM["advice_name"] == nil || reflect.TypeOf(adviceNameM["advice_name"]).String() != "string" {
  3512. utils.ErrorLog("advice_name")
  3513. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3514. return
  3515. }
  3516. adviceName, _ := adviceNameM["advice_name"].(string)
  3517. if len(adviceName) == 0 {
  3518. utils.ErrorLog("len(advice_name) == 0")
  3519. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3520. return
  3521. }
  3522. advice.AdviceName = adviceName
  3523. if adviceNameM["drug_spec"] != nil && reflect.TypeOf(adviceNameM["drug_spec"]).String() == "string" {
  3524. drugSpec, _ := strconv.ParseFloat(adviceNameM["drug_spec"].(string), 64)
  3525. advice.DrugSpec = drugSpec
  3526. }
  3527. if adviceNameM["advice_desc"] != nil && reflect.TypeOf(adviceNameM["advice_desc"]).String() == "string" {
  3528. adviceDesc, _ := adviceNameM["advice_desc"].(string)
  3529. advice.AdviceDesc = adviceDesc
  3530. }
  3531. if adviceNameM["drug_spec_unit"] != nil && reflect.TypeOf(adviceNameM["drug_spec_unit"]).String() == "string" {
  3532. drugSpecUnit, _ := adviceNameM["drug_spec_unit"].(string)
  3533. advice.DrugSpecUnit = drugSpecUnit
  3534. }
  3535. //if adviceNameM["single_dose"] != nil && reflect.TypeOf(adviceNameM["single_dose"]).String() == "string" {
  3536. // singleDose, _ := strconv.ParseFloat(adviceNameM["single_dose"].(string), 64)
  3537. // advice.SingleDose = singleDose
  3538. //}
  3539. if adviceNameM["single_dose"] != nil || reflect.TypeOf(adviceNameM["single_dose"]).String() == "float64" {
  3540. //single_dose := int64(adviceNameM["single_dose"].(float64))
  3541. advice.SingleDose = adviceNameM["single_dose"].(float64)
  3542. }
  3543. if adviceNameM["single_dose_unit"] != nil && reflect.TypeOf(adviceNameM["single_dose_unit"]).String() == "string" {
  3544. singleDoseUnit, _ := adviceNameM["single_dose_unit"].(string)
  3545. advice.SingleDoseUnit = singleDoseUnit
  3546. }
  3547. //if adviceNameM["prescribing_number"] != nil && reflect.TypeOf(adviceNameM["prescribing_number"]).String() == "string" {
  3548. // prescribingNumber, _ := strconv.ParseFloat(adviceNameM["prescribing_number"].(string), 64)
  3549. // advice.PrescribingNumber = prescribingNumber
  3550. //}
  3551. if adviceNameM["prescribing_number"] != nil || reflect.TypeOf(adviceNameM["prescribing_number"]).String() == "float64" {
  3552. //single_dose := int64(adviceNameM["single_dose"].(float64))
  3553. advice.PrescribingNumber = adviceNameM["prescribing_number"].(float64)
  3554. }
  3555. if adviceNameM["prescribing_number_unit"] != nil && reflect.TypeOf(adviceNameM["prescribing_number_unit"]).String() == "string" {
  3556. prescribingNumberUnit, _ := adviceNameM["prescribing_number_unit"].(string)
  3557. advice.PrescribingNumberUnit = prescribingNumberUnit
  3558. }
  3559. if adviceNameM["delivery_way"] != nil && reflect.TypeOf(adviceNameM["delivery_way"]).String() == "string" {
  3560. deliveryWay, _ := adviceNameM["delivery_way"].(string)
  3561. advice.DeliveryWay = deliveryWay
  3562. }
  3563. if adviceNameM["execution_frequency"] != nil && reflect.TypeOf(adviceNameM["execution_frequency"]).String() == "string" {
  3564. executionFrequency, _ := adviceNameM["execution_frequency"].(string)
  3565. advice.ExecutionFrequency = executionFrequency
  3566. }
  3567. if adviceNameM["frequency_type"] != nil || reflect.TypeOf(adviceNameM["frequency_type"]).String() == "float64" {
  3568. frequency_type := int64(adviceNameM["frequency_type"].(float64))
  3569. advice.FrequencyType = frequency_type
  3570. }
  3571. if adviceNameM["day_count"] != nil || reflect.TypeOf(adviceNameM["day_count"]).String() == "float64" {
  3572. day_count := int64(adviceNameM["day_count"].(float64))
  3573. advice.DayCount = day_count
  3574. }
  3575. if adviceNameM["week_day"] != nil && reflect.TypeOf(adviceNameM["week_day"]).String() == "string" {
  3576. week_day, _ := adviceNameM["week_day"].(string)
  3577. advice.WeekDay = week_day
  3578. }
  3579. if adviceNameM["way"] != nil || reflect.TypeOf(adviceNameM["way"]).String() == "float64" {
  3580. way := int64(adviceNameM["way"].(float64))
  3581. advice.Way = way
  3582. }
  3583. if adviceNameM["drug_id"] != nil || reflect.TypeOf(adviceNameM["drug_id"]).String() == "float64" {
  3584. drug_id := int64(adviceNameM["drug_id"].(float64))
  3585. advice.DrugId = drug_id
  3586. }
  3587. if adviceNameM["drug_name_id"] != nil || reflect.TypeOf(adviceNameM["drug_name_id"]).String() == "float64" {
  3588. drug_name_id := int64(adviceNameM["drug_name_id"].(float64))
  3589. advice.DrugNameId = drug_name_id
  3590. }
  3591. if adviceNameM["template_id"] != nil && reflect.TypeOf(adviceNameM["template_id"]).String() == "string" {
  3592. template_id, _ := adviceNameM["template_id"].(string)
  3593. advice.TemplateId = template_id
  3594. }
  3595. if adviceNameM["child"] != nil && reflect.TypeOf(adviceNameM["child"]).String() == "string" {
  3596. executionFrequency, _ := adviceNameM["execution_frequency"].(string)
  3597. advice.ExecutionFrequency = executionFrequency
  3598. }
  3599. if adviceNameM["child"] != nil && reflect.TypeOf(adviceNameM["child"]).String() == "[]interface {}" {
  3600. children := adviceNameM["child"].([]interface{})
  3601. if len(children) > 0 {
  3602. for _, childrenMap := range children {
  3603. childMap := childrenMap.(map[string]interface{})
  3604. var child models.GroupAdvice
  3605. child.Remark = Remark
  3606. child.AdviceType = adviceType
  3607. child.StartTime = StartTime
  3608. child.AdviceDate = AdviceDate
  3609. child.RecordDate = RecordDate
  3610. child.Status = 1
  3611. child.CreatedTime = time.Now().Unix()
  3612. child.UpdatedTime = time.Now().Unix()
  3613. child.StopState = 2
  3614. child.ExecutionState = 2
  3615. child.UserOrgId = adminUserInfo.Org.Id
  3616. child.PatientId = patient
  3617. child.AdviceDoctor = adminUserInfo.AdminUser.Id
  3618. child.IsSettle = 1
  3619. if childMap["advice_name"] == nil || reflect.TypeOf(childMap["advice_name"]).String() != "string" {
  3620. utils.ErrorLog("child advice_name")
  3621. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3622. return
  3623. }
  3624. childAdviceName, _ := childMap["advice_name"].(string)
  3625. if len(childAdviceName) == 0 {
  3626. utils.ErrorLog("len(child advice_name) == 0")
  3627. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3628. return
  3629. }
  3630. child.AdviceName = childAdviceName
  3631. if childMap["advice_desc"] != nil && reflect.TypeOf(childMap["advice_desc"]).String() == "string" {
  3632. childAdviceDesc, _ := childMap["advice_desc"].(string)
  3633. child.AdviceDesc = childAdviceDesc
  3634. }
  3635. if childMap["drug_spec"] != nil && reflect.TypeOf(childMap["drug_spec"]).String() == "string" {
  3636. childDrugSpec, _ := strconv.ParseFloat(childMap["drug_spec"].(string), 64)
  3637. child.DrugSpec = childDrugSpec
  3638. }
  3639. if childMap["drug_spec_unit"] != nil && reflect.TypeOf(childMap["drug_spec_unit"]).String() == "string" {
  3640. childDrugSpecUnit, _ := childMap["drug_spec_unit"].(string)
  3641. child.DrugSpecUnit = childDrugSpecUnit
  3642. }
  3643. if childMap["single_dose"] != nil && reflect.TypeOf(childMap["single_dose"]).String() == "float64" {
  3644. child.SingleDose = childMap["single_dose"].(float64)
  3645. }
  3646. if childMap["single_dose_unit"] != nil && reflect.TypeOf(childMap["single_dose_unit"]).String() == "string" {
  3647. childSingleDoseUnit, _ := childMap["single_dose_unit"].(string)
  3648. child.SingleDoseUnit = childSingleDoseUnit
  3649. }
  3650. if childMap["prescribing_number"] != nil && reflect.TypeOf(childMap["prescribing_number"]).String() == "float64" {
  3651. child.PrescribingNumber = childMap["prescribing_number"].(float64)
  3652. }
  3653. if childMap["prescribing_number_unit"] != nil && reflect.TypeOf(childMap["prescribing_number_unit"]).String() == "string" {
  3654. childPrescribingNumberUnit, _ := childMap["prescribing_number_unit"].(string)
  3655. child.PrescribingNumberUnit = childPrescribingNumberUnit
  3656. }
  3657. child.DeliveryWay = advice.DeliveryWay
  3658. child.ExecutionFrequency = advice.ExecutionFrequency
  3659. advice.Children = append(advice.Children, &child)
  3660. }
  3661. }
  3662. }
  3663. temp_advice, _ := service.FindRemindAdvice(advice.UserOrgId, advice.AdviceName, advice.AdviceDesc, advice.TemplateId, advice.FrequencyType, patient, advice.RecordDate)
  3664. if temp_advice.ID == 0 {
  3665. advices = append(advices, &advice)
  3666. }
  3667. }
  3668. if len(advices) > 0 {
  3669. list, err := service.CreateMGroupAdvice(adminUserInfo.Org.Id, advices, groupNo)
  3670. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient, 10) + ":" + strconv.FormatInt(RecordDate, 10) + ":doctor_advices"
  3671. redis := service.RedisClient()
  3672. //清空key 值
  3673. redis.Set(key, "", time.Second)
  3674. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(AdviceDate, 10) + ":advice_list_all"
  3675. redis.Set(keyOne, "", time.Second)
  3676. keyThree := "scheduals_" + adviceDate + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  3677. defer redis.Close()
  3678. redis.Set(keyThree, "", time.Second)
  3679. if err != nil {
  3680. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateDoctorAdviceFail)
  3681. return
  3682. }
  3683. c.ServeSuccessJSON(map[string]interface{}{
  3684. "msg": "ok",
  3685. "advices": list,
  3686. })
  3687. } else {
  3688. c.ServeSuccessJSON(map[string]interface{}{
  3689. "msg": "ok",
  3690. })
  3691. }
  3692. return
  3693. }
  3694. func (c *DialysisAPIController) UploadDryWeight() {
  3695. patient_id, _ := c.GetInt64("id")
  3696. dry_weight, _ := c.GetFloat("dry_weight")
  3697. doctor_id, _ := c.GetInt64("doctor_id")
  3698. remark := c.GetString("remark")
  3699. adminUserInfo := c.GetMobileAdminUserInfo()
  3700. weightAdjust, err := service.FindLastDryWeightAdjust(adminUserInfo.Org.Id, patient_id)
  3701. if err == gorm.ErrRecordNotFound {
  3702. dryWeight := &models.SgjPatientDryweight{
  3703. PatientId: patient_id,
  3704. DryWeight: dry_weight,
  3705. Remakes: remark,
  3706. Ctime: time.Now().Unix(),
  3707. Mtime: time.Now().Unix(),
  3708. Creator: doctor_id,
  3709. Status: 1,
  3710. UserOrgId: adminUserInfo.Org.Id,
  3711. AdjustedValue: "/",
  3712. UserId: adminUserInfo.AdminUser.Id,
  3713. }
  3714. createErr := service.CreatePatientWeightAdjust(dryWeight)
  3715. redis := service.RedisClient()
  3716. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + ":assessment_befores_list_all"
  3717. redis.Set(keyOne, "", time.Second)
  3718. loc, _ := time.LoadLocation("Local")
  3719. nowTime := time.Now()
  3720. nowDay := nowTime.Format("2006-01-02")
  3721. dayTime, _ := time.ParseInLocation("2006-01-02 15:04:05", nowDay+" 00:00:00", loc)
  3722. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dayTime.Unix(), 10) + ":assessment_before_dislysis"
  3723. redis.Set(key, "", time.Second)
  3724. keyTwo := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":last_dry_weight"
  3725. redis.Set(keyTwo, "", time.Second)
  3726. redis.Close()
  3727. if createErr == nil {
  3728. c.ServeSuccessJSON(map[string]interface{}{
  3729. "msg": "提交成功",
  3730. "weight": dryWeight,
  3731. })
  3732. }
  3733. } else {
  3734. dryWeight := &models.SgjPatientDryweight{
  3735. PatientId: patient_id,
  3736. DryWeight: dry_weight,
  3737. Remakes: remark,
  3738. Ctime: time.Now().Unix(),
  3739. Mtime: time.Now().Unix(),
  3740. Creator: doctor_id,
  3741. Status: 1,
  3742. UserOrgId: adminUserInfo.Org.Id,
  3743. AdjustedValue: "/",
  3744. UserId: adminUserInfo.AdminUser.Id,
  3745. }
  3746. var value float64
  3747. value = dry_weight - weightAdjust.DryWeight
  3748. if value < 0 {
  3749. dryWeight.AdjustedValue = strconv.FormatFloat(math.Abs(value), 'f', 1, 64) + "(下调)"
  3750. } else if value == 0 {
  3751. dryWeight.AdjustedValue = "/"
  3752. } else if value > 0 {
  3753. dryWeight.AdjustedValue = strconv.FormatFloat(value, 'f', 1, 64) + "(上调)"
  3754. }
  3755. createErr := service.CreatePatientWeightAdjust(dryWeight)
  3756. redis := service.RedisClient()
  3757. loc, _ := time.LoadLocation("Local")
  3758. nowTime := time.Now()
  3759. nowDay := nowTime.Format("2006-01-02")
  3760. dayTime, _ := time.ParseInLocation("2006-01-02 15:04:05", nowDay+" 00:00:00", loc)
  3761. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(dayTime.Unix(), 10) + ":assessment_befores_list_all"
  3762. redis.Set(keyOne, "", time.Second)
  3763. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dayTime.Unix(), 10) + ":assessment_before_dislysis"
  3764. redis.Set(key, "", time.Second)
  3765. keyTwo := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":last_dry_weight"
  3766. redis.Set(keyTwo, "", time.Second)
  3767. redis.Close()
  3768. if createErr == nil {
  3769. c.ServeSuccessJSON(map[string]interface{}{
  3770. "msg": "提交成功",
  3771. "weight": dryWeight,
  3772. })
  3773. }
  3774. }
  3775. }
  3776. func (c *DialysisAPIController) GetSolution() {
  3777. patient_id, _ := c.GetInt64("patient_id")
  3778. mode_id, _ := c.GetInt64("mode_id")
  3779. adminUserInfo := c.GetMobileAdminUserInfo()
  3780. solution, err := service.MobileGetDialysisSolutionByModeIdSeven(adminUserInfo.Org.Id, patient_id, mode_id)
  3781. prescription, err := service.MobileGetLastDialysisPrescribeByModeIdSeven(adminUserInfo.Org.Id, patient_id, mode_id)
  3782. system_prescription, err := service.MobileGetSystemDialysisPrescribeByModeIdSeven(adminUserInfo.Org.Id, mode_id)
  3783. dialysisPrescription, _ := service.MobileGetLastDialysisPrescription(patient_id, adminUserInfo.Org.Id)
  3784. if err != nil {
  3785. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3786. return
  3787. }
  3788. c.ServeSuccessJSON(map[string]interface{}{
  3789. "solution": solution,
  3790. "prescription": prescription,
  3791. "system_prescription": system_prescription,
  3792. "dialysisPrescription": dialysisPrescription,
  3793. })
  3794. }
  3795. func (c *DialysisAPIController) GetSchedule() {
  3796. schedual_type, _ := c.GetInt64("schedual_type")
  3797. adminUserInfo := c.GetMobileAdminUserInfo()
  3798. scheduleTime, _ := c.GetInt64("record_date")
  3799. deviceNumber, _ := service.GetAllDeviceNumbers(adminUserInfo.Org.Id, scheduleTime, schedual_type)
  3800. list, _ := service.GetAllBedNumberSeven(adminUserInfo.Org.Id)
  3801. c.ServeSuccessJSON(map[string]interface{}{
  3802. "number": deviceNumber,
  3803. "list": list,
  3804. })
  3805. }
  3806. func (c *DialysisAPIController) GetPatientId() {
  3807. id, _ := c.GetInt64("id")
  3808. //orgid := c.GetMobileAdminUserInfo().Org.Id
  3809. patientId, _ := service.GetPatientId(id)
  3810. //获取该患者的所有传染病
  3811. list, _ := service.GetPatientInfectious(id)
  3812. c.ServeSuccessJSON(map[string]interface{}{
  3813. "patient": patientId,
  3814. "infectioulist": list,
  3815. })
  3816. }
  3817. func (this *DialysisAPIController) GetDialysisSchedule() {
  3818. schedualDate := this.GetString("date")
  3819. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  3820. if parseDateErr != nil {
  3821. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3822. return
  3823. }
  3824. adminInfo := this.GetMobileAdminUserInfo()
  3825. orgID := adminInfo.Org.Id
  3826. redis := service.RedisClient()
  3827. defer redis.Close()
  3828. key := "scheduals_" + schedualDate + "_" + strconv.FormatInt(orgID, 10)
  3829. scheduals, _ := service.MobileGetDialysisScheduals(orgID, date.Unix(), 0)
  3830. if len(scheduals) > 0 {
  3831. //缓存数据
  3832. scheduals_json, err := json.Marshal(scheduals)
  3833. if err == nil {
  3834. redis.Set(key, scheduals_json, time.Second*30)
  3835. }
  3836. }
  3837. this.ServeSuccessJSON(map[string]interface{}{
  3838. "scheduals": scheduals,
  3839. })
  3840. }
  3841. func (this *DialysisAPIController) GetLastOrNextDoctorAdvice() {
  3842. change_type, _ := this.GetInt64("type", 0)
  3843. record_date := this.GetString("record_time")
  3844. patient_id, _ := this.GetInt64("patient_id", 0)
  3845. timeLayout := "2006-01-02"
  3846. loc, _ := time.LoadLocation("Local")
  3847. theAdviceRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3848. record_time := theAdviceRecordTime.Unix()
  3849. adminUserInfo := this.GetMobileAdminUserInfo()
  3850. advices, sch, err := service.GetDoctorAdviceByType(change_type, record_time, adminUserInfo.Org.Id, patient_id)
  3851. if err == nil {
  3852. if len(advices) == 0 {
  3853. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDoctorAdviceEmpty)
  3854. return
  3855. } else {
  3856. this.ServeSuccessJSON(map[string]interface{}{
  3857. "advices": advices,
  3858. "schedule": sch,
  3859. })
  3860. return
  3861. }
  3862. } else {
  3863. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3864. return
  3865. }
  3866. }
  3867. func (c *DialysisAPIController) CreateConsumables() {
  3868. record_date := c.GetString("record_time")
  3869. patient_id, _ := c.GetInt64("patient_id", 0)
  3870. active, _ := c.GetInt64("active")
  3871. adminUser := c.GetMobileAdminUserInfo()
  3872. timeLayout := "2006-01-02"
  3873. loc, _ := time.LoadLocation("Local")
  3874. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3875. record_time := theRecordTime.Unix()
  3876. dataBody := make(map[string]interface{}, 0)
  3877. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  3878. if err != nil {
  3879. utils.ErrorLog(err.Error())
  3880. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3881. return
  3882. }
  3883. houseConfig, _ := service.GetAllStoreHouseConfig(adminUser.Org.Id)
  3884. var beforePrepares []*models.DialysisBeforePrepareGoods
  3885. var newBeforePrepares []*models.NewDialysisBeforePrepareGoods
  3886. var dialysisBefor []*models.DialysisBeforePrepare
  3887. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  3888. goods, _ := dataBody["goods"].([]interface{})
  3889. if len(goods) > 0 {
  3890. for _, item := range goods {
  3891. items := item.(map[string]interface{})
  3892. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  3893. utils.ErrorLog("good_id")
  3894. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3895. return
  3896. }
  3897. good_id := int64(items["good_id"].(float64))
  3898. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  3899. utils.ErrorLog("good_type_id")
  3900. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3901. return
  3902. }
  3903. good_type_id := int64(items["good_type_id"].(float64))
  3904. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  3905. utils.ErrorLog("count")
  3906. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3907. return
  3908. }
  3909. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3910. commdity_code := items["commdity_code"].(string)
  3911. fmt.Println("commdity", commdity_code)
  3912. prepareGoods := &models.DialysisBeforePrepareGoods{
  3913. GoodTypeId: good_type_id,
  3914. GoodId: good_id,
  3915. Count: count,
  3916. StorehouseId: houseConfig.StorehouseOutInfo,
  3917. }
  3918. beforePrepares = append(beforePrepares, prepareGoods)
  3919. newPrepareGoods := &models.NewDialysisBeforePrepareGoods{
  3920. GoodTypeId: good_type_id,
  3921. GoodId: good_id,
  3922. Count: count,
  3923. StorehouseId: houseConfig.StorehouseOutInfo,
  3924. }
  3925. newBeforePrepares = append(newBeforePrepares, newPrepareGoods)
  3926. prepare := &models.DialysisBeforePrepare{
  3927. GoodTypeId: good_type_id,
  3928. GoodId: good_id,
  3929. Count: count,
  3930. PatientId: patient_id,
  3931. RecordDate: record_time,
  3932. UserOrgId: adminUser.Org.Id,
  3933. Status: 1,
  3934. Ctime: time.Now().Unix(),
  3935. Creater: adminUser.AdminUser.Id,
  3936. CommdityCode: commdity_code,
  3937. StorehouseId: houseConfig.StorehouseOutInfo,
  3938. }
  3939. dialysisBefor = append(dialysisBefor, prepare)
  3940. }
  3941. }
  3942. //查询是否有库存
  3943. for _, item := range dialysisBefor {
  3944. _, err := service.FindFirstWarehousingInfoByStock(item.GoodId, item.GoodTypeId, houseConfig.StorehouseOutInfo)
  3945. if err == gorm.ErrRecordNotFound {
  3946. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3947. c.ServeSuccessJSON(map[string]interface{}{
  3948. "message": "1",
  3949. "good_name": goodObj.GoodName,
  3950. "specification_name": goodObj.SpecificationName,
  3951. })
  3952. return
  3953. }
  3954. if err != nil {
  3955. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3956. c.ServeSuccessJSON(map[string]interface{}{
  3957. "message": "1",
  3958. "good_name": goodObj.GoodName,
  3959. "specification_name": goodObj.SpecificationName,
  3960. })
  3961. return
  3962. }
  3963. }
  3964. fmt.Println("active------------------------------------", active)
  3965. fmt.Println("len------------------------------", len(goods))
  3966. //新增
  3967. if active == 1 && len(goods) > 0 {
  3968. for _, item := range dialysisBefor {
  3969. dialyPrepareOne := models.DialysisBeforePrepare{
  3970. GoodTypeId: item.GoodTypeId,
  3971. GoodId: item.GoodId,
  3972. PatientId: item.PatientId,
  3973. RecordDate: item.RecordDate,
  3974. UserOrgId: item.UserOrgId,
  3975. Count: item.Count,
  3976. Ctime: time.Now().Unix(),
  3977. Creater: item.Creater,
  3978. CommdityCode: item.CommdityCode,
  3979. Status: 1,
  3980. StorehouseId: houseConfig.StorehouseOutInfo,
  3981. }
  3982. //先清除再插入
  3983. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3984. err = service.CreateDialysisBeforePrepareOne(&dialyPrepareOne)
  3985. //查询默认仓库
  3986. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminUser.Org.Id)
  3987. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminUser.Org.Id)
  3988. var total_count int64
  3989. for _, it := range stockList {
  3990. total_count += it.StockCount
  3991. }
  3992. //基础库插入数据
  3993. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminUser.Org.Id)
  3994. //更新库存
  3995. goodList, _ := service.GetSumGoodList(adminUser.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  3996. var flush_count int64
  3997. for _, it := range goodList {
  3998. flush_count += it.StockCount
  3999. }
  4000. service.UpdateSumGood(adminUser.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  4001. }
  4002. if err == nil {
  4003. c.ServeSuccessJSON(map[string]interface{}{
  4004. "msg": "保存成功",
  4005. "message": "2",
  4006. })
  4007. return
  4008. } else {
  4009. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4010. return
  4011. }
  4012. }
  4013. if len(beforePrepares) > 0 && active == 2 {
  4014. for _, item := range beforePrepares {
  4015. //1.查看该患者该耗材型号最后一次出库数量
  4016. goodInfo, _ := service.GetLastGoodListByPatientId(record_time, patient_id, item.GoodId, item.GoodTypeId)
  4017. //判断当前出库数量和最后一次出库数量的大小
  4018. //如果当前出库数量小于或等于最后一次出库数量 正常出库后 需要退库操作
  4019. if item.Count <= goodInfo.Count {
  4020. //退库
  4021. err = ConsumablesDeliveryTotalSeven(adminUser.Org.Id, patient_id, record_time, beforePrepares, adminUser.AdminUser.Id, item.Count)
  4022. //查询今日出库数据
  4023. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminUser.Org.Id, patient_id, record_time)
  4024. for _, it := range list {
  4025. prepare := models.DialysisBeforePrepare{
  4026. UserOrgId: it.OrgId,
  4027. PatientId: patient_id,
  4028. RecordDate: it.RecordTime,
  4029. GoodId: it.GoodId,
  4030. GoodTypeId: it.GoodTypeId,
  4031. Count: it.Count,
  4032. Ctime: time.Now().Unix(),
  4033. Creater: adminUser.AdminUser.Id,
  4034. Status: 1,
  4035. StorehouseId: houseConfig.StorehouseOutInfo,
  4036. }
  4037. //删除准备表数据
  4038. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  4039. service.CreateDialysisBeforePrepareOne(&prepare)
  4040. }
  4041. }
  4042. var last_total int64
  4043. //如果当前出库数量大于 最后一次出库数量,那么则需要去查询当前批次耗材的库存是否足够
  4044. if item.Count >= goodInfo.Count {
  4045. //查询当前批次当前耗材最后一条出库数据
  4046. lastOutInfo, _ := service.GetLastWarehouOutInfoByPatientId(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  4047. //计算当前出库和最后一次出库数据相差数据
  4048. last_total = item.Count - lastOutInfo.Count
  4049. //查询该批次剩余库存
  4050. lastInfo, _ := service.GetLastStockOut(lastOutInfo.WarehouseInfotId)
  4051. //比较剩余库存 和 当前相差的数量,库存剩余量大于则正常出库
  4052. if lastInfo.StockCount >= last_total {
  4053. err = ConsumablesDeliveryTotalSix(adminUser.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminUser.AdminUser.Id)
  4054. //查询今日出库数据
  4055. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminUser.Org.Id, patient_id, record_time)
  4056. for _, it := range list {
  4057. prepare := models.DialysisBeforePrepare{
  4058. UserOrgId: it.OrgId,
  4059. PatientId: patient_id,
  4060. RecordDate: it.RecordTime,
  4061. GoodId: it.GoodId,
  4062. GoodTypeId: it.GoodTypeId,
  4063. Count: it.Count,
  4064. Ctime: time.Now().Unix(),
  4065. Creater: adminUser.AdminUser.Id,
  4066. Status: 1,
  4067. StorehouseId: houseConfig.StorehouseOutInfo,
  4068. }
  4069. //删除准备表数据
  4070. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  4071. service.CreateDialysisBeforePrepareOne(&prepare)
  4072. //查询默认仓库
  4073. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminUser.Org.Id)
  4074. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminUser.Org.Id)
  4075. var total_count int64
  4076. for _, it := range stockList {
  4077. total_count += it.StockCount
  4078. }
  4079. //基础库插入数据
  4080. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminUser.Org.Id)
  4081. goodList, _ := service.GetSumGoodList(adminUser.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  4082. var flush_count int64
  4083. for _, it := range goodList {
  4084. flush_count += it.StockCount
  4085. }
  4086. service.UpdateSumGood(adminUser.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  4087. }
  4088. }
  4089. //如果库存不够,则出库到下一个批次
  4090. if lastInfo.StockCount < last_total {
  4091. err = ConsumablesDeliveryTotalSix(adminUser.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminUser.AdminUser.Id)
  4092. //查询今日出库数据
  4093. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminUser.Org.Id, patient_id, record_time)
  4094. for _, it := range list {
  4095. prepare := models.DialysisBeforePrepare{
  4096. UserOrgId: it.OrgId,
  4097. PatientId: patient_id,
  4098. RecordDate: it.RecordTime,
  4099. GoodId: it.GoodId,
  4100. GoodTypeId: it.GoodTypeId,
  4101. Count: it.Count,
  4102. Ctime: time.Now().Unix(),
  4103. Creater: adminUser.AdminUser.Id,
  4104. Status: 1,
  4105. StorehouseId: houseConfig.StorehouseOutInfo,
  4106. }
  4107. //删除准备表数据
  4108. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  4109. service.CreateDialysisBeforePrepareOne(&prepare)
  4110. //查询默认仓库
  4111. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminUser.Org.Id)
  4112. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminUser.Org.Id)
  4113. var total_count int64
  4114. for _, it := range stockList {
  4115. total_count += it.StockCount
  4116. }
  4117. //基础库插入数据
  4118. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminUser.Org.Id)
  4119. goodList, _ := service.GetSumGoodList(adminUser.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  4120. var flush_count int64
  4121. for _, it := range goodList {
  4122. flush_count += it.StockCount
  4123. }
  4124. service.UpdateSumGood(adminUser.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  4125. }
  4126. if err != nil {
  4127. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  4128. c.ServeSuccessJSON(map[string]interface{}{
  4129. "message": "1",
  4130. "good_name": goodObj.GoodName,
  4131. "specification_name": goodObj.SpecificationName,
  4132. })
  4133. return
  4134. }
  4135. }
  4136. }
  4137. if err != nil {
  4138. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  4139. c.ServeSuccessJSON(map[string]interface{}{
  4140. "message": "1",
  4141. "good_name": goodObj.GoodName,
  4142. "specification_name": goodObj.SpecificationName,
  4143. })
  4144. return
  4145. }
  4146. }
  4147. }
  4148. }
  4149. var errs error
  4150. if errs == nil {
  4151. c.ServeSuccessJSON(map[string]interface{}{
  4152. "msg": "提交成功",
  4153. "message": "2",
  4154. "good_name": "",
  4155. "specification_name": "",
  4156. })
  4157. return
  4158. } else {
  4159. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4160. return
  4161. }
  4162. }
  4163. func (c *DialysisAPIController) CreateStockOutInfo() {
  4164. patient_id, _ := c.GetInt64("patient_id", 0)
  4165. record_date := c.GetString("record_time")
  4166. if patient_id <= 0 {
  4167. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4168. return
  4169. }
  4170. adminInfo := c.GetMobileAdminUserInfo()
  4171. creator := c.GetMobileAdminUserInfo().AdminUser.Id
  4172. timeLayout := "2006-01-02"
  4173. loc, _ := time.LoadLocation("Local")
  4174. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  4175. record_time := theRecordTime.Unix()
  4176. consumables, _ := service.FindConsumablesByDate(adminInfo.Org.Id, patient_id, record_time)
  4177. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  4178. //去重
  4179. consumables = RemoveRepeatedGood(consumables)
  4180. if record.IsOpen == 1 {
  4181. houseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4182. //查询是否有库存
  4183. for _, item := range consumables {
  4184. warehouse, _ := service.FindFirstWarehousingInfoByStockTwo(item.GoodId, item.GoodTypeId, houseConfig.StorehouseOutInfo)
  4185. if item.Count > warehouse.Count {
  4186. goodErrcode := models.XtGoodErrcode{
  4187. UserOrgId: item.UserOrgId,
  4188. Errcode: "自动出库库存不足",
  4189. GoodId: item.GoodId,
  4190. Status: 1,
  4191. Ctime: time.Now().Unix(),
  4192. Mtime: 0,
  4193. Count: 0,
  4194. StockCount: 0,
  4195. Creater: creator,
  4196. BatchNumberId: warehouse.ID,
  4197. WarehouseOutId: 0,
  4198. }
  4199. service.CreateGoodErrcode(goodErrcode)
  4200. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  4201. c.ServeSuccessJSON(map[string]interface{}{
  4202. "message": "1",
  4203. "good_name": goodObj.GoodName,
  4204. "specification_name": goodObj.SpecificationName,
  4205. })
  4206. return
  4207. }
  4208. }
  4209. //查询是否有出库单
  4210. out, err := service.FindStockOutByIsSys(adminInfo.Org.Id, 1, record_time)
  4211. if err == gorm.ErrRecordNotFound {
  4212. //没有记录,则创建出库单
  4213. timeStr := time.Now().Format("2006-01-02")
  4214. timeArr := strings.Split(timeStr, "-")
  4215. total, _ := service.FindAllWarehouseOut(adminInfo.Org.Id)
  4216. total = total + 1
  4217. warehousing_out_order := strconv.FormatInt(adminInfo.Org.Id, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  4218. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  4219. number = number + total
  4220. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  4221. creater := adminInfo.AdminUser.Id
  4222. warehouseOut := models.WarehouseOut{
  4223. WarehouseOutOrderNumber: warehousing_out_order,
  4224. OperationTime: time.Now().Unix(),
  4225. OrgId: adminInfo.Org.Id,
  4226. Creater: creater,
  4227. Ctime: time.Now().Unix(),
  4228. Status: 1,
  4229. WarehouseOutTime: record_time,
  4230. Dealer: 0,
  4231. Manufacturer: 0,
  4232. Type: 1,
  4233. IsSys: 1,
  4234. StorehouseId: houseConfig.StorehouseOutInfo,
  4235. IsCheck: 1,
  4236. }
  4237. err := service.AddSigleWarehouseOut(&warehouseOut)
  4238. if err != nil {
  4239. goodErrcode := models.XtGoodErrcode{
  4240. UserOrgId: adminInfo.Org.Id,
  4241. Errcode: "创建出库单失败",
  4242. GoodId: 0,
  4243. Status: 1,
  4244. Ctime: time.Now().Unix(),
  4245. Mtime: 0,
  4246. Count: 0,
  4247. StockCount: 0,
  4248. Creater: creator,
  4249. BatchNumberId: 0,
  4250. WarehouseOutId: 0,
  4251. }
  4252. service.CreateGoodErrcode(goodErrcode)
  4253. utils.TraceLog("创建出库单失败 err = %v", err)
  4254. } else {
  4255. for _, item := range consumables {
  4256. //出库
  4257. err := service.ConsumablesGoodDelivery(item.UserOrgId, patient_id, record_time, item, &warehouseOut, item.Count)
  4258. //err := service.ConsumableMobileDelivery(item.UserOrgId, patient_id, record_time, item, &warehouseOut, adminInfo.AdminUser.Id, item.Count)
  4259. //fmt.Println("item----------------------------------count", item.Count)
  4260. if err == nil {
  4261. goodErrcode := models.XtGoodErrcode{
  4262. UserOrgId: adminInfo.Org.Id,
  4263. Errcode: "自动出库接口报错",
  4264. GoodId: 0,
  4265. Status: 1,
  4266. Ctime: time.Now().Unix(),
  4267. Mtime: 0,
  4268. Count: 0,
  4269. StockCount: 0,
  4270. Creater: creator,
  4271. BatchNumberId: 0,
  4272. WarehouseOutId: 0,
  4273. }
  4274. service.CreateGoodErrcode(goodErrcode)
  4275. utils.TraceLog("创建出库单失败 err = %v", err)
  4276. }
  4277. //查询
  4278. //出库数量相加
  4279. errs := service.ModifyGoodSumCount(houseConfig.StorehouseOutInfo, item.Count, item.UserOrgId, item.GoodId)
  4280. if errs != nil {
  4281. goodErrcode := models.XtGoodErrcode{
  4282. UserOrgId: item.UserOrgId,
  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. }
  4297. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  4298. if len(list) == 0 {
  4299. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4300. return
  4301. }
  4302. for _, item := range list {
  4303. prepare := models.DialysisBeforePrepare{
  4304. UserOrgId: adminInfo.Org.Id,
  4305. PatientId: patient_id,
  4306. RecordDate: record_time,
  4307. GoodId: item.GoodId,
  4308. GoodTypeId: item.GoodTypeId,
  4309. Count: item.Count,
  4310. Creater: adminInfo.AdminUser.Id,
  4311. Status: 1,
  4312. Ctime: time.Now().Unix(),
  4313. StorehouseId: houseConfig.StorehouseOutInfo,
  4314. }
  4315. //清空准备表数据
  4316. err := service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  4317. if err != nil {
  4318. goodErrcode := models.XtGoodErrcode{
  4319. UserOrgId: item.OrgId,
  4320. Errcode: "自动出库清空准备表数据报错",
  4321. GoodId: item.GoodId,
  4322. Status: 1,
  4323. Ctime: time.Now().Unix(),
  4324. Mtime: 0,
  4325. Count: 0,
  4326. StockCount: 0,
  4327. Creater: creater,
  4328. BatchNumberId: 0,
  4329. WarehouseOutId: 0,
  4330. }
  4331. service.CreateGoodErrcode(goodErrcode)
  4332. }
  4333. errs := service.CreateDialysisBeforePrepareOne(&prepare)
  4334. if errs != nil {
  4335. goodErrcode := models.XtGoodErrcode{
  4336. UserOrgId: item.OrgId,
  4337. Errcode: "自动出库创建准备表数据报错",
  4338. GoodId: item.GoodId,
  4339. Status: 1,
  4340. Ctime: time.Now().Unix(),
  4341. Mtime: 0,
  4342. Count: 0,
  4343. StockCount: 0,
  4344. Creater: creater,
  4345. BatchNumberId: 0,
  4346. WarehouseOutId: 0,
  4347. }
  4348. service.CreateGoodErrcode(goodErrcode)
  4349. }
  4350. //查询默认仓库
  4351. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4352. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  4353. var total_count int64
  4354. for _, it := range stockList {
  4355. total_count += it.StockCount
  4356. }
  4357. //基础库插入数据
  4358. errcodes := service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminInfo.Org.Id)
  4359. if errcodes != nil {
  4360. goodErrcode := models.XtGoodErrcode{
  4361. UserOrgId: item.OrgId,
  4362. Errcode: "自动出库基础库插入数据",
  4363. GoodId: item.GoodId,
  4364. Status: 1,
  4365. Ctime: time.Now().Unix(),
  4366. Mtime: 0,
  4367. Count: 0,
  4368. StockCount: 0,
  4369. Creater: creater,
  4370. BatchNumberId: 0,
  4371. WarehouseOutId: 0,
  4372. }
  4373. service.CreateGoodErrcode(goodErrcode)
  4374. }
  4375. goodList, _ := service.GetSumGoodList(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  4376. var flush_count int64
  4377. for _, it := range goodList {
  4378. flush_count += it.StockCount
  4379. }
  4380. errsss := service.UpdateSumGood(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  4381. if errsss != nil {
  4382. goodErrcode := models.XtGoodErrcode{
  4383. UserOrgId: item.OrgId,
  4384. Errcode: "自动出库剩余库存更新数据",
  4385. GoodId: item.GoodId,
  4386. Status: 1,
  4387. Ctime: time.Now().Unix(),
  4388. Mtime: 0,
  4389. Count: 0,
  4390. StockCount: 0,
  4391. Creater: creater,
  4392. BatchNumberId: 0,
  4393. WarehouseOutId: 0,
  4394. }
  4395. service.CreateGoodErrcode(goodErrcode)
  4396. }
  4397. }
  4398. }
  4399. //
  4400. } else if err == nil {
  4401. for _, item := range consumables {
  4402. //出库
  4403. err := service.ConsumablesGoodDelivery(item.UserOrgId, patient_id, record_time, item, &out, item.Count)
  4404. //err := service.ConsumableMobileDelivery(item.UserOrgId, patient_id, record_time, item, &out, adminInfo.AdminUser.Id, item.Count)
  4405. //fmt.Println("item----------------------------------count", item.Count)
  4406. if err != nil {
  4407. goodErrcode := models.XtGoodErrcode{
  4408. UserOrgId: adminInfo.Org.Id,
  4409. Errcode: "自动出库接口报错",
  4410. GoodId: 0,
  4411. Status: 1,
  4412. Ctime: time.Now().Unix(),
  4413. Mtime: 0,
  4414. Count: 0,
  4415. StockCount: 0,
  4416. Creater: creator,
  4417. BatchNumberId: 0,
  4418. WarehouseOutId: 0,
  4419. }
  4420. service.CreateGoodErrcode(goodErrcode)
  4421. }
  4422. //出库数量相加
  4423. errss := service.ModifyGoodSumCount(houseConfig.StorehouseOutInfo, item.Count, item.UserOrgId, item.GoodId)
  4424. if errss != nil {
  4425. goodErrcode := models.XtGoodErrcode{
  4426. UserOrgId: item.UserOrgId,
  4427. Errcode: "创建剩余库存字段报错",
  4428. GoodId: item.GoodId,
  4429. Status: 1,
  4430. Ctime: time.Now().Unix(),
  4431. Mtime: time.Now().Unix(),
  4432. Count: 0,
  4433. StockCount: 0,
  4434. Creater: item.Creater,
  4435. BatchNumberId: 0,
  4436. WarehouseOutId: 0,
  4437. }
  4438. service.CreateGoodErrcode(goodErrcode)
  4439. }
  4440. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  4441. if len(list) == 0 {
  4442. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4443. return
  4444. }
  4445. for _, item := range list {
  4446. prepare := models.DialysisBeforePrepare{
  4447. UserOrgId: adminInfo.Org.Id,
  4448. PatientId: patient_id,
  4449. RecordDate: record_time,
  4450. GoodId: item.GoodId,
  4451. GoodTypeId: item.GoodTypeId,
  4452. Count: item.Count,
  4453. Creater: adminInfo.AdminUser.Id,
  4454. Status: 1,
  4455. Ctime: time.Now().Unix(),
  4456. StorehouseId: houseConfig.StorehouseOutInfo,
  4457. }
  4458. //清空准备表数据
  4459. errs := service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  4460. if errs != nil {
  4461. goodErrcode := models.XtGoodErrcode{
  4462. UserOrgId: adminInfo.Org.Id,
  4463. Errcode: "自动出库清空准备表数据报错",
  4464. GoodId: 0,
  4465. Status: 1,
  4466. Ctime: time.Now().Unix(),
  4467. Mtime: 0,
  4468. Count: 0,
  4469. StockCount: 0,
  4470. Creater: creator,
  4471. BatchNumberId: 0,
  4472. WarehouseOutId: 0,
  4473. }
  4474. service.CreateGoodErrcode(goodErrcode)
  4475. }
  4476. errcodes := service.CreateDialysisBeforePrepareOne(&prepare)
  4477. if errcodes != nil {
  4478. goodErrcode := models.XtGoodErrcode{
  4479. UserOrgId: adminInfo.Org.Id,
  4480. Errcode: "自动出库创建准备表数据报错",
  4481. GoodId: 0,
  4482. Status: 1,
  4483. Ctime: time.Now().Unix(),
  4484. Mtime: 0,
  4485. Count: 0,
  4486. StockCount: 0,
  4487. Creater: creator,
  4488. BatchNumberId: 0,
  4489. WarehouseOutId: 0,
  4490. }
  4491. service.CreateGoodErrcode(goodErrcode)
  4492. }
  4493. //查询默认仓库
  4494. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4495. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  4496. var total_count int64
  4497. for _, it := range stockList {
  4498. total_count += it.StockCount
  4499. }
  4500. //基础库插入数据
  4501. errcodes = service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminInfo.Org.Id)
  4502. if errcodes != nil {
  4503. goodErrcode := models.XtGoodErrcode{
  4504. UserOrgId: adminInfo.Org.Id,
  4505. Errcode: "自动出库基础库插入数据报错",
  4506. GoodId: 0,
  4507. Status: 1,
  4508. Ctime: time.Now().Unix(),
  4509. Mtime: 0,
  4510. Count: 0,
  4511. StockCount: 0,
  4512. Creater: creator,
  4513. BatchNumberId: 0,
  4514. WarehouseOutId: 0,
  4515. }
  4516. service.CreateGoodErrcode(goodErrcode)
  4517. }
  4518. goodList, _ := service.GetSumGoodList(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  4519. var flush_count int64
  4520. for _, it := range goodList {
  4521. flush_count += it.StockCount
  4522. }
  4523. errss := service.UpdateSumGood(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  4524. creater := c.GetMobileAdminUserInfo().AdminUser.Id
  4525. if errss != nil {
  4526. goodErrcode := models.XtGoodErrcode{
  4527. UserOrgId: item.OrgId,
  4528. Errcode: "自动出库剩余库存更新数据",
  4529. GoodId: item.GoodId,
  4530. Status: 1,
  4531. Ctime: time.Now().Unix(),
  4532. Mtime: 0,
  4533. Count: 0,
  4534. StockCount: 0,
  4535. Creater: creater,
  4536. BatchNumberId: 0,
  4537. WarehouseOutId: 0,
  4538. }
  4539. service.CreateGoodErrcode(goodErrcode)
  4540. }
  4541. }
  4542. }
  4543. }
  4544. c.ServeSuccessJSON(map[string]interface{}{
  4545. "msg": "提交成功",
  4546. "message": "2",
  4547. "good_name": "",
  4548. "specification_name": "",
  4549. })
  4550. return
  4551. } else {
  4552. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeOpenStocktWrong)
  4553. return
  4554. }
  4555. }
  4556. func (c *DialysisAPIController) EditConsumables() {
  4557. patient_id, _ := c.GetInt64("patient_id", 0)
  4558. record_date := c.GetString("record_time")
  4559. if patient_id <= 0 {
  4560. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4561. return
  4562. }
  4563. adminInfo := c.GetMobileAdminUserInfo()
  4564. timeLayout := "2006-01-02"
  4565. loc, _ := time.LoadLocation("Local")
  4566. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  4567. record_time := theRecordTime.Unix()
  4568. dataBody := make(map[string]interface{}, 0)
  4569. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  4570. if err != nil {
  4571. utils.ErrorLog(err.Error())
  4572. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4573. return
  4574. }
  4575. houseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4576. var beforePrepares []*models.DialysisBeforePrepareGoods
  4577. var newBeforePrepares []*models.NewDialysisBeforePrepareGoods
  4578. var cancelbefor []*models.DialysisBeforePrepareGoods
  4579. var outbefor []*models.DialysisBeforePrepareGoods
  4580. //判断是否开启自动出库
  4581. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  4582. if record.IsOpen == 1 {
  4583. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  4584. goods, _ := dataBody["goods"].([]interface{})
  4585. if len(goods) > 0 {
  4586. for _, item := range goods {
  4587. items := item.(map[string]interface{})
  4588. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  4589. utils.ErrorLog("good_id")
  4590. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4591. return
  4592. }
  4593. good_id := int64(items["good_id"].(float64))
  4594. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  4595. utils.ErrorLog("good_type_id")
  4596. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4597. return
  4598. }
  4599. good_type_id := int64(items["good_type_id"].(float64))
  4600. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  4601. utils.ErrorLog("count")
  4602. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4603. return
  4604. }
  4605. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  4606. commdity_code := items["commdity_code"].(string)
  4607. fmt.Println(commdity_code)
  4608. prepareGoods := &models.DialysisBeforePrepareGoods{
  4609. GoodTypeId: good_type_id,
  4610. GoodId: good_id,
  4611. Count: count,
  4612. StorehouseId: houseConfig.StorehouseOutInfo,
  4613. }
  4614. beforePrepares = append(beforePrepares, prepareGoods)
  4615. newPrepareGoods := &models.NewDialysisBeforePrepareGoods{
  4616. GoodTypeId: good_type_id,
  4617. GoodId: good_id,
  4618. Count: count,
  4619. StorehouseId: houseConfig.StorehouseOutInfo,
  4620. }
  4621. newBeforePrepares = append(newBeforePrepares, newPrepareGoods)
  4622. }
  4623. for _, item := range beforePrepares {
  4624. //1.查看该患者该耗材型号最后一次出库数量
  4625. goodInfo, _ := service.GetLastGoodListByPatientIdOne(record_time, patient_id, item.GoodId, item.GoodTypeId)
  4626. //判断当前出库数量和最后一次出库数量的大小
  4627. //如果当前出库数量小于最后一次出库数量 正常出库后 需要退库操作
  4628. if item.Count < goodInfo.Count {
  4629. cancelbefor = append(cancelbefor, item)
  4630. }
  4631. //如果当前出库数量大于 最后一次出库数量,那么则需要去查询当前批次耗材的库存是否足够
  4632. if item.Count > goodInfo.Count {
  4633. outbefor = append(outbefor, item)
  4634. }
  4635. //处理编辑耗材新增不了的问题
  4636. if goodInfo.Count == item.Count {
  4637. lastCount, _ := service.GetAutoGoodLastCount(item.GoodId, item.Count, record_time, patient_id)
  4638. service.UpdateLastAutoCount(lastCount.ID, item.Count)
  4639. }
  4640. }
  4641. fmt.Println("退库长度", len(cancelbefor))
  4642. fmt.Println("出库长度", len(outbefor))
  4643. //退库
  4644. for _, item := range cancelbefor {
  4645. warehouseOut, _ := service.FindStockOutByIsSys(adminInfo.Org.Id, 1, record_time)
  4646. creater := adminInfo.AdminUser.Id
  4647. //退库
  4648. //err = ConsumablesDeliveryTotalSeven(adminInfo.Org.Id, patient_id, record_time, cancelbefor, adminInfo.AdminUser.Id, item.Count)
  4649. //查询该患者当天已经出库的耗材信息
  4650. warehouseOutInfos, _ := service.FindStockOutInfoByStockTwo(adminInfo.Org.Id, item.GoodTypeId, item.GoodId, record_time, patient_id)
  4651. var delete_count int64 = 0
  4652. delete_count = warehouseOutInfos.Count - item.Count
  4653. houseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4654. // 在出库记录表里记录退库详情
  4655. warehouseOutInfo := &models.WarehouseOutInfo{
  4656. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4657. WarehouseOutId: warehouseOut.ID,
  4658. Status: 1,
  4659. Ctime: time.Now().Unix(),
  4660. OrgId: adminInfo.Org.Id,
  4661. Type: 1,
  4662. IsSys: 1,
  4663. SysRecordTime: record_time,
  4664. GoodTypeId: item.GoodTypeId,
  4665. GoodId: item.GoodId,
  4666. PatientId: patient_id,
  4667. ConsumableType: 2,
  4668. StorehouseId: houseConfig.StorehouseOutInfo,
  4669. IsCheck: 1,
  4670. }
  4671. warehouseOutInfo.Count = item.Count
  4672. stockInInfo, _ := service.FindLastStockInInfoRecord(item.GoodId, adminInfo.Org.Id)
  4673. warehouseOutInfo.Price = stockInInfo.Price
  4674. warehouseOutInfo.Dealer = stockInInfo.Dealer
  4675. warehouseOutInfo.Manufacturer = stockInInfo.Manufacturer
  4676. warehouseOutInfo.ExpiryDate = stockInInfo.ExpiryDate
  4677. warehouseOutInfo.ProductDate = stockInInfo.ProductDate
  4678. warehouseOutInfo.Number = warehouseOutInfos.Number
  4679. warehouseOutInfo.LicenseNumber = stockInInfo.LicenseNumber
  4680. warehouseOutInfo.WarehouseInfotId = stockInInfo.ID
  4681. //查找当天是否存在出库记录
  4682. _, errcod := service.GetWarehouseOutInfoIsExistOne(item.GoodId, patient_id, record_time, 0)
  4683. if errcod == gorm.ErrRecordNotFound {
  4684. service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  4685. //插入详情明细表
  4686. stockFlow := models.VmStockFlow{
  4687. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4688. WarehouseOutId: warehouseOut.ID,
  4689. GoodId: item.GoodId,
  4690. Number: warehouseOutInfos.Number,
  4691. ProductDate: stockInInfo.ProductDate,
  4692. ExpireDate: stockInInfo.ExpiryDate,
  4693. Count: item.Count,
  4694. Price: stockInInfo.Price,
  4695. Status: 1,
  4696. Ctime: time.Now().Unix(),
  4697. UserOrgId: adminInfo.Org.Id,
  4698. Manufacturer: stockInInfo.Manufacturer,
  4699. Dealer: stockInInfo.Dealer,
  4700. LicenseNumber: stockInInfo.LicenseNumber,
  4701. IsEdit: 2,
  4702. Creator: creater,
  4703. SystemTime: record_time,
  4704. ConsumableType: 3,
  4705. WarehousingDetailId: 0,
  4706. IsSys: 1,
  4707. UpdateCreator: creater,
  4708. PatientId: patient_id,
  4709. StorehouseId: houseConfig.StorehouseOutInfo,
  4710. }
  4711. exsit, errflow := service.GetStockFlowIsExsit(warehouseOutInfos.WarehouseInfotId, patient_id, record_time, item.GoodId)
  4712. if errflow == gorm.ErrRecordNotFound {
  4713. //创建流水表
  4714. err := service.CreateStockFlowOne(stockFlow)
  4715. fmt.Println("err", err)
  4716. } else if errflow == nil {
  4717. //插入详情明细表
  4718. stockFlow := models.VmStockFlow{
  4719. ID: exsit.ID,
  4720. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  4721. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4722. WarehouseOutId: warehouseOut.ID,
  4723. GoodId: item.GoodId,
  4724. Number: warehouseOutInfos.Number,
  4725. ProductDate: stockInInfo.ProductDate,
  4726. ExpireDate: stockInInfo.ExpiryDate,
  4727. Count: exsit.Count - delete_count,
  4728. Price: stockInInfo.Price,
  4729. Status: 1,
  4730. Ctime: time.Now().Unix(),
  4731. UserOrgId: adminInfo.Org.Id,
  4732. Manufacturer: stockInInfo.Manufacturer,
  4733. Dealer: stockInInfo.Dealer,
  4734. LicenseNumber: stockInInfo.LicenseNumber,
  4735. IsEdit: 2,
  4736. Creator: creater,
  4737. SystemTime: record_time,
  4738. ConsumableType: 3,
  4739. WarehousingDetailId: 0,
  4740. IsSys: 1,
  4741. UpdateCreator: creater,
  4742. PatientId: patient_id,
  4743. StorehouseId: houseConfig.StorehouseOutInfo,
  4744. }
  4745. service.UpdatedStockFlowOne(stockFlow, warehouseOut.ID, patient_id, record_time, item.GoodId)
  4746. }
  4747. } else if errcod == nil {
  4748. service.UpdatedWarehouseOutInfo(warehouseOutInfo, item.GoodId, patient_id, record_time, 0)
  4749. //插入详情明细表
  4750. stockFlow := models.VmStockFlow{
  4751. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  4752. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4753. WarehouseOutId: warehouseOut.ID,
  4754. GoodId: item.GoodId,
  4755. Number: warehouseOutInfos.Number,
  4756. ProductDate: stockInInfo.ProductDate,
  4757. ExpireDate: stockInInfo.ExpiryDate,
  4758. Count: item.Count,
  4759. Price: stockInInfo.Price,
  4760. Status: 1,
  4761. Ctime: time.Now().Unix(),
  4762. UserOrgId: adminInfo.Org.Id,
  4763. Manufacturer: stockInInfo.Manufacturer,
  4764. Dealer: stockInInfo.Dealer,
  4765. LicenseNumber: stockInInfo.LicenseNumber,
  4766. IsEdit: 2,
  4767. Creator: creater,
  4768. SystemTime: record_time,
  4769. ConsumableType: 3,
  4770. WarehousingDetailId: 0,
  4771. IsSys: 1,
  4772. UpdateCreator: creater,
  4773. PatientId: patient_id,
  4774. ReturnCount: delete_count,
  4775. StorehouseId: houseConfig.StorehouseOutInfo,
  4776. }
  4777. exsit, errflows := service.GetStockFlowIsExsit(warehouseOutInfos.WarehouseInfotId, patient_id, record_time, item.GoodId)
  4778. if errflows == gorm.ErrRecordNotFound {
  4779. //创建流水表
  4780. service.CreateStockFlowOne(stockFlow)
  4781. } else if errflows == nil {
  4782. stockFlow := models.VmStockFlow{
  4783. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  4784. ID: exsit.ID,
  4785. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4786. WarehouseOutId: warehouseOut.ID,
  4787. GoodId: item.GoodId,
  4788. Number: warehouseOutInfos.Number,
  4789. ProductDate: stockInInfo.ProductDate,
  4790. ExpireDate: stockInInfo.ExpiryDate,
  4791. Count: exsit.Count - delete_count,
  4792. Price: stockInInfo.Price,
  4793. Status: 1,
  4794. Ctime: time.Now().Unix(),
  4795. UserOrgId: adminInfo.Org.Id,
  4796. Manufacturer: stockInInfo.Manufacturer,
  4797. Dealer: stockInInfo.Dealer,
  4798. LicenseNumber: stockInInfo.LicenseNumber,
  4799. IsEdit: 2,
  4800. Creator: creater,
  4801. SystemTime: record_time,
  4802. ConsumableType: 3,
  4803. WarehousingDetailId: 0,
  4804. IsSys: 1,
  4805. UpdateCreator: creater,
  4806. PatientId: patient_id,
  4807. ReturnCount: delete_count,
  4808. StorehouseId: houseConfig.StorehouseOutInfo,
  4809. }
  4810. service.UpdatedStockFlowOne(stockFlow, warehouseOut.ID, patient_id, record_time, item.GoodId)
  4811. }
  4812. }
  4813. //更改自动出库的表格
  4814. details := models.BloodAutomaticReduceDetail{
  4815. WarehouseOutId: warehouseOutInfo.ID,
  4816. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  4817. PatientId: patient_id,
  4818. Ctime: time.Now().Unix(),
  4819. Mtime: time.Now().Unix(),
  4820. Status: 1,
  4821. RecordTime: record_time,
  4822. OrgId: adminInfo.Org.Id,
  4823. GoodId: item.GoodId,
  4824. GoodTypeId: item.GoodTypeId,
  4825. Count: item.Count,
  4826. StorehouseId: houseConfig.StorehouseOutInfo,
  4827. }
  4828. //查询当天耗材是否已经存在数据
  4829. _, errcode := service.GetAutoMaticReduceDetail(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  4830. if errcode == gorm.ErrRecordNotFound {
  4831. service.CreateAutoReduceRecord(&details)
  4832. } else if errcode == nil {
  4833. service.DeleteAutoRedeceDetailTwo(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  4834. service.CreateAutoReduceRecord(&details)
  4835. }
  4836. service.ModifyGoodAddInformation(item.GoodId, delete_count, adminInfo.Org.Id)
  4837. //增加出库库存数量
  4838. service.ModifyReduceGoodSumCount(houseConfig.StorehouseOutInfo, delete_count, adminInfo.Org.Id, item.GoodId)
  4839. errOne := service.UpDateWarehouStockFlowByStockDelete(warehouseOutInfos.WarehouseInfotId, record_time, item.GoodId, delete_count, patient_id)
  4840. fmt.Println("errOne", errOne)
  4841. // 删除出库完成后,要增加对应批次的库存数量
  4842. service.UpDateWarehouseInfoByStockDelete(warehouseOutInfos.WarehouseInfotId, delete_count, patient_id, record_time, item.GoodId)
  4843. //查询默认仓库
  4844. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4845. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  4846. var total_count int64
  4847. for _, it := range stockList {
  4848. total_count += it.StockCount
  4849. }
  4850. //基础库插入数据
  4851. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminInfo.Org.Id)
  4852. //更新剩余库存
  4853. goodList, _ := service.GetSumGoodList(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  4854. var flush_count int64
  4855. for _, it := range goodList {
  4856. flush_count += it.StockCount
  4857. }
  4858. service.UpdateSumGood(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  4859. }
  4860. //出库
  4861. for _, item := range outbefor {
  4862. fmt.Println("出库ID", item.GoodId)
  4863. var last_total int64
  4864. //1.查看该患者该耗材型号最后一次出库数量
  4865. goodInfoOne, _ := service.GetLastGoodListByPatientIdOne(record_time, patient_id, item.GoodId, item.GoodTypeId)
  4866. //计算当前出库和最后一次出库数据相差数据
  4867. last_total = item.Count - goodInfoOne.Count
  4868. //查询该批次剩余库存
  4869. lastInfo, _ := service.GetLastStockOut(goodInfoOne.WarehouseInfotId)
  4870. if lastInfo.StockCount == 0 {
  4871. //查询该耗材的总库存
  4872. wareinfo, _ := service.GetStockGoodCount(item.GoodId)
  4873. if wareinfo.StockCount == 0 {
  4874. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  4875. c.ServeSuccessJSON(map[string]interface{}{
  4876. "message": "1",
  4877. "good_name": goodObj.GoodName,
  4878. "specification_name": goodObj.SpecificationName,
  4879. })
  4880. return
  4881. }
  4882. }
  4883. //查询该耗材的总库存
  4884. wareinfo, _ := service.GetStockGoodCount(item.GoodId)
  4885. // 如果库存差大于剩余库存则提示库存不足
  4886. if last_total > wareinfo.StockCount {
  4887. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  4888. c.ServeSuccessJSON(map[string]interface{}{
  4889. "message": "1",
  4890. "good_name": goodObj.GoodName,
  4891. "specification_name": goodObj.SpecificationName,
  4892. })
  4893. return
  4894. } else {
  4895. fmt.Println("出库2o2o2o2o2oo2o2o2o2o2o2o", item.GoodId)
  4896. out, err := service.FindStockOutByIsSys(adminInfo.Org.Id, 1, record_time)
  4897. houseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4898. if err == gorm.ErrRecordNotFound {
  4899. //没有记录,则创建出库单
  4900. timeStr := time.Now().Format("2006-01-02")
  4901. timeArr := strings.Split(timeStr, "-")
  4902. total, _ := service.FindAllWarehouseOut(adminInfo.Org.Id)
  4903. total = total + 1
  4904. warehousing_out_order := strconv.FormatInt(adminInfo.Org.Id, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  4905. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  4906. number = number + total
  4907. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  4908. warehouseOut := models.WarehouseOut{
  4909. WarehouseOutOrderNumber: warehousing_out_order,
  4910. OperationTime: time.Now().Unix(),
  4911. OrgId: adminInfo.Org.Id,
  4912. Creater: adminInfo.AdminUser.Id,
  4913. Ctime: time.Now().Unix(),
  4914. Status: 1,
  4915. WarehouseOutTime: record_time,
  4916. Dealer: 0,
  4917. Manufacturer: 0,
  4918. Type: 1,
  4919. IsSys: 1,
  4920. StorehouseId: houseConfig.StorehouseOutInfo,
  4921. IsCheck: 1,
  4922. }
  4923. service.AddSigleWarehouseOut(&warehouseOut)
  4924. }
  4925. //出库
  4926. //err = ConsumablesDeliveryTotalSix(adminInfo.Org.Id, patient_id, record_time, outbefor, newBeforePrepares, adminInfo.AdminUser.Id)
  4927. //houseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4928. //1.查看该患者该耗材型号最后一次出库数量
  4929. goodInfoTwo, _ := service.GetLastGoodListByPatientIdOne(record_time, patient_id, item.GoodId, item.GoodTypeId)
  4930. fmt.Println("count2323323222323wi", item.Count)
  4931. prepare := models.DialysisBeforePrepare{
  4932. UserOrgId: adminInfo.Org.Id,
  4933. PatientId: patient_id,
  4934. RecordDate: record_time,
  4935. GoodId: item.GoodId,
  4936. GoodTypeId: item.GoodTypeId,
  4937. Count: item.Count - goodInfoTwo.Count,
  4938. Ctime: time.Now().Unix(),
  4939. Mtime: 0,
  4940. Creater: adminInfo.AdminUser.Id,
  4941. Modifier: adminInfo.AdminUser.Id,
  4942. Status: 1,
  4943. CommdityCode: "",
  4944. NewCount: 0,
  4945. ProjectId: 0,
  4946. StorehouseId: houseConfig.StorehouseOutInfo,
  4947. }
  4948. fmt.Println("prepare", prepare.Count)
  4949. fmt.Println("count", item.Count)
  4950. service.ConsumablesGoodDelivery(adminInfo.Org.Id, patient_id, record_time, &prepare, &out, item.Count)
  4951. //增加出库数量
  4952. service.ModifyGoodSumCount(houseConfig.StorehouseOutInfo, prepare.Count, adminInfo.Org.Id, item.GoodId)
  4953. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4954. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  4955. var total_count int64
  4956. for _, it := range stockList {
  4957. total_count += it.StockCount
  4958. }
  4959. //基础库插入数据
  4960. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminInfo.Org.Id)
  4961. //剩余库存
  4962. goodList, _ := service.GetSumGoodList(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  4963. var flush_count int64
  4964. for _, it := range goodList {
  4965. flush_count += it.StockCount
  4966. }
  4967. service.UpdateSumGood(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  4968. }
  4969. }
  4970. //查询今日出库数据
  4971. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  4972. for _, it := range list {
  4973. prepare := models.DialysisBeforePrepare{
  4974. UserOrgId: it.OrgId,
  4975. PatientId: patient_id,
  4976. RecordDate: it.RecordTime,
  4977. GoodId: it.GoodId,
  4978. GoodTypeId: it.GoodTypeId,
  4979. Count: it.Count,
  4980. Ctime: time.Now().Unix(),
  4981. Creater: adminInfo.AdminUser.Id,
  4982. Status: 1,
  4983. StorehouseId: houseConfig.StorehouseOutInfo,
  4984. }
  4985. //删除准备表数据
  4986. service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, it.GoodId, it.GoodTypeId)
  4987. service.CreateDialysisBeforePrepareOne(&prepare)
  4988. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4989. stockList, _ := service.GetStockCountByGoodId(it.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  4990. var total_count int64
  4991. for _, it := range stockList {
  4992. total_count += it.StockCount
  4993. }
  4994. //基础库插入数据
  4995. service.UpdateGoodInfoReduceSumCount(it.GoodId, total_count, adminInfo.Org.Id)
  4996. goodList, _ := service.GetSumGoodList(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, it.GoodId)
  4997. var flush_count int64
  4998. for _, it := range goodList {
  4999. flush_count += it.StockCount
  5000. }
  5001. service.UpdateSumGood(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, it.GoodId, flush_count)
  5002. //if err != nil {
  5003. // goodObj, _ := service.GetGoodInformationByGoodId(it.GoodId)
  5004. // c.ServeSuccessJSON(map[string]interface{}{
  5005. // "message": "2",
  5006. // "good_name": goodObj.GoodName,
  5007. // "specification_name": goodObj.SpecificationName,
  5008. // })
  5009. // return
  5010. //}
  5011. }
  5012. }
  5013. }
  5014. //更新自动出库的地方
  5015. var errs error
  5016. if errs == nil {
  5017. c.ServeSuccessJSON(map[string]interface{}{
  5018. "msg": "修改成功",
  5019. "message": "2",
  5020. "good_name": "",
  5021. "specification_name": "",
  5022. })
  5023. return
  5024. } else {
  5025. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  5026. return
  5027. }
  5028. }
  5029. }
  5030. func (c *DialysisAPIController) GetDialysisGoods() {
  5031. schedualDate := c.GetString("schedule_date")
  5032. schedule_type, _ := c.GetInt64("schedule_type")
  5033. partition_id, _ := c.GetInt64("partition_id")
  5034. page, _ := c.GetInt("page")
  5035. patient_id, _ := c.GetInt64("patient_id")
  5036. schedualEndDate := int64(0)
  5037. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  5038. if parseDateErr != nil && len(schedualDate) != 0 {
  5039. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  5040. return
  5041. }
  5042. endDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", schedualDate+" 23:59:59")
  5043. if parseDateErr != nil && len(schedualDate) != 0 {
  5044. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  5045. return
  5046. }
  5047. schedualEndDate = endDate.Unix()
  5048. adminUser := c.GetMobileAdminUserInfo()
  5049. _, err := service.FindStockOutByIsSys(adminUser.Org.Id, 1, date.Unix())
  5050. goodTypes, _ := service.FindAllGoodType(adminUser.Org.Id)
  5051. project, _ := service.GetHisPrescriptionProject(adminUser.Org.Id, patient_id, date.Unix())
  5052. _, config := service.FindXTHisRecordByOrgId(adminUser.Org.Id)
  5053. outConfig, _ := service.FindGoodOutConfigById(adminUser.Org.Id)
  5054. settleConfig, _ := service.GetSettleOpenConfigByOrgId(adminUser.Org.Id)
  5055. //获取当天该病人的透析处方
  5056. prescribe, parseDateErr := service.GetDialysisPrescribe(adminUser.Org.Id, patient_id, date.Unix())
  5057. good_info, _ := service.FindAllGoodInfo(adminUser.Org.Id)
  5058. if err == gorm.ErrRecordNotFound {
  5059. dialysisGoods, _, total := service.MobileGetDialysisGoods(adminUser.Org.Id, date.Unix(), schedule_type, partition_id, page, 0, patient_id, "", schedualEndDate)
  5060. warehouseOutList, _ := service.GetAllWarehouseOutSumList(patient_id, adminUser.Org.Id, date.Unix())
  5061. if patient_id != 0 {
  5062. for _, item := range dialysisGoods { //获取当天排班的每个患者的最后日期的库存使用情况
  5063. goodUser, _ := service.GetLastDialysisGoods(item.PatientId, adminUser.Org.Id, date.Unix())
  5064. lastGoodUserDetial, _ := service.GetLastDialysisBeforePrepare(item.PatientId, adminUser.Org.Id, date.Unix())
  5065. //获取患者总的出库数据
  5066. item.LastAutomaticReduceDetail = goodUser
  5067. item.LastDialysisBeforePrepare = lastGoodUserDetial
  5068. item.Project = project
  5069. }
  5070. }
  5071. c.ServeSuccessJSON(map[string]interface{}{
  5072. "dialysis_goods": dialysisGoods,
  5073. "good_type": goodTypes,
  5074. "total": total,
  5075. "prescribe": prescribe,
  5076. "good_info": good_info,
  5077. "warehouseOutList": warehouseOutList,
  5078. "config": config,
  5079. "outConfig": outConfig,
  5080. "settleConfig": settleConfig,
  5081. })
  5082. return
  5083. } else if err == nil {
  5084. //获取当天排班的每个患者的库存使用情况
  5085. dialysisGoods, err, total := service.MobileGetDialysisGoods(adminUser.Org.Id, date.Unix(), schedule_type, partition_id, page, 0, patient_id, "", schedualEndDate)
  5086. //获取患者总的出库数据
  5087. warehouseOutList, _ := service.GetAllWarehouseOutSumList(patient_id, adminUser.Org.Id, date.Unix())
  5088. if patient_id != 0 {
  5089. for _, item := range dialysisGoods { //获取当天排班的每个患者的最后日期的库存使用情况
  5090. goodUser, _ := service.GetLastDialysisGoods(item.PatientId, adminUser.Org.Id, date.Unix())
  5091. lastGoodUserDetial, _ := service.GetLastDialysisBeforePrepare(item.PatientId, adminUser.Org.Id, date.Unix())
  5092. item.Project = project
  5093. item.LastAutomaticReduceDetail = goodUser
  5094. item.LastDialysisBeforePrepare = lastGoodUserDetial
  5095. }
  5096. }
  5097. if err == nil {
  5098. c.ServeSuccessJSON(map[string]interface{}{
  5099. "dialysis_goods": dialysisGoods,
  5100. "good_type": goodTypes,
  5101. "total": total,
  5102. "prescribe": prescribe,
  5103. "good_info": good_info,
  5104. "project": project,
  5105. "warehouseOutList": warehouseOutList,
  5106. "config": config,
  5107. "outConfig": outConfig,
  5108. "settleConfig": settleConfig,
  5109. })
  5110. return
  5111. } else {
  5112. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  5113. return
  5114. }
  5115. } else if err != nil {
  5116. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  5117. return
  5118. }
  5119. }
  5120. func (c *DialysisAPIController) GetDialysisGoodsStatistics() {
  5121. start_time := c.GetString("start_time")
  5122. end_time := c.GetString("end_time")
  5123. timeLayout := "2006-01-02"
  5124. loc, _ := time.LoadLocation("Local")
  5125. var theStartTime int64
  5126. if len(start_time) > 0 {
  5127. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  5128. if err != nil {
  5129. utils.ErrorLog(err.Error())
  5130. }
  5131. theStartTime = theTime.Unix()
  5132. }
  5133. var theEndtTime int64
  5134. if len(end_time) > 0 {
  5135. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
  5136. if err != nil {
  5137. utils.ErrorLog(err.Error())
  5138. }
  5139. theEndtTime = theTime.Unix()
  5140. }
  5141. adminUser := c.GetMobileAdminUserInfo()
  5142. outInfo, err := service.MobileGetGoodsStatistics(adminUser.Org.Id, theStartTime, theEndtTime)
  5143. stockCount, err := service.GetOutStockTotalCountOne(theStartTime, theEndtTime, adminUser.Org.Id)
  5144. if err == nil {
  5145. c.ServeSuccessJSON(map[string]interface{}{
  5146. "stock_out": outInfo,
  5147. "stockCount": stockCount,
  5148. })
  5149. return
  5150. } else {
  5151. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  5152. return
  5153. }
  5154. }
  5155. func (c *DialysisAPIController) GetStockInGoodInfo() {
  5156. patient_id, _ := c.GetInt64("patient_id", 0)
  5157. record_time := c.GetString("record_time")
  5158. adminUser := c.GetMobileAdminUserInfo()
  5159. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", record_time)
  5160. if parseDateErr != nil && len(record_time) != 0 {
  5161. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  5162. return
  5163. }
  5164. goodTypes, _ := service.FindAllGoodTypeOne(adminUser.Org.Id)
  5165. good_info, _ := service.FindAllGoodInfo(adminUser.Org.Id)
  5166. goodUser, _ := service.GetAllStockOutUserDetail(patient_id, adminUser.Org.Id, date.Unix())
  5167. lastGoodUserDetial, _ := service.GetLastDialysisGoods(patient_id, adminUser.Org.Id, date.Unix())
  5168. project, _ := service.GetHisPrescriptionProject(adminUser.Org.Id, patient_id, date.Unix())
  5169. //获取今日患者的透析处方参数
  5170. prescribe, parseDateErr := service.GetDialysisPrescribe(adminUser.Org.Id, patient_id, date.Unix())
  5171. outInfo, _ := service.GetGoodWarehouseOutInfo(adminUser.Org.Id, patient_id, date.Unix())
  5172. _, configs := service.FindXTHisRecordByOrgId(adminUser.Org.Id)
  5173. c.ServeSuccessJSON(map[string]interface{}{
  5174. "good_type": goodTypes,
  5175. "good_user": goodUser,
  5176. "good_info": good_info,
  5177. "last_good_user": lastGoodUserDetial,
  5178. "project": project,
  5179. "prescription": prescribe,
  5180. "outInfo": outInfo,
  5181. "configs": configs,
  5182. })
  5183. return
  5184. }
  5185. func (c *DialysisAPIController) CreateOtherStockOutInfo() {
  5186. patient_id, _ := c.GetInt64("patient_id", 0)
  5187. record_date := c.GetString("record_time")
  5188. timeLayout := "2006-01-02"
  5189. loc, _ := time.LoadLocation("Local")
  5190. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  5191. record_time := theRecordTime.Unix()
  5192. adminInfo := c.GetMobileAdminUserInfo()
  5193. dataBody := make(map[string]interface{}, 0)
  5194. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  5195. if err != nil {
  5196. utils.ErrorLog(err.Error())
  5197. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  5198. return
  5199. }
  5200. houseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  5201. var beforePrepares []*models.DialysisBeforePrepareGoods
  5202. var newBeforePrepares []*models.NewDialysisBeforePrepareGoods
  5203. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  5204. goods, _ := dataBody["goods"].([]interface{})
  5205. if len(goods) > 0 {
  5206. for _, item := range goods {
  5207. items := item.(map[string]interface{})
  5208. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  5209. utils.ErrorLog("good_id")
  5210. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  5211. return
  5212. }
  5213. good_id := int64(items["good_id"].(float64))
  5214. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  5215. utils.ErrorLog("good_type_id")
  5216. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  5217. return
  5218. }
  5219. good_type_id := int64(items["good_type_id"].(float64))
  5220. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  5221. utils.ErrorLog("count")
  5222. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  5223. return
  5224. }
  5225. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  5226. if items["project_id"] == nil || reflect.TypeOf(items["project_id"]).String() != "float64" {
  5227. utils.ErrorLog("project_id")
  5228. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  5229. return
  5230. }
  5231. project_id := int64(items["project_id"].(float64))
  5232. prepare := &models.DialysisBeforePrepareGoods{
  5233. GoodId: good_id,
  5234. GoodTypeId: good_type_id,
  5235. Count: count,
  5236. ProjectId: project_id,
  5237. StorehouseId: houseConfig.StorehouseOutInfo,
  5238. }
  5239. beforePrepares = append(beforePrepares, prepare)
  5240. newPrepare := &models.NewDialysisBeforePrepareGoods{
  5241. GoodId: good_id,
  5242. GoodTypeId: good_type_id,
  5243. Count: count,
  5244. ProjectId: project_id,
  5245. StorehouseId: houseConfig.StorehouseOutInfo,
  5246. }
  5247. newBeforePrepares = append(newBeforePrepares, newPrepare)
  5248. }
  5249. }
  5250. }
  5251. //查询是否有库存
  5252. for _, item := range beforePrepares {
  5253. storeConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  5254. warehouse, _ := service.FindFirstWarehousingInfoByStockTwo(item.GoodId, item.GoodTypeId, storeConfig.StorehouseOutInfo)
  5255. if item.Count > warehouse.Count {
  5256. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  5257. c.ServeSuccessJSON(map[string]interface{}{
  5258. "message": "1",
  5259. "good_name": goodObj.GoodName,
  5260. "specification_name": goodObj.SpecificationName,
  5261. })
  5262. return
  5263. }
  5264. }
  5265. //出库逻辑
  5266. err = service.ConsumablesDeliveryTotal(adminInfo.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminInfo.AdminUser.Id)
  5267. if err != nil {
  5268. utils.ErrorLog(err.Error())
  5269. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  5270. return
  5271. }
  5272. //查询当天出库的数据
  5273. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  5274. for _, item := range list {
  5275. prepare := models.DialysisBeforePrepare{
  5276. UserOrgId: item.OrgId,
  5277. PatientId: item.PatientId,
  5278. RecordDate: item.RecordTime,
  5279. GoodId: item.GoodId,
  5280. GoodTypeId: item.GoodTypeId,
  5281. Count: item.Count,
  5282. Creater: adminInfo.AdminUser.Id,
  5283. Status: 1,
  5284. Ctime: time.Now().Unix(),
  5285. ProjectId: item.ProjectId,
  5286. StorehouseId: houseConfig.StorehouseOutInfo,
  5287. }
  5288. //清空准备表的数据
  5289. err = service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  5290. //插入准备表数据
  5291. service.CreateDialysisBeforePrepareOne(&prepare)
  5292. //查询默认仓库
  5293. //查询默认仓库
  5294. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  5295. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  5296. var total_count int64
  5297. for _, it := range stockList {
  5298. total_count += it.StockCount
  5299. }
  5300. //基础库插入数据
  5301. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminInfo.Org.Id)
  5302. ////更新剩余库存
  5303. goodList, _ := service.GetSumGoodList(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  5304. var flush_count int64
  5305. for _, it := range goodList {
  5306. flush_count += it.StockCount
  5307. }
  5308. errs := service.UpdateSumGood(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  5309. if errs != nil {
  5310. goodErrcode := models.XtGoodErrcode{
  5311. UserOrgId: item.OrgId,
  5312. Errcode: "手动出库更新剩余出库失败",
  5313. GoodId: item.GoodId,
  5314. Status: 1,
  5315. Ctime: time.Now().Unix(),
  5316. Mtime: 0,
  5317. Count: 0,
  5318. StockCount: 0,
  5319. Creater: adminInfo.AdminUser.Id,
  5320. BatchNumberId: 0,
  5321. WarehouseOutId: 0,
  5322. }
  5323. service.CreateGoodErrcode(goodErrcode)
  5324. }
  5325. }
  5326. //更新自动出库的地方
  5327. var errs error
  5328. if errs == nil {
  5329. c.ServeSuccessJSON(map[string]interface{}{
  5330. "msg": "修改成功",
  5331. "message": "2",
  5332. "good_name": "",
  5333. "specification_name": "",
  5334. })
  5335. return
  5336. } else {
  5337. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  5338. return
  5339. }
  5340. }
  5341. func RemoveRepeatedGood(arr []*models.DialysisBeforePrepare) (newArr []*models.DialysisBeforePrepare) {
  5342. newArr = make([]*models.DialysisBeforePrepare, 0)
  5343. for i := 0; i < len(arr); i++ {
  5344. repeat := false
  5345. for j := i + 1; j < len(arr); j++ {
  5346. if arr[i].GoodId == arr[j].GoodId && arr[i].GoodTypeId == arr[j].GoodTypeId {
  5347. repeat = true
  5348. break
  5349. }
  5350. }
  5351. if !repeat {
  5352. newArr = append(newArr, arr[i])
  5353. }
  5354. }
  5355. return
  5356. }
  5357. func (c *DialysisAPIController) GetAllDrug() {
  5358. patient_id, _ := c.GetInt64("patient_id", 0)
  5359. adminInfo := c.GetMobileAdminUserInfo()
  5360. _, drugStockConfig := service.FindDrugStockAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  5361. privateDrugConfig, _ := service.GetDrugSetByUserOrgId(adminInfo.Org.Id)
  5362. drugList, _ := service.GetAllBaseDrugLibList(adminInfo.Org.Id)
  5363. privateDrugList, _ := service.GetPrivateDrugList(patient_id, adminInfo.Org.Id)
  5364. c.ServeSuccessJSON(map[string]interface{}{
  5365. "base_drug_config": drugStockConfig,
  5366. "private_drug_config": privateDrugConfig,
  5367. "base_drug_list": drugList,
  5368. "private_drug_list": privateDrugList,
  5369. })
  5370. }
  5371. func RemoveRepeatedGoodTwo(arr []*models.DialysisBeforePrepare) (newArr []*models.DialysisBeforePrepare) {
  5372. newArr = make([]*models.DialysisBeforePrepare, 0)
  5373. for i := 0; i < len(arr); i++ {
  5374. repeat := false
  5375. for j := i + 1; j < len(arr); j++ {
  5376. if arr[i].GoodId == arr[j].GoodId {
  5377. repeat = true
  5378. break
  5379. }
  5380. }
  5381. if !repeat {
  5382. newArr = append(newArr, arr[i])
  5383. }
  5384. }
  5385. return
  5386. }
  5387. func (c *DialysisAPIController) GetDepartment() {
  5388. adminInfo := c.GetMobileAdminUserInfo()
  5389. departments, err := service.GetAllDepartMent(adminInfo.Org.Id)
  5390. if err == nil {
  5391. c.ServeSuccessJSON(map[string]interface{}{
  5392. "departments": departments,
  5393. })
  5394. } else {
  5395. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  5396. return
  5397. }
  5398. }
  5399. func (c *DialysisAPIController) GetMobilePrintStockGood() {
  5400. types, _ := c.GetInt("type", 0)
  5401. start_time := c.GetString("start_time")
  5402. end_time := c.GetString("end_time")
  5403. orgId := c.GetMobileAdminUserInfo().Org.Id
  5404. timeLayout := "2006-01-02"
  5405. loc, _ := time.LoadLocation("Local")
  5406. var startTime int64
  5407. if len(start_time) > 0 {
  5408. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  5409. if err != nil {
  5410. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  5411. return
  5412. }
  5413. startTime = theTime.Unix()
  5414. }
  5415. var endTime int64
  5416. if len(end_time) > 0 {
  5417. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
  5418. if err != nil {
  5419. utils.ErrorLog(err.Error())
  5420. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  5421. return
  5422. }
  5423. endTime = theTime.Unix()
  5424. }
  5425. list, err := service.FindPrintStockGoodInfoByType(types, startTime, endTime, orgId)
  5426. stockTotal, err := service.GetOutStockTotalCountTwo(startTime, endTime, orgId)
  5427. if err != nil {
  5428. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  5429. } else {
  5430. c.ServeSuccessJSON(map[string]interface{}{
  5431. "list": list,
  5432. "type": types,
  5433. "stockTotal": stockTotal,
  5434. })
  5435. }
  5436. }
  5437. func (c *DialysisAPIController) BatchDeleteMonitor() {
  5438. ids := c.GetString("ids")
  5439. //patient_id, _ := c.GetInt64("patient_id")
  5440. //monitoring_date, _ := c.GetInt64("monitoring_date")
  5441. idArray := strings.Split(ids, ",")
  5442. err := service.BatchDeleteMonitor(idArray)
  5443. fmt.Print("err", err)
  5444. //orgid := c.GetMobileAdminUserInfo().Org.Id
  5445. //redis := service.RedisClient()
  5446. //key := strconv.FormatInt(orgid, 10) + ":" + ":monitor_record_list_all"
  5447. //redis.Set(key, "", time.Second)
  5448. //keyOne := strconv.FormatInt(orgid, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(monitoring_date, 10) + ":monitor_records"
  5449. //redis.Set(keyOne, "", time.Second)
  5450. //fmt.Println("keyo呢32332322332332232332",keyOne)
  5451. //redis.Close()
  5452. c.ServeSuccessJSON(map[string]interface{}{
  5453. "msg": "批量删除成功",
  5454. })
  5455. return
  5456. }
  5457. func (c *DialysisAPIController) GetPatientDialysisRecordList() {
  5458. id, _ := c.GetInt64("id")
  5459. timeLayout := "2006-01-02"
  5460. loc, _ := time.LoadLocation("Local")
  5461. start_time := time.Now().Format("2006-01-02")
  5462. startime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  5463. nowTime := time.Now()
  5464. endTime := nowTime.AddDate(-2, 0, 0)
  5465. endTimes := endTime.Format("2006-01-02")
  5466. endtime, _ := time.ParseInLocation(timeLayout+" 15:04:05", endTimes+" 00:00:00", loc)
  5467. list, _ := service.GetPatientDialysisRecordList(id, endtime.Unix(), startime.Unix())
  5468. fmt.Println("endtime232332322332322323232332", endTime.Unix())
  5469. c.ServeSuccessJSON(map[string]interface{}{
  5470. "list": list,
  5471. })
  5472. return
  5473. }
  5474. func (c *DialysisAPIController) BathDeleteAdviceList() {
  5475. dataBody := make(map[string]interface{}, 0)
  5476. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  5477. ids := c.GetString("ids")
  5478. idArray := strings.Split(ids, ",")
  5479. origin, _ := c.GetInt64("origin")
  5480. if origin == 1 {
  5481. err = service.BatchDeleteAdvice(idArray)
  5482. fmt.Print("err", err)
  5483. c.ServeSuccessJSON(map[string]interface{}{
  5484. "msg": "批量删除成功",
  5485. })
  5486. return
  5487. }
  5488. if origin == 2 {
  5489. service.BatchDeleteHisAdvice(idArray)
  5490. }
  5491. }
  5492. func (c *DialysisAPIController) UpdateAutoReduceDetail() {
  5493. good_id, _ := c.GetInt64("good_id")
  5494. count, _ := c.GetInt64("count")
  5495. record_time, _ := c.GetInt64("record_time")
  5496. patient_id, _ := c.GetInt64("patient_id")
  5497. detail, _ := service.UpdateAutoReduceDetail(good_id, count, record_time, patient_id)
  5498. c.ServeSuccessJSON(map[string]interface{}{
  5499. "detail": detail,
  5500. })
  5501. return
  5502. }
  5503. func (c *DialysisAPIController) DeleteAutoReduceDetail() {
  5504. good_id, _ := c.GetInt64("good_id")
  5505. record_time, _ := c.GetInt64("record_time")
  5506. patient_id, _ := c.GetInt64("patient_id")
  5507. service.DeleteDialysisBeforOne(good_id, record_time, patient_id)
  5508. err := service.DeleteAutoReduceDetail(good_id, record_time, patient_id)
  5509. fmt.Print("err", err)
  5510. c.ServeSuccessJSON(map[string]interface{}{
  5511. "msg": "批量删除成功",
  5512. })
  5513. return
  5514. }
  5515. func (c *DialysisAPIController) BatchAdviceCheck() {
  5516. ids := c.GetString("ids")
  5517. idArray := strings.Split(ids, ",")
  5518. creator, _ := c.GetInt64("creator")
  5519. origin, _ := c.GetInt64("origin")
  5520. if origin == 1 {
  5521. err := service.BatchAdviceCheck(idArray, creator)
  5522. fmt.Println(err)
  5523. list, _ := service.GetAdviceExecutionById(idArray)
  5524. c.ServeSuccessJSON(map[string]interface{}{
  5525. "list": list,
  5526. })
  5527. return
  5528. }
  5529. if origin == 2 {
  5530. service.BatchHisAdviceCheck(idArray, creator)
  5531. list, _ := service.GetHisAdviceExecutionById(idArray)
  5532. c.ServeSuccessJSON(map[string]interface{}{
  5533. "list": list,
  5534. })
  5535. return
  5536. }
  5537. }
  5538. func (c *DialysisAPIController) BatchAdviceExecution() {
  5539. ids := c.GetString("ids")
  5540. idArray := strings.Split(ids, ",")
  5541. executionTime := c.GetString("execution_time")
  5542. creator, _ := c.GetInt64("creator")
  5543. timeLayout := "2006-01-02 15:04:05"
  5544. loc, _ := time.LoadLocation("Local")
  5545. theTime, _ := time.ParseInLocation(timeLayout, executionTime, loc)
  5546. orgin, _ := c.GetInt64("origin")
  5547. if orgin == 1 {
  5548. err := service.BatchAdviceExecution(idArray, creator, theTime.Unix())
  5549. list, _ := service.GetAdviceExecutionById(idArray)
  5550. fmt.Println(err)
  5551. c.ServeSuccessJSON(map[string]interface{}{
  5552. "list": list,
  5553. })
  5554. return
  5555. }
  5556. if orgin == 2 {
  5557. err := service.BatchHisAdviceExecution(idArray, creator, theTime.Unix())
  5558. list, _ := service.GetHisAdviceExecutionById(idArray)
  5559. fmt.Println(err)
  5560. c.ServeSuccessJSON(map[string]interface{}{
  5561. "list": list,
  5562. })
  5563. return
  5564. }
  5565. }
  5566. func (c *DialysisAPIController) UpdateStockGoods() {
  5567. good_id, _ := c.GetInt64("good_id")
  5568. record_time, _ := c.GetInt64("record_time")
  5569. patient_id, _ := c.GetInt64("patient_id")
  5570. count, _ := c.GetInt64("count")
  5571. err := service.UpdateStockGoods(good_id, record_time, patient_id, count)
  5572. fmt.Print("err", err)
  5573. c.ServeSuccessJSON(map[string]interface{}{
  5574. "msg": "更新成功",
  5575. })
  5576. return
  5577. }
  5578. // 当前数据比上一次出库数据少
  5579. func ConsumablesDeliveryTotalSeven(orgID int64, patient_id int64, record_time int64, goods []*models.DialysisBeforePrepareGoods, creater int64, count int64) (err error) {
  5580. //查询该患者当天已经出库的耗材信息
  5581. goods_yc, _ := service.FindConsumablesByDateThree(orgID, patient_id, record_time)
  5582. // 和新请求的出库数据进行对比,分出那些是继续出库的,那些是需要删除出库的
  5583. for i := len(goods_yc) - 1; i >= 0; i-- {
  5584. goods_yc_temp := goods_yc[i]
  5585. for j := len(goods) - 1; j >= 0; j-- {
  5586. goods_temp := goods[j]
  5587. // 已经出库和新请求出库都存在该耗材,则判断出库数量,分成是继续出库,还是删除出库
  5588. if goods_yc_temp.GoodTypeId == goods_temp.GoodTypeId && goods_yc_temp.GoodId == goods_temp.GoodId {
  5589. // 已经出库和新请求出库的出库数量一致,则清除两个结构体里的数据(既不出库,也不删除出库)
  5590. if goods_yc_temp.Count == goods_temp.Count {
  5591. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  5592. goods = append(goods[:j], goods[j+1:]...)
  5593. break
  5594. }
  5595. // 如果已经出库的数量 大于 新请求出库的数量,则代表需要删除出库
  5596. if goods_yc_temp.Count > goods_temp.Count {
  5597. temp_count := goods_yc_temp.Count - goods_temp.Count
  5598. goods_yc[i].Count = temp_count
  5599. goods = append(goods[:j], goods[j+1:]...)
  5600. break
  5601. }
  5602. // 如果已经出库的数量 小于 新请求出库的梳理,则代表需要增加出库
  5603. if goods_yc_temp.Count < goods_temp.Count {
  5604. temp_count := goods_temp.Count - goods_yc_temp.Count
  5605. goods[j].Count = temp_count
  5606. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  5607. break
  5608. }
  5609. }
  5610. }
  5611. }
  5612. // goods_yc 这个数据就是需要已经出库了,但是现在需要删除出库的耗材数据
  5613. // goods 这个数据就是需要出库的耗材的数据(新增的数据)
  5614. //退库
  5615. if len(goods_yc) > 0 {
  5616. for _, good_yc := range goods_yc {
  5617. out, _ := service.FindStockOutByIsSys(orgID, 1, record_time)
  5618. ConsumablesDeliveryDeleteNew(orgID, record_time, good_yc, &out, patient_id, creater, count)
  5619. }
  5620. }
  5621. return nil
  5622. }
  5623. // 耗材出库删除
  5624. func ConsumablesDeliveryDeleteFour(orgID int64, record_time int64, good_yc *models.BloodAutomaticReduceDetail, warehouseOut *models.WarehouseOut, patient_id int64, creater int64, count int64) (err error) {
  5625. // 先根据相关信息查询当天该耗材的出库信息
  5626. warehouseOutInfos, err := service.FindStockOutInfoByStockTwo(orgID, good_yc.GoodTypeId, good_yc.GoodId, record_time, good_yc.PatientId)
  5627. if err != nil {
  5628. return err
  5629. }
  5630. var delete_count int64 = 0
  5631. delete_count = warehouseOutInfos.Count - count
  5632. houseConfig, _ := service.GetAllStoreHouseConfig(orgID)
  5633. // 在出库记录表里记录退库详情
  5634. warehouseOutInfo := &models.WarehouseOutInfo{
  5635. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  5636. WarehouseOutId: warehouseOut.ID,
  5637. Status: 1,
  5638. Ctime: time.Now().Unix(),
  5639. OrgId: orgID,
  5640. Type: 1,
  5641. IsSys: 1,
  5642. SysRecordTime: record_time,
  5643. GoodTypeId: good_yc.GoodTypeId,
  5644. GoodId: good_yc.GoodId,
  5645. PatientId: good_yc.PatientId,
  5646. ConsumableType: 2,
  5647. StorehouseId: houseConfig.StorehouseOutInfo,
  5648. IsCheck: 1,
  5649. }
  5650. warehouseOutInfo.Count = count
  5651. stockInInfo, _ := service.FindLastStockInInfoRecord(good_yc.GoodId, orgID)
  5652. warehouseOutInfo.Price = stockInInfo.Price
  5653. warehouseOutInfo.Dealer = stockInInfo.Dealer
  5654. warehouseOutInfo.Manufacturer = stockInInfo.Manufacturer
  5655. warehouseOutInfo.ExpiryDate = stockInInfo.ExpiryDate
  5656. warehouseOutInfo.ProductDate = stockInInfo.ProductDate
  5657. warehouseOutInfo.Number = warehouseOutInfos.Number
  5658. warehouseOutInfo.LicenseNumber = stockInInfo.LicenseNumber
  5659. warehouseOutInfo.WarehouseInfotId = stockInInfo.ID
  5660. //查找当天是否存在出库记录
  5661. _, errcod := service.GetWarehouseOutInfoIsExistOne(good_yc.GoodId, good_yc.PatientId, record_time, good_yc.ProjectId)
  5662. if errcod == gorm.ErrRecordNotFound {
  5663. errOne := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  5664. //插入详情明细表
  5665. stockFlow := models.VmStockFlow{
  5666. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  5667. WarehouseOutId: warehouseOut.ID,
  5668. GoodId: good_yc.GoodId,
  5669. Number: warehouseOutInfos.Number,
  5670. ProductDate: stockInInfo.ProductDate,
  5671. ExpireDate: stockInInfo.ExpiryDate,
  5672. Count: count,
  5673. Price: stockInInfo.Price,
  5674. Status: 1,
  5675. Ctime: time.Now().Unix(),
  5676. UserOrgId: good_yc.OrgId,
  5677. Manufacturer: stockInInfo.Manufacturer,
  5678. Dealer: stockInInfo.Dealer,
  5679. LicenseNumber: stockInInfo.LicenseNumber,
  5680. IsEdit: 2,
  5681. Creator: creater,
  5682. SystemTime: record_time,
  5683. ConsumableType: 3,
  5684. WarehousingDetailId: 0,
  5685. IsSys: 1,
  5686. UpdateCreator: creater,
  5687. PatientId: patient_id,
  5688. StorehouseId: houseConfig.StorehouseOutInfo,
  5689. }
  5690. exsit, errflow := service.GetStockFlowIsExsit(warehouseOutInfos.WarehouseInfotId, patient_id, record_time, good_yc.GoodId)
  5691. if errflow == gorm.ErrRecordNotFound {
  5692. //创建流水表
  5693. err := service.CreateStockFlowOne(stockFlow)
  5694. fmt.Println("err", err)
  5695. } else if errflow == nil {
  5696. //插入详情明细表
  5697. stockFlow := models.VmStockFlow{
  5698. ID: exsit.ID,
  5699. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  5700. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  5701. WarehouseOutId: warehouseOut.ID,
  5702. GoodId: good_yc.GoodId,
  5703. Number: warehouseOutInfos.Number,
  5704. ProductDate: stockInInfo.ProductDate,
  5705. ExpireDate: stockInInfo.ExpiryDate,
  5706. Count: exsit.Count - delete_count,
  5707. Price: stockInInfo.Price,
  5708. Status: 1,
  5709. Ctime: time.Now().Unix(),
  5710. UserOrgId: good_yc.OrgId,
  5711. Manufacturer: stockInInfo.Manufacturer,
  5712. Dealer: stockInInfo.Dealer,
  5713. LicenseNumber: stockInInfo.LicenseNumber,
  5714. IsEdit: 2,
  5715. Creator: creater,
  5716. SystemTime: record_time,
  5717. ConsumableType: 3,
  5718. WarehousingDetailId: 0,
  5719. IsSys: 1,
  5720. UpdateCreator: creater,
  5721. PatientId: patient_id,
  5722. StorehouseId: houseConfig.StorehouseOutInfo,
  5723. }
  5724. service.UpdatedStockFlowOne(stockFlow, warehouseOut.ID, patient_id, record_time, good_yc.GoodId)
  5725. }
  5726. if errOne != nil {
  5727. return errOne
  5728. }
  5729. } else if errcod == nil {
  5730. service.UpdatedWarehouseOutInfo(warehouseOutInfo, good_yc.GoodId, good_yc.PatientId, record_time, good_yc.ProjectId)
  5731. //插入详情明细表
  5732. stockFlow := models.VmStockFlow{
  5733. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  5734. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  5735. WarehouseOutId: warehouseOut.ID,
  5736. GoodId: good_yc.GoodId,
  5737. Number: warehouseOutInfos.Number,
  5738. ProductDate: stockInInfo.ProductDate,
  5739. ExpireDate: stockInInfo.ExpiryDate,
  5740. Count: count,
  5741. Price: stockInInfo.Price,
  5742. Status: 1,
  5743. Ctime: time.Now().Unix(),
  5744. UserOrgId: good_yc.OrgId,
  5745. Manufacturer: stockInInfo.Manufacturer,
  5746. Dealer: stockInInfo.Dealer,
  5747. LicenseNumber: stockInInfo.LicenseNumber,
  5748. IsEdit: 2,
  5749. Creator: creater,
  5750. SystemTime: record_time,
  5751. ConsumableType: 3,
  5752. WarehousingDetailId: 0,
  5753. IsSys: 1,
  5754. UpdateCreator: creater,
  5755. PatientId: patient_id,
  5756. ReturnCount: delete_count,
  5757. StorehouseId: houseConfig.StorehouseOutInfo,
  5758. }
  5759. exsit, errflows := service.GetStockFlowIsExsit(warehouseOutInfos.WarehouseInfotId, patient_id, record_time, good_yc.GoodId)
  5760. if errflows == gorm.ErrRecordNotFound {
  5761. //创建流水表
  5762. service.CreateStockFlowOne(stockFlow)
  5763. } else if errflows == nil {
  5764. stockFlow := models.VmStockFlow{
  5765. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  5766. ID: exsit.ID,
  5767. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  5768. WarehouseOutId: warehouseOut.ID,
  5769. GoodId: good_yc.GoodId,
  5770. Number: warehouseOutInfos.Number,
  5771. ProductDate: stockInInfo.ProductDate,
  5772. ExpireDate: stockInInfo.ExpiryDate,
  5773. Count: exsit.Count - delete_count,
  5774. Price: stockInInfo.Price,
  5775. Status: 1,
  5776. Ctime: time.Now().Unix(),
  5777. UserOrgId: good_yc.OrgId,
  5778. Manufacturer: stockInInfo.Manufacturer,
  5779. Dealer: stockInInfo.Dealer,
  5780. LicenseNumber: stockInInfo.LicenseNumber,
  5781. IsEdit: 2,
  5782. Creator: creater,
  5783. SystemTime: record_time,
  5784. ConsumableType: 3,
  5785. WarehousingDetailId: 0,
  5786. IsSys: 1,
  5787. UpdateCreator: creater,
  5788. PatientId: patient_id,
  5789. ReturnCount: delete_count,
  5790. StorehouseId: houseConfig.StorehouseOutInfo,
  5791. }
  5792. service.UpdatedStockFlowOne(stockFlow, warehouseOut.ID, patient_id, record_time, good_yc.GoodId)
  5793. }
  5794. }
  5795. //更改自动出库的表格
  5796. details := models.BloodAutomaticReduceDetail{
  5797. WarehouseOutId: warehouseOutInfo.ID,
  5798. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  5799. PatientId: patient_id,
  5800. Ctime: time.Now().Unix(),
  5801. Mtime: time.Now().Unix(),
  5802. Status: 1,
  5803. RecordTime: record_time,
  5804. OrgId: orgID,
  5805. GoodId: good_yc.GoodId,
  5806. GoodTypeId: good_yc.GoodTypeId,
  5807. Count: count,
  5808. StorehouseId: houseConfig.StorehouseOutInfo,
  5809. }
  5810. //查询当天耗材是否已经存在数据
  5811. _, errcode := service.GetAutoMaticReduceDetail(orgID, patient_id, record_time, good_yc.GoodId, good_yc.GoodTypeId)
  5812. if errcode == gorm.ErrRecordNotFound {
  5813. errTwo := service.CreateAutoReduceRecord(&details)
  5814. if errTwo != nil {
  5815. return errTwo
  5816. }
  5817. } else if errcode == nil {
  5818. service.DeleteAutoRedeceDetailTwo(orgID, patient_id, record_time, good_yc.GoodId, good_yc.GoodTypeId)
  5819. service.CreateAutoReduceRecord(&details)
  5820. }
  5821. service.ModifyGoodAddInformation(good_yc.GoodId, delete_count, good_yc.OrgId)
  5822. //增加出库库存数量
  5823. service.ModifyReduceGoodSumCount(houseConfig.StorehouseOutInfo, delete_count, good_yc.OrgId, good_yc.GoodId)
  5824. errOne := service.UpDateWarehouStockFlowByStockDelete(warehouseOutInfos.WarehouseInfotId, record_time, good_yc.GoodId, delete_count, good_yc.PatientId)
  5825. fmt.Println("errOne", errOne)
  5826. // 删除出库完成后,要增加对应批次的库存数量
  5827. errThree := service.UpDateWarehouseInfoByStockDelete(warehouseOutInfos.WarehouseInfotId, delete_count, patient_id, record_time, good_yc.GoodId)
  5828. if errThree != nil {
  5829. return errThree
  5830. }
  5831. if good_yc.Count == 0 {
  5832. return nil
  5833. } else {
  5834. return errors.New("退库和出库数据不匹配")
  5835. }
  5836. }
  5837. func ConsumablesDeliveryTotalSix(orgID int64, patient_id int64, record_time int64, goods []*models.DialysisBeforePrepareGoods, goodOne []*models.NewDialysisBeforePrepareGoods, creater int64) (err error) {
  5838. //查询该患者当天已经出库的耗材信息
  5839. goods_yc, _ := service.FindConsumablesByDateThree(orgID, patient_id, record_time)
  5840. // 和新请求的出库数据进行对比,分出那些是继续出库的,那些是需要删除出库的
  5841. for i := len(goods_yc) - 1; i >= 0; i-- {
  5842. goods_yc_temp := goods_yc[i]
  5843. for j := len(goods) - 1; j >= 0; j-- {
  5844. goods_temp := goods[j]
  5845. // 已经出库和新请求出库都存在该耗材,则判断出库数量,分成是继续出库,还是删除出库
  5846. if goods_yc_temp.GoodTypeId == goods_temp.GoodTypeId && goods_yc_temp.GoodId == goods_temp.GoodId {
  5847. // 已经出库和新请求出库的出库数量一致,则清除两个结构体里的数据(既不出库,也不删除出库)
  5848. if goods_yc_temp.Count == goods_temp.Count {
  5849. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  5850. goods = append(goods[:j], goods[j+1:]...)
  5851. break
  5852. }
  5853. // 如果已经出库的数量 大于 新请求出库的数量,则代表需要删除出库
  5854. if goods_yc_temp.Count > goods_temp.Count {
  5855. temp_count := goods_yc_temp.Count - goods_temp.Count
  5856. goods_yc[i].Count = temp_count
  5857. goods = append(goods[:j], goods[j+1:]...)
  5858. break
  5859. }
  5860. // 如果已经出库的数量 小于 新请求出库的梳理,则代表需要增加出库
  5861. if goods_yc_temp.Count < goods_temp.Count {
  5862. temp_count := goods_temp.Count - goods_yc_temp.Count
  5863. goods[j].Count = temp_count
  5864. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  5865. break
  5866. }
  5867. }
  5868. }
  5869. }
  5870. // goods_yc 这个数据就是需要已经出库了,但是现在需要删除出库的耗材数据
  5871. // goods 这个数据就是需要出库的耗材的数据(新增的数据)
  5872. fmt.Println("剩余需要出库的", len(goods))
  5873. if len(goods) > 0 {
  5874. out, err := service.FindStockOutByIsSys(orgID, 1, record_time)
  5875. houseConfig, _ := service.GetAllStoreHouseConfig(orgID)
  5876. if err == gorm.ErrRecordNotFound {
  5877. //没有记录,则创建出库单
  5878. timeStr := time.Now().Format("2006-01-02")
  5879. timeArr := strings.Split(timeStr, "-")
  5880. total, _ := service.FindAllWarehouseOut(orgID)
  5881. total = total + 1
  5882. warehousing_out_order := strconv.FormatInt(orgID, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  5883. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  5884. number = number + total
  5885. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  5886. warehouseOut := models.WarehouseOut{
  5887. WarehouseOutOrderNumber: warehousing_out_order,
  5888. OperationTime: time.Now().Unix(),
  5889. OrgId: orgID,
  5890. Creater: creater,
  5891. Ctime: time.Now().Unix(),
  5892. Status: 1,
  5893. WarehouseOutTime: record_time,
  5894. Dealer: 0,
  5895. Manufacturer: 0,
  5896. Type: 1,
  5897. IsSys: 1,
  5898. StorehouseId: houseConfig.StorehouseOutInfo,
  5899. IsCheck: 1,
  5900. }
  5901. err := service.AddSigleWarehouseOut(&warehouseOut)
  5902. if err != nil {
  5903. utils.TraceLog("创建出库单失败 err = %v", err)
  5904. return err
  5905. } else {
  5906. out = warehouseOut
  5907. }
  5908. }
  5909. for _, item := range goods {
  5910. var newCount int64 = 0
  5911. for _, it := range goodOne {
  5912. if item.GoodTypeId == it.GoodTypeId && item.GoodId == it.GoodId {
  5913. newCount = it.Count
  5914. }
  5915. }
  5916. prepare := models.DialysisBeforePrepare{
  5917. GoodTypeId: item.GoodTypeId,
  5918. GoodId: item.GoodId,
  5919. Count: item.Count,
  5920. StorehouseId: houseConfig.StorehouseOutInfo,
  5921. }
  5922. service.ConsumablesGoodDelivery(orgID, patient_id, record_time, &prepare, &out, newCount)
  5923. //增加出库数量
  5924. service.ModifyGoodSumCount(houseConfig.StorehouseOutInfo, item.Count, orgID, item.GoodId)
  5925. }
  5926. }
  5927. if len(goods_yc) > 0 {
  5928. for _, good_yc := range goods_yc {
  5929. out, _ := service.FindStockOutByIsSys(orgID, 1, record_time)
  5930. ConsumablesDeliveryDeleteThree(orgID, record_time, good_yc, &out)
  5931. }
  5932. }
  5933. return nil
  5934. }
  5935. // 耗材出库删除
  5936. func ConsumablesDeliveryDeleteThree(orgID int64, record_time int64, good_yc *models.BloodAutomaticReduceDetail, warehouseOut *models.WarehouseOut) (err error) {
  5937. // 先根据相关信息查询当天该耗材的出库信息
  5938. warehouseOutInfos, err := service.FindStockOutInfoByStockOne(orgID, good_yc.GoodTypeId, good_yc.GoodId, record_time)
  5939. if err != nil {
  5940. return err
  5941. }
  5942. var delete_count int64 = 0
  5943. for _, ware := range warehouseOutInfos {
  5944. // 判断当前出库的数据和删除出库数量
  5945. if good_yc.Count <= ware.Count {
  5946. delete_count = good_yc.Count
  5947. } else {
  5948. delete_count = ware.Count
  5949. }
  5950. warehouseOutInfo := &models.WarehouseOutInfo{
  5951. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  5952. WarehouseOutId: warehouseOut.ID,
  5953. Status: 1,
  5954. Ctime: time.Now().Unix(),
  5955. Remark: "",
  5956. OrgId: orgID,
  5957. Type: 1,
  5958. Manufacturer: 0,
  5959. Dealer: 0,
  5960. IsSys: 0,
  5961. SysRecordTime: record_time,
  5962. GoodTypeId: good_yc.GoodTypeId,
  5963. GoodId: good_yc.GoodId,
  5964. StorehouseId: warehouseOut.StorehouseId,
  5965. IsCheck: 1,
  5966. }
  5967. warehouseOutInfo.Count = delete_count
  5968. stockInInfo, _ := service.FindLastStockInInfoRecord(good_yc.GoodId, orgID)
  5969. warehouseOutInfo.Price = stockInInfo.Price
  5970. errOne := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  5971. if errOne != nil {
  5972. return errOne
  5973. }
  5974. // 删除出库完成后,要改变流水库存(有疑问)
  5975. errOne = service.UpDateWarehouStockFlowByStockDelete(ware.WarehouseInfotId, record_time, good_yc.GoodId, delete_count, good_yc.PatientId)
  5976. fmt.Println("errOne", errOne)
  5977. errThree := service.UpDateWarehouseInfoByStockDelete(ware.WarehouseInfotId, delete_count, good_yc.PatientId, record_time, good_yc.GoodId)
  5978. service.ModifyGoodAddInformation(good_yc.GoodId, delete_count, good_yc.OrgId)
  5979. //扣减出库数量
  5980. service.ModifyReduceGoodSumCount(warehouseOut.StorehouseId, good_yc.Count, good_yc.OrgId, good_yc.GoodId)
  5981. if errThree != nil {
  5982. return errThree
  5983. }
  5984. }
  5985. if good_yc.Count == 0 {
  5986. return nil
  5987. } else {
  5988. return errors.New("退库和出库数据不匹配")
  5989. }
  5990. }
  5991. func (this *DialysisAPIController) GetMobileScheduleList() {
  5992. limit, _ := this.GetInt64("limit")
  5993. page, _ := this.GetInt64("page")
  5994. type_options_visible, _ := this.GetInt64("type_options_visible")
  5995. sch_type_options_visible, _ := this.GetInt64("sch_type_options_visible")
  5996. zone_options_visible, _ := this.GetInt64("zone_options_visible")
  5997. fmt.Println(limit, page, type_options_visible, sch_type_options_visible, zone_options_visible)
  5998. }
  5999. func RemoveRepeatedCheckRecod(arr []*models.HisPrescriptionProject) (newArr []*models.HisPrescriptionProject) {
  6000. newArr = make([]*models.HisPrescriptionProject, 0)
  6001. for i := 0; i < len(arr); i++ {
  6002. repeat := false
  6003. for j := i + 1; j < len(arr); j++ {
  6004. if arr[i].TeamId == arr[j].TeamId {
  6005. repeat = true
  6006. break
  6007. }
  6008. }
  6009. if !repeat {
  6010. newArr = append(newArr, arr[i])
  6011. }
  6012. }
  6013. return
  6014. }
  6015. func (this *DialysisAPIController) GetRoleList() {
  6016. admin_user_id, _ := this.GetInt64("admin_user_id")
  6017. orgid := this.GetMobileAdminUserInfo().Org.Id
  6018. list, err := service.GetRoleList(orgid, admin_user_id)
  6019. fmt.Println(err)
  6020. this.ServeSuccessJSON(map[string]interface{}{
  6021. "list": list,
  6022. })
  6023. return
  6024. }
  6025. func ConsumablesDeliveryDeleteNew(orgID int64, record_time int64, good_yc *models.BloodAutomaticReduceDetail, warehouseOut *models.WarehouseOut, patient_id int64, creater int64, count int64) (err error) {
  6026. fmt.Println("退库222322232322332232332322332232332233wo", good_yc.GoodId)
  6027. // 先根据相关信息查询当天该耗材的出库信息
  6028. warehouseOutInfos, err := service.FindStockOutInfoByStockTwo(orgID, good_yc.GoodTypeId, good_yc.GoodId, record_time, good_yc.PatientId)
  6029. if err != nil {
  6030. return err
  6031. }
  6032. var delete_count int64 = 0
  6033. delete_count = warehouseOutInfos.Count - count
  6034. houseConfig, _ := service.GetAllStoreHouseConfig(orgID)
  6035. // 删除出库完成后,要增加对应批次的库存数量
  6036. errThree := service.UpDateWarehouseInfoByStockDelete(warehouseOutInfos.WarehouseInfotId, delete_count, patient_id, record_time, good_yc.GoodId)
  6037. if errThree != nil {
  6038. return errThree
  6039. }
  6040. //增加退库数量
  6041. service.UpdateSumAddCancelCount(orgID, good_yc.GoodId, houseConfig.StorehouseOutInfo, delete_count)
  6042. //扣减出库数量
  6043. service.ModifyAddGoodSumCount(houseConfig.StorehouseOutInfo, delete_count, orgID, good_yc.GoodId)
  6044. //查询剩余库存
  6045. goodList, _ := service.GetAllGoodSumCount(good_yc.GoodId, orgID, houseConfig.StorehouseOutInfo)
  6046. var sum_count int64
  6047. for _, item := range goodList {
  6048. sum_count += item.StockCount
  6049. }
  6050. // 在出库记录表里记录退库详情
  6051. warehouseOutInfo := &models.WarehouseOutInfo{
  6052. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  6053. WarehouseOutId: warehouseOut.ID,
  6054. Status: 1,
  6055. Ctime: time.Now().Unix(),
  6056. OrgId: orgID,
  6057. Type: 1,
  6058. IsSys: 1,
  6059. SysRecordTime: record_time,
  6060. GoodTypeId: good_yc.GoodTypeId,
  6061. GoodId: good_yc.GoodId,
  6062. PatientId: good_yc.PatientId,
  6063. ConsumableType: 2,
  6064. StorehouseId: houseConfig.StorehouseOutInfo,
  6065. IsCheck: 1,
  6066. OverCount: sum_count,
  6067. }
  6068. warehouseOutInfo.Count = count
  6069. stockInInfo, _ := service.FindLastStockInInfoRecord(good_yc.GoodId, orgID)
  6070. warehouseOutInfo.Price = stockInInfo.Price
  6071. warehouseOutInfo.Dealer = stockInInfo.Dealer
  6072. warehouseOutInfo.Manufacturer = stockInInfo.Manufacturer
  6073. warehouseOutInfo.ExpiryDate = stockInInfo.ExpiryDate
  6074. warehouseOutInfo.ProductDate = stockInInfo.ProductDate
  6075. warehouseOutInfo.Number = warehouseOutInfos.Number
  6076. warehouseOutInfo.LicenseNumber = stockInInfo.LicenseNumber
  6077. warehouseOutInfo.WarehouseInfotId = stockInInfo.ID
  6078. //查找当天是否存在出库记录
  6079. _, errcod := service.GetWarehouseOutInfoIsExistOne(good_yc.GoodId, good_yc.PatientId, record_time, good_yc.ProjectId)
  6080. if errcod == gorm.ErrRecordNotFound {
  6081. errOne := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  6082. //插入详情明细表
  6083. if errOne != nil {
  6084. return errOne
  6085. }
  6086. //插入详情明细表
  6087. stockFlow := models.VmStockFlow{
  6088. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  6089. WarehouseOutId: warehouseOut.ID,
  6090. GoodId: good_yc.GoodId,
  6091. Number: warehouseOutInfos.Number,
  6092. ProductDate: stockInInfo.ProductDate,
  6093. ExpireDate: stockInInfo.ExpiryDate,
  6094. Count: count,
  6095. Price: stockInInfo.Price,
  6096. Status: 1,
  6097. Ctime: time.Now().Unix(),
  6098. UserOrgId: good_yc.OrgId,
  6099. Manufacturer: stockInInfo.Manufacturer,
  6100. Dealer: stockInInfo.Dealer,
  6101. LicenseNumber: stockInInfo.LicenseNumber,
  6102. IsEdit: 2,
  6103. Creator: creater,
  6104. SystemTime: record_time,
  6105. ConsumableType: 3,
  6106. WarehousingDetailId: 0,
  6107. IsSys: 1,
  6108. UpdateCreator: creater,
  6109. PatientId: patient_id,
  6110. StorehouseId: houseConfig.StorehouseOutInfo,
  6111. OverCount: sum_count,
  6112. ProjectId: good_yc.ProjectId,
  6113. }
  6114. err := service.CreateStockFlowOne(stockFlow)
  6115. fmt.Println("err", err)
  6116. } else if errcod == nil {
  6117. service.UpdatedWarehouseOutInfo(warehouseOutInfo, good_yc.GoodId, good_yc.PatientId, record_time, good_yc.ProjectId)
  6118. }
  6119. //创建退库单
  6120. operation_time := time.Now().Unix()
  6121. //创建退库单
  6122. timeStr := time.Now().Format("2006-01-02")
  6123. timeArr := strings.Split(timeStr, "-")
  6124. total, _ := service.FindAllCancelStockTotal(orgID)
  6125. total = total + 1
  6126. orderNumber := "CKTKD" + strconv.FormatInt(orgID, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000" + strconv.FormatInt(total, 10)
  6127. cancelStock := models.CancelStock{
  6128. OrderNumber: orderNumber,
  6129. OperaTime: operation_time,
  6130. OrgId: orgID,
  6131. Creater: warehouseOut.Creater,
  6132. Ctime: time.Now().Unix(),
  6133. Status: 1,
  6134. ReturnTime: record_time,
  6135. Type: 1,
  6136. StorehouseId: stockInInfo.StorehouseId,
  6137. IsCheck: 1,
  6138. }
  6139. _, msgerrkonde := service.GetCancelStockDetailByOrderNumberOne(record_time, orgID)
  6140. if msgerrkonde == gorm.ErrRecordNotFound {
  6141. service.AddSigleCancelStock(&cancelStock)
  6142. }
  6143. cancel, _ := service.GetLastCancelStockById(orgID)
  6144. manufacturer, _ := service.GetManufactureById(stockInInfo.Manufacturer)
  6145. deaerler, _ := service.GetDealerById(stockInInfo.Dealer)
  6146. cancelStockInfo := models.CancelStockInfo{
  6147. GoodId: stockInInfo.GoodId,
  6148. CancelStockId: cancel.ID,
  6149. GoodTypeId: stockInInfo.GoodTypeId,
  6150. Count: delete_count,
  6151. Price: stockInInfo.PackingPrice,
  6152. Total: 0,
  6153. ProductDate: stockInInfo.ProductDate,
  6154. ExpiryDate: stockInInfo.ExpiryDate,
  6155. Ctime: time.Now().Unix(),
  6156. Status: 1,
  6157. OrgId: orgID,
  6158. OrderNumber: cancel.OrderNumber,
  6159. Type: 0,
  6160. Dealer: deaerler.DealerName,
  6161. Manufacturer: manufacturer.ManufacturerName,
  6162. Number: stockInInfo.Number,
  6163. RegisterAccount: "",
  6164. Remark: "",
  6165. WarehouseInfoId: stockInInfo.ID,
  6166. PatientId: patient_id,
  6167. RecordDate: record_time,
  6168. StorehouseId: stockInInfo.StorehouseId,
  6169. IsCheck: 1,
  6170. }
  6171. service.CreateCancelStockInfoOne(&cancelStockInfo)
  6172. cancelInfo, _ := service.GetLastCancelStockInfoByGoodId(stockInInfo.GoodId)
  6173. flow := models.VmStockFlow{
  6174. WarehousingId: warehouseOutInfo.WarehouseInfotId,
  6175. GoodId: good_yc.GoodId,
  6176. Number: warehouseOutInfos.Number,
  6177. LicenseNumber: stockInInfo.LicenseNumber,
  6178. Count: delete_count,
  6179. UserOrgId: orgID,
  6180. PatientId: patient_id,
  6181. SystemTime: record_time,
  6182. ConsumableType: 7,
  6183. IsSys: 0,
  6184. WarehousingOrder: "",
  6185. WarehouseOutId: warehouseOutInfos.WarehouseOutId,
  6186. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  6187. IsEdit: 0,
  6188. CancelStockId: cancel.ID,
  6189. CancelOrderNumber: cancel.OrderNumber,
  6190. Manufacturer: manufacturer.ID,
  6191. Dealer: 0,
  6192. Creator: warehouseOut.Creater,
  6193. UpdateCreator: 0,
  6194. Status: 1,
  6195. Ctime: time.Now().Unix(),
  6196. Mtime: 0,
  6197. Price: stockInInfo.Price,
  6198. WarehousingDetailId: stockInInfo.ID,
  6199. WarehouseOutDetailId: warehouseOutInfos.ID,
  6200. CancelOutDetailId: cancelInfo.ID,
  6201. ProductDate: stockInInfo.ProductDate,
  6202. ExpireDate: stockInInfo.ExpiryDate,
  6203. StorehouseId: houseConfig.StorehouseOutInfo,
  6204. OverCount: sum_count,
  6205. }
  6206. service.CreateStockFlowOne(flow)
  6207. //更改自动出库的表格
  6208. details := models.BloodAutomaticReduceDetail{
  6209. WarehouseOutId: warehouseOutInfo.ID,
  6210. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  6211. PatientId: patient_id,
  6212. Ctime: time.Now().Unix(),
  6213. Mtime: time.Now().Unix(),
  6214. Status: 1,
  6215. RecordTime: record_time,
  6216. OrgId: orgID,
  6217. GoodId: good_yc.GoodId,
  6218. GoodTypeId: good_yc.GoodTypeId,
  6219. Count: count,
  6220. StorehouseId: houseConfig.StorehouseOutInfo,
  6221. }
  6222. //查询当天耗材是否已经存在数据
  6223. _, errcode := service.GetAutoMaticReduceDetail(orgID, patient_id, record_time, good_yc.GoodId, good_yc.GoodTypeId)
  6224. if errcode == gorm.ErrRecordNotFound {
  6225. errTwo := service.CreateAutoReduceRecord(&details)
  6226. if errTwo != nil {
  6227. return errTwo
  6228. }
  6229. } else if errcode == nil {
  6230. service.DeleteAutoRedeceDetailTwo(orgID, patient_id, record_time, good_yc.GoodId, good_yc.GoodTypeId)
  6231. service.CreateAutoReduceRecord(&details)
  6232. }
  6233. service.ModifyGoodAddInformation(good_yc.GoodId, delete_count, good_yc.OrgId)
  6234. //增加出库库存数量
  6235. //service.ModifyReduceGoodSumCount(houseConfig.StorehouseOutInfo,delete_count,good_yc.OrgId,good_yc.GoodId)
  6236. if good_yc.Count == 0 {
  6237. return nil
  6238. } else {
  6239. return errors.New("退库和出库数据不匹配")
  6240. }
  6241. }
  6242. func (this *DialysisAPIController) SavePatientSign() {
  6243. adminUserInfo := this.GetMobileAdminUserInfo()
  6244. patient_id, _ := this.GetInt64("patient_id")
  6245. dialysis_date, _ := this.GetInt64("dialysis_date")
  6246. orgid := adminUserInfo.Org.Id
  6247. var esdata models.DialysisOrder
  6248. var err error
  6249. if err = json.Unmarshal(this.Ctx.Input.RequestBody, &esdata); err != nil {
  6250. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  6251. return
  6252. }
  6253. esdata.Hash = esdata.Hash
  6254. esdata.Url = beego.AppConfig.String("qiniu_domain") + esdata.Hash
  6255. order := models.DialysisOrder{
  6256. Hash: esdata.Hash,
  6257. Url: esdata.Url,
  6258. }
  6259. err = service.UpdatePatientSign(patient_id, dialysis_date, order, orgid)
  6260. redis := service.RedisClient()
  6261. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":dialysis_order"
  6262. redis.Set(key, "", time.Second)
  6263. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":dialysis_orders_list_all"
  6264. //清空key 值
  6265. redis.Set(keyOne, "", time.Second)
  6266. //scheduleDateStartOne := startDate.Format("2006-01-02")
  6267. //keyTwo := "scheduals_" + scheduleDateStartOne + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  6268. //redis.Set(keyTwo, "", time.Second)
  6269. keyThree := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":doctor_advices"
  6270. redis.Set(keyThree, "", time.Second)
  6271. keyFour := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":monitor_records"
  6272. redis.Set(keyFour, "", time.Second)
  6273. keyFive := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":patient_info"
  6274. redis.Set(keyFive, "", time.Second)
  6275. keySix := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":his_doctor_advice"
  6276. redis.Set(keySix, "", time.Second)
  6277. keySeven := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + ":device_list_all"
  6278. redis.Set(keySeven, "", time.Second)
  6279. if err != nil {
  6280. fmt.Println(err)
  6281. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
  6282. return
  6283. }
  6284. this.ServeSuccessJSON(map[string]interface{}{
  6285. "electronic_signature": esdata,
  6286. })
  6287. }
  6288. func (this *DialysisAPIController) GetPatientSign() {
  6289. patient_id, _ := this.GetInt64("patient_id")
  6290. dialysis_date, _ := this.GetInt64("dialysis_date")
  6291. adminUserInfo := this.GetMobileAdminUserInfo()
  6292. orgId := adminUserInfo.Org.Id
  6293. dialysisOrder, err := service.GetPatientSign(patient_id, dialysis_date, orgId)
  6294. if err != nil {
  6295. fmt.Println(err)
  6296. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
  6297. return
  6298. }
  6299. this.ServeSuccessJSON(map[string]interface{}{
  6300. "dialysisOrder": dialysisOrder,
  6301. })
  6302. }
  6303. func (this *DialysisAPIController) GetScheduleByPatient() {
  6304. patient_id, _ := this.GetInt64("patient_id")
  6305. schedule_date, _ := this.GetInt64("schedule_date")
  6306. orgid := this.GetMobileAdminUserInfo().Org.Id
  6307. schedule, _ := service.GetScheduleByPatient(patient_id, schedule_date, orgid)
  6308. this.ServeSuccessJSON(map[string]interface{}{
  6309. "schedule": schedule,
  6310. })
  6311. }
  6312. func (this *DialysisAPIController) GetDialysisRecordOrder() {
  6313. org_id := this.GetMobileAdminUserInfo().Org.Id
  6314. patient_id, _ := this.GetInt64("patient_id")
  6315. schedule_date, _ := this.GetInt64("schedule_date")
  6316. order, _ := service.GetDialysisRecordOrder(org_id, patient_id, schedule_date)
  6317. this.ServeSuccessJSON(map[string]interface{}{
  6318. "order": order,
  6319. })
  6320. }
  6321. func (this *DialysisAPIController) GetScheduleTypeByIdList() {
  6322. org_id := this.GetMobileAdminUserInfo().Org.Id
  6323. schedule_date := this.GetString("schedule_date")
  6324. schedule_type, _ := this.GetInt64("schedule_type")
  6325. timeLayout := "2006-01-02"
  6326. loc, _ := time.LoadLocation("Local")
  6327. var startdateunix int64
  6328. if len(schedule_date) > 0 {
  6329. theTime, err := time.ParseInLocation(timeLayout+"15:04:05", schedule_date+"00:00:00", loc)
  6330. if err != nil {
  6331. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  6332. return
  6333. }
  6334. startdateunix = theTime.Unix()
  6335. }
  6336. list, _ := service.GetScheduleTypeById(org_id, startdateunix, schedule_type)
  6337. scheduals, _ := service.MobileGetDialysisScheduals(org_id, startdateunix, schedule_type)
  6338. devices, _ := service.GetAllDevicetByListSix(org_id)
  6339. for key, item := range scheduals {
  6340. // 床位信息
  6341. for _, device := range devices {
  6342. if item.BedId == device.ID {
  6343. scheduals[key].DeviceNumber = device
  6344. break
  6345. }
  6346. }
  6347. }
  6348. this.ServeSuccessJSON(map[string]interface{}{
  6349. "list": list,
  6350. "scheduals": scheduals,
  6351. })
  6352. }
  6353. func (this *DialysisAPIController) SavePatientPicture() {
  6354. patient_id, _ := this.GetInt64("patient_id")
  6355. dialysis_date, _ := this.GetInt64("schedule_date")
  6356. avatar := this.GetString("avatar")
  6357. fmt.Println("patient_id", patient_id)
  6358. orgId := this.GetMobileAdminUserInfo().Org.Id
  6359. order := models.DialysisOrder{
  6360. Url: avatar,
  6361. }
  6362. err := service.UpdatePatientSign(patient_id, dialysis_date, order, orgId)
  6363. redis := service.RedisClient()
  6364. key := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":dialysis_order"
  6365. redis.Set(key, "", time.Second)
  6366. keyOne := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":dialysis_orders_list_all"
  6367. //清空key 值
  6368. redis.Set(keyOne, "", time.Second)
  6369. keyThree := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":doctor_advices"
  6370. redis.Set(keyThree, "", time.Second)
  6371. keyFour := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":monitor_records"
  6372. redis.Set(keyFour, "", time.Second)
  6373. keyFive := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":patient_info"
  6374. redis.Set(keyFive, "", time.Second)
  6375. keySix := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":his_doctor_advice"
  6376. redis.Set(keySix, "", time.Second)
  6377. keySeven := strconv.FormatInt(orgId, 10) + ":" + ":device_list_all"
  6378. redis.Set(keySeven, "", time.Second)
  6379. if err != nil {
  6380. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
  6381. return
  6382. }
  6383. this.ServeSuccessJSON(map[string]interface{}{
  6384. "order": order,
  6385. })
  6386. }
  6387. func (this *DialysisAPIController) ExectionMobileAdvice() {
  6388. ids := this.GetString("ids")
  6389. idSplit := strings.Split(ids, ",")
  6390. orgId := this.GetMobileAdminUserInfo().Org.Id
  6391. config, _ := service.FindXTHisRecordByOrgIdSix(orgId)
  6392. execution_time := this.GetString("exce_time")
  6393. timeLayout2 := "2006-01-02 15:04:05"
  6394. loc, _ := time.LoadLocation("Local")
  6395. theTime, errs := time.ParseInLocation(timeLayout2, execution_time, loc)
  6396. if errs != nil {
  6397. utils.ErrorLog(errs.Error())
  6398. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  6399. return
  6400. }
  6401. //his客户
  6402. if config.IsOpen == 1 {
  6403. list, _ := service.GetHisMobileAdviceGroupList(orgId, idSplit)
  6404. adviceList, _ := service.GetHisMobileAdviceList(orgId, idSplit)
  6405. for _, item := range list {
  6406. for _, it := range adviceList {
  6407. if item.DrugId == it.DrugId {
  6408. item.ChildDoctorAdvice = append(item.ChildDoctorAdvice, it)
  6409. }
  6410. }
  6411. }
  6412. for _, item := range list {
  6413. medical, _ := service.GetBaseDrugMedical(item.DrugId)
  6414. var sum_out_count int64
  6415. for _, itemThree := range item.ChildDoctorAdvice {
  6416. var prescribing_number int64
  6417. stringPrescribingNumber := strconv.FormatFloat(itemThree.PrescribingNumber, 'f', -1, 64)
  6418. parseIntPrescribingNumber, _ := strconv.ParseInt(stringPrescribingNumber, 10, 64)
  6419. if itemThree.PrescribingNumberUnit == medical.MaxUnit && medical.MaxUnit != medical.MinUnit {
  6420. prescribing_number = parseIntPrescribingNumber * medical.MinNumber
  6421. }
  6422. if itemThree.PrescribingNumberUnit == medical.MinUnit && medical.MaxUnit != medical.MinUnit {
  6423. prescribing_number = parseIntPrescribingNumber
  6424. }
  6425. if itemThree.PrescribingNumberUnit == medical.MinUnit && medical.MaxUnit == medical.MinUnit {
  6426. prescribing_number = parseIntPrescribingNumber
  6427. }
  6428. sum_out_count += prescribing_number
  6429. }
  6430. houseConfig, _ := service.GetAllStoreHouseConfig(orgId)
  6431. drugStockOut, _ := service.GetDrugSumOutCountByDrugId(item.DrugId, orgId, houseConfig.DrugStorehouseOut)
  6432. //库存不足
  6433. if sum_out_count > drugStockOut.FlushCount {
  6434. this.ServeSuccessJSON(map[string]interface{}{
  6435. "msg": "2",
  6436. "drug": medical,
  6437. "ids": ids,
  6438. })
  6439. return
  6440. }
  6441. }
  6442. creater := this.GetMobileAdminUserInfo().AdminUser.Id
  6443. //执行医嘱
  6444. errs := service.ExectionMobileAdvice(orgId, idSplit, theTime.Unix(), creater)
  6445. advices, _ := service.FindHisDoctorAdviceByIds(orgId, idSplit)
  6446. for _, item := range advices {
  6447. key := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.PatientId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":doctor_advices"
  6448. redis := service.RedisClient()
  6449. //清空key 值
  6450. redis.Set(key, "", time.Second)
  6451. keyTwo := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":advice_list_all"
  6452. redis.Set(keyTwo, "", time.Second)
  6453. keyThree := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.PatientId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":his_doctor_advice"
  6454. redis.Set(keyThree, "", time.Second)
  6455. recordDate := theTime.Format("2006-01-02")
  6456. keyFour := "scheduals_" + recordDate + "_" + strconv.FormatInt(orgId, 10)
  6457. redis.Set(keyFour, "", time.Second)
  6458. keyFive := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":his_advices_list_all"
  6459. redis.Set(keyFive, "", time.Second)
  6460. defer redis.Close()
  6461. }
  6462. if errs == nil {
  6463. //药品管理信息
  6464. _, drugStockConfig := service.FindDrugStockAutomaticReduceRecordByOrgId(orgId)
  6465. storeHouseConfig, _ := service.GetAllStoreHouseConfig(orgId)
  6466. if drugStockConfig.IsOpen == 1 {
  6467. for _, item := range advices {
  6468. advice, _ := service.FindHisDoctorAdviceById(orgId, item.ID)
  6469. config, _ := service.GetDrugOpenConfigOne(orgId)
  6470. if config.IsOpen != 1 {
  6471. //查询该药品是否有库存
  6472. medical, _ := service.GetBaseDrugMedical(item.DrugId)
  6473. pharmacyConfig, _ := service.FindPharmacyConfig(advice.UserOrgId)
  6474. if medical.IsUse == 2 {
  6475. if config.IsOpen != 1 {
  6476. if pharmacyConfig.IsOpen == 1 && medical.IsPharmacy == 0 {
  6477. service.HisDrugsDelivery(orgId, creater, &advice)
  6478. }
  6479. if pharmacyConfig.IsOpen != 1 {
  6480. service.HisDrugsDelivery(orgId, creater, &advice)
  6481. }
  6482. //更新字典里面的库存
  6483. stockInfo, _ := service.GetDrugAllStockInfo(storeHouseConfig.DrugStorehouseOut, item.UserOrgId, item.DrugId)
  6484. var sum_count int64
  6485. for _, its := range stockInfo {
  6486. if its.MaxUnit == medical.MaxUnit {
  6487. its.StockMaxNumber = its.StockMaxNumber * medical.MinNumber
  6488. }
  6489. sum_count += its.StockMaxNumber + its.StockMinNumber
  6490. }
  6491. service.UpdateBaseDrugSumTwo(item.DrugId, sum_count, item.UserOrgId)
  6492. //剩余库存
  6493. service.UpdateDrugStockCount(item.DrugId, item.UserOrgId, storeHouseConfig.DrugStorehouseOut, sum_count)
  6494. }
  6495. }
  6496. }
  6497. }
  6498. }
  6499. this.ServeSuccessJSON(map[string]interface{}{
  6500. "msg": "1",
  6501. "ids": ids,
  6502. })
  6503. return
  6504. } else {
  6505. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  6506. }
  6507. }
  6508. fmt.Println("config233322333223", config.IsOpen)
  6509. //血透客户
  6510. if config.IsOpen == 2 || config.IsOpen == 0 {
  6511. //药品管理信息
  6512. _, drugStockConfig := service.FindDrugStockAutomaticReduceRecordByOrgId(orgId)
  6513. if drugStockConfig.IsOpen == 1 {
  6514. list, _ := service.GetBloodMobileAdviceGroupList(orgId, idSplit)
  6515. adviceList, _ := service.GetBloodMobileAdviceList(orgId, idSplit)
  6516. for _, item := range list {
  6517. for _, it := range adviceList {
  6518. if item.DrugId == it.DrugId {
  6519. item.ChildDoctorAdvice = append(item.ChildDoctorAdvice, it)
  6520. }
  6521. }
  6522. }
  6523. for _, item := range list {
  6524. medical, _ := service.GetBaseDrugMedical(item.DrugId)
  6525. var sum_out_count int64
  6526. for _, itemThree := range item.ChildDoctorAdvice {
  6527. var prescribing_number int64
  6528. stringPrescribingNumber := strconv.FormatFloat(itemThree.PrescribingNumber, 'f', -1, 64)
  6529. parseIntPrescribingNumber, _ := strconv.ParseInt(stringPrescribingNumber, 10, 64)
  6530. if itemThree.PrescribingNumberUnit == medical.MaxUnit && medical.MaxUnit != medical.MinUnit {
  6531. prescribing_number = parseIntPrescribingNumber * medical.MinNumber
  6532. }
  6533. if itemThree.PrescribingNumberUnit == medical.MinUnit && medical.MaxUnit != medical.MinUnit {
  6534. prescribing_number = parseIntPrescribingNumber
  6535. }
  6536. if itemThree.PrescribingNumberUnit == medical.MinUnit && medical.MaxUnit == medical.MinUnit {
  6537. prescribing_number = parseIntPrescribingNumber
  6538. }
  6539. sum_out_count += prescribing_number
  6540. }
  6541. houseConfig, _ := service.GetAllStoreHouseConfig(orgId)
  6542. drugStockOut, _ := service.GetDrugSumOutCountByDrugId(item.DrugId, orgId, houseConfig.DrugStorehouseOut)
  6543. //库存不足
  6544. if sum_out_count > drugStockOut.FlushCount {
  6545. this.ServeSuccessJSON(map[string]interface{}{
  6546. "msg": "2",
  6547. "drug": medical,
  6548. "ids": ids,
  6549. })
  6550. return
  6551. }
  6552. }
  6553. creater := this.GetMobileAdminUserInfo().AdminUser.Id
  6554. fmt.Println("creater2332243244224242424", creater)
  6555. //执行医嘱
  6556. errs := service.ExectionBloodMobileAdvice(orgId, idSplit, theTime.Unix(), creater)
  6557. advices, _ := service.FindAllDoctorAdviceByIds(orgId, idSplit)
  6558. for _, item := range advices {
  6559. key := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.PatientId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":doctor_advices"
  6560. redis := service.RedisClient()
  6561. //清空key 值
  6562. redis.Set(key, "", time.Second)
  6563. keyTwo := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":advice_list_all"
  6564. redis.Set(keyTwo, "", time.Second)
  6565. keyThree := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.PatientId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":his_doctor_advice"
  6566. redis.Set(keyThree, "", time.Second)
  6567. recordDate := theTime.Format("2006-01-02")
  6568. keyFour := "scheduals_" + recordDate + "_" + strconv.FormatInt(orgId, 10)
  6569. redis.Set(keyFour, "", time.Second)
  6570. keyFive := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":his_advices_list_all"
  6571. redis.Set(keyFive, "", time.Second)
  6572. defer redis.Close()
  6573. }
  6574. if errs == nil {
  6575. for _, item := range advices {
  6576. storeHouseConfig, _ := service.GetAllStoreHouseConfig(orgId)
  6577. medical, _ := service.GetBaseDrugMedical(item.DrugId)
  6578. //查询是否出库按钮开启
  6579. adviceSetting, _ := service.FindAdviceSettingById(item.UserOrgId)
  6580. if adviceSetting.IsAdviceOpen == 1 {
  6581. //查询是否出库按钮开启
  6582. prescriptionConfig, _ := service.FindPrescriptionConfigById(item.UserOrgId)
  6583. pharmacyConfig, _ := service.FindPharmacyConfig(item.UserOrgId)
  6584. if prescriptionConfig.IsOpen == 1 {
  6585. if medical.IsUse == 2 {
  6586. if pharmacyConfig.IsOpen == 1 && medical.IsPharmacy == 0 {
  6587. service.DrugsDelivery(item.UserOrgId, item.ExecutionStaff, &item)
  6588. }
  6589. if pharmacyConfig.IsOpen != 1 {
  6590. service.DrugsDelivery(item.UserOrgId, item.ExecutionStaff, &item)
  6591. }
  6592. //更新字典里面的库存
  6593. stockInfo, _ := service.GetDrugAllStockInfo(storeHouseConfig.DrugStorehouseOut, item.UserOrgId, item.DrugId)
  6594. var sum_count int64
  6595. for _, its := range stockInfo {
  6596. if its.MaxUnit == medical.MaxUnit {
  6597. its.StockMaxNumber = its.StockMaxNumber * medical.MinNumber
  6598. }
  6599. sum_count += its.StockMaxNumber + its.StockMinNumber
  6600. }
  6601. service.UpdateBaseDrugSumTwo(item.DrugId, sum_count, item.UserOrgId)
  6602. //剩余库存
  6603. service.UpdateDrugStockCount(item.DrugId, item.UserOrgId, storeHouseConfig.DrugStorehouseOut, sum_count)
  6604. }
  6605. }
  6606. } else {
  6607. pharmacyConfig, _ := service.FindPharmacyConfig(item.UserOrgId)
  6608. if medical.IsUse == 2 {
  6609. if pharmacyConfig.IsOpen == 1 && medical.IsPharmacy == 0 {
  6610. service.DrugsDelivery(item.UserOrgId, item.ExecutionStaff, &item)
  6611. }
  6612. if pharmacyConfig.IsOpen != 1 {
  6613. service.DrugsDelivery(item.UserOrgId, item.ExecutionStaff, &item)
  6614. }
  6615. stockInfo, _ := service.GetDrugAllStockInfo(storeHouseConfig.DrugStorehouseOut, item.UserOrgId, item.DrugId)
  6616. var sum_count int64
  6617. for _, its := range stockInfo {
  6618. if its.MaxUnit == medical.MaxUnit {
  6619. its.StockMaxNumber = its.StockMaxNumber * medical.MinNumber
  6620. }
  6621. sum_count += its.StockMaxNumber + its.StockMinNumber
  6622. }
  6623. service.UpdateBaseDrugSumTwo(item.DrugId, sum_count, item.UserOrgId)
  6624. //剩余库存
  6625. service.UpdateDrugStockCount(item.DrugId, item.UserOrgId, storeHouseConfig.DrugStorehouseOut, sum_count)
  6626. }
  6627. }
  6628. }
  6629. }
  6630. this.ServeSuccessJSON(map[string]interface{}{
  6631. "msg": "1",
  6632. "ids": ids,
  6633. })
  6634. return
  6635. } else {
  6636. creater := this.GetMobileAdminUserInfo().AdminUser.Id
  6637. //执行医嘱
  6638. service.ExectionBloodMobileAdvice(orgId, idSplit, theTime.Unix(), creater)
  6639. advices, _ := service.FindAllDoctorAdviceByIds(orgId, idSplit)
  6640. for _, item := range advices {
  6641. key := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.PatientId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":doctor_advices"
  6642. redis := service.RedisClient()
  6643. //清空key 值
  6644. redis.Set(key, "", time.Second)
  6645. keyTwo := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":advice_list_all"
  6646. redis.Set(keyTwo, "", time.Second)
  6647. keyThree := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.PatientId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":his_doctor_advice"
  6648. redis.Set(keyThree, "", time.Second)
  6649. recordDate := theTime.Format("2006-01-02")
  6650. keyFour := "scheduals_" + recordDate + "_" + strconv.FormatInt(orgId, 10)
  6651. redis.Set(keyFour, "", time.Second)
  6652. keyFive := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":his_advices_list_all"
  6653. redis.Set(keyFive, "", time.Second)
  6654. defer redis.Close()
  6655. }
  6656. this.ServeSuccessJSON(map[string]interface{}{
  6657. "msg": "1",
  6658. "ids": ids,
  6659. })
  6660. return
  6661. }
  6662. }
  6663. }
  6664. func (this *DialysisAPIController) GetSettleMobileAdvice() {
  6665. ids := this.GetString("ids")
  6666. idSplit := strings.Split(ids, ",")
  6667. orgId := this.GetMobileAdminUserInfo().Org.Id
  6668. config, _ := service.FindXTHisRecordByOrgIdSix(orgId)
  6669. if config.IsOpen == 1 {
  6670. service.UpdateSettleMobileHisAdvice(orgId, idSplit)
  6671. this.ServeSuccessJSON(map[string]interface{}{
  6672. "msg": "1",
  6673. "ids": ids,
  6674. })
  6675. return
  6676. }
  6677. if config.IsOpen == 0 || config.IsOpen == 2 {
  6678. service.UpdateSettleMobileBloodAdvice(orgId, idSplit)
  6679. this.ServeSuccessJSON(map[string]interface{}{
  6680. "msg": "1",
  6681. "ids": ids,
  6682. })
  6683. return
  6684. }
  6685. }
  6686. func (this *DialysisAPIController) GetCheckMobileAdvice() {
  6687. ids := this.GetString("ids")
  6688. idSplit := strings.Split(ids, ",")
  6689. orgId := this.GetMobileAdminUserInfo().Org.Id
  6690. config, _ := service.FindXTHisRecordByOrgIdSix(orgId)
  6691. //his
  6692. if config.IsOpen == 1 {
  6693. checker := this.GetMobileAdminUserInfo().AdminUser.Id
  6694. theTime := time.Now()
  6695. advices := models.HisDoctorAdviceThirty{
  6696. CheckTime: theTime.Unix(),
  6697. Checker: checker,
  6698. UpdatedTime: time.Now().Unix(),
  6699. }
  6700. service.CheckHisMobileDoctorAdvice(orgId, idSplit, advices)
  6701. list, _ := service.FindDoctorAdviceByIds(orgId, idSplit)
  6702. for _, item := range list {
  6703. key := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.PatientId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":doctor_advices"
  6704. redis := service.RedisClient()
  6705. //清空key 值
  6706. redis.Set(key, "", time.Second)
  6707. keyTwo := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":advice_list_all"
  6708. redis.Set(keyTwo, "", time.Second)
  6709. keyThree := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.PatientId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":his_doctor_advice"
  6710. redis.Set(keyThree, "", time.Second)
  6711. recordDate := theTime.Format("2006-01-02")
  6712. keyFour := "scheduals_" + recordDate + "_" + strconv.FormatInt(orgId, 10)
  6713. redis.Set(keyFour, "", time.Second)
  6714. keyFive := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":his_advices_list_all"
  6715. redis.Set(keyFive, "", time.Second)
  6716. defer redis.Close()
  6717. }
  6718. this.ServeSuccessJSON(map[string]interface{}{
  6719. "msg": "1",
  6720. "ids": ids,
  6721. })
  6722. return
  6723. }
  6724. //血透
  6725. if config.IsOpen == 0 || config.IsOpen == 2 {
  6726. checker := this.GetMobileAdminUserInfo().AdminUser.Id
  6727. theTime := time.Now()
  6728. advices := models.DoctorAdvice{
  6729. CheckTime: theTime.Unix(),
  6730. Checker: checker,
  6731. UpdatedTime: time.Now().Unix(),
  6732. }
  6733. service.CheckBloodDoctorAdvice(orgId, idSplit, advices)
  6734. list, _ := service.FindDoctorAdviceByIds(orgId, idSplit)
  6735. for _, item := range list {
  6736. key := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.PatientId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":doctor_advices"
  6737. redis := service.RedisClient()
  6738. //清空key 值
  6739. redis.Set(key, "", time.Second)
  6740. keyTwo := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":advice_list_all"
  6741. redis.Set(keyTwo, "", time.Second)
  6742. keyThree := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.PatientId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":his_doctor_advice"
  6743. redis.Set(keyThree, "", time.Second)
  6744. recordDate := theTime.Format("2006-01-02")
  6745. keyFour := "scheduals_" + recordDate + "_" + strconv.FormatInt(orgId, 10)
  6746. redis.Set(keyFour, "", time.Second)
  6747. keyFive := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":his_advices_list_all"
  6748. redis.Set(keyFive, "", time.Second)
  6749. defer redis.Close()
  6750. }
  6751. this.ServeSuccessJSON(map[string]interface{}{
  6752. "msg": "1",
  6753. "ids": ids,
  6754. })
  6755. return
  6756. }
  6757. }
  6758. func (this *DialysisAPIController) CheckSchedule() {
  6759. patientID, _ := this.GetInt64("patient_id")
  6760. recordDateStr := this.GetString("record_date")
  6761. nurseID, _ := this.GetInt64("nurse")
  6762. schedual_type, _ := this.GetInt64("schedual_type")
  6763. bedID, _ := this.GetInt64("bed")
  6764. start_time := this.GetString("start_time")
  6765. if patientID <= 0 || len(recordDateStr) == 0 || nurseID <= 0 || bedID <= 0 {
  6766. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  6767. return
  6768. }
  6769. startDate, parseStartDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", start_time)
  6770. if parseStartDateErr != nil {
  6771. this.ErrorLog("时间解析失败:%v", parseStartDateErr)
  6772. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  6773. return
  6774. }
  6775. recordDate, parseErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  6776. if parseErr != nil {
  6777. this.ErrorLog("时间解析失败:%v", parseErr)
  6778. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  6779. return
  6780. }
  6781. adminUserInfo := this.GetMobileAdminUserInfo()
  6782. patient, getPatientErr := service.MobileGetPatientById(adminUserInfo.Org.Id, patientID)
  6783. if getPatientErr != nil {
  6784. this.ErrorLog("获取患者信息失败:%v", getPatientErr)
  6785. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  6786. return
  6787. } else if patient == nil {
  6788. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  6789. return
  6790. }
  6791. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  6792. if getNurseErr != nil {
  6793. this.ErrorLog("获取护士失败:%v", getNurseErr)
  6794. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  6795. return
  6796. } else if nurse == nil {
  6797. this.ErrorLog("护士不存在")
  6798. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  6799. return
  6800. }
  6801. deviceNumber, getDeviceNumberErr := service.GetDeviceNumberByID(adminUserInfo.Org.Id, bedID)
  6802. if getDeviceNumberErr != nil {
  6803. this.ErrorLog("获取床位号失败:%v", getDeviceNumberErr)
  6804. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  6805. return
  6806. } else if deviceNumber == nil {
  6807. this.ErrorLog("床位号不存在")
  6808. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  6809. return
  6810. }
  6811. dialysisRecord, getRecordErr := service.MobileGetDialysisRecord(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  6812. if getRecordErr != nil {
  6813. this.ErrorLog("获取透析记录失败:%v", getRecordErr)
  6814. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  6815. return
  6816. } else if dialysisRecord != nil {
  6817. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatStart)
  6818. return
  6819. }
  6820. scheduleDateStart := startDate.Format("2006-01-02") + " 00:00:00"
  6821. scheduleDateEnd := startDate.Format("2006-01-02") + " 23:59:59"
  6822. timeLayout := "2006-01-02 15:04:05"
  6823. loc, _ := time.LoadLocation("Local")
  6824. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  6825. theEndTime, _ := time.ParseInLocation(timeLayout, scheduleDateEnd, loc)
  6826. schedulestartTime := theStartTime.Unix()
  6827. scheduleendTime := theEndTime.Unix()
  6828. //查询更改的机号,是否有人用了,如果只是排班了,但是没上机,直接替换,如果排班且上机了,就提示他无法上机
  6829. //sch, _ := service.GetSourceSch(adminUserInfo.Org.Id, patientID, scheduleendTime)
  6830. schedule, err := service.GetDayScheduleByBedid(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  6831. //查询该床位是否有人用了
  6832. order, _ := service.GetDialysisOrderByBedIdTwo(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  6833. if err == nil {
  6834. if schedule.ID == 0 {
  6835. this.ServeSuccessJSON(map[string]interface{}{
  6836. "status": 0,
  6837. "msg": "请求失败",
  6838. })
  6839. } else {
  6840. if schedule.ID > 0 && schedule.DialysisOrder.ID == 0 { //有排班没上机记录
  6841. if order.ID > 0 { //该机位被其他人占用了
  6842. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  6843. return
  6844. } else { //2022-11-04 更变需求,如果改床位有排班,但是没上机,则进行互换床位操作,如果改床位是本人的话,不做处理
  6845. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  6846. if daySchedule.ID > 0 && schedule.PatientId != daySchedule.PatientId {
  6847. this.ServeSuccessJSON(map[string]interface{}{
  6848. "status": 1,
  6849. "msg": "该机位已有排班,继续操作将会与原来的排班信息进行互调,请问是否继续?",
  6850. })
  6851. return
  6852. } else {
  6853. this.ServeSuccessJSON(map[string]interface{}{
  6854. "status": 0,
  6855. "msg": "",
  6856. })
  6857. }
  6858. }
  6859. } else if schedule.ID > 0 && schedule.DialysisOrder.ID > 0 {
  6860. this.ServeSuccessJSON(map[string]interface{}{
  6861. "status": 2,
  6862. "msg": "当前机位已有患者在使用,请重新选择!",
  6863. })
  6864. }
  6865. }
  6866. } else {
  6867. this.ServeSuccessJSON(map[string]interface{}{
  6868. "status": 0,
  6869. "msg": "",
  6870. })
  6871. }
  6872. }