dialysis_api_controller.go 259KB

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