StatisticsController.cs 436 KB

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