StatisticsController.cs 443 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306
  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. /// <summary>
  3205. /// 团组报表 - 会务超支验证excel下载
  3206. /// </summary>
  3207. /// <param name="dto"></param>
  3208. /// <returns></returns>
  3209. [HttpPost("PostGroupStatementValidateExpenses")]
  3210. public async Task<IActionResult> PostGroupStatementValidateExpenses(PostGroupStatementValidateExpensesDto dto)
  3211. {
  3212. // 1. 参数与业务校验
  3213. if (dto.GroupId <= 0 || dto.CurrUserId <= 0) return Ok(JsonView(false, "参数非法"));
  3214. var isConfGroup = await _sqlSugar.Queryable<Grp_DelegationInfo, Sys_SetData>((g, s) => g.TeamDid == s.Id)
  3215. .Where((g, s) => g.IsDel == 0 && g.Id == dto.GroupId && s.STid == 10 && s.Name.Contains("会务活动"))
  3216. .AnyAsync();
  3217. if (!isConfGroup) return Ok(JsonView(false, "当前团组非会务团组,禁止操作"));
  3218. // 2. 数据查询与处理
  3219. var feeList = await _sqlSugar.Queryable<Grp_DecreasePayments>()
  3220. .InnerJoin<Grp_CreditCardPayment>((x, y) => x.Id == y.CId && x.DiId == y.DIId && y.CTable == 98)
  3221. .LeftJoin<Sys_Users>((x, y, z) => x.CreateUserId == z.Id)
  3222. .Where((x, y, z) => x.IsDel == 0 && x.DiId == dto.GroupId)
  3223. .Select((x, y, z) => new ConfValidateExpensesView
  3224. {
  3225. PriceName = x.PriceName,
  3226. FeeEntry = y.PayMoney * y.DayRate,
  3227. AuditStatus = y.IsAuditGM.ToString(),
  3228. AuditTime = y.AuditGMDate,
  3229. PayLabel = y.IsPay.ToString(),
  3230. Remark = x.Remark,
  3231. Applicant = z.CnName,
  3232. ApplicantTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")
  3233. }).ToListAsync();
  3234. if (!feeList.Any()) return Ok(JsonView(false, "未检索到实际费用记录"));
  3235. var expenseData = await _sqlSugar.Queryable<Grp_ConferenceAffairsCostChild>()
  3236. .InnerJoin<Grp_ConferenceAffairsCost>((x, y) => x.ConferenceAffairsCostId == y.Id)
  3237. .Where((x, y) => y.IsDel == 0 && y.Diid == dto.GroupId && x.ReviewStatus == 1)
  3238. .Select((x, y) => new { x.PriceName, Total = x.CostPrice * x.Rate * x.Count })
  3239. .ToListAsync();
  3240. var expenseDict = expenseData.ToDictionary(k => k.PriceName, v => v.Total);
  3241. // 数据转换逻辑
  3242. int index = 1;
  3243. foreach (var item in feeList.OrderBy(x => x.PriceName).ThenBy(x => x.ApplicantTime))
  3244. {
  3245. item.Index = index++;
  3246. item.AuditStatus = MapAuditStatus(item.AuditStatus);
  3247. item.PayLabel = item.PayLabel == "1" ? "已支付" : "未支付";
  3248. if (expenseDict.TryGetValue(item.PriceName, out decimal budget))
  3249. {
  3250. item.ExpenseEntry = budget;
  3251. item.OverspentLabel = item.FeeEntry > budget ? "超支" : "未超支";
  3252. }
  3253. else
  3254. {
  3255. item.OverspentLabel = item.FeeEntry <= 0 ? "未超支" : "成本未录入项(系统判定超支)";
  3256. }
  3257. }
  3258. // 3. 路径与导出
  3259. try
  3260. {
  3261. var groupName = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => x.Id == dto.GroupId).Select(x => x.TeamName).FirstAsync() ?? "未知团组";
  3262. string baseUrl = AppSettingsHelper.Get("ExcelBaseUrl").TrimEnd('/');
  3263. string basePath = AppSettingsHelper.Get("ExcelBasePath").TrimEnd('\\').TrimEnd('/');
  3264. string fptPath = AppSettingsHelper.Get("ExcelFtpPath");
  3265. string dirName = "GroupConf";
  3266. // 目录不存在时创建
  3267. string targetDir = Path.Combine(basePath, dirName);
  3268. if (!Directory.Exists(targetDir)) Directory.CreateDirectory(targetDir);
  3269. string fileName = $"{groupName}_会务校验_{DateTime.Now:yyyyMMddHHmm}.xlsx";
  3270. string fullPath = Path.Combine(targetDir, fileName);
  3271. // 生成文件
  3272. var isSuccess = await ExportToExcel(feeList, fullPath, "超支验证明细");
  3273. if (isSuccess)
  3274. {
  3275. return Ok(JsonView(true, "操作成功", new { url = $"{baseUrl}{fptPath}{dirName}/{fileName}" }));
  3276. }
  3277. return Ok(JsonView(false, "文件生成失败"));
  3278. }
  3279. catch (Exception ex)
  3280. {
  3281. return Ok(JsonView(false, $"导出异常:{ex.Message}"));
  3282. }
  3283. }
  3284. private string MapAuditStatus(string status) => status switch
  3285. {
  3286. "0" => "未审核",
  3287. "1" => "已审核",
  3288. "2" => "未通过",
  3289. "3" => "自动审核",
  3290. _ => "未知"
  3291. };
  3292. public static async Task<bool> ExportToExcel<T>(IEnumerable<T> data, string absolutePath, string sheetName)
  3293. {
  3294. Workbook workbook = new Workbook();
  3295. Worksheet sheet = workbook.Worksheets[0];
  3296. sheet.Name = sheetName;
  3297. PropertyInfo[] props = typeof(T).GetProperties();
  3298. // 1. 表头处理
  3299. Style headerStyle = workbook.CreateStyle();
  3300. headerStyle.Font.Name = "微软雅黑";
  3301. headerStyle.Font.IsBold = true;
  3302. headerStyle.Pattern = BackgroundType.Solid;
  3303. headerStyle.ForegroundColor = System.Drawing.Color.LightGray;
  3304. headerStyle.HorizontalAlignment = TextAlignmentType.Center;
  3305. for (int i = 0; i < props.Length; i++)
  3306. {
  3307. var attr = props[i].GetCustomAttribute<DisplayAttribute>();
  3308. sheet.Cells[0, i].PutValue(attr?.Name ?? props[i].Name);
  3309. sheet.Cells[0, i].SetStyle(headerStyle);
  3310. }
  3311. // 2. 数据处理
  3312. var list = data.ToList();
  3313. for (int r = 0; r < list.Count; r++)
  3314. {
  3315. for (int c = 0; c < props.Length; c++)
  3316. {
  3317. var val = props[c].GetValue(list[r]);
  3318. Aspose.Cells.Cell cell = sheet.Cells[r + 1, c];
  3319. cell.PutValue(val);
  3320. // 高亮逻辑:仅在超支单元格设置红色
  3321. if (props[c].Name == "OverspentLabel" && val?.ToString()?.Contains("超支") == true)
  3322. {
  3323. Style s = cell.GetStyle();
  3324. s.Font.Color = System.Drawing.Color.Red;
  3325. s.Font.IsBold = true;
  3326. cell.SetStyle(s);
  3327. }
  3328. }
  3329. }
  3330. sheet.AutoFitColumns();
  3331. // 3. 物理保存
  3332. try
  3333. {
  3334. using (FileStream fs = new FileStream(absolutePath, FileMode.Create, FileAccess.Write, FileShare.None))
  3335. {
  3336. workbook.Save(fs, SaveFormat.Xlsx);
  3337. await fs.FlushAsync();
  3338. }
  3339. return System.IO.File.Exists(absolutePath);
  3340. }
  3341. catch { return false; }
  3342. }
  3343. #endregion
  3344. #region 报表/折线图统计
  3345. //企业利润-团组利润
  3346. //企业利润-会务利润
  3347. /// <summary>
  3348. /// 企业利润
  3349. /// Details
  3350. /// 待添加权限验证
  3351. /// </summary>
  3352. /// <param name="_dto">团组列表请求dto</param>
  3353. /// <returns></returns>
  3354. [HttpPost("PostCorporateProfit")]
  3355. //[JsonConverter(typeof(DecimalConverter), 2)]
  3356. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3357. public async Task<IActionResult> PostCorporateProfit(PostCorporateProfitDto _dto)
  3358. {
  3359. #region 参数验证
  3360. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  3361. if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  3362. if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));
  3363. if (_dto.StatisticsType > 2 && _dto.StatisticsType < 1) return Ok(JsonView(false, "请输入有效的StatisticsType参数,1 月份 2 季度"));
  3364. if (_dto.BusinessType > 3 && _dto.BusinessType < 1) return Ok(JsonView(false, "请输入有效的BusinessType参数,1 所有 2 团组 3 会务"));
  3365. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3366. #region 页面操作权限验证
  3367. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3368. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  3369. #endregion
  3370. string sqlWhere = string.Empty;
  3371. //起止时间
  3372. DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");
  3373. DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");
  3374. sqlWhere = string.Format(@$" Where Isdel = 0 ");
  3375. //业务类型
  3376. List<int> groupTypeId = new List<int>();
  3377. if (_dto.BusinessType == 2) //团组
  3378. {
  3379. groupTypeId.AddRange(new List<int>() {
  3380. 38, // 政府团
  3381. 39, // 企业团
  3382. 40, // 散客团
  3383. 1048 // 高校团
  3384. });
  3385. }
  3386. else if (_dto.BusinessType == 3) //会务
  3387. {
  3388. groupTypeId.AddRange(new List<int>() {
  3389. 102, // 未知
  3390. 248, // 非团组
  3391. 302, // 成都-会务活动
  3392. 691, // 四川-会务活动
  3393. 762, // 四川-赛事项目收入
  3394. 1047 // 成都-赛事项目收入
  3395. });
  3396. }
  3397. if (groupTypeId.Count > 0)
  3398. {
  3399. sqlWhere += string.Format(@$" And TeamDid In ({string.Join(',', groupTypeId)})");
  3400. }
  3401. string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");
  3402. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();
  3403. if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));
  3404. List<int> diIds = groupInfos.Select(it => it.Id).ToList();
  3405. List<CorporateProfit> corporateProfits = await CorporateProfit(diIds);
  3406. List<MonthInfo> months = new List<MonthInfo>();
  3407. if (_dto.StatisticsType == 1) //月份
  3408. {
  3409. months = GeneralMethod.GetMonthInfos(Convert.ToInt32(_dto.Year));
  3410. }
  3411. else if (_dto.StatisticsType == 1) //季度
  3412. {
  3413. months = GeneralMethod.GetQuarter(Convert.ToInt32(_dto.Year));
  3414. }
  3415. List<CorporateProfitMonthView> _view = new List<CorporateProfitMonthView>();
  3416. foreach (var item in months)
  3417. {
  3418. DateTime monthBeginDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.BeginDays} 00:00:00");
  3419. DateTime monthEndDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.EndDays} 23:59:59");
  3420. var corporateProfit = corporateProfits.Where(it => it.CreateDt >= monthBeginDt && it.CreateDt <= monthEndDt).ToList();
  3421. _view.Add(new CorporateProfitMonthView()
  3422. {
  3423. Month = item.Month,
  3424. Profit = corporateProfit.Sum(it => it.ReceivedProfit),
  3425. GroupInfos = corporateProfit.OrderBy(it => it.CreateDt).ToList()
  3426. });
  3427. }
  3428. return Ok(JsonView(true, "操作成功!", _view));
  3429. #endregion
  3430. }
  3431. /// <summary>
  3432. /// 计算团组利润
  3433. /// </summary>
  3434. /// <param name="diIds"></param>
  3435. /// <returns></returns>
  3436. private async Task<List<CorporateProfit>> CorporateProfit(List<int> diIds)
  3437. {
  3438. List<CorporateProfit> corporateProfits = new List<CorporateProfit>();
  3439. if (diIds.Count < 1)
  3440. {
  3441. return corporateProfits;
  3442. }
  3443. #region 计算团组利润
  3444. /*
  3445. * 团组报表计算方式
  3446. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  3447. * 应收金额 = 应收表.Sum()
  3448. * 已收金额 = 已收表.Sum()
  3449. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  3450. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  3451. *
  3452. */
  3453. string diIdStr = string.Join(",", diIds);
  3454. string sql = string.Format(@$"Select * From Grp_DelegationInfo Where Isdel = 0 And Id In ({diIdStr})");
  3455. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).ToListAsync();
  3456. #region 费用类型 币种,转账,客户信息
  3457. List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  3458. var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>().Where(it => it.IsDel == 0).ToListAsync();
  3459. #endregion
  3460. foreach (var _diId in diIds)
  3461. {
  3462. List<ExpenditureInfo> expenditureInfos = new List<ExpenditureInfo>();
  3463. #region 团组收入
  3464. /*
  3465. * 应收报表
  3466. */
  3467. decimal frTotalAmount = 0.00M;//应收总金额
  3468. string _frSql = string.Format(@"Select fr.Id,fr.Diid,fr.PriceName,fr.Price,fr.Count,fr.Unit,fr.Currency,
  3469. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  3470. From Fin_ForeignReceivables fr
  3471. Left Join Sys_SetData sd On fr.Currency = sd.Id
  3472. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _diId);
  3473. List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  3474. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  3475. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "应收项", Amount = frTotalAmount });
  3476. /*
  3477. * 已收报表
  3478. */
  3479. decimal prTotalAmount = 0.00M;//已收总金额
  3480. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  3481. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  3482. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  3483. From Fin_ProceedsReceived pr
  3484. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  3485. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  3486. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _diId);
  3487. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  3488. prTotalAmount = _prViews.Sum(it => it.Price);
  3489. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "已收项", Amount = prTotalAmount });
  3490. /*
  3491. * 超支费用
  3492. */
  3493. decimal exTotalAmount = 0.00M;
  3494. string _ecSql = string.Format(@"Select gec.Id As GECId,gec.DiId As GECDiId,gec.PriceName,ccp.PayMoney,sd1.Name As PaymentCurrency,
  3495. ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  3496. sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  3497. From OA2023DB.dbo.Fin_GroupExtraCost gec
  3498. Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  3499. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3500. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3501. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  3502. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3503. Where ccp.IsDel = 0 And ccp.CTable = 1015 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ccp.DiId = {0} Order By CreateTime", _diId);
  3504. List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(_ecSql).ToListAsync();
  3505. exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  3506. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "超支费用", Amount = exTotalAmount });
  3507. /*
  3508. * 收款退还
  3509. */
  3510. decimal promTotalAmount = 0.00M;// 收款退还总金额
  3511. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  3512. //删除了 And prom.PriceType = 1
  3513. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  3514. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  3515. prom.PayType As PrPayType,prom.PriceType As PrPriceType,ccp.*,prom.CreateTime As PrCreateTime
  3516. From Fin_PaymentRefundAndOtherMoney prom
  3517. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  3518. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3519. Where prom.IsDel = 0 And prom.PayType = 1 And ccp.CTable = 285
  3520. And ccp.IsAuditGM = 1 And ccp.IsPay = 1
  3521. And prom.DiId = {0} Order By PrCreateTime", _diId);
  3522. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  3523. foreach (var ropItem in _promDatas)
  3524. {
  3525. string thisCueencyCode = "Unknown";
  3526. string thisCueencyName = "Unknown";
  3527. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  3528. if (currency != null)
  3529. {
  3530. thisCueencyCode = currency.Name;
  3531. thisCueencyName = currency.Remark;
  3532. }
  3533. string orbitalPrivateTransferStr = "Unknown";
  3534. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  3535. if (orbitalPrivateTransfer != null)
  3536. {
  3537. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  3538. }
  3539. string payStr = "Unknown";
  3540. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  3541. if (pay != null)
  3542. {
  3543. payStr = pay.Name;
  3544. }
  3545. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  3546. {
  3547. Id = ropItem.Id,
  3548. DiId = ropItem.DIId,
  3549. PriceName = ropItem.PrPriceName,
  3550. PayCurrencyCode = thisCueencyCode,
  3551. PayCurrencyName = thisCueencyName,
  3552. Price = ropItem.PrPrice,
  3553. CNYPrice = ropItem.RMBPrice,
  3554. ThisRate = ropItem.DayRate,
  3555. Payee = ropItem.Payee,
  3556. PayTime = ropItem.AuditGMDate,
  3557. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  3558. PayType = payStr,
  3559. IsPay = ropItem.IsPay,
  3560. Applicant = ropItem.Appliction
  3561. };
  3562. _promView.Add(gsd_PaymentRefund);
  3563. }
  3564. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  3565. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "收款退还", Amount = promTotalAmount });
  3566. #endregion
  3567. #region 团组支出
  3568. GroupExpenditureView _geView = new GroupExpenditureView();
  3569. #region 酒店预定费用
  3570. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  3571. string hotelFeeSql = string.Format(@"Select hr.Id As HrId,hr.DiId As HrDiId,hr.City,hr.HotelName,hr.CheckInDate,hr.CheckOutDate,
  3572. sd1.Name As PaymentCurrency,hr.SingleRoomPrice,hr.SingleRoomCount,hr.DoubleRoomPrice,
  3573. hr.DoubleRoomCount,hr.SuiteRoomPrice,hr.SuiteRoomCount,hr.OtherRoomPrice,hr.OtherRoomCount,
  3574. hr.BreakfastPrice,sd4.Name As BreakfastCurrency,hr.Isoppay,hr.GovernmentRent,
  3575. sd5.Name As GovernmentRentCurrency,hr.CityTax,sd6.Name As CityTaxCurrency,
  3576. ccp.PayMoney,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,
  3577. sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant
  3578. From Grp_HotelReservations hr
  3579. Left Join Grp_CreditCardPayment ccp On hr.Id = ccp.CId
  3580. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3581. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3582. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  3583. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3584. Left Join Sys_SetData sd4 On hr.BreakfastCurrency = sd4.Id
  3585. Left Join Sys_SetData sd5 On hr.GovernmentRentCurrency = sd5.Id
  3586. Left Join Sys_SetData sd6 On hr.CityTaxCurrency = sd6.Id
  3587. Where hr.IsDel = 0 And ccp.IsDel = 0 And ccp.CTable = 76 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And hr.DiId = {0}
  3588. Order By CheckInDate Asc", _diId);
  3589. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  3590. decimal HotelCNYTotalPrice = groupHotelFeeViews.Sum(it => it.CNYPrice);
  3591. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "酒店预定", Amount = HotelCNYTotalPrice });
  3592. #endregion
  3593. #region 地接费用
  3594. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  3595. string CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.Area,ctggrc.*,ctggrc.Price As PayMoney,
  3596. sd2.name As PaymentCurrency,ccp.PayPercentage,
  3597. (ctggrc.Price / (ccp.PayPercentage / 100)) As AmountPaid,
  3598. (ctggrc.Price / (ccp.PayPercentage / 100) - ctggrc.Price) As BalancePayment,
  3599. ccp.DayRate,(ctggrc.Price * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  3600. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  3601. From Grp_CarTouristGuideGroundReservations ctggr
  3602. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price,sd2.Name As PriceCurrency,
  3603. cggrc.PriceContent
  3604. From Grp_CarTouristGuideGroundReservationsContent cggrc
  3605. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  3606. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  3607. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  3608. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  3609. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  3610. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  3611. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  3612. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3613. Where ctggr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ctggr.DiId = {0}
  3614. Order By CreateTime", _diId);
  3615. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  3616. decimal CTGGRCNYTotalPrice = groupCTGGRFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  3617. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "地接", Amount = CTGGRCNYTotalPrice });
  3618. #endregion
  3619. #region 机票预订费用
  3620. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  3621. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  3622. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  3623. sd1.Name As PayMoneyCurrency,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  3624. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime
  3625. From Grp_AirTicketReservations atr
  3626. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  3627. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3628. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3629. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  3630. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  3631. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3632. Where atr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And atr.DiId = {0} Order By CreateTime", _diId);
  3633. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  3634. decimal AirCNYTotalPrice = groupAirFeeViews.Sum(it => it.CNYPrice);
  3635. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "机票预订", Amount = AirCNYTotalPrice });
  3636. #endregion
  3637. #region 签证费用
  3638. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  3639. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  3640. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  3641. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime
  3642. From Grp_VisaInfo vi
  3643. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  3644. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3645. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3646. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  3647. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3648. Where vi.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And vi.DIId = {0} Order By CreateTime", _diId);
  3649. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  3650. decimal VisaCNYTotalPirce = groupVisaFeeViews.Sum(it => it.PayMoney);
  3651. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "签证", Amount = VisaCNYTotalPirce });
  3652. #endregion
  3653. #region 邀请/公务活动 CTable = 81
  3654. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  3655. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  3656. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  3657. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  3658. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  3659. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  3660. From Grp_InvitationOfficialActivities ioa
  3661. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  3662. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3663. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3664. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  3665. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  3666. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  3667. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  3668. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  3669. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3670. Where ioa.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ioa.Diid = {0} Order By CreateTime", _diId);
  3671. groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
  3672. decimal InvitationalCNYTotalPrice = groupInvitationalFeeViews.Sum(it => it.CNYPrice);
  3673. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "邀请/公务活动", Amount = InvitationalCNYTotalPrice });
  3674. #endregion
  3675. #region 保险费用
  3676. List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
  3677. string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.RMBPrice As CNYPrice,
  3678. sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  3679. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
  3680. From Grp_Customers ic
  3681. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  3682. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3683. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3684. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3685. Where ic.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ic.DiId = {0} Order By CreateTime", _diId);
  3686. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  3687. decimal InsuranceCNYTotalPrice = groupInsuranceFeeViews.Sum(it => it.CNYPrice);
  3688. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "保险费用", Amount = InsuranceCNYTotalPrice });
  3689. #endregion
  3690. #region 其他款项费用 98
  3691. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  3692. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  3693. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  3694. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  3695. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  3696. From Grp_DecreasePayments dp
  3697. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.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 dp.IsDel = 0 And ccp.Ctable = 98 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And dp.Diid = {0}
  3702. Order By CreateTime", _diId);
  3703. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  3704. decimal DecreaseCNYTotalPrice = groupDecreaseFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  3705. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "其他款项", Amount = DecreaseCNYTotalPrice });
  3706. #endregion
  3707. #endregion
  3708. /*
  3709. * 团组报表计算方式
  3710. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  3711. * 应收金额 = 应收表.Sum()
  3712. * 已收金额 = 已收表.Sum()
  3713. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  3714. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  3715. *
  3716. */
  3717. decimal _totalExpenditure = 0.00M; //总支出
  3718. decimal _amountReceivable = 0.00M; //应收金额
  3719. decimal _amountReceived = 0.00M; //已收金额
  3720. decimal _receivableProfit = 0.00M; //应收利润
  3721. decimal _receivedProfit = 0.00M; //已收利润
  3722. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  3723. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount;
  3724. _amountReceivable = frTotalAmount;
  3725. _amountReceived = prTotalAmount;
  3726. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  3727. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  3728. var groupInfo = groupInfos.Find(it => it.Id == _diId);
  3729. corporateProfits.Add(new CorporateProfit()
  3730. {
  3731. DiId = _diId,
  3732. TeamName = groupInfo?.TeamName ?? "Unkwnon",
  3733. CreateDt = Convert.ToDateTime(groupInfo?.CreateTime),
  3734. TotalExpenditure = _totalExpenditure,
  3735. ExpenditureItem = expenditureInfos,
  3736. AmountReceivable = _amountReceivable,
  3737. AmountReceived = _amountReceived,
  3738. ReceivableProfit = _receivableProfit,
  3739. ReceivedProfit = _receivedProfit,
  3740. });
  3741. }
  3742. #endregion
  3743. return corporateProfits;
  3744. }
  3745. //未来预测-地区接团/出团量
  3746. //未来预测-地区酒店预订量
  3747. //未来预测-地区机票预订量
  3748. //未来预测-地区车辆预订量
  3749. /// <summary>
  3750. /// (国家/城市)地区预订数量(团,酒店,机票,车辆)
  3751. /// Details
  3752. /// 待添加权限验证
  3753. /// </summary>
  3754. /// <param name="_dto">团组列表请求dto</param>
  3755. /// <returns></returns>
  3756. [HttpPost("PostRegionalBookingsNumber")]
  3757. //[JsonConverter(typeof(DecimalConverter), 2)]
  3758. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3759. public async Task<IActionResult> PostRegionalBookingsNumber(PostRegionalBookingsNumberDto _dto)
  3760. {
  3761. #region 参数验证
  3762. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  3763. //if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  3764. if (_dto.Type > 1 && _dto.Type > 5) return Ok(JsonView(false, "请输入有效的Type参数,1 团 2 酒店 3 机票 4 车辆"));
  3765. if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));
  3766. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3767. #region 页面操作权限验证
  3768. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3769. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  3770. #endregion
  3771. string sqlWhere = string.Empty;
  3772. //起止时间
  3773. DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");
  3774. DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");
  3775. sqlWhere = string.Format(@$" Where Isdel = 0 ");
  3776. string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");
  3777. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();
  3778. if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));
  3779. List<GroupTypeNumberInfo> datas = new List<GroupTypeNumberInfo>();
  3780. foreach (var item in groupInfos)
  3781. {
  3782. var data = await GroupBookingsNumber(_dto.Type, item);
  3783. if (data.TypeItem.Count > 0)
  3784. {
  3785. datas.Add(data);
  3786. }
  3787. }
  3788. //类型处理
  3789. if (_dto.Type == 1)//接团
  3790. {
  3791. List<GroupBookingNumberView> views = new List<GroupBookingNumberView>();
  3792. //dynamic groupData = null;
  3793. foreach (var item in datas)
  3794. {
  3795. if (item.TypeItem.Count > 0)
  3796. {
  3797. foreach (var item1 in item.TypeItem)
  3798. {
  3799. if (item1.RegionItem.Count > 0)
  3800. {
  3801. GroupInfo groupInfo = new GroupInfo()
  3802. {
  3803. DiId = item.DiId,
  3804. TeamName = item.GroupName,
  3805. CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",
  3806. ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",
  3807. Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",
  3808. };
  3809. views.Add(new GroupBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, GroupItem = new List<GroupInfo>() { groupInfo } });
  3810. }
  3811. }
  3812. }
  3813. }
  3814. var viewsGroup = views.GroupBy(it => it.Name);
  3815. List<GroupBookingNumberView> _view = new List<GroupBookingNumberView>();
  3816. foreach (var item in viewsGroup)
  3817. {
  3818. List<GroupInfo> infos = new List<GroupInfo>();
  3819. foreach (var item1 in item)
  3820. {
  3821. infos.AddRange(item1.GroupItem);
  3822. }
  3823. infos = infos.OrderByDescending(it => it.CreateTime).ToList(); //
  3824. _view.Add(new GroupBookingNumberView() { Name = item.Key, Number = item.Count(), GroupItem = infos });
  3825. }
  3826. _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();
  3827. return Ok(JsonView(true, "操作成功!", _view, _view.Count));
  3828. }
  3829. else if (_dto.Type == 2)
  3830. {
  3831. List<HotelBookingNumberView> views = new List<HotelBookingNumberView>();
  3832. foreach (var item in datas)
  3833. {
  3834. if (item.TypeItem.Count > 0)
  3835. {
  3836. foreach (var item1 in item.TypeItem)
  3837. {
  3838. if (item1.RegionItem.Count > 0)
  3839. {
  3840. foreach (var item2 in item1.RegionItem)
  3841. {
  3842. GroupInfo groupInfo = new GroupInfo()
  3843. {
  3844. DiId = item.DiId,
  3845. TeamName = item.GroupName,
  3846. CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",
  3847. ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",
  3848. Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",
  3849. };
  3850. List<HotelInfo> hotels = new List<HotelInfo>();
  3851. foreach (var item3 in item2.Data)
  3852. {
  3853. StatisticsHotelInfo statisticsHotelInfos = JsonConvert.DeserializeObject<StatisticsHotelInfo>(JsonConvert.SerializeObject(item3));
  3854. HotelInfo hotelInfo = new HotelInfo()
  3855. {
  3856. HotelName = statisticsHotelInfos.HotelName,
  3857. SingleRoomNum = statisticsHotelInfos.SingleRoomNum,
  3858. DoubleRoomNum = statisticsHotelInfos.DoubleRoomNum,
  3859. SuiteRoomNum = statisticsHotelInfos.SuiteRoomNum,
  3860. OtherRoomNum = statisticsHotelInfos.OtherRoomNum,
  3861. GroupInfo = groupInfo
  3862. };
  3863. hotels.Add(hotelInfo);
  3864. }
  3865. views.Add(new HotelBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, HotelItem = hotels });
  3866. }
  3867. }
  3868. }
  3869. }
  3870. }
  3871. var viewsGroup = views.GroupBy(it => it.Name);
  3872. List<HotelBookingNumberView> _view = new List<HotelBookingNumberView>();
  3873. foreach (var item in viewsGroup)
  3874. {
  3875. List<HotelInfo> infos = new List<HotelInfo>();
  3876. foreach (var item1 in item)
  3877. {
  3878. infos.AddRange(item1.HotelItem);
  3879. }
  3880. _view.Add(new HotelBookingNumberView() { Name = item.Key, Number = item.Count(), HotelItem = infos });
  3881. }
  3882. _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();
  3883. return Ok(JsonView(true, "操作成功!", views, views.Count));
  3884. }
  3885. return Ok(JsonView(false, "操作失败!"));
  3886. #endregion
  3887. }
  3888. /// <summary>
  3889. /// 计算团组ALLType预订数量
  3890. /// </summary>
  3891. /// <param name="type"></param>
  3892. /// <param name="info"></param>
  3893. /// <returns></returns>
  3894. private async Task<GroupTypeNumberInfo> GroupBookingsNumber(int type, Grp_DelegationInfo info)
  3895. {
  3896. GroupTypeNumberInfo _view = new GroupTypeNumberInfo();
  3897. if (info == null)
  3898. {
  3899. return _view;
  3900. }
  3901. _view.DiId = info.Id;
  3902. _view.GroupName = info.TeamName;
  3903. List<TypeInfo> _types = new List<TypeInfo>();
  3904. #region 计算团组ALLType预订数量
  3905. if (type == 1)
  3906. {
  3907. //接团 客户集团所在地区
  3908. string group_region = string.Empty;
  3909. int group_number = 0;
  3910. if (!string.IsNullOrEmpty(info.ClientUnit))
  3911. {
  3912. var _NewClientData = await _sqlSugar.Queryable<Crm_NewClientData>()
  3913. .Where(it => it.IsDel == 0 && it.Client.Equals(AesEncryptionHelper.Encrypt(info.ClientUnit)))
  3914. .FirstAsync();
  3915. if (_NewClientData != null)
  3916. {
  3917. var regionInfo = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.Id == _NewClientData.Lvlid).FirstAsync();
  3918. if (regionInfo != null)
  3919. {
  3920. group_region = regionInfo.Name.Replace("级", "");
  3921. group_number++;
  3922. }
  3923. }
  3924. }
  3925. if (group_number > 0)
  3926. {
  3927. _types.Add(new TypeInfo() { Id = 1, RegionItem = new List<RegionInfo>() { new RegionInfo() { Name = group_region, Number = group_number } } });
  3928. }
  3929. }
  3930. else if (type == 2)
  3931. {
  3932. //酒店
  3933. var hotelInfos = await _sqlSugar.Queryable<Grp_HotelReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  3934. if (hotelInfos.Count > 0)
  3935. {
  3936. List<RegionInfo> hotelRegions = new List<RegionInfo>();
  3937. foreach (var item in hotelInfos)
  3938. {
  3939. var hotelNumberInfo = new StatisticsHotelInfo()
  3940. {
  3941. HotelName = item.HotelName,
  3942. SingleRoomNum = item.SingleRoomCount,
  3943. DoubleRoomNum = item.DoubleRoomCount,
  3944. SuiteRoomNum = item.SuiteRoomCount,
  3945. OtherRoomNum = item.OtherRoomCount,
  3946. };
  3947. int hotelRoomTotal = item.SingleRoomCount + item.DoubleRoomCount + item.SuiteRoomCount + item.OtherRoomCount;
  3948. if (hotelRegions.Select(it => it.Name).ToList().Contains(item.City))
  3949. {
  3950. RegionInfo hotelRegion = hotelRegions.Find(it => it.Name.Equals(item.City));
  3951. if (hotelRegion != null)
  3952. {
  3953. hotelRegions.Remove(hotelRegion);
  3954. if (hotelRegion.Data.Count > 0)
  3955. {
  3956. hotelRegion.Data.Add(hotelNumberInfo);
  3957. }
  3958. hotelRegion.Number += hotelRoomTotal;
  3959. hotelRegions.Add(hotelRegion);
  3960. }
  3961. }
  3962. else
  3963. {
  3964. hotelRegions.Add(new RegionInfo() { Name = item.City, Number = hotelRoomTotal, Data = new List<dynamic>() { hotelNumberInfo } });
  3965. }
  3966. }
  3967. _types.Add(new TypeInfo() { Id = 2, RegionItem = hotelRegions });
  3968. }
  3969. }
  3970. else if (type == 3)
  3971. {
  3972. //机票
  3973. var airTicketInfos = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
  3974. .LeftJoin<Grp_CreditCardPayment>((atr, ccp) => atr.Id == ccp.CId && ccp.IsPay == 1)
  3975. .LeftJoin<Sys_SetData>((atr, ccp, sd) => atr.CType == sd.Id)
  3976. .Where((atr, ccp, sd) => atr.IsDel == 0 && atr.DIId == info.Id)
  3977. .Select((atr, ccp, sd) => new { atr.ClientNum, atr.CType, ccp.Payee, AirType = sd.Name })
  3978. .ToListAsync();
  3979. if (airTicketInfos.Count > 0)
  3980. {
  3981. List<RegionInfo> airTicketRegions = new List<RegionInfo>();
  3982. foreach (var item in airTicketInfos)
  3983. {
  3984. var ticketClass = new
  3985. {
  3986. TiketClass = item.AirType,
  3987. Number = item.ClientNum
  3988. };
  3989. if (airTicketRegions.Select(it => it.Name).ToList().Contains(item.Payee))
  3990. {
  3991. RegionInfo airTicketRegion = airTicketRegions.Find(it => it.Name.Equals(item.Payee));
  3992. if (airTicketRegion != null)
  3993. {
  3994. airTicketRegions.Remove(airTicketRegion);
  3995. if (airTicketRegion.Data.Count > 0)
  3996. {
  3997. airTicketRegion.Data.Add(ticketClass);
  3998. }
  3999. airTicketRegion.Number += item.ClientNum;
  4000. airTicketRegions.Add(airTicketRegion);
  4001. }
  4002. }
  4003. else
  4004. {
  4005. airTicketRegions.Add(new RegionInfo() { Name = item.Payee, Number = item.ClientNum, Data = new List<dynamic>() { ticketClass } });
  4006. }
  4007. }
  4008. _types.Add(new TypeInfo() { Id = 3, RegionItem = airTicketRegions });
  4009. }
  4010. }
  4011. else if (type == 4)
  4012. {
  4013. //车辆
  4014. var opInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  4015. var opContentInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservationsContent>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  4016. if (opInfos.Count > 0)
  4017. {
  4018. List<RegionInfo> opRegions = new List<RegionInfo>();
  4019. foreach (var item in opInfos)
  4020. {
  4021. int carNum = 0;
  4022. var opContentInfo = opContentInfos.Where(it => it.CTGGRId == item.Id && it.SId == 91).ToList();
  4023. if (opContentInfo.Count > 0)
  4024. {
  4025. foreach (var item1 in opContentInfo)
  4026. {
  4027. if (item1.Price > 0 && item1.Count > 0)
  4028. {
  4029. carNum += item1.Count;
  4030. }
  4031. }
  4032. }
  4033. if (carNum > 0)
  4034. {
  4035. var opData = new
  4036. {
  4037. ServiceCompany = item.ServiceCompany,
  4038. BusName = item.BusName,
  4039. Numbuer = carNum
  4040. };
  4041. if (opRegions.Select(it => it.Name).ToList().Contains(item.Area))
  4042. {
  4043. RegionInfo opRegion = opRegions.Find(it => it.Name.Equals(item.Area));
  4044. if (opRegion != null)
  4045. {
  4046. opRegions.Remove(opRegion);
  4047. if (opRegion.Data.Count > 0)
  4048. {
  4049. opRegion.Data.Add(opData);
  4050. }
  4051. opRegion.Number += carNum;
  4052. opRegions.Add(opRegion);
  4053. }
  4054. }
  4055. else
  4056. {
  4057. opRegions.Add(new RegionInfo() { Name = item.Area, Number = carNum, Data = new List<dynamic>() { opData } });
  4058. }
  4059. }
  4060. }
  4061. _types.Add(new TypeInfo() { Id = 4, RegionItem = opRegions });
  4062. }
  4063. }
  4064. #endregion
  4065. _view.TypeItem = _types;
  4066. return _view;
  4067. }
  4068. #endregion
  4069. #region 市场部销售额
  4070. /// <summary>
  4071. /// 市场部销售额
  4072. /// Init 基础数据(公司/人员/年份/季度/月份)
  4073. /// </summary>
  4074. /// <param name="_dto">市场部销售额请求dto</param>
  4075. /// <returns></returns>
  4076. [HttpPost("PostMarketingSalesInitData")]
  4077. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4078. public async Task<IActionResult> PostMarketingSalesInitData(MarketingSalesInitDataDto _dto)
  4079. {
  4080. #region 参数验证
  4081. MarketingSalesInitDataDtoFoalidator validationRules = new MarketingSalesInitDataDtoFoalidator();
  4082. var validResult = await validationRules.ValidateAsync(_dto);
  4083. if (!validResult.IsValid)
  4084. {
  4085. var errors = new StringBuilder();
  4086. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4087. return Ok(JsonView(false, errors.ToString()));
  4088. }
  4089. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4090. #region 页面操作权限验证
  4091. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4092. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4093. #endregion
  4094. var companyData = _sqlSugar.Queryable<Sys_Company>().Where(it => it.IsDel == 0)
  4095. .Select(it => new { id = it.Id, name = it.CompanyName })
  4096. .ToList();
  4097. List<int> companyIds = companyData.Select(it => it.id).ToList();
  4098. List<int> pickGroupUserIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0)
  4099. .Select(it => it.JietuanOperator)
  4100. .ToList();
  4101. var userData = _sqlSugar.Queryable<Sys_Users>()
  4102. .Where(it => it.IsDel == 0 && (pickGroupUserIds.Contains(it.Id) || it.Id == 21))
  4103. .Select(it => new { id = it.Id, companyId = it.CompanyId, name = it.CnName })
  4104. .ToList();
  4105. companyData.Insert(0, new { id = -1, name = "全部" });
  4106. userData.Insert(0, new { id = -1, companyId = -1, name = "全部" });
  4107. #region 年份
  4108. var dtData = new List<dynamic>();
  4109. int dt = DateTime.Now.Year;
  4110. for (int y = dt; y >= dt - 4; y--)
  4111. {
  4112. //季度
  4113. var quarterDatas = new List<dynamic>();
  4114. quarterDatas.Add(new { name = "全部", beginDt = $"{y}-01-01", endDt = $"{y}-12-31" });
  4115. for (int q = 0; q < 4; q++)
  4116. {
  4117. dynamic quarterData = null;
  4118. if (q == 0)
  4119. {
  4120. var monthDatas = new List<dynamic>();
  4121. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-01-01", endDt = $" {y}-03-31" });
  4122. for (int m = 1; m < 4; m++)
  4123. {
  4124. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  4125. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  4126. }
  4127. //quarterData = new { name = "第一季度", beginDt = $"{y}-01-01", endDt = $" {y}-03-31", monthData = monthDatas };
  4128. quarterData = new { name = "第一季度", monthData = monthDatas };
  4129. }
  4130. else if (q == 1)
  4131. {
  4132. var monthDatas = new List<dynamic>();
  4133. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-04-01", endDt = $"{y}-06-30" });
  4134. for (int m = 4; m < 7; m++)
  4135. {
  4136. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  4137. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  4138. }
  4139. //quarterData = new { name = "第二季度", beginDt = $"{y}-04-01", endDt = $"{y}-06-30", monthData = monthDatas };
  4140. quarterData = new { name = "第二季度", monthData = monthDatas };
  4141. }
  4142. else if (q == 2)
  4143. {
  4144. var monthDatas = new List<dynamic>();
  4145. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-07-01", endDt = $"{y}-09-30" });
  4146. for (int m = 7; m < 10; m++)
  4147. {
  4148. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  4149. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  4150. }
  4151. //quarterData = new { name = "第三季度", beginDt = $"{y}-07-01", endDt = $"{y}-09-30", monthData = monthDatas };
  4152. quarterData = new { name = "第三季度", monthData = monthDatas };
  4153. }
  4154. else if (q == 3)
  4155. {
  4156. var monthDatas = new List<dynamic>();
  4157. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-10-01", endDt = $"{y}-12-31" });
  4158. for (int m = 10; m < 13; m++)
  4159. {
  4160. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  4161. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  4162. }
  4163. //quarterData = new { name = "第四季度", beginDt = $"{y}-10-01", endDt = $"{y}-12-31", monthData = monthDatas };
  4164. quarterData = new { name = "第四季度", monthData = monthDatas };
  4165. }
  4166. quarterDatas.Add(quarterData);
  4167. }
  4168. dtData.Add(new
  4169. {
  4170. year = y,
  4171. //yearData = new { beginDt = $"{y}-01-01", endDt = $"{y}-12-31" },
  4172. quarterData = quarterDatas,
  4173. });
  4174. }
  4175. #endregion
  4176. return Ok(JsonView(true, "操作成功!", new { companyData = companyData, userData = userData, dtData = dtData }));
  4177. #endregion
  4178. }
  4179. private static string ConvertToChinese(int month)
  4180. {
  4181. if (month < 1 || month > 12)
  4182. throw new ArgumentOutOfRangeException(nameof(month), "月份必须在1到12之间。");
  4183. var cultureInfo = new System.Globalization.CultureInfo("zh-CN");
  4184. var dateTimeFormat = cultureInfo.DateTimeFormat;
  4185. return dateTimeFormat.GetMonthName(month);
  4186. }
  4187. /// <summary>
  4188. /// 市场部销售额
  4189. /// 年度/季度/月度 报表(同比)
  4190. /// </summary>
  4191. /// <param name="_dto">市场部销售额请求dto</param>
  4192. /// <returns></returns>
  4193. [HttpPost("PostMarketingSalesStatistics")]
  4194. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4195. public async Task<IActionResult> PostMarketingSalesStatistics_Year(MarketingSalesStatisticsDto _dto)
  4196. {
  4197. #region 参数验证
  4198. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4199. var validResult = await validationRules.ValidateAsync(_dto);
  4200. if (!validResult.IsValid)
  4201. {
  4202. var errors = new StringBuilder();
  4203. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4204. return Ok(JsonView(false, errors.ToString()));
  4205. }
  4206. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4207. #region 页面操作权限验证
  4208. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4209. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4210. #endregion
  4211. #endregion
  4212. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4213. return Ok(JsonView(true, "操作成功!", await GroupSales(_dto.CompanyId, _dto.GroupPickupUserId, beginDt, endDt)));
  4214. }
  4215. private async Task<List<int>> GetUserIds(int companyId, int groupPickupUserId)
  4216. {
  4217. //全部人员Id
  4218. //查询所有公司的市场部
  4219. var pickGroupIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0).Select(it => it.JietuanOperator).Distinct().ToList();
  4220. var userIds = new List<int>();
  4221. var userDatas = await _sqlSugar.Queryable<Sys_Users>()
  4222. .InnerJoin<Sys_Company>((u, c) => u.CompanyId == c.Id)
  4223. .Where((u, c) => u.IsDel == 0 && pickGroupIds.Contains(u.Id))
  4224. .Select((u, c) => new { u.Id, u.CompanyId, u.CnName })
  4225. .ToListAsync();
  4226. userIds = userDatas.Select(it => it.Id).ToList();
  4227. if (companyId > 0)
  4228. {
  4229. userIds = userDatas.Where(it => it.CompanyId == companyId).Select(it => it.Id).ToList();
  4230. }
  4231. if (groupPickupUserId > 0)
  4232. {
  4233. userIds = userDatas.Where(it => it.Id == groupPickupUserId).Select(it => it.Id).ToList();
  4234. }
  4235. return userIds;
  4236. }
  4237. /// <summary>
  4238. /// 计算团组销售额
  4239. /// </summary>
  4240. /// <param name="companyId"></param>
  4241. /// <param name="groupPickupUserId"></param>
  4242. /// <param name="beginDt"></param>
  4243. /// <param name="endDt"></param>
  4244. /// <returns></returns>
  4245. private async Task<SalesYOYView> GroupSales(int companyId, int groupPickupUserId, string beginDt, string endDt)
  4246. {
  4247. decimal thisSales = 0.00M, lastSales = 0.00M, yoy = 1.00M;
  4248. var _view = new SalesYOYView();
  4249. List<int> userIds = new List<int>();
  4250. userIds = await GetUserIds(companyId, groupPickupUserId);
  4251. string userSqlWhere = "";
  4252. if (userIds.Count > 0)
  4253. {
  4254. userSqlWhere = string.Format($" And Id IN ({string.Join(',', userIds)})");
  4255. }
  4256. else
  4257. {
  4258. _view = new SalesYOYView
  4259. {
  4260. thisYearSales = "0.00",
  4261. lastYearSales = "0.00",
  4262. };
  4263. return _view;
  4264. }
  4265. string lastBeginDt = Convert.ToDateTime(beginDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss"),
  4266. lastEndDt = Convert.ToDateTime(endDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss");
  4267. // string salesSql = string.Format(@"
  4268. //SELECT
  4269. // 'ThisSales' As [Name],
  4270. // CAST(SUM(Sales) AS decimal(12,2)) As Sales
  4271. //FROM
  4272. // (
  4273. // SELECT di.VisitDate,
  4274. // (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  4275. // WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  4276. // ) AS Sales
  4277. // FROM
  4278. // Grp_DelegationInfo di
  4279. // WHERE di.IsDel = 0 AND di.IsSure = 1
  4280. // AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
  4281. // AND di.VisitDate BETWEEN '{1}' AND '{2}'
  4282. // ) temp
  4283. //Union ALL
  4284. //SELECT
  4285. // 'LastSales' 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 {3})
  4297. // AND di.VisitDate BETWEEN '{4}' AND '{5}'
  4298. // ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
  4299. string salesSql = string.Format(@"
  4300. SELECT
  4301. 'ThisSales' 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
  4312. AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
  4313. AND di.VisitDate BETWEEN '{1}' AND '{2}'
  4314. ) temp
  4315. Union ALL
  4316. SELECT
  4317. 'LastSales' 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 {3})
  4329. AND di.IsBid = 0
  4330. AND di.TeamName Not Like '%投标%'
  4331. AND di.VisitDate BETWEEN '{4}' AND '{5}'
  4332. ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
  4333. var salesData = await _sqlSugar.SqlQueryable<SalesView>(salesSql).ToListAsync();
  4334. thisSales = salesData.Where(x => x.Name.Equals("ThisSales")).First()?.Sales ?? 0;
  4335. lastSales = salesData.Where(x => x.Name.Equals("LastSales")).First()?.Sales ?? 0;
  4336. if (lastSales != 0 && thisSales != 0) yoy = (thisSales - lastSales) / lastSales;
  4337. return new SalesYOYView()
  4338. {
  4339. thisYearSales = thisSales.ToString("#0.00"),
  4340. lastYearSales = lastSales.ToString("#0.00"),
  4341. yoy = yoy.ToString("#0.00")
  4342. };
  4343. }
  4344. private class SalesView
  4345. {
  4346. public string Name { get; set; }
  4347. public decimal Sales { get; set; }
  4348. }
  4349. private class SalesYOYView
  4350. {
  4351. public string thisYearSales { get; set; }
  4352. public string lastYearSales { get; set; }
  4353. public string yoy { get; set; } = "1.00";
  4354. }
  4355. /// <summary>
  4356. /// 市场部销售额
  4357. /// 团组列表
  4358. /// </summary>
  4359. /// <param name="_dto">市场部销售额请求dto</param>
  4360. /// <returns></returns>
  4361. [HttpPost("PostMarketingSalesGroupList")]
  4362. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4363. public async Task<IActionResult> PostMarketingSalesGroupList(MarketingSalesGroupListDto _dto)
  4364. {
  4365. #region 参数验证
  4366. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4367. var validResult = await validationRules.ValidateAsync(_dto);
  4368. if (!validResult.IsValid)
  4369. {
  4370. var errors = new StringBuilder();
  4371. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4372. return Ok(JsonView(false, errors.ToString()));
  4373. }
  4374. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4375. #region 页面操作权限验证
  4376. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4377. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4378. #endregion
  4379. #endregion
  4380. string userSql = "";
  4381. List<int> userIds = new List<int>();
  4382. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4383. if (userIds.Count <= 0)
  4384. {
  4385. return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  4386. }
  4387. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  4388. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  4389. {
  4390. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  4391. }
  4392. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4393. // string sql = string.Format(@$"SELECT
  4394. // ROW_NUMBER() OVER (
  4395. // ORDER BY
  4396. // CollectionDays
  4397. // ) AS RowNumber,
  4398. // *
  4399. //FROM
  4400. // (
  4401. // SELECT
  4402. // di.Id,
  4403. // di.TeamName,
  4404. // di.ClientUnit,
  4405. // di.ClientName,
  4406. // di.VisitDate,
  4407. // di.VisitPNumber,
  4408. // di.JietuanOperator,
  4409. // di.VisitEndDate,
  4410. // (
  4411. // SELECT
  4412. // CAST(
  4413. // COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4414. // ) AS GroupSales
  4415. // FROM
  4416. // Fin_ForeignReceivables
  4417. // WHERE
  4418. // IsDel = 0
  4419. // AND di.Id = Diid
  4420. // AND AddingWay IN (0, 1, 2)
  4421. // ) AS GroupSales,
  4422. // u.CnName AS GroupPickupUser,
  4423. // DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  4424. // FROM
  4425. // Grp_DelegationInfo di
  4426. // WITH
  4427. // (NoLock)
  4428. // LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  4429. // WHERE
  4430. // di.Isdel = 0
  4431. // AND di.IsSure = 1 {userSql}
  4432. // AND VisitDate Between '{beginDt}' And '{endDt}'
  4433. // ) Temp ");
  4434. string sql = string.Format(@$"SELECT
  4435. ROW_NUMBER() OVER (
  4436. ORDER BY
  4437. CollectionDays
  4438. ) AS RowNumber,
  4439. *
  4440. FROM
  4441. (
  4442. SELECT
  4443. di.Id,
  4444. di.TeamName,
  4445. di.ClientUnit,
  4446. di.ClientName,
  4447. di.VisitDate,
  4448. di.VisitPNumber,
  4449. di.JietuanOperator,
  4450. di.VisitEndDate,
  4451. (
  4452. SELECT
  4453. CAST(
  4454. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4455. ) AS GroupSales
  4456. FROM
  4457. Fin_ForeignReceivables
  4458. WHERE
  4459. IsDel = 0
  4460. AND di.Id = Diid
  4461. AND AddingWay IN (0, 1, 2)
  4462. ) AS GroupSales,
  4463. u.CnName AS GroupPickupUser,
  4464. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  4465. FROM
  4466. Grp_DelegationInfo di
  4467. WITH
  4468. (NoLock)
  4469. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  4470. WHERE
  4471. di.Isdel = 0
  4472. AND (
  4473. SELECT
  4474. CAST(
  4475. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4476. ) AS GroupSales
  4477. FROM
  4478. Fin_ForeignReceivables
  4479. WHERE
  4480. IsDel = 0
  4481. AND di.Id = Diid
  4482. AND AddingWay IN (0, 1, 2)
  4483. ) > 0
  4484. {userSql}
  4485. AND di.IsBid = 0
  4486. AND di.TeamName Not Like '%投标%'
  4487. AND VisitDate Between '{beginDt}' And '{endDt}'
  4488. ) Temp ");
  4489. RefAsync<int> total = 0;
  4490. var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  4491. return Ok(JsonView(true, "操作成功!", groupData, total));
  4492. }
  4493. /// <summary>
  4494. /// 市场部销售额
  4495. /// 团组列表Excel下载
  4496. /// </summary>
  4497. /// <param name="_dto">市场部销售额请求dto</param>
  4498. /// <returns></returns>
  4499. [HttpPost("PostMarketingSalesGroupExcel")]
  4500. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4501. public async Task<IActionResult> PostMarketingSalesGroupExcel(MarketingSalesGroupListDto _dto)
  4502. {
  4503. #region 参数验证
  4504. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4505. var validResult = await validationRules.ValidateAsync(_dto);
  4506. if (!validResult.IsValid)
  4507. {
  4508. var errors = new StringBuilder();
  4509. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4510. return Ok(JsonView(false, errors.ToString()));
  4511. }
  4512. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4513. #region 页面操作权限验证
  4514. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4515. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4516. #endregion
  4517. #endregion
  4518. string userSql = "";
  4519. var userIds = new List<int>();
  4520. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4521. if (userIds.Count <= 0)
  4522. {
  4523. return Ok(JsonView(false));
  4524. }
  4525. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  4526. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  4527. {
  4528. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  4529. }
  4530. string beginDt = $"{_dto.BeginDt} 00:00:00",
  4531. endDt = $"{_dto.EndDt} 23:59:59";
  4532. string sql = string.Format(@$"SELECT
  4533. ROW_NUMBER() OVER (
  4534. ORDER BY
  4535. CollectionDays
  4536. ) AS RowNumber,
  4537. *
  4538. FROM
  4539. (
  4540. SELECT
  4541. di.Id,
  4542. di.TeamName,
  4543. di.ClientUnit,
  4544. di.ClientName,
  4545. di.VisitDate,
  4546. di.VisitPNumber,
  4547. di.JietuanOperator,
  4548. di.VisitEndDate,
  4549. (
  4550. SELECT
  4551. CAST(
  4552. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4553. ) AS GroupSales
  4554. FROM
  4555. Fin_ForeignReceivables
  4556. WHERE
  4557. IsDel = 0
  4558. AND di.Id = Diid
  4559. AND AddingWay IN (0, 1, 2)
  4560. ) AS GroupSales,
  4561. u.CnName AS GroupPickupUser,
  4562. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  4563. FROM
  4564. Grp_DelegationInfo di
  4565. WITH
  4566. (NoLock)
  4567. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  4568. WHERE
  4569. di.Isdel = 0
  4570. AND (
  4571. SELECT
  4572. CAST(
  4573. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4574. ) AS GroupSales
  4575. FROM
  4576. Fin_ForeignReceivables
  4577. WHERE
  4578. IsDel = 0
  4579. AND di.Id = Diid
  4580. AND AddingWay IN (0, 1, 2)
  4581. ) > 0
  4582. {userSql}
  4583. AND di.IsBid = 0
  4584. AND di.TeamName Not Like '%投标%'
  4585. AND VisitDate Between '{beginDt}' And '{endDt}'
  4586. ) Temp ");
  4587. var view = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToListAsync();
  4588. if (view.Count < 1) return Ok(JsonView(false, "暂无数据!"));
  4589. //DataTable dt = GeneralMethod.
  4590. DataTable dt = CommonFun.GetDataTableFromIList(view);
  4591. dt.TableName = $"_view";
  4592. WorkbookDesigner designer = new WorkbookDesigner();
  4593. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/营业额团组报表模板.xls");
  4594. designer.SetDataSource(dt);
  4595. designer.SetDataSource("Total", view.Sum(x => x.GroupSales));
  4596. designer.Workbook.Worksheets[0].Name = "营业额团组报表";
  4597. designer.Process();
  4598. string fileName = $"MarketingSales/{_dto.BeginDt}~{_dto.EndDt}营业额团组报表{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
  4599. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  4600. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  4601. return Ok(JsonView(true, "操作成功", new { url = rst }));
  4602. }
  4603. /// <summary>
  4604. /// 市场部销售额
  4605. /// 客户类型、客户等级 统计
  4606. /// </summary>
  4607. /// <param name="_dto">市场部销售额请求dto</param>
  4608. /// <returns></returns>
  4609. [HttpPost("PostMarketingSalesGroupStatistics")]
  4610. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4611. public async Task<IActionResult> PostMarketingSalesGroupStatistics(MarketingSalesGroupStatisticsDto _dto)
  4612. {
  4613. #region 参数验证
  4614. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4615. var validResult = await validationRules.ValidateAsync(_dto);
  4616. if (!validResult.IsValid)
  4617. {
  4618. var errors = new StringBuilder();
  4619. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4620. return Ok(JsonView(false, errors.ToString()));
  4621. }
  4622. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4623. #region 页面操作权限验证
  4624. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4625. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4626. #endregion
  4627. #endregion
  4628. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4629. List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4630. string userSql = "";
  4631. if (userIds.Count > 0)
  4632. {
  4633. userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
  4634. }
  4635. else
  4636. {
  4637. if (_dto.PortType == 2 || _dto.PortType == 3)
  4638. {
  4639. return Ok(JsonView(true, "操作成功!", new List<object> { }));
  4640. }
  4641. else
  4642. {
  4643. return Ok(JsonView(true, "操作成功!", new
  4644. {
  4645. customerTypeData = new List<object> { },
  4646. clientGradeData = new List<object> { }
  4647. }));
  4648. }
  4649. }
  4650. string sql = "";
  4651. if (_dto.StatisticsType == 1)
  4652. {
  4653. sql = string.Format(@$"Select
  4654. sd.[Name],
  4655. Count(*) As [Count]
  4656. From Grp_DelegationInfo di
  4657. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  4658. Where di.Isdel = 0
  4659. And (
  4660. SELECT
  4661. CAST(
  4662. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4663. ) AS GroupSales
  4664. FROM
  4665. Fin_ForeignReceivables fr
  4666. WHERE
  4667. fr.IsDel = 0
  4668. AND di.Id = fr.Diid
  4669. AND AddingWay IN (0, 1, 2)
  4670. ) > 0
  4671. {userSql}
  4672. AND di.IsBid = 0
  4673. AND di.TeamName Not Like '%投标%'
  4674. And VisitDate Between '{beginDt}' And '{endDt}'
  4675. Group By [Name]
  4676. Order By Count Desc");
  4677. }
  4678. else if (_dto.StatisticsType == 2)
  4679. {
  4680. sql = string.Format(@$"Select
  4681. sd.[Name],
  4682. Count(*) As [Count]
  4683. From Grp_DelegationInfo di
  4684. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  4685. Where di.Isdel = 0
  4686. And (
  4687. SELECT
  4688. CAST(
  4689. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4690. ) AS GroupSales
  4691. FROM
  4692. Fin_ForeignReceivables fr
  4693. WHERE
  4694. fr.IsDel = 0
  4695. AND di.Id = fr.Diid
  4696. AND AddingWay IN (0, 1, 2)
  4697. ) > 0
  4698. {userSql}
  4699. AND di.IsBid = 0
  4700. AND di.TeamName Not Like '%投标%'
  4701. And VisitDate Between '{beginDt}' And '{endDt}'
  4702. Group By [Name]
  4703. Order By Count Desc");
  4704. }
  4705. else return Ok(JsonView(false, "StatisticsType不在可取范围!"));
  4706. if (_dto.PortType == 1)
  4707. {
  4708. string sql1 = string.Format(@$"Select
  4709. sd.[Name],
  4710. Count(*) As [Count]
  4711. From Grp_DelegationInfo di
  4712. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  4713. Where di.Isdel = 0
  4714. And (
  4715. SELECT
  4716. CAST(
  4717. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4718. ) AS GroupSales
  4719. FROM
  4720. Fin_ForeignReceivables fr
  4721. WHERE
  4722. fr.IsDel = 0
  4723. AND di.Id = fr.Diid
  4724. AND AddingWay IN (0, 1, 2)
  4725. ) > 0
  4726. {userSql}
  4727. AND di.IsBid = 0
  4728. AND di.TeamName Not Like '%投标%'
  4729. And VisitDate Between '{beginDt}' And '{endDt}'
  4730. Group By [Name]
  4731. Order By Count Desc");
  4732. var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
  4733. string sql2 = string.Format(@$"Select
  4734. sd.[Name],
  4735. Count(*) As [Count]
  4736. From Grp_DelegationInfo di
  4737. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  4738. Where di.Isdel = 0
  4739. And (
  4740. SELECT
  4741. CAST(
  4742. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4743. ) AS GroupSales
  4744. FROM
  4745. Fin_ForeignReceivables fr
  4746. WHERE
  4747. fr.IsDel = 0
  4748. AND di.Id = fr.Diid
  4749. AND AddingWay IN (0, 1, 2)
  4750. ) > 0
  4751. {userSql}
  4752. AND di.IsBid = 0
  4753. AND di.TeamName Not Like '%投标%'
  4754. And VisitDate Between '{beginDt}' And '{endDt}'
  4755. Group By [Name]
  4756. Order By Count Desc");
  4757. var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
  4758. return Ok(JsonView(true, "操作成功!", new
  4759. {
  4760. customerTypeData = customerTypeData,
  4761. clientGradeData = clientGradeData
  4762. }));
  4763. }
  4764. else if (_dto.PortType == 2 || _dto.PortType == 3)
  4765. {
  4766. var data = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql).ToListAsync();
  4767. return Ok(JsonView(true, "操作成功!", data, data.Count));
  4768. }
  4769. else return Ok(JsonView(false, MsgTips.Port));
  4770. }
  4771. /// <summary>
  4772. /// 市场部销售额
  4773. /// 接单排名
  4774. /// </summary>
  4775. /// <param name="_dto">市场部销售额请求dto</param>
  4776. /// <returns></returns>
  4777. [HttpPost("PostMarketingSalesOrderRanking")]
  4778. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4779. public async Task<IActionResult> PostMarketingSalesOrderRanking(MarketingSalesOrderRankingDto _dto)
  4780. {
  4781. #region 参数验证
  4782. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4783. var validResult = await validationRules.ValidateAsync(_dto);
  4784. if (!validResult.IsValid)
  4785. {
  4786. var errors = new StringBuilder();
  4787. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4788. return Ok(JsonView(false, errors.ToString()));
  4789. }
  4790. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4791. #region 页面操作权限验证
  4792. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4793. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4794. #endregion
  4795. #endregion
  4796. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4797. List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4798. string userSql = "";
  4799. if (userIds.Count > 0)
  4800. {
  4801. userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
  4802. }
  4803. else return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  4804. string sql = string.Format(@$"Select
  4805. ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
  4806. u.CnName As UserName,
  4807. Count(*) As [Count]
  4808. From Grp_DelegationInfo di
  4809. Left Join Sys_Users u On di.JietuanOperator = u.Id
  4810. Where di.Isdel = 0
  4811. AND (
  4812. SELECT
  4813. CAST(
  4814. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4815. ) AS GroupSales
  4816. FROM
  4817. Fin_ForeignReceivables fr
  4818. WHERE
  4819. fr.IsDel = 0
  4820. AND di.Id = fr.Diid
  4821. AND AddingWay IN (0, 1, 2)
  4822. ) > 0
  4823. {userSql}
  4824. AND di.IsBid = 0
  4825. AND di.TeamName Not Like '%投标%'
  4826. AND VisitDate Between '{beginDt}' AND '{endDt}'
  4827. Group By CnName");
  4828. RefAsync<int> total = 0;
  4829. var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  4830. return Ok(JsonView(true, "操作成功!", rankingData, total));
  4831. }
  4832. /// <summary>
  4833. /// 市场部销售额
  4834. /// 团组列表、客户类型、客户等级、接单排名
  4835. /// </summary>
  4836. /// <param name="_dto">市场部销售额请求dto</param>
  4837. /// <returns></returns>
  4838. [HttpPost("PostMarketingSalesGroupItem")]
  4839. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4840. public async Task<IActionResult> PostMarketingSalesGroupItem(MarketingSalesGroupListDto _dto)
  4841. {
  4842. #region 参数验证
  4843. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4844. var validResult = await validationRules.ValidateAsync(_dto);
  4845. if (!validResult.IsValid)
  4846. {
  4847. var errors = new StringBuilder();
  4848. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4849. return Ok(JsonView(false, errors.ToString()));
  4850. }
  4851. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4852. #region 页面操作权限验证
  4853. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4854. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4855. #endregion
  4856. #endregion
  4857. string userSql = "";
  4858. List<int> userIds = new List<int>();
  4859. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4860. if (userIds.Count <= 0)
  4861. {
  4862. return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  4863. }
  4864. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  4865. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  4866. {
  4867. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  4868. }
  4869. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4870. #region 团组List
  4871. string sql = string.Format(@$"SELECT
  4872. ROW_NUMBER() OVER (
  4873. ORDER BY
  4874. CollectionDays
  4875. ) AS RowNumber,
  4876. *
  4877. FROM
  4878. (
  4879. SELECT
  4880. di.Id,
  4881. di.TeamName,
  4882. di.ClientUnit,
  4883. di.ClientName,
  4884. di.VisitDate,
  4885. di.VisitPNumber,
  4886. di.JietuanOperator,
  4887. di.VisitEndDate,
  4888. (
  4889. SELECT
  4890. CAST(
  4891. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4892. ) AS GroupSales
  4893. FROM
  4894. Fin_ForeignReceivables
  4895. WHERE
  4896. IsDel = 0
  4897. AND di.Id = Diid
  4898. AND AddingWay IN (0, 1, 2)
  4899. ) AS GroupSales,
  4900. u.CnName AS GroupPickupUser,
  4901. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  4902. FROM
  4903. Grp_DelegationInfo di
  4904. WITH
  4905. (NoLock)
  4906. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  4907. WHERE
  4908. di.Isdel = 0
  4909. AND (
  4910. SELECT
  4911. CAST(
  4912. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4913. ) AS GroupSales
  4914. FROM
  4915. Fin_ForeignReceivables fr
  4916. WHERE
  4917. fr.IsDel = 0
  4918. AND di.Id = fr.Diid
  4919. AND AddingWay IN (0, 1, 2)
  4920. ) > 0
  4921. {userSql}
  4922. AND di.IsBid = 0
  4923. AND di.TeamName Not Like '%投标%'
  4924. AND VisitDate Between '{beginDt}' And '{endDt}'
  4925. ) Temp ");
  4926. RefAsync<int> total = 0;
  4927. var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  4928. #endregion
  4929. #region 客户类型、客户等级 统计
  4930. string sql1 = string.Format(@$"Select
  4931. sd.[Name],
  4932. Count(*) As [Count]
  4933. From Grp_DelegationInfo di
  4934. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  4935. Where di.Isdel = 0
  4936. And (
  4937. SELECT
  4938. CAST(
  4939. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4940. ) AS GroupSales
  4941. FROM
  4942. Fin_ForeignReceivables fr
  4943. WHERE
  4944. fr.IsDel = 0
  4945. AND di.Id = fr.Diid
  4946. AND AddingWay IN (0, 1, 2)
  4947. ) > 0
  4948. {userSql}
  4949. AND di.IsBid = 0
  4950. AND di.TeamName Not Like '%投标%'
  4951. And VisitDate Between '{beginDt}' And '{endDt}'
  4952. Group By [Name]
  4953. Order By Count Desc");
  4954. var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
  4955. string sql2 = string.Format(@$"Select
  4956. sd.[Name],
  4957. Count(*) As [Count]
  4958. From Grp_DelegationInfo di
  4959. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  4960. Where di.Isdel = 0
  4961. And (
  4962. SELECT
  4963. CAST(
  4964. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4965. ) AS GroupSales
  4966. FROM
  4967. Fin_ForeignReceivables fr
  4968. WHERE
  4969. fr.IsDel = 0
  4970. AND di.Id = fr.Diid
  4971. AND AddingWay IN (0, 1, 2)
  4972. ) > 0
  4973. {userSql}
  4974. AND di.IsBid = 0
  4975. AND di.TeamName Not Like '%投标%'
  4976. And VisitDate Between '{beginDt}' And '{endDt}'
  4977. Group By [Name]
  4978. Order By Count Desc");
  4979. var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
  4980. #endregion
  4981. #region 接单排名
  4982. string sql4 = string.Format(@$"Select
  4983. ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
  4984. u.CnName As UserName,
  4985. Count(*) As [Count]
  4986. From Grp_DelegationInfo di
  4987. Left Join Sys_Users u On di.JietuanOperator = u.Id
  4988. Where di.Isdel = 0
  4989. And (
  4990. SELECT
  4991. CAST(
  4992. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4993. ) AS GroupSales
  4994. FROM
  4995. Fin_ForeignReceivables fr
  4996. WHERE
  4997. fr.IsDel = 0
  4998. AND di.Id = fr.Diid
  4999. AND AddingWay IN (0, 1, 2)
  5000. ) > 0
  5001. {userSql}
  5002. AND di.IsBid = 0
  5003. AND di.TeamName Not Like '%投标%'
  5004. And VisitDate Between '{beginDt}' And '{endDt}'
  5005. Group By CnName");
  5006. var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql4).ToListAsync();
  5007. #endregion
  5008. var viewData = new
  5009. {
  5010. groupData = groupData,
  5011. groupTotal = total,
  5012. customerTypeData = customerTypeData,
  5013. clientGradeData = clientGradeData,
  5014. rankingData = rankingData
  5015. };
  5016. return Ok(JsonView(true, "操作成功!", viewData, total));
  5017. }
  5018. /// <summary>
  5019. /// 市场部销售额
  5020. /// 客户拜访列表
  5021. /// </summary>
  5022. /// <param name="_dto">市场部销售额请求dto</param>
  5023. /// <returns></returns>
  5024. [HttpPost("PostMarketingSalesVCList")]
  5025. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5026. public async Task<IActionResult> PostMarketingSalesVCList(MarketingSalesVCListDto _dto)
  5027. {
  5028. #region 参数验证
  5029. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  5030. var validResult = await validationRules.ValidateAsync(_dto);
  5031. if (!validResult.IsValid)
  5032. {
  5033. var errors = new StringBuilder();
  5034. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  5035. return Ok(JsonView(false, errors.ToString()));
  5036. }
  5037. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  5038. #region 页面操作权限验证
  5039. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  5040. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  5041. #endregion
  5042. #endregion
  5043. return Ok(await _visitingClientsRep._List(_dto.PortType, _dto.PageIndex, _dto.PageSize, _dto.DiId, _dto.Search));
  5044. }
  5045. /// <summary>
  5046. /// 市场部销售额
  5047. /// 客户拜访 操作(添加 Or 编辑)
  5048. /// </summary>
  5049. /// <param name="_dto">市场部销售额请求dto</param>
  5050. /// <returns></returns>
  5051. [HttpPost("PostMarketingSalesVCOperate")]
  5052. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5053. public async Task<IActionResult> PostMarketingSalesVCOperate(MarketingSalesVCOperrateDto _dto)
  5054. {
  5055. #region 参数验证
  5056. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  5057. var validResult = await validationRules.ValidateAsync(_dto);
  5058. if (!validResult.IsValid)
  5059. {
  5060. var errors = new StringBuilder();
  5061. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  5062. return Ok(JsonView(false, errors.ToString()));
  5063. }
  5064. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  5065. #region 页面操作权限验证
  5066. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  5067. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  5068. #endregion
  5069. #endregion
  5070. return Ok(await _visitingClientsRep._AddOrEdit(_dto));
  5071. }
  5072. /// <summary>
  5073. /// 市场部销售额
  5074. /// 客户拜访 Del
  5075. /// </summary>
  5076. /// <param name="_dto">市场部销售额请求dto</param>
  5077. /// <returns></returns>
  5078. [HttpPost("PostMarketingSalesVCDel")]
  5079. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5080. public async Task<IActionResult> PostMarketingSalesVCDel(MarketingSalesVCDelDto _dto)
  5081. {
  5082. return Ok(await _visitingClientsRep._Del(_dto.Id, _dto.UserId));
  5083. }
  5084. /// <summary>
  5085. /// 市场部销售额
  5086. /// 客户拜访 操作 save
  5087. /// </summary>
  5088. /// <param name="_dto">市场部销售额请求dto</param>
  5089. /// <returns></returns>
  5090. [HttpPost("PostMarketingSalesVCSave")]
  5091. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5092. public async Task<IActionResult> PostMarketingSalesVCSave(MarketingSalesVCSaveDto _dto)
  5093. {
  5094. #region 参数验证
  5095. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  5096. var validResult = await validationRules.ValidateAsync(_dto);
  5097. if (!validResult.IsValid)
  5098. {
  5099. var errors = new StringBuilder();
  5100. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  5101. return Ok(JsonView(false, errors.ToString()));
  5102. }
  5103. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  5104. #region 页面操作权限验证
  5105. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  5106. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  5107. #endregion
  5108. #endregion
  5109. return Ok(await _visitingClientsRep._Save(_dto));
  5110. }
  5111. #endregion
  5112. #region 日付报表
  5113. /// <summary>
  5114. /// 日付类型数据
  5115. /// </summary>
  5116. /// <param name="_dto"></param>
  5117. /// <returns></returns>
  5118. [HttpPost("DailypaymentTypeInit")]
  5119. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5120. public async Task<IActionResult> DailypaymentTypeInit(DailypaymentTypeInitDto _dto)
  5121. {
  5122. #region 参数验证
  5123. if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
  5124. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  5125. #region 页面操作权限验证
  5126. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  5127. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  5128. #endregion
  5129. #endregion
  5130. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  5131. {
  5132. var defaultParentIds = new List<int>()
  5133. {
  5134. 48, // 人员费用
  5135. 49, // 办公费用
  5136. 50, // 销售费用
  5137. 51, // 其他费用
  5138. 55, // 大运会
  5139. 90, // 各部门基础固定费用明细
  5140. 104, // 团组费用
  5141. 116, // 物资采购
  5142. };
  5143. var dailypaymentTypeData = await RedisRepository.RedisFactory
  5144. .CreateRedisRepository()
  5145. .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
  5146. var dailyTypeData = await _sqlSugar.Queryable<DailypaymentParentTypeView>()
  5147. .Includes(x => x.SubData)
  5148. .Where(x => defaultParentIds.Contains(x.Id))
  5149. .ToListAsync();
  5150. dailyTypeData.ForEach(x =>
  5151. {
  5152. x.SubData.ForEach(y =>
  5153. {
  5154. int currId = dailypaymentTypeData.Find(z => z == y.Id);
  5155. y.IsChecked = currId != 0;
  5156. });
  5157. });
  5158. var companyData = await _sqlSugar.Queryable<Sys_Company>()
  5159. .Where(x => x.IsDel == 0)
  5160. .Select(x => new { id = x.Id, name = x.CompanyName })
  5161. .ToListAsync();
  5162. return Ok(JsonView(true, "查询成功!", new { dailyTypeData, companyData }));
  5163. }
  5164. else return Ok(JsonView(false, "查询失败"));
  5165. }
  5166. /// <summary>
  5167. /// 日付类型数据 Save
  5168. /// </summary>
  5169. /// <param name="_dto"></param>
  5170. /// <returns></returns>
  5171. [HttpPost("DailypaymentTypeDataSave")]
  5172. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5173. public async Task<IActionResult> DailypaymentTypeDataSave(DailypaymentTypeDataSaveDto _dto)
  5174. {
  5175. #region 参数验证
  5176. if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
  5177. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  5178. #region 页面操作权限验证
  5179. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  5180. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  5181. #endregion
  5182. #endregion
  5183. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  5184. {
  5185. if (_dto.TypeIds.Count < 1) return Ok(JsonView(false, "请传入需要保存的TypeIds"));
  5186. var res = await RedisRepository.RedisFactory
  5187. .CreateRedisRepository()
  5188. .StringSetAsync(
  5189. key: "DailypaymentTypeData",
  5190. _dto.TypeIds,
  5191. timeout: null);
  5192. if (!res) return Ok(JsonView(false, "操作失败"));
  5193. return Ok(JsonView(true, "操作成功!"));
  5194. }
  5195. else return Ok(JsonView(false, "操作失败"));
  5196. }
  5197. /// <summary>
  5198. /// 日付数据列表
  5199. /// </summary>
  5200. /// <param name="_dto"></param>
  5201. /// <returns></returns>
  5202. [HttpPost("DailypaymentRange")]
  5203. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5204. public async Task<IActionResult> DailypaymentRange(DailypaymentRangeDto _dto)
  5205. {
  5206. #region 参数验证
  5207. var validator = new DailypaymentRangeDtoValidator();
  5208. var validationRes = validator.Validate(_dto);
  5209. if (!validationRes.IsValid)
  5210. {
  5211. StringBuilder sb = new StringBuilder();
  5212. foreach (var item in validationRes.Errors)
  5213. {
  5214. sb.AppendLine(item.ErrorMessage);
  5215. }
  5216. return Ok(JsonView(false, sb.ToString()));
  5217. }
  5218. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  5219. #region 页面操作权限验证
  5220. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  5221. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  5222. #endregion
  5223. #endregion
  5224. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  5225. {
  5226. DateTime _beginDt = Convert.ToDateTime($"{_dto.BeginDt} 00:00:00"),
  5227. _endDt = Convert.ToDateTime($"{_dto.EndDt} 23:59:59");
  5228. var sqlWhere = string.Format(@" And dfp.CreateTime Between '{0}' And '{1}'", _beginDt, _endDt);
  5229. var dailypaymentTypeData = await RedisRepository.RedisFactory
  5230. .CreateRedisRepository()
  5231. .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
  5232. var sql = string.Format(@"
  5233. Select
  5234. dfp.Id,
  5235. dfp.Instructions,
  5236. dfp.PriceTypeId,
  5237. sd1.Name As FeeType,
  5238. dfp.TransferTypeId,
  5239. sd2.Name As TransferType,
  5240. dfp.SumPrice,
  5241. dfp.FAuditDate,
  5242. dfp.MAuditDate,
  5243. dfp.CompanyId,
  5244. c.CompanyName,
  5245. dfp.CreateUserId As ApplicantId,
  5246. u.CnName As Applicant,
  5247. dfp.CreateTime As ApplicantDt,
  5248. dfp.Instructions+u.CnName As ViewStr
  5249. From Fin_DailyFeePayment dfp
  5250. Left Join Sys_Users u On dfp.CreateUserId = u.Id
  5251. Left Join Sys_SetData sd1 On dfp.TransferTypeId = sd1.Id
  5252. Left Join Sys_Company c On dfp.CompanyId = c.Id
  5253. Left Join Sys_SetData sd2 On dfp.PriceTypeId = sd2.Id
  5254. Where dfp.IsDel = 0
  5255. -- And dfp.IsPay = 1
  5256. ");//--Order By dfp.CreateTime Desc
  5257. if (_dto.Type == 1) //data
  5258. {
  5259. RefAsync<int> total = 0;
  5260. var _view = await _sqlSugar.SqlQueryable<DailyFeePaymentRangeView>(sql)
  5261. .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
  5262. .WhereIF(dailypaymentTypeData.Count > 0,
  5263. x => dailypaymentTypeData.Contains(x.PriceTypeId))
  5264. .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
  5265. .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
  5266. .OrderByDescending(x => x.ApplicantDt)
  5267. .ToPageListAsync(
  5268. pageNumber: _dto.PageIndex,
  5269. pageSize: _dto.PageSize,
  5270. totalNumber: total
  5271. );
  5272. _sqlSugar.ThenMapper(_view, x =>
  5273. {
  5274. x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
  5275. .SetContext(x1 => x1.DFPId, () => x.Id, x)
  5276. .Where(x => x.IsDel == 0)
  5277. .ToList();
  5278. });
  5279. //单独处理
  5280. return Ok(JsonView(true, "操作成功!", new { data = _view, total = _view.Sum(x => x.SumPrice) }, total));
  5281. }
  5282. else if (_dto.Type == 2) //view
  5283. {
  5284. var _view = await _sqlSugar.SqlQueryable<ExcelView>(sql)
  5285. .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
  5286. .WhereIF(dailypaymentTypeData.Count > 0,
  5287. x => dailypaymentTypeData.Contains(x.PriceTypeId))
  5288. .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
  5289. .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
  5290. .OrderByDescending(x => x.ApplicantDt)
  5291. .ToPageListAsync(
  5292. pageNumber: 1,
  5293. pageSize: 99999
  5294. );
  5295. _sqlSugar.ThenMapper(_view, x =>
  5296. {
  5297. x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
  5298. .SetContext(x1 => x1.DFPId, () => x.Id, x)
  5299. .Where(x => x.IsDel == 0)
  5300. .ToList();
  5301. string str = "";
  5302. int index = 1;
  5303. foreach (var item in x.Contents)
  5304. {
  5305. string str1 = $"{index}、费用名称:[{item.PriceName}] 单价:[{item.Price:#0.00}] 数量:[{item.Quantity:#0.00}] 小计:[{item.ItemTotal:#0.00}] 备注:[{item.Remark}]";
  5306. if (index == x.Contents.Count) str += str1;
  5307. else str += str1 + "\r\n";
  5308. index++;
  5309. }
  5310. x.ContentStr = str;
  5311. });
  5312. if (_view.Count > 0)
  5313. {
  5314. //DataTable dt = GeneralMethod.
  5315. DataTable dt = CommonFun.GetDataTableFromIList(_view);
  5316. dt.TableName = $"_view";
  5317. decimal total = _view.Sum(x => x.SumPrice);
  5318. WorkbookDesigner designer = new WorkbookDesigner();
  5319. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/日付报表模板.xls");
  5320. designer.SetDataSource(dt);
  5321. designer.SetDataSource("Total", total);
  5322. designer.Workbook.Worksheets[0].Name = "日付报表";
  5323. designer.Process();
  5324. string fileName = $"DailyPayment/日付报表{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
  5325. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  5326. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  5327. return Ok(JsonView(true, "操作成功", new { url = rst }));
  5328. }
  5329. return Ok(JsonView(true, ",暂无数据"));
  5330. }
  5331. return Ok(JsonView(false, "操作失败"));
  5332. }
  5333. else return Ok(JsonView(false, "操作失败"));
  5334. }
  5335. #endregion
  5336. #region 统计模块
  5337. /// <summary>
  5338. /// 同比
  5339. /// 营业额(今年和去年的)、成本支出(今年和去年的)、毛利润(今年和去年的)
  5340. /// </summary>
  5341. /// <param name="_dto">市场部销售额请求dto</param>
  5342. /// <returns></returns>
  5343. [HttpPost("StatisticsYOY")]
  5344. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5345. public async Task<IActionResult> StatisticsYOY(YOYDto _dto)
  5346. {
  5347. //同比增长率 = (本期 - 同期) / 同期 * 100%;
  5348. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5349. string beginDt = $"{_dto.Year - 1}-01-01 00:00:00",
  5350. endDt = $"{_dto.Year}-12-31 23:59:59";
  5351. string sql = string.Format(@"
  5352. SELECT
  5353. di.Id,
  5354. di.TeamName,
  5355. di.VisitDate,
  5356. YEAR(di.VisitDate) AS YEAR,
  5357. MONTH(di.VisitDate) AS MONTH,
  5358. (
  5359. SELECT
  5360. CAST(SUM(ItemSumPrice * Rate) AS DECIMAL(12, 2))
  5361. FROM
  5362. Fin_ForeignReceivables
  5363. WHERE
  5364. IsDel = 0
  5365. AND AddingWay IN (0, 1, 2)
  5366. AND di.Id = Diid
  5367. ) AS SaleAmount,
  5368. (
  5369. SELECT
  5370. CAST(
  5371. SUM(
  5372. (
  5373. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  5374. )
  5375. ) AS DECIMAL(12, 2)
  5376. )
  5377. FROM
  5378. Grp_AirTicketReservations atr
  5379. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5380. AND ccp.CTable = 85
  5381. AND atr.Id = ccp.CId
  5382. WHERE
  5383. atr.IsDel = 0
  5384. AND ccp.IsAuditGM = 1
  5385. AND ccp.IsPay = 1
  5386. AND di.Id = atr.DiId
  5387. ) AirTicketAmount,
  5388. (
  5389. SELECT
  5390. CAST(
  5391. SUM(
  5392. (
  5393. ctggr.ServiceQuotedPrice * (ccp.PayPercentage / 100) * ccp.DayRate
  5394. )
  5395. ) AS DECIMAL(12, 2)
  5396. )
  5397. FROM
  5398. Grp_CarTouristGuideGroundReservations ctggr
  5399. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  5400. AND ccp.CTable = 79
  5401. AND ctggr.Id = ccp.CId
  5402. WHERE
  5403. ctggr.IsDel = 0
  5404. AND ccp.IsAuditGM = 1
  5405. AND ccp.IsPay = 1
  5406. AND di.Id = ctggr.DiId
  5407. ) AS OPAmount,
  5408. (
  5409. SELECT
  5410. CAST(SUM((ccp.PayMoney * ccp.DayRate)) AS DECIMAL(12, 2))
  5411. FROM
  5412. Grp_DecreasePayments dp
  5413. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5414. AND ccp.CTable = 98
  5415. AND dp.Id = ccp.CId
  5416. WHERE
  5417. dp.IsDel = 0
  5418. AND ccp.Ctable = 98
  5419. AND ccp.IsAuditGM = 1
  5420. AND ccp.IsPay = 1
  5421. AND di.Id = dp.Diid
  5422. ) AS OtherCostAmount,
  5423. (
  5424. SELECT
  5425. CAST(
  5426. SUM(
  5427. (
  5428. (ccp.PayMoney * ccp.DayRate)
  5429. )
  5430. ) AS DECIMAL(12, 2)
  5431. )
  5432. FROM
  5433. Grp_VisaInfo vi
  5434. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5435. AND ccp.CTable = 80
  5436. AND vi.Id = ccp.CId
  5437. WHERE
  5438. vi.IsDel = 0
  5439. AND ccp.IsAuditGM = 1
  5440. AND ccp.IsPay = 1
  5441. AND di.Id = vi.DIId
  5442. ) AS VisaAmount,
  5443. (
  5444. SELECT
  5445. CAST(
  5446. SUM(
  5447. (ccp.PayMoney * ccp.DayRate)
  5448. ) AS DECIMAL(12, 2)
  5449. )
  5450. FROM
  5451. Grp_InvitationOfficialActivities ioa
  5452. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5453. AND ccp.CTable = 81
  5454. AND ioa.Id = ccp.CId
  5455. WHERE
  5456. ioa.IsDel = 0
  5457. AND ccp.IsAuditGM = 1
  5458. AND ccp.IsPay = 1
  5459. AND di.Id = ioa.Diid
  5460. ) AS OAAmount,
  5461. (
  5462. SELECT
  5463. CAST(
  5464. SUM(
  5465. (ccp.PayMoney * ccp.DayRate)
  5466. ) AS DECIMAL(12, 2)
  5467. )
  5468. FROM
  5469. Grp_Customers ic
  5470. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5471. AND ccp.CTable = 82
  5472. AND ic.Id = ccp.CId
  5473. WHERE
  5474. ic.IsDel = 0
  5475. AND ccp.IsAuditGM = 1
  5476. AND ccp.IsPay = 1
  5477. AND di.Id = ic.DiId
  5478. ) AS InsureAmount,
  5479. (
  5480. SELECT
  5481. CAST(
  5482. SUM(
  5483. (ccp.PayMoney * ccp.DayRate)
  5484. ) AS DECIMAL(12, 2)
  5485. )
  5486. FROM
  5487. Grp_HotelReservations hr
  5488. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  5489. WHERE
  5490. hr.IsDel = 0
  5491. AND ccp.IsDel = 0
  5492. AND ccp.CTable = 76
  5493. AND ccp.IsAuditGM = 1
  5494. AND ccp.PayMoney <> 0
  5495. AND ccp.IsPay = 1
  5496. AND di.Id = hr.DiId
  5497. ) AS HotelAmount,
  5498. (
  5499. SELECT
  5500. CAST(
  5501. SUM((gec.PriceSum * gec.Coefficient * ccp.DayRate)) AS DECIMAL(12, 2)
  5502. )
  5503. FROM
  5504. OA2023DB.dbo.Fin_GroupExtraCost gec
  5505. INNER JOIN Grp_CreditCardPayment ccp ON gec.Id = ccp.CId
  5506. WHERE
  5507. ccp.IsDel = 0
  5508. AND ccp.CTable = 1015
  5509. AND ccp.IsAuditGM = 1
  5510. AND ccp.IsPay = 1
  5511. AND di.Id = gec.DiId
  5512. ) AS ExcessAmount,
  5513. (
  5514. SELECT
  5515. CAST(
  5516. SUM(
  5517. (ccp.PayMoney * ccp.DayRate)
  5518. ) AS DECIMAL(12, 2)
  5519. )
  5520. FROM
  5521. Fin_PaymentRefundAndOtherMoney prom
  5522. INNER JOIN Grp_CreditCardPayment ccp ON prom.DiId = ccp.DIId
  5523. AND prom.Id = ccp.CId
  5524. WHERE
  5525. prom.IsDel = 0
  5526. AND prom.PayType = 1
  5527. AND ccp.CTable = 285
  5528. AND ccp.IsAuditGM = 1
  5529. AND ccp.IsPay = 1
  5530. AND di.Id = prom.DiId
  5531. ) AS SKTHAmount
  5532. FROM
  5533. Grp_DelegationInfo di
  5534. WHERE
  5535. di.IsDel = 0
  5536. AND di.TeamDid IN (38,39,40,1048)
  5537. AND di.VisitDate BETWEEN '{0}' AND '{1}'
  5538. ORDER BY
  5539. di.VisitDate
  5540. ", beginDt, endDt);
  5541. var data = await _sqlSugar.SqlQueryable<StatisticsYOYView>(sql).ToListAsync();
  5542. var thisYearData = data.Where(x => x.Year == _dto.Year).ToList();
  5543. var lastYearData = data.Where(x => x.Year == (_dto.Year - 1)).ToList();
  5544. List<YOYReturnView> salesYOYData = new List<YOYReturnView>();
  5545. List<YOYReturnView> costYOYData = new List<YOYReturnView>();
  5546. List<YOYReturnView> grossProfitYOYData = new List<YOYReturnView>();
  5547. int monthIndex = 1;
  5548. while (monthIndex < 13)
  5549. {
  5550. var thisMonthData = thisYearData.Where(x => x.Month == monthIndex).ToList();
  5551. var lastMonthData = lastYearData.Where(x => x.Month == monthIndex).ToList();
  5552. var thisGroupIds = thisMonthData.Select(x => x.Id).ToList();
  5553. var lastGroupIds = lastMonthData.Select(x => x.Id).ToList();
  5554. decimal thisSalesAmount = thisMonthData.Sum(x => x?.SaleAmount ?? 0.00M),
  5555. lastSalesAmount = lastMonthData.Sum(x => x?.SaleAmount ?? 0.00M),
  5556. thisCostAmount = thisMonthData.Sum(x => x?.CostAmount ?? 0.00M),
  5557. lastCostAmount = lastMonthData.Sum(x => x?.CostAmount ?? 0.00M),
  5558. thisgrossProfitAmount = thisMonthData.Sum(x => x?.GrossProfitAmount ?? 0.00M),
  5559. lastgrossProfitAmount = lastMonthData.Sum(x => x?.GrossProfitAmount ?? 0.00M);
  5560. salesYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisSalesAmount, lastSalesAmount, thisGroupIds, lastGroupIds));
  5561. costYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisCostAmount, lastCostAmount, thisGroupIds, lastGroupIds));
  5562. grossProfitYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisgrossProfitAmount, lastgrossProfitAmount, thisGroupIds, lastGroupIds));
  5563. monthIndex++;
  5564. }
  5565. salesYOYData = salesYOYData.OrderBy(x => x.Month).ToList();
  5566. costYOYData = costYOYData.OrderBy(x => x.Month).ToList();
  5567. grossProfitYOYData = grossProfitYOYData.OrderBy(x => x.Month).ToList();
  5568. return Ok(JsonView(true, "操作成功!", new { salesYOYData = salesYOYData, costYOYData = costYOYData, grossProfitYOYData = grossProfitYOYData }));
  5569. }
  5570. /// <summary>
  5571. /// 国交数据统计-机票相关
  5572. /// 机票票数、机票到达地、预订平台
  5573. /// </summary>
  5574. /// <param name="_dto"></param>
  5575. /// <returns></returns>
  5576. [HttpPost("StatisticsAirTicket")]
  5577. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5578. public async Task<IActionResult> StatisticsAirTicket(YOYDto _dto)
  5579. {
  5580. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5581. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5582. endDt = $"{_dto.Year}-12-31 23:59:59";
  5583. string sql = string.Format(@"
  5584. SELECT
  5585. atr.DIId,
  5586. atr.FlightsDate,
  5587. YEAR(atr.FlightsDate) AS YEAR,
  5588. MONTH(atr.FlightsDate) AS MONTH,
  5589. atr.CType,
  5590. sd.Name As CTypeName,
  5591. atr.FlightsCity,
  5592. atr.ClientNum,
  5593. atr.ClientName,
  5594. di.TeamName As 'GroupName',
  5595. CASE
  5596. WHEN ccp.Payee = '' OR ccp.Payee IS NULL THEN '未知'
  5597. ELSE ccp.Payee
  5598. END AS 'Platform'
  5599. FROM
  5600. Grp_AirTicketReservations atr
  5601. INNER JOIN Grp_CreditCardPayment ccp ON atr.Id = ccp.CId
  5602. AND ccp.IsDel = 0
  5603. AND CTable = 85
  5604. INNER JOIN Grp_DelegationInfo di ON atr.DIId = di.Id
  5605. LEFT JOIN Sys_SetData sd On atr.CType = sd.Id
  5606. WHERE
  5607. atr.IsDel = 0
  5608. AND di.TeamDid IN (38,39,40,1048)
  5609. AND atr.CType IN(457,458,459,460,574,575)
  5610. AND CHARINDEX('行程单',atr.ClientName) = 0
  5611. AND CHARINDEX('返点',atr.ClientName) = 0
  5612. AND CHARINDEX('-1',atr.ClientName) = 0
  5613. AND ccp.IsPay = 1
  5614. AND atr.FlightsDate BETWEEN '{0}' AND '{1}'
  5615. ORDER BY atr.FlightsDate
  5616. ", beginDt, endDt);
  5617. var data = await _sqlSugar.SqlQueryable<StatisticsAirTicketView>(sql).ToListAsync();
  5618. var groupIds = data.Select(x => x.DIId).ToList();
  5619. //处理城市数据
  5620. var threeCodeData = await _sqlSugar.Queryable<Res_ThreeCode>().Where(x => x.IsDel == 0).ToListAsync();
  5621. //处理团组名称
  5622. var groupNames = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => groupIds.Contains(x.Id)).Select(x => new { Id = x.Id, GroupName = x.TeamName }).ToListAsync();
  5623. data.ForEach(x =>
  5624. {
  5625. string cityName = "";
  5626. if (!string.IsNullOrEmpty(x.FlightsCity))
  5627. {
  5628. string cityCode = x.FlightsCity.Replace("-", "").Replace("/", "");
  5629. int cityNum = cityCode.Length / 3;
  5630. if (cityCode.Length % 3 == 0)
  5631. {
  5632. for (int i = 0; i < cityNum; i++)
  5633. {
  5634. string code = "";
  5635. if (i == 0) code = cityCode.Substring(0, 3);
  5636. else code = cityCode.Substring(i * 3, 3);
  5637. if (!string.IsNullOrEmpty(code))
  5638. {
  5639. if (i == cityNum - 1)
  5640. {
  5641. cityName += threeCodeData.Find(x1 => x1.Three.Equals(code))?.City ?? "";
  5642. }
  5643. else
  5644. {
  5645. var str1 = threeCodeData.Find(x1 => x1.Three.Equals(code))?.City ?? "";
  5646. cityName += str1 + "、";
  5647. }
  5648. }
  5649. }
  5650. }
  5651. }
  5652. x.FlightsCityName = cityName;
  5653. });
  5654. var airTicketNumData = new List<AirTicketReturnView>();
  5655. var airTicketAreaData = new List<AirTicketCityReturnView>();
  5656. int monthIndex = 1;
  5657. while (monthIndex < 13)
  5658. {
  5659. var monthData = data.Where(x => x.Month == monthIndex).ToList();
  5660. //机票票数处理
  5661. int airticket_quantity = monthData.Sum(x => x.ClientNum);
  5662. var linkGroupIds = monthData.Select(x => x.DIId).ToList();
  5663. List<AitTicketInfo> aitTicketInfos = new List<AitTicketInfo>();
  5664. foreach (var item in monthData)
  5665. {
  5666. string groupName = groupNames.Find(x => item.DIId == x.Id)?.GroupName ?? "";
  5667. aitTicketInfos.Add(new AitTicketInfo(item.DIId, groupName, item.ClientNum));
  5668. }
  5669. var aitTicketInfosGroupBy = aitTicketInfos.GroupBy(x => x.Id);
  5670. List<AitTicketInfo> aitTicketInfos1 = new List<AitTicketInfo>();
  5671. foreach (var item in aitTicketInfosGroupBy)
  5672. {
  5673. aitTicketInfos1.Add(new AitTicketInfo(item.Key, item.First().GroupName, item.Sum(x => x.Quantity)));
  5674. }
  5675. aitTicketInfos1 = aitTicketInfos1.OrderBy(x => x.Quantity).ToList();
  5676. linkGroupIds = linkGroupIds.Distinct().ToList();
  5677. airTicketNumData.Add(new AirTicketReturnView(_dto.Year, monthIndex, airticket_quantity, aitTicketInfos1, linkGroupIds));
  5678. //机票城市处理
  5679. //城市处理
  5680. var airTicketCityInfos = new List<string>();
  5681. foreach (var item in monthData)
  5682. {
  5683. if (!string.IsNullOrEmpty(item.FlightsCityName))
  5684. {
  5685. if (item.FlightsCityName.Contains("、"))
  5686. {
  5687. var cityArray = item.FlightsCityName.Split("、").ToList();
  5688. foreach (var item1 in cityArray)
  5689. {
  5690. if (!string.IsNullOrEmpty(item1))
  5691. {
  5692. airTicketCityInfos.Add(item1);
  5693. }
  5694. }
  5695. }
  5696. else
  5697. {
  5698. airTicketCityInfos.Add(item.FlightsCityName);
  5699. }
  5700. }
  5701. }
  5702. //int quantity1 = airTicketCityInfos.Count;
  5703. int city_totalquantity = 0;
  5704. var airTicketCityInfosGroupby = airTicketCityInfos.GroupBy(x => x);
  5705. var airTicketCityInfos1 = new List<AirTicketCityInfo>();
  5706. foreach (var item in airTicketCityInfosGroupby)
  5707. {
  5708. var city_quantity = item.ToList().Count;
  5709. city_totalquantity += city_quantity;
  5710. airTicketCityInfos1.Add(new AirTicketCityInfo(item.Key, city_quantity));
  5711. }
  5712. airTicketCityInfos1 = airTicketCityInfos1.OrderByDescending(x => x.Quantity).ToList();
  5713. airTicketAreaData.Add(new AirTicketCityReturnView(_dto.Year, monthIndex, city_totalquantity, airTicketCityInfos1, linkGroupIds));
  5714. monthIndex++;
  5715. }
  5716. var airTicketPlatformData = data.GroupBy(g => g.Platform)
  5717. .Select(g => new
  5718. {
  5719. platform = g.Key,
  5720. total = g.Sum(x => x.ClientNum),
  5721. children = g.GroupBy(g1 => g1.DIId)
  5722. .Select(g1 => new
  5723. {
  5724. diId = g1.Key,
  5725. groupName = g1.FirstOrDefault()?.GroupName ?? "-",
  5726. total = g1.Sum(x1 => x1.ClientNum),
  5727. children = g1.Select(x1 => new
  5728. {
  5729. //diId = x1.DIId,
  5730. //groupName = x1.GroupName,
  5731. flightsCityName = x1.FlightsCityName,
  5732. total = x1.ClientNum
  5733. })
  5734. .ToList()
  5735. })
  5736. .OrderByDescending(x1 => x1.total)
  5737. .ToList()
  5738. })
  5739. .OrderByDescending(x => x.total)
  5740. .ToList();
  5741. return Ok(JsonView(true, "操作成功!", new
  5742. {
  5743. airTicketNumData = airTicketNumData,
  5744. airTicketAreaData = airTicketAreaData,
  5745. airTicketPlatformData = airTicketPlatformData
  5746. }));
  5747. }
  5748. /// <summary>
  5749. /// 国交数据统计-酒店
  5750. /// 国家TOP10、地区TOP10、预订平台
  5751. /// </summary>
  5752. /// <param name="_dto"></param>
  5753. /// <returns></returns>
  5754. [HttpPost("StatisticsHotel")]
  5755. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5756. public async Task<IActionResult> StatisticsHotel(YOYDto _dto)
  5757. {
  5758. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5759. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5760. endDt = $"{_dto.Year}-12-31 23:59:59";
  5761. string sql = string.Format(@"
  5762. SELECT
  5763. hr.DIId,
  5764. CASE
  5765. WHEN ntf.Country IS NULL THEN '未选择'
  5766. ELSE ntf.Country
  5767. END AS 'Country',
  5768. hr.City,
  5769. hr.HotelName,
  5770. sd.Name AS BookinSite,
  5771. hr.CheckInDate,
  5772. YEAR(hr.CheckInDate) AS YEAR,
  5773. MONTH(hr.CheckInDate) AS MONTH,
  5774. hr.CheckOutDate,
  5775. hr.SingleRoomCount,
  5776. hr.DoubleRoomCount,
  5777. hr.SuiteRoomCount,
  5778. hr.OtherRoomCount
  5779. FROM
  5780. Grp_HotelReservations hr
  5781. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  5782. AND ccp.IsDel = 0
  5783. AND CTable = 76
  5784. INNER JOIN Grp_DelegationInfo di ON hr.DiId = di.Id
  5785. LEFT JOIN Sys_SetData sd ON hr.ReservationsWebsite = sd.Id
  5786. LEFT JOIN Grp_NationalTravelFee ntf ON hr.AreaId = ntf.Id
  5787. WHERE
  5788. hr.IsDel = 0
  5789. AND di.TeamDid IN (38,39,40,1048)
  5790. AND ccp.IsPay = 1
  5791. AND (
  5792. hr.SingleRoomCount > 0
  5793. OR hr.DoubleRoomCount > 0
  5794. OR hr.SuiteRoomCount > 0
  5795. OR hr.OtherRoomCount > 0
  5796. )
  5797. AND CHARINDEX('早餐',hr.HotelName) = 0
  5798. AND CHARINDEX('晚餐',hr.HotelName) = 0
  5799. AND CHARINDEX('升级',hr.HotelName) = 0
  5800. AND CHARINDEX('饮料茶水费',hr.HotelName) = 0
  5801. AND CHARINDEX('城市税',hr.HotelName) = 0
  5802. AND CHARINDEX('退款',hr.HotelName) = 0
  5803. AND CHARINDEX('返现',hr.HotelName) = 0
  5804. AND CHARINDEX('会议室',hr.HotelName) = 0
  5805. AND CHARINDEX('迷你吧消费',hr.HotelName) = 0
  5806. AND CHARINDEX('运费',hr.HotelName) = 0
  5807. AND CHARINDEX('地接',hr.HotelName) = 0
  5808. AND CHARINDEX('损失',hr.HotelName) = 0
  5809. AND CHARINDEX('补差',hr.HotelName) = 0
  5810. AND hr.CheckInDate BETWEEN CONVERT(datetime,'{0}') AND CONVERT(datetime,'{1}')
  5811. ORDER BY
  5812. hr.CheckInDate
  5813. ", beginDt, endDt);
  5814. var data = await _sqlSugar.SqlQueryable<StatisticsHotelView>(sql).ToListAsync();
  5815. var hotelCountryGroupByData = data.GroupBy(x => x.Country)
  5816. .Select(g => new
  5817. {
  5818. Country = g.Key,
  5819. BookingRoomNum = g.Sum(x => x.RoomTotal),
  5820. hotelData = g.GroupBy(x => x.HotelName)
  5821. .Select(g1 => new
  5822. {
  5823. hotelName = g1.Key,
  5824. roomNights = g1.Sum(x => x.RoomNights),
  5825. roomTotal = g1.Sum(x => x.RoomTotal),
  5826. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  5827. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  5828. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  5829. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  5830. })
  5831. .ToList(),
  5832. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  5833. })
  5834. .OrderByDescending(x => x.BookingRoomNum)
  5835. .Take(10)
  5836. .ToList();
  5837. var hotelData = data.OrderBy(x => x.CityStr).ToList();
  5838. var hotelCityGroupByData = data.GroupBy(x => x.CityStr)
  5839. .Select(g => new
  5840. {
  5841. city = g.Key,
  5842. BookingRoomNum = g.Sum(x => x.RoomTotal),
  5843. hotelData = g.GroupBy(x => x.HotelName)
  5844. .Select(g1 => new
  5845. {
  5846. hotelName = g1.Key,
  5847. roomNights = g1.Sum(x => x.RoomNights),
  5848. roomTotal = g1.Sum(x => x.RoomTotal),
  5849. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  5850. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  5851. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  5852. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  5853. })
  5854. .ToList(),
  5855. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  5856. })
  5857. .OrderByDescending(x => x.BookingRoomNum)
  5858. .Take(10)
  5859. .ToList();
  5860. var hotelPlatformGroupByData = data.GroupBy(x => x.BookinSite)
  5861. .Select(g => new
  5862. {
  5863. Platform = g.Key,
  5864. BookingRoomNum = g.Sum(x => x.RoomTotal),
  5865. hotelData = g.GroupBy(x => x.HotelName)
  5866. .Select(g1 => new
  5867. {
  5868. hotelName = g1.Key,
  5869. roomNights = g1.Sum(x => x.RoomNights),
  5870. roomTotal = g1.Sum(x => x.RoomTotal),
  5871. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  5872. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  5873. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  5874. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  5875. })
  5876. .ToList(),
  5877. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  5878. })
  5879. .OrderByDescending(x => x.BookingRoomNum)
  5880. .ToList();
  5881. return Ok(JsonView(true, "操作成功!", new { hotelCountryGroupByData = hotelCountryGroupByData, hotelCityData = hotelCityGroupByData, hotelPlatformData = hotelPlatformGroupByData }));
  5882. }
  5883. /// <summary>
  5884. /// 国交数据统计
  5885. /// 商邀邀请国家数量TOP10
  5886. /// </summary>
  5887. /// <param name="_dto"></param>
  5888. /// <returns></returns>
  5889. [HttpPost("StatisticsInvitation")]
  5890. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5891. public async Task<IActionResult> StatisticsInvitation(YOYDto _dto)
  5892. {
  5893. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5894. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5895. endDt = $"{_dto.Year}-12-31 23:59:59";
  5896. string sql = string.Format(@"
  5897. SELECT
  5898. oa.DiId,
  5899. di.TeamName AS GroupName,
  5900. oa.Country,
  5901. oa.Area AS City,
  5902. oa.Client,
  5903. oa.Date
  5904. FROM
  5905. Res_OfficialActivities oa
  5906. LEFT JOIN Grp_DelegationInfo di ON oa.DiId = di.Id
  5907. WHERE
  5908. oa.IsDel = 0
  5909. AND oa.Date BETWEEN '{0}' AND '{1}'
  5910. ", beginDt, endDt);
  5911. var data = await _sqlSugar.SqlQueryable<StatisticsInvitation_HW>(sql).ToListAsync();
  5912. var groupByCountry = data.GroupBy(x => x.Country)
  5913. .Select(g => new
  5914. {
  5915. Country = g.Key,
  5916. TimeNum = g.Count(),
  5917. LinkGroupIds = g.Select(x => x.GroupName).Distinct().ToList()
  5918. })
  5919. .OrderByDescending(x => x.TimeNum)
  5920. .Take(10)
  5921. .ToList();
  5922. var groupByClient = data.GroupBy(x => x.Client)
  5923. .Select(g => new
  5924. {
  5925. Country = g.Key,
  5926. TimeNum = g.Count(),
  5927. LinkGroupIds = g.Select(x => x.GroupName).Distinct().ToList()
  5928. })
  5929. .OrderByDescending(x => x.TimeNum)
  5930. .Take(10)
  5931. .ToList();
  5932. return Ok(JsonView(true, "操作成功!", new { groupByCountry = groupByCountry, groupByClient = groupByClient }));
  5933. }
  5934. /// <summary>
  5935. /// 会务数据统计
  5936. /// 会务城市TOP10排序
  5937. /// </summary>
  5938. /// <param name="_dto"></param>
  5939. /// <returns></returns>
  5940. [HttpPost("StatisticsConferenceCity")]
  5941. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5942. public async Task<IActionResult> StatisticsConferenceCity(YOYDto _dto)
  5943. {
  5944. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5945. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5946. endDt = $"{_dto.Year}-12-31 23:59:59";
  5947. string sql = string.Format(@"
  5948. SELECT
  5949. ioa.DiId,
  5950. ioa.InviterArea AS Country
  5951. FROM
  5952. Grp_InvitationOfficialActivities ioa
  5953. INNER JOIN Grp_CreditCardPayment ccp ON ioa.Id = ccp.CId
  5954. AND ccp.IsDel = 0
  5955. AND ccp.CTable = 81
  5956. INNER JOIN Grp_DelegationInfo di ON ioa.DiId = di.Id
  5957. WHERE
  5958. ioa.IsDel = 0
  5959. AND di.TeamDid IN (102,248,302,691,762,1047)
  5960. AND ccp.IsPay = 1
  5961. AND ioa.CreateTime BETWEEN '{0}' AND '{1}'
  5962. ", beginDt, endDt);
  5963. var data = await _sqlSugar.SqlQueryable<StatisticsInvitation>(sql).ToListAsync();
  5964. var groupByData = data.GroupBy(x => x.Country)
  5965. .Select(g => new
  5966. {
  5967. Country = g.Key,
  5968. TimeNum = g.Count(),
  5969. LinkGroupIds = g.Select(x => x.DIId).ToList()
  5970. })
  5971. .OrderByDescending(x => x.TimeNum)
  5972. .Take(10)
  5973. .ToList();
  5974. return Ok(JsonView(true, "操作成功!", groupByData));
  5975. }
  5976. /// <summary>
  5977. /// 团组数据统计
  5978. /// 团组合作前十的客户TOP10排序
  5979. /// </summary>
  5980. /// <param name="_dto"></param>
  5981. /// <returns></returns>
  5982. [HttpPost("StatisticsCooperativeCustomer")]
  5983. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5984. public async Task<IActionResult> StatisticsCooperativeCustomer(YOYDto _dto)
  5985. {
  5986. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5987. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5988. endDt = $"{_dto.Year}-12-31 23:59:59";
  5989. DateTime _beginDt = Convert.ToDateTime(beginDt),
  5990. _endDt = Convert.ToDateTime(endDt);
  5991. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  5992. .Where(x => x.IsDel == 0)
  5993. //.Where(x => x.IsSure == 1)
  5994. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  5995. .ToListAsync();
  5996. var groupInfos1 = groupInfos.GroupBy(x => x.ClientName);
  5997. var view = groupInfos1.Select(x =>
  5998. new
  5999. {
  6000. clienName = x.Key,
  6001. clientUnit = x.FirstOrDefault()?.ClientUnit ?? "",
  6002. visitsNum = x.Count()
  6003. }
  6004. )
  6005. .OrderByDescending(x => x.visitsNum)
  6006. .Take(10)
  6007. .ToList();
  6008. return Ok(JsonView(true, "操作成功!", view));
  6009. }
  6010. /// <summary>
  6011. /// 团组数据统计
  6012. /// 已出团客户单位的类型比例图(饼状图-政府团、企业团等)
  6013. /// </summary>
  6014. /// <param name="_dto"></param>
  6015. /// <returns></returns>
  6016. [HttpPost("StatisticsCooperativeCustomerType")]
  6017. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6018. public async Task<IActionResult> StatisticsCooperativeCustomerType(YOYDto _dto)
  6019. {
  6020. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  6021. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  6022. endDt = $"{_dto.Year}-12-31 23:59:59";
  6023. DateTime _beginDt = Convert.ToDateTime(beginDt),
  6024. _endDt = Convert.ToDateTime(endDt);
  6025. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  6026. .LeftJoin<Sys_SetData>((di, sd) => di.TeamDid == sd.Id)
  6027. .Where((di, sd) => di.IsDel == 0)
  6028. .Where((di, sd) => di.VisitDate >= _beginDt && di.VisitDate <= _endDt)
  6029. .Select((di, sd) => new
  6030. {
  6031. Id = di.Id,
  6032. GroupTypeId = di.TeamDid,
  6033. GroupTypeName = sd.Name,
  6034. })
  6035. .ToListAsync();
  6036. var groupInfos1 = groupInfos.GroupBy(x => x.GroupTypeName);
  6037. var view = groupInfos1.Select(x =>
  6038. new
  6039. {
  6040. groupTypeName = x.Key,
  6041. groupNum = x.Count(),
  6042. linkGroupId = x.Select(x1 => x1.Id).ToList()
  6043. }
  6044. )
  6045. .OrderByDescending(x => x.groupNum)
  6046. .ToList();
  6047. return Ok(JsonView(true, "操作成功!", view));
  6048. }
  6049. /// <summary>
  6050. /// 团组数据统计
  6051. /// 团组数量
  6052. /// </summary>
  6053. /// <param name="_dto"></param>
  6054. /// <returns></returns>
  6055. [HttpPost("StatisticsGroupNum")]
  6056. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6057. public async Task<IActionResult> StatisticsGroupNum(YOYDto _dto)
  6058. {
  6059. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  6060. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  6061. endDt = $"{_dto.Year}-12-31 23:59:59";
  6062. DateTime _beginDt = Convert.ToDateTime(beginDt),
  6063. _endDt = Convert.ToDateTime(endDt);
  6064. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  6065. .Where(x => x.IsDel == 0)
  6066. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  6067. .Select(x => new StatisticsGroupInfoEntity
  6068. {
  6069. Id = x.Id,
  6070. VisitDate = x.VisitDate,
  6071. Month = x.VisitDate.Month,
  6072. //MonthName = x.VisitDate.ToString("MMM", CultureInfo.GetCultureInfo("zh-CN")),
  6073. VisitPNumber = x.VisitPNumber
  6074. })
  6075. .MergeTable()
  6076. .OrderBy(x => new { x.Month })
  6077. .ToListAsync();
  6078. string groupNumStr = $"年度出访量:{groupInfos.Count}\r\n";
  6079. var groupNumYearData = new
  6080. {
  6081. year = _dto.Year,
  6082. yearName = _dto.Year + "年",
  6083. num = groupInfos.Count,
  6084. linkGroupIds = groupInfos.Select(x => x.Id).ToList()
  6085. };
  6086. var groupNumData = groupInfos.GroupBy(x => x.Quarter)
  6087. .Select(x => new
  6088. {
  6089. Quarter = x.Key,
  6090. QuarterName = x.FirstOrDefault()?.QuarterName ?? "-",
  6091. Num = x.Count(),
  6092. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  6093. })
  6094. .OrderBy(x => x.Quarter)
  6095. .ToList();
  6096. groupNumData.ForEach(x =>
  6097. {
  6098. groupNumStr += $"{x.QuarterName}出访量:{x.Num};";
  6099. });
  6100. var groupNumMonthData = groupInfos.GroupBy(x => x.Month)
  6101. .Select(x => new
  6102. {
  6103. Month = x.Key,
  6104. MonthName = x.FirstOrDefault()?.MonthName ?? "-",
  6105. Num = x.Count(),
  6106. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  6107. })
  6108. .OrderBy(x => x.Month)
  6109. .ToList();
  6110. return Ok(JsonView(true, "操作成功!", new
  6111. {
  6112. yearData = groupNumYearData,
  6113. quarterData = groupNumData,
  6114. monthData = groupNumMonthData,
  6115. remark = groupNumStr
  6116. }));
  6117. }
  6118. /// <summary>
  6119. /// 团组数据统计
  6120. /// 团组人数
  6121. /// </summary>
  6122. /// <param name="_dto"></param>
  6123. /// <returns></returns>
  6124. [HttpPost("StatisticsGroupPeopleNum")]
  6125. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6126. public async Task<IActionResult> StatisticsGroupPeopleNum(YOYDto _dto)
  6127. {
  6128. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  6129. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  6130. endDt = $"{_dto.Year}-12-31 23:59:59";
  6131. DateTime _beginDt = Convert.ToDateTime(beginDt),
  6132. _endDt = Convert.ToDateTime(endDt);
  6133. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  6134. .Where(x => x.IsDel == 0)
  6135. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  6136. .Select(x => new StatisticsGroupInfoEntity
  6137. {
  6138. Id = x.Id,
  6139. VisitDate = x.VisitDate,
  6140. Month = x.VisitDate.Month,
  6141. VisitPNumber = x.VisitPNumber
  6142. })
  6143. .MergeTable()
  6144. .OrderBy(x => new { x.Month })
  6145. .ToListAsync();
  6146. string groupPeopleNumStr = $"年度出访人数:{groupInfos.Sum(x => x.VisitPNumber)}\r\n";
  6147. var groupPeopleNumYearData = new
  6148. {
  6149. year = _dto.Year,
  6150. yearName = _dto.Year + "年",
  6151. num = groupInfos.Sum(x => x.VisitPNumber),
  6152. linkGroupIds = groupInfos.Select(x => x.Id).ToList()
  6153. };
  6154. var groupPeopleNumData = groupInfos.GroupBy(x => x.Quarter)
  6155. .Select(x => new
  6156. {
  6157. Quarter = x.Key,
  6158. QuarterName = x.FirstOrDefault()?.QuarterName ?? "-",
  6159. Num = x.Sum(x1 => x1.VisitPNumber),
  6160. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  6161. })
  6162. .OrderBy(x => x.Quarter)
  6163. .ToList();
  6164. groupPeopleNumData.ForEach(x =>
  6165. {
  6166. groupPeopleNumStr += $"{x.QuarterName}出访人数:{x.Num};";
  6167. });
  6168. var groupPeopleNumMonthData = groupInfos.GroupBy(x => x.Month)
  6169. .Select(x => new
  6170. {
  6171. Month = x.Key,
  6172. MonthName = x.FirstOrDefault()?.MonthName ?? "-",
  6173. Num = x.Sum(x1 => x1.VisitPNumber),
  6174. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  6175. })
  6176. .OrderBy(x => x.Month)
  6177. .ToList();
  6178. return Ok(JsonView(true, "操作成功!", new
  6179. {
  6180. yearData = groupPeopleNumYearData,
  6181. quarterData = groupPeopleNumData,
  6182. monthData = groupPeopleNumMonthData,
  6183. remark = groupPeopleNumStr
  6184. }));
  6185. }
  6186. /// <summary>
  6187. /// 团组数据统计
  6188. /// OP 成本
  6189. /// </summary>
  6190. /// <param name="_dto"></param>
  6191. /// <returns></returns>
  6192. [HttpPost("StatisticsOP")]
  6193. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6194. public async Task<IActionResult> StatisticsOP(StatisticsOPDto _dto)
  6195. {
  6196. if (_dto.Year < 1) return Ok(JsonView(false, "Year参数错误!"));
  6197. if (_dto.Type < 1 || _dto.Type > 2) return Ok(JsonView(false, "Type参数错误!"));
  6198. int thisYear = _dto.Year, lastYear = _dto.Year - 1;
  6199. string beginDt = $"{lastYear}-01-01 00:00:00",
  6200. endDt = $"{thisYear}-12-31 23:59:59";
  6201. string sql = string.Format(@"
  6202. SELECT
  6203. temp.Id,
  6204. DiId,
  6205. PaymentTime,
  6206. [Year],
  6207. [Quarter],
  6208. [Month],
  6209. Area,
  6210. FeeType,
  6211. sd1.Name AS FeeTypeName,
  6212. FeeSubType,
  6213. sd2.Name AS FeeSubTypeName,
  6214. CONVERT(DECIMAL(12, 2), Price * Qauntity * ExchangeRate) AS Price
  6215. FROM
  6216. (
  6217. SELECT
  6218. ctggr.Id,
  6219. ctggr.DiId,
  6220. ctggr.Area,
  6221. CASE
  6222. WHEN ctggr.PriceType IS NULL THEN 1069
  6223. ELSE ctggr.PriceType
  6224. END AS FeeType,
  6225. ctggrc.SId AS FeeSubType,
  6226. ctggrc.Price,
  6227. CASE
  6228. WHEN ctggrc.Count IS NULL THEN 1
  6229. ELSE ctggrc.Count
  6230. END AS Qauntity,
  6231. ccp.DayRate AS ExchangeRate,
  6232. ctggrc.CreateTime AS PaymentTime,
  6233. YEAR(ctggrc.CreateTime) AS [Year],
  6234. CONVERT(INT,DATENAME(QUARTER, ctggrc.CreateTime)) AS [Quarter],
  6235. MONTH(ctggrc.CreateTime) AS [Month]
  6236. FROM
  6237. Grp_CarTouristGuideGroundReservations ctggr
  6238. INNER JOIN Grp_CarTouristGuideGroundReservationsContent ctggrc ON ctggr.Id = ctggrc.CTGGRId
  6239. AND ctggrc.IsDel = 0
  6240. INNER JOIN Grp_CreditCardPayment ccp ON ctggr.Id = ccp.CId
  6241. AND ccp.CTable = 79
  6242. AND ccp.IsDel = 0
  6243. WHERE
  6244. ctggr.IsDel = 0
  6245. AND ctggrc.SId != 1070 --费用子项筛掉尾款
  6246. AND ctggrc.Price > 0 --筛选真实存在的数据
  6247. AND ccp.IsPay = 1
  6248. ) temp
  6249. LEFT JOIN Sys_SetData sd1 ON FeeType = sd1.Id
  6250. LEFT JOIN Sys_SetData sd2 ON FeeSubType = sd2.Id
  6251. WHERE
  6252. temp.Area NOT LIKE '%尾款%' -- 筛选掉尾款相关信息
  6253. AND temp.FeeType != 1062 --费用类型筛选掉全款和首付款数据
  6254. AND temp.PaymentTime BETWEEN CONVERT(datetime,'{0}') AND CONVERT(datetime,'{1}')
  6255. ORDER BY
  6256. temp.[Year],
  6257. temp.[Quarter],
  6258. temp.[Month]
  6259. ", beginDt, endDt);
  6260. var opInfos = await _sqlSugar.SqlQueryable<StatisticsOP>(sql).ToListAsync();
  6261. //处理地区相关信息
  6262. var countrys = await _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(x => x.IsDel == 0).ToListAsync();
  6263. for (int i = 0; i < opInfos.Count; i++)
  6264. {
  6265. string country = string.Empty, city = string.Empty;
  6266. int dataId = 0;
  6267. bool isCountryId = int.TryParse(opInfos[i].Area, out dataId);
  6268. string[] citySelecter = new string[] { "其他城市", "所有城市" };
  6269. if (isCountryId)
  6270. {
  6271. var countryInfo = countrys.Find(x => x.Id == dataId);
  6272. country = countryInfo?.Country ?? "";
  6273. if (citySelecter.Contains(countryInfo?.City)) city = country;
  6274. else city = countryInfo?.City ?? "";
  6275. }
  6276. else
  6277. {
  6278. var countryInfo1 = countrys.Find(x => opInfos[i].Area.Contains(x.Country));
  6279. if (countryInfo1 != null)
  6280. {
  6281. country = countryInfo1?.Country ?? "";
  6282. city = countryInfo1?.City ?? country;
  6283. var countryInfo2 = countrys.Find(x => opInfos[i].Area.Contains(x.City));
  6284. if (citySelecter.Contains(countryInfo2?.City)) city = country;
  6285. else city = countryInfo2?.City ?? country;
  6286. }
  6287. else
  6288. {
  6289. var countryInfo2 = countrys.Find(x => opInfos[i].Area.Contains(x.City));
  6290. if (countryInfo2 != null)
  6291. {
  6292. country = countryInfo2?.Country ?? "";
  6293. city = countryInfo2?.City ?? "";
  6294. if (citySelecter.Contains(countryInfo2?.City)) city = country;
  6295. }
  6296. }
  6297. }
  6298. opInfos[i].Country = country;
  6299. opInfos[i].City = city;
  6300. }
  6301. var opParentFeeData = new StatisticsOP()._OPParentFeeInfo;
  6302. if (_dto.Type == 1)
  6303. {
  6304. //同比增长率=(本期数-同期数)/ 同期数
  6305. var yearData = opInfos.GroupBy(x => x.ParentFeeName)
  6306. .Select(x => new StatisticsOPYOY(
  6307. feeId: x.FirstOrDefault()?.ParentFeeId ?? 0,
  6308. feeName: x.Key,
  6309. currPeriodFee: x.Where(x => x.Year == thisYear).Sum(x => x.Price),
  6310. samePeriodFee: x.Where(x => x.Year == lastYear).Sum(x => x.Price),
  6311. currPeriodGroupTotal: x.Where(x => x.Year == thisYear).Select(x => x.DiId).Distinct().Count(),
  6312. samePeriodGroupTotal: x.Where(x => x.Year == lastYear).Select(x => x.DiId).Distinct().Count(),
  6313. subFeeData: x.GroupBy(x1 => x1.FeeSubType)
  6314. .Select(x1 => new StatisticsOPSubFeeYOY(
  6315. feeId: x1.Key,
  6316. feeName: x1.FirstOrDefault()?.FeeSubTypeName ?? "",
  6317. currPeriodFee: x1.Where(x1 => x1.Year == thisYear).Sum(x1 => x1.Price),
  6318. samePeriodFee: x1.Where(x1 => x1.Year == lastYear).Sum(x1 => x1.Price),
  6319. currPeriodGroupTotal: x1.Where(x1 => x1.Year == thisYear).Select(x1 => x1.DiId).Distinct().Count(),
  6320. samePeriodGroupTotal: x1.Where(x1 => x1.Year == lastYear).Select(x1 => x1.DiId).Distinct().Count(),
  6321. cityData: x1.GroupBy(x2 => x2.City)
  6322. .Select(x2 => new StatisticsOPCityYOY(
  6323. cityName: x2.Key,
  6324. currPeriodGroupTotal: x2.Where(x2 => x2.Year == thisYear).Select(x2 => x2.DiId).Distinct().Count(),
  6325. samePeriodGroupTotal: x2.Where(x2 => x2.Year == lastYear).Select(x2 => x2.DiId).Distinct().Count(),
  6326. currPeriodFee: x2.Where(x2 => x2.Year == thisYear).Sum(x2 => x2.Price),
  6327. samePeriodFee: x2.Where(x2 => x2.Year == lastYear).Sum(x2 => x2.Price)
  6328. ))
  6329. .ToArray()
  6330. ))
  6331. .ToArray()
  6332. ))
  6333. .OrderBy(x => x.FeeId)
  6334. .ToList();
  6335. var opParentYearIds = yearData.Select(x => x.FeeId).ToList();
  6336. var opParentYearDataSelector = opParentFeeData.Where(x => !opParentYearIds.Contains(x.Id)).ToList();
  6337. if (opParentYearDataSelector.Count > 0)
  6338. {
  6339. foreach (var item in opParentYearDataSelector)
  6340. {
  6341. yearData.Add(
  6342. new StatisticsOPYOY(feeId: item.Id,
  6343. feeName: item.Name,
  6344. currPeriodFee: 0.00M,
  6345. samePeriodFee: 0.00M,
  6346. currPeriodGroupTotal: 0,
  6347. samePeriodGroupTotal: 0,
  6348. subFeeData: Array.Empty<StatisticsOPSubFeeYOY>()
  6349. ));
  6350. }
  6351. yearData = yearData.OrderBy(x => x.FeeId).ToList();
  6352. }
  6353. return Ok(JsonView(true, "操作成功!", yearData));
  6354. }
  6355. else if (_dto.Type == 2)
  6356. {
  6357. var monthData = opInfos.GroupBy(x => x.Month)
  6358. .Select(x => new StatisticsOPMonthYOY(
  6359. monthId: x.Key,
  6360. monthName: System.Enum.IsDefined(typeof(MonthEnum), (int)x.Key) ? ((MonthEnum)(int)x.Key).GetEnumDescription() : "",
  6361. feeDatas: x.GroupBy(x1 => x1.ParentFeeId)
  6362. .Select(x1 => new StatisticsOPYOY(
  6363. feeId: x1.Key,
  6364. feeName: x1.FirstOrDefault()?.ParentFeeName ?? "",
  6365. currPeriodFee: x1.Where(x1 => x1.Year == thisYear).Sum(x1 => x1.Price),
  6366. samePeriodFee: x1.Where(x1 => x1.Year == lastYear).Sum(x1 => x1.Price),
  6367. currPeriodGroupTotal: x1.Where(x1 => x1.Year == thisYear).Select(x1 => x1.DiId).Distinct().Count(),
  6368. samePeriodGroupTotal: x1.Where(x1 => x1.Year == lastYear).Select(x1 => x1.DiId).Distinct().Count(),
  6369. subFeeData: x1.GroupBy(x2 => x2.FeeSubType)
  6370. .Select(x2 => new StatisticsOPSubFeeYOY(
  6371. feeId: x2.Key,
  6372. feeName: x2.FirstOrDefault()?.FeeSubTypeName ?? "",
  6373. currPeriodFee: x2.Where(x2 => x2.Year == thisYear).Sum(x2 => x2.Price),
  6374. samePeriodFee: x2.Where(x2 => x2.Year == lastYear).Sum(x2 => x2.Price),
  6375. currPeriodGroupTotal: x2.Where(x2 => x2.Year == thisYear).Select(x2 => x2.DiId).Distinct().Count(),
  6376. samePeriodGroupTotal: x2.Where(x2 => x2.Year == lastYear).Select(x2 => x2.DiId).Distinct().Count(),
  6377. cityData: x2.GroupBy(x3 => x3.City)
  6378. .Select(x3 => new StatisticsOPCityYOY(
  6379. cityName: x3.Key,
  6380. currPeriodFee: x3.Where(x3 => x3.Year == thisYear).Sum(x3 => x3.Price),
  6381. samePeriodFee: x3.Where(x3 => x3.Year == lastYear).Sum(x3 => x3.Price),
  6382. currPeriodGroupTotal: x3.Where(x3 => x3.Year == thisYear).Select(x3 => x3.DiId).Distinct().Count(),
  6383. samePeriodGroupTotal: x3.Where(x3 => x3.Year == lastYear).Select(x3 => x3.DiId).Distinct().Count()
  6384. ))
  6385. .ToArray()
  6386. ))
  6387. .ToArray()
  6388. ))
  6389. .ToArray()
  6390. ))
  6391. //.OrderBy(x => x.MonthId)
  6392. .ToList();
  6393. //1、月份是否足够十二月
  6394. var monthIds = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
  6395. var monthDataIds = monthData.Select(x => x.MonthId).ToArray();
  6396. var newMonthIds = monthIds.Where(x => !monthDataIds.Contains(x)).ToList();
  6397. if (newMonthIds.Count > 0)
  6398. {
  6399. foreach (var item in newMonthIds)
  6400. {
  6401. monthData.Add(new StatisticsOPMonthYOY(
  6402. monthId: item,
  6403. monthName: System.Enum.IsDefined(typeof(MonthEnum), (int)item) ? ((MonthEnum)(int)item).GetEnumDescription() : "",
  6404. feeDatas: System.Array.Empty<StatisticsOPYOY>()
  6405. ));
  6406. }
  6407. monthData = monthData.OrderBy(x => x.MonthId).ToList();
  6408. }
  6409. //2、费用父类是否足够
  6410. for (int i = 0; i < monthData.Count; i++)
  6411. {
  6412. var month = monthData[i];
  6413. var opParentFeeIds = month.FeeDatas.Select(x => x.FeeId).ToList();
  6414. var opParentFeeDataSelector = opParentFeeData.Where(x => !opParentFeeIds.Contains(x.Id)).ToList();
  6415. if (opParentFeeDataSelector.Count > 0)
  6416. {
  6417. var feeDatas = month.FeeDatas.ToList();
  6418. foreach (var item in opParentFeeDataSelector)
  6419. {
  6420. feeDatas.Add(new StatisticsOPYOY(
  6421. feeId: item.Id,
  6422. feeName: item.Name,
  6423. currPeriodFee: 0.00M,
  6424. samePeriodFee: 0.00M,
  6425. currPeriodGroupTotal: 0,
  6426. samePeriodGroupTotal: 0,
  6427. subFeeData: System.Array.Empty<StatisticsOPSubFeeYOY>()
  6428. ));
  6429. }
  6430. feeDatas = feeDatas.OrderBy(x => x.FeeId).ToList();
  6431. monthData[i].FeeDatas = feeDatas.ToArray();
  6432. }
  6433. }
  6434. //3、费用子类是否足够
  6435. return Ok(JsonView(true, "操作成功!", monthData));
  6436. }
  6437. return Ok(JsonView(false, "操作失败!"));
  6438. }
  6439. /// <summary>
  6440. /// 团组数据统计
  6441. /// 团组预算/实际成本
  6442. /// </summary>
  6443. /// <param name="_dto"></param>
  6444. /// <returns></returns>
  6445. [HttpPost("StatisticsGroupCost")]
  6446. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6447. public async Task<IActionResult> StatisticsBRCost(StatisticsBRCostDto _dto)
  6448. {
  6449. if (_dto.Year < 1) return Ok(JsonView(false, "Year参数错误!"));
  6450. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  6451. endDt = $"{_dto.Year}-12-31 23:59:59";
  6452. var sql = string.Format(@"
  6453. SELECT
  6454. ROW_NUMBER() OVER(
  6455. ORDER BY
  6456. di.VisitDate DESC
  6457. ) AS 'RowNumber',
  6458. di.Id,
  6459. di.TeamName AS 'GroupName',
  6460. di.ClientUnit,
  6461. di.VisitDate,
  6462. di.VisitDays,
  6463. di.VisitPNumber,
  6464. (
  6465. SELECT
  6466. TOP 1 CASE
  6467. ISNUMERIC (gcp.Currency)
  6468. WHEN 1 THEN (
  6469. SELECT
  6470. Name
  6471. FROM
  6472. Sys_SetData sd
  6473. WHERE
  6474. CAST(gcp.Currency AS INT) = sd.Id
  6475. )
  6476. ELSE gcp.Currency
  6477. END AS 'CurrencyCode'
  6478. FROM
  6479. Grp_GroupCostParameter gcp
  6480. WHERE
  6481. gcp.IsDel = 0
  6482. AND gcp.DiId = di.Id
  6483. ) Budget_CurrencyCode,
  6484. --预算币种
  6485. (
  6486. SELECT
  6487. TOP 1 CAST(COALESCE(gcp.Rate, 0.0000) AS DECIMAL(12, 4))
  6488. FROM
  6489. Grp_GroupCostParameter gcp
  6490. WHERE
  6491. gcp.IsDel = 0
  6492. AND gcp.DiId = di.Id
  6493. ) Budget_Rate,
  6494. --预算汇率
  6495. (
  6496. SELECT
  6497. CAST(
  6498. SUM(COALESCE(gcp.VisaCB, 0) * COALESCE(gcp.VisaRS, 0)) AS DECIMAL(12, 2)
  6499. )
  6500. FROM
  6501. Grp_GroupCostParameter gcp
  6502. WHERE
  6503. gcp.IsDel = 0
  6504. AND gcp.DiId = di.id
  6505. ) Budget_VisaAmount,
  6506. -- 预算签证成本
  6507. (
  6508. SELECT
  6509. CAST(
  6510. SUM(
  6511. (
  6512. (ccp.PayMoney * ccp.DayRate)
  6513. )
  6514. ) AS DECIMAL(12, 2)
  6515. )
  6516. FROM
  6517. Grp_VisaInfo vi
  6518. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6519. AND ccp.CTable = 80
  6520. AND vi.Id = ccp.CId
  6521. WHERE
  6522. vi.IsDel = 0
  6523. AND ccp.IsAuditGM = 1
  6524. AND ccp.IsPay = 1
  6525. AND di.Id = vi.DIId
  6526. ) AS Reality_VisaAmount,
  6527. -- 实际签证成本
  6528. (
  6529. SELECT
  6530. CAST(
  6531. SUM(
  6532. COALESCE(gcp.JJCCB, 0) * COALESCE(gcp.JJCRS, 0) + COALESCE(gcp.GWCCB, 0) * COALESCE(gcp.GWCRS, 0) + COALESCE(gcp.TDCCB, 0) * COALESCE(gcp.TDCRS, 0)
  6533. ) AS DECIMAL(12, 2)
  6534. )
  6535. FROM
  6536. Grp_GroupCostParameter gcp
  6537. WHERE
  6538. gcp.IsDel = 0
  6539. AND gcp.DiId = di.id
  6540. ) Budget_AirTicketAmount,
  6541. -- 预算机票成本
  6542. (
  6543. SELECT
  6544. CAST(
  6545. SUM(
  6546. (
  6547. (ccp.PayMoney * ccp.DayRate)
  6548. )
  6549. ) AS DECIMAL(12, 2)
  6550. )
  6551. FROM
  6552. Grp_AirTicketReservations atr
  6553. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6554. AND ccp.CTable = 85
  6555. AND atr.Id = ccp.CId
  6556. WHERE
  6557. atr.IsDel = 0
  6558. AND ccp.IsAuditGM = 1
  6559. AND ccp.IsPay = 1
  6560. AND di.Id = atr.DiId
  6561. ) Reality_AirTicketAmount,
  6562. --实际机票
  6563. (
  6564. SELECT
  6565. CAST(
  6566. SUM(
  6567. 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)
  6568. ) AS DECIMAL(12, 2)
  6569. )
  6570. FROM
  6571. Grp_GroupCostParameter gcp
  6572. WHERE
  6573. gcp.IsDel = 0
  6574. AND gcp.DiId = di.id
  6575. ) Budget_HotelAmount,
  6576. -- 预算酒店成本
  6577. (
  6578. SELECT
  6579. CAST(
  6580. SUM(
  6581. (ccp.PayMoney * ccp.DayRate)
  6582. ) AS DECIMAL(12, 2)
  6583. )
  6584. FROM
  6585. Grp_HotelReservations hr
  6586. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  6587. WHERE
  6588. hr.IsDel = 0
  6589. AND ccp.IsDel = 0
  6590. AND ccp.CTable = 76
  6591. AND ccp.IsAuditGM = 1
  6592. AND ccp.PayMoney <> 0
  6593. AND ccp.IsPay = 1
  6594. AND di.Id = hr.DiId
  6595. ) AS Reality_HotelAmount,
  6596. -- 实际酒店成本
  6597. (
  6598. SELECT
  6599. CAST(
  6600. SUM(COALESCE(gcp.DJCB, 0) * COALESCE(gcp.DJRS, 0)) AS DECIMAL(12, 2)
  6601. )
  6602. FROM
  6603. Grp_GroupCostParameter gcp
  6604. WHERE
  6605. gcp.IsDel = 0
  6606. AND gcp.DiId = di.id
  6607. ) Budget_OPAmount,
  6608. -- 预算 OP
  6609. (
  6610. SELECT
  6611. CAST(
  6612. SUM(
  6613. (
  6614. ctggr.ServiceQuotedPrice * (ccp.PayPercentage / 100) * ccp.DayRate
  6615. )
  6616. ) AS DECIMAL(12, 2)
  6617. )
  6618. FROM
  6619. Grp_CarTouristGuideGroundReservations ctggr
  6620. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  6621. AND ccp.CTable = 79
  6622. AND ctggr.Id = ccp.CId
  6623. WHERE
  6624. ctggr.IsDel = 0
  6625. AND ccp.IsAuditGM = 1
  6626. AND ccp.IsPay = 1
  6627. AND di.Id = ctggr.DiId
  6628. ) AS Reality_OPAmount,
  6629. -- 实际 OP
  6630. (
  6631. SELECT
  6632. CAST(
  6633. SUM(COALESCE(gcp.GWCB, 0) * COALESCE(gcp.GWRS, 0)) AS DECIMAL(12, 2)
  6634. )
  6635. FROM
  6636. Grp_GroupCostParameter gcp
  6637. WHERE
  6638. gcp.IsDel = 0
  6639. AND gcp.DiId = di.id
  6640. ) Budget_OAAmount,
  6641. -- 预算 商邀
  6642. (
  6643. SELECT
  6644. CAST(
  6645. SUM(
  6646. (ccp.PayMoney * ccp.DayRate)
  6647. ) AS DECIMAL(12, 2)
  6648. )
  6649. FROM
  6650. Grp_InvitationOfficialActivities ioa
  6651. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6652. AND ccp.CTable = 81
  6653. AND ioa.Id = ccp.CId
  6654. WHERE
  6655. ioa.IsDel = 0
  6656. AND ccp.IsAuditGM = 1
  6657. AND ccp.IsPay = 1
  6658. AND di.Id = ioa.Diid
  6659. ) AS Reality_OAAmount,
  6660. -- 实际 商邀
  6661. (
  6662. SELECT
  6663. CAST(
  6664. SUM(
  6665. 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)
  6666. ) AS DECIMAL(12, 2)
  6667. )
  6668. FROM
  6669. Grp_GroupCostParameter gcp
  6670. WHERE
  6671. gcp.IsDel = 0
  6672. AND gcp.DiId = di.id
  6673. ) Budget_OtherAmount,
  6674. -- 预算其他成本
  6675. (
  6676. SELECT
  6677. CAST(
  6678. SUM(
  6679. (ccp.PayMoney * ccp.DayRate)
  6680. ) AS DECIMAL(12, 2)
  6681. )
  6682. FROM
  6683. Grp_Customers ic
  6684. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6685. AND ccp.CTable = 82
  6686. AND ic.Id = ccp.CId
  6687. WHERE
  6688. ic.IsDel = 0
  6689. AND ccp.IsAuditGM = 1And ccp.IsPay = 1
  6690. AND di.Id = ic.DiId
  6691. ) AS Reality_InsureAmount,
  6692. -- 实际保险成本
  6693. (
  6694. SELECT
  6695. CAST(SUM((ccp.PayMoney * ccp.DayRate)) AS DECIMAL(12, 2))
  6696. FROM
  6697. Grp_DecreasePayments dp
  6698. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6699. AND ccp.CTable = 98
  6700. AND dp.Id = ccp.CId
  6701. WHERE
  6702. dp.IsDel = 0
  6703. AND ccp.Ctable = 98
  6704. AND ccp.IsAuditGM = 1
  6705. AND ccp.IsPay = 1
  6706. AND di.Id = dp.Diid
  6707. ) AS Reality_OtherCostAmount -- 实际其他款项
  6708. FROM
  6709. Grp_DelegationInfo di
  6710. WHERE
  6711. di.IsDel = 0
  6712. AND di.IsBid = 0
  6713. --AND di.TeamDid IN (38, 39, 40, 1048)
  6714. AND di.VisitDate BETWEEN '{0}' AND '{1}'
  6715. ", beginDt, endDt);
  6716. if (!string.IsNullOrEmpty(_dto.Search))
  6717. {
  6718. sql += $"AND di.TeamName Like '%{_dto.Search}%'";
  6719. }
  6720. var view = await _sqlSugar.SqlQueryable<StatisticsBRCostView>(sql).ToListAsync();
  6721. view = view.Where(x => !x.GroupName.Contains("投标") && x.RealityAmount > 0).OrderByDescending(x => x.Id).ToList();
  6722. var total = view.Count;
  6723. var toSkip = (_dto.PageIndex - 1) * _dto.PageSize;
  6724. var data = view.Skip(toSkip).Take(_dto.PageSize).ToList();
  6725. if (data.Count > 0)
  6726. {
  6727. var diIds = data.Select(x => x.Id).ToList();
  6728. var currencyData = await _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0 && x.STid == 66).ToListAsync();
  6729. var ccpData = await _sqlSugar.Queryable<Grp_CreditCardPayment>()
  6730. .Where(x => x.IsDel == 0 &&
  6731. diIds.Contains(x.DIId) &&
  6732. x.IsPay == 1 &&
  6733. x.IsAuditGM == 1
  6734. )
  6735. .ToListAsync();
  6736. for (int i = 0; i < data.Count; i++)
  6737. {
  6738. var info = data[i];
  6739. info.RowNumber = i + 1;
  6740. #region 1:签证 80
  6741. var visaDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 80).ToList();
  6742. var visaDesc = "-";
  6743. if (visaDatas.Count > 0)
  6744. {
  6745. visaDesc = $"实际币种金额:";
  6746. foreach (var visa in visaDatas)
  6747. {
  6748. var currencyCode = currencyData.Find(x => x.Id == visa.PaymentCurrency)?.Name;
  6749. visaDesc += $"{visa.PayMoney} {currencyCode} 汇率:{visa.DayRate.ToString("#0.0000")};";
  6750. }
  6751. }
  6752. info.Reality_VisaAmountDesc = visaDesc;
  6753. #endregion
  6754. #region 2:机票 85
  6755. var airDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 85).ToList();
  6756. var airDesc = "-";
  6757. if (airDatas.Count > 0)
  6758. {
  6759. airDesc = $"实际币种金额:";
  6760. foreach (var air in airDatas)
  6761. {
  6762. var currencyCode = currencyData.Find(x => x.Id == air.PaymentCurrency)?.Name;
  6763. airDesc += $"{air.PayMoney} {currencyCode} 汇率:{air.DayRate.ToString("#0.0000")};";
  6764. }
  6765. }
  6766. info.Reality_AirTicketAmountDesc = airDesc;
  6767. #endregion
  6768. #region 3:酒店 76
  6769. var hotelDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 76 && x.PayMoney != 0).ToList();
  6770. var hotelDesc = "-";
  6771. if (hotelDatas.Count > 0)
  6772. {
  6773. hotelDesc = $"实际币种金额:";
  6774. foreach (var hotel in hotelDatas)
  6775. {
  6776. var currencyCode = currencyData.Find(x => x.Id == hotel.PaymentCurrency)?.Name;
  6777. hotelDesc += $"{hotel.PayMoney} {currencyCode} 汇率:{hotel.DayRate.ToString("#0.0000")};";
  6778. }
  6779. }
  6780. info.Reality_HotelAmountDesc = hotelDesc;
  6781. #endregion
  6782. #region 4:OP 79
  6783. var opDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 79 && x.PayMoney != 0).ToList();
  6784. var opDesc = "-";
  6785. if (opDatas.Count > 0)
  6786. {
  6787. opDesc = $"实际币种金额;";
  6788. foreach (var op in opDatas)
  6789. {
  6790. var currencyCode = currencyData.Find(x => x.Id == op.PaymentCurrency)?.Name;
  6791. opDesc += $"{op.PayMoney} {currencyCode} 汇率:{op.DayRate.ToString("#0.0000")};";
  6792. }
  6793. }
  6794. info.Reality_OPAmountDesc = opDesc;
  6795. #endregion
  6796. #region 5:商邀 81
  6797. var oaDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 81 && x.PayMoney != 0).ToList();
  6798. var oaDesc = "-";
  6799. if (oaDatas.Count > 0)
  6800. {
  6801. oaDesc = $"实际币种金额:";
  6802. foreach (var oa in oaDatas)
  6803. {
  6804. var currencyCode = currencyData.Find(x => x.Id == oa.PaymentCurrency)?.Name;
  6805. oaDesc += $"{oa.PayMoney} {currencyCode} 汇率:{oa.DayRate.ToString("#0.0000")};";
  6806. }
  6807. }
  6808. info.Reality_OAAmountDesc = oaDesc;
  6809. #endregion
  6810. #region 6:其他款项(保险 82、其他款项 98)
  6811. var cTables = new List<int>() { 82, 98 };
  6812. var otherDatas = ccpData.Where(x => x.DIId == info.Id && cTables.Contains(x.CTable) && x.PayMoney != 0).ToList();
  6813. var otherDesc = "-";
  6814. if (otherDatas.Count > 0)
  6815. {
  6816. otherDesc = $"实际币种金额:";
  6817. foreach (var other in otherDatas)
  6818. {
  6819. var currencyCode = currencyData.Find(x => x.Id == other.PaymentCurrency)?.Name;
  6820. otherDesc += $"{other.PayMoney} {currencyCode} 汇率:{other.DayRate.ToString("#0.0000")};";
  6821. }
  6822. }
  6823. info.Reality_OtherCostAmountDesc = otherDesc;
  6824. #endregion
  6825. }
  6826. }
  6827. var briefData = _mapper.Map<List<StatisticsBRCostBriefView>>(data);
  6828. return Ok(JsonView(briefData, total));
  6829. }
  6830. /// <summary>
  6831. /// 团组数据统计
  6832. /// 当前时间团组所在城市
  6833. /// </summary>
  6834. /// <param name="dto"></param>
  6835. /// <returns></returns>
  6836. [HttpPost("StatisticsNowCityOfGroup")]
  6837. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6838. public async Task<IActionResult> StatisticsNowCityOfGroup(StatisticsNowCityOfGroupDto dto)
  6839. {
  6840. if (!SharingStaticData.PortTypes.Contains(dto.PortType)) return Ok(JsonView(false, MsgTips.Port));
  6841. var nowLable = DateTime.Now.ToString("yyyy-MM-dd");
  6842. var sql = string.Format(@"SELECT * FROM Grp_DelegationInfo WHERE ISdel = 0 AND '{0}' BETWEEN VisitStartDate AND VisitEndDate", nowLable);
  6843. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql)
  6844. .Select(x => new { x.Id, x.VisitCountry, x.TeamName, x.ClientUnit, x.VisitStartDate, x.VisitEndDate }).
  6845. ToListAsync();
  6846. if (!groupInfos.Any()) return Ok(JsonView(false, "今日暂无团组出行!"));
  6847. var groupIds = groupInfos.Select(x => x.Id).ToList();
  6848. //三字码
  6849. var threeDatas = await _sqlSugar.Queryable<Res_ThreeCode>().Where(x => x.IsDel == 0).ToListAsync();
  6850. //国家
  6851. var countryDatas = await _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(x => x.IsDel == 0 && !string.IsNullOrEmpty(x.Country) && !string.IsNullOrEmpty(x.City)).ToListAsync();
  6852. //公务
  6853. var OADatas = await _sqlSugar
  6854. .Queryable<Res_OfficialActivities>().Where(x => x.IsDel == 0 && groupIds.Contains(x.DiId) && !string.IsNullOrEmpty(x.Country) && !string.IsNullOrEmpty(x.Area))
  6855. .ToListAsync();
  6856. //酒店
  6857. var hotelDatas = await _sqlSugar.Queryable<Grp_HotelReservations>()
  6858. .LeftJoin<Grp_NationalTravelFee>((hr, ntf) => hr.AreaId == ntf.Id)
  6859. .Where((hr, ntf) => hr.IsDel == 0 && groupIds.Contains(hr.DiId))
  6860. .Select((hr, ntf) => new
  6861. {
  6862. hr.DiId,
  6863. hr.AreaId,
  6864. hr.HotelName,
  6865. hr.CheckInDate,
  6866. hr.CheckOutDate,
  6867. hr.HotelAddress,
  6868. ntf.Country,
  6869. ntf.City
  6870. })
  6871. .ToListAsync();
  6872. //机票
  6873. /*
  6874. *舱位类型
  6875. *457 头等舱
  6876. *458 公务舱
  6877. *459 超经舱
  6878. *460 经济舱
  6879. *461 退票
  6880. *565 其他
  6881. *574 长段公务舱
  6882. *575 短途经济舱
  6883. *1023 行程单打印费
  6884. *1024 选座费
  6885. */
  6886. var classTypes = new int[] { 457, 458, 459, 460, 574, 575 };
  6887. var airDatas = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
  6888. .Where(atr => atr.IsDel == 0 && groupIds.Contains(atr.DIId) && classTypes.Contains(atr.CType))
  6889. .ToListAsync();
  6890. string[] characters = { "|", "、" };
  6891. var result = new List<StatisticsNowCityOfGroupResultView>();
  6892. foreach (var item in groupInfos)
  6893. {
  6894. string statusText = string.Empty,
  6895. address = string.Empty;
  6896. var countrys = item.VisitCountry;
  6897. if (string.IsNullOrEmpty(countrys)) continue;
  6898. var currCountrys = item.VisitCountry.Split(characters, StringSplitOptions.RemoveEmptyEntries);
  6899. var stutus = true;
  6900. #region 公务
  6901. var currOADatas = OADatas.Where(x => x.DiId == item.Id && currCountrys.Any(c => x.Country.Contains(c))).ToList();
  6902. if (currOADatas.Any())
  6903. {
  6904. foreach (var curr_oa in currOADatas)
  6905. {
  6906. var localTime = GetCountryOrCityCurrentDateTime(curr_oa.Country, curr_oa.Area);
  6907. if (localTime == null) continue;
  6908. var currOaDtStart = Convert.ToDateTime($"{Convert.ToDateTime(curr_oa.Date).ToString("yyyy-MM-dd")} {curr_oa.Time}");
  6909. var currOaDtEnd = currOaDtStart.AddHours(2);
  6910. var currTimeZoneStatus = localTime >= currOaDtStart && localTime <= currOaDtEnd;
  6911. if (!currTimeZoneStatus) continue;
  6912. stutus = false;
  6913. statusText = "公务活动中";
  6914. address = curr_oa.Address;
  6915. break;
  6916. }
  6917. }
  6918. #endregion
  6919. #region 酒店
  6920. var currHotelDatas = hotelDatas.Where(x => x.DiId == item.Id && !string.IsNullOrEmpty(x.Country) && currCountrys.Any(c => x.Country.Contains(c))).ToList();
  6921. if (stutus && hotelDatas.Any())
  6922. {
  6923. foreach (var curr_hotel in currHotelDatas)
  6924. {
  6925. var checkInDt = Convert.ToDateTime(curr_hotel.CheckInDate);
  6926. List<(DateTime start, DateTime end)> timeRanges = new List<(DateTime, DateTime)>();
  6927. while (checkInDt <= Convert.ToDateTime(curr_hotel.CheckOutDate))
  6928. {
  6929. int year = checkInDt.Year,
  6930. month = checkInDt.Month,
  6931. day = checkInDt.Day;
  6932. timeRanges.Add((new DateTime(year, month, day, 0, 0, 0), new DateTime(year, month, day, 9, 0, 0)));
  6933. timeRanges.Add((new DateTime(year, month, day, 18, 0, 0), new DateTime(year, month, day, 23, 59, 59)));
  6934. checkInDt = checkInDt.AddDays(1);
  6935. }
  6936. if (!timeRanges.Any()) continue;
  6937. if (string.IsNullOrEmpty(curr_hotel.Country) && string.IsNullOrEmpty(curr_hotel.City)) continue;
  6938. var countryInfo = countryDatas.Where(x => x.Id == curr_hotel.AreaId).FirstOrDefault();
  6939. if (countryInfo == null) continue;
  6940. var localTime = GetCountryOrCityCurrentDateTime(countryInfo.Country, countryInfo.City);
  6941. var currTimeZoneStatus = timeRanges.Any(range => localTime >= range.start && localTime <= range.end);
  6942. if (!currTimeZoneStatus) continue;
  6943. stutus = false;
  6944. statusText = "入住酒店中";
  6945. address = curr_hotel.HotelAddress;
  6946. break;
  6947. }
  6948. }
  6949. #endregion
  6950. #region 机票--通过三字码解析处理
  6951. var airTicketDatas = GetTableByBlackCode(item.Id);
  6952. if (stutus && airTicketDatas != null)
  6953. {
  6954. foreach (DataRow curr_airTicket in airTicketDatas.Rows)
  6955. {
  6956. string departDate = curr_airTicket["Date"].ToString(), //出发日期
  6957. departThree = curr_airTicket["Three"].ToString(), //城市三字码
  6958. departTime = curr_airTicket["StartTime"].ToString(), //出发时刻
  6959. departTerminal = curr_airTicket["StartBuilding"].ToString(), //出发航站楼
  6960. arriveTerminal = curr_airTicket["EndBuilding"].ToString(), //抵达航站楼
  6961. arrivedDate = curr_airTicket["ArrivedDate"].ToString(), //抵达日期
  6962. arrivedTime = curr_airTicket["EndTime"].ToString(), //抵达日期
  6963. flightTime = curr_airTicket["FlightTime"].ToString(); //飞行时间
  6964. if (string.IsNullOrEmpty(departThree)) continue;
  6965. string departAirThree = departThree.Substring(0, 3),
  6966. arriveAirThree = departThree.Substring(3, 3);
  6967. string departCountry = string.Empty,
  6968. departCity = string.Empty,
  6969. departAirport = string.Empty,
  6970. arriveCountry = string.Empty,
  6971. arriveCity = string.Empty,
  6972. arriveAirport = string.Empty;
  6973. var departCountryInfo = threeDatas.Find(x => x.Three.Equals(departAirThree));
  6974. var arriveCountryInfo = threeDatas.Find(x => x.Three.Equals(arriveAirThree));
  6975. if (departCountryInfo == null || arriveCountryInfo == null) continue;
  6976. departCountry = departCountryInfo.Country;
  6977. departCity = departCountryInfo.City;
  6978. departAirport = departCountryInfo.AirPort;
  6979. arriveCountry = arriveCountryInfo.Country;
  6980. arriveCity = arriveCountryInfo.City;
  6981. arriveAirport = arriveCountryInfo.AirPort;
  6982. var arriveDateTimeBool = DateTime.TryParse(arrivedDate + " " + arrivedTime.Insert(2, ":"), out DateTime arriveDateTime);
  6983. if (!arriveDateTimeBool) continue;
  6984. var filghtHoursBool = int.TryParse(flightTime.Split("H")[0].ToString(), out int filghtHours);
  6985. var filghtMinutesBool = int.TryParse(flightTime.Split("H")[1].Remove(2).ToString(), out int filghtMinutes);
  6986. if (!filghtHoursBool || !filghtHoursBool) continue;
  6987. var departDateTime = arriveDateTime.AddHours(-filghtHours).AddMinutes(-filghtMinutes);
  6988. var localTime = GetCountryOrCityCurrentDateTime(arriveCountry, arriveCity);
  6989. var currTimeZoneStatus = localTime >= departDateTime && localTime <= arriveDateTime;
  6990. if (!currTimeZoneStatus) continue;
  6991. stutus = false;
  6992. statusText = $"正飞往{arriveCity}城市中";
  6993. address = $"{arriveCountry}{arriveAirport}{arriveTerminal}";
  6994. break;
  6995. }
  6996. }
  6997. if (stutus) statusText = $"其他";
  6998. #endregion
  6999. result.Add(new StatisticsNowCityOfGroupResultView()
  7000. {
  7001. GroupName = item.TeamName,
  7002. Client = item.ClientUnit,
  7003. StatusText = statusText,
  7004. Address = address
  7005. });
  7006. }
  7007. result.AddRange(new List<StatisticsNowCityOfGroupResultView>() {
  7008. new StatisticsNowCityOfGroupResultView(){ GroupName = "模拟数据团组1",Client = "模拟数据单位1",StatusText = "正在公务中",Address = "日本〒104-0032 Tokyo, Chuo City, Hatchobori, 1 Chome−12−8 EAST2階" },
  7009. new StatisticsNowCityOfGroupResultView(){ GroupName = "模拟数据团组2",Client = "模拟数据单位2",StatusText = "入住酒店中",Address = "日本〒104-0032 Tokyo, Chuo City, Hatchobori, 1 Chome−12−8 EAST2階" },
  7010. new StatisticsNowCityOfGroupResultView(){ GroupName = "模拟数据团组3",Client = "模拟数据单位3",StatusText = "其他",Address = "日本〒104-0032 Tokyo, Chuo City, Hatchobori, 1 Chome−12−8 EAST2階" },
  7011. });
  7012. var result1 = result.GroupBy(x => x.Address).Select(g => new
  7013. {
  7014. address = g.Key,
  7015. Items = g.ToList().Select(gg => new { gg.GroupName, gg.Client, gg.StatusText }).ToList()
  7016. });
  7017. if (!result1.Any()) return Ok(JsonView(false, "今天暂无出行的的团!"));
  7018. return Ok(JsonView(result1));
  7019. }
  7020. private StatisticsNowCityOfGroupView CitySplit(string cityLable, List<Res_ThreeCode> cities)
  7021. {
  7022. var info = new StatisticsNowCityOfGroupView();
  7023. if (string.IsNullOrEmpty(cityLable)) return info;
  7024. var cityArray = cityLable.Split("-");
  7025. var departCityCode = cityArray[0];
  7026. var arriveCityCode = cityArray[1];
  7027. var departAirportInfo = cities.Find(x => x.Three.Equals(departCityCode.ToUpper()));
  7028. info.DepartAirportCode = departCityCode;
  7029. info.DepartCountryName = departAirportInfo?.Country ?? "-";
  7030. info.DepartCityName = departAirportInfo?.City ?? "-";
  7031. var arriveAirportInfo = cities.Find(x => x.Three.Equals(arriveCityCode.ToUpper()));
  7032. info.ArriveAirportCode = arriveCityCode;
  7033. info.ArriveCountryName = arriveAirportInfo?.Country ?? "-";
  7034. info.ArriveCityName = arriveAirportInfo?.City ?? "-";
  7035. return info;
  7036. }
  7037. #endregion
  7038. #region 企业利润
  7039. /// <summary>
  7040. /// 企业利润 infos
  7041. /// </summary>
  7042. /// <param name="beginDt"></param>
  7043. /// <param name="endDt"></param>
  7044. /// <returns></returns>
  7045. private async Task<CorporateProfitInfosView> CorporateProfitInfos(string beginDt, string endDt)
  7046. {
  7047. var view = new CorporateProfitInfosView();
  7048. #region 已审核SQL
  7049. // string sql = string.Format(@"SELECT
  7050. // ROW_NUMBER() OVER(ORDER BY di.VisitDate Asc) AS 'RowIndex',
  7051. // di.Id,
  7052. // di.ClientName,
  7053. // di.TeamName,
  7054. // di.TeamDid,
  7055. // ss.Name AS 'GroupTypeName',
  7056. // di.VisitDate,
  7057. // di.VisitPNumber,
  7058. // (
  7059. // SELECT
  7060. // SUM(ffr.ItemSumPrice)
  7061. // FROM
  7062. // OA2023DB.dbo.Fin_ForeignReceivables ffr
  7063. // WHERE
  7064. // ffr.IsDel = 0
  7065. // AND ffr.Diid = di.Id
  7066. // ) 'ReceivableAmount',
  7067. // (
  7068. // SELECT
  7069. // SUM(fpr.Price)
  7070. // FROM
  7071. // OA2023DB.dbo.Fin_ProceedsReceived fpr
  7072. // WHERE
  7073. // fpr.IsDel = 0
  7074. // AND fpr.DIId = di.Id
  7075. // ) 'ReceivedAmount',
  7076. // (
  7077. // SELECT
  7078. // SUM(ccp.PayMoney * ccp.DayRate)
  7079. // FROM
  7080. // Fin_PaymentRefundAndOtherMoney prom
  7081. // INNER JOIN Grp_CreditCardPayment ccp ON prom.Id = ccp.CId
  7082. // AND prom.DiId = ccp.DIId
  7083. // WHERE
  7084. // prom.IsDel = 0
  7085. // AND prom.PayType = 1
  7086. // AND ccp.CTable = 285
  7087. // AND ccp.IsAuditGM = 1
  7088. // AND prom.DiId = di.Id
  7089. // ) AS 'RefundedAmount',
  7090. // (
  7091. // SELECT
  7092. // SUM(ccp.PayMoney * ccp.DayRate)
  7093. // FROM
  7094. // Grp_HotelReservations hr
  7095. // INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  7096. // WHERE
  7097. // hr.IsDel = 0
  7098. // AND ccp.IsDel = 0
  7099. // AND ccp.CTable = 76
  7100. // AND (
  7101. // ccp.IsAuditGM = 1
  7102. // OR ccp.IsAuditGM = 3
  7103. // )
  7104. // AND hr.DiId = di.Id
  7105. // ) AS 'HotelAmount',
  7106. // (
  7107. // SELECT
  7108. // SUM(
  7109. // (ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate)
  7110. // )
  7111. // FROM
  7112. // Grp_CarTouristGuideGroundReservations ctggr
  7113. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  7114. // AND ccp.CTable = 79
  7115. // AND ctggr.Id = ccp.CId
  7116. // WHERE
  7117. // ctggr.IsDel = 0
  7118. // AND (
  7119. // ccp.IsAuditGM = 1
  7120. // OR ccp.IsAuditGM = 3
  7121. // )
  7122. // AND ctggr.DiId = di.Id
  7123. // ) AS 'LocalGuideAmount',
  7124. // (
  7125. // SELECT
  7126. // SUM(ccp.PayMoney * ccp.DayRate)
  7127. // FROM
  7128. // Grp_AirTicketReservations atr
  7129. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7130. // AND ccp.CTable = 85
  7131. // AND atr.Id = ccp.CId
  7132. // WHERE
  7133. // atr.IsDel = 0
  7134. // AND ccp.IsAuditGM = 1
  7135. // AND atr.DIId = di.Id
  7136. // ) AS 'AirTicketAmount',
  7137. // (
  7138. // SELECT
  7139. // SUM(ccp.PayMoney * ccp.DayRate)
  7140. // FROM
  7141. // Grp_VisaInfo vi
  7142. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7143. // AND ccp.CTable = 80
  7144. // AND vi.Id = ccp.CId
  7145. // WHERE
  7146. // vi.IsDel = 0
  7147. // AND ccp.IsAuditGM = 1
  7148. // AND vi.DIId = di.Id
  7149. // ) AS 'VisaAmount',
  7150. // (
  7151. // SELECT
  7152. // SUM(ccp.PayMoney * ccp.DayRate)
  7153. // FROM
  7154. // Grp_InvitationOfficialActivities ioa
  7155. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7156. // AND ccp.CTable = 81
  7157. // AND ioa.Id = ccp.CId
  7158. // WHERE
  7159. // ioa.IsDel = 0
  7160. // AND ccp.IsAuditGM = 1
  7161. // AND ioa.DiId = di.Id
  7162. // ) AS 'OAAmount',
  7163. // (
  7164. // SELECT
  7165. // SUM(ccp.PayMoney * ccp.DayRate)
  7166. // FROM
  7167. // Grp_Customers ic
  7168. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7169. // AND ccp.CTable = 82
  7170. // AND ic.Id = ccp.CId
  7171. // WHERE
  7172. // ic.IsDel = 0
  7173. // AND ccp.IsAuditGM = 1
  7174. // AND ic.DiId = di.Id
  7175. // ) AS 'InsureAmount',
  7176. // (
  7177. // SELECT
  7178. // SUM(ccp.PayMoney * ccp.DayRate)
  7179. // FROM
  7180. // Grp_DecreasePayments dp
  7181. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7182. // AND ccp.CTable = 98
  7183. // AND dp.Id = ccp.CId
  7184. // WHERE
  7185. // dp.IsDel = 0
  7186. // AND ccp.IsAuditGM = 1
  7187. // AND dp.Diid = di.Id
  7188. // ) AS 'OtherAmount'
  7189. //FROM
  7190. // OA2023DB.dbo.Grp_DelegationInfo di
  7191. // LEFT JOIN Sys_SetData ss ON di.TeamDid = ss.Id
  7192. //WHERE
  7193. // di.IsDel = 0
  7194. // AND di.IsBid = 0
  7195. // AND di.VisitDate BETWEEN '{0}' AND '{1}'", beginDt, endDt);
  7196. #endregion
  7197. //含未审核SQL
  7198. string sql = string.Format(@"SELECT
  7199. ROW_NUMBER() OVER(
  7200. ORDER BY
  7201. di.VisitDate Asc
  7202. ) AS 'RowIndex',
  7203. di.Id,
  7204. di.ClientName,
  7205. di.TeamName,
  7206. di.TeamDid,
  7207. ss.Name AS 'GroupTypeName',
  7208. di.VisitDate,
  7209. di.VisitPNumber,
  7210. (
  7211. SELECT
  7212. SUM(ffr.ItemSumPrice)
  7213. FROM
  7214. OA2023DB.dbo.Fin_ForeignReceivables ffr
  7215. WHERE
  7216. ffr.IsDel = 0
  7217. AND ffr.Diid = di.Id
  7218. ) 'ReceivableAmount',
  7219. (
  7220. SELECT
  7221. SUM(fpr.Price)
  7222. FROM
  7223. OA2023DB.dbo.Fin_ProceedsReceived fpr
  7224. WHERE
  7225. fpr.IsDel = 0
  7226. AND fpr.DIId = di.Id
  7227. ) 'ReceivedAmount',
  7228. (
  7229. SELECT
  7230. SUM(ccp.PayMoney * ccp.DayRate)
  7231. FROM
  7232. Fin_PaymentRefundAndOtherMoney prom
  7233. INNER JOIN Grp_CreditCardPayment ccp ON prom.Id = ccp.CId
  7234. AND prom.DiId = ccp.DIId
  7235. WHERE
  7236. prom.IsDel = 0
  7237. AND prom.PayType = 1
  7238. AND ccp.CTable = 285 --AND ccp.IsAuditGM = 1
  7239. AND ccp.IsAuditGM != 2
  7240. AND prom.DiId = di.Id
  7241. ) AS 'RefundedAmount',
  7242. (
  7243. SELECT
  7244. SUM(ccp.PayMoney * ccp.DayRate)
  7245. FROM
  7246. Grp_HotelReservations hr
  7247. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  7248. WHERE
  7249. hr.IsDel = 0
  7250. AND ccp.IsDel = 0
  7251. AND ccp.CTable = 76 -- AND (
  7252. -- ccp.IsAuditGM = 1
  7253. -- OR ccp.IsAuditGM = 3
  7254. -- )
  7255. AND ccp.IsAuditGM != 2
  7256. AND hr.DiId = di.Id
  7257. ) AS 'HotelAmount',
  7258. (
  7259. SELECT
  7260. SUM(
  7261. (ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate)
  7262. )
  7263. FROM
  7264. Grp_CarTouristGuideGroundReservations ctggr
  7265. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  7266. AND ccp.CTable = 79
  7267. AND ctggr.Id = ccp.CId
  7268. WHERE
  7269. ctggr.IsDel = 0 -- AND (
  7270. -- ccp.IsAuditGM = 1
  7271. -- OR ccp.IsAuditGM = 3
  7272. -- )
  7273. AND ccp.IsAuditGM != 2
  7274. AND ctggr.DiId = di.Id
  7275. ) AS 'LocalGuideAmount',
  7276. (
  7277. SELECT
  7278. SUM(ccp.PayMoney * ccp.DayRate)
  7279. FROM
  7280. Grp_AirTicketReservations atr
  7281. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7282. AND ccp.CTable = 85
  7283. AND atr.Id = ccp.CId
  7284. WHERE
  7285. atr.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7286. AND ccp.IsAuditGM != 2
  7287. AND atr.DIId = di.Id
  7288. ) AS 'AirTicketAmount',
  7289. (
  7290. SELECT
  7291. SUM(ccp.PayMoney * ccp.DayRate)
  7292. FROM
  7293. Grp_VisaInfo vi
  7294. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7295. AND ccp.CTable = 80
  7296. AND vi.Id = ccp.CId
  7297. WHERE
  7298. vi.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7299. AND ccp.IsAuditGM != 2
  7300. AND vi.DIId = di.Id
  7301. ) AS 'VisaAmount',
  7302. (
  7303. SELECT
  7304. SUM(ccp.PayMoney * ccp.DayRate)
  7305. FROM
  7306. Grp_InvitationOfficialActivities ioa
  7307. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7308. AND ccp.CTable = 81
  7309. AND ioa.Id = ccp.CId
  7310. WHERE
  7311. ioa.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7312. AND ccp.IsAuditGM != 2
  7313. AND ioa.DiId = di.Id
  7314. ) AS 'OAAmount',
  7315. (
  7316. SELECT
  7317. SUM(ccp.PayMoney * ccp.DayRate)
  7318. FROM
  7319. Grp_Customers ic
  7320. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7321. AND ccp.CTable = 82
  7322. AND ic.Id = ccp.CId
  7323. WHERE
  7324. ic.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7325. AND ccp.IsAuditGM != 2
  7326. AND ic.DiId = di.Id
  7327. ) AS 'InsureAmount',
  7328. (
  7329. SELECT
  7330. SUM(ccp.PayMoney * ccp.DayRate)
  7331. FROM
  7332. Grp_DecreasePayments dp
  7333. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7334. AND ccp.CTable = 98
  7335. AND dp.Id = ccp.CId
  7336. WHERE
  7337. dp.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7338. AND ccp.IsAuditGM != 2
  7339. AND dp.Diid = di.Id
  7340. ) AS 'OtherAmount',
  7341. (
  7342. SELECT
  7343. SUM(dfp.SumPrice)
  7344. FROM
  7345. Fin_DailyFeePayment dfp
  7346. WHERE
  7347. dfp.IsDel = 0
  7348. AND dfp.GroupId = di.Id
  7349. ) AS 'DailyAmout'
  7350. FROM
  7351. OA2023DB.dbo.Grp_DelegationInfo di
  7352. LEFT JOIN Sys_SetData ss ON di.TeamDid = ss.Id
  7353. WHERE
  7354. di.IsDel = 0
  7355. -- AND di.IsBid = 0
  7356. AND di.VisitDate BETWEEN '{0}' AND '{1}'", beginDt, endDt);
  7357. var groupItems = await _sqlSugar.SqlQueryable<CorporateProfitInfo>(sql).ToArrayAsync();
  7358. if (groupItems.Any())
  7359. {
  7360. // 排除 投标、延期、取消 等团组名称包含的关键词 并且 团组成本费用为0 排除在外
  7361. var excludeKeywords = new List<string> { "测试", "延期", "投标", "取消" };
  7362. groupItems = groupItems.Where(g =>
  7363. !excludeKeywords.Any(keyword => g.TeamName.Contains(keyword)) &&
  7364. g.CostTotal != 0
  7365. ).ToArray();
  7366. var groupIds = groupItems.Select(x => x.Id).ToArray();
  7367. var feeCountInfos = await CorporateProfitFeeCount(groupIds);
  7368. if (feeCountInfos.Any())
  7369. {
  7370. foreach (var item in groupItems)
  7371. {
  7372. var tips = feeCountInfos.FirstOrDefault(x => x.Id == item.Id)?.FeeCountTipsLabel ?? "";
  7373. if (!string.IsNullOrEmpty(tips)) item.FeeCountTipsLabel = tips;
  7374. }
  7375. }
  7376. }
  7377. var dailySql = string.Format(@"SELECT
  7378. dfp.Id,
  7379. dfp.CompanyId,
  7380. sc.CompanyName,
  7381. sd.DepName AS 'Branch',
  7382. su.CnName AS 'Applicant',
  7383. dfp.PriceTypeId,
  7384. sst.Id AS 'PriceParentTypeId',
  7385. sst.Name AS 'PriceParentTypeName',
  7386. ss.Id AS 'PriceTypeId',
  7387. ss.Name AS 'PriceypeName',
  7388. dfp.Instructions,
  7389. dfp.SumPrice AS 'CNYTotal',
  7390. dfpc.PriceName,
  7391. dfpc.Quantity,
  7392. dfpc.Price,
  7393. dfpc.ItemTotal,
  7394. dfpc.Remark,
  7395. dfp.CreateTime
  7396. From
  7397. Fin_DailyFeePayment dfp
  7398. INNER JOIN Fin_DailyFeePaymentContent dfpc on dfp.Id = dfpc.DFPId
  7399. LEFT JOIN Sys_Company sc on dfp.CompanyId = sc.Id
  7400. LEFT JOIN Sys_Users su on dfp.CreateUserId = su.Id
  7401. LEFT JOIN Sys_Department sd on su.DepId = sd.Id
  7402. LEFT JOIN Sys_SetData ss on dfp.PriceTypeId = ss.Id
  7403. LEFT JOIN Sys_SetDataType sst on ss.STid = sst.Id
  7404. WHERE
  7405. dfp.IsDel = 0
  7406. AND dfpc.IsDel = 0
  7407. AND dfp.CreateTime BETWEEN '{0}' AND '{1}'
  7408. -- AND dfp.IsPay = 1
  7409. ORDER BY
  7410. dfp.CompanyId,
  7411. su.DepId,
  7412. dfp.CreateUserId,
  7413. dfp.PriceTypeId,
  7414. dfp.CreateTime ASC", beginDt, endDt);
  7415. var dailyItems = await _sqlSugar.SqlQueryable<DailyInfo>(dailySql).ToArrayAsync();
  7416. view.GroupItems = groupItems.OrderBy(x => x.RowIndex).ToArray();
  7417. view.DailyItems = dailyItems;
  7418. return view;
  7419. }
  7420. /// <summary>
  7421. /// 企业利润
  7422. /// 团组费用条数统计
  7423. /// </summary>
  7424. /// <param name="groupIds"></param>
  7425. /// <returns></returns>
  7426. private async Task<CorporateProfitFeeCount[]> CorporateProfitFeeCount(int[] groupIds)
  7427. {
  7428. if (!groupIds.Any()) return Array.Empty<CorporateProfitFeeCount>();
  7429. //含未审核SQL
  7430. string sql = string.Format(@"SELECT
  7431. ROW_NUMBER() OVER(
  7432. ORDER BY
  7433. di.VisitDate Asc
  7434. ) AS 'RowIndex',
  7435. di.Id,
  7436. di.TeamName,
  7437. di.VisitDate,
  7438. (
  7439. SELECT
  7440. Count(1)
  7441. FROM
  7442. OA2023DB.dbo.Fin_ForeignReceivables ffr
  7443. WHERE
  7444. ffr.IsDel = 0
  7445. AND ffr.Diid = di.Id
  7446. ) 'ReceivableTotal',
  7447. (
  7448. SELECT
  7449. Count(1)
  7450. FROM
  7451. OA2023DB.dbo.Fin_ProceedsReceived fpr
  7452. WHERE
  7453. fpr.IsDel = 0
  7454. AND fpr.DIId = di.Id
  7455. ) 'ReceivedTotal',
  7456. (
  7457. SELECT
  7458. Count(1)
  7459. FROM
  7460. Fin_PaymentRefundAndOtherMoney prom
  7461. INNER JOIN Grp_CreditCardPayment ccp ON prom.Id = ccp.CId
  7462. AND prom.DiId = ccp.DIId
  7463. WHERE
  7464. prom.IsDel = 0
  7465. AND prom.PayType = 1
  7466. AND ccp.CTable = 285
  7467. --AND ccp.IsAuditGM = 1
  7468. AND ccp.IsAuditGM != 2
  7469. AND prom.DiId = di.Id
  7470. ) AS 'RefundedTotal',
  7471. (
  7472. SELECT
  7473. Count(1)
  7474. FROM
  7475. Grp_HotelReservations hr
  7476. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  7477. WHERE
  7478. hr.IsDel = 0
  7479. AND ccp.IsDel = 0
  7480. AND ccp.CTable = 76 -- AND (
  7481. -- ccp.IsAuditGM = 1
  7482. -- OR ccp.IsAuditGM = 3
  7483. -- )
  7484. AND ccp.IsAuditGM != 2
  7485. AND hr.DiId = di.Id
  7486. ) AS 'HotelTotal',
  7487. (
  7488. SELECT
  7489. Count(1)
  7490. FROM
  7491. Grp_CarTouristGuideGroundReservations ctggr
  7492. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  7493. AND ccp.CTable = 79
  7494. AND ctggr.Id = ccp.CId
  7495. WHERE
  7496. ctggr.IsDel = 0 -- AND (
  7497. -- ccp.IsAuditGM = 1
  7498. -- OR ccp.IsAuditGM = 3
  7499. -- )
  7500. AND ccp.IsAuditGM != 2
  7501. AND ctggr.DiId = di.Id
  7502. ) AS 'LocalGuideTotal',
  7503. (
  7504. SELECT
  7505. Count(1)
  7506. FROM
  7507. Grp_AirTicketReservations atr
  7508. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7509. AND ccp.CTable = 85
  7510. AND atr.Id = ccp.CId
  7511. WHERE
  7512. atr.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7513. AND ccp.IsAuditGM != 2
  7514. AND atr.DIId = di.Id
  7515. ) AS 'AirTicketToal',
  7516. (
  7517. SELECT
  7518. Count(1)
  7519. FROM
  7520. Grp_VisaInfo vi
  7521. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7522. AND ccp.CTable = 80
  7523. AND vi.Id = ccp.CId
  7524. WHERE
  7525. vi.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7526. AND ccp.IsAuditGM != 2
  7527. AND vi.DIId = di.Id
  7528. ) AS 'VisaTotal',
  7529. (
  7530. SELECT
  7531. Count(1)
  7532. FROM
  7533. Grp_InvitationOfficialActivities ioa
  7534. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7535. AND ccp.CTable = 81
  7536. AND ioa.Id = ccp.CId
  7537. WHERE
  7538. ioa.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7539. AND ccp.IsAuditGM != 2
  7540. AND ioa.DiId = di.Id
  7541. ) AS 'OATotal',
  7542. (
  7543. SELECT
  7544. Count(1)
  7545. FROM
  7546. Grp_Customers ic
  7547. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7548. AND ccp.CTable = 82
  7549. AND ic.Id = ccp.CId
  7550. WHERE
  7551. ic.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7552. AND ccp.IsAuditGM != 2
  7553. AND ic.DiId = di.Id
  7554. ) AS 'InsureTotal',
  7555. (
  7556. SELECT
  7557. Count(1)
  7558. FROM
  7559. Grp_DecreasePayments dp
  7560. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7561. AND ccp.CTable = 98
  7562. AND dp.Id = ccp.CId
  7563. WHERE
  7564. dp.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7565. AND ccp.IsAuditGM != 2
  7566. AND dp.Diid = di.Id
  7567. ) AS 'OtherTotal'
  7568. FROM
  7569. OA2023DB.dbo.Grp_DelegationInfo di
  7570. LEFT JOIN Sys_SetData ss ON di.TeamDid = ss.Id
  7571. WHERE
  7572. di.IsDel = 0
  7573. AND di.IsBid = 0
  7574. AND di.Id IN({0})", string.Join(",", groupIds));
  7575. return await _sqlSugar.SqlQueryable<CorporateProfitFeeCount>(sql).ToArrayAsync();
  7576. }
  7577. /// <summary>
  7578. /// 团组利润item详情
  7579. /// </summary>
  7580. /// <param name="type">
  7581. /// 1:详情
  7582. /// 2:excel 生成
  7583. /// </param>
  7584. /// <param name="begin"></param>
  7585. /// <param name="end"></param>
  7586. /// <returns></returns>
  7587. private async Task<CorporateProfitItemView> CorporateProfitItems(int type, string begin, string end)
  7588. {
  7589. var data = await CorporateProfitInfos(begin, end);
  7590. var groupItems = data.GroupItems;
  7591. var dailyItems = data.DailyItems;
  7592. var priceTypeIds = new List<int>() {
  7593. 686, // 686 信用卡还款
  7594. 687, // 687 张总私人费用
  7595. 688, // 688 代报销社保生育补贴
  7596. 688, // 688 代报销社保生育补贴
  7597. 306, // 306 人事行政费用-张总家用类
  7598. 325, // 325 会展部备用金
  7599. 689, // 689 团组签证保险
  7600. };
  7601. var companyDailyItems = dailyItems
  7602. .Where(x => !priceTypeIds.Contains(x.PriceTypeId))
  7603. .GroupBy(x => x.CompanyName)
  7604. .Select(g => new { CompanyName = g.Key, CNYTotal = g.Sum(x => x.CNYTotal) })
  7605. .OrderBy(x => x.CNYTotal)
  7606. .ToArray();
  7607. //业务类型
  7608. var groupTypeIds = new List<int>() {
  7609. 38, // 政府团
  7610. 39, // 企业团
  7611. 40, // 散客团
  7612. 1048 // 高校团
  7613. };
  7614. var inforTypeIds = new List<int>() {
  7615. 302, // 成都-会务活动
  7616. 691, // 四川-会务活动
  7617. 1539, // 纽茵-会务活动
  7618. 1548 // 重庆-会务活动
  7619. };
  7620. //团组 收款、成本、利润 合计
  7621. var groupCollectionTotal = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CollectionTotal);
  7622. var groupReceivableTotal = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableProfitTotal);
  7623. var groupCostTotal = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal);
  7624. var groupProfitTotal = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ProfitTotal);
  7625. //非团组 收款、成本、利润 合计
  7626. var notGroupCollectionTotal = groupItems.Where(x => !groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CollectionTotal);
  7627. var notGroupReceivableTotal = groupItems.Where(x => !groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableProfitTotal);
  7628. var notGroupCostTotal = groupItems.Where(x => !groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal);
  7629. var notGroupProfitTotal = groupItems.Where(x => !groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ProfitTotal);
  7630. //会务数量
  7631. int inforCount = groupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Count();
  7632. //服务人数
  7633. int serviceCount = groupItems.Sum(x => x.VisitPNumber);
  7634. //总利润
  7635. decimal totalProfit = groupProfitTotal + notGroupProfitTotal;
  7636. var dailyLabel = $"*不含日付费用类型(信用卡还款、张总私人费用、代报销社保生育补贴、人事行政费用 - 张总家用类、会展部备用金、团组签证保险)\r\n";
  7637. var dailyExcelLabel = dailyLabel;
  7638. if (companyDailyItems.Any())
  7639. {
  7640. foreach (var dailyFee in companyDailyItems)
  7641. {
  7642. dailyLabel += $"<p>[{dailyFee.CompanyName}]日常产生费用:{dailyFee.CNYTotal.ToString("#0.00")} CNY </p>";
  7643. dailyExcelLabel += $"[{dailyFee.CompanyName}]日常产生费用:{dailyFee.CNYTotal.ToString("#0.00")} CNY \r\n";
  7644. }
  7645. }
  7646. 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>");
  7647. var datas = _mapper.Map<CorporateProfitItem[]>(groupItems);
  7648. if (type == 2) //excel 下载
  7649. {
  7650. var designer = new WorkbookDesigner();
  7651. var tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/团组利润模板.xls";
  7652. designer.Workbook = new Workbook(tempPath);
  7653. designer.SetDataSource("ReceivablesTemp", datas);
  7654. designer.SetDataSource("ReceivableProfitTotal", groupReceivableTotal.ToString("#0.00"));
  7655. designer.SetDataSource("NotReceivableProfitTotal", notGroupReceivableTotal.ToString("#0.00"));
  7656. designer.SetDataSource("SumAccounts", groupCollectionTotal.ToString("#0.00"));
  7657. designer.SetDataSource("SumReceived", groupCostTotal.ToString("#0.00"));
  7658. designer.SetDataSource("SumBalance", groupProfitTotal.ToString("#0.00"));
  7659. designer.SetDataSource("notSumAccounts", notGroupCollectionTotal.ToString("#0.00"));
  7660. designer.SetDataSource("notSumReceived", notGroupCostTotal.ToString("#0.00"));
  7661. designer.SetDataSource("SumOfNotTeamBalance", notGroupProfitTotal.ToString("#0.00"));
  7662. designer.SetDataSource("DailyLabel", dailyExcelLabel);
  7663. designer.SetDataSource("MeetingNumber", inforCount + "个");
  7664. designer.SetDataSource("ServiceNumber", serviceCount + "人");
  7665. designer.SetDataSource("SumAllBalance", totalProfit.ToString("#0.00"));
  7666. //根据数据源处理生成报表内容
  7667. designer.Process();
  7668. string fileName = $"团组利润({Convert.ToDateTime(begin).ToString("yyyy年MM月dd日")}~{Convert.ToDateTime(end).ToString("yyyy年MM月dd日")}){Guid.NewGuid().ToString()}.xls";
  7669. designer.Workbook.Save($"{AppSettingsHelper.Get("ExcelBasePath")}CorporateProfit/{fileName}");
  7670. string url = $"{AppSettingsHelper.Get("ExcelBaseUrl")}Office/Excel/CorporateProfit/{fileName}";
  7671. label = url;
  7672. }
  7673. return new CorporateProfitItemView()
  7674. {
  7675. Items = datas,
  7676. Label = label
  7677. };
  7678. }
  7679. /// <summary>
  7680. /// 企业利润
  7681. /// Item
  7682. /// </summary>
  7683. /// <param name="dto"></param>
  7684. /// <returns></returns>
  7685. [HttpPost("CorporateProfitItem")]
  7686. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  7687. public async Task<IActionResult> CorporateProfitItem(CorporateProfitItemDto dto)
  7688. {
  7689. int portType = dto.PortType,
  7690. userId = dto.UserId,
  7691. pageId = dto.PageId;
  7692. #region 参数验证
  7693. //var validationRules = new CorporateProfitItemDtoFoalidator();
  7694. //var validResult = await validationRules.ValidateAsync(dto);
  7695. //if (!validResult.IsValid)
  7696. //{
  7697. // var errors = new StringBuilder();
  7698. // foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  7699. // return Ok(JsonView(false, errors.ToString()));
  7700. //}
  7701. //#region 页面操作权限验证
  7702. //var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(userId, pageId);
  7703. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限!"));
  7704. //#endregion
  7705. #endregion
  7706. string beginDt = $"{dto.BeginDt} 00:00:00",
  7707. endDt = $"{dto.EndDt} 23:59:59";
  7708. return Ok(JsonView(true, "操作成功!", await CorporateProfitItems(1, beginDt, endDt)));
  7709. }
  7710. /// <summary>
  7711. /// 企业利润 Excel导出
  7712. /// </summary>
  7713. /// <param name="dto"></param>
  7714. /// <returns></returns>
  7715. [HttpPost("CorporateProfitExcelDownload")]
  7716. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  7717. public async Task<IActionResult> CorporateProfitExcelDownload(CorporateProfitExcelDownloadDto dto)
  7718. {
  7719. int portType = dto.PortType,
  7720. userId = dto.UserId,
  7721. pageId = dto.PageId,
  7722. excelType = dto.ExcelType;
  7723. #region 参数验证
  7724. var validationRules = new CorporateProfitExcelDownloadDtoFoalidator();
  7725. var validResult = await validationRules.ValidateAsync(dto);
  7726. if (!validResult.IsValid)
  7727. {
  7728. var errors = new StringBuilder();
  7729. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  7730. return Ok(JsonView(false, errors.ToString()));
  7731. }
  7732. #region 页面操作权限验证
  7733. //var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(userId,pageId);
  7734. //if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权限!"));
  7735. #endregion
  7736. #endregion
  7737. // 基础转换:解析传入的起止时间
  7738. DateTime beginDate = DateTime.Parse(dto.BeginDt).Date; // 强制取 00:00:00
  7739. DateTime endDate = DateTime.Parse(dto.EndDt).Date.AddDays(1).AddSeconds(-1); // 强制取 23:59:59
  7740. // 本月:按照时间范围的【最大月份】起止时间
  7741. // 逻辑:以 endDate 为基准,计算它所在月份的第一天和最后一天
  7742. DateTime monthBase = endDate;
  7743. DateTime monthBegin = new DateTime(monthBase.Year, monthBase.Month, 1);
  7744. DateTime monthEnd = monthBegin.AddMonths(1).AddSeconds(-1); // 自动处理 28/30/31 天及跨年
  7745. //业务类型
  7746. var priceTypeIds = new List<int>() {
  7747. 686, //686 信用卡还款
  7748. 687, //687 张总私人费用
  7749. 688, //688 代报销社保生育补贴
  7750. 688, //688 代报销社保生育补贴
  7751. 306, //306 人事行政费用-张总家用类
  7752. 325, //325 会展部备用金
  7753. 689, //689 团组签证保险
  7754. };
  7755. var montData = await CorporateProfitInfos(monthBegin.ToString("yyyy-MM-dd HH:mm:ss"), monthEnd.ToString("yyyy-MM-dd HH:mm:ss"));
  7756. var monthGroupItems = montData.GroupItems;
  7757. var monthDailyItems = montData.DailyItems;
  7758. var yearData = await CorporateProfitInfos(beginDate.ToString("yyyy-MM-dd HH:mm:ss"), endDate.ToString("yyyy-MM-dd HH:mm:ss"));
  7759. var yearGroupItems = yearData.GroupItems;
  7760. var yearDailyItems = yearData.DailyItems;
  7761. //筛选不统计的费用类型
  7762. //if (yearDailyItems.Any()) yearDailyItems = yearDailyItems.Where(x => !priceTypeIds.Contains(x.PriceTypeId)).ToArray();
  7763. #region 公共参数
  7764. //团组收款、成本、利润 合计
  7765. decimal monthGroupCollectionTotal = monthGroupItems.Sum(x => x.CollectionTotal),
  7766. monthGroupCostTotal = monthGroupItems.Sum(x => x.CostTotal),
  7767. yearGroupCollectionTotal = yearGroupItems.Sum(x => x.CollectionTotal),
  7768. yearGroupCostTotal = yearGroupItems.Sum(x => x.CostTotal);
  7769. // 日付申请 48 人员费用、 49 办公费用、50 销售费用、51 其他费用、55 大运会、90 各部门基础固定费用明细
  7770. decimal monthStaffCosts = monthDailyItems.Where(x => x.PriceParentTypeId == 48).Sum(x => x.CNYTotal),
  7771. monthOfficeExpenses = monthDailyItems.Where(x => x.PriceParentTypeId == 49).Sum(x => x.CNYTotal),
  7772. monthCostSales = monthDailyItems.Where(x => x.PriceParentTypeId == 50).Sum(x => x.CNYTotal),
  7773. monthOtherFees = monthDailyItems.Where(x => x.PriceParentTypeId == 51).Sum(x => x.CNYTotal),
  7774. monthDyhFees = monthDailyItems.Where(x => x.PriceParentTypeId == 55).Sum(x => x.CNYTotal),
  7775. monthDepartFixedExpenses = monthDailyItems.Where(x => x.PriceParentTypeId == 90).Sum(x => x.CNYTotal),
  7776. yearStaffCosts = yearDailyItems.Where(x => x.PriceParentTypeId == 48).Sum(x => x.CNYTotal),
  7777. yearOfficeExpenses = yearDailyItems.Where(x => x.PriceParentTypeId == 49).Sum(x => x.CNYTotal),
  7778. yearCostSales = yearDailyItems.Where(x => x.PriceParentTypeId == 50).Sum(x => x.CNYTotal),
  7779. yearOtherFees = yearDailyItems.Where(x => x.PriceParentTypeId == 51).Sum(x => x.CNYTotal),
  7780. yearDyhFees = yearDailyItems.Where(x => x.PriceParentTypeId == 55).Sum(x => x.CNYTotal),
  7781. yearDepartFixedExpenses = yearDailyItems.Where(x => x.PriceParentTypeId == 90).Sum(x => x.CNYTotal);
  7782. #endregion
  7783. //月度报表、季度报表、年度报表
  7784. if (excelType == 1 || excelType == 2 || excelType == 3)
  7785. {
  7786. var designer = new WorkbookDesigner();
  7787. string fileName = $"({beginDate.ToString("yyyy年MM月dd日")}~{endDate.ToString("yyyy年MM月dd日")}){Guid.NewGuid().ToString()}.xls",
  7788. fileNamePrefix = string.Empty,
  7789. tempPath = string.Empty,
  7790. workSheetName = string.Empty;
  7791. if (excelType == 1)
  7792. {
  7793. tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/月度报表模板.xls";
  7794. workSheetName = "月度报表";
  7795. fileNamePrefix = "月度报表";
  7796. }
  7797. else if (excelType == 2)
  7798. {
  7799. tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/季度报表模板.xls";
  7800. workSheetName = "季度报表";
  7801. fileNamePrefix = "季度报表";
  7802. }
  7803. else if (excelType == 3)
  7804. {
  7805. tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/年度报表模板.xls";
  7806. workSheetName = "年度报表";
  7807. fileNamePrefix = "年度报表";
  7808. }
  7809. else return Ok(JsonView(false));
  7810. designer.Workbook = new Workbook(tempPath);
  7811. designer.Workbook.Worksheets[0].Name = workSheetName;
  7812. #region 填充值
  7813. string time = $"所属期间: {beginDate.ToString("yyyy 年 MM 月 dd 日")} 至 {endDate.ToString("yyyy 年 MM 月 dd 日")}";
  7814. designer.SetDataSource("Time", time);
  7815. designer.SetDataSource("MonthReceivedPrice", monthGroupCollectionTotal.ToString("#0.00"));//本月已收
  7816. designer.SetDataSource("YearReceivedPrice", yearGroupCollectionTotal.ToString("#0.00")); //本年已收
  7817. designer.SetDataSource("MonthSumReceives", monthGroupCollectionTotal.ToString("#0.00"));//本月团组收款
  7818. designer.SetDataSource("MonthTeamCost", monthGroupCostTotal.ToString("#0.00")); //本月团组成本
  7819. designer.SetDataSource("YearSumReceives", yearGroupCollectionTotal.ToString("#0.00"));//本年团组收款
  7820. designer.SetDataSource("YearTeamCost", yearGroupCostTotal.ToString("#0.00")); //本年团组成本
  7821. designer.SetDataSource("MonthStaffCosts", monthStaffCosts.ToString("#0.00"));//本月人员费用
  7822. designer.SetDataSource("YearStaffCosts", yearStaffCosts.ToString("#0.00")); //本年人员费用
  7823. designer.SetDataSource("MonthOfficeExpenses", monthOfficeExpenses.ToString("#0.00"));//本月办公费用
  7824. designer.SetDataSource("YearOfficeExpenses", yearOfficeExpenses.ToString("#0.00")); //本年办公费用
  7825. designer.SetDataSource("MonthCostSales", monthCostSales.ToString("#0.00"));//本月销售费用
  7826. designer.SetDataSource("YearCostSales", yearCostSales.ToString("#0.00")); //本年销售费用
  7827. designer.SetDataSource("MonthOtherFees", monthOtherFees.ToString("#0.00"));//本月其他费用
  7828. designer.SetDataSource("YearOtherFees", yearOtherFees.ToString("#0.00")); //本年其他费用
  7829. designer.SetDataSource("MonthDYHFees", monthDyhFees.ToString("#0.00"));//本月大运会费用
  7830. designer.SetDataSource("YearDYHFees", yearDyhFees.ToString("#0.00")); //本年大运会费用
  7831. designer.SetDataSource("MonthDepartFixedFees", monthDepartFixedExpenses.ToString("#0.00"));//本月各部门基础固定费用明细费用
  7832. designer.SetDataSource("YearDepartFixedFees", yearDepartFixedExpenses.ToString("#0.00")); //本年各部门基础固定费用明细费用
  7833. // 填表时间
  7834. string fillingTime = $"填报时间:{DateTime.Now.ToString("yyyy.MM.dd")}";
  7835. designer.SetDataSource("FillingTime", fillingTime);
  7836. #endregion
  7837. //根据数据源处理生成报表内容
  7838. designer.Process();
  7839. fileName = fileNamePrefix + fileName;
  7840. designer.Workbook.Save($"{AppSettingsHelper.Get("ExcelBasePath")}CorporateProfit/{fileName}");
  7841. string url = $"{AppSettingsHelper.Get("ExcelBaseUrl")}Office/Excel/CorporateProfit/{fileName}";
  7842. return Ok(JsonView(true, "操作成功!", url));
  7843. }
  7844. //利润报表
  7845. else if (excelType == 4)
  7846. {
  7847. var designer = new WorkbookDesigner();
  7848. var tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/利润报表New.xlsx";
  7849. designer.Workbook = new Workbook(tempPath);
  7850. #region 填充值
  7851. string time = $"所属期间: {beginDate.ToString("yyyy 年 MM 月 dd 日")} 至 {endDate.ToString("yyyy 年 MM 月 dd 日")}";
  7852. designer.SetDataSource("Time", time);
  7853. //业务类型
  7854. var groupTypeIds = new List<int>() {
  7855. 38, // 政府团
  7856. 39, // 企业团
  7857. 40, // 散客团
  7858. 1048 // 高校团
  7859. };
  7860. var inforTypeIds = new List<int>() {
  7861. 302, // 成都-会务活动
  7862. 691, // 四川-会务活动
  7863. 1539, // 纽茵-会务活动
  7864. 1548 // 重庆-会务活动
  7865. };
  7866. var competitionTypeIds = new List<int>() {
  7867. 762, // 四川-赛事项目收入
  7868. 1047, // 成都-赛事项目收入
  7869. };
  7870. var otherTypeIds = new List<int>();
  7871. otherTypeIds.AddRange(groupTypeIds);
  7872. otherTypeIds.AddRange(inforTypeIds);
  7873. otherTypeIds.AddRange(competitionTypeIds);
  7874. decimal monthAllIncomes = monthGroupItems.Sum(x => x.ReceivableAmount), //月-收入
  7875. monthTzIncomes = monthGroupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7876. monthHwIncomes = monthGroupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7877. monthSsIncomes = monthGroupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7878. monthQtIncomes = monthGroupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7879. monthAllCost = monthGroupItems.Sum(x => x.CostTotal), //月-成本
  7880. monthTzCost = monthGroupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7881. monthHwCost = monthGroupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7882. monthSsCost = monthGroupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7883. monthQtCost = monthGroupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7884. monthAllGross = monthAllIncomes - monthAllCost, //月-毛利金额
  7885. monthTzGross = monthTzIncomes - monthTzCost,
  7886. monthHwGross = monthHwIncomes - monthHwCost,
  7887. monthSsGross = monthSsIncomes - monthSsCost,
  7888. monthQtGross = monthQtIncomes - monthQtCost,
  7889. yearAllIncomes = yearGroupItems.Sum(x => x.ReceivableAmount), //年-收入
  7890. yearTzIncomes = yearGroupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7891. yearHwIncomes = yearGroupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7892. yearSsIncomes = yearGroupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7893. yearQtIncomes = yearGroupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7894. yearAllCost = yearGroupItems.Sum(x => x.CostTotal), //年-成本
  7895. yearTzCost = yearGroupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7896. yearHwCost = yearGroupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7897. yearSsCost = yearGroupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7898. yearQtCost = yearGroupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7899. yearAllGross = yearAllIncomes - yearAllCost, //年-毛利金额
  7900. yearTzGross = yearTzIncomes - yearTzCost,
  7901. yearHwGross = yearHwIncomes - yearHwCost,
  7902. yearSsGross = yearSsIncomes - yearSsCost,
  7903. yearQtGross = yearQtIncomes - yearQtCost;
  7904. //年-团数量
  7905. int yearAllCount = yearGroupItems.Length,
  7906. yearTzCount = yearGroupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Count(),
  7907. yearHwCount = yearGroupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Count(),
  7908. yearSsCount = yearGroupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Count(),
  7909. yearQtCount = yearGroupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Count();
  7910. //年-利率
  7911. string yearAllRate = "0.00 %",
  7912. yearTzRate = "0.00 %",
  7913. yearHwRate = "0.00 %",
  7914. yearSsRate = "0.00 %",
  7915. yearQtRate = "0.00 %";
  7916. if (yearAllIncomes != 0) yearAllRate = (yearAllGross / yearAllIncomes * 100).ToString("#0.00") + "%";
  7917. if (yearTzIncomes != 0) yearTzRate = (yearTzGross / yearTzIncomes * 100).ToString("#0.00") + "%";
  7918. if (yearHwIncomes != 0) yearHwRate = (yearHwGross / yearHwIncomes * 100).ToString("#0.00") + "%";
  7919. if (yearSsIncomes != 0) yearSsRate = (yearSsGross / yearSsIncomes * 100).ToString("#0.00") + "%";
  7920. if (yearQtIncomes != 0) yearQtRate = (yearQtGross / yearQtIncomes * 100).ToString("#0.00") + "%";
  7921. #region 月
  7922. //收入
  7923. designer.SetDataSource("MonthAllIncomes", monthAllIncomes.ToString("#0.00"));
  7924. designer.SetDataSource("MonthtzIncomes", monthTzIncomes.ToString("#0.00"));
  7925. designer.SetDataSource("MonthhwIncomes", monthHwIncomes.ToString("#0.00"));
  7926. designer.SetDataSource("MonthssIncomes", monthSsIncomes.ToString("#0.00"));
  7927. designer.SetDataSource("MonthqtIncomes", monthQtIncomes.ToString("#0.00"));
  7928. //成本
  7929. designer.SetDataSource("MonthAllCost", monthAllCost.ToString("#0.00"));
  7930. designer.SetDataSource("MonthtzCost", monthTzCost.ToString("#0.00"));
  7931. designer.SetDataSource("MonthhwCost", monthHwCost.ToString("#0.00"));
  7932. designer.SetDataSource("MonthssCost", monthSsCost.ToString("#0.00"));
  7933. designer.SetDataSource("MonthqtCost", monthQtCost.ToString("#0.00"));
  7934. //毛利金额
  7935. designer.SetDataSource("MonthAllGross", monthAllGross.ToString("#0.00"));
  7936. designer.SetDataSource("MonthtzGross", monthTzGross.ToString("#0.00"));
  7937. designer.SetDataSource("MonthhwGross", monthHwGross.ToString("#0.00"));
  7938. designer.SetDataSource("MonthssGross", monthSsGross.ToString("#0.00"));
  7939. designer.SetDataSource("MonthqtGross", monthQtGross.ToString("#0.00"));
  7940. #endregion
  7941. #region 年
  7942. //收入
  7943. designer.SetDataSource("YearAllIncomes", yearAllIncomes.ToString("#0.00"));
  7944. designer.SetDataSource("YeartzIncomes", yearTzIncomes.ToString("#0.00"));
  7945. designer.SetDataSource("YearhwIncomes", yearHwIncomes.ToString("#0.00"));
  7946. designer.SetDataSource("YearssIncomes", yearSsIncomes.ToString("#0.00"));
  7947. designer.SetDataSource("YearqtIncomes", yearQtIncomes.ToString("#0.00"));
  7948. //成本
  7949. designer.SetDataSource("YearAllCost", yearAllCost.ToString("#0.00"));
  7950. designer.SetDataSource("YeartzCost", yearTzCost.ToString("#0.00"));
  7951. designer.SetDataSource("YearhwCost", yearHwCost.ToString("#0.00"));
  7952. designer.SetDataSource("YearssCost", yearSsCost.ToString("#0.00"));
  7953. designer.SetDataSource("YearqtCost", yearQtCost.ToString("#0.00"));
  7954. //毛利金额
  7955. designer.SetDataSource("YearAllGross", yearAllGross.ToString("#0.00"));
  7956. designer.SetDataSource("YeartzGross", yearTzGross.ToString("#0.00"));
  7957. designer.SetDataSource("YearhwGross", yearHwGross.ToString("#0.00"));
  7958. designer.SetDataSource("YearssGross", yearSsGross.ToString("#0.00"));
  7959. designer.SetDataSource("YearqtGross", yearQtGross.ToString("#0.00"));
  7960. //毛利率
  7961. designer.SetDataSource("YearAllRate", yearAllRate);
  7962. designer.SetDataSource("YeartzRate", yearTzRate);
  7963. designer.SetDataSource("YearhwRate", yearHwRate);
  7964. designer.SetDataSource("YearssRate", yearSsRate);
  7965. designer.SetDataSource("YearqtRate", yearQtRate);
  7966. //数量
  7967. designer.SetDataSource("AllCount", yearAllCount.ToString());
  7968. designer.SetDataSource("tzCount", yearTzCount.ToString());
  7969. designer.SetDataSource("hwCount", yearHwCount.ToString());
  7970. designer.SetDataSource("ssCount", yearSsCount.ToString());
  7971. designer.SetDataSource("qtCount", yearQtCount.ToString());
  7972. #endregion
  7973. #region 日付相关
  7974. var dailyViewItems = new List<CorporateProfitDailyView>();
  7975. var dailyTypes = await _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0).ToListAsync();
  7976. var conmmentTexts = new List<CorporateProfitDailyCommentView>();
  7977. #region 员工费用 48
  7978. decimal monthStaffCostTotal = monthDailyItems.Where(x => x.PriceParentTypeId == 48).Sum(x => x.ItemTotal),
  7979. yearStaffCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 48).Sum(x => x.ItemTotal);
  7980. dailyViewItems.Add(new CorporateProfitDailyView() { No = "一", PriceName = "人员费用", ThisMonthAmount = monthStaffCostTotal, ThisYearAmount = yearStaffCostTotal });
  7981. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  7982. {
  7983. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceParentTypeId == 48).ToArray()),
  7984. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 48).ToArray())
  7985. });
  7986. var dailyStaffTypes = dailyTypes.Where(x => x.STid == 48).OrderBy(x => x.Id).ToList();
  7987. foreach (var item in dailyStaffTypes)
  7988. {
  7989. string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
  7990. decimal monthAmount = monthDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  7991. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  7992. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  7993. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  7994. {
  7995. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  7996. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  7997. });
  7998. }
  7999. #endregion
  8000. #region 办公费用
  8001. decimal monthWorkCostTotal = monthDailyItems.Where(x => x.PriceParentTypeId == 49).Sum(x => x.ItemTotal), //总费用
  8002. yearWorkCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 49).Sum(x => x.ItemTotal);
  8003. dailyViewItems.Add(new CorporateProfitDailyView() { No = "二", PriceName = "办公费用", ThisMonthAmount = monthWorkCostTotal, ThisYearAmount = yearWorkCostTotal });
  8004. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8005. {
  8006. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceParentTypeId == 49).ToArray()),
  8007. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 49).ToArray())
  8008. });
  8009. var dailyWorkTypes = dailyTypes.Where(x => x.STid == 49).OrderBy(x => x.Id).ToList();
  8010. foreach (var item in dailyWorkTypes)
  8011. {
  8012. string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
  8013. decimal monthAmount = monthDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  8014. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  8015. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  8016. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8017. {
  8018. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  8019. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  8020. });
  8021. }
  8022. #endregion
  8023. #region 销售费用
  8024. decimal monthSalesCostTotal = monthDailyItems.Where(x => x.PriceParentTypeId == 50).Sum(x => x.ItemTotal), //总费用
  8025. yearSalesCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 50).Sum(x => x.ItemTotal);
  8026. dailyViewItems.Add(new CorporateProfitDailyView() { No = "三", PriceName = "销售费用", ThisMonthAmount = monthSalesCostTotal, ThisYearAmount = yearSalesCostTotal });
  8027. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8028. {
  8029. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceParentTypeId == 50).ToArray()),
  8030. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 50).ToArray())
  8031. });
  8032. var dailySalesTypes = dailyTypes.Where(x => x.STid == 50).OrderBy(x => x.Id).ToList();
  8033. foreach (var item in dailySalesTypes)
  8034. {
  8035. string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
  8036. decimal monthAmount = monthDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  8037. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  8038. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  8039. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8040. {
  8041. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  8042. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  8043. });
  8044. }
  8045. #endregion
  8046. #region 51 其他费用
  8047. decimal monthOtherCostTotal = monthDailyItems.Where(x => x.PriceParentTypeId == 51).Sum(x => x.ItemTotal), //总费用
  8048. yearOtherCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 51).Sum(x => x.ItemTotal);
  8049. dailyViewItems.Add(new CorporateProfitDailyView() { No = "四", PriceName = "其他费用", ThisMonthAmount = monthOtherCostTotal, ThisYearAmount = yearOtherCostTotal });
  8050. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8051. {
  8052. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceParentTypeId == 51).ToArray()),
  8053. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 51).ToArray())
  8054. });
  8055. var dailyOtherTypes = dailyTypes.Where(x => x.STid == 51).OrderBy(x => x.Id).ToList();
  8056. foreach (var item in dailyOtherTypes)
  8057. {
  8058. string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
  8059. decimal monthAmount = monthDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  8060. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  8061. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  8062. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8063. {
  8064. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  8065. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  8066. });
  8067. }
  8068. #endregion
  8069. #region 55 大运会
  8070. decimal monthDyhCostTotal = monthDailyItems.Where(x => x.PriceParentTypeId == 55).Sum(x => x.ItemTotal), //总费用
  8071. yearDyhCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 55).Sum(x => x.ItemTotal);
  8072. dailyViewItems.Add(new CorporateProfitDailyView() { No = "五", PriceName = "大运会", ThisMonthAmount = monthDyhCostTotal, ThisYearAmount = yearDyhCostTotal });
  8073. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8074. {
  8075. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceParentTypeId == 55).ToArray()),
  8076. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 55).ToArray())
  8077. });
  8078. var dailyDyhTypes = dailyTypes.Where(x => x.STid == 55).OrderBy(x => x.Id).ToList();
  8079. foreach (var item in dailyDyhTypes)
  8080. {
  8081. string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
  8082. decimal monthAmount = monthDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  8083. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  8084. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  8085. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8086. {
  8087. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  8088. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  8089. });
  8090. }
  8091. #endregion
  8092. #region 90 各部门基础固定费用明细
  8093. decimal monthBasicCostTotal = monthDailyItems.Where(x => x.PriceParentTypeId == 90).Sum(x => x.ItemTotal), //总费用
  8094. yearBasicCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 90).Sum(x => x.ItemTotal);
  8095. dailyViewItems.Add(new CorporateProfitDailyView() { No = "六", PriceName = "各部门基础固定费用明细", ThisMonthAmount = monthBasicCostTotal, ThisYearAmount = yearBasicCostTotal });
  8096. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8097. {
  8098. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceParentTypeId == 90).ToArray()),
  8099. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 90).ToArray())
  8100. });
  8101. var dailyBasicTypes = dailyTypes.Where(x => x.STid == 90).OrderBy(x => x.Id).ToList();
  8102. foreach (var item in dailyBasicTypes)
  8103. {
  8104. string priceName = item.Name;
  8105. decimal monthAmount = monthDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  8106. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  8107. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  8108. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8109. {
  8110. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  8111. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  8112. });
  8113. }
  8114. #endregion
  8115. // 办公费用
  8116. // 月
  8117. decimal officePirceMonth = monthStaffCostTotal + monthWorkCostTotal + monthSalesCostTotal + monthOtherCostTotal + monthDyhCostTotal + monthBasicCostTotal;
  8118. designer.SetDataSource("officePirceMonth", officePirceMonth.ToString("#0.00"));
  8119. // 年
  8120. decimal officePirceYear = yearStaffCostTotal + yearWorkCostTotal + yearSalesCostTotal + yearOtherCostTotal + yearDyhCostTotal + yearBasicCostTotal;
  8121. designer.SetDataSource("officePirceYear", officePirceYear.ToString("#0.00"));
  8122. //designer.SetDataSource("DailyView", dailyViewItems);
  8123. var dt = CommonFun.ToDataTableArray(dailyViewItems);
  8124. dt.TableName = "DailyView";
  8125. designer.SetDataSource(dt);
  8126. #endregion
  8127. #endregion
  8128. //根据数据源处理生成报表内容
  8129. designer.Process();
  8130. var dailySheet = designer.Workbook.Worksheets[1];
  8131. //渲染批注
  8132. for (int i = 0; i < dailyViewItems.Count; i++)
  8133. {
  8134. string monthComment = $"C{i + 3}",
  8135. yearComment = $"D{i + 3}";
  8136. int monthCommentIndex = dailySheet.Comments.Add(monthComment),
  8137. yearCommentIndex = dailySheet.Comments.Add(yearComment);
  8138. if (dailyViewItems[i].ThisMonthAmount != 0.00M)
  8139. {
  8140. string commentText1 = conmmentTexts[i].MonthComment;
  8141. Aspose.Cells.Comment comment = dailySheet.Comments[monthCommentIndex];
  8142. comment.Note = commentText1;
  8143. comment.Width = 400;
  8144. comment.Height = 400;
  8145. comment.Font.Color = Color.Red;
  8146. }
  8147. if (dailyViewItems[i].ThisYearAmount != 0.00M)
  8148. {
  8149. string commentText2 = conmmentTexts[i].YearComment;
  8150. Aspose.Cells.Comment comment = dailySheet.Comments[yearCommentIndex];
  8151. comment.Note = commentText2;
  8152. comment.Width = 400;
  8153. comment.Height = 400;
  8154. comment.Font.Color = Color.Red;
  8155. }
  8156. }
  8157. string fileName = $"利润报表({beginDate.ToString("yyyy年MM月dd日")}~{endDate.ToString("yyyy年MM月dd日")}){Guid.NewGuid().ToString()}.xls";
  8158. designer.Workbook.Save($"{AppSettingsHelper.Get("ExcelBasePath")}CorporateProfit/{fileName}");
  8159. string url = $"{AppSettingsHelper.Get("ExcelBaseUrl")}Office/Excel/CorporateProfit/{fileName}";
  8160. return Ok(JsonView(true, "操作成功!", url));
  8161. }
  8162. else if (excelType == 5)
  8163. {
  8164. var view = await CorporateProfitItems(2, beginDate.ToString("yyyy-MM-dd HH:mm:ss"), endDate.ToString("yyyy-MM-dd HH:mm:ss"));
  8165. return Ok(JsonView(true, "操作成功!", view.Label));
  8166. }
  8167. return Ok(JsonView(false));
  8168. }
  8169. private static string DailyListToString(DailyInfo[] infos)
  8170. {
  8171. StringBuilder sb = new StringBuilder();
  8172. int index = 1;
  8173. foreach (var info in infos)
  8174. {
  8175. sb.Append(index + "、");
  8176. sb.Append($"[{info.ItemTotal.ToString("#0.00")}]:{info.PriceName};");
  8177. sb.Append(Environment.NewLine);
  8178. index++;
  8179. }
  8180. return sb.ToString();
  8181. }
  8182. #endregion
  8183. }
  8184. }