StatisticsController.cs 303 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417
  1. using Aspose.Cells;
  2. using Aspose.Words.Tables;
  3. using EyeSoft.Collections.Generic;
  4. using Google.Protobuf.WellKnownTypes;
  5. using Microsoft.AspNetCore.Mvc.ViewEngines;
  6. using Microsoft.EntityFrameworkCore.Metadata.Internal;
  7. using MySqlX.XDevAPI.Relational;
  8. using NetUV.Core.Handles;
  9. using NPOI.POIFS.Properties;
  10. using NPOI.SS.Formula.Functions;
  11. using NPOI.SS.Formula.PTG;
  12. using OASystem.API.OAMethodLib;
  13. using OASystem.API.OAMethodLib.JuHeAPI;
  14. using OASystem.Domain.AesEncryption;
  15. using OASystem.Domain.Dtos.Statistics;
  16. using OASystem.Domain.Entities.Customer;
  17. using OASystem.Domain.Entities.Groups;
  18. using OASystem.Domain.ViewModels.Financial;
  19. using OASystem.Domain.ViewModels.JuHeExchangeRate;
  20. using OASystem.Domain.ViewModels.QiYeWeChat;
  21. using OASystem.Domain.ViewModels.Statistics;
  22. using OASystem.Infrastructure.Repositories.Groups;
  23. using System;
  24. using System.Data;
  25. using static OASystem.API.OAMethodLib.GeneralMethod;
  26. using TypeInfo = OASystem.Domain.ViewModels.Statistics.TypeInfo;
  27. namespace OASystem.API.Controllers
  28. {
  29. /// <summary>
  30. /// 统计模块
  31. /// </summary>
  32. [Route("api/[controller]")]
  33. [ApiController]
  34. public class StatisticsController : ControllerBase
  35. {
  36. private readonly int _decimalPlaces;
  37. private readonly IConfiguration _config;
  38. private readonly IMapper _mapper;
  39. private readonly SqlSugarClient _sqlSugar;
  40. private readonly DelegationInfoRepository _groupRep;
  41. private readonly SetDataRepository _setDataRep;
  42. private readonly TeamRateRepository _teamRateRep;
  43. private readonly VisitingClientsRepository _visitingClientsRep;
  44. private readonly IJuHeApiService _juHeApiService;
  45. /// <summary>
  46. /// Init
  47. /// </summary>
  48. /// <param name="mapper"></param>
  49. /// <param name="config"></param>
  50. /// <param name="sqlSugar"></param>
  51. /// <param name="groupRep"></param>
  52. /// <param name="setDataRep"></param>
  53. /// <param name="teamRate"></param>
  54. /// <param name="visitingClientsRep"></param>
  55. /// <param name="juHeApiService"></param>
  56. public StatisticsController(
  57. IMapper mapper,
  58. IConfiguration config,
  59. SqlSugarClient sqlSugar,
  60. DelegationInfoRepository groupRep,
  61. SetDataRepository setDataRep,
  62. TeamRateRepository teamRate,
  63. VisitingClientsRepository visitingClientsRep,
  64. IJuHeApiService juHeApiService
  65. )
  66. {
  67. _mapper = mapper;
  68. _config = config;
  69. _groupRep = groupRep;
  70. _setDataRep = setDataRep;
  71. _sqlSugar = sqlSugar;
  72. _teamRateRep = teamRate;
  73. _visitingClientsRep = visitingClientsRep;
  74. _juHeApiService = juHeApiService;
  75. }
  76. #region 团组报表
  77. /// <summary>
  78. /// 团组报表
  79. /// Items
  80. /// </summary>
  81. /// <param name="_dto">团组列表请求dto</param>
  82. /// <returns></returns>
  83. [HttpPost("PostGroupStatementItems")]
  84. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  85. public async Task<IActionResult> PostGroupStatementItems(GroupStatementItemsDto _dto)
  86. {
  87. #region 参数验证
  88. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  89. if (_dto.PageId < 1) return Ok(JsonView(false, "页面Id为空"));
  90. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  91. #region 页面操作权限验证
  92. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  93. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  94. #endregion
  95. #endregion
  96. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  97. {
  98. string sqlWhere = string.Empty;
  99. if (_dto.IsSure == 0) //未完成
  100. {
  101. sqlWhere += string.Format(@" And IsSure = 0");
  102. }
  103. else if (_dto.IsSure == 1) //已完成
  104. {
  105. sqlWhere += string.Format(@" And IsSure = 1");
  106. }
  107. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  108. {
  109. string tj = _dto.SearchCriteria;
  110. sqlWhere += string.Format(@"And (ssd.Name Like '%{0}%' Or TeamName Like '%{1}%' Or ClientName Like '%{2}%' Or ClientName Like '%{3}%' Or su.CnName Like '%{4}%')",
  111. tj, tj, tj, tj, tj);
  112. }
  113. string sql = string.Format(@"Select row_number() over(order by gdi.VisitDate Desc) as Row_Number,
  114. gdi.Id,TourCode,ssd1.Id TeamLevId,ssd1.Name TeamLev,TeamName,
  115. ClientName,ClientUnit,VisitDate,ssd.Id TeamTypeId, ssd.Name TeamType,
  116. VisitDays,VisitPNumber,su.CnName JietuanOperator,IsSure,gdi.CreateTime,
  117. pr.LastCollectionTime
  118. From Grp_DelegationInfo gdi
  119. Left Join Sys_SetData ssd On gdi.TeamDid = ssd.Id
  120. Left Join Sys_SetData ssd1 On gdi.TeamLevSId = ssd1.Id
  121. Left Join Sys_Users su On gdi.JietuanOperator = su.Id
  122. Left Join (
  123. SELECT Diid, MAX(CreateTime) LastCollectionTime
  124. FROM Fin_ProceedsReceived
  125. Where IsDel = 0
  126. GROUP BY Diid
  127. ) pr On gdi.Id = pr.Diid
  128. Where gdi.IsDel = 0 {0} ", sqlWhere);
  129. RefAsync<int> total = 0;//REF和OUT不支持异步,想要真的异步这是最优解
  130. var _DelegationList = await _sqlSugar.SqlQueryable<GroupStatementItemView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);//ToPageAsync
  131. var _view = new
  132. {
  133. PageFuncAuth = pageFunAuthView,
  134. Data = _DelegationList
  135. };
  136. return Ok(JsonView(true, "查询成功!", _view, total));
  137. }
  138. else
  139. {
  140. return Ok(JsonView(false, "查询失败"));
  141. }
  142. }
  143. /// <summary>
  144. /// 团组报表
  145. /// Details
  146. /// </summary>
  147. /// <param name="_dto">团组列表请求dto</param>
  148. /// <returns></returns>
  149. [HttpPost("PostGroupStatementDetails")]
  150. //[JsonConverter(typeof(DecimalConverter), 2)]
  151. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  152. public async Task<IActionResult> PostGroupStatementDetails(GroupStatementDetailsDto _dto)
  153. {
  154. /*
  155. * 团组报表计算方式
  156. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  157. * 应收金额 = 应收表.Sum()
  158. * 已收金额 = 已收表.Sum()
  159. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  160. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  161. *
  162. */
  163. #region 参数验证
  164. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  165. if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  166. if (_dto.DiId < 1) return Ok(JsonView(false, "团组Id为空"));
  167. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  168. #region 页面操作权限验证
  169. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  170. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  171. #endregion
  172. #endregion
  173. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  174. {
  175. GroupStatementDetailsView _view = new GroupStatementDetailsView();
  176. #region 费用类型 币种,转账,客户信息
  177. List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  178. var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>()
  179. .Where(it => it.IsDel == 0)
  180. .Select(x => new Crm_DeleClient { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, Sex = x.Sex })
  181. .ToListAsync();
  182. foreach (var item in _clientDatas) EncryptionProcessor.DecryptProperties(item);
  183. var groupInfo = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => x.Id == _dto.DiId).FirstAsync();
  184. var visitDate = groupInfo.VisitDate;
  185. #endregion
  186. #region 团组收入
  187. GroupIncomeView _giView = new GroupIncomeView();
  188. /*
  189. * 应收报表
  190. * 增加方式=实际报价时 费用必须审核才能进入团组报表
  191. */
  192. decimal frTotalAmount = 0.00M;//应收总金额
  193. string _frSql = string.Format(@" Select fr.Id,fr.AddingWay,fr.Status,u.CnName As Auditor,fr.AuditTime,fr.Diid,fr.PriceName,fr.Price,fr.Count,fr.Unit,fr.Currency,
  194. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  195. From Fin_ForeignReceivables fr
  196. Left Join Sys_SetData sd On fr.Currency = sd.Id
  197. Left Join Sys_Users u On fr.Auditor = u.Id
  198. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
  199. List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  200. //List<Gsd_ForeignReceivablesView> _frViews = new List<Gsd_ForeignReceivablesView>();
  201. //if (_frViews1.Count > 0)
  202. //{
  203. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay != 2).ToList());
  204. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay == 2 && x.Status == 1).ToList());
  205. //}
  206. _frViews.ForEach(x =>
  207. {
  208. string namePrefix = string.Empty;
  209. if (x.AddingWay == 0) namePrefix = $"账单模块-";
  210. else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
  211. else if (x.AddingWay == 2) namePrefix = $"实际报价-";
  212. x.PriceName = $"{namePrefix}{x.PriceName}";
  213. });
  214. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  215. _giView.Receivables = _frViews;
  216. _giView.ReceivableStr = string.Format(@"应收款合计:{0} CNY(人民币)", frTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  217. /*
  218. * 已收报表
  219. */
  220. decimal prTotalAmount = 0.00M;//已收总金额
  221. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  222. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  223. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  224. From Fin_ProceedsReceived pr
  225. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  226. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  227. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
  228. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  229. prTotalAmount = _prViews.Sum(it => it.Price);
  230. _giView.ProceedsReceivedViews = _prViews;
  231. _giView.ProceedsReceivedStr = string.Format(@$"应收合计:{frTotalAmount:#0.00} CNY 已收款合计:{prTotalAmount.ConvertToDecimal1():#0.00} CNY");
  232. /*
  233. * 超支费用
  234. */
  235. decimal exTotalAmount = 0.00M;
  236. // string ecSql = string.Format(@"Select gec.Id As GECId,gec.DiId As GECDiId,gec.PriceName,(gec.PriceSum * gec.Coefficient) As PayMoney,sd1.Name As PaymentCurrency,
  237. // (gec.PriceSum * gec.Coefficient * ccp.DayRate) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  238. // sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  239. //From OA2023DB.dbo.Fin_GroupExtraCost gec
  240. //Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  241. // Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  242. // Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  243. // Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  244. // Left Join Sys_Users u On ccp.CreateUserId = u.Id
  245. //Where ccp.IsDel = 0 And ccp.CTable = 1015 {1} And ccp.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1 And ccp.IsPay = 1 " : " ");
  246. // List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(ecSql).ToListAsync();
  247. // #region 超支费用 - 模拟数据
  248. // //if (_ExtraCostsViews.Count < 1)
  249. // //{
  250. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  251. // // {
  252. // // GECId = 0,
  253. // // GECDiId = 2334,
  254. // // PriceName = "模拟数据-超支费用名称",
  255. // // PayMoney = 1000.00M,
  256. // // PaymentCurrency = "CNY",
  257. // // DayRate = 1.0000M,
  258. // // CNYPrice = 1000.00M,
  259. // // Payee = "模拟数据-超支费用收款方",
  260. // // OrbitalPrivateTransfer = 1,
  261. // // PayWay = "刷卡",
  262. // // CardType = "招行卡",
  263. // // IsPay = 1,
  264. // // Applicant = "刘华举"
  265. // // });
  266. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  267. // // {
  268. // // GECId = 0,
  269. // // GECDiId = 2334,
  270. // // PriceName = "模拟数据-超支费用名称",
  271. // // PayMoney = 1000.00M,
  272. // // PaymentCurrency = "CNY",
  273. // // DayRate = 1.0000M,
  274. // // CNYPrice = 1000.00M,
  275. // // Payee = "模拟数据-超支费用收款方",
  276. // // OrbitalPrivateTransfer = 1,
  277. // // PayWay = "刷卡",
  278. // // CardType = "招行卡",
  279. // // IsPay = 1,
  280. // // Applicant = "刘华举"
  281. // // });
  282. // //}
  283. // #endregion
  284. // exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  285. // _giView.ExtraCostsViews = _ExtraCostsViews;
  286. // _giView.ExtraCostsStr = string.Format(@"人民币总费用:{0} CNY", exTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  287. /*
  288. * 收款退还
  289. */
  290. decimal promTotalAmount = 0.00M;// 收款退还总金额
  291. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  292. //删除了 And prom.PriceType = 1
  293. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  294. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  295. prom.PayType As PrPayType,prom.PriceType As PrPriceType,
  296. ccp.RMBPrice * ccp.DayRate As RMBPrice,ccp.*,prom.CreateTime As PrCreateTime
  297. From Fin_PaymentRefundAndOtherMoney prom
  298. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  299. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  300. Where prom.IsDel = 0
  301. And prom.PayType = 1
  302. And ccp.CTable = 285
  303. {1}
  304. And prom.DiId = {0} Order By PrCreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  305. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  306. foreach (var ropItem in _promDatas)
  307. {
  308. string thisCueencyCode = "Unknown";
  309. string thisCueencyName = "Unknown";
  310. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  311. if (currency != null)
  312. {
  313. thisCueencyCode = currency.Name;
  314. thisCueencyName = currency.Remark;
  315. }
  316. string orbitalPrivateTransferStr = "Unknown";
  317. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  318. if (orbitalPrivateTransfer != null)
  319. {
  320. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  321. }
  322. string payStr = "Unknown";
  323. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  324. if (pay != null)
  325. {
  326. payStr = pay.Name;
  327. }
  328. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  329. {
  330. Id = ropItem.Id,
  331. DiId = ropItem.DIId,
  332. PriceName = ropItem.PrPriceName,
  333. PayCurrencyCode = thisCueencyCode,
  334. PayCurrencyName = thisCueencyName,
  335. Price = ropItem.PrPrice,
  336. CNYPrice = ropItem.PayMoney * ropItem.DayRate,
  337. ThisRate = ropItem.DayRate,
  338. Payee = ropItem.Payee,
  339. PayTime = ropItem.AuditGMDate,
  340. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  341. PayType = payStr,
  342. IsPay = ropItem.IsPay,
  343. Applicant = ropItem.Appliction
  344. };
  345. _promView.Add(gsd_PaymentRefund);
  346. }
  347. #region 收款退还 - 模拟数据
  348. //if (_promView.Count < 1)
  349. //{
  350. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  351. // {
  352. // Id = 0,
  353. // DiId = 2334,
  354. // PriceName = "模拟数据-费用名称",
  355. // PayCurrencyCode = "CNY",
  356. // PayCurrencyName = "人民币",
  357. // Price = 1000.00M,
  358. // CNYPrice = 1000.00M,
  359. // ThisRate = 1.00M,
  360. // Payee = "模拟数据-收款方",
  361. // PayTime = "2023-01-01 15:20:01",
  362. // OrbitalPrivateTransfer = 1,
  363. // PayType = "刷卡",
  364. // IsPay = 1,
  365. // Applicant = "刘华举"
  366. // });
  367. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  368. // {
  369. // Id = 0,
  370. // DiId = 2334,
  371. // PriceName = "模拟数据-费用名称",
  372. // PayCurrencyCode = "CNY",
  373. // PayCurrencyName = "人民币",
  374. // Price = 1000.00M,
  375. // CNYPrice = 1000.00M,
  376. // ThisRate = 1.00M,
  377. // Payee = "模拟数据-收款方",
  378. // PayTime = "2023-01-01 15:20:01",
  379. // OrbitalPrivateTransfer = 1,
  380. // PayType = "刷卡",
  381. // IsPay = 1,
  382. // Applicant = "刘华举"
  383. // });
  384. //}
  385. #endregion
  386. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  387. _giView.PaymentRefundAndOtherMoneyViews = _promView;
  388. _giView.PaymentRefundAndOtherMoneyStr = string.Format(@"人民币总费用:{0} CNY", promTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  389. decimal BalancePayment = frTotalAmount - prTotalAmount + promTotalAmount;
  390. _view.GroupIncome = _giView;
  391. _view.GroupIncomeStr = string.Format(@"<span style='color:red;'>剩余尾款:{0} CNY(包含了收款退还费用数据)</span>", BalancePayment.ConvertToDecimal1().ToString("#0.00"));
  392. #endregion
  393. #region 团组支出
  394. GroupExpenditureView _geView = new GroupExpenditureView();
  395. #region 酒店预定费用
  396. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  397. //ccp.RMBPrice As CNYPrice
  398. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  399. string hotelFeeSql = string.Format(@"
  400. SELECT
  401. hr.Id AS HrId,
  402. hr.DiId AS HrDiId,
  403. hr.City,
  404. hr.HotelName,
  405. hr.CheckInDate,
  406. hr.CheckOutDate,
  407. hr.CardPrice AS RoomPrice,
  408. sd1.Name AS PaymentCurrency,
  409. hr.SingleRoomPrice,
  410. hr.SingleRoomCount,
  411. hr.DoubleRoomPrice,
  412. hr.DoubleRoomCount,
  413. hr.SuiteRoomPrice,
  414. hr.SuiteRoomCount,
  415. hr.OtherRoomPrice,
  416. hr.OtherRoomCount,
  417. hr.BreakfastPrice,
  418. sd4.Name AS BreakfastCurrency,
  419. hr.Isoppay,
  420. hr.GovernmentRent,
  421. sd5.Name AS GovernmentRentCurrency,
  422. hr.CityTax,
  423. sd6.Name AS CityTaxCurrency,
  424. ccp.PayMoney,
  425. (
  426. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  427. ) AS CNYPrice,
  428. ccp.PayPercentage,
  429. ccp.DayRate,
  430. ccp.Payee,
  431. ccp.OrbitalPrivateTransfer,
  432. sd2.Name AS PayWay,
  433. sd3.Name AS CardType,
  434. ccp.IsPay,
  435. u.CnName AS Applicant
  436. FROM
  437. Grp_HotelReservations hr
  438. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  439. LEFT JOIN Sys_SetData sd1 ON ccp.PaymentCurrency = sd1.Id
  440. LEFT JOIN Sys_SetData sd2 ON ccp.PayDId = sd2.Id
  441. LEFT JOIN Sys_SetData sd3 ON ccp.CTDId = sd3.Id
  442. LEFT JOIN Sys_Users u ON ccp.CreateUserId = u.Id
  443. LEFT JOIN Sys_SetData sd4 ON hr.BreakfastCurrency = sd4.Id
  444. LEFT JOIN Sys_SetData sd5 ON hr.GovernmentRentCurrency = sd5.Id
  445. LEFT JOIN Sys_SetData sd6 ON hr.CityTaxCurrency = sd6.Id
  446. WHERE
  447. hr.IsDel = 0
  448. AND ccp.IsDel = 0
  449. AND ccp.CTable = 76 {1}
  450. AND ccp.PayMoney <> 0
  451. AND hr.DiId = {0}
  452. ORDER BY
  453. CheckInDate Asc", _dto.DiId, _dto.isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  454. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  455. List<int> hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
  456. var groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
  457. decimal HotelCNYTotalPrice = 0.00M;
  458. var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
  459. foreach (var item in groupHotelFeeViews)
  460. {
  461. if (groupHotelContentFeeViews.Count > 0)
  462. {
  463. string paymentStr = string.Empty;
  464. var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
  465. item.RoomPrice = roomData?.Price ?? 0.00M;
  466. if (item.RoomPrice != 0)
  467. {
  468. if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
  469. item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
  470. string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  471. string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
  472. item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
  473. 收款方:{roomData?.Payee}<br/>
  474. 费用标识:{feeMark1} <br/>
  475. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  476. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
  477. 是否由地接支付:{isFeeMark1} <br/>";
  478. }
  479. var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
  480. item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
  481. if (item.BreakfastPrice != 0)
  482. {
  483. if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
  484. item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
  485. string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  486. string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
  487. item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
  488. 收款方:{breakfastData?.Payee}<br/>
  489. 费用标识:{feeMark2} <br/>
  490. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  491. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
  492. 是否由地接支付:{isFeeMark2} <br/>";
  493. }
  494. var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
  495. item.GovernmentRent = landTaxData?.Price ?? 0.00M;
  496. if (item.GovernmentRent != 0)
  497. {
  498. if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
  499. item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
  500. string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  501. string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
  502. item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
  503. 收款方:{landTaxData?.Payee}<br/>
  504. 费用标识:{feeMark3} <br/>
  505. 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
  506. 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
  507. 是否由地接支付:{isFeeMark3} <br/>";
  508. }
  509. var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
  510. item.CityTax = cityTaxData?.Price ?? 0.00M;
  511. if (item.CityTax != 0)
  512. {
  513. if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
  514. item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
  515. string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  516. string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
  517. item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
  518. 收款方:{cityTaxData?.Payee}<br/>
  519. 费用标识:{feeMark4} <br/>
  520. 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
  521. 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
  522. 是否由地接支付:{isFeeMark4} <br/>";
  523. }
  524. if (!string.IsNullOrEmpty(paymentStr))
  525. {
  526. item.IsPay = 2;
  527. item.PayTips = paymentStr;
  528. }
  529. //item.CNYPrice = roomData?.Price ?? 0.00M * roomData?.Rate ?? 0.00M +
  530. // breakfastData?.Price ?? 0.00M * breakfastData?.Rate ?? 0.00M +
  531. // landTaxData?.Price ?? 0.00M * landTaxData?.Rate ?? 0.00M +
  532. // cityTaxData?.Price ?? 0.00M * cityTaxData?.Rate ?? 0.00M;
  533. }
  534. else
  535. {
  536. decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
  537. (item.DoubleRoomCount * item.DoubleRoomPrice) +
  538. (item.SuiteRoomCount * item.SuiteRoomPrice) +
  539. (item.OtherRoomCount * item.OtherRoomPrice);
  540. //item.RoomPrice = item.CardPrice;
  541. item.RoomPriceCurrency = item.PaymentCurrency;
  542. }
  543. HotelCNYTotalPrice += item.CNYPrice;
  544. item.PayMoney = item.PayMoney.ConvertToDecimal1();
  545. item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
  546. }
  547. _geView.GroupHotelFeeViews = groupHotelFeeViews;
  548. _geView.GroupHotelFeeStr = string.Format(@"人民币总费用:{0} CNY", HotelCNYTotalPrice.ToString("#0.00"));
  549. #endregion
  550. #region 地接费用
  551. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  552. string CTGGRFeeSql = string.Empty;
  553. if (visitDate > Convert.ToDateTime("2024-04-17"))
  554. {
  555. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
  556. sd2.name As PaymentCurrency,ccp.PayPercentage,
  557. (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
  558. (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
  559. ccp.DayRate,(ctggrc.Price * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  560. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  561. From Grp_CarTouristGuideGroundReservations ctggr
  562. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
  563. cggrc.DatePrice,cggrc.PriceContent
  564. From Grp_CarTouristGuideGroundReservationsContent cggrc
  565. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  566. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  567. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  568. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  569. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  570. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  571. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  572. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  573. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  574. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  575. }
  576. else
  577. {
  578. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,
  579. ccp.PayMoney,sd2.name As PaymentCurrency,ccp.PayPercentage,
  580. (ccp.PayMoney * (ccp.PayPercentage / 100)) As AmountPaid,
  581. (ccp.PayMoney -ccp.PayMoney * (ccp.PayPercentage / 100)) As BalancePayment,
  582. ccp.DayRate,(ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,
  583. ccp.Payee,ccp.AuditGMDate,
  584. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  585. From Grp_CarTouristGuideGroundReservations ctggr
  586. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  587. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  588. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  589. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  590. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  591. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  592. }
  593. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  594. string CTGGRFeeStr = "";
  595. decimal CTGGRCNYTotalPrice = 0.00M;
  596. //按1 地区,2 币种,3 汇率 分组计算
  597. var groupCTGGRFeeDatas = groupCTGGRFeeViews.GroupBy(it => it.Area);
  598. foreach (var ctggfr in groupCTGGRFeeDatas)
  599. {
  600. var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
  601. if (ctggfr_curr.Count() > 0)
  602. {
  603. foreach (var curr in ctggfr_curr)
  604. {
  605. var ctggfr_rate = curr.GroupBy(it => it.DayRate);
  606. if (ctggfr_rate.Count() > 0)
  607. {
  608. foreach (var rate in ctggfr_rate)
  609. {
  610. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{rate.Sum(it => it.AmountPaid).ToString("#0.00")}
  611. {rate.FirstOrDefault()?.PaymentCurrency}(人民币:
  612. {rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  613. {rate.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  614. CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  615. }
  616. }
  617. else
  618. {
  619. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{curr.Sum(it => it.AmountPaid).ToString("#0.00")}
  620. {curr.FirstOrDefault()?.PaymentCurrency}(人民币:
  621. {curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  622. {curr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  623. CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  624. }
  625. }
  626. }
  627. else
  628. {
  629. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{ctggfr.Sum(it => it.AmountPaid).ToString("#0.00")}
  630. {ctggfr.FirstOrDefault()?.PaymentCurrency}(人民币:
  631. {ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  632. {ctggfr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  633. CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  634. }
  635. }
  636. foreach (var item in groupCTGGRFeeViews)
  637. {
  638. if (!string.IsNullOrEmpty(item.AuditGMDate))
  639. {
  640. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  641. }
  642. if (item.DatePrice != null)
  643. {
  644. item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
  645. }
  646. //CTGGRFeeStr += string.Format(@"{0} 总费用:{1} {2}(人民币:{3} CNY 当时支付汇率:{4})\r\n",
  647. // item.Area, item.AmountPaid.ConvertToDecimal1().ToString("#0.00"), item.PaymentCurrency, item.CNYPrice.ToString("#0.0000"), item.DayRate.ToString("#0.0000"));
  648. //CTGGRCNYTotalPrice += item.CNYPrice;
  649. }
  650. _geView.GroupCTGGRFeeViews = groupCTGGRFeeViews;
  651. _geView.GroupCTGGRFeeStr = string.Format(@"{0}人民币总费用:{1} CNY", CTGGRFeeStr, CTGGRCNYTotalPrice.ToString("#0.00"));
  652. #endregion
  653. #region 机票预订费用
  654. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  655. //ccp.RMBPrice As CNYPrice
  656. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  657. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  658. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  659. sd1.Name As PayMoneyCurrency,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  660. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime,
  661. atr.CType
  662. From Grp_AirTicketReservations atr
  663. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  664. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  665. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  666. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  667. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  668. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  669. Where atr.IsDel = 0 {1} And atr.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  670. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  671. string str = "";
  672. List<dynamic> airClientPris = new List<dynamic>();
  673. decimal AirCNYTotalPrice = 0.00M;
  674. decimal JJCCNYTotalPrice = 0.00M, JJCPeopleNum = 0.00M, JJCAveragePrice = 0.00M;
  675. decimal GWCCNYTotalPrice = 0.00M, GWCPeopleNum = 0.00M, GWCAveragePrice = 0.00M;
  676. //if (groupAirFeeViews.Count > 0)
  677. //{
  678. // JJCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.CNYPrice);
  679. // JJCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.ClientNum);
  680. // JJCAveragePrice = (JJCCNYTotalPrice / JJCPeopleNum).ConvertToDecimal1();
  681. // GWCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.CNYPrice);
  682. // GWCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.ClientNum);
  683. // GWCAveragePrice = (GWCCNYTotalPrice / GWCPeopleNum).ConvertToDecimal1();
  684. //}
  685. int Index = 0;
  686. foreach (var item in groupAirFeeViews)
  687. {
  688. if (item.AirId > 2924)
  689. {
  690. string itemClientName = "";
  691. if (!string.IsNullOrEmpty(item.ClientName))
  692. {
  693. System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  694. System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  695. if (m_EnName.Success || m_ZHName.Success)
  696. {
  697. itemClientName = item.ClientName;
  698. decimal unitCost = 0.00M;
  699. AirCNYTotalPrice += item.CNYPrice;
  700. continue;
  701. }
  702. string[] clientIds = new string[] { };
  703. if (item.ClientName.Contains(','))
  704. {
  705. clientIds = item.ClientName.Split(',');
  706. }
  707. else
  708. {
  709. clientIds = new string[] { item.ClientName };
  710. }
  711. if (clientIds.Length > 0)
  712. {
  713. int[] output = Array.ConvertAll<string, int>(clientIds, delegate (string s) { return int.Parse(s); });
  714. if (output.Contains(-1))
  715. {
  716. itemClientName += $@"行程单";
  717. output = output.Where(val => val != -1).ToArray();
  718. }
  719. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  720. decimal unitCost = 0.00M;
  721. unitCost = (item.PayMoney / item.ClientNum).ConvertToDecimal1();
  722. int clienIndex = 1;
  723. foreach (var client in clients)
  724. {
  725. airClientPris.Add(new
  726. {
  727. CnName = client.LastName + client.FirstName,
  728. EnName = client.Pinyin,
  729. Price = unitCost,
  730. AirType = item.AirTypeName
  731. });
  732. string six = "";
  733. if (client.Sex == 0) six = "Mr";
  734. else if (client.Sex == 1) six = "Ms";
  735. itemClientName += string.Format(@"{0}.{1} {2};", clienIndex, client.LastName + client.FirstName, six);
  736. clienIndex++;
  737. }
  738. }
  739. }
  740. item.ClientName = itemClientName;
  741. }
  742. else
  743. {
  744. string clientPinYinName = "";
  745. decimal unitCost = 0.00M;
  746. int cNum = item.ClientNum == 0 ? 1 : item.ClientNum;
  747. unitCost = (item.PayMoney / cNum).ConvertToDecimal1();
  748. Regex r = new Regex("[0-9]");
  749. string name1 = item.ClientName;
  750. name1 = r.Replace(name1, "");
  751. string[] clientNames = name1.Split('.');
  752. for (int i = 0; i < item.ClientNum; i++)
  753. {
  754. string name = "";
  755. if (clientNames.Length > 0)
  756. {
  757. int index = i + 1;
  758. if (index < clientNames.Length)
  759. {
  760. name = clientNames[index].Replace("MR", "").Replace("MS", "").Trim();
  761. if (!string.IsNullOrEmpty(name))
  762. {
  763. airClientPris.Add(new
  764. {
  765. CnName = name,
  766. EnName = name,
  767. Price = unitCost,
  768. AirType = item.AirTypeName
  769. });
  770. }
  771. //if (name.Length > 0)
  772. //{
  773. // string nameLastStr = name[name.Length - 1].ToString();
  774. // if (nameLastStr.IsNumeric())
  775. // {
  776. // name = name.Substring(0, name.Length - 1).Trim();
  777. // }
  778. //}
  779. }
  780. }
  781. clientPinYinName += string.Format(@"{0}.{1}出票价为:{2} CNY;", Index + 1, name, unitCost.ToString("#0.00"));
  782. }
  783. }
  784. if (!string.IsNullOrEmpty(item.AuditGMDate))
  785. {
  786. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  787. }
  788. AirCNYTotalPrice += item.CNYPrice;
  789. }
  790. _geView.GroupAirFeeViews = groupAirFeeViews;
  791. if (airClientPris.Count > 0)
  792. {
  793. var peoplePriStr = "";
  794. var airClientPris1 = airClientPris.GroupBy(item => item.CnName)
  795. .Select(group => group.First())
  796. .ToList();
  797. int airClientPrisIndex = 1;
  798. foreach (var item in airClientPris1)
  799. {
  800. decimal price = 0.00M;
  801. var prices = airClientPris.Where(it => it.CnName == item.CnName).ToList();
  802. foreach (var pri in prices)
  803. {
  804. price += pri.Price;
  805. }
  806. peoplePriStr += $@"{airClientPrisIndex}.{item.EnName}出票价为: {price.ToString("#0.00")} CNY;";
  807. airClientPrisIndex++;
  808. }
  809. if (!string.IsNullOrEmpty(peoplePriStr))
  810. {
  811. str = $@"其中:{peoplePriStr}";
  812. }
  813. //经济舱均价
  814. var airJJCPris = airClientPris.Where(it => it.AirType == "经济舱").ToList();
  815. if (airJJCPris.Count > 0)
  816. {
  817. decimal jjcTotalPrice = 0.00M;
  818. foreach (var item in airJJCPris)
  819. {
  820. jjcTotalPrice += item.Price;
  821. }
  822. decimal jjcPeopleNum = airJJCPris.GroupBy(item => item.CnName)
  823. .Select(group => group.First())
  824. .ToList().Count;
  825. JJCAveragePrice = jjcTotalPrice / jjcPeopleNum;
  826. }
  827. //公务舱均价
  828. var airGWCPris = airClientPris.Where(it => it.AirType == "公务舱").ToList();
  829. if (airGWCPris.Count > 0)
  830. {
  831. decimal gwcTotalPrice = 0.00M;
  832. foreach (var item in airGWCPris)
  833. {
  834. gwcTotalPrice += item.Price;
  835. }
  836. decimal gwcPeopleNum = airGWCPris.GroupBy(item => item.CnName)
  837. .Select(group => group.First())
  838. .ToList().Count;
  839. GWCAveragePrice = gwcTotalPrice / gwcPeopleNum;
  840. }
  841. }
  842. _geView.GroupAirFeeStr = $@"人民币总费用:{AirCNYTotalPrice.ToString("#0.00")} CNY\r\n{str}\r\n经济舱均价为:{JJCAveragePrice.ToString("#0.00")}CNY/人;公务舱均价为:{GWCAveragePrice.ToString("#0.00")}CNY/人;";
  843. #endregion
  844. #region 签证费用
  845. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  846. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  847. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  848. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime,
  849. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  850. From Grp_VisaInfo vi
  851. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  852. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  853. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  854. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  855. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  856. Where vi.IsDel = 0 {1} And vi.DIId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  857. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  858. decimal VisaCNYTotalPirce = 0.00M;
  859. foreach (var item in groupVisaFeeViews)
  860. {
  861. string itemClientName = "";
  862. string visaClients = item.VisaClient;
  863. if (!string.IsNullOrEmpty(visaClients))
  864. {
  865. string[] clientIds = new string[] { };
  866. if (visaClients.Contains(','))
  867. {
  868. clientIds = visaClients.Split(',');
  869. }
  870. else
  871. {
  872. clientIds = new string[] { visaClients };
  873. }
  874. if (clientIds.Length > 0)
  875. {
  876. List<int> clientIds1 = new List<int>() { };
  877. foreach (var clientIdStr in clientIds)
  878. {
  879. if (clientIdStr.IsNumeric())
  880. {
  881. clientIds1.Add(int.Parse(clientIdStr));
  882. }
  883. }
  884. if (clientIds1.Count > 0)
  885. {
  886. var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
  887. foreach (var client in clients)
  888. {
  889. itemClientName += $"{client.LastName + client.FirstName},";
  890. }
  891. }
  892. else
  893. {
  894. itemClientName = visaClients;
  895. }
  896. }
  897. }
  898. if (itemClientName.Length > 0)
  899. {
  900. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  901. }
  902. item.VisaClient = itemClientName;
  903. VisaCNYTotalPirce += item.CNYPrice;
  904. if (!string.IsNullOrEmpty(item.AuditGMDate))
  905. {
  906. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  907. }
  908. }
  909. _geView.GroupVisaFeeViews = groupVisaFeeViews;
  910. _geView.GroupVisaFeeStr = string.Format(@"人民币总费用:{0} CNY", VisaCNYTotalPirce.ConvertToDecimal1().ToString("#.00"));
  911. #endregion
  912. #region 邀请/公务活动 CTable = 81
  913. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  914. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  915. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  916. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  917. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,
  918. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice2,ccp.Payee,ccp.AuditGMDate,
  919. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  920. From Grp_InvitationOfficialActivities ioa
  921. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  922. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  923. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  924. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  925. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  926. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  927. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  928. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  929. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  930. Where ioa.IsDel = 0 {1} And ioa.Diid = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  931. groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
  932. #region 邀请/公务活动 - 模拟数据
  933. //if (groupInvitationalFeeViews.Count < 1)
  934. //{
  935. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  936. // {
  937. // IOAId = 0,
  938. // IOADiId = 2334,
  939. // InviterArea = "模拟数据-邀请方地区",
  940. // Inviter = "模拟数据-邀请方",
  941. // InviteTime = "2023-10-10",
  942. // InviteCost = 100.00M,
  943. // InviteCurrency = "EUR",
  944. // SendCost = 100.00M,
  945. // SendCurrency = "EUR",
  946. // EventsCost = 10000.00M,
  947. // EventsCurrency = "EUR",
  948. // TranslateCost = 300.00M,
  949. // TranslateCurrency = "EUR",
  950. // PayMoney = 10500.00M,
  951. // PaymentCurrency = "EUR",
  952. // CNYPrice = 76765.50M,
  953. // Payee = "模拟数据-收款方",
  954. // AuditGMDate = "2023-12-05",
  955. // OrbitalPrivateTransfer = 1,
  956. // PayWay = "刷卡",
  957. // IsPay = 1,
  958. // Applicant = "刘华举"
  959. // });
  960. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  961. // {
  962. // IOAId = 0,
  963. // IOADiId = 2334,
  964. // InviterArea = "模拟数据-邀请方地区",
  965. // Inviter = "模拟数据-邀请方",
  966. // InviteTime = "2023-10-10",
  967. // InviteCost = 100.00M,
  968. // InviteCurrency = "EUR",
  969. // SendCost = 100.00M,
  970. // SendCurrency = "EUR",
  971. // EventsCost = 10000.00M,
  972. // EventsCurrency = "EUR",
  973. // TranslateCost = 300.00M,
  974. // TranslateCurrency = "EUR",
  975. // PayMoney = 10500.00M,
  976. // PaymentCurrency = "EUR",
  977. // CNYPrice = 76765.50M,
  978. // Payee = "模拟数据-收款方",
  979. // AuditGMDate = "2023-12-05",
  980. // OrbitalPrivateTransfer = 1,
  981. // PayWay = "刷卡",
  982. // IsPay = 1,
  983. // Applicant = "刘华举"
  984. // });
  985. //}
  986. #endregion
  987. decimal InvitationalCNYTotalPrice = 0.00M;
  988. foreach (var item in groupInvitationalFeeViews)
  989. {
  990. InvitationalCNYTotalPrice += item.CNYPrice2;
  991. if (!string.IsNullOrEmpty(item.AuditGMDate))
  992. {
  993. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  994. }
  995. string currencyRateStr = "";
  996. List<string> currencys = new List<string>();
  997. if (!string.IsNullOrEmpty(item.InviteCurrency)) currencys.Add(item.InviteCurrency);
  998. if (!string.IsNullOrEmpty(item.SendCurrency)) currencys.Add(item.SendCurrency);
  999. if (!string.IsNullOrEmpty(item.EventsCurrency)) currencys.Add(item.EventsCurrency);
  1000. if (!string.IsNullOrEmpty(item.TranslateCurrency)) currencys.Add(item.TranslateCurrency);
  1001. if (!string.IsNullOrEmpty(item.PaymentCurrency)) currencys.Add(item.PaymentCurrency);
  1002. currencyRateStr = await GeneralMethod.PostGroupRateByCTableAndCurrency(teamRateData, 81, currencys);
  1003. item.CurrencyRateStr = currencyRateStr;
  1004. }
  1005. _geView.GroupInvitationalFeeViews = groupInvitationalFeeViews;
  1006. _geView.GroupInvitationalFeeStr = string.Format(@"人民币总费用:{0} CNY", InvitationalCNYTotalPrice.ToString("#.00"));
  1007. #endregion
  1008. #region 保险费用
  1009. List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
  1010. string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.PayMoney * ccp.DayRate As CNYPrice,
  1011. sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  1012. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
  1013. From Grp_Customers ic
  1014. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  1015. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1016. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1017. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1018. Where ic.IsDel = 0 {1} And ic.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1019. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  1020. decimal InsuranceCNYTotalPrice = 0.00M;
  1021. foreach (var item in groupInsuranceFeeViews)
  1022. {
  1023. InsuranceCNYTotalPrice += item.CNYPrice;
  1024. string itemClientName = "";
  1025. string insClients = item.ClientName;
  1026. if (!string.IsNullOrEmpty(insClients))
  1027. {
  1028. //System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  1029. //System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  1030. //if (m_EnName.Success || m_ZHName.Success)
  1031. //{
  1032. // itemClientName = insClients;
  1033. // continue;
  1034. //}
  1035. string[] clientIds = new string[] { };
  1036. if (insClients.Contains(','))
  1037. {
  1038. clientIds = insClients.Split(',');
  1039. }
  1040. else
  1041. {
  1042. clientIds = new string[] { insClients };
  1043. }
  1044. if (clientIds.Length > 0)
  1045. {
  1046. List<int> output = new List<int>();
  1047. foreach (var clientId in clientIds)
  1048. {
  1049. if (clientId.IsNumeric())
  1050. {
  1051. output.Add(int.Parse(clientId));
  1052. }
  1053. }
  1054. if (output.Count > 0)
  1055. {
  1056. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  1057. foreach (var client in clients)
  1058. {
  1059. itemClientName += $"{client.LastName + client.FirstName},";
  1060. }
  1061. if (itemClientName.Length > 0)
  1062. {
  1063. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  1064. }
  1065. }
  1066. else
  1067. {
  1068. itemClientName = insClients;
  1069. }
  1070. }
  1071. }
  1072. item.ClientName = itemClientName;
  1073. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1074. {
  1075. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1076. }
  1077. }
  1078. _geView.GroupInsuranceFeeViews = groupInsuranceFeeViews;
  1079. _geView.GroupInsuranceFeeStr = string.Format(@"人民币总费用:{0} CNY", InsuranceCNYTotalPrice.ToString("#0.00"));
  1080. #endregion
  1081. #region 其他款项费用 98
  1082. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  1083. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1084. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  1085. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  1086. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  1087. From Grp_DecreasePayments dp
  1088. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  1089. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1090. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1091. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1092. Where dp.IsDel = 0 And ccp.Ctable = 98 {1} And dp.Diid = {0}
  1093. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1094. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  1095. #region 保险费用 - 模拟数据
  1096. //if (groupDecreaseFeeViews.Count < 1)
  1097. //{
  1098. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  1099. // {
  1100. // DPId = 0,
  1101. // DPDiId = 2334,
  1102. // PriceName = "模拟数据-费用名称",
  1103. // PayMoney = 1000.00M,
  1104. // PayMoneyCurrency = "CNY",
  1105. // DayRate = 1.0000M,
  1106. // CNYPrice = 1.0000M,
  1107. // AuditGMDate = "2023-12-10 12:13:00",
  1108. // Payee = "模拟数据-付款方",
  1109. // OrbitalPrivateTransfer = 1,
  1110. // PayWay = "现金",
  1111. // IsPay = 1,
  1112. // Applicant = "刘华举"
  1113. // });
  1114. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  1115. // {
  1116. // DPId = 0,
  1117. // DPDiId = 2334,
  1118. // PriceName = "模拟数据-费用名称",
  1119. // PayMoney = 1000.00M,
  1120. // PayMoneyCurrency = "CNY",
  1121. // DayRate = 1.0000M,
  1122. // CNYPrice = 1.0000M,
  1123. // AuditGMDate = "2023-12-10 12:13:00",
  1124. // Payee = "模拟数据-付款方",
  1125. // OrbitalPrivateTransfer = 1,
  1126. // PayWay = "现金",
  1127. // IsPay = 1,
  1128. // Applicant = "刘华举"
  1129. // });
  1130. //}
  1131. #endregion
  1132. decimal DecreaseCNYTotalPrice = 0.00M;
  1133. foreach (var item in groupDecreaseFeeViews)
  1134. {
  1135. item.CNYPrice = Convert.ToDecimal(item.CNYPrice.ToString("#0.00"));
  1136. DecreaseCNYTotalPrice += item.CNYPrice;
  1137. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1138. {
  1139. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1140. }
  1141. }
  1142. _geView.GroupDecreaseFeeViews = groupDecreaseFeeViews;
  1143. _geView.GroupDecreaseFeeStr = string.Format(@"人民币总费用:{0} CNY", DecreaseCNYTotalPrice.ToString("#0.00"));
  1144. #endregion
  1145. _view.GroupExpenditure = _geView;
  1146. #endregion
  1147. /*
  1148. * 团组报表计算方式
  1149. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  1150. * 应收金额 = 应收表.Sum()
  1151. * 已收金额 = 已收表.Sum()
  1152. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  1153. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  1154. *
  1155. */
  1156. decimal _totalExpenditure = 0.00M; //总支出
  1157. decimal _amountReceivable = 0.00M; //应收金额
  1158. decimal _amountReceived = 0.00M; //已收金额
  1159. decimal _receivableProfit = 0.00M; //应收利润
  1160. decimal _receivedProfit = 0.00M; //已收利润
  1161. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  1162. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount;
  1163. _amountReceivable = frTotalAmount;
  1164. _amountReceived = prTotalAmount;
  1165. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  1166. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  1167. _view.FeeTotalStr = string.Format(@$"<span>
  1168. <span>当前总支出:{_totalExpenditure.ToString("#0.00")} CNY</span>
  1169. <span style='padding-left:10px;color: Green;'>应收金额:{_amountReceivable.ToString("#0.00")} CNY</span>
  1170. <span style='padding-left:10px;color: Green;'>已收金额:{_amountReceived.ToString("#0.00")} CNY</span>
  1171. <span style='padding-left:10px;color: Green;'>应收利润(应收-支出):{_receivableProfit.ToString("#0.00")} CNY</span>
  1172. <span style='padding-left:10px;color: Green;'>已收利润(已收-支出):{_receivedProfit.ToString("#0.00")} CNY</span>
  1173. </span>");
  1174. return Ok(JsonView(true, "查询成功!", _view));
  1175. }
  1176. else
  1177. {
  1178. return Ok(JsonView(false, "查询成功"));
  1179. }
  1180. }
  1181. /// <summary>
  1182. /// 团组报表
  1183. /// Excel 下载
  1184. /// </summary>
  1185. /// <param name="_dto">团组列表请求dto</param>
  1186. /// <returns></returns>
  1187. [HttpPost("PostGroupStatementExportExcel")]
  1188. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1189. public async Task<IActionResult> PostGroupStatementExportExcel(GroupStatementDetailsDto _dto)
  1190. {
  1191. //pageId 38
  1192. int currUserId = _dto.UserId, pageId = _dto.PageId, diId = _dto.DiId;
  1193. bool isAudit = _dto.isAudit;
  1194. #region 参数验证
  1195. if (currUserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1196. if (pageId < 1) return Ok(JsonView(false, "页面Id为空"));
  1197. if (diId < 1) return Ok(JsonView(false, "数据Id为空"));
  1198. #region 页面操作权限验证
  1199. var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(currUserId, pageId);
  1200. if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权!"));
  1201. #endregion
  1202. #endregion
  1203. var groupInfo = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => x.IsDel == 0 && x.Id == diId).First();
  1204. if (groupInfo == null) return Ok(JsonView(false, "暂无该条团组信息!"));
  1205. var userInfo = _sqlSugar.Queryable<Sys_Users>().Where(x => x.IsDel == 0 && x.Id == currUserId).First();
  1206. string groupNo = groupInfo.TourCode,
  1207. groupName = groupInfo.TeamName.Replace("|", "、"),
  1208. lister = userInfo?.CnName ?? "-";
  1209. var _clientDatas = _sqlSugar.Queryable<Crm_DeleClient>()
  1210. .Where(it => it.IsDel == 0)
  1211. .Select(x => new Crm_DeleClient { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, Sex = x.Sex })
  1212. .ToList();
  1213. //获取模板
  1214. string tempPath = (AppSettingsHelper.Get("ExcelBasePath") + "Template/团组费用统计模板.xls");
  1215. var designer = new WorkbookDesigner();
  1216. designer.Workbook = new Workbook(tempPath);
  1217. // 获取工作簿中的工作表集合
  1218. var worksheets = designer.Workbook.Worksheets;
  1219. #region 获取sheet,定义datatable,局部变量
  1220. //酒店费用相关
  1221. var hotelFeeSheet = worksheets["酒店费用"];
  1222. var hotelFeeDt = new DataTable($"HotelFeeView");
  1223. decimal hotelCNYTotalCost = 0.00M;
  1224. //地接费用相关
  1225. var OPFeeSheet = worksheets["地接费用"];
  1226. var OPFeeDt = new DataTable($"OPFeeView");
  1227. var OPFeeLabel = string.Empty;
  1228. decimal OPCNYTotalCost = 0.00M;
  1229. //签证费用相关
  1230. var visaFeeSheet = worksheets["签证费用"];
  1231. var visaFeeDt = new DataTable($"VisaFeeView");
  1232. decimal visaCNYTotalCost = 0.00M;
  1233. //邀请费用相关
  1234. var OAFeeSheet = worksheets["邀请费用"];
  1235. var OAFeeDt = new DataTable($"OAFeeView");
  1236. decimal OACNYTotalCost = 0.00M;
  1237. //机票费用相关
  1238. var airTicketFeeSheet = worksheets["机票费用"];
  1239. var airTicketFeeDt = new DataTable($"AirTicketFeeView");
  1240. decimal airTicketCNYTotalCost = 0.00M;
  1241. //保险费用相关
  1242. var insureFeeSheet = worksheets["保险费用"];
  1243. var insureFeeDt = new DataTable($"InsureFeeView");
  1244. decimal insureCNYTotalCost = 0.00M;
  1245. //其他费用相关
  1246. var otherFeeSheet = worksheets["其他费用"];
  1247. var otherFeeDt = new DataTable($"OtherFeeView");
  1248. decimal otherCNYTotalCost = 0.00M;
  1249. //收款退还相关
  1250. var SKTHFeeSheet = worksheets["收款退还"];
  1251. var SKTHFeeDt = new DataTable($"SKTHFeeView");
  1252. decimal SKTHCNYTotalCost = 0.00M;
  1253. var totalAmount = 0.00M; //支出成本合计
  1254. var accountsAmount = 0.00M; //应收金额合计
  1255. var receivedAmount = 0.00M; //已收金额合计
  1256. var accountsProfit = 0.00M; //应收利润合计
  1257. var receiveProfit = 0.00M; //已收利润合计
  1258. var profitMargin = 0.00M; //利润差合计
  1259. //应收合计相关
  1260. var receivableFeeSheet = worksheets["团组收入(未收)"];
  1261. var receivableFeeDt = new DataTable($"ReceivableFeeView");
  1262. //已收合计相关
  1263. var receivedFeeSheet = worksheets["团组收入(已收)"];
  1264. var receivedFeeDt = new DataTable($"ReceivedFeeView");
  1265. //团组收入支出利润
  1266. var groupIEProfitDt = new DataTable($"IEProfitFeeView");
  1267. #endregion
  1268. #region 酒店费用
  1269. if (hotelFeeSheet != null)
  1270. {
  1271. string hotelFeeSql = string.Format(@"
  1272. SELECT
  1273. hr.Id AS HrId,
  1274. hr.DiId AS HrDiId,
  1275. hr.City,
  1276. hr.HotelName,
  1277. hr.CheckInDate,
  1278. hr.CheckOutDate,
  1279. hr.CardPrice AS RoomPrice,
  1280. sd1.Name AS PaymentCurrency,
  1281. hr.SingleRoomPrice,
  1282. hr.SingleRoomCount,
  1283. hr.DoubleRoomPrice,
  1284. hr.DoubleRoomCount,
  1285. hr.SuiteRoomPrice,
  1286. hr.SuiteRoomCount,
  1287. hr.OtherRoomPrice,
  1288. hr.OtherRoomCount,
  1289. hr.BreakfastPrice,
  1290. sd4.Name AS BreakfastCurrency,
  1291. hr.Isoppay,
  1292. hr.GovernmentRent,
  1293. sd5.Name AS GovernmentRentCurrency,
  1294. hr.CityTax,
  1295. sd6.Name AS CityTaxCurrency,
  1296. ccp.PayMoney,
  1297. (
  1298. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  1299. ) AS CNYPrice,
  1300. ccp.PayPercentage,
  1301. ccp.DayRate,
  1302. ccp.Payee,
  1303. ccp.OrbitalPrivateTransfer,
  1304. sd2.Name AS PayWay,
  1305. sd3.Name AS CardType,
  1306. ccp.IsPay,
  1307. u.CnName AS Applicant,
  1308. hr.Remark
  1309. FROM
  1310. Grp_HotelReservations hr
  1311. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  1312. LEFT JOIN Sys_SetData sd1 ON ccp.PaymentCurrency = sd1.Id
  1313. LEFT JOIN Sys_SetData sd2 ON ccp.PayDId = sd2.Id
  1314. LEFT JOIN Sys_SetData sd3 ON ccp.CTDId = sd3.Id
  1315. LEFT JOIN Sys_Users u ON ccp.CreateUserId = u.Id
  1316. LEFT JOIN Sys_SetData sd4 ON hr.BreakfastCurrency = sd4.Id
  1317. LEFT JOIN Sys_SetData sd5 ON hr.GovernmentRentCurrency = sd5.Id
  1318. LEFT JOIN Sys_SetData sd6 ON hr.CityTaxCurrency = sd6.Id
  1319. WHERE
  1320. hr.IsDel = 0
  1321. AND ccp.IsDel = 0
  1322. AND ccp.CTable = 76 {1}
  1323. AND ccp.PayMoney <> 0
  1324. AND hr.DiId = {0}
  1325. ORDER BY
  1326. CheckInDate Asc", _dto.DiId, _dto.isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  1327. var groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  1328. if (groupHotelFeeViews.Any())
  1329. {
  1330. var _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  1331. var hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
  1332. var groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
  1333. var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
  1334. foreach (var item in groupHotelFeeViews)
  1335. {
  1336. if (groupHotelContentFeeViews.Count > 0)
  1337. {
  1338. string paymentStr = string.Empty;
  1339. var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
  1340. item.RoomPrice = roomData?.Price ?? 0.00M;
  1341. if (item.RoomPrice != 0)
  1342. {
  1343. if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
  1344. item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
  1345. string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1346. string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
  1347. item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
  1348. 收款方:{roomData?.Payee}<br/>
  1349. 费用标识:{feeMark1} <br/>
  1350. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  1351. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
  1352. 是否由地接支付:{isFeeMark1} <br/>";
  1353. }
  1354. var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
  1355. item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
  1356. if (item.BreakfastPrice != 0)
  1357. {
  1358. if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
  1359. item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
  1360. string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1361. string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
  1362. item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
  1363. 收款方:{breakfastData?.Payee}<br/>
  1364. 费用标识:{feeMark2} <br/>
  1365. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  1366. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
  1367. 是否由地接支付:{isFeeMark2} <br/>";
  1368. }
  1369. var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
  1370. item.GovernmentRent = landTaxData?.Price ?? 0.00M;
  1371. if (item.GovernmentRent != 0)
  1372. {
  1373. if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
  1374. item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
  1375. string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1376. string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
  1377. item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
  1378. 收款方:{landTaxData?.Payee}<br/>
  1379. 费用标识:{feeMark3} <br/>
  1380. 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
  1381. 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
  1382. 是否由地接支付:{isFeeMark3} <br/>";
  1383. }
  1384. var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
  1385. item.CityTax = cityTaxData?.Price ?? 0.00M;
  1386. if (item.CityTax != 0)
  1387. {
  1388. if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
  1389. item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
  1390. string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1391. string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
  1392. item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
  1393. 收款方:{cityTaxData?.Payee}<br/>
  1394. 费用标识:{feeMark4} <br/>
  1395. 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
  1396. 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
  1397. 是否由地接支付:{isFeeMark4} <br/>";
  1398. }
  1399. if (!string.IsNullOrEmpty(paymentStr))
  1400. {
  1401. item.IsPay = 2;
  1402. item.PayTips = paymentStr;
  1403. }
  1404. //item.CNYPrice = roomData?.Price ?? 0.00M * roomData?.Rate ?? 0.00M +
  1405. // breakfastData?.Price ?? 0.00M * breakfastData?.Rate ?? 0.00M +
  1406. // landTaxData?.Price ?? 0.00M * landTaxData?.Rate ?? 0.00M +
  1407. // cityTaxData?.Price ?? 0.00M * cityTaxData?.Rate ?? 0.00M;
  1408. }
  1409. else
  1410. {
  1411. decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
  1412. (item.DoubleRoomCount * item.DoubleRoomPrice) +
  1413. (item.SuiteRoomCount * item.SuiteRoomPrice) +
  1414. (item.OtherRoomCount * item.OtherRoomPrice);
  1415. //item.RoomPrice = item.CardPrice;
  1416. item.RoomPriceCurrency = item.PaymentCurrency;
  1417. }
  1418. item.PayMoney = item.PayMoney.ConvertToDecimal1();
  1419. item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
  1420. }
  1421. }
  1422. hotelCNYTotalCost = groupHotelFeeViews.Sum(x => x.CNYPrice);
  1423. hotelFeeDt = CommonFun.ToDataTableArray(groupHotelFeeViews);
  1424. hotelFeeDt.TableName = $"HotelFeeView";
  1425. }
  1426. #endregion
  1427. #region 地接费用
  1428. if (OPFeeSheet != null)
  1429. {
  1430. string CTGGRFeeSql = string.Empty;
  1431. if (groupInfo.VisitDate > Convert.ToDateTime("2024-04-17"))
  1432. {
  1433. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
  1434. sd2.name As PaymentCurrency,ccp.PayPercentage,
  1435. (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
  1436. (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
  1437. ccp.DayRate,(ctggrc.Price * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  1438. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  1439. From Grp_CarTouristGuideGroundReservations ctggr
  1440. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
  1441. cggrc.DatePrice,cggrc.PriceContent
  1442. From Grp_CarTouristGuideGroundReservationsContent cggrc
  1443. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  1444. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  1445. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  1446. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  1447. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  1448. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  1449. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  1450. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1451. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  1452. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  1453. }
  1454. else
  1455. {
  1456. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,
  1457. ccp.PayMoney,sd2.name As PaymentCurrency,ccp.PayPercentage,
  1458. (ccp.PayMoney * (ccp.PayPercentage / 100)) As AmountPaid,
  1459. (ccp.PayMoney -ccp.PayMoney * (ccp.PayPercentage / 100)) As BalancePayment,
  1460. ccp.DayRate,(ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,
  1461. ccp.Payee,ccp.AuditGMDate,
  1462. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  1463. From Grp_CarTouristGuideGroundReservations ctggr
  1464. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  1465. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  1466. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  1467. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1468. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  1469. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  1470. }
  1471. var groupOPFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  1472. string CTGGRFeeStr = "";
  1473. var OPToDataTableViews = groupOPFeeViews;
  1474. decimal CTGGRCNYTotalPrice = 0.00M;
  1475. //按1 地区,2 币种,3 汇率 分组计算
  1476. var groupCTGGRFeeDatas = groupOPFeeViews.GroupBy(it => it.Area);
  1477. foreach (var ctggfr in groupCTGGRFeeDatas)
  1478. {
  1479. var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
  1480. if (ctggfr_curr.Count() > 0)
  1481. {
  1482. foreach (var curr in ctggfr_curr)
  1483. {
  1484. var ctggfr_rate = curr.GroupBy(it => it.DayRate);
  1485. if (ctggfr_rate.Count() > 0)
  1486. {
  1487. foreach (var rate in ctggfr_rate)
  1488. {
  1489. CTGGRFeeStr += string.Format($"{ctggfr.Key} 总费用:{rate.Sum(it => it.AmountPaid).ToString("#0.00")} {rate.FirstOrDefault()?.PaymentCurrency}(人民币:{rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:{rate.FirstOrDefault()?.DayRate.ToString("#0.0000")})\n");
  1490. CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1491. }
  1492. }
  1493. else
  1494. {
  1495. CTGGRFeeStr += string.Format($"{ctggfr.Key} 总费用:{curr.Sum(it => it.AmountPaid).ToString("#0.00")} {curr.FirstOrDefault()?.PaymentCurrency}(人民币:{curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:{curr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\n");
  1496. CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1497. }
  1498. }
  1499. }
  1500. else
  1501. {
  1502. CTGGRFeeStr += string.Format($"{ctggfr.Key} 总费用:{ctggfr.Sum(it => it.AmountPaid).ToString("#0.00")} {ctggfr.FirstOrDefault()?.PaymentCurrency}(人民币:{ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:{ctggfr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\n");
  1503. CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1504. }
  1505. }
  1506. foreach (var item in groupOPFeeViews)
  1507. {
  1508. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1509. {
  1510. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1511. }
  1512. if (item.DatePrice != null)
  1513. {
  1514. item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
  1515. }
  1516. }
  1517. OPCNYTotalCost = CTGGRCNYTotalPrice;
  1518. OPFeeDt = CommonFun.ToDataTableArray(OPToDataTableViews);
  1519. OPFeeLabel = CTGGRFeeStr;
  1520. OPFeeDt.TableName = $"OPFeeView";
  1521. }
  1522. #endregion
  1523. #region 签证费用
  1524. if (visaFeeSheet != null)
  1525. {
  1526. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1527. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,sd2.Name As PaymentModes,sd3.Name As CardTypeName,u.CnName As Applicant,vi.CreateTime,
  1528. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
  1529. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1530. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,vi.Remark
  1531. From Grp_VisaInfo vi
  1532. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  1533. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1534. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1535. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  1536. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1537. Where vi.IsDel = 0 {1} And vi.DIId = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1538. var groupVisaFeeViews = _sqlSugar.SqlQueryable<GroupVisaFeeExcelView>(groupVisaFeeSql).ToList();
  1539. foreach (var item in groupVisaFeeViews)
  1540. {
  1541. string names = string.Empty;
  1542. string visaClients = item.VisaClient;
  1543. if (!string.IsNullOrEmpty(visaClients))
  1544. {
  1545. var clientIds = new string[] { };
  1546. if (visaClients.Contains(',')) clientIds = visaClients.Split(',');
  1547. else clientIds = new string[] { visaClients };
  1548. if (clientIds.Length > 0)
  1549. {
  1550. var clientIds1 = new List<int>() { };
  1551. foreach (var clientIdStr in clientIds)
  1552. {
  1553. var isInt = int.TryParse(clientIdStr, out int id);
  1554. if (isInt) clientIds1.Add(id);
  1555. }
  1556. if (clientIds1.Count > 0)
  1557. {
  1558. var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
  1559. foreach (var client in clients)
  1560. {
  1561. EncryptionProcessor.DecryptProperties(client);
  1562. names += $"{client.LastName + client.FirstName},";
  1563. }
  1564. }
  1565. else names = visaClients;
  1566. }
  1567. if (names.Length > 0) names = names.Substring(0, names.Length - 1);
  1568. item.VisaClient = names;
  1569. }
  1570. }
  1571. visaCNYTotalCost = groupVisaFeeViews.Sum(x => x.CNYPrice);
  1572. visaFeeDt = CommonFun.ToDataTableArray(groupVisaFeeViews);
  1573. visaFeeDt.TableName = $"VisaFeeView";
  1574. }
  1575. #endregion
  1576. #region 邀请费用
  1577. if (OAFeeSheet != null)
  1578. {
  1579. string feeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,CONVERT(DATE, ioa.InviteTime) AS InviteTime,
  1580. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  1581. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  1582. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,ccp.ConsumptionDate,
  1583. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1584. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1585. ccp.Payee,ioa.Remark,ccp.AuditGMDate,u.CnName As Applicant,ioa.CreateTime
  1586. From Grp_InvitationOfficialActivities ioa
  1587. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  1588. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1589. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1590. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  1591. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  1592. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  1593. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  1594. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  1595. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1596. Where ioa.IsDel = 0 {1} And ioa.Diid = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1597. var feeViews = _sqlSugar.SqlQueryable<GroupOAFeeExcelView>(feeSql).ToList();
  1598. OACNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1599. OAFeeDt = CommonFun.ToDataTableArray(feeViews);
  1600. OAFeeDt.TableName = $"OAFeeView";
  1601. }
  1602. #endregion
  1603. #region 机票费用
  1604. if (airTicketFeeSheet != null)
  1605. {
  1606. string feeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,
  1607. sd4.Name As AirTypeName,atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,
  1608. atr.PriceDescription,ccp.PayMoney,ccp.DayRate,sd1.Name As PayMoneyCurrency,
  1609. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
  1610. ccp.Payee,Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1611. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1612. sd3.Name As CardType,ccp.AuditGMDate,u.CnName As Applicant,atr.CreateTime,atr.Remark
  1613. From Grp_AirTicketReservations atr
  1614. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  1615. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1616. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1617. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  1618. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  1619. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1620. Where atr.IsDel = 0 {1} And atr.DiId = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1621. var feeViews = _sqlSugar.SqlQueryable<GroupAirTicketExcelView>(feeSql).ToList();
  1622. airTicketCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1623. airTicketFeeDt = CommonFun.ToDataTableArray(feeViews);
  1624. airTicketFeeDt.TableName = $"AirTicketFeeView";
  1625. }
  1626. #endregion
  1627. #region 保险费用
  1628. if (insureFeeSheet != null)
  1629. {
  1630. string feeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,
  1631. sd1.Name As PayMoneyCurrency,ccp.DayRate,ccp.PayMoney * ccp.DayRate As CNYPrice,ccp.ConsumptionDate,
  1632. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1633. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1634. ccp.Payee,ccp.AuditGMDate,u.CnName As Applicant,ic.CreateTime,ic.Remark
  1635. From Grp_Customers ic
  1636. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  1637. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1638. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1639. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1640. Where ic.IsDel = 0 {1} And ic.DiId = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1641. var feeViews = _sqlSugar.SqlQueryable<GroupInsureExcelView>(feeSql).ToList();
  1642. foreach (var item in feeViews)
  1643. {
  1644. string itemClientName = "";
  1645. string insClients = item.ClientName;
  1646. if (!string.IsNullOrEmpty(insClients))
  1647. {
  1648. string[] clientIds = new string[] { };
  1649. if (insClients.Contains(',')) clientIds = insClients.Split(',');
  1650. else clientIds = new string[] { insClients };
  1651. if (clientIds.Length > 0)
  1652. {
  1653. List<int> output = new List<int>();
  1654. foreach (var clientId in clientIds)
  1655. if (int.TryParse(clientId, out int id))
  1656. output.Add(id);
  1657. if (output.Count > 0)
  1658. {
  1659. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  1660. foreach (var client in clients)
  1661. {
  1662. EncryptionProcessor.DecryptProperties(client);
  1663. itemClientName += $"{client.LastName + client.FirstName},";
  1664. }
  1665. if (itemClientName.Length > 0)
  1666. {
  1667. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  1668. }
  1669. }
  1670. else itemClientName = insClients;
  1671. }
  1672. }
  1673. item.ClientName = itemClientName;
  1674. }
  1675. insureCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1676. insureFeeDt = CommonFun.ToDataTableArray(feeViews);
  1677. insureFeeDt.TableName = $"InsureFeeView";
  1678. }
  1679. #endregion
  1680. #region 其他费用
  1681. if (insureFeeSheet != null)
  1682. {
  1683. string feeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1684. ccp.DayRate,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
  1685. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1686. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1687. ccp.Payee,ccp.AuditGMDate,u.CnName As Applicant,dp.CreateTime,dp.Remark
  1688. From Grp_DecreasePayments dp
  1689. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  1690. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1691. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1692. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1693. Where dp.IsDel = 0 And ccp.Ctable = 98 {1} And dp.Diid = {0}
  1694. Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1695. var feeViews = _sqlSugar.SqlQueryable<GroupOtherFeeExcelView>(feeSql).ToList();
  1696. otherCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1697. otherFeeDt = CommonFun.ToDataTableArray(feeViews);
  1698. otherFeeDt.TableName = $"OtherFeeView";
  1699. }
  1700. #endregion
  1701. #region 收款退还
  1702. if (SKTHFeeSheet != null)
  1703. {
  1704. //删除了 And prom.PriceType = 1
  1705. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  1706. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  1707. prom.PayType As PrPayType,prom.PriceType As PrPriceType,
  1708. ccp.RMBPrice * ccp.DayRate As RMBPrice,ccp.*,prom.CreateTime As PrCreateTime,prom.Remark AS SKTHRemark
  1709. From Fin_PaymentRefundAndOtherMoney prom
  1710. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  1711. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1712. Where prom.IsDel = 0
  1713. And prom.PayType = 1
  1714. And ccp.CTable = 285
  1715. {1}
  1716. And prom.DiId = {0} Order By PrCreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1717. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  1718. if (_promDatas.Any())
  1719. {
  1720. var _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  1721. var _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  1722. foreach (var ropItem in _promDatas)
  1723. {
  1724. string thisCueencyCode = "Unknown";
  1725. string thisCueencyName = "Unknown";
  1726. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  1727. if (currency != null)
  1728. {
  1729. thisCueencyCode = currency.Name;
  1730. thisCueencyName = currency.Remark;
  1731. }
  1732. string orbitalPrivateTransferStr = "Unknown";
  1733. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  1734. if (orbitalPrivateTransfer != null)
  1735. {
  1736. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  1737. }
  1738. string payStr = "Unknown";
  1739. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  1740. if (pay != null)
  1741. {
  1742. payStr = pay.Name;
  1743. }
  1744. var gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  1745. {
  1746. Id = ropItem.Id,
  1747. DiId = ropItem.DIId,
  1748. PriceName = ropItem.PrPriceName,
  1749. PayCurrencyCode = thisCueencyCode,
  1750. PayCurrencyName = thisCueencyName,
  1751. Price = ropItem.PrPrice,
  1752. CNYPrice = ropItem.PayMoney * ropItem.DayRate,
  1753. ThisRate = ropItem.DayRate,
  1754. Payee = ropItem.Payee,
  1755. PayTime = ropItem.AuditGMDate,
  1756. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  1757. PayType = payStr,
  1758. IsPay = ropItem.IsPay,
  1759. Applicant = ropItem.Appliction,
  1760. Remark = ropItem.SKTHRemark
  1761. };
  1762. _promView.Add(gsd_PaymentRefund);
  1763. }
  1764. SKTHCNYTotalCost = _promView.Sum(x => x.CNYPrice);
  1765. SKTHFeeDt = CommonFun.ToDataTableArray(_promView);
  1766. SKTHFeeDt.TableName = $"SKTHFeeView";
  1767. }
  1768. }
  1769. #endregion
  1770. #region 应收金额(增加方式=实际报价时 费用必须审核才能进入团组报表)
  1771. decimal frTotalAmount = 0.00M;//应收总金额
  1772. string _frSql = string.Format(@" Select fr.Id,fr.AddingWay,fr.Status,u.CnName As Auditor,fr.AuditTime,fr.Diid,fr.PriceName,fr.Price,fr.Count,fr.Unit,fr.Currency,
  1773. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime,fr.Remark
  1774. From Fin_ForeignReceivables fr
  1775. Left Join Sys_SetData sd On fr.Currency = sd.Id
  1776. Left Join Sys_Users u On fr.Auditor = u.Id
  1777. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
  1778. var _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  1779. _frViews.ForEach(x =>
  1780. {
  1781. string namePrefix = string.Empty;
  1782. if (x.AddingWay == 0) namePrefix = $"账单模块-";
  1783. else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
  1784. else if (x.AddingWay == 2) namePrefix = $"实际报价-";
  1785. x.PriceName = $"{namePrefix}{x.PriceName}";
  1786. });
  1787. if (_frViews.Any())
  1788. {
  1789. accountsAmount = _frViews.Sum(it => it.ItemSumPrice);
  1790. receivableFeeDt = CommonFun.ToDataTableArray(_frViews);
  1791. receivableFeeDt.TableName = $"ReceivedFeeView";
  1792. }
  1793. #endregion
  1794. #region 已收金额
  1795. decimal prTotalAmount = 0.00M;//已收总金额
  1796. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  1797. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  1798. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  1799. From Fin_ProceedsReceived pr
  1800. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  1801. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  1802. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
  1803. var _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  1804. if (_prViews.Any())
  1805. {
  1806. receivedAmount = _prViews.Sum(it => it.Price);
  1807. receivedFeeDt = CommonFun.ToDataTableArray(_prViews);
  1808. receivedFeeDt.TableName = $"ReceivableFeeView";
  1809. }
  1810. #endregion
  1811. #region 团组收入支出利润
  1812. groupIEProfitDt.Columns.AddRange(new DataColumn[] {
  1813. new DataColumn(){ ColumnName = "ModuleName"},
  1814. new DataColumn(){ ColumnName = "FeeTotal",DataType = typeof(decimal)},
  1815. new DataColumn(){ ColumnName = "FeeCurrency"},
  1816. });
  1817. var groupIEProfitDt_rows = new[] {
  1818. new object[] { $"签证费用", visaCNYTotalCost, $"CNY" },
  1819. new object[] { $"酒店费用", hotelCNYTotalCost, $"CNY" },
  1820. new object[] { $"地接费用", OPCNYTotalCost, $"CNY" },
  1821. new object[] { $"商邀费用", OACNYTotalCost, $"CNY" },
  1822. new object[] { $"机票费用", airTicketCNYTotalCost, $"CNY" },
  1823. new object[] { $"保险费用", insureCNYTotalCost, $"CNY" },
  1824. new object[] { $"其他费用", otherCNYTotalCost, $"CNY" },
  1825. new object[] { $"收款退还费用", SKTHCNYTotalCost, $"CNY" },
  1826. };
  1827. // 批量添加
  1828. foreach (var rowData in groupIEProfitDt_rows)
  1829. {
  1830. groupIEProfitDt.Rows.Add(rowData);
  1831. }
  1832. #endregion
  1833. #region 统一填充数据源
  1834. designer.SetDataSource("GroupNo", groupNo);
  1835. designer.SetDataSource("GroupName", groupName);
  1836. designer.SetDataSource("Lister", lister);
  1837. //酒店
  1838. designer.SetDataSource(hotelFeeDt);
  1839. designer.SetDataSource("HotelCNYTotalCost", $"{hotelCNYTotalCost.ToString("#0.00")} CNY");
  1840. //地接
  1841. designer.SetDataSource(OPFeeDt);
  1842. designer.SetDataSource("OPFeeLabel", OPFeeLabel);
  1843. designer.SetDataSource("OPCNYTotalCost", $"{OPCNYTotalCost.ToString("#0.00")} CNY");
  1844. //签证
  1845. designer.SetDataSource(visaFeeDt);
  1846. designer.SetDataSource("VisaCNYTotalCost", $"{visaCNYTotalCost.ToString("#0.00")} CNY");
  1847. //商邀
  1848. designer.SetDataSource(OAFeeDt);
  1849. designer.SetDataSource("OACNYTotalCost", $"{OACNYTotalCost.ToString("#0.00")} CNY");
  1850. //机票
  1851. designer.SetDataSource(airTicketFeeDt);
  1852. designer.SetDataSource("AirTicketCNYTotalCost", $"{airTicketCNYTotalCost.ToString("#0.00")} CNY");
  1853. //保险
  1854. designer.SetDataSource(insureFeeDt);
  1855. designer.SetDataSource("InsureCNYTotalCost", $"{insureCNYTotalCost.ToString("#0.00")} CNY");
  1856. //其他费用
  1857. designer.SetDataSource(otherFeeDt);
  1858. designer.SetDataSource("OtherCNYTotalCost", $"{otherCNYTotalCost.ToString("#0.00")} CNY");
  1859. //收款退还
  1860. designer.SetDataSource(SKTHFeeDt);
  1861. designer.SetDataSource("SKTHCNYTotalCost", $"{SKTHCNYTotalCost.ToString("#0.00")}");
  1862. //已收金额
  1863. designer.SetDataSource(receivedFeeDt);
  1864. designer.SetDataSource("ReceivedAmount", $"{receivedAmount.ToString("#0.00")}");
  1865. //应收金额
  1866. designer.SetDataSource(receivableFeeDt);
  1867. designer.SetDataSource("AccountsAmount", $"{accountsAmount.ToString("#0.00")}");
  1868. //应收已收 -- 尾款
  1869. var balancePayment = accountsAmount - SKTHCNYTotalCost - receivedAmount;
  1870. designer.SetDataSource("BalancePayment", $"{balancePayment.ToString("#0.00")}");
  1871. //团组收入支出利润
  1872. designer.SetDataSource(groupIEProfitDt);
  1873. #region 各项费用计算
  1874. /*
  1875. * 团组报表计算方式
  1876. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  1877. * 应收金额 = 应收表.Sum() - 收款退还
  1878. * 已收金额 = 已收表.Sum() - 收款退还
  1879. * 应收利润(应收-支出) = 应收金额 - 当前总支出
  1880. * 已收利润(已收-支出) = 已收金额 - 当前总支出
  1881. * 利润差 = 应收利润 - 已收利润
  1882. */
  1883. totalAmount = visaCNYTotalCost + hotelCNYTotalCost + OPCNYTotalCost + OACNYTotalCost + airTicketCNYTotalCost + insureCNYTotalCost + otherCNYTotalCost;//合计金额
  1884. accountsProfit = accountsAmount - totalAmount - SKTHCNYTotalCost; //应收利润
  1885. receiveProfit = receivedAmount - totalAmount - SKTHCNYTotalCost; //已收利润
  1886. profitMargin = accountsProfit - receiveProfit; //利润差
  1887. designer.SetDataSource("TotalAmount", $"{totalAmount.ToString("#0.00")}");
  1888. designer.SetDataSource("AccountsProfit", $"{accountsProfit.ToString("#0.00")}");
  1889. designer.SetDataSource("ReceiveProfit", $"{receiveProfit.ToString("#0.00")}");
  1890. designer.SetDataSource("ProfitMargin", $"{profitMargin.ToString("#0.00")}");
  1891. #endregion
  1892. designer.Process();
  1893. #endregion
  1894. #region 单元格样式设置 未付款设置为红色
  1895. /*
  1896. * 设置单元格样式
  1897. */
  1898. //背景颜色
  1899. Style style = designer.Workbook.CreateStyle();
  1900. style.ForegroundColor = Color.FromArgb(254, 242, 203);
  1901. style.Pattern = BackgroundType.Solid;
  1902. //字体
  1903. style.Font.Name = "微软雅黑"; // 字体名称
  1904. style.Font.Size = 10; // 字体大小
  1905. style.Font.Color = System.Drawing.Color.Black; // 字体颜色
  1906. StatementExportExcelSetCell(designer, hotelFeeSheet, hotelFeeDt, style, "IsPayLable", 8, "A", "V"); //酒店
  1907. StatementExportExcelSetCell(designer, OPFeeSheet, OPFeeDt, style, "IsPayLabel", 6, "A", "M"); //OP
  1908. StatementExportExcelSetCell(designer, visaFeeSheet, visaFeeDt, style, "IsPay", 6, "A", "I"); //签证
  1909. StatementExportExcelSetCell(designer, OAFeeSheet, OAFeeDt, style, "IsPay", 6, "A", "R"); //商邀
  1910. StatementExportExcelSetCell(designer, airTicketFeeSheet, airTicketFeeDt, style, "IsPay", 6, "A", "M"); //机票
  1911. StatementExportExcelSetCell(designer, insureFeeSheet, insureFeeDt, style, "IsPay", 6, "A", "I"); //保险
  1912. StatementExportExcelSetCell(designer, otherFeeSheet, otherFeeDt, style, "IsPay", 6, "A", "J"); //其他
  1913. StatementExportExcelSetCell(designer, SKTHFeeSheet, SKTHFeeDt, style, "IsPayLable", 6, "A", "K"); //首款退还
  1914. #endregion
  1915. //文件名
  1916. string fileName = $"{groupName}[{groupNo}]_团组费用清单{DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
  1917. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + "GroupStatement/" + fileName);
  1918. string url = AppSettingsHelper.Get("ExcelBaseUrl") + "Office/Excel/GroupStatement/" + fileName;
  1919. return Ok(JsonView(true, "成功", url));
  1920. }
  1921. private void StatementExportExcelSetCell(WorkbookDesigner designer, Worksheet sheet, DataTable dt, Style style, string judgeLable, int startIndex, string startRange, string endRange)
  1922. {
  1923. if (designer == null) return;
  1924. if (sheet == null) return;
  1925. if (style == null) return;
  1926. if (dt == null) return;
  1927. if (string.IsNullOrEmpty(startRange)) return;
  1928. if (string.IsNullOrEmpty(endRange)) return;
  1929. for (int i = 0; i < dt.Rows.Count; i++)
  1930. {
  1931. var isPayStr = dt.Rows[i][$"{judgeLable}"].ToString();
  1932. if (string.IsNullOrEmpty(isPayStr)) continue;
  1933. if (isPayStr.Contains("未付款"))
  1934. {
  1935. var excelIndex = startIndex + i;
  1936. Aspose.Cells.Range range = sheet.Cells.CreateRange($"{startRange}{excelIndex}", $"{endRange}{excelIndex}");
  1937. range.ApplyStyle(style, new StyleFlag() { CellShading = true, Font = true });
  1938. }
  1939. }
  1940. }
  1941. #endregion
  1942. #region 报表/折线图统计
  1943. //企业利润-团组利润
  1944. //企业利润-会务利润
  1945. /// <summary>
  1946. /// 企业利润
  1947. /// Details
  1948. /// 待添加权限验证
  1949. /// </summary>
  1950. /// <param name="_dto">团组列表请求dto</param>
  1951. /// <returns></returns>
  1952. [HttpPost("PostCorporateProfit")]
  1953. //[JsonConverter(typeof(DecimalConverter), 2)]
  1954. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1955. public async Task<IActionResult> PostCorporateProfit(PostCorporateProfitDto _dto)
  1956. {
  1957. #region 参数验证
  1958. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1959. if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  1960. if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));
  1961. if (_dto.StatisticsType > 2 && _dto.StatisticsType < 1) return Ok(JsonView(false, "请输入有效的StatisticsType参数,1 月份 2 季度"));
  1962. if (_dto.BusinessType > 3 && _dto.BusinessType < 1) return Ok(JsonView(false, "请输入有效的BusinessType参数,1 所有 2 团组 3 会务"));
  1963. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1964. #region 页面操作权限验证
  1965. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  1966. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  1967. #endregion
  1968. string sqlWhere = string.Empty;
  1969. //起止时间
  1970. DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");
  1971. DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");
  1972. sqlWhere = string.Format(@$" Where Isdel = 0 ");
  1973. //业务类型
  1974. List<int> groupTypeId = new List<int>();
  1975. if (_dto.BusinessType == 2) //团组
  1976. {
  1977. groupTypeId.AddRange(new List<int>() {
  1978. 38, // 政府团
  1979. 39, // 企业团
  1980. 40, // 散客团
  1981. 1048 // 高校团
  1982. });
  1983. }
  1984. else if (_dto.BusinessType == 3) //会务
  1985. {
  1986. groupTypeId.AddRange(new List<int>() {
  1987. 102, // 未知
  1988. 248, // 非团组
  1989. 302, // 成都-会务活动
  1990. 691, // 四川-会务活动
  1991. 762, // 四川-赛事项目收入
  1992. 1047 // 成都-赛事项目收入
  1993. });
  1994. }
  1995. if (groupTypeId.Count > 0)
  1996. {
  1997. sqlWhere += string.Format(@$" And TeamDid In ({string.Join(',', groupTypeId)})");
  1998. }
  1999. string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");
  2000. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();
  2001. if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));
  2002. List<int> diIds = groupInfos.Select(it => it.Id).ToList();
  2003. List<CorporateProfit> corporateProfits = await CorporateProfit(diIds);
  2004. List<MonthInfo> months = new List<MonthInfo>();
  2005. if (_dto.StatisticsType == 1) //月份
  2006. {
  2007. months = GeneralMethod.GetMonthInfos(Convert.ToInt32(_dto.Year));
  2008. }
  2009. else if (_dto.StatisticsType == 1) //季度
  2010. {
  2011. months = GeneralMethod.GetQuarter(Convert.ToInt32(_dto.Year));
  2012. }
  2013. List<CorporateProfitMonthView> _view = new List<CorporateProfitMonthView>();
  2014. foreach (var item in months)
  2015. {
  2016. DateTime monthBeginDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.BeginDays} 00:00:00");
  2017. DateTime monthEndDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.EndDays} 23:59:59");
  2018. var corporateProfit = corporateProfits.Where(it => it.CreateDt >= monthBeginDt && it.CreateDt <= monthEndDt).ToList();
  2019. _view.Add(new CorporateProfitMonthView()
  2020. {
  2021. Month = item.Month,
  2022. Profit = corporateProfit.Sum(it => it.ReceivedProfit),
  2023. GroupInfos = corporateProfit.OrderBy(it => it.CreateDt).ToList()
  2024. });
  2025. }
  2026. return Ok(JsonView(true, "操作成功!", _view));
  2027. #endregion
  2028. }
  2029. /// <summary>
  2030. /// 计算团组利润
  2031. /// </summary>
  2032. /// <param name="diIds"></param>
  2033. /// <returns></returns>
  2034. private async Task<List<CorporateProfit>> CorporateProfit(List<int> diIds)
  2035. {
  2036. List<CorporateProfit> corporateProfits = new List<CorporateProfit>();
  2037. if (diIds.Count < 1)
  2038. {
  2039. return corporateProfits;
  2040. }
  2041. #region 计算团组利润
  2042. /*
  2043. * 团组报表计算方式
  2044. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  2045. * 应收金额 = 应收表.Sum()
  2046. * 已收金额 = 已收表.Sum()
  2047. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  2048. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  2049. *
  2050. */
  2051. string diIdStr = string.Join(",", diIds);
  2052. string sql = string.Format(@$"Select * From Grp_DelegationInfo Where Isdel = 0 And Id In ({diIdStr})");
  2053. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).ToListAsync();
  2054. #region 费用类型 币种,转账,客户信息
  2055. List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  2056. var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>().Where(it => it.IsDel == 0).ToListAsync();
  2057. #endregion
  2058. foreach (var _diId in diIds)
  2059. {
  2060. List<ExpenditureInfo> expenditureInfos = new List<ExpenditureInfo>();
  2061. #region 团组收入
  2062. /*
  2063. * 应收报表
  2064. */
  2065. decimal frTotalAmount = 0.00M;//应收总金额
  2066. string _frSql = string.Format(@"Select fr.Id,fr.Diid,fr.PriceName,fr.Price,fr.Count,fr.Unit,fr.Currency,
  2067. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  2068. From Fin_ForeignReceivables fr
  2069. Left Join Sys_SetData sd On fr.Currency = sd.Id
  2070. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _diId);
  2071. List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  2072. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  2073. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "应收项", Amount = frTotalAmount });
  2074. /*
  2075. * 已收报表
  2076. */
  2077. decimal prTotalAmount = 0.00M;//已收总金额
  2078. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  2079. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  2080. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  2081. From Fin_ProceedsReceived pr
  2082. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  2083. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  2084. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _diId);
  2085. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  2086. prTotalAmount = _prViews.Sum(it => it.Price);
  2087. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "已收项", Amount = prTotalAmount });
  2088. /*
  2089. * 超支费用
  2090. */
  2091. decimal exTotalAmount = 0.00M;
  2092. string _ecSql = string.Format(@"Select gec.Id As GECId,gec.DiId As GECDiId,gec.PriceName,ccp.PayMoney,sd1.Name As PaymentCurrency,
  2093. ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  2094. sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  2095. From OA2023DB.dbo.Fin_GroupExtraCost gec
  2096. Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  2097. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2098. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2099. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2100. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2101. Where ccp.IsDel = 0 And ccp.CTable = 1015 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ccp.DiId = {0} Order By CreateTime", _diId);
  2102. List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(_ecSql).ToListAsync();
  2103. exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  2104. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "超支费用", Amount = exTotalAmount });
  2105. /*
  2106. * 收款退还
  2107. */
  2108. decimal promTotalAmount = 0.00M;// 收款退还总金额
  2109. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  2110. //删除了 And prom.PriceType = 1
  2111. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  2112. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  2113. prom.PayType As PrPayType,prom.PriceType As PrPriceType,ccp.*,prom.CreateTime As PrCreateTime
  2114. From Fin_PaymentRefundAndOtherMoney prom
  2115. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  2116. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2117. Where prom.IsDel = 0 And prom.PayType = 1 And ccp.CTable = 285
  2118. And ccp.IsAuditGM = 1 And ccp.IsPay = 1
  2119. And prom.DiId = {0} Order By PrCreateTime", _diId);
  2120. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  2121. foreach (var ropItem in _promDatas)
  2122. {
  2123. string thisCueencyCode = "Unknown";
  2124. string thisCueencyName = "Unknown";
  2125. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  2126. if (currency != null)
  2127. {
  2128. thisCueencyCode = currency.Name;
  2129. thisCueencyName = currency.Remark;
  2130. }
  2131. string orbitalPrivateTransferStr = "Unknown";
  2132. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  2133. if (orbitalPrivateTransfer != null)
  2134. {
  2135. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  2136. }
  2137. string payStr = "Unknown";
  2138. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  2139. if (pay != null)
  2140. {
  2141. payStr = pay.Name;
  2142. }
  2143. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  2144. {
  2145. Id = ropItem.Id,
  2146. DiId = ropItem.DIId,
  2147. PriceName = ropItem.PrPriceName,
  2148. PayCurrencyCode = thisCueencyCode,
  2149. PayCurrencyName = thisCueencyName,
  2150. Price = ropItem.PrPrice,
  2151. CNYPrice = ropItem.RMBPrice,
  2152. ThisRate = ropItem.DayRate,
  2153. Payee = ropItem.Payee,
  2154. PayTime = ropItem.AuditGMDate,
  2155. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  2156. PayType = payStr,
  2157. IsPay = ropItem.IsPay,
  2158. Applicant = ropItem.Appliction
  2159. };
  2160. _promView.Add(gsd_PaymentRefund);
  2161. }
  2162. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  2163. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "收款退还", Amount = promTotalAmount });
  2164. #endregion
  2165. #region 团组支出
  2166. GroupExpenditureView _geView = new GroupExpenditureView();
  2167. #region 酒店预定费用
  2168. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  2169. string hotelFeeSql = string.Format(@"Select hr.Id As HrId,hr.DiId As HrDiId,hr.City,hr.HotelName,hr.CheckInDate,hr.CheckOutDate,
  2170. sd1.Name As PaymentCurrency,hr.SingleRoomPrice,hr.SingleRoomCount,hr.DoubleRoomPrice,
  2171. hr.DoubleRoomCount,hr.SuiteRoomPrice,hr.SuiteRoomCount,hr.OtherRoomPrice,hr.OtherRoomCount,
  2172. hr.BreakfastPrice,sd4.Name As BreakfastCurrency,hr.Isoppay,hr.GovernmentRent,
  2173. sd5.Name As GovernmentRentCurrency,hr.CityTax,sd6.Name As CityTaxCurrency,
  2174. ccp.PayMoney,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,
  2175. sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant
  2176. From Grp_HotelReservations hr
  2177. Left Join Grp_CreditCardPayment ccp On hr.Id = ccp.CId
  2178. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2179. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2180. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2181. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2182. Left Join Sys_SetData sd4 On hr.BreakfastCurrency = sd4.Id
  2183. Left Join Sys_SetData sd5 On hr.GovernmentRentCurrency = sd5.Id
  2184. Left Join Sys_SetData sd6 On hr.CityTaxCurrency = sd6.Id
  2185. Where hr.IsDel = 0 And ccp.IsDel = 0 And ccp.CTable = 76 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And hr.DiId = {0}
  2186. Order By CheckInDate Asc", _diId);
  2187. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  2188. decimal HotelCNYTotalPrice = groupHotelFeeViews.Sum(it => it.CNYPrice);
  2189. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "酒店预定", Amount = HotelCNYTotalPrice });
  2190. #endregion
  2191. #region 地接费用
  2192. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  2193. string CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.Area,ctggrc.*,ctggrc.Price As PayMoney,
  2194. sd2.name As PaymentCurrency,ccp.PayPercentage,
  2195. (ctggrc.Price / (ccp.PayPercentage / 100)) As AmountPaid,
  2196. (ctggrc.Price / (ccp.PayPercentage / 100) - ctggrc.Price) As BalancePayment,
  2197. ccp.DayRate,(ctggrc.Price * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  2198. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  2199. From Grp_CarTouristGuideGroundReservations ctggr
  2200. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price,sd2.Name As PriceCurrency,
  2201. cggrc.PriceContent
  2202. From Grp_CarTouristGuideGroundReservationsContent cggrc
  2203. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  2204. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  2205. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  2206. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  2207. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  2208. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  2209. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  2210. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2211. Where ctggr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ctggr.DiId = {0}
  2212. Order By CreateTime", _diId);
  2213. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  2214. decimal CTGGRCNYTotalPrice = groupCTGGRFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  2215. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "地接", Amount = CTGGRCNYTotalPrice });
  2216. #endregion
  2217. #region 机票预订费用
  2218. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  2219. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  2220. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  2221. sd1.Name As PayMoneyCurrency,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  2222. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime
  2223. From Grp_AirTicketReservations atr
  2224. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  2225. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2226. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2227. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2228. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  2229. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2230. Where atr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And atr.DiId = {0} Order By CreateTime", _diId);
  2231. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  2232. decimal AirCNYTotalPrice = groupAirFeeViews.Sum(it => it.CNYPrice);
  2233. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "机票预订", Amount = AirCNYTotalPrice });
  2234. #endregion
  2235. #region 签证费用
  2236. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  2237. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  2238. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  2239. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime
  2240. From Grp_VisaInfo vi
  2241. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  2242. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2243. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2244. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2245. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2246. Where vi.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And vi.DIId = {0} Order By CreateTime", _diId);
  2247. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  2248. decimal VisaCNYTotalPirce = groupVisaFeeViews.Sum(it => it.PayMoney);
  2249. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "签证", Amount = VisaCNYTotalPirce });
  2250. #endregion
  2251. #region 邀请/公务活动 CTable = 81
  2252. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  2253. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  2254. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  2255. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  2256. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  2257. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  2258. From Grp_InvitationOfficialActivities ioa
  2259. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  2260. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2261. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2262. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  2263. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  2264. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  2265. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  2266. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  2267. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2268. Where ioa.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ioa.Diid = {0} Order By CreateTime", _diId);
  2269. groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
  2270. decimal InvitationalCNYTotalPrice = groupInvitationalFeeViews.Sum(it => it.CNYPrice);
  2271. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "邀请/公务活动", Amount = InvitationalCNYTotalPrice });
  2272. #endregion
  2273. #region 保险费用
  2274. List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
  2275. string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.RMBPrice As CNYPrice,
  2276. sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  2277. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
  2278. From Grp_Customers ic
  2279. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  2280. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2281. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2282. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2283. Where ic.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ic.DiId = {0} Order By CreateTime", _diId);
  2284. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  2285. decimal InsuranceCNYTotalPrice = groupInsuranceFeeViews.Sum(it => it.CNYPrice);
  2286. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "保险费用", Amount = InsuranceCNYTotalPrice });
  2287. #endregion
  2288. #region 其他款项费用 98
  2289. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  2290. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  2291. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  2292. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  2293. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  2294. From Grp_DecreasePayments dp
  2295. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  2296. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2297. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2298. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2299. Where dp.IsDel = 0 And ccp.Ctable = 98 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And dp.Diid = {0}
  2300. Order By CreateTime", _diId);
  2301. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  2302. decimal DecreaseCNYTotalPrice = groupDecreaseFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  2303. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "其他款项", Amount = DecreaseCNYTotalPrice });
  2304. #endregion
  2305. #endregion
  2306. /*
  2307. * 团组报表计算方式
  2308. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  2309. * 应收金额 = 应收表.Sum()
  2310. * 已收金额 = 已收表.Sum()
  2311. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  2312. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  2313. *
  2314. */
  2315. decimal _totalExpenditure = 0.00M; //总支出
  2316. decimal _amountReceivable = 0.00M; //应收金额
  2317. decimal _amountReceived = 0.00M; //已收金额
  2318. decimal _receivableProfit = 0.00M; //应收利润
  2319. decimal _receivedProfit = 0.00M; //已收利润
  2320. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  2321. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount;
  2322. _amountReceivable = frTotalAmount;
  2323. _amountReceived = prTotalAmount;
  2324. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  2325. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  2326. var groupInfo = groupInfos.Find(it => it.Id == _diId);
  2327. corporateProfits.Add(new CorporateProfit()
  2328. {
  2329. DiId = _diId,
  2330. TeamName = groupInfo?.TeamName ?? "Unkwnon",
  2331. CreateDt = Convert.ToDateTime(groupInfo?.CreateTime),
  2332. TotalExpenditure = _totalExpenditure,
  2333. ExpenditureItem = expenditureInfos,
  2334. AmountReceivable = _amountReceivable,
  2335. AmountReceived = _amountReceived,
  2336. ReceivableProfit = _receivableProfit,
  2337. ReceivedProfit = _receivedProfit,
  2338. });
  2339. }
  2340. #endregion
  2341. return corporateProfits;
  2342. }
  2343. //未来预测-地区接团/出团量
  2344. //未来预测-地区酒店预订量
  2345. //未来预测-地区机票预订量
  2346. //未来预测-地区车辆预订量
  2347. /// <summary>
  2348. /// (国家/城市)地区预订数量(团,酒店,机票,车辆)
  2349. /// Details
  2350. /// 待添加权限验证
  2351. /// </summary>
  2352. /// <param name="_dto">团组列表请求dto</param>
  2353. /// <returns></returns>
  2354. [HttpPost("PostRegionalBookingsNumber")]
  2355. //[JsonConverter(typeof(DecimalConverter), 2)]
  2356. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2357. public async Task<IActionResult> PostRegionalBookingsNumber(PostRegionalBookingsNumberDto _dto)
  2358. {
  2359. #region 参数验证
  2360. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  2361. //if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  2362. if (_dto.Type > 1 && _dto.Type > 5) return Ok(JsonView(false, "请输入有效的Type参数,1 团 2 酒店 3 机票 4 车辆"));
  2363. if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));
  2364. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2365. #region 页面操作权限验证
  2366. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2367. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  2368. #endregion
  2369. string sqlWhere = string.Empty;
  2370. //起止时间
  2371. DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");
  2372. DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");
  2373. sqlWhere = string.Format(@$" Where Isdel = 0 ");
  2374. string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");
  2375. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();
  2376. if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));
  2377. List<GroupTypeNumberInfo> datas = new List<GroupTypeNumberInfo>();
  2378. foreach (var item in groupInfos)
  2379. {
  2380. var data = await GroupBookingsNumber(_dto.Type, item);
  2381. if (data.TypeItem.Count > 0)
  2382. {
  2383. datas.Add(data);
  2384. }
  2385. }
  2386. //类型处理
  2387. if (_dto.Type == 1)//接团
  2388. {
  2389. List<GroupBookingNumberView> views = new List<GroupBookingNumberView>();
  2390. dynamic groupData = null;
  2391. foreach (var item in datas)
  2392. {
  2393. if (item.TypeItem.Count > 0)
  2394. {
  2395. foreach (var item1 in item.TypeItem)
  2396. {
  2397. if (item1.RegionItem.Count > 0)
  2398. {
  2399. GroupInfo groupInfo = new GroupInfo()
  2400. {
  2401. DiId = item.DiId,
  2402. TeamName = item.GroupName,
  2403. CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",
  2404. ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",
  2405. Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",
  2406. };
  2407. views.Add(new GroupBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, GroupItem = new List<GroupInfo>() { groupInfo } });
  2408. }
  2409. }
  2410. }
  2411. }
  2412. var viewsGroup = views.GroupBy(it => it.Name);
  2413. List<GroupBookingNumberView> _view = new List<GroupBookingNumberView>();
  2414. foreach (var item in viewsGroup)
  2415. {
  2416. List<GroupInfo> infos = new List<GroupInfo>();
  2417. foreach (var item1 in item)
  2418. {
  2419. infos.AddRange(item1.GroupItem);
  2420. }
  2421. infos = infos.OrderByDescending(it => it.CreateTime).ToList(); //
  2422. _view.Add(new GroupBookingNumberView() { Name = item.Key, Number = item.Count(), GroupItem = infos });
  2423. }
  2424. _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();
  2425. return Ok(JsonView(true, "操作成功!", _view, _view.Count));
  2426. }
  2427. else if (_dto.Type == 2)
  2428. {
  2429. List<HotelBookingNumberView> views = new List<HotelBookingNumberView>();
  2430. foreach (var item in datas)
  2431. {
  2432. if (item.TypeItem.Count > 0)
  2433. {
  2434. foreach (var item1 in item.TypeItem)
  2435. {
  2436. if (item1.RegionItem.Count > 0)
  2437. {
  2438. foreach (var item2 in item1.RegionItem)
  2439. {
  2440. GroupInfo groupInfo = new GroupInfo()
  2441. {
  2442. DiId = item.DiId,
  2443. TeamName = item.GroupName,
  2444. CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",
  2445. ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",
  2446. Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",
  2447. };
  2448. List<HotelInfo> hotels = new List<HotelInfo>();
  2449. foreach (var item3 in item2.Data)
  2450. {
  2451. StatisticsHotelInfo statisticsHotelInfos = JsonConvert.DeserializeObject<StatisticsHotelInfo>(JsonConvert.SerializeObject(item3));
  2452. HotelInfo hotelInfo = new HotelInfo()
  2453. {
  2454. HotelName = statisticsHotelInfos.HotelName,
  2455. SingleRoomNum = statisticsHotelInfos.SingleRoomNum,
  2456. DoubleRoomNum = statisticsHotelInfos.DoubleRoomNum,
  2457. SuiteRoomNum = statisticsHotelInfos.SuiteRoomNum,
  2458. OtherRoomNum = statisticsHotelInfos.OtherRoomNum,
  2459. GroupInfo = groupInfo
  2460. };
  2461. hotels.Add(hotelInfo);
  2462. }
  2463. views.Add(new HotelBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, HotelItem = hotels });
  2464. }
  2465. }
  2466. }
  2467. }
  2468. }
  2469. var viewsGroup = views.GroupBy(it => it.Name);
  2470. List<HotelBookingNumberView> _view = new List<HotelBookingNumberView>();
  2471. foreach (var item in viewsGroup)
  2472. {
  2473. List<HotelInfo> infos = new List<HotelInfo>();
  2474. foreach (var item1 in item)
  2475. {
  2476. infos.AddRange(item1.HotelItem);
  2477. }
  2478. _view.Add(new HotelBookingNumberView() { Name = item.Key, Number = item.Count(), HotelItem = infos });
  2479. }
  2480. _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();
  2481. return Ok(JsonView(true, "操作成功!", views, views.Count));
  2482. }
  2483. return Ok(JsonView(false, "操作失败!"));
  2484. #endregion
  2485. }
  2486. /// <summary>
  2487. /// 计算团组ALLType预订数量
  2488. /// </summary>
  2489. /// <param name="diIds"></param>
  2490. /// <returns></returns>
  2491. private async Task<GroupTypeNumberInfo> GroupBookingsNumber(int type, Grp_DelegationInfo info)
  2492. {
  2493. GroupTypeNumberInfo _view = new GroupTypeNumberInfo();
  2494. if (info == null)
  2495. {
  2496. return _view;
  2497. }
  2498. _view.DiId = info.Id;
  2499. _view.GroupName = info.TeamName;
  2500. List<TypeInfo> _types = new List<TypeInfo>();
  2501. #region 计算团组ALLType预订数量
  2502. if (type == 1)
  2503. {
  2504. //接团 客户集团所在地区
  2505. string group_region = string.Empty;
  2506. int group_number = 0;
  2507. if (!string.IsNullOrEmpty(info.ClientUnit))
  2508. {
  2509. var _NewClientData = await _sqlSugar.Queryable<Crm_NewClientData>()
  2510. .Where(it => it.IsDel == 0 && it.Client.Equals(AesEncryptionHelper.Encrypt(info.ClientUnit)))
  2511. .FirstAsync();
  2512. if (_NewClientData != null)
  2513. {
  2514. var regionInfo = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.Id == _NewClientData.Lvlid).FirstAsync();
  2515. if (regionInfo != null)
  2516. {
  2517. group_region = regionInfo.Name.Replace("级", "");
  2518. group_number++;
  2519. }
  2520. }
  2521. }
  2522. if (group_number > 0)
  2523. {
  2524. _types.Add(new TypeInfo() { Id = 1, RegionItem = new List<RegionInfo>() { new RegionInfo() { Name = group_region, Number = group_number } } });
  2525. }
  2526. }
  2527. else if (type == 2)
  2528. {
  2529. //酒店
  2530. var hotelInfos = await _sqlSugar.Queryable<Grp_HotelReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  2531. if (hotelInfos.Count > 0)
  2532. {
  2533. List<RegionInfo> hotelRegions = new List<RegionInfo>();
  2534. foreach (var item in hotelInfos)
  2535. {
  2536. var hotelNumberInfo = new StatisticsHotelInfo()
  2537. {
  2538. HotelName = item.HotelName,
  2539. SingleRoomNum = item.SingleRoomCount,
  2540. DoubleRoomNum = item.DoubleRoomCount,
  2541. SuiteRoomNum = item.SuiteRoomCount,
  2542. OtherRoomNum = item.OtherRoomCount,
  2543. };
  2544. int hotelRoomTotal = item.SingleRoomCount + item.DoubleRoomCount + item.SuiteRoomCount + item.OtherRoomCount;
  2545. if (hotelRegions.Select(it => it.Name).ToList().Contains(item.City))
  2546. {
  2547. RegionInfo hotelRegion = hotelRegions.Find(it => it.Name.Equals(item.City));
  2548. if (hotelRegion != null)
  2549. {
  2550. hotelRegions.Remove(hotelRegion);
  2551. if (hotelRegion.Data.Count > 0)
  2552. {
  2553. hotelRegion.Data.Add(hotelNumberInfo);
  2554. }
  2555. hotelRegion.Number += hotelRoomTotal;
  2556. hotelRegions.Add(hotelRegion);
  2557. }
  2558. }
  2559. else
  2560. {
  2561. hotelRegions.Add(new RegionInfo() { Name = item.City, Number = hotelRoomTotal, Data = new List<dynamic>() { hotelNumberInfo } });
  2562. }
  2563. }
  2564. _types.Add(new TypeInfo() { Id = 2, RegionItem = hotelRegions });
  2565. }
  2566. }
  2567. else if (type == 3)
  2568. {
  2569. //机票
  2570. var airTicketInfos = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
  2571. .LeftJoin<Grp_CreditCardPayment>((atr, ccp) => atr.Id == ccp.CId && ccp.IsPay == 1)
  2572. .LeftJoin<Sys_SetData>((atr, ccp, sd) => atr.CType == sd.Id)
  2573. .Where((atr, ccp, sd) => atr.IsDel == 0 && atr.DIId == info.Id)
  2574. .Select((atr, ccp, sd) => new { atr.ClientNum, atr.CType, ccp.Payee, AirType = sd.Name })
  2575. .ToListAsync();
  2576. if (airTicketInfos.Count > 0)
  2577. {
  2578. List<RegionInfo> airTicketRegions = new List<RegionInfo>();
  2579. foreach (var item in airTicketInfos)
  2580. {
  2581. var ticketClass = new
  2582. {
  2583. TiketClass = item.AirType,
  2584. Number = item.ClientNum
  2585. };
  2586. if (airTicketRegions.Select(it => it.Name).ToList().Contains(item.Payee))
  2587. {
  2588. RegionInfo airTicketRegion = airTicketRegions.Find(it => it.Name.Equals(item.Payee));
  2589. if (airTicketRegion != null)
  2590. {
  2591. airTicketRegions.Remove(airTicketRegion);
  2592. if (airTicketRegion.Data.Count > 0)
  2593. {
  2594. airTicketRegion.Data.Add(ticketClass);
  2595. }
  2596. airTicketRegion.Number += item.ClientNum;
  2597. airTicketRegions.Add(airTicketRegion);
  2598. }
  2599. }
  2600. else
  2601. {
  2602. airTicketRegions.Add(new RegionInfo() { Name = item.Payee, Number = item.ClientNum, Data = new List<dynamic>() { ticketClass } });
  2603. }
  2604. }
  2605. _types.Add(new TypeInfo() { Id = 3, RegionItem = airTicketRegions });
  2606. }
  2607. }
  2608. else if (type == 4)
  2609. {
  2610. //车辆
  2611. var opInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  2612. var opContentInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservationsContent>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  2613. if (opInfos.Count > 0)
  2614. {
  2615. List<RegionInfo> opRegions = new List<RegionInfo>();
  2616. foreach (var item in opInfos)
  2617. {
  2618. int carNum = 0;
  2619. var opContentInfo = opContentInfos.Where(it => it.CTGGRId == item.Id && it.SId == 91).ToList();
  2620. if (opContentInfo.Count > 0)
  2621. {
  2622. foreach (var item1 in opContentInfo)
  2623. {
  2624. if (item1.Price > 0 && item1.Count > 0)
  2625. {
  2626. carNum += item1.Count;
  2627. }
  2628. }
  2629. }
  2630. if (carNum > 0)
  2631. {
  2632. var opData = new
  2633. {
  2634. ServiceCompany = item.ServiceCompany,
  2635. BusName = item.BusName,
  2636. Numbuer = carNum
  2637. };
  2638. if (opRegions.Select(it => it.Name).ToList().Contains(item.Area))
  2639. {
  2640. RegionInfo opRegion = opRegions.Find(it => it.Name.Equals(item.Area));
  2641. if (opRegion != null)
  2642. {
  2643. opRegions.Remove(opRegion);
  2644. if (opRegion.Data.Count > 0)
  2645. {
  2646. opRegion.Data.Add(opData);
  2647. }
  2648. opRegion.Number += carNum;
  2649. opRegions.Add(opRegion);
  2650. }
  2651. }
  2652. else
  2653. {
  2654. opRegions.Add(new RegionInfo() { Name = item.Area, Number = carNum, Data = new List<dynamic>() { opData } });
  2655. }
  2656. }
  2657. }
  2658. _types.Add(new TypeInfo() { Id = 4, RegionItem = opRegions });
  2659. }
  2660. }
  2661. #endregion
  2662. _view.TypeItem = _types;
  2663. return _view;
  2664. }
  2665. #endregion
  2666. #region 市场部销售额
  2667. /// <summary>
  2668. /// 市场部销售额
  2669. /// Init 基础数据(公司/人员/年份/季度/月份)
  2670. /// </summary>
  2671. /// <param name="_dto">市场部销售额请求dto</param>
  2672. /// <returns></returns>
  2673. [HttpPost("PostMarketingSalesInitData")]
  2674. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2675. public async Task<IActionResult> PostMarketingSalesInitData(MarketingSalesInitDataDto _dto)
  2676. {
  2677. #region 参数验证
  2678. MarketingSalesInitDataDtoFoalidator validationRules = new MarketingSalesInitDataDtoFoalidator();
  2679. var validResult = await validationRules.ValidateAsync(_dto);
  2680. if (!validResult.IsValid)
  2681. {
  2682. var errors = new StringBuilder();
  2683. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2684. return Ok(JsonView(false, errors.ToString()));
  2685. }
  2686. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2687. #region 页面操作权限验证
  2688. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2689. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2690. #endregion
  2691. var companyData = _sqlSugar.Queryable<Sys_Company>().Where(it => it.IsDel == 0)
  2692. .Select(it => new { id = it.Id, name = it.CompanyName })
  2693. .ToList();
  2694. List<int> companyIds = companyData.Select(it => it.id).ToList();
  2695. List<int> pickGroupUserIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0)
  2696. .Select(it => it.JietuanOperator)
  2697. .ToList();
  2698. var userData = _sqlSugar.Queryable<Sys_Users>()
  2699. .Where(it => it.IsDel == 0 && (pickGroupUserIds.Contains(it.Id) || it.Id == 21))
  2700. .Select(it => new { id = it.Id, companyId = it.CompanyId, name = it.CnName })
  2701. .ToList();
  2702. companyData.Insert(0, new { id = -1, name = "全部" });
  2703. userData.Insert(0, new { id = -1, companyId = -1, name = "全部" });
  2704. #region 年份
  2705. var dtData = new List<dynamic>();
  2706. int dt = DateTime.Now.Year;
  2707. for (int y = dt; y >= dt - 4; y--)
  2708. {
  2709. //季度
  2710. var quarterDatas = new List<dynamic>();
  2711. quarterDatas.Add(new { name = "全部", beginDt = $"{y}-01-01", endDt = $"{y}-12-31" });
  2712. for (int q = 0; q < 4; q++)
  2713. {
  2714. dynamic quarterData = null;
  2715. if (q == 0)
  2716. {
  2717. var monthDatas = new List<dynamic>();
  2718. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-01-01", endDt = $" {y}-03-31" });
  2719. for (int m = 1; m < 4; m++)
  2720. {
  2721. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  2722. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  2723. }
  2724. //quarterData = new { name = "第一季度", beginDt = $"{y}-01-01", endDt = $" {y}-03-31", monthData = monthDatas };
  2725. quarterData = new { name = "第一季度", monthData = monthDatas };
  2726. }
  2727. else if (q == 1)
  2728. {
  2729. var monthDatas = new List<dynamic>();
  2730. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-04-01", endDt = $"{y}-06-30" });
  2731. for (int m = 4; m < 7; m++)
  2732. {
  2733. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  2734. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  2735. }
  2736. //quarterData = new { name = "第二季度", beginDt = $"{y}-04-01", endDt = $"{y}-06-30", monthData = monthDatas };
  2737. quarterData = new { name = "第二季度", monthData = monthDatas };
  2738. }
  2739. else if (q == 2)
  2740. {
  2741. var monthDatas = new List<dynamic>();
  2742. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-07-01", endDt = $"{y}-09-30" });
  2743. for (int m = 7; m < 10; m++)
  2744. {
  2745. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  2746. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  2747. }
  2748. //quarterData = new { name = "第三季度", beginDt = $"{y}-07-01", endDt = $"{y}-09-30", monthData = monthDatas };
  2749. quarterData = new { name = "第三季度", monthData = monthDatas };
  2750. }
  2751. else if (q == 3)
  2752. {
  2753. var monthDatas = new List<dynamic>();
  2754. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-10-01", endDt = $"{y}-12-31" });
  2755. for (int m = 10; m < 13; m++)
  2756. {
  2757. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  2758. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  2759. }
  2760. //quarterData = new { name = "第四季度", beginDt = $"{y}-10-01", endDt = $"{y}-12-31", monthData = monthDatas };
  2761. quarterData = new { name = "第四季度", monthData = monthDatas };
  2762. }
  2763. quarterDatas.Add(quarterData);
  2764. }
  2765. dtData.Add(new
  2766. {
  2767. year = y,
  2768. //yearData = new { beginDt = $"{y}-01-01", endDt = $"{y}-12-31" },
  2769. quarterData = quarterDatas,
  2770. });
  2771. }
  2772. #endregion
  2773. return Ok(JsonView(true, "操作成功!", new { companyData = companyData, userData = userData, dtData = dtData }));
  2774. #endregion
  2775. }
  2776. private static string ConvertToChinese(int month)
  2777. {
  2778. if (month < 1 || month > 12)
  2779. throw new ArgumentOutOfRangeException(nameof(month), "月份必须在1到12之间。");
  2780. var cultureInfo = new System.Globalization.CultureInfo("zh-CN");
  2781. var dateTimeFormat = cultureInfo.DateTimeFormat;
  2782. return dateTimeFormat.GetMonthName(month);
  2783. }
  2784. /// <summary>
  2785. /// 市场部销售额
  2786. /// 年度/季度/月度 报表(同比)
  2787. /// </summary>
  2788. /// <param name="_dto">市场部销售额请求dto</param>
  2789. /// <returns></returns>
  2790. [HttpPost("PostMarketingSalesStatistics")]
  2791. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2792. public async Task<IActionResult> PostMarketingSalesStatistics_Year(MarketingSalesStatisticsDto _dto)
  2793. {
  2794. #region 参数验证
  2795. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  2796. var validResult = await validationRules.ValidateAsync(_dto);
  2797. if (!validResult.IsValid)
  2798. {
  2799. var errors = new StringBuilder();
  2800. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2801. return Ok(JsonView(false, errors.ToString()));
  2802. }
  2803. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2804. #region 页面操作权限验证
  2805. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2806. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2807. #endregion
  2808. #endregion
  2809. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  2810. return Ok(JsonView(true, "操作成功!", await GroupSales(_dto.CompanyId, _dto.GroupPickupUserId, beginDt, endDt)));
  2811. }
  2812. private async Task<List<int>> GetUserIds(int companyId, int groupPickupUserId)
  2813. {
  2814. //全部人员Id
  2815. //查询所有公司的市场部
  2816. var pickGroupIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0).Select(it => it.JietuanOperator).Distinct().ToList();
  2817. var userIds = new List<int>();
  2818. var userDatas = await _sqlSugar.Queryable<Sys_Users>()
  2819. .InnerJoin<Sys_Company>((u, c) => u.CompanyId == c.Id)
  2820. .Where((u, c) => u.IsDel == 0 && pickGroupIds.Contains(u.Id))
  2821. .Select((u, c) => new { u.Id, u.CompanyId, u.CnName })
  2822. .ToListAsync();
  2823. userIds = userDatas.Select(it => it.Id).ToList();
  2824. if (companyId > 0)
  2825. {
  2826. userIds = userDatas.Where(it => it.CompanyId == companyId).Select(it => it.Id).ToList();
  2827. }
  2828. if (groupPickupUserId > 0)
  2829. {
  2830. userIds = userDatas.Where(it => it.Id == groupPickupUserId).Select(it => it.Id).ToList();
  2831. }
  2832. return userIds;
  2833. }
  2834. /// <summary>
  2835. /// 计算团组销售额
  2836. /// </summary>
  2837. /// <param name="companyId"></param>
  2838. /// <param name="groupPickupUserId"></param>
  2839. /// <param name="beginDt"></param>
  2840. /// <param name="endDt"></param>
  2841. /// <returns></returns>
  2842. private async Task<SalesYOYView> GroupSales(int companyId, int groupPickupUserId, string beginDt, string endDt)
  2843. {
  2844. decimal thisSales = 0.00M, lastSales = 0.00M, yoy = 1.00M;
  2845. var _view = new SalesYOYView();
  2846. List<int> userIds = new List<int>();
  2847. userIds = await GetUserIds(companyId, groupPickupUserId);
  2848. string userSqlWhere = "";
  2849. if (userIds.Count > 0)
  2850. {
  2851. userSqlWhere = string.Format($" And Id IN ({string.Join(',', userIds)})");
  2852. }
  2853. else
  2854. {
  2855. _view = new SalesYOYView
  2856. {
  2857. thisYearSales = "0.00",
  2858. lastYearSales = "0.00",
  2859. };
  2860. return _view;
  2861. }
  2862. string lastBeginDt = Convert.ToDateTime(beginDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss"),
  2863. lastEndDt = Convert.ToDateTime(endDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss");
  2864. // string salesSql = string.Format(@"
  2865. //SELECT
  2866. // 'ThisSales' As [Name],
  2867. // CAST(SUM(Sales) AS decimal(12,2)) As Sales
  2868. //FROM
  2869. // (
  2870. // SELECT di.VisitDate,
  2871. // (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  2872. // WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  2873. // ) AS Sales
  2874. // FROM
  2875. // Grp_DelegationInfo di
  2876. // WHERE di.IsDel = 0 AND di.IsSure = 1
  2877. // AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
  2878. // AND di.VisitDate BETWEEN '{1}' AND '{2}'
  2879. // ) temp
  2880. //Union ALL
  2881. //SELECT
  2882. // 'LastSales' As [Name],
  2883. // CAST(SUM(Sales) AS decimal(12,2)) As Sales
  2884. //FROM
  2885. // (
  2886. // SELECT di.VisitDate,
  2887. // (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  2888. // WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  2889. // ) AS Sales
  2890. // FROM
  2891. // Grp_DelegationInfo di
  2892. // WHERE di.IsDel = 0 AND di.IsSure = 1
  2893. // AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {3})
  2894. // AND di.VisitDate BETWEEN '{4}' AND '{5}'
  2895. // ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
  2896. string salesSql = string.Format(@"
  2897. SELECT
  2898. 'ThisSales' As [Name],
  2899. CAST(SUM(Sales) AS decimal(12,2)) As Sales
  2900. FROM
  2901. (
  2902. SELECT di.VisitDate,
  2903. (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  2904. WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  2905. ) AS Sales
  2906. FROM
  2907. Grp_DelegationInfo di
  2908. WHERE di.IsDel = 0
  2909. AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
  2910. AND di.VisitDate BETWEEN '{1}' AND '{2}'
  2911. ) temp
  2912. Union ALL
  2913. SELECT
  2914. 'LastSales' As [Name],
  2915. CAST(SUM(Sales) AS decimal(12,2)) As Sales
  2916. FROM
  2917. (
  2918. SELECT di.VisitDate,
  2919. (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  2920. WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  2921. ) AS Sales
  2922. FROM
  2923. Grp_DelegationInfo di
  2924. WHERE di.IsDel = 0
  2925. AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {3})
  2926. AND di.IsBid = 0
  2927. AND di.TeamName Not Like '%投标%'
  2928. AND di.VisitDate BETWEEN '{4}' AND '{5}'
  2929. ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
  2930. var salesData = await _sqlSugar.SqlQueryable<SalesView>(salesSql).ToListAsync();
  2931. thisSales = salesData.Where(x => x.Name.Equals("ThisSales")).First()?.Sales ?? 0;
  2932. lastSales = salesData.Where(x => x.Name.Equals("LastSales")).First()?.Sales ?? 0;
  2933. if (lastSales != 0 && thisSales != 0) yoy = (thisSales - lastSales) / lastSales;
  2934. return new SalesYOYView()
  2935. {
  2936. thisYearSales = thisSales.ToString("#0.00"),
  2937. lastYearSales = lastSales.ToString("#0.00"),
  2938. yoy = yoy.ToString("#0.00")
  2939. };
  2940. }
  2941. private class SalesView
  2942. {
  2943. public string Name { get; set; }
  2944. public decimal Sales { get; set; }
  2945. }
  2946. private class SalesYOYView
  2947. {
  2948. public string thisYearSales { get; set; }
  2949. public string lastYearSales { get; set; }
  2950. public string yoy { get; set; } = "1.00";
  2951. }
  2952. /// <summary>
  2953. /// 市场部销售额
  2954. /// 团组列表
  2955. /// </summary>
  2956. /// <param name="_dto">市场部销售额请求dto</param>
  2957. /// <returns></returns>
  2958. [HttpPost("PostMarketingSalesGroupList")]
  2959. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2960. public async Task<IActionResult> PostMarketingSalesGroupList(MarketingSalesGroupListDto _dto)
  2961. {
  2962. #region 参数验证
  2963. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  2964. var validResult = await validationRules.ValidateAsync(_dto);
  2965. if (!validResult.IsValid)
  2966. {
  2967. var errors = new StringBuilder();
  2968. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2969. return Ok(JsonView(false, errors.ToString()));
  2970. }
  2971. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2972. #region 页面操作权限验证
  2973. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2974. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2975. #endregion
  2976. #endregion
  2977. string userSql = "";
  2978. List<int> userIds = new List<int>();
  2979. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  2980. if (userIds.Count <= 0)
  2981. {
  2982. return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  2983. }
  2984. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  2985. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  2986. {
  2987. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  2988. }
  2989. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  2990. // string sql = string.Format(@$"SELECT
  2991. // ROW_NUMBER() OVER (
  2992. // ORDER BY
  2993. // CollectionDays
  2994. // ) AS RowNumber,
  2995. // *
  2996. //FROM
  2997. // (
  2998. // SELECT
  2999. // di.Id,
  3000. // di.TeamName,
  3001. // di.ClientUnit,
  3002. // di.ClientName,
  3003. // di.VisitDate,
  3004. // di.VisitPNumber,
  3005. // di.JietuanOperator,
  3006. // di.VisitEndDate,
  3007. // (
  3008. // SELECT
  3009. // CAST(
  3010. // COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3011. // ) AS GroupSales
  3012. // FROM
  3013. // Fin_ForeignReceivables
  3014. // WHERE
  3015. // IsDel = 0
  3016. // AND di.Id = Diid
  3017. // AND AddingWay IN (0, 1, 2)
  3018. // ) AS GroupSales,
  3019. // u.CnName AS GroupPickupUser,
  3020. // DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  3021. // FROM
  3022. // Grp_DelegationInfo di
  3023. // WITH
  3024. // (NoLock)
  3025. // LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  3026. // WHERE
  3027. // di.Isdel = 0
  3028. // AND di.IsSure = 1 {userSql}
  3029. // AND VisitDate Between '{beginDt}' And '{endDt}'
  3030. // ) Temp ");
  3031. string sql = string.Format(@$"SELECT
  3032. ROW_NUMBER() OVER (
  3033. ORDER BY
  3034. CollectionDays
  3035. ) AS RowNumber,
  3036. *
  3037. FROM
  3038. (
  3039. SELECT
  3040. di.Id,
  3041. di.TeamName,
  3042. di.ClientUnit,
  3043. di.ClientName,
  3044. di.VisitDate,
  3045. di.VisitPNumber,
  3046. di.JietuanOperator,
  3047. di.VisitEndDate,
  3048. (
  3049. SELECT
  3050. CAST(
  3051. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3052. ) AS GroupSales
  3053. FROM
  3054. Fin_ForeignReceivables
  3055. WHERE
  3056. IsDel = 0
  3057. AND di.Id = Diid
  3058. AND AddingWay IN (0, 1, 2)
  3059. ) AS GroupSales,
  3060. u.CnName AS GroupPickupUser,
  3061. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  3062. FROM
  3063. Grp_DelegationInfo di
  3064. WITH
  3065. (NoLock)
  3066. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  3067. WHERE
  3068. di.Isdel = 0
  3069. AND (
  3070. SELECT
  3071. CAST(
  3072. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3073. ) AS GroupSales
  3074. FROM
  3075. Fin_ForeignReceivables
  3076. WHERE
  3077. IsDel = 0
  3078. AND di.Id = Diid
  3079. AND AddingWay IN (0, 1, 2)
  3080. ) > 0
  3081. {userSql}
  3082. AND di.IsBid = 0
  3083. AND di.TeamName Not Like '%投标%'
  3084. AND VisitDate Between '{beginDt}' And '{endDt}'
  3085. ) Temp ");
  3086. RefAsync<int> total = 0;
  3087. var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  3088. return Ok(JsonView(true, "操作成功!", groupData, total));
  3089. }
  3090. /// <summary>
  3091. /// 市场部销售额
  3092. /// 团组列表Excel下载
  3093. /// </summary>
  3094. /// <param name="_dto">市场部销售额请求dto</param>
  3095. /// <returns></returns>
  3096. [HttpPost("PostMarketingSalesGroupExcel")]
  3097. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3098. public async Task<IActionResult> PostMarketingSalesGroupExcel(MarketingSalesGroupListDto _dto)
  3099. {
  3100. #region 参数验证
  3101. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  3102. var validResult = await validationRules.ValidateAsync(_dto);
  3103. if (!validResult.IsValid)
  3104. {
  3105. var errors = new StringBuilder();
  3106. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3107. return Ok(JsonView(false, errors.ToString()));
  3108. }
  3109. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3110. #region 页面操作权限验证
  3111. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3112. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3113. #endregion
  3114. #endregion
  3115. string userSql = "";
  3116. var userIds = new List<int>();
  3117. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  3118. if (userIds.Count <= 0)
  3119. {
  3120. return Ok(JsonView(false));
  3121. }
  3122. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  3123. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  3124. {
  3125. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  3126. }
  3127. string beginDt = $"{_dto.BeginDt} 00:00:00",
  3128. endDt = $"{_dto.EndDt} 23:59:59";
  3129. string sql = string.Format(@$"SELECT
  3130. ROW_NUMBER() OVER (
  3131. ORDER BY
  3132. CollectionDays
  3133. ) AS RowNumber,
  3134. *
  3135. FROM
  3136. (
  3137. SELECT
  3138. di.Id,
  3139. di.TeamName,
  3140. di.ClientUnit,
  3141. di.ClientName,
  3142. di.VisitDate,
  3143. di.VisitPNumber,
  3144. di.JietuanOperator,
  3145. di.VisitEndDate,
  3146. (
  3147. SELECT
  3148. CAST(
  3149. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3150. ) AS GroupSales
  3151. FROM
  3152. Fin_ForeignReceivables
  3153. WHERE
  3154. IsDel = 0
  3155. AND di.Id = Diid
  3156. AND AddingWay IN (0, 1, 2)
  3157. ) AS GroupSales,
  3158. u.CnName AS GroupPickupUser,
  3159. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  3160. FROM
  3161. Grp_DelegationInfo di
  3162. WITH
  3163. (NoLock)
  3164. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  3165. WHERE
  3166. di.Isdel = 0
  3167. AND (
  3168. SELECT
  3169. CAST(
  3170. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3171. ) AS GroupSales
  3172. FROM
  3173. Fin_ForeignReceivables
  3174. WHERE
  3175. IsDel = 0
  3176. AND di.Id = Diid
  3177. AND AddingWay IN (0, 1, 2)
  3178. ) > 0
  3179. {userSql}
  3180. AND di.IsBid = 0
  3181. AND di.TeamName Not Like '%投标%'
  3182. AND VisitDate Between '{beginDt}' And '{endDt}'
  3183. ) Temp ");
  3184. var view = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToListAsync();
  3185. if (view.Count < 1) return Ok(JsonView(false, "暂无数据!"));
  3186. //DataTable dt = GeneralMethod.
  3187. DataTable dt = CommonFun.GetDataTableFromIList(view);
  3188. dt.TableName = $"_view";
  3189. WorkbookDesigner designer = new WorkbookDesigner();
  3190. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/营业额团组报表模板.xls");
  3191. designer.SetDataSource(dt);
  3192. designer.SetDataSource("Total", view.Sum(x => x.GroupSales));
  3193. designer.Workbook.Worksheets[0].Name = "营业额团组报表";
  3194. designer.Process();
  3195. string fileName = $"MarketingSales/{_dto.BeginDt}{_dto.EndDt}营业额团组报表{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
  3196. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  3197. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  3198. return Ok(JsonView(true, "操作成功", new { url = rst }));
  3199. }
  3200. /// <summary>
  3201. /// 市场部销售额
  3202. /// 客户类型、客户等级 统计
  3203. /// </summary>
  3204. /// <param name="_dto">市场部销售额请求dto</param>
  3205. /// <returns></returns>
  3206. [HttpPost("PostMarketingSalesGroupStatistics")]
  3207. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3208. public async Task<IActionResult> PostMarketingSalesGroupStatistics(MarketingSalesGroupStatisticsDto _dto)
  3209. {
  3210. #region 参数验证
  3211. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  3212. var validResult = await validationRules.ValidateAsync(_dto);
  3213. if (!validResult.IsValid)
  3214. {
  3215. var errors = new StringBuilder();
  3216. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3217. return Ok(JsonView(false, errors.ToString()));
  3218. }
  3219. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3220. #region 页面操作权限验证
  3221. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3222. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3223. #endregion
  3224. #endregion
  3225. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  3226. List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  3227. string userSql = "";
  3228. if (userIds.Count > 0)
  3229. {
  3230. userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
  3231. }
  3232. else
  3233. {
  3234. if (_dto.PortType == 2 || _dto.PortType == 3)
  3235. {
  3236. return Ok(JsonView(true, "操作成功!", new List<object> { }));
  3237. }
  3238. else
  3239. {
  3240. return Ok(JsonView(true, "操作成功!", new
  3241. {
  3242. customerTypeData = new List<object> { },
  3243. clientGradeData = new List<object> { }
  3244. }));
  3245. }
  3246. }
  3247. string sql = "";
  3248. if (_dto.StatisticsType == 1)
  3249. {
  3250. sql = string.Format(@$"Select
  3251. sd.[Name],
  3252. Count(*) As [Count]
  3253. From Grp_DelegationInfo di
  3254. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  3255. Where di.Isdel = 0
  3256. And (
  3257. SELECT
  3258. CAST(
  3259. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3260. ) AS GroupSales
  3261. FROM
  3262. Fin_ForeignReceivables fr
  3263. WHERE
  3264. fr.IsDel = 0
  3265. AND di.Id = fr.Diid
  3266. AND AddingWay IN (0, 1, 2)
  3267. ) > 0
  3268. {userSql}
  3269. AND di.IsBid = 0
  3270. AND di.TeamName Not Like '%投标%'
  3271. And VisitDate Between '{beginDt}' And '{endDt}'
  3272. Group By [Name]
  3273. Order By Count Desc");
  3274. }
  3275. else if (_dto.StatisticsType == 2)
  3276. {
  3277. sql = string.Format(@$"Select
  3278. sd.[Name],
  3279. Count(*) As [Count]
  3280. From Grp_DelegationInfo di
  3281. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  3282. Where di.Isdel = 0
  3283. And (
  3284. SELECT
  3285. CAST(
  3286. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3287. ) AS GroupSales
  3288. FROM
  3289. Fin_ForeignReceivables fr
  3290. WHERE
  3291. fr.IsDel = 0
  3292. AND di.Id = fr.Diid
  3293. AND AddingWay IN (0, 1, 2)
  3294. ) > 0
  3295. {userSql}
  3296. AND di.IsBid = 0
  3297. AND di.TeamName Not Like '%投标%'
  3298. And VisitDate Between '{beginDt}' And '{endDt}'
  3299. Group By [Name]
  3300. Order By Count Desc");
  3301. }
  3302. else return Ok(JsonView(false, "StatisticsType不在可取范围!"));
  3303. if (_dto.PortType == 1)
  3304. {
  3305. string sql1 = string.Format(@$"Select
  3306. sd.[Name],
  3307. Count(*) As [Count]
  3308. From Grp_DelegationInfo di
  3309. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  3310. Where di.Isdel = 0
  3311. And (
  3312. SELECT
  3313. CAST(
  3314. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3315. ) AS GroupSales
  3316. FROM
  3317. Fin_ForeignReceivables fr
  3318. WHERE
  3319. fr.IsDel = 0
  3320. AND di.Id = fr.Diid
  3321. AND AddingWay IN (0, 1, 2)
  3322. ) > 0
  3323. {userSql}
  3324. AND di.IsBid = 0
  3325. AND di.TeamName Not Like '%投标%'
  3326. And VisitDate Between '{beginDt}' And '{endDt}'
  3327. Group By [Name]
  3328. Order By Count Desc");
  3329. var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
  3330. string sql2 = string.Format(@$"Select
  3331. sd.[Name],
  3332. Count(*) As [Count]
  3333. From Grp_DelegationInfo di
  3334. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  3335. Where di.Isdel = 0
  3336. And (
  3337. SELECT
  3338. CAST(
  3339. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3340. ) AS GroupSales
  3341. FROM
  3342. Fin_ForeignReceivables fr
  3343. WHERE
  3344. fr.IsDel = 0
  3345. AND di.Id = fr.Diid
  3346. AND AddingWay IN (0, 1, 2)
  3347. ) > 0
  3348. {userSql}
  3349. AND di.IsBid = 0
  3350. AND di.TeamName Not Like '%投标%'
  3351. And VisitDate Between '{beginDt}' And '{endDt}'
  3352. Group By [Name]
  3353. Order By Count Desc");
  3354. var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
  3355. return Ok(JsonView(true, "操作成功!", new
  3356. {
  3357. customerTypeData = customerTypeData,
  3358. clientGradeData = clientGradeData
  3359. }));
  3360. }
  3361. else if (_dto.PortType == 2 || _dto.PortType == 3)
  3362. {
  3363. var data = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql).ToListAsync();
  3364. return Ok(JsonView(true, "操作成功!", data, data.Count));
  3365. }
  3366. else return Ok(JsonView(false, MsgTips.Port));
  3367. }
  3368. /// <summary>
  3369. /// 市场部销售额
  3370. /// 接单排名
  3371. /// </summary>
  3372. /// <param name="_dto">市场部销售额请求dto</param>
  3373. /// <returns></returns>
  3374. [HttpPost("PostMarketingSalesOrderRanking")]
  3375. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3376. public async Task<IActionResult> PostMarketingSalesOrderRanking(MarketingSalesOrderRankingDto _dto)
  3377. {
  3378. #region 参数验证
  3379. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  3380. var validResult = await validationRules.ValidateAsync(_dto);
  3381. if (!validResult.IsValid)
  3382. {
  3383. var errors = new StringBuilder();
  3384. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3385. return Ok(JsonView(false, errors.ToString()));
  3386. }
  3387. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3388. #region 页面操作权限验证
  3389. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3390. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3391. #endregion
  3392. #endregion
  3393. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  3394. List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  3395. string userSql = "";
  3396. if (userIds.Count > 0)
  3397. {
  3398. userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
  3399. }
  3400. else return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  3401. string sql = string.Format(@$"Select
  3402. ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
  3403. u.CnName As UserName,
  3404. Count(*) As [Count]
  3405. From Grp_DelegationInfo di
  3406. Left Join Sys_Users u On di.JietuanOperator = u.Id
  3407. Where di.Isdel = 0
  3408. AND (
  3409. SELECT
  3410. CAST(
  3411. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3412. ) AS GroupSales
  3413. FROM
  3414. Fin_ForeignReceivables fr
  3415. WHERE
  3416. fr.IsDel = 0
  3417. AND di.Id = fr.Diid
  3418. AND AddingWay IN (0, 1, 2)
  3419. ) > 0
  3420. {userSql}
  3421. AND di.IsBid = 0
  3422. AND di.TeamName Not Like '%投标%'
  3423. AND VisitDate Between '{beginDt}' AND '{endDt}'
  3424. Group By CnName");
  3425. RefAsync<int> total = 0;
  3426. var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  3427. return Ok(JsonView(true, "操作成功!", rankingData, total));
  3428. }
  3429. /// <summary>
  3430. /// 市场部销售额
  3431. /// 团组列表、客户类型、客户等级、接单排名
  3432. /// </summary>
  3433. /// <param name="_dto">市场部销售额请求dto</param>
  3434. /// <returns></returns>
  3435. [HttpPost("PostMarketingSalesGroupItem")]
  3436. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3437. public async Task<IActionResult> PostMarketingSalesGroupItem(MarketingSalesGroupListDto _dto)
  3438. {
  3439. #region 参数验证
  3440. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  3441. var validResult = await validationRules.ValidateAsync(_dto);
  3442. if (!validResult.IsValid)
  3443. {
  3444. var errors = new StringBuilder();
  3445. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3446. return Ok(JsonView(false, errors.ToString()));
  3447. }
  3448. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3449. #region 页面操作权限验证
  3450. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3451. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3452. #endregion
  3453. #endregion
  3454. string userSql = "";
  3455. List<int> userIds = new List<int>();
  3456. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  3457. if (userIds.Count <= 0)
  3458. {
  3459. return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  3460. }
  3461. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  3462. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  3463. {
  3464. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  3465. }
  3466. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  3467. #region 团组List
  3468. string sql = string.Format(@$"SELECT
  3469. ROW_NUMBER() OVER (
  3470. ORDER BY
  3471. CollectionDays
  3472. ) AS RowNumber,
  3473. *
  3474. FROM
  3475. (
  3476. SELECT
  3477. di.Id,
  3478. di.TeamName,
  3479. di.ClientUnit,
  3480. di.ClientName,
  3481. di.VisitDate,
  3482. di.VisitPNumber,
  3483. di.JietuanOperator,
  3484. di.VisitEndDate,
  3485. (
  3486. SELECT
  3487. CAST(
  3488. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3489. ) AS GroupSales
  3490. FROM
  3491. Fin_ForeignReceivables
  3492. WHERE
  3493. IsDel = 0
  3494. AND di.Id = Diid
  3495. AND AddingWay IN (0, 1, 2)
  3496. ) AS GroupSales,
  3497. u.CnName AS GroupPickupUser,
  3498. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  3499. FROM
  3500. Grp_DelegationInfo di
  3501. WITH
  3502. (NoLock)
  3503. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  3504. WHERE
  3505. di.Isdel = 0
  3506. AND (
  3507. SELECT
  3508. CAST(
  3509. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3510. ) AS GroupSales
  3511. FROM
  3512. Fin_ForeignReceivables fr
  3513. WHERE
  3514. fr.IsDel = 0
  3515. AND di.Id = fr.Diid
  3516. AND AddingWay IN (0, 1, 2)
  3517. ) > 0
  3518. {userSql}
  3519. AND di.IsBid = 0
  3520. AND di.TeamName Not Like '%投标%'
  3521. AND VisitDate Between '{beginDt}' And '{endDt}'
  3522. ) Temp ");
  3523. RefAsync<int> total = 0;
  3524. var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  3525. #endregion
  3526. #region 客户类型、客户等级 统计
  3527. string sql1 = string.Format(@$"Select
  3528. sd.[Name],
  3529. Count(*) As [Count]
  3530. From Grp_DelegationInfo di
  3531. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  3532. Where di.Isdel = 0
  3533. And (
  3534. SELECT
  3535. CAST(
  3536. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3537. ) AS GroupSales
  3538. FROM
  3539. Fin_ForeignReceivables fr
  3540. WHERE
  3541. fr.IsDel = 0
  3542. AND di.Id = fr.Diid
  3543. AND AddingWay IN (0, 1, 2)
  3544. ) > 0
  3545. {userSql}
  3546. AND di.IsBid = 0
  3547. AND di.TeamName Not Like '%投标%'
  3548. And VisitDate Between '{beginDt}' And '{endDt}'
  3549. Group By [Name]
  3550. Order By Count Desc");
  3551. var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
  3552. string sql2 = string.Format(@$"Select
  3553. sd.[Name],
  3554. Count(*) As [Count]
  3555. From Grp_DelegationInfo di
  3556. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  3557. Where di.Isdel = 0
  3558. And (
  3559. SELECT
  3560. CAST(
  3561. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3562. ) AS GroupSales
  3563. FROM
  3564. Fin_ForeignReceivables fr
  3565. WHERE
  3566. fr.IsDel = 0
  3567. AND di.Id = fr.Diid
  3568. AND AddingWay IN (0, 1, 2)
  3569. ) > 0
  3570. {userSql}
  3571. AND di.IsBid = 0
  3572. AND di.TeamName Not Like '%投标%'
  3573. And VisitDate Between '{beginDt}' And '{endDt}'
  3574. Group By [Name]
  3575. Order By Count Desc");
  3576. var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
  3577. #endregion
  3578. #region 接单排名
  3579. string sql4 = string.Format(@$"Select
  3580. ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
  3581. u.CnName As UserName,
  3582. Count(*) As [Count]
  3583. From Grp_DelegationInfo di
  3584. Left Join Sys_Users u On di.JietuanOperator = u.Id
  3585. Where di.Isdel = 0
  3586. And (
  3587. SELECT
  3588. CAST(
  3589. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3590. ) AS GroupSales
  3591. FROM
  3592. Fin_ForeignReceivables fr
  3593. WHERE
  3594. fr.IsDel = 0
  3595. AND di.Id = fr.Diid
  3596. AND AddingWay IN (0, 1, 2)
  3597. ) > 0
  3598. {userSql}
  3599. AND di.IsBid = 0
  3600. AND di.TeamName Not Like '%投标%'
  3601. And VisitDate Between '{beginDt}' And '{endDt}'
  3602. Group By CnName");
  3603. var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql4).ToListAsync();
  3604. #endregion
  3605. var viewData = new
  3606. {
  3607. groupData = groupData,
  3608. groupTotal = total,
  3609. customerTypeData = customerTypeData,
  3610. clientGradeData = clientGradeData,
  3611. rankingData = rankingData
  3612. };
  3613. return Ok(JsonView(true, "操作成功!", viewData, total));
  3614. }
  3615. /// <summary>
  3616. /// 市场部销售额
  3617. /// 客户拜访列表
  3618. /// </summary>
  3619. /// <param name="_dto">市场部销售额请求dto</param>
  3620. /// <returns></returns>
  3621. [HttpPost("PostMarketingSalesVCList")]
  3622. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3623. public async Task<IActionResult> PostMarketingSalesVCList(MarketingSalesVCListDto _dto)
  3624. {
  3625. #region 参数验证
  3626. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  3627. var validResult = await validationRules.ValidateAsync(_dto);
  3628. if (!validResult.IsValid)
  3629. {
  3630. var errors = new StringBuilder();
  3631. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3632. return Ok(JsonView(false, errors.ToString()));
  3633. }
  3634. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3635. #region 页面操作权限验证
  3636. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3637. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3638. #endregion
  3639. #endregion
  3640. return Ok(await _visitingClientsRep._List(_dto.PortType, _dto.PageIndex, _dto.PageSize, _dto.DiId, _dto.Search));
  3641. }
  3642. /// <summary>
  3643. /// 市场部销售额
  3644. /// 客户拜访 操作(添加 Or 编辑)
  3645. /// </summary>
  3646. /// <param name="_dto">市场部销售额请求dto</param>
  3647. /// <returns></returns>
  3648. [HttpPost("PostMarketingSalesVCOperate")]
  3649. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3650. public async Task<IActionResult> PostMarketingSalesVCOperate(MarketingSalesVCOperrateDto _dto)
  3651. {
  3652. #region 参数验证
  3653. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  3654. var validResult = await validationRules.ValidateAsync(_dto);
  3655. if (!validResult.IsValid)
  3656. {
  3657. var errors = new StringBuilder();
  3658. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3659. return Ok(JsonView(false, errors.ToString()));
  3660. }
  3661. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3662. #region 页面操作权限验证
  3663. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3664. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3665. #endregion
  3666. #endregion
  3667. return Ok(await _visitingClientsRep._AddOrEdit(_dto));
  3668. }
  3669. /// <summary>
  3670. /// 市场部销售额
  3671. /// 客户拜访 Del
  3672. /// </summary>
  3673. /// <param name="_dto">市场部销售额请求dto</param>
  3674. /// <returns></returns>
  3675. [HttpPost("PostMarketingSalesVCDel")]
  3676. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3677. public async Task<IActionResult> PostMarketingSalesVCDel(MarketingSalesVCDelDto _dto)
  3678. {
  3679. return Ok(await _visitingClientsRep._Del(_dto.Id, _dto.UserId));
  3680. }
  3681. /// <summary>
  3682. /// 市场部销售额
  3683. /// 客户拜访 操作 save
  3684. /// </summary>
  3685. /// <param name="_dto">市场部销售额请求dto</param>
  3686. /// <returns></returns>
  3687. [HttpPost("PostMarketingSalesVCSave")]
  3688. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3689. public async Task<IActionResult> PostMarketingSalesVCSave(MarketingSalesVCSaveDto _dto)
  3690. {
  3691. #region 参数验证
  3692. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  3693. var validResult = await validationRules.ValidateAsync(_dto);
  3694. if (!validResult.IsValid)
  3695. {
  3696. var errors = new StringBuilder();
  3697. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3698. return Ok(JsonView(false, errors.ToString()));
  3699. }
  3700. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3701. #region 页面操作权限验证
  3702. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3703. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3704. #endregion
  3705. #endregion
  3706. return Ok(await _visitingClientsRep._Save(_dto));
  3707. }
  3708. #endregion
  3709. #region 日付报表
  3710. /// <summary>
  3711. /// 日付类型数据
  3712. /// </summary>
  3713. /// <param name="_dto"></param>
  3714. /// <returns></returns>
  3715. [HttpPost("DailypaymentTypeInit")]
  3716. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3717. public async Task<IActionResult> DailypaymentTypeInit(DailypaymentTypeInitDto _dto)
  3718. {
  3719. #region 参数验证
  3720. if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
  3721. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3722. #region 页面操作权限验证
  3723. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3724. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  3725. #endregion
  3726. #endregion
  3727. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  3728. {
  3729. var defaultParentIds = new List<int>() {
  3730. 48,// 人员费用
  3731. 49,// 办公费用
  3732. 50,// 销售费用
  3733. 51,// 其他费用
  3734. 55,// 大运会
  3735. };
  3736. var dailypaymentTypeData = await RedisRepository.RedisFactory
  3737. .CreateRedisRepository()
  3738. .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
  3739. var dailyTypeData = await _sqlSugar.Queryable<DailypaymentParentTypeView>()
  3740. .Includes(x => x.SubData)
  3741. .Where(x => defaultParentIds.Contains(x.Id))
  3742. .ToListAsync();
  3743. dailyTypeData.ForEach(x =>
  3744. {
  3745. x.SubData.ForEach(y =>
  3746. {
  3747. int currId = dailypaymentTypeData.Find(z => z == y.Id);
  3748. y.IsChecked = currId == 0 ? false : true;
  3749. });
  3750. });
  3751. var companyData = await _sqlSugar.Queryable<Sys_Company>()
  3752. .Where(x => x.IsDel == 0)
  3753. .Select(x => new { id = x.Id, name = x.CompanyName })
  3754. .ToListAsync();
  3755. return Ok(JsonView(true, "查询成功!", new { dailyTypeData = dailyTypeData, companyData = companyData }));
  3756. }
  3757. else
  3758. {
  3759. return Ok(JsonView(false, "查询失败"));
  3760. }
  3761. }
  3762. /// <summary>
  3763. /// 日付类型数据 Save
  3764. /// </summary>
  3765. /// <param name="_dto"></param>
  3766. /// <returns></returns>
  3767. [HttpPost("DailypaymentTypeDataSave")]
  3768. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3769. public async Task<IActionResult> DailypaymentTypeDataSave(DailypaymentTypeDataSaveDto _dto)
  3770. {
  3771. #region 参数验证
  3772. if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
  3773. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3774. #region 页面操作权限验证
  3775. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3776. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  3777. #endregion
  3778. #endregion
  3779. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  3780. {
  3781. if (_dto.TypeIds.Count < 1) return Ok(JsonView(false, "请传入需要保存的TypeIds"));
  3782. var res = await RedisRepository.RedisFactory
  3783. .CreateRedisRepository()
  3784. .StringSetAsync(
  3785. key: "DailypaymentTypeData",
  3786. _dto.TypeIds,
  3787. timeout: null);
  3788. if (!res) return Ok(JsonView(false, "操作失败"));
  3789. return Ok(JsonView(true, "操作成功!"));
  3790. }
  3791. else return Ok(JsonView(false, "操作失败"));
  3792. }
  3793. /// <summary>
  3794. /// 日付数据列表
  3795. /// </summary>
  3796. /// <param name="_dto"></param>
  3797. /// <returns></returns>
  3798. [HttpPost("DailypaymentRange")]
  3799. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3800. public async Task<IActionResult> DailypaymentRange(DailypaymentRangeDto _dto)
  3801. {
  3802. #region 参数验证
  3803. var validator = new DailypaymentRangeDtoValidator();
  3804. var validationRes = validator.Validate(_dto);
  3805. if (!validationRes.IsValid)
  3806. {
  3807. StringBuilder sb = new StringBuilder();
  3808. foreach (var item in validationRes.Errors)
  3809. {
  3810. sb.AppendLine(item.ErrorMessage);
  3811. }
  3812. return Ok(JsonView(false, sb.ToString()));
  3813. }
  3814. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3815. #region 页面操作权限验证
  3816. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3817. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  3818. #endregion
  3819. #endregion
  3820. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  3821. {
  3822. DateTime _beginDt = Convert.ToDateTime($"{_dto.BeginDt} 00:00:00"),
  3823. _endDt = Convert.ToDateTime($"{_dto.EndDt} 23:59:59");
  3824. var sqlWhere = string.Format(@" And dfp.CreateTime Between '{0}' And '{1}'", _beginDt, _endDt);
  3825. var dailypaymentTypeData = await RedisRepository.RedisFactory
  3826. .CreateRedisRepository()
  3827. .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
  3828. var sql = string.Format(@"
  3829. Select
  3830. dfp.Id,
  3831. dfp.Instructions,
  3832. dfp.PriceTypeId,
  3833. sd1.Name As FeeType,
  3834. dfp.TransferTypeId,
  3835. sd2.Name As TransferType,
  3836. dfp.SumPrice,
  3837. dfp.FAuditDate,
  3838. dfp.MAuditDate,
  3839. dfp.CompanyId,
  3840. c.CompanyName,
  3841. dfp.CreateUserId As ApplicantId,
  3842. u.CnName As Applicant,
  3843. dfp.CreateTime As ApplicantDt,
  3844. dfp.Instructions+u.CnName As ViewStr
  3845. From Fin_DailyFeePayment dfp
  3846. Left Join Sys_Users u On dfp.CreateUserId = u.Id
  3847. Left Join Sys_SetData sd1 On dfp.TransferTypeId = sd1.Id
  3848. Left Join Sys_Company c On dfp.CompanyId = c.Id
  3849. Left Join Sys_SetData sd2 On dfp.PriceTypeId = sd2.Id
  3850. Where dfp.IsDel = 0 And dfp.IsPay = 1
  3851. ");//--Order By dfp.CreateTime Desc
  3852. if (_dto.Type == 1) //data
  3853. {
  3854. RefAsync<int> total = 0;
  3855. var _view = await _sqlSugar.SqlQueryable<DailyFeePaymentRangeView>(sql)
  3856. .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
  3857. .WhereIF(dailypaymentTypeData.Count > 0,
  3858. x => dailypaymentTypeData.Contains(x.PriceTypeId))
  3859. .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
  3860. .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
  3861. .OrderByDescending(x => x.ApplicantDt)
  3862. .ToPageListAsync(
  3863. pageNumber: _dto.PageIndex,
  3864. pageSize: _dto.PageSize,
  3865. totalNumber: total
  3866. );
  3867. _sqlSugar.ThenMapper(_view, x =>
  3868. {
  3869. x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
  3870. .SetContext(x1 => x1.DFPId, () => x.Id, x)
  3871. .ToList();
  3872. });
  3873. //单独处理
  3874. return Ok(JsonView(true, "操作成功!", new { data = _view, total = _view.Sum(x => x.SumPrice) }, total));
  3875. }
  3876. else if (_dto.Type == 2) //view
  3877. {
  3878. var _view = await _sqlSugar.SqlQueryable<ExcelView>(sql)
  3879. .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
  3880. .WhereIF(dailypaymentTypeData.Count > 0,
  3881. x => dailypaymentTypeData.Contains(x.PriceTypeId))
  3882. .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
  3883. .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
  3884. .OrderByDescending(x => x.ApplicantDt)
  3885. .ToPageListAsync(
  3886. pageNumber: 1,
  3887. pageSize: 99999
  3888. );
  3889. _sqlSugar.ThenMapper(_view, x =>
  3890. {
  3891. x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
  3892. .SetContext(x1 => x1.DFPId, () => x.Id, x)
  3893. .ToList();
  3894. string str = "";
  3895. int index = 1;
  3896. foreach (var item in x.Contents)
  3897. {
  3898. string str1 = $"{index}、费用名称:[{item.PriceName}] 单价:[{item.Price:#0.00}] 数量:[{item.Quantity:#0.00}] 小计:[{item.ItemTotal:#0.00}] 备注:[{item.Remark}]";
  3899. if (index == x.Contents.Count) str += str1;
  3900. else str += str1 + "\r\n";
  3901. index++;
  3902. }
  3903. x.ContentStr = str;
  3904. });
  3905. if (_view.Count > 0)
  3906. {
  3907. //DataTable dt = GeneralMethod.
  3908. DataTable dt = CommonFun.GetDataTableFromIList(_view);
  3909. dt.TableName = $"_view";
  3910. decimal total = _view.Sum(x => x.SumPrice);
  3911. WorkbookDesigner designer = new WorkbookDesigner();
  3912. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/日付报表模板.xls");
  3913. designer.SetDataSource(dt);
  3914. designer.SetDataSource("Total", total);
  3915. designer.Workbook.Worksheets[0].Name = "日付报表";
  3916. designer.Process();
  3917. string fileName = $"DailyPayment/日付报表{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
  3918. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  3919. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  3920. return Ok(JsonView(true, "操作成功", new { url = rst }));
  3921. }
  3922. return Ok(JsonView(true, ",暂无数据"));
  3923. }
  3924. return Ok(JsonView(false, "操作失败"));
  3925. }
  3926. else return Ok(JsonView(false, "操作失败"));
  3927. }
  3928. #endregion
  3929. #region 统计模块
  3930. /// <summary>
  3931. /// 同比
  3932. /// 营业额(今年和去年的)、成本支出(今年和去年的)、毛利润(今年和去年的)
  3933. /// </summary>
  3934. /// <param name="_dto">市场部销售额请求dto</param>
  3935. /// <returns></returns>
  3936. [HttpPost("StatisticsYOY")]
  3937. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3938. public async Task<IActionResult> StatisticsYOY(YOYDto _dto)
  3939. {
  3940. //同比增长率 = (本期 - 同期) / 同期 * 100%;
  3941. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  3942. string beginDt = $"{_dto.Year - 1}-01-01 00:00:00",
  3943. endDt = $"{_dto.Year}-12-31 23:59:59";
  3944. string sql = string.Format(@"
  3945. SELECT
  3946. di.Id,
  3947. di.TeamName,
  3948. di.VisitDate,
  3949. YEAR(di.VisitDate) AS YEAR,
  3950. MONTH(di.VisitDate) AS MONTH,
  3951. (
  3952. SELECT
  3953. CAST(SUM(ItemSumPrice * Rate) AS DECIMAL(12, 2))
  3954. FROM
  3955. Fin_ForeignReceivables
  3956. WHERE
  3957. IsDel = 0
  3958. AND AddingWay IN (0, 1, 2)
  3959. AND di.Id = Diid
  3960. ) AS SaleAmount,
  3961. (
  3962. SELECT
  3963. CAST(
  3964. SUM(
  3965. (
  3966. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  3967. )
  3968. ) AS DECIMAL(12, 2)
  3969. )
  3970. FROM
  3971. Grp_AirTicketReservations atr
  3972. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  3973. AND ccp.CTable = 85
  3974. AND atr.Id = ccp.CId
  3975. WHERE
  3976. atr.IsDel = 0
  3977. AND ccp.IsAuditGM = 1
  3978. AND ccp.IsPay = 1
  3979. AND di.Id = atr.DiId
  3980. ) AirTicketAmount,
  3981. (
  3982. SELECT
  3983. CAST(
  3984. SUM(
  3985. (
  3986. ctggr.ServiceQuotedPrice * (ccp.PayPercentage / 100) * ccp.DayRate
  3987. )
  3988. ) AS DECIMAL(12, 2)
  3989. )
  3990. FROM
  3991. Grp_CarTouristGuideGroundReservations ctggr
  3992. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  3993. AND ccp.CTable = 79
  3994. AND ctggr.Id = ccp.CId
  3995. WHERE
  3996. ctggr.IsDel = 0
  3997. AND ccp.IsAuditGM = 1
  3998. AND ccp.IsPay = 1
  3999. AND di.Id = ctggr.DiId
  4000. ) AS OPAmount,
  4001. (
  4002. SELECT
  4003. CAST(SUM((ccp.PayMoney * ccp.DayRate)) AS DECIMAL(12, 2))
  4004. FROM
  4005. Grp_DecreasePayments dp
  4006. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  4007. AND ccp.CTable = 98
  4008. AND dp.Id = ccp.CId
  4009. WHERE
  4010. dp.IsDel = 0
  4011. AND ccp.Ctable = 98
  4012. AND ccp.IsAuditGM = 1
  4013. AND ccp.IsPay = 1
  4014. AND di.Id = dp.Diid
  4015. ) AS OtherCostAmount,
  4016. (
  4017. SELECT
  4018. CAST(
  4019. SUM(
  4020. (
  4021. (ccp.PayMoney * ccp.DayRate)
  4022. )
  4023. ) AS DECIMAL(12, 2)
  4024. )
  4025. FROM
  4026. Grp_VisaInfo vi
  4027. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  4028. AND ccp.CTable = 80
  4029. AND vi.Id = ccp.CId
  4030. WHERE
  4031. vi.IsDel = 0
  4032. AND ccp.IsAuditGM = 1
  4033. AND ccp.IsPay = 1
  4034. AND di.Id = vi.DIId
  4035. ) AS VisaAmount,
  4036. (
  4037. SELECT
  4038. CAST(
  4039. SUM(
  4040. (ccp.PayMoney * ccp.DayRate)
  4041. ) AS DECIMAL(12, 2)
  4042. )
  4043. FROM
  4044. Grp_InvitationOfficialActivities ioa
  4045. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  4046. AND ccp.CTable = 81
  4047. AND ioa.Id = ccp.CId
  4048. WHERE
  4049. ioa.IsDel = 0
  4050. AND ccp.IsAuditGM = 1
  4051. AND ccp.IsPay = 1
  4052. AND di.Id = ioa.Diid
  4053. ) AS OAAmount,
  4054. (
  4055. SELECT
  4056. CAST(
  4057. SUM(
  4058. (ccp.PayMoney * ccp.DayRate)
  4059. ) AS DECIMAL(12, 2)
  4060. )
  4061. FROM
  4062. Grp_Customers ic
  4063. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  4064. AND ccp.CTable = 82
  4065. AND ic.Id = ccp.CId
  4066. WHERE
  4067. ic.IsDel = 0
  4068. AND ccp.IsAuditGM = 1
  4069. AND ccp.IsPay = 1
  4070. AND di.Id = ic.DiId
  4071. ) AS InsureAmount,
  4072. (
  4073. SELECT
  4074. CAST(
  4075. SUM(
  4076. (ccp.PayMoney * ccp.DayRate)
  4077. ) AS DECIMAL(12, 2)
  4078. )
  4079. FROM
  4080. Grp_HotelReservations hr
  4081. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  4082. WHERE
  4083. hr.IsDel = 0
  4084. AND ccp.IsDel = 0
  4085. AND ccp.CTable = 76
  4086. AND ccp.IsAuditGM = 1
  4087. AND ccp.PayMoney <> 0
  4088. AND ccp.IsPay = 1
  4089. AND di.Id = hr.DiId
  4090. ) AS HotelAmount,
  4091. (
  4092. SELECT
  4093. CAST(
  4094. SUM((gec.PriceSum * gec.Coefficient * ccp.DayRate)) AS DECIMAL(12, 2)
  4095. )
  4096. FROM
  4097. OA2023DB.dbo.Fin_GroupExtraCost gec
  4098. INNER JOIN Grp_CreditCardPayment ccp ON gec.Id = ccp.CId
  4099. WHERE
  4100. ccp.IsDel = 0
  4101. AND ccp.CTable = 1015
  4102. AND ccp.IsAuditGM = 1
  4103. AND ccp.IsPay = 1
  4104. AND di.Id = gec.DiId
  4105. ) AS ExcessAmount,
  4106. (
  4107. SELECT
  4108. CAST(
  4109. SUM(
  4110. (ccp.PayMoney * ccp.DayRate)
  4111. ) AS DECIMAL(12, 2)
  4112. )
  4113. FROM
  4114. Fin_PaymentRefundAndOtherMoney prom
  4115. INNER JOIN Grp_CreditCardPayment ccp ON prom.DiId = ccp.DIId
  4116. AND prom.Id = ccp.CId
  4117. WHERE
  4118. prom.IsDel = 0
  4119. AND prom.PayType = 1
  4120. AND ccp.CTable = 285
  4121. AND ccp.IsAuditGM = 1
  4122. AND ccp.IsPay = 1
  4123. AND di.Id = prom.DiId
  4124. ) AS SKTHAmount
  4125. FROM
  4126. Grp_DelegationInfo di
  4127. WHERE
  4128. di.IsDel = 0
  4129. AND di.TeamDid IN (38,39,40,1048)
  4130. AND di.VisitDate BETWEEN '{0}' AND '{1}'
  4131. ORDER BY
  4132. di.VisitDate
  4133. ", beginDt, endDt);
  4134. var data = await _sqlSugar.SqlQueryable<StatisticsYOYView>(sql).ToListAsync();
  4135. var thisYearData = data.Where(x => x.Year == _dto.Year).ToList();
  4136. var lastYearData = data.Where(x => x.Year == (_dto.Year - 1)).ToList();
  4137. List<YOYReturnView> salesYOYData = new List<YOYReturnView>();
  4138. List<YOYReturnView> costYOYData = new List<YOYReturnView>();
  4139. List<YOYReturnView> grossProfitYOYData = new List<YOYReturnView>();
  4140. int monthIndex = 1;
  4141. while (monthIndex < 13)
  4142. {
  4143. var thisMonthData = thisYearData.Where(x => x.Month == monthIndex).ToList();
  4144. var lastMonthData = lastYearData.Where(x => x.Month == monthIndex).ToList();
  4145. var thisGroupIds = thisMonthData.Select(x => x.Id).ToList();
  4146. var lastGroupIds = lastMonthData.Select(x => x.Id).ToList();
  4147. decimal thisSalesAmount = thisMonthData.Sum(x => x?.SaleAmount ?? 0.00M),
  4148. lastSalesAmount = lastMonthData.Sum(x => x?.SaleAmount ?? 0.00M),
  4149. thisCostAmount = thisMonthData.Sum(x => x?.CostAmount ?? 0.00M),
  4150. lastCostAmount = lastMonthData.Sum(x => x?.CostAmount ?? 0.00M),
  4151. thisgrossProfitAmount = thisMonthData.Sum(x => x?.GrossProfitAmount ?? 0.00M),
  4152. lastgrossProfitAmount = lastMonthData.Sum(x => x?.GrossProfitAmount ?? 0.00M);
  4153. salesYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisSalesAmount, lastSalesAmount, thisGroupIds, lastGroupIds));
  4154. costYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisCostAmount, lastCostAmount, thisGroupIds, lastGroupIds));
  4155. grossProfitYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisgrossProfitAmount, lastgrossProfitAmount, thisGroupIds, lastGroupIds));
  4156. monthIndex++;
  4157. }
  4158. salesYOYData = salesYOYData.OrderBy(x => x.Month).ToList();
  4159. costYOYData = costYOYData.OrderBy(x => x.Month).ToList();
  4160. grossProfitYOYData = grossProfitYOYData.OrderBy(x => x.Month).ToList();
  4161. return Ok(JsonView(true, "操作成功!", new { salesYOYData = salesYOYData, costYOYData = costYOYData, grossProfitYOYData = grossProfitYOYData }));
  4162. }
  4163. /// <summary>
  4164. /// 国交数据统计-机票相关
  4165. /// 机票票数、机票到达地、预订平台
  4166. /// </summary>
  4167. /// <param name="_dto"></param>
  4168. /// <returns></returns>
  4169. [HttpPost("StatisticsAirTicket")]
  4170. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4171. public async Task<IActionResult> StatisticsAirTicket(YOYDto _dto)
  4172. {
  4173. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4174. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4175. endDt = $"{_dto.Year}-12-31 23:59:59";
  4176. string sql = string.Format(@"
  4177. SELECT
  4178. atr.DIId,
  4179. atr.FlightsDate,
  4180. YEAR(atr.FlightsDate) AS YEAR,
  4181. MONTH(atr.FlightsDate) AS MONTH,
  4182. atr.CType,
  4183. sd.Name As CTypeName,
  4184. atr.FlightsCity,
  4185. atr.ClientNum,
  4186. atr.ClientName,
  4187. di.TeamName As 'GroupName',
  4188. CASE
  4189. WHEN ccp.Payee = '' OR ccp.Payee IS NULL THEN '未知'
  4190. ELSE ccp.Payee
  4191. END AS 'Platform'
  4192. FROM
  4193. Grp_AirTicketReservations atr
  4194. INNER JOIN Grp_CreditCardPayment ccp ON atr.Id = ccp.CId
  4195. AND ccp.IsDel = 0
  4196. AND CTable = 85
  4197. INNER JOIN Grp_DelegationInfo di ON atr.DIId = di.Id
  4198. LEFT JOIN Sys_SetData sd On atr.CType = sd.Id
  4199. WHERE
  4200. atr.IsDel = 0
  4201. AND di.TeamDid IN (38,39,40,1048)
  4202. AND atr.CType IN(457,458,459,460,574,575)
  4203. AND CHARINDEX('行程单',atr.ClientName) = 0
  4204. AND CHARINDEX('返点',atr.ClientName) = 0
  4205. AND CHARINDEX('-1',atr.ClientName) = 0
  4206. AND ccp.IsPay = 1
  4207. AND atr.FlightsDate BETWEEN '{0}' AND '{1}'
  4208. ORDER BY atr.FlightsDate
  4209. ", beginDt, endDt);
  4210. var data = await _sqlSugar.SqlQueryable<StatisticsAirTicketView>(sql).ToListAsync();
  4211. var groupIds = data.Select(x => x.DIId).ToList();
  4212. //处理城市数据
  4213. var threeCodeData = await _sqlSugar.Queryable<Res_ThreeCode>().Where(x => x.IsDel == 0).ToListAsync();
  4214. //处理团组名称
  4215. var groupNames = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => groupIds.Contains(x.Id)).Select(x => new { Id = x.Id, GroupName = x.TeamName }).ToListAsync();
  4216. data.ForEach(x =>
  4217. {
  4218. string cityName = "";
  4219. if (!string.IsNullOrEmpty(x.FlightsCity))
  4220. {
  4221. string cityCode = x.FlightsCity.Replace("-", "").Replace("/", "");
  4222. int cityNum = cityCode.Length / 3;
  4223. if (cityCode.Length % 3 == 0)
  4224. {
  4225. for (int i = 0; i < cityNum; i++)
  4226. {
  4227. string code = "";
  4228. if (i == 0) code = cityCode.Substring(0, 3);
  4229. else code = cityCode.Substring(i * 3, 3);
  4230. if (!string.IsNullOrEmpty(code))
  4231. {
  4232. if (i == cityNum - 1)
  4233. {
  4234. cityName += threeCodeData.Find(x1 => x1.Three.Equals(code))?.City ?? "";
  4235. }
  4236. else
  4237. {
  4238. var str1 = threeCodeData.Find(x1 => x1.Three.Equals(code))?.City ?? "";
  4239. cityName += str1 + "、";
  4240. }
  4241. }
  4242. }
  4243. }
  4244. }
  4245. x.FlightsCityName = cityName;
  4246. });
  4247. var airTicketNumData = new List<AirTicketReturnView>();
  4248. var airTicketAreaData = new List<AirTicketCityReturnView>();
  4249. int monthIndex = 1;
  4250. while (monthIndex < 13)
  4251. {
  4252. var monthData = data.Where(x => x.Month == monthIndex).ToList();
  4253. //机票票数处理
  4254. int airticket_quantity = monthData.Sum(x => x.ClientNum);
  4255. var linkGroupIds = monthData.Select(x => x.DIId).ToList();
  4256. List<AitTicketInfo> aitTicketInfos = new List<AitTicketInfo>();
  4257. foreach (var item in monthData)
  4258. {
  4259. string groupName = groupNames.Find(x => item.DIId == x.Id)?.GroupName ?? "";
  4260. aitTicketInfos.Add(new AitTicketInfo(item.DIId, groupName, item.ClientNum));
  4261. }
  4262. var aitTicketInfosGroupBy = aitTicketInfos.GroupBy(x => x.Id);
  4263. List<AitTicketInfo> aitTicketInfos1 = new List<AitTicketInfo>();
  4264. foreach (var item in aitTicketInfosGroupBy)
  4265. {
  4266. aitTicketInfos1.Add(new AitTicketInfo(item.Key, item.First().GroupName, item.Sum(x => x.Quantity)));
  4267. }
  4268. aitTicketInfos1 = aitTicketInfos1.OrderBy(x => x.Quantity).ToList();
  4269. linkGroupIds = linkGroupIds.Distinct().ToList();
  4270. airTicketNumData.Add(new AirTicketReturnView(_dto.Year, monthIndex, airticket_quantity, aitTicketInfos1, linkGroupIds));
  4271. //机票城市处理
  4272. //城市处理
  4273. var airTicketCityInfos = new List<string>();
  4274. foreach (var item in monthData)
  4275. {
  4276. if (!string.IsNullOrEmpty(item.FlightsCityName))
  4277. {
  4278. if (item.FlightsCityName.Contains("、"))
  4279. {
  4280. var cityArray = item.FlightsCityName.Split("、").ToList();
  4281. foreach (var item1 in cityArray)
  4282. {
  4283. if (!string.IsNullOrEmpty(item1))
  4284. {
  4285. airTicketCityInfos.Add(item1);
  4286. }
  4287. }
  4288. }
  4289. else
  4290. {
  4291. airTicketCityInfos.Add(item.FlightsCityName);
  4292. }
  4293. }
  4294. }
  4295. //int quantity1 = airTicketCityInfos.Count;
  4296. int city_totalquantity = 0;
  4297. var airTicketCityInfosGroupby = airTicketCityInfos.GroupBy(x => x);
  4298. var airTicketCityInfos1 = new List<AirTicketCityInfo>();
  4299. foreach (var item in airTicketCityInfosGroupby)
  4300. {
  4301. var city_quantity = item.ToList().Count;
  4302. city_totalquantity += city_quantity;
  4303. airTicketCityInfos1.Add(new AirTicketCityInfo(item.Key, city_quantity));
  4304. }
  4305. airTicketCityInfos1 = airTicketCityInfos1.OrderByDescending(x => x.Quantity).ToList();
  4306. airTicketAreaData.Add(new AirTicketCityReturnView(_dto.Year, monthIndex, city_totalquantity, airTicketCityInfos1, linkGroupIds));
  4307. monthIndex++;
  4308. }
  4309. var airTicketPlatformData = data.GroupBy(g => g.Platform)
  4310. .Select(g => new
  4311. {
  4312. platform = g.Key,
  4313. total = g.Sum(x => x.ClientNum),
  4314. children = g.GroupBy(g1 => g1.DIId)
  4315. .Select(g1 => new
  4316. {
  4317. diId = g1.Key,
  4318. groupName = g1.FirstOrDefault()?.GroupName ?? "-",
  4319. total = g1.Sum(x1 => x1.ClientNum),
  4320. children = g1.Select(x1 => new
  4321. {
  4322. //diId = x1.DIId,
  4323. //groupName = x1.GroupName,
  4324. flightsCityName = x1.FlightsCityName,
  4325. total = x1.ClientNum
  4326. })
  4327. .ToList()
  4328. })
  4329. .OrderByDescending(x1 => x1.total)
  4330. .ToList()
  4331. })
  4332. .OrderByDescending(x => x.total)
  4333. .ToList();
  4334. return Ok(JsonView(true, "操作成功!", new
  4335. {
  4336. airTicketNumData = airTicketNumData,
  4337. airTicketAreaData = airTicketAreaData,
  4338. airTicketPlatformData = airTicketPlatformData
  4339. }));
  4340. }
  4341. /// <summary>
  4342. /// 国交数据统计-酒店
  4343. /// 国家TOP10、地区TOP10、预订平台
  4344. /// </summary>
  4345. /// <param name="_dto"></param>
  4346. /// <returns></returns>
  4347. [HttpPost("StatisticsHotel")]
  4348. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4349. public async Task<IActionResult> StatisticsHotel(YOYDto _dto)
  4350. {
  4351. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4352. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4353. endDt = $"{_dto.Year}-12-31 23:59:59";
  4354. string sql = string.Format(@"
  4355. SELECT
  4356. hr.DIId,
  4357. CASE
  4358. WHEN ntf.Country IS NULL THEN '未选择'
  4359. ELSE ntf.Country
  4360. END AS 'Country',
  4361. hr.City,
  4362. hr.HotelName,
  4363. sd.Name AS BookinSite,
  4364. hr.CheckInDate,
  4365. YEAR(hr.CheckInDate) AS YEAR,
  4366. MONTH(hr.CheckInDate) AS MONTH,
  4367. hr.CheckOutDate,
  4368. hr.SingleRoomCount,
  4369. hr.DoubleRoomCount,
  4370. hr.SuiteRoomCount,
  4371. hr.OtherRoomCount
  4372. FROM
  4373. Grp_HotelReservations hr
  4374. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  4375. AND ccp.IsDel = 0
  4376. AND CTable = 76
  4377. INNER JOIN Grp_DelegationInfo di ON hr.DiId = di.Id
  4378. LEFT JOIN Sys_SetData sd ON hr.ReservationsWebsite = sd.Id
  4379. LEFT JOIN Grp_NationalTravelFee ntf ON hr.AreaId = ntf.Id
  4380. WHERE
  4381. hr.IsDel = 0
  4382. AND di.TeamDid IN (38,39,40,1048)
  4383. AND ccp.IsPay = 1
  4384. AND (
  4385. hr.SingleRoomCount > 0
  4386. OR hr.DoubleRoomCount > 0
  4387. OR hr.SuiteRoomCount > 0
  4388. OR hr.OtherRoomCount > 0
  4389. )
  4390. AND CHARINDEX('早餐',hr.HotelName) = 0
  4391. AND CHARINDEX('晚餐',hr.HotelName) = 0
  4392. AND CHARINDEX('升级',hr.HotelName) = 0
  4393. AND CHARINDEX('饮料茶水费',hr.HotelName) = 0
  4394. AND CHARINDEX('城市税',hr.HotelName) = 0
  4395. AND CHARINDEX('退款',hr.HotelName) = 0
  4396. AND CHARINDEX('返现',hr.HotelName) = 0
  4397. AND CHARINDEX('会议室',hr.HotelName) = 0
  4398. AND CHARINDEX('迷你吧消费',hr.HotelName) = 0
  4399. AND CHARINDEX('运费',hr.HotelName) = 0
  4400. AND CHARINDEX('地接',hr.HotelName) = 0
  4401. AND CHARINDEX('损失',hr.HotelName) = 0
  4402. AND CHARINDEX('补差',hr.HotelName) = 0
  4403. AND hr.CheckInDate BETWEEN CONVERT(datetime,'{0}') AND CONVERT(datetime,'{1}')
  4404. ORDER BY
  4405. hr.CheckInDate
  4406. ", beginDt, endDt);
  4407. var data = await _sqlSugar.SqlQueryable<StatisticsHotelView>(sql).ToListAsync();
  4408. var hotelCountryGroupByData = data.GroupBy(x => x.Country)
  4409. .Select(g => new
  4410. {
  4411. Country = g.Key,
  4412. BookingRoomNum = g.Sum(x => x.RoomTotal),
  4413. hotelData = g.GroupBy(x => x.HotelName)
  4414. .Select(g1 => new
  4415. {
  4416. hotelName = g1.Key,
  4417. roomNights = g1.Sum(x => x.RoomNights),
  4418. roomTotal = g1.Sum(x => x.RoomTotal),
  4419. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  4420. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  4421. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  4422. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  4423. })
  4424. .ToList(),
  4425. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  4426. })
  4427. .OrderByDescending(x => x.BookingRoomNum)
  4428. .Take(10)
  4429. .ToList();
  4430. var hotelData = data.OrderBy(x => x.CityStr).ToList();
  4431. var hotelCityGroupByData = data.GroupBy(x => x.CityStr)
  4432. .Select(g => new
  4433. {
  4434. city = g.Key,
  4435. BookingRoomNum = g.Sum(x => x.RoomTotal),
  4436. hotelData = g.GroupBy(x => x.HotelName)
  4437. .Select(g1 => new
  4438. {
  4439. hotelName = g1.Key,
  4440. roomNights = g1.Sum(x => x.RoomNights),
  4441. roomTotal = g1.Sum(x => x.RoomTotal),
  4442. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  4443. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  4444. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  4445. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  4446. })
  4447. .ToList(),
  4448. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  4449. })
  4450. .OrderByDescending(x => x.BookingRoomNum)
  4451. .Take(10)
  4452. .ToList();
  4453. var hotelPlatformGroupByData = data.GroupBy(x => x.BookinSite)
  4454. .Select(g => new
  4455. {
  4456. Platform = g.Key,
  4457. BookingRoomNum = g.Sum(x => x.RoomTotal),
  4458. hotelData = g.GroupBy(x => x.HotelName)
  4459. .Select(g1 => new
  4460. {
  4461. hotelName = g1.Key,
  4462. roomNights = g1.Sum(x => x.RoomNights),
  4463. roomTotal = g1.Sum(x => x.RoomTotal),
  4464. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  4465. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  4466. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  4467. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  4468. })
  4469. .ToList(),
  4470. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  4471. })
  4472. .OrderByDescending(x => x.BookingRoomNum)
  4473. .ToList();
  4474. return Ok(JsonView(true, "操作成功!", new { hotelCountryGroupByData = hotelCountryGroupByData, hotelCityData = hotelCityGroupByData, hotelPlatformData = hotelPlatformGroupByData }));
  4475. }
  4476. /// <summary>
  4477. /// 国交数据统计
  4478. /// 商邀邀请国家数量TOP10
  4479. /// </summary>
  4480. /// <param name="_dto"></param>
  4481. /// <returns></returns>
  4482. [HttpPost("StatisticsInvitation")]
  4483. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4484. public async Task<IActionResult> StatisticsInvitation(YOYDto _dto)
  4485. {
  4486. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4487. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4488. endDt = $"{_dto.Year}-12-31 23:59:59";
  4489. string sql = string.Format(@"
  4490. SELECT
  4491. oa.DiId,
  4492. di.TeamName AS GroupName,
  4493. oa.Country,
  4494. oa.Area AS City,
  4495. oa.Client,
  4496. oa.Date
  4497. FROM
  4498. Res_OfficialActivities oa
  4499. LEFT JOIN Grp_DelegationInfo di ON oa.DiId = di.Id
  4500. WHERE
  4501. oa.IsDel = 0
  4502. AND oa.Date BETWEEN '{0}' AND '{1}'
  4503. ", beginDt, endDt);
  4504. var data = await _sqlSugar.SqlQueryable<StatisticsInvitation_HW>(sql).ToListAsync();
  4505. var groupByCountry = data.GroupBy(x => x.Country)
  4506. .Select(g => new
  4507. {
  4508. Country = g.Key,
  4509. TimeNum = g.Count(),
  4510. LinkGroupIds = g.Select(x => x.GroupName).Distinct().ToList()
  4511. })
  4512. .OrderByDescending(x => x.TimeNum)
  4513. .Take(10)
  4514. .ToList();
  4515. var groupByClient = data.GroupBy(x => x.Client)
  4516. .Select(g => new
  4517. {
  4518. Country = g.Key,
  4519. TimeNum = g.Count(),
  4520. LinkGroupIds = g.Select(x => x.GroupName).Distinct().ToList()
  4521. })
  4522. .OrderByDescending(x => x.TimeNum)
  4523. .Take(10)
  4524. .ToList();
  4525. return Ok(JsonView(true, "操作成功!", new { groupByCountry = groupByCountry, groupByClient = groupByClient }));
  4526. }
  4527. /// <summary>
  4528. /// 会务数据统计
  4529. /// 会务城市TOP10排序
  4530. /// </summary>
  4531. /// <param name="_dto"></param>
  4532. /// <returns></returns>
  4533. [HttpPost("StatisticsConferenceCity")]
  4534. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4535. public async Task<IActionResult> StatisticsConferenceCity(YOYDto _dto)
  4536. {
  4537. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4538. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4539. endDt = $"{_dto.Year}-12-31 23:59:59";
  4540. string sql = string.Format(@"
  4541. SELECT
  4542. ioa.DiId,
  4543. ioa.InviterArea AS Country
  4544. FROM
  4545. Grp_InvitationOfficialActivities ioa
  4546. INNER JOIN Grp_CreditCardPayment ccp ON ioa.Id = ccp.CId
  4547. AND ccp.IsDel = 0
  4548. AND ccp.CTable = 81
  4549. INNER JOIN Grp_DelegationInfo di ON ioa.DiId = di.Id
  4550. WHERE
  4551. ioa.IsDel = 0
  4552. AND di.TeamDid IN (102,248,302,691,762,1047)
  4553. AND ccp.IsPay = 1
  4554. AND ioa.CreateTime BETWEEN '{0}' AND '{1}'
  4555. ", beginDt, endDt);
  4556. var data = await _sqlSugar.SqlQueryable<StatisticsInvitation>(sql).ToListAsync();
  4557. var groupByData = data.GroupBy(x => x.Country)
  4558. .Select(g => new
  4559. {
  4560. Country = g.Key,
  4561. TimeNum = g.Count(),
  4562. LinkGroupIds = g.Select(x => x.DIId).ToList()
  4563. })
  4564. .OrderByDescending(x => x.TimeNum)
  4565. .Take(10)
  4566. .ToList();
  4567. return Ok(JsonView(true, "操作成功!", groupByData));
  4568. }
  4569. /// <summary>
  4570. /// 团组数据统计
  4571. /// 团组合作前十的客户TOP10排序
  4572. /// </summary>
  4573. /// <param name="_dto"></param>
  4574. /// <returns></returns>
  4575. [HttpPost("StatisticsCooperativeCustomer")]
  4576. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4577. public async Task<IActionResult> StatisticsCooperativeCustomer(YOYDto _dto)
  4578. {
  4579. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4580. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4581. endDt = $"{_dto.Year}-12-31 23:59:59";
  4582. DateTime _beginDt = Convert.ToDateTime(beginDt),
  4583. _endDt = Convert.ToDateTime(endDt);
  4584. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  4585. .Where(x => x.IsDel == 0)
  4586. //.Where(x => x.IsSure == 1)
  4587. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  4588. .ToListAsync();
  4589. var groupInfos1 = groupInfos.GroupBy(x => x.ClientName);
  4590. var view = groupInfos1.Select(x =>
  4591. new
  4592. {
  4593. clienName = x.Key,
  4594. clientUnit = x.FirstOrDefault()?.ClientUnit ?? "",
  4595. visitsNum = x.Count()
  4596. }
  4597. )
  4598. .OrderByDescending(x => x.visitsNum)
  4599. .Take(10)
  4600. .ToList();
  4601. return Ok(JsonView(true, "操作成功!", view));
  4602. }
  4603. /// <summary>
  4604. /// 团组数据统计
  4605. /// 已出团客户单位的类型比例图(饼状图-政府团、企业团等)
  4606. /// </summary>
  4607. /// <param name="_dto"></param>
  4608. /// <returns></returns>
  4609. [HttpPost("StatisticsCooperativeCustomerType")]
  4610. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4611. public async Task<IActionResult> StatisticsCooperativeCustomerType(YOYDto _dto)
  4612. {
  4613. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4614. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4615. endDt = $"{_dto.Year}-12-31 23:59:59";
  4616. DateTime _beginDt = Convert.ToDateTime(beginDt),
  4617. _endDt = Convert.ToDateTime(endDt);
  4618. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  4619. .LeftJoin<Sys_SetData>((di, sd) => di.TeamDid == sd.Id)
  4620. .Where((di, sd) => di.IsDel == 0)
  4621. .Where((di, sd) => di.VisitDate >= _beginDt && di.VisitDate <= _endDt)
  4622. .Select((di, sd) => new
  4623. {
  4624. Id = di.Id,
  4625. GroupTypeId = di.TeamDid,
  4626. GroupTypeName = sd.Name,
  4627. })
  4628. .ToListAsync();
  4629. var groupInfos1 = groupInfos.GroupBy(x => x.GroupTypeName);
  4630. var view = groupInfos1.Select(x =>
  4631. new
  4632. {
  4633. groupTypeName = x.Key,
  4634. groupNum = x.Count(),
  4635. linkGroupId = x.Select(x1 => x1.Id).ToList()
  4636. }
  4637. )
  4638. .OrderByDescending(x => x.groupNum)
  4639. .ToList();
  4640. return Ok(JsonView(true, "操作成功!", view));
  4641. }
  4642. /// <summary>
  4643. /// 团组数据统计
  4644. /// 团组数量
  4645. /// </summary>
  4646. /// <param name="_dto"></param>
  4647. /// <returns></returns>
  4648. [HttpPost("StatisticsGroupNum")]
  4649. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4650. public async Task<IActionResult> StatisticsGroupNum(YOYDto _dto)
  4651. {
  4652. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4653. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4654. endDt = $"{_dto.Year}-12-31 23:59:59";
  4655. DateTime _beginDt = Convert.ToDateTime(beginDt),
  4656. _endDt = Convert.ToDateTime(endDt);
  4657. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  4658. .Where(x => x.IsDel == 0)
  4659. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  4660. .Select(x => new StatisticsGroupInfoEntity
  4661. {
  4662. Id = x.Id,
  4663. VisitDate = x.VisitDate,
  4664. Month = x.VisitDate.Month,
  4665. //MonthName = x.VisitDate.ToString("MMM", CultureInfo.GetCultureInfo("zh-CN")),
  4666. VisitPNumber = x.VisitPNumber
  4667. })
  4668. .MergeTable()
  4669. .OrderBy(x => new { x.Month })
  4670. .ToListAsync();
  4671. string groupNumStr = $"年度出访量:{groupInfos.Count}\r\n";
  4672. var groupNumYearData = new
  4673. {
  4674. year = _dto.Year,
  4675. yearName = _dto.Year + "年",
  4676. num = groupInfos.Count,
  4677. linkGroupIds = groupInfos.Select(x => x.Id).ToList()
  4678. };
  4679. var groupNumData = groupInfos.GroupBy(x => x.Quarter)
  4680. .Select(x => new
  4681. {
  4682. Quarter = x.Key,
  4683. QuarterName = x.FirstOrDefault()?.QuarterName ?? "-",
  4684. Num = x.Count(),
  4685. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  4686. })
  4687. .OrderBy(x => x.Quarter)
  4688. .ToList();
  4689. groupNumData.ForEach(x =>
  4690. {
  4691. groupNumStr += $"{x.QuarterName}出访量:{x.Num};";
  4692. });
  4693. var groupNumMonthData = groupInfos.GroupBy(x => x.Month)
  4694. .Select(x => new
  4695. {
  4696. Month = x.Key,
  4697. MonthName = x.FirstOrDefault()?.MonthName ?? "-",
  4698. Num = x.Count(),
  4699. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  4700. })
  4701. .OrderBy(x => x.Month)
  4702. .ToList();
  4703. return Ok(JsonView(true, "操作成功!", new
  4704. {
  4705. yearData = groupNumYearData,
  4706. quarterData = groupNumData,
  4707. monthData = groupNumMonthData,
  4708. remark = groupNumStr
  4709. }));
  4710. }
  4711. /// <summary>
  4712. /// 团组数据统计
  4713. /// 团组人数
  4714. /// </summary>
  4715. /// <param name="_dto"></param>
  4716. /// <returns></returns>
  4717. [HttpPost("StatisticsGroupPeopleNum")]
  4718. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4719. public async Task<IActionResult> StatisticsGroupPeopleNum(YOYDto _dto)
  4720. {
  4721. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4722. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4723. endDt = $"{_dto.Year}-12-31 23:59:59";
  4724. DateTime _beginDt = Convert.ToDateTime(beginDt),
  4725. _endDt = Convert.ToDateTime(endDt);
  4726. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  4727. .Where(x => x.IsDel == 0)
  4728. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  4729. .Select(x => new StatisticsGroupInfoEntity
  4730. {
  4731. Id = x.Id,
  4732. VisitDate = x.VisitDate,
  4733. Month = x.VisitDate.Month,
  4734. VisitPNumber = x.VisitPNumber
  4735. })
  4736. .MergeTable()
  4737. .OrderBy(x => new { x.Month })
  4738. .ToListAsync();
  4739. string groupPeopleNumStr = $"年度出访人数:{groupInfos.Sum(x => x.VisitPNumber)}\r\n";
  4740. var groupPeopleNumYearData = new
  4741. {
  4742. year = _dto.Year,
  4743. yearName = _dto.Year + "年",
  4744. num = groupInfos.Sum(x => x.VisitPNumber),
  4745. linkGroupIds = groupInfos.Select(x => x.Id).ToList()
  4746. };
  4747. var groupPeopleNumData = groupInfos.GroupBy(x => x.Quarter)
  4748. .Select(x => new
  4749. {
  4750. Quarter = x.Key,
  4751. QuarterName = x.FirstOrDefault()?.QuarterName ?? "-",
  4752. Num = x.Sum(x1 => x1.VisitPNumber),
  4753. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  4754. })
  4755. .OrderBy(x => x.Quarter)
  4756. .ToList();
  4757. groupPeopleNumData.ForEach(x =>
  4758. {
  4759. groupPeopleNumStr += $"{x.QuarterName}出访人数:{x.Num};";
  4760. });
  4761. var groupPeopleNumMonthData = groupInfos.GroupBy(x => x.Month)
  4762. .Select(x => new
  4763. {
  4764. Month = x.Key,
  4765. MonthName = x.FirstOrDefault()?.MonthName ?? "-",
  4766. Num = x.Sum(x1 => x1.VisitPNumber),
  4767. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  4768. })
  4769. .OrderBy(x => x.Month)
  4770. .ToList();
  4771. return Ok(JsonView(true, "操作成功!", new
  4772. {
  4773. yearData = groupPeopleNumYearData,
  4774. quarterData = groupPeopleNumData,
  4775. monthData = groupPeopleNumMonthData,
  4776. remark = groupPeopleNumStr
  4777. }));
  4778. }
  4779. /// <summary>
  4780. /// 团组数据统计
  4781. /// OP 成本
  4782. /// </summary>
  4783. /// <param name="_dto"></param>
  4784. /// <returns></returns>
  4785. [HttpPost("StatisticsOP")]
  4786. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4787. public async Task<IActionResult> StatisticsOP(StatisticsOPDto _dto)
  4788. {
  4789. if (_dto.Year < 1) return Ok(JsonView(false, "Year参数错误!"));
  4790. if (_dto.Type < 1 || _dto.Type > 2) return Ok(JsonView(false, "Type参数错误!"));
  4791. int thisYear = _dto.Year, lastYear = _dto.Year - 1;
  4792. string beginDt = $"{lastYear}-01-01 00:00:00",
  4793. endDt = $"{thisYear}-12-31 23:59:59";
  4794. string sql = string.Format(@"
  4795. SELECT
  4796. temp.Id,
  4797. DiId,
  4798. PaymentTime,
  4799. [Year],
  4800. [Quarter],
  4801. [Month],
  4802. Area,
  4803. FeeType,
  4804. sd1.Name AS FeeTypeName,
  4805. FeeSubType,
  4806. sd2.Name AS FeeSubTypeName,
  4807. CONVERT(DECIMAL(12, 2), Price * Qauntity * ExchangeRate) AS Price
  4808. FROM
  4809. (
  4810. SELECT
  4811. ctggr.Id,
  4812. ctggr.DiId,
  4813. ctggr.Area,
  4814. CASE
  4815. WHEN ctggr.PriceType IS NULL THEN 1069
  4816. ELSE ctggr.PriceType
  4817. END AS FeeType,
  4818. ctggrc.SId AS FeeSubType,
  4819. ctggrc.Price,
  4820. CASE
  4821. WHEN ctggrc.Count IS NULL THEN 1
  4822. ELSE ctggrc.Count
  4823. END AS Qauntity,
  4824. ccp.DayRate AS ExchangeRate,
  4825. ctggrc.CreateTime AS PaymentTime,
  4826. YEAR(ctggrc.CreateTime) AS [Year],
  4827. CONVERT(INT,DATENAME(QUARTER, ctggrc.CreateTime)) AS [Quarter],
  4828. MONTH(ctggrc.CreateTime) AS [Month]
  4829. FROM
  4830. Grp_CarTouristGuideGroundReservations ctggr
  4831. INNER JOIN Grp_CarTouristGuideGroundReservationsContent ctggrc ON ctggr.Id = ctggrc.CTGGRId
  4832. AND ctggrc.IsDel = 0
  4833. INNER JOIN Grp_CreditCardPayment ccp ON ctggr.Id = ccp.CId
  4834. AND ccp.CTable = 79
  4835. AND ccp.IsDel = 0
  4836. WHERE
  4837. ctggr.IsDel = 0
  4838. AND ctggrc.SId != 1070 --费用子项筛掉尾款
  4839. AND ctggrc.Price > 0 --筛选真实存在的数据
  4840. AND ccp.IsPay = 1
  4841. ) temp
  4842. LEFT JOIN Sys_SetData sd1 ON FeeType = sd1.Id
  4843. LEFT JOIN Sys_SetData sd2 ON FeeSubType = sd2.Id
  4844. WHERE
  4845. temp.Area NOT LIKE '%尾款%' -- 筛选掉尾款相关信息
  4846. AND temp.FeeType != 1062 --费用类型筛选掉全款和首付款数据
  4847. AND temp.PaymentTime BETWEEN CONVERT(datetime,'{0}') AND CONVERT(datetime,'{1}')
  4848. ORDER BY
  4849. temp.[Year],
  4850. temp.[Quarter],
  4851. temp.[Month]
  4852. ", beginDt, endDt);
  4853. var opInfos = await _sqlSugar.SqlQueryable<StatisticsOP>(sql).ToListAsync();
  4854. //处理地区相关信息
  4855. var countrys = await _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(x => x.IsDel == 0).ToListAsync();
  4856. for (int i = 0; i < opInfos.Count; i++)
  4857. {
  4858. string country = string.Empty, city = string.Empty;
  4859. int dataId = 0;
  4860. bool isCountryId = int.TryParse(opInfos[i].Area, out dataId);
  4861. string[] citySelecter = new string[] { "其他城市", "所有城市" };
  4862. if (isCountryId)
  4863. {
  4864. var countryInfo = countrys.Find(x => x.Id == dataId);
  4865. country = countryInfo?.Country ?? "";
  4866. if (citySelecter.Contains(countryInfo?.City)) city = country;
  4867. else city = countryInfo?.City ?? "";
  4868. }
  4869. else
  4870. {
  4871. var countryInfo1 = countrys.Find(x => opInfos[i].Area.Contains(x.Country));
  4872. if (countryInfo1 != null)
  4873. {
  4874. country = countryInfo1?.Country ?? "";
  4875. city = countryInfo1?.City ?? country;
  4876. var countryInfo2 = countrys.Find(x => opInfos[i].Area.Contains(x.City));
  4877. if (citySelecter.Contains(countryInfo2?.City)) city = country;
  4878. else city = countryInfo2?.City ?? country;
  4879. }
  4880. else
  4881. {
  4882. var countryInfo2 = countrys.Find(x => opInfos[i].Area.Contains(x.City));
  4883. if (countryInfo2 != null)
  4884. {
  4885. country = countryInfo2?.Country ?? "";
  4886. city = countryInfo2?.City ?? "";
  4887. if (citySelecter.Contains(countryInfo2?.City)) city = country;
  4888. }
  4889. }
  4890. }
  4891. opInfos[i].Country = country;
  4892. opInfos[i].City = city;
  4893. }
  4894. var opParentFeeData = new StatisticsOP()._OPParentFeeInfo;
  4895. if (_dto.Type == 1)
  4896. {
  4897. //同比增长率=(本期数-同期数)/ 同期数
  4898. var yearData = opInfos.GroupBy(x => x.ParentFeeName)
  4899. .Select(x => new StatisticsOPYOY(
  4900. feeId: x.FirstOrDefault()?.ParentFeeId ?? 0,
  4901. feeName: x.Key,
  4902. currPeriodFee: x.Where(x => x.Year == thisYear).Sum(x => x.Price),
  4903. samePeriodFee: x.Where(x => x.Year == lastYear).Sum(x => x.Price),
  4904. currPeriodGroupTotal: x.Where(x => x.Year == thisYear).Select(x => x.DiId).Distinct().Count(),
  4905. samePeriodGroupTotal: x.Where(x => x.Year == lastYear).Select(x => x.DiId).Distinct().Count(),
  4906. subFeeData: x.GroupBy(x1 => x1.FeeSubType)
  4907. .Select(x1 => new StatisticsOPSubFeeYOY(
  4908. feeId: x1.Key,
  4909. feeName: x1.FirstOrDefault()?.FeeSubTypeName ?? "",
  4910. currPeriodFee: x1.Where(x1 => x1.Year == thisYear).Sum(x1 => x1.Price),
  4911. samePeriodFee: x1.Where(x1 => x1.Year == lastYear).Sum(x1 => x1.Price),
  4912. currPeriodGroupTotal: x1.Where(x1 => x1.Year == thisYear).Select(x1 => x1.DiId).Distinct().Count(),
  4913. samePeriodGroupTotal: x1.Where(x1 => x1.Year == lastYear).Select(x1 => x1.DiId).Distinct().Count(),
  4914. cityData: x1.GroupBy(x2 => x2.City)
  4915. .Select(x2 => new StatisticsOPCityYOY(
  4916. cityName: x2.Key,
  4917. currPeriodGroupTotal: x2.Where(x2 => x2.Year == thisYear).Select(x2 => x2.DiId).Distinct().Count(),
  4918. samePeriodGroupTotal: x2.Where(x2 => x2.Year == lastYear).Select(x2 => x2.DiId).Distinct().Count(),
  4919. currPeriodFee: x2.Where(x2 => x2.Year == thisYear).Sum(x2 => x2.Price),
  4920. samePeriodFee: x2.Where(x2 => x2.Year == lastYear).Sum(x2 => x2.Price)
  4921. ))
  4922. .ToArray()
  4923. ))
  4924. .ToArray()
  4925. ))
  4926. .OrderBy(x => x.FeeId)
  4927. .ToList();
  4928. var opParentYearIds = yearData.Select(x => x.FeeId).ToList();
  4929. var opParentYearDataSelector = opParentFeeData.Where(x => !opParentYearIds.Contains(x.Id)).ToList();
  4930. if (opParentYearDataSelector.Count > 0)
  4931. {
  4932. foreach (var item in opParentYearDataSelector)
  4933. {
  4934. yearData.Add(
  4935. new StatisticsOPYOY(feeId: item.Id,
  4936. feeName: item.Name,
  4937. currPeriodFee: 0.00M,
  4938. samePeriodFee: 0.00M,
  4939. currPeriodGroupTotal: 0,
  4940. samePeriodGroupTotal: 0,
  4941. subFeeData: new StatisticsOPSubFeeYOY[] { }
  4942. ));
  4943. }
  4944. yearData = yearData.OrderBy(x => x.FeeId).ToList();
  4945. }
  4946. return Ok(JsonView(true, "操作成功!", yearData));
  4947. }
  4948. else if (_dto.Type == 2)
  4949. {
  4950. var monthData = opInfos.GroupBy(x => x.Month)
  4951. .Select(x => new StatisticsOPMonthYOY(
  4952. monthId: x.Key,
  4953. monthName: System.Enum.IsDefined(typeof(MonthEnum), (int)x.Key) ? ((MonthEnum)(int)x.Key).GetEnumDescription() : "",
  4954. feeDatas: x.GroupBy(x1 => x1.ParentFeeId)
  4955. .Select(x1 => new StatisticsOPYOY(
  4956. feeId: x1.Key,
  4957. feeName: x1.FirstOrDefault()?.ParentFeeName ?? "",
  4958. currPeriodFee: x1.Where(x1 => x1.Year == thisYear).Sum(x1 => x1.Price),
  4959. samePeriodFee: x1.Where(x1 => x1.Year == lastYear).Sum(x1 => x1.Price),
  4960. currPeriodGroupTotal: x1.Where(x1 => x1.Year == thisYear).Select(x1 => x1.DiId).Distinct().Count(),
  4961. samePeriodGroupTotal: x1.Where(x1 => x1.Year == lastYear).Select(x1 => x1.DiId).Distinct().Count(),
  4962. subFeeData: x1.GroupBy(x2 => x2.FeeSubType)
  4963. .Select(x2 => new StatisticsOPSubFeeYOY(
  4964. feeId: x2.Key,
  4965. feeName: x2.FirstOrDefault()?.FeeSubTypeName ?? "",
  4966. currPeriodFee: x2.Where(x2 => x2.Year == thisYear).Sum(x2 => x2.Price),
  4967. samePeriodFee: x2.Where(x2 => x2.Year == lastYear).Sum(x2 => x2.Price),
  4968. currPeriodGroupTotal: x2.Where(x2 => x2.Year == thisYear).Select(x2 => x2.DiId).Distinct().Count(),
  4969. samePeriodGroupTotal: x2.Where(x2 => x2.Year == lastYear).Select(x2 => x2.DiId).Distinct().Count(),
  4970. cityData: x2.GroupBy(x3 => x3.City)
  4971. .Select(x3 => new StatisticsOPCityYOY(
  4972. cityName: x3.Key,
  4973. currPeriodFee: x3.Where(x3 => x3.Year == thisYear).Sum(x3 => x3.Price),
  4974. samePeriodFee: x3.Where(x3 => x3.Year == lastYear).Sum(x3 => x3.Price),
  4975. currPeriodGroupTotal: x3.Where(x3 => x3.Year == thisYear).Select(x3 => x3.DiId).Distinct().Count(),
  4976. samePeriodGroupTotal: x3.Where(x3 => x3.Year == lastYear).Select(x3 => x3.DiId).Distinct().Count()
  4977. ))
  4978. .ToArray()
  4979. ))
  4980. .ToArray()
  4981. ))
  4982. .ToArray()
  4983. ))
  4984. //.OrderBy(x => x.MonthId)
  4985. .ToList();
  4986. //1、月份是否足够十二月
  4987. var monthIds = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
  4988. var monthDataIds = monthData.Select(x => x.MonthId).ToArray();
  4989. var newMonthIds = monthIds.Where(x => !monthDataIds.Contains(x)).ToList();
  4990. if (newMonthIds.Count > 0)
  4991. {
  4992. foreach (var item in newMonthIds)
  4993. {
  4994. monthData.Add(new StatisticsOPMonthYOY(
  4995. monthId: item,
  4996. monthName: System.Enum.IsDefined(typeof(MonthEnum), (int)item) ? ((MonthEnum)(int)item).GetEnumDescription() : "",
  4997. feeDatas: Array.Empty<StatisticsOPYOY>()
  4998. ));
  4999. }
  5000. monthData = monthData.OrderBy(x => x.MonthId).ToList();
  5001. }
  5002. //2、费用父类是否足够
  5003. for (int i = 0; i < monthData.Count; i++)
  5004. {
  5005. var month = monthData[i];
  5006. var opParentFeeIds = month.FeeDatas.Select(x => x.FeeId).ToList();
  5007. var opParentFeeDataSelector = opParentFeeData.Where(x => !opParentFeeIds.Contains(x.Id)).ToList();
  5008. if (opParentFeeDataSelector.Count > 0)
  5009. {
  5010. var feeDatas = month.FeeDatas.ToList();
  5011. foreach (var item in opParentFeeDataSelector)
  5012. {
  5013. feeDatas.Add(new StatisticsOPYOY(
  5014. feeId: item.Id,
  5015. feeName: item.Name,
  5016. currPeriodFee: 0.00M,
  5017. samePeriodFee: 0.00M,
  5018. currPeriodGroupTotal: 0,
  5019. samePeriodGroupTotal: 0,
  5020. subFeeData: Array.Empty<StatisticsOPSubFeeYOY>()
  5021. ));
  5022. }
  5023. feeDatas = feeDatas.OrderBy(x => x.FeeId).ToList();
  5024. monthData[i].FeeDatas = feeDatas.ToArray();
  5025. }
  5026. }
  5027. //3、费用子类是否足够
  5028. return Ok(JsonView(true, "操作成功!", monthData));
  5029. }
  5030. return Ok(JsonView(false, "操作失败!"));
  5031. }
  5032. /// <summary>
  5033. /// 团组数据统计
  5034. /// 团组预算/实际成本
  5035. /// </summary>
  5036. /// <param name="_dto"></param>
  5037. /// <returns></returns>
  5038. [HttpPost("StatisticsGroupCost")]
  5039. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5040. public async Task<IActionResult> StatisticsBRCost(StatisticsBRCostDto _dto)
  5041. {
  5042. if (_dto.Year < 1) return Ok(JsonView(false, "Year参数错误!"));
  5043. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5044. endDt = $"{_dto.Year}-12-31 23:59:59";
  5045. var sql = string.Format(@"
  5046. SELECT
  5047. ROW_NUMBER() OVER(
  5048. ORDER BY
  5049. di.VisitDate DESC
  5050. ) AS 'RowNumber',
  5051. di.Id,
  5052. di.TeamName AS 'GroupName',
  5053. di.ClientUnit,
  5054. di.VisitDate,
  5055. di.VisitDays,
  5056. di.VisitPNumber,
  5057. (
  5058. SELECT
  5059. TOP 1 CASE
  5060. ISNUMERIC (gcp.Currency)
  5061. WHEN 1 THEN (
  5062. SELECT
  5063. Name
  5064. FROM
  5065. Sys_SetData sd
  5066. WHERE
  5067. CAST(gcp.Currency AS INT) = sd.Id
  5068. )
  5069. ELSE gcp.Currency
  5070. END AS 'CurrencyCode'
  5071. FROM
  5072. Grp_GroupCostParameter gcp
  5073. WHERE
  5074. gcp.IsDel = 0
  5075. AND gcp.DiId = di.Id
  5076. ) Budget_CurrencyCode,
  5077. --预算币种
  5078. (
  5079. SELECT
  5080. TOP 1 CAST(COALESCE(gcp.Rate, 0.0000) AS DECIMAL(12, 4))
  5081. FROM
  5082. Grp_GroupCostParameter gcp
  5083. WHERE
  5084. gcp.IsDel = 0
  5085. AND gcp.DiId = di.Id
  5086. ) Budget_Rate,
  5087. --预算汇率
  5088. (
  5089. SELECT
  5090. CAST(
  5091. SUM(COALESCE(gcp.VisaCB, 0) * COALESCE(gcp.VisaRS, 0)) AS DECIMAL(12, 2)
  5092. )
  5093. FROM
  5094. Grp_GroupCostParameter gcp
  5095. WHERE
  5096. gcp.IsDel = 0
  5097. AND gcp.DiId = di.id
  5098. ) Budget_VisaAmount,
  5099. -- 预算签证成本
  5100. (
  5101. SELECT
  5102. CAST(
  5103. SUM(
  5104. (
  5105. (ccp.PayMoney * ccp.DayRate)
  5106. )
  5107. ) AS DECIMAL(12, 2)
  5108. )
  5109. FROM
  5110. Grp_VisaInfo vi
  5111. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5112. AND ccp.CTable = 80
  5113. AND vi.Id = ccp.CId
  5114. WHERE
  5115. vi.IsDel = 0
  5116. AND ccp.IsAuditGM = 1
  5117. AND ccp.IsPay = 1
  5118. AND di.Id = vi.DIId
  5119. ) AS Reality_VisaAmount,
  5120. -- 实际签证成本
  5121. (
  5122. SELECT
  5123. CAST(
  5124. SUM(
  5125. COALESCE(gcp.JJCCB, 0) * COALESCE(gcp.JJCRS, 0) + COALESCE(gcp.GWCCB, 0) * COALESCE(gcp.GWCRS, 0) + COALESCE(gcp.TDCCB, 0) * COALESCE(gcp.TDCRS, 0)
  5126. ) AS DECIMAL(12, 2)
  5127. )
  5128. FROM
  5129. Grp_GroupCostParameter gcp
  5130. WHERE
  5131. gcp.IsDel = 0
  5132. AND gcp.DiId = di.id
  5133. ) Budget_AirTicketAmount,
  5134. -- 预算机票成本
  5135. (
  5136. SELECT
  5137. CAST(
  5138. SUM(
  5139. (
  5140. (ccp.PayMoney * ccp.DayRate)
  5141. )
  5142. ) AS DECIMAL(12, 2)
  5143. )
  5144. FROM
  5145. Grp_AirTicketReservations atr
  5146. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5147. AND ccp.CTable = 85
  5148. AND atr.Id = ccp.CId
  5149. WHERE
  5150. atr.IsDel = 0
  5151. AND ccp.IsAuditGM = 1
  5152. AND ccp.IsPay = 1
  5153. AND di.Id = atr.DiId
  5154. ) Reality_AirTicketAmount,
  5155. --实际机票
  5156. (
  5157. SELECT
  5158. CAST(
  5159. SUM(
  5160. COALESCE(gcp.SGRCB, 0) * COALESCE(gcp.SGRNumber, 0) + COALESCE(gcp.TBRCB, 0) * COALESCE(gcp.TBRNumber, 0) + COALESCE(gcp.SUITECB, 0) * COALESCE(gcp.SUITENumber, 0) + COALESCE(gcp.SUITENumber, 0) * COALESCE(gcp.JSESXS, 0)
  5161. ) AS DECIMAL(12, 2)
  5162. )
  5163. FROM
  5164. Grp_GroupCostParameter gcp
  5165. WHERE
  5166. gcp.IsDel = 0
  5167. AND gcp.DiId = di.id
  5168. ) Budget_HotelAmount,
  5169. -- 预算酒店成本
  5170. (
  5171. SELECT
  5172. CAST(
  5173. SUM(
  5174. (ccp.PayMoney * ccp.DayRate)
  5175. ) AS DECIMAL(12, 2)
  5176. )
  5177. FROM
  5178. Grp_HotelReservations hr
  5179. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  5180. WHERE
  5181. hr.IsDel = 0
  5182. AND ccp.IsDel = 0
  5183. AND ccp.CTable = 76
  5184. AND ccp.IsAuditGM = 1
  5185. AND ccp.PayMoney <> 0
  5186. AND ccp.IsPay = 1
  5187. AND di.Id = hr.DiId
  5188. ) AS Reality_HotelAmount,
  5189. -- 实际酒店成本
  5190. (
  5191. SELECT
  5192. CAST(
  5193. SUM(COALESCE(gcp.DJCB, 0) * COALESCE(gcp.DJRS, 0)) AS DECIMAL(12, 2)
  5194. )
  5195. FROM
  5196. Grp_GroupCostParameter gcp
  5197. WHERE
  5198. gcp.IsDel = 0
  5199. AND gcp.DiId = di.id
  5200. ) Budget_OPAmount,
  5201. -- 预算 OP
  5202. (
  5203. SELECT
  5204. CAST(
  5205. SUM(
  5206. (
  5207. ctggr.ServiceQuotedPrice * (ccp.PayPercentage / 100) * ccp.DayRate
  5208. )
  5209. ) AS DECIMAL(12, 2)
  5210. )
  5211. FROM
  5212. Grp_CarTouristGuideGroundReservations ctggr
  5213. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  5214. AND ccp.CTable = 79
  5215. AND ctggr.Id = ccp.CId
  5216. WHERE
  5217. ctggr.IsDel = 0
  5218. AND ccp.IsAuditGM = 1
  5219. AND ccp.IsPay = 1
  5220. AND di.Id = ctggr.DiId
  5221. ) AS Reality_OPAmount,
  5222. -- 实际 OP
  5223. (
  5224. SELECT
  5225. CAST(
  5226. SUM(COALESCE(gcp.GWCB, 0) * COALESCE(gcp.GWRS, 0)) AS DECIMAL(12, 2)
  5227. )
  5228. FROM
  5229. Grp_GroupCostParameter gcp
  5230. WHERE
  5231. gcp.IsDel = 0
  5232. AND gcp.DiId = di.id
  5233. ) Budget_OAAmount,
  5234. -- 预算 商邀
  5235. (
  5236. SELECT
  5237. CAST(
  5238. SUM(
  5239. (ccp.PayMoney * ccp.DayRate)
  5240. ) AS DECIMAL(12, 2)
  5241. )
  5242. FROM
  5243. Grp_InvitationOfficialActivities ioa
  5244. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5245. AND ccp.CTable = 81
  5246. AND ioa.Id = ccp.CId
  5247. WHERE
  5248. ioa.IsDel = 0
  5249. AND ccp.IsAuditGM = 1
  5250. AND ccp.IsPay = 1
  5251. AND di.Id = ioa.Diid
  5252. ) AS Reality_OAAmount,
  5253. -- 实际 商邀
  5254. (
  5255. SELECT
  5256. CAST(
  5257. SUM(
  5258. COALESCE(gcp.BXCB, 0) * COALESCE(gcp.BXRS, 0) + COALESCE(gcp.HCPCB, 0) * COALESCE(gcp.HCPRS, 0) + COALESCE(gcp.CPCB, 0) * COALESCE(gcp.CPRS, 0) + COALESCE(gcp.HSCB, 0) * COALESCE(gcp.HSRS, 0) + COALESCE(gcp.LYJCB, 0) * COALESCE(gcp.LYJRS, 0)
  5259. ) AS DECIMAL(12, 2)
  5260. )
  5261. FROM
  5262. Grp_GroupCostParameter gcp
  5263. WHERE
  5264. gcp.IsDel = 0
  5265. AND gcp.DiId = di.id
  5266. ) Budget_OtherAmount,
  5267. -- 预算其他成本
  5268. (
  5269. SELECT
  5270. CAST(
  5271. SUM(
  5272. (ccp.PayMoney * ccp.DayRate)
  5273. ) AS DECIMAL(12, 2)
  5274. )
  5275. FROM
  5276. Grp_Customers ic
  5277. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5278. AND ccp.CTable = 82
  5279. AND ic.Id = ccp.CId
  5280. WHERE
  5281. ic.IsDel = 0
  5282. AND ccp.IsAuditGM = 1And ccp.IsPay = 1
  5283. AND di.Id = ic.DiId
  5284. ) AS Reality_InsureAmount,
  5285. -- 实际保险成本
  5286. (
  5287. SELECT
  5288. CAST(SUM((ccp.PayMoney * ccp.DayRate)) AS DECIMAL(12, 2))
  5289. FROM
  5290. Grp_DecreasePayments dp
  5291. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5292. AND ccp.CTable = 98
  5293. AND dp.Id = ccp.CId
  5294. WHERE
  5295. dp.IsDel = 0
  5296. AND ccp.Ctable = 98
  5297. AND ccp.IsAuditGM = 1
  5298. AND ccp.IsPay = 1
  5299. AND di.Id = dp.Diid
  5300. ) AS Reality_OtherCostAmount -- 实际其他款项
  5301. FROM
  5302. Grp_DelegationInfo di
  5303. WHERE
  5304. di.IsDel = 0
  5305. AND di.IsBid = 0
  5306. --AND di.TeamDid IN (38, 39, 40, 1048)
  5307. AND di.VisitDate BETWEEN '{0}' AND '{1}'
  5308. ", beginDt, endDt);
  5309. if (!string.IsNullOrEmpty(_dto.Search))
  5310. {
  5311. sql += $"AND di.TeamName Like '%{_dto.Search}%'";
  5312. }
  5313. var view = await _sqlSugar.SqlQueryable<StatisticsBRCostView>(sql).ToListAsync();
  5314. view = view.Where(x => !x.GroupName.Contains("投标") && x.RealityAmount > 0).OrderByDescending(x => x.Id).ToList();
  5315. var total = view.Count;
  5316. var toSkip = (_dto.PageIndex - 1) * _dto.PageSize;
  5317. var data = view.Skip(toSkip).Take(_dto.PageSize).ToList();
  5318. if (data.Count > 0)
  5319. {
  5320. var diIds = data.Select(x => x.Id).ToList();
  5321. var currencyData = await _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0 && x.STid == 66).ToListAsync();
  5322. var ccpData = await _sqlSugar.Queryable<Grp_CreditCardPayment>()
  5323. .Where(x => x.IsDel == 0 &&
  5324. diIds.Contains(x.DIId) &&
  5325. x.IsPay == 1 &&
  5326. x.IsAuditGM == 1
  5327. )
  5328. .ToListAsync();
  5329. for (int i = 0; i < data.Count; i++)
  5330. {
  5331. var info = data[i];
  5332. info.RowNumber = i + 1;
  5333. #region 1:签证 80
  5334. var visaDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 80).ToList();
  5335. var visaDesc = "-";
  5336. if (visaDatas.Count > 0)
  5337. {
  5338. visaDesc = $"实际币种金额:";
  5339. foreach (var visa in visaDatas)
  5340. {
  5341. var currencyCode = currencyData.Find(x => x.Id == visa.PaymentCurrency)?.Name;
  5342. visaDesc += $"{visa.PayMoney} {currencyCode} 汇率:{visa.DayRate.ToString("#0.0000")};";
  5343. }
  5344. }
  5345. info.Reality_VisaAmountDesc = visaDesc;
  5346. #endregion
  5347. #region 2:机票 85
  5348. var airDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 85).ToList();
  5349. var airDesc = "-";
  5350. if (airDatas.Count > 0)
  5351. {
  5352. airDesc = $"实际币种金额:";
  5353. foreach (var air in airDatas)
  5354. {
  5355. var currencyCode = currencyData.Find(x => x.Id == air.PaymentCurrency)?.Name;
  5356. airDesc += $"{air.PayMoney} {currencyCode} 汇率:{air.DayRate.ToString("#0.0000")};";
  5357. }
  5358. }
  5359. info.Reality_AirTicketAmountDesc = airDesc;
  5360. #endregion
  5361. #region 3:酒店 76
  5362. var hotelDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 76 && x.PayMoney != 0).ToList();
  5363. var hotelDesc = "-";
  5364. if (hotelDatas.Count > 0)
  5365. {
  5366. hotelDesc = $"实际币种金额:";
  5367. foreach (var hotel in hotelDatas)
  5368. {
  5369. var currencyCode = currencyData.Find(x => x.Id == hotel.PaymentCurrency)?.Name;
  5370. hotelDesc += $"{hotel.PayMoney} {currencyCode} 汇率:{hotel.DayRate.ToString("#0.0000")};";
  5371. }
  5372. }
  5373. info.Reality_HotelAmountDesc = hotelDesc;
  5374. #endregion
  5375. #region 4:OP 79
  5376. var opDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 79 && x.PayMoney != 0).ToList();
  5377. var opDesc = "-";
  5378. if (opDatas.Count > 0)
  5379. {
  5380. opDesc = $"实际币种金额;";
  5381. foreach (var op in opDatas)
  5382. {
  5383. var currencyCode = currencyData.Find(x => x.Id == op.PaymentCurrency)?.Name;
  5384. opDesc += $"{op.PayMoney} {currencyCode} 汇率:{op.DayRate.ToString("#0.0000")};";
  5385. }
  5386. }
  5387. info.Reality_OPAmountDesc = opDesc;
  5388. #endregion
  5389. #region 5:商邀 81
  5390. var oaDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 81 && x.PayMoney != 0).ToList();
  5391. var oaDesc = "-";
  5392. if (oaDatas.Count > 0)
  5393. {
  5394. oaDesc = $"实际币种金额:";
  5395. foreach (var oa in oaDatas)
  5396. {
  5397. var currencyCode = currencyData.Find(x => x.Id == oa.PaymentCurrency)?.Name;
  5398. oaDesc += $"{oa.PayMoney} {currencyCode} 汇率:{oa.DayRate.ToString("#0.0000")};";
  5399. }
  5400. }
  5401. info.Reality_OAAmountDesc = oaDesc;
  5402. #endregion
  5403. #region 6:其他款项(保险 82、其他款项 98)
  5404. var cTables = new List<int>() { 82, 98 };
  5405. var otherDatas = ccpData.Where(x => x.DIId == info.Id && cTables.Contains(x.CTable) && x.PayMoney != 0).ToList();
  5406. var otherDesc = "-";
  5407. if (otherDatas.Count > 0)
  5408. {
  5409. otherDesc = $"实际币种金额:";
  5410. foreach (var other in otherDatas)
  5411. {
  5412. var currencyCode = currencyData.Find(x => x.Id == other.PaymentCurrency)?.Name;
  5413. otherDesc += $"{other.PayMoney} {currencyCode} 汇率:{other.DayRate.ToString("#0.0000")};";
  5414. }
  5415. }
  5416. info.Reality_OtherCostAmountDesc = otherDesc;
  5417. #endregion
  5418. }
  5419. }
  5420. var briefData = _mapper.Map<List<StatisticsBRCostBriefView>>(data);
  5421. return Ok(JsonView(briefData, total));
  5422. }
  5423. /// <summary>
  5424. /// 团组数据统计
  5425. /// 当前时间团组所在城市
  5426. /// </summary>
  5427. /// <param name="dto"></param>
  5428. /// <returns></returns>
  5429. [HttpPost("StatisticsNowCityOfGroup")]
  5430. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5431. public async Task<IActionResult> StatisticsNowCityOfGroup(StatisticsNowCityOfGroupDto dto)
  5432. {
  5433. if (!SharingStaticData.PortTypes.Contains(dto.PortType)) return Ok(JsonView(false, MsgTips.Port));
  5434. var nowLable = DateTime.Now.ToString("yyyy-MM-dd");
  5435. var sql = string.Format(@"SELECT * FROM Grp_DelegationInfo WHERE ISdel = 0 AND '{0}' BETWEEN VisitStartDate AND VisitEndDate", nowLable);
  5436. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql)
  5437. .Select(x => new { x.Id, x.VisitCountry, x.TeamName,x.ClientUnit, x.VisitStartDate, x.VisitEndDate }).
  5438. ToListAsync();
  5439. if (!groupInfos.Any()) return Ok(JsonView(false, "今日暂无团组出行!"));
  5440. var groupIds = groupInfos.Select(x => x.Id).ToList();
  5441. //三字码
  5442. var threeDatas = await _sqlSugar.Queryable<Res_ThreeCode>().Where(x => x.IsDel == 0).ToListAsync();
  5443. //国家
  5444. var countryDatas = await _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(x => x.IsDel == 0 && !string.IsNullOrEmpty(x.Country) && !string.IsNullOrEmpty(x.City)).ToListAsync();
  5445. //公务
  5446. var OADatas = await _sqlSugar.Queryable<Res_OfficialActivities>().Where(x => x.IsDel == 0 && groupIds.Contains(x.DiId) && !string.IsNullOrEmpty(x.Area)).ToListAsync();
  5447. //酒店
  5448. var hotelDatas = await _sqlSugar.Queryable<Grp_HotelReservations>()
  5449. .LeftJoin<Grp_NationalTravelFee>((hr, ntf) => hr.AreaId == ntf.Id)
  5450. .Where((hr, ntf) => hr.IsDel == 0 && groupIds.Contains(hr.DiId))
  5451. .Select((hr, ntf) => new {
  5452. hr.DiId,
  5453. hr.HotelName,
  5454. hr.CheckInDate,
  5455. hr.CheckOutDate,
  5456. hr.HotelAddress,
  5457. ntf.Country,
  5458. ntf.City
  5459. })
  5460. .ToListAsync();
  5461. //机票
  5462. /*
  5463. *舱位类型
  5464. *457 头等舱
  5465. *458 公务舱
  5466. *459 超经舱
  5467. *460 经济舱
  5468. *461 退票
  5469. *565 其他
  5470. *574 长段公务舱
  5471. *575 短途经济舱
  5472. *1023 行程单打印费
  5473. *1024 选座费
  5474. */
  5475. var classTypes = new int[] { 457, 458, 459, 460, 574, 575 };
  5476. var airDatas = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
  5477. .Where(atr => atr.IsDel == 0 && groupIds.Contains(atr.DIId) && classTypes.Contains(atr.CType))
  5478. .ToListAsync();
  5479. //洲 当前时间data
  5480. var continents = new List<string>();
  5481. var groupCountrys = new List<string>();
  5482. string[] characters = { "|", "、" };
  5483. foreach (var item in groupInfos)
  5484. {
  5485. var country = item.VisitCountry;
  5486. if (string.IsNullOrEmpty(country)) continue;
  5487. if (characters.Any(x => country.Contains(x)))
  5488. {
  5489. var countryArray = country.Split(characters, StringSplitOptions.RemoveEmptyEntries);
  5490. foreach (var country1 in countryArray)
  5491. {
  5492. groupCountrys.Add(country1);
  5493. var continent = countryDatas.Find(x => x.Country.Equals(country1))?.Continent ?? countryDatas.Find(x => x.City.Equals(country1))?.Continent ?? "";
  5494. if (!string.IsNullOrEmpty(continent)) continents.Add(continent);
  5495. }
  5496. }
  5497. else
  5498. {
  5499. groupCountrys.Add(country);
  5500. var continent = countryDatas.Find(x => x.Country.Equals(country))?.Continent ?? countryDatas.Find(x => x.City.Equals(country))?.Continent ?? "";
  5501. if (!string.IsNullOrEmpty(continent)) continents.Add(continent);
  5502. }
  5503. }
  5504. if (!continents.Any()) return Ok(JsonView(false, "未查询出国家所属洲!"));
  5505. continents = continents.Distinct().ToList();
  5506. var tzDatas = new List<TimezoneInfoView>();
  5507. var juHeApiMsg = "";
  5508. foreach (var continent in continents)
  5509. {
  5510. var tzResult = await _juHeApiService.GetContinentTimezoneAsync(continent);
  5511. if (tzResult.Error_code != 0)
  5512. {
  5513. juHeApiMsg += string.Format("{0}\r", tzResult.Reason);
  5514. continue;
  5515. }
  5516. if (tzResult.Result == null)
  5517. {
  5518. juHeApiMsg += string.Format("聚合api响应数据为空\r");
  5519. continue;
  5520. }
  5521. var info = JsonConvert.DeserializeObject<ContinentInfoView>(tzResult.Result.ToJson());
  5522. if (info == null && !info.tz.Any())
  5523. {
  5524. juHeApiMsg += string.Format("聚合api响应数据为空\r");
  5525. continue;
  5526. }
  5527. tzDatas.AddRange(info.tz);
  5528. }
  5529. if (!tzDatas.Any()) return Ok(JsonView(false, $"聚合API获取世界时间失败!! Message:{juHeApiMsg}"));
  5530. var groupCountrytz = tzDatas.Where(x => groupCountrys.Contains(x.tz_simple)).ToList();
  5531. var result = new List<StatisticsNowCityOfGroupResultView>();
  5532. foreach (var item in groupInfos)
  5533. {
  5534. string statusText = string.Empty,
  5535. address = string.Empty;
  5536. var countrys = item.VisitCountry;
  5537. if (string.IsNullOrEmpty(countrys)) continue;
  5538. var currCountrys = item.VisitCountry.Split(characters, StringSplitOptions.RemoveEmptyEntries);
  5539. var stutus = true;
  5540. //公务
  5541. var currOADatas = OADatas.Where(x => x.DiId == item.Id && currCountrys.Any(c => x.Country.Contains(c))).ToList();
  5542. if (currOADatas.Any())
  5543. {
  5544. foreach (var curr_oa in currOADatas)
  5545. {
  5546. var currOaDtStart = Convert.ToDateTime($"{Convert.ToDateTime(curr_oa.Date).ToString("yyyy-MM-dd")} {curr_oa.Time}");
  5547. var currOaDtEnd = currOaDtStart.AddHours(2);
  5548. var curr_tz1 = tzDatas.Where(x => curr_oa.Area.Contains(x.tz_simple)).ToList();
  5549. var curr_tz2 = curr_tz1.Where(x => Convert.ToDateTime(x.time) >= currOaDtStart && Convert.ToDateTime(x.time) <= currOaDtEnd).FirstOrDefault();
  5550. if (curr_tz2 == null) continue;
  5551. stutus = false;
  5552. statusText = "公务活动中";
  5553. address = curr_oa.Address;
  5554. break;
  5555. }
  5556. }
  5557. //酒店
  5558. var currHotelDatas = hotelDatas.Where(x => x.DiId == item.Id && !string.IsNullOrEmpty(x.Country) && currCountrys.Any(c => x.Country.Contains(c))).ToList();
  5559. if (stutus && hotelDatas.Any())
  5560. {
  5561. foreach (var curr_hotel in currHotelDatas)
  5562. {
  5563. var checkInDt = Convert.ToDateTime(curr_hotel.CheckInDate);
  5564. List<(DateTime start, DateTime end)> timeRanges = new List<(DateTime, DateTime)>();
  5565. while (checkInDt <= Convert.ToDateTime(curr_hotel.CheckOutDate))
  5566. {
  5567. int year = checkInDt.Year,
  5568. month = checkInDt.Month,
  5569. day = checkInDt.Day;
  5570. timeRanges.Add((new DateTime(year, month, day, 0, 0, 0), new DateTime(year, month, day, 18, 0, 0)));
  5571. timeRanges.Add((new DateTime(year, month, day, 18, 0, 0), new DateTime(year, month, day, 23, 59, 59)));
  5572. checkInDt = checkInDt.AddDays(1);
  5573. }
  5574. if (!timeRanges.Any()) continue;
  5575. if (string.IsNullOrEmpty(curr_hotel.Country) && string.IsNullOrEmpty(curr_hotel.City)) continue;
  5576. var curr_tz1 = tzDatas.Where(x => curr_hotel.Country.Contains(x.tz_simple) || curr_hotel.City.Contains(x.tz_simple)).ToList();
  5577. var curr_tz2 = curr_tz1.Where(x => timeRanges.Any(range => Convert.ToDateTime(x.time) >= range.start && Convert.ToDateTime(x.time) <= range.end)).FirstOrDefault();
  5578. if (curr_tz2 == null) continue;
  5579. stutus = false;
  5580. statusText = "入住酒店中";
  5581. address = curr_hotel.HotelAddress;
  5582. break;
  5583. }
  5584. }
  5585. result.Add(new StatisticsNowCityOfGroupResultView()
  5586. {
  5587. GroupName = item.TeamName,
  5588. Client = item.ClientUnit,
  5589. StatusText = statusText,
  5590. Address = address
  5591. });
  5592. }
  5593. return Ok(JsonView(result));
  5594. }
  5595. private StatisticsNowCityOfGroupView CitySplit(string cityLable, List<Res_ThreeCode> cities)
  5596. {
  5597. var info = new StatisticsNowCityOfGroupView();
  5598. if (string.IsNullOrEmpty(cityLable)) return info;
  5599. var cityArray = cityLable.Split("-");
  5600. var departCityCode = cityArray[0];
  5601. var arriveCityCode = cityArray[1];
  5602. var departAirportInfo = cities.Find(x => x.Three.Equals(departCityCode.ToUpper()));
  5603. info.DepartAirportCode = departCityCode;
  5604. info.DepartCountryName = departAirportInfo?.Country ?? "-";
  5605. info.DepartCityName = departAirportInfo?.City ?? "-";
  5606. var arriveAirportInfo = cities.Find(x => x.Three.Equals(arriveCityCode.ToUpper()));
  5607. info.ArriveAirportCode = arriveCityCode;
  5608. info.ArriveCountryName = arriveAirportInfo?.Country ?? "-";
  5609. info.ArriveCityName = arriveAirportInfo?.City ?? "-";
  5610. return info;
  5611. }
  5612. #endregion
  5613. }
  5614. }