StatisticsController.cs 392 KB

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