dialysis_api_controller.go 288KB

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