StatisticsController.cs 435 KB

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