StatisticsController.cs 429 KB

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