StatisticsController.cs 443 KB

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