StatisticsController.cs 408 KB

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