StatisticsController.cs 444 KB

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