dialysis_api_controller.go 288KB

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