StatisticsController.cs 310 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537
  1. using Aspose.Cells;
  2. using Aspose.Words.Tables;
  3. using EyeSoft.Collections.Generic;
  4. using Google.Protobuf.WellKnownTypes;
  5. using Microsoft.AspNetCore.Mvc.ViewEngines;
  6. using Microsoft.EntityFrameworkCore.Metadata.Internal;
  7. using MySqlX.XDevAPI.Relational;
  8. using NetUV.Core.Handles;
  9. using NodaTime;
  10. using NPOI.POIFS.Properties;
  11. using NPOI.SS.Formula.Functions;
  12. using NPOI.SS.Formula.PTG;
  13. using OASystem.API.OAMethodLib;
  14. using OASystem.API.OAMethodLib.JuHeAPI;
  15. using OASystem.Domain.AesEncryption;
  16. using OASystem.Domain.Dtos.Statistics;
  17. using OASystem.Domain.Entities.Customer;
  18. using OASystem.Domain.Entities.Financial;
  19. using OASystem.Domain.Entities.Groups;
  20. using OASystem.Domain.ViewModels.Financial;
  21. using OASystem.Domain.ViewModels.JuHeExchangeRate;
  22. using OASystem.Domain.ViewModels.QiYeWeChat;
  23. using OASystem.Domain.ViewModels.Statistics;
  24. using OASystem.Infrastructure.Repositories.Groups;
  25. using System;
  26. using System.Data;
  27. using TencentCloud.Ocr.V20181119.Models;
  28. using static OASystem.API.OAMethodLib.GeneralMethod;
  29. using TypeInfo = OASystem.Domain.ViewModels.Statistics.TypeInfo;
  30. namespace OASystem.API.Controllers
  31. {
  32. /// <summary>
  33. /// 统计模块
  34. /// </summary>
  35. [Route("api/[controller]")]
  36. [ApiController]
  37. public class StatisticsController : ControllerBase
  38. {
  39. private readonly int _decimalPlaces;
  40. private readonly IConfiguration _config;
  41. private readonly IMapper _mapper;
  42. private readonly SqlSugarClient _sqlSugar;
  43. private readonly DelegationInfoRepository _groupRep;
  44. private readonly SetDataRepository _setDataRep;
  45. private readonly TeamRateRepository _teamRateRep;
  46. private readonly VisitingClientsRepository _visitingClientsRep;
  47. private readonly IJuHeApiService _juHeApiService;
  48. /// <summary>
  49. /// Init
  50. /// </summary>
  51. /// <param name="mapper"></param>
  52. /// <param name="config"></param>
  53. /// <param name="sqlSugar"></param>
  54. /// <param name="groupRep"></param>
  55. /// <param name="setDataRep"></param>
  56. /// <param name="teamRate"></param>
  57. /// <param name="visitingClientsRep"></param>
  58. /// <param name="juHeApiService"></param>
  59. public StatisticsController(
  60. IMapper mapper,
  61. IConfiguration config,
  62. SqlSugarClient sqlSugar,
  63. DelegationInfoRepository groupRep,
  64. SetDataRepository setDataRep,
  65. TeamRateRepository teamRate,
  66. VisitingClientsRepository visitingClientsRep,
  67. IJuHeApiService juHeApiService
  68. )
  69. {
  70. _mapper = mapper;
  71. _config = config;
  72. _groupRep = groupRep;
  73. _setDataRep = setDataRep;
  74. _sqlSugar = sqlSugar;
  75. _teamRateRep = teamRate;
  76. _visitingClientsRep = visitingClientsRep;
  77. _juHeApiService = juHeApiService;
  78. }
  79. #region 团组报表
  80. /// <summary>
  81. /// 团组报表
  82. /// Items
  83. /// </summary>
  84. /// <param name="_dto">团组列表请求dto</param>
  85. /// <returns></returns>
  86. [HttpPost("PostGroupStatementItems")]
  87. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  88. public async Task<IActionResult> PostGroupStatementItems(GroupStatementItemsDto _dto)
  89. {
  90. #region 参数验证
  91. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  92. if (_dto.PageId < 1) return Ok(JsonView(false, "页面Id为空"));
  93. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  94. #region 页面操作权限验证
  95. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  96. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  97. #endregion
  98. #endregion
  99. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  100. {
  101. string sqlWhere = string.Empty;
  102. if (_dto.IsSure == 0) //未完成
  103. {
  104. sqlWhere += string.Format(@" And IsSure = 0");
  105. }
  106. else if (_dto.IsSure == 1) //已完成
  107. {
  108. sqlWhere += string.Format(@" And IsSure = 1");
  109. }
  110. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  111. {
  112. string tj = _dto.SearchCriteria;
  113. 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}%')",
  114. tj, tj, tj, tj, tj);
  115. }
  116. string sql = string.Format(@"Select row_number() over(order by gdi.VisitDate Desc) as Row_Number,
  117. gdi.Id,TourCode,ssd1.Id TeamLevId,ssd1.Name TeamLev,TeamName,
  118. ClientName,ClientUnit,VisitDate,ssd.Id TeamTypeId, ssd.Name TeamType,
  119. VisitDays,VisitPNumber,su.CnName JietuanOperator,IsSure,gdi.CreateTime,
  120. pr.LastCollectionTime
  121. From Grp_DelegationInfo gdi
  122. Left Join Sys_SetData ssd On gdi.TeamDid = ssd.Id
  123. Left Join Sys_SetData ssd1 On gdi.TeamLevSId = ssd1.Id
  124. Left Join Sys_Users su On gdi.JietuanOperator = su.Id
  125. Left Join (
  126. SELECT Diid, MAX(CreateTime) LastCollectionTime
  127. FROM Fin_ProceedsReceived
  128. Where IsDel = 0
  129. GROUP BY Diid
  130. ) pr On gdi.Id = pr.Diid
  131. Where gdi.IsDel = 0 {0} ", sqlWhere);
  132. RefAsync<int> total = 0;//REF和OUT不支持异步,想要真的异步这是最优解
  133. var _DelegationList = await _sqlSugar.SqlQueryable<GroupStatementItemView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);//ToPageAsync
  134. var _view = new
  135. {
  136. PageFuncAuth = pageFunAuthView,
  137. Data = _DelegationList
  138. };
  139. return Ok(JsonView(true, "查询成功!", _view, total));
  140. }
  141. else
  142. {
  143. return Ok(JsonView(false, "查询失败"));
  144. }
  145. }
  146. /// <summary>
  147. /// 团组报表
  148. /// Details
  149. /// </summary>
  150. /// <param name="_dto">团组列表请求dto</param>
  151. /// <returns></returns>
  152. [HttpPost("PostGroupStatementDetails")]
  153. //[JsonConverter(typeof(DecimalConverter), 2)]
  154. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  155. public async Task<IActionResult> PostGroupStatementDetails(GroupStatementDetailsDto _dto)
  156. {
  157. /*
  158. * 团组报表计算方式
  159. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  160. * 应收金额 = 应收表.Sum()
  161. * 已收金额 = 已收表.Sum()
  162. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  163. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  164. *
  165. */
  166. #region 参数验证
  167. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  168. if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  169. if (_dto.DiId < 1) return Ok(JsonView(false, "团组Id为空"));
  170. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  171. #region 页面操作权限验证
  172. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  173. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  174. #endregion
  175. #endregion
  176. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  177. {
  178. GroupStatementDetailsView _view = new GroupStatementDetailsView();
  179. #region 费用类型 币种,转账,客户信息
  180. List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  181. var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>()
  182. .Where(it => it.IsDel == 0)
  183. .Select(x => new Crm_DeleClient { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, Sex = x.Sex })
  184. .ToListAsync();
  185. foreach (var item in _clientDatas) EncryptionProcessor.DecryptProperties(item);
  186. var groupInfo = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => x.Id == _dto.DiId).FirstAsync();
  187. var visitDate = groupInfo.VisitDate;
  188. #endregion
  189. #region 团组收入
  190. GroupIncomeView _giView = new GroupIncomeView();
  191. /*
  192. * 应收报表
  193. * 增加方式=实际报价时 费用必须审核才能进入团组报表
  194. */
  195. decimal frTotalAmount = 0.00M;//应收总金额
  196. 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,
  197. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  198. From Fin_ForeignReceivables fr
  199. Left Join Sys_SetData sd On fr.Currency = sd.Id
  200. Left Join Sys_Users u On fr.Auditor = u.Id
  201. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
  202. List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  203. //List<Gsd_ForeignReceivablesView> _frViews = new List<Gsd_ForeignReceivablesView>();
  204. //if (_frViews1.Count > 0)
  205. //{
  206. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay != 2).ToList());
  207. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay == 2 && x.Status == 1).ToList());
  208. //}
  209. _frViews.ForEach(x =>
  210. {
  211. string namePrefix = string.Empty;
  212. if (x.AddingWay == 0) namePrefix = $"账单模块-";
  213. else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
  214. else if (x.AddingWay == 2) namePrefix = $"实际报价-";
  215. x.PriceName = $"{namePrefix}{x.PriceName}";
  216. });
  217. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  218. _giView.Receivables = _frViews;
  219. _giView.ReceivableStr = string.Format(@"应收款合计:{0} CNY(人民币)", frTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  220. /*
  221. * 已收报表
  222. */
  223. decimal prTotalAmount = 0.00M;//已收总金额
  224. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  225. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  226. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  227. From Fin_ProceedsReceived pr
  228. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  229. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  230. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
  231. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  232. prTotalAmount = _prViews.Sum(it => it.Price);
  233. _giView.ProceedsReceivedViews = _prViews;
  234. _giView.ProceedsReceivedStr = string.Format(@$"应收合计:{frTotalAmount:#0.00} CNY 已收款合计:{prTotalAmount.ConvertToDecimal1():#0.00} CNY");
  235. /*
  236. * 超支费用
  237. */
  238. decimal exTotalAmount = 0.00M;
  239. // 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,
  240. // (gec.PriceSum * gec.Coefficient * ccp.DayRate) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  241. // sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  242. //From OA2023DB.dbo.Fin_GroupExtraCost gec
  243. //Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  244. // Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  245. // Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  246. // Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  247. // Left Join Sys_Users u On ccp.CreateUserId = u.Id
  248. //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 " : " ");
  249. // List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(ecSql).ToListAsync();
  250. // #region 超支费用 - 模拟数据
  251. // //if (_ExtraCostsViews.Count < 1)
  252. // //{
  253. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  254. // // {
  255. // // GECId = 0,
  256. // // GECDiId = 2334,
  257. // // PriceName = "模拟数据-超支费用名称",
  258. // // PayMoney = 1000.00M,
  259. // // PaymentCurrency = "CNY",
  260. // // DayRate = 1.0000M,
  261. // // CNYPrice = 1000.00M,
  262. // // Payee = "模拟数据-超支费用收款方",
  263. // // OrbitalPrivateTransfer = 1,
  264. // // PayWay = "刷卡",
  265. // // CardType = "招行卡",
  266. // // IsPay = 1,
  267. // // Applicant = "刘华举"
  268. // // });
  269. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  270. // // {
  271. // // GECId = 0,
  272. // // GECDiId = 2334,
  273. // // PriceName = "模拟数据-超支费用名称",
  274. // // PayMoney = 1000.00M,
  275. // // PaymentCurrency = "CNY",
  276. // // DayRate = 1.0000M,
  277. // // CNYPrice = 1000.00M,
  278. // // Payee = "模拟数据-超支费用收款方",
  279. // // OrbitalPrivateTransfer = 1,
  280. // // PayWay = "刷卡",
  281. // // CardType = "招行卡",
  282. // // IsPay = 1,
  283. // // Applicant = "刘华举"
  284. // // });
  285. // //}
  286. // #endregion
  287. // exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  288. // _giView.ExtraCostsViews = _ExtraCostsViews;
  289. // _giView.ExtraCostsStr = string.Format(@"人民币总费用:{0} CNY", exTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  290. /*
  291. * 收款退还
  292. */
  293. decimal promTotalAmount = 0.00M;// 收款退还总金额
  294. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  295. //删除了 And prom.PriceType = 1
  296. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  297. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  298. prom.PayType As PrPayType,prom.PriceType As PrPriceType,
  299. ccp.RMBPrice * ccp.DayRate As RMBPrice,ccp.*,prom.CreateTime As PrCreateTime
  300. From Fin_PaymentRefundAndOtherMoney prom
  301. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  302. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  303. Where prom.IsDel = 0
  304. And prom.PayType = 1
  305. And ccp.CTable = 285
  306. {1}
  307. And prom.DiId = {0} Order By PrCreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  308. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  309. foreach (var ropItem in _promDatas)
  310. {
  311. string thisCueencyCode = "Unknown";
  312. string thisCueencyName = "Unknown";
  313. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  314. if (currency != null)
  315. {
  316. thisCueencyCode = currency.Name;
  317. thisCueencyName = currency.Remark;
  318. }
  319. string orbitalPrivateTransferStr = "Unknown";
  320. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  321. if (orbitalPrivateTransfer != null)
  322. {
  323. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  324. }
  325. string payStr = "Unknown";
  326. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  327. if (pay != null)
  328. {
  329. payStr = pay.Name;
  330. }
  331. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  332. {
  333. Id = ropItem.Id,
  334. DiId = ropItem.DIId,
  335. PriceName = ropItem.PrPriceName,
  336. PayCurrencyCode = thisCueencyCode,
  337. PayCurrencyName = thisCueencyName,
  338. Price = ropItem.PrPrice,
  339. CNYPrice = ropItem.PayMoney * ropItem.DayRate,
  340. ThisRate = ropItem.DayRate,
  341. Payee = ropItem.Payee,
  342. PayTime = ropItem.AuditGMDate,
  343. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  344. PayType = payStr,
  345. IsPay = ropItem.IsPay,
  346. Applicant = ropItem.Appliction
  347. };
  348. _promView.Add(gsd_PaymentRefund);
  349. }
  350. #region 收款退还 - 模拟数据
  351. //if (_promView.Count < 1)
  352. //{
  353. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  354. // {
  355. // Id = 0,
  356. // DiId = 2334,
  357. // PriceName = "模拟数据-费用名称",
  358. // PayCurrencyCode = "CNY",
  359. // PayCurrencyName = "人民币",
  360. // Price = 1000.00M,
  361. // CNYPrice = 1000.00M,
  362. // ThisRate = 1.00M,
  363. // Payee = "模拟数据-收款方",
  364. // PayTime = "2023-01-01 15:20:01",
  365. // OrbitalPrivateTransfer = 1,
  366. // PayType = "刷卡",
  367. // IsPay = 1,
  368. // Applicant = "刘华举"
  369. // });
  370. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  371. // {
  372. // Id = 0,
  373. // DiId = 2334,
  374. // PriceName = "模拟数据-费用名称",
  375. // PayCurrencyCode = "CNY",
  376. // PayCurrencyName = "人民币",
  377. // Price = 1000.00M,
  378. // CNYPrice = 1000.00M,
  379. // ThisRate = 1.00M,
  380. // Payee = "模拟数据-收款方",
  381. // PayTime = "2023-01-01 15:20:01",
  382. // OrbitalPrivateTransfer = 1,
  383. // PayType = "刷卡",
  384. // IsPay = 1,
  385. // Applicant = "刘华举"
  386. // });
  387. //}
  388. #endregion
  389. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  390. _giView.PaymentRefundAndOtherMoneyViews = _promView;
  391. _giView.PaymentRefundAndOtherMoneyStr = string.Format(@"人民币总费用:{0} CNY", promTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  392. decimal BalancePayment = frTotalAmount - prTotalAmount + promTotalAmount;
  393. _view.GroupIncome = _giView;
  394. _view.GroupIncomeStr = string.Format(@"<span style='color:red;'>剩余尾款:{0} CNY(包含了收款退还费用数据)</span>", BalancePayment.ConvertToDecimal1().ToString("#0.00"));
  395. #endregion
  396. #region 团组支出
  397. GroupExpenditureView _geView = new GroupExpenditureView();
  398. #region 酒店预定费用
  399. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  400. //ccp.RMBPrice As CNYPrice
  401. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  402. string hotelFeeSql = string.Format(@"
  403. SELECT
  404. hr.Id AS HrId,
  405. hr.DiId AS HrDiId,
  406. hr.City,
  407. hr.HotelName,
  408. hr.CheckInDate,
  409. hr.CheckOutDate,
  410. hr.CardPrice AS RoomPrice,
  411. sd1.Name AS PaymentCurrency,
  412. hr.SingleRoomPrice,
  413. hr.SingleRoomCount,
  414. hr.DoubleRoomPrice,
  415. hr.DoubleRoomCount,
  416. hr.SuiteRoomPrice,
  417. hr.SuiteRoomCount,
  418. hr.OtherRoomPrice,
  419. hr.OtherRoomCount,
  420. hr.BreakfastPrice,
  421. sd4.Name AS BreakfastCurrency,
  422. hr.Isoppay,
  423. hr.GovernmentRent,
  424. sd5.Name AS GovernmentRentCurrency,
  425. hr.CityTax,
  426. sd6.Name AS CityTaxCurrency,
  427. ccp.PayMoney,
  428. (
  429. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  430. ) AS CNYPrice,
  431. ccp.PayPercentage,
  432. ccp.DayRate,
  433. ccp.Payee,
  434. ccp.OrbitalPrivateTransfer,
  435. sd2.Name AS PayWay,
  436. sd3.Name AS CardType,
  437. ccp.IsPay,
  438. u.CnName AS Applicant
  439. FROM
  440. Grp_HotelReservations hr
  441. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  442. LEFT JOIN Sys_SetData sd1 ON ccp.PaymentCurrency = sd1.Id
  443. LEFT JOIN Sys_SetData sd2 ON ccp.PayDId = sd2.Id
  444. LEFT JOIN Sys_SetData sd3 ON ccp.CTDId = sd3.Id
  445. LEFT JOIN Sys_Users u ON ccp.CreateUserId = u.Id
  446. LEFT JOIN Sys_SetData sd4 ON hr.BreakfastCurrency = sd4.Id
  447. LEFT JOIN Sys_SetData sd5 ON hr.GovernmentRentCurrency = sd5.Id
  448. LEFT JOIN Sys_SetData sd6 ON hr.CityTaxCurrency = sd6.Id
  449. WHERE
  450. hr.IsDel = 0
  451. AND ccp.IsDel = 0
  452. AND ccp.CTable = 76 {1}
  453. AND ccp.PayMoney <> 0
  454. AND hr.DiId = {0}
  455. ORDER BY
  456. CheckInDate Asc", _dto.DiId, _dto.isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  457. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  458. List<int> hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
  459. var groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
  460. decimal HotelCNYTotalPrice = 0.00M;
  461. var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
  462. foreach (var item in groupHotelFeeViews)
  463. {
  464. if (groupHotelContentFeeViews.Count > 0)
  465. {
  466. string paymentStr = string.Empty;
  467. var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
  468. item.RoomPrice = roomData?.Price ?? 0.00M;
  469. if (item.RoomPrice != 0)
  470. {
  471. if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
  472. item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
  473. string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  474. string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
  475. item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
  476. 收款方:{roomData?.Payee}<br/>
  477. 费用标识:{feeMark1} <br/>
  478. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  479. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
  480. 是否由地接支付:{isFeeMark1} <br/>";
  481. }
  482. var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
  483. item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
  484. if (item.BreakfastPrice != 0)
  485. {
  486. if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
  487. item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
  488. string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  489. string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
  490. item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
  491. 收款方:{breakfastData?.Payee}<br/>
  492. 费用标识:{feeMark2} <br/>
  493. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  494. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
  495. 是否由地接支付:{isFeeMark2} <br/>";
  496. }
  497. var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
  498. item.GovernmentRent = landTaxData?.Price ?? 0.00M;
  499. if (item.GovernmentRent != 0)
  500. {
  501. if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
  502. item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
  503. string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  504. string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
  505. item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
  506. 收款方:{landTaxData?.Payee}<br/>
  507. 费用标识:{feeMark3} <br/>
  508. 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
  509. 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
  510. 是否由地接支付:{isFeeMark3} <br/>";
  511. }
  512. var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
  513. item.CityTax = cityTaxData?.Price ?? 0.00M;
  514. if (item.CityTax != 0)
  515. {
  516. if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
  517. item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
  518. string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  519. string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
  520. item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
  521. 收款方:{cityTaxData?.Payee}<br/>
  522. 费用标识:{feeMark4} <br/>
  523. 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
  524. 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
  525. 是否由地接支付:{isFeeMark4} <br/>";
  526. }
  527. if (!string.IsNullOrEmpty(paymentStr))
  528. {
  529. item.IsPay = 2;
  530. item.PayTips = paymentStr;
  531. }
  532. //item.CNYPrice = roomData?.Price ?? 0.00M * roomData?.Rate ?? 0.00M +
  533. // breakfastData?.Price ?? 0.00M * breakfastData?.Rate ?? 0.00M +
  534. // landTaxData?.Price ?? 0.00M * landTaxData?.Rate ?? 0.00M +
  535. // cityTaxData?.Price ?? 0.00M * cityTaxData?.Rate ?? 0.00M;
  536. }
  537. else
  538. {
  539. decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
  540. (item.DoubleRoomCount * item.DoubleRoomPrice) +
  541. (item.SuiteRoomCount * item.SuiteRoomPrice) +
  542. (item.OtherRoomCount * item.OtherRoomPrice);
  543. //item.RoomPrice = item.CardPrice;
  544. item.RoomPriceCurrency = item.PaymentCurrency;
  545. }
  546. HotelCNYTotalPrice += item.CNYPrice;
  547. item.PayMoney = item.PayMoney.ConvertToDecimal1();
  548. item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
  549. }
  550. _geView.GroupHotelFeeViews = groupHotelFeeViews;
  551. _geView.GroupHotelFeeStr = string.Format(@"人民币总费用:{0} CNY", HotelCNYTotalPrice.ToString("#0.00"));
  552. #endregion
  553. #region 地接费用
  554. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  555. string CTGGRFeeSql = string.Empty;
  556. if (visitDate > Convert.ToDateTime("2024-04-17"))
  557. {
  558. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
  559. sd2.name As PaymentCurrency,ccp.PayPercentage,
  560. (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
  561. (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
  562. ccp.DayRate,(ctggrc.Price * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  563. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  564. From Grp_CarTouristGuideGroundReservations ctggr
  565. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
  566. cggrc.DatePrice,cggrc.PriceContent
  567. From Grp_CarTouristGuideGroundReservationsContent cggrc
  568. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  569. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  570. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  571. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  572. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  573. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  574. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  575. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  576. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  577. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  578. }
  579. else
  580. {
  581. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,
  582. ccp.PayMoney,sd2.name As PaymentCurrency,ccp.PayPercentage,
  583. (ccp.PayMoney * (ccp.PayPercentage / 100)) As AmountPaid,
  584. (ccp.PayMoney -ccp.PayMoney * (ccp.PayPercentage / 100)) As BalancePayment,
  585. ccp.DayRate,(ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,
  586. ccp.Payee,ccp.AuditGMDate,
  587. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  588. From Grp_CarTouristGuideGroundReservations ctggr
  589. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  590. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  591. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  592. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  593. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  594. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  595. }
  596. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  597. string CTGGRFeeStr = "";
  598. decimal CTGGRCNYTotalPrice = 0.00M;
  599. //按1 地区,2 币种,3 汇率 分组计算
  600. var groupCTGGRFeeDatas = groupCTGGRFeeViews.GroupBy(it => it.Area);
  601. foreach (var ctggfr in groupCTGGRFeeDatas)
  602. {
  603. var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
  604. if (ctggfr_curr.Count() > 0)
  605. {
  606. foreach (var curr in ctggfr_curr)
  607. {
  608. var ctggfr_rate = curr.GroupBy(it => it.DayRate);
  609. if (ctggfr_rate.Count() > 0)
  610. {
  611. foreach (var rate in ctggfr_rate)
  612. {
  613. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{rate.Sum(it => it.AmountPaid).ToString("#0.00")}
  614. {rate.FirstOrDefault()?.PaymentCurrency}(人民币:
  615. {rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  616. {rate.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  617. CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  618. }
  619. }
  620. else
  621. {
  622. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{curr.Sum(it => it.AmountPaid).ToString("#0.00")}
  623. {curr.FirstOrDefault()?.PaymentCurrency}(人民币:
  624. {curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  625. {curr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  626. CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  627. }
  628. }
  629. }
  630. else
  631. {
  632. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{ctggfr.Sum(it => it.AmountPaid).ToString("#0.00")}
  633. {ctggfr.FirstOrDefault()?.PaymentCurrency}(人民币:
  634. {ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  635. {ctggfr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  636. CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  637. }
  638. }
  639. foreach (var item in groupCTGGRFeeViews)
  640. {
  641. if (!string.IsNullOrEmpty(item.AuditGMDate))
  642. {
  643. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  644. }
  645. if (item.DatePrice != null)
  646. {
  647. item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
  648. }
  649. //CTGGRFeeStr += string.Format(@"{0} 总费用:{1} {2}(人民币:{3} CNY 当时支付汇率:{4})\r\n",
  650. // item.Area, item.AmountPaid.ConvertToDecimal1().ToString("#0.00"), item.PaymentCurrency, item.CNYPrice.ToString("#0.0000"), item.DayRate.ToString("#0.0000"));
  651. //CTGGRCNYTotalPrice += item.CNYPrice;
  652. }
  653. _geView.GroupCTGGRFeeViews = groupCTGGRFeeViews;
  654. _geView.GroupCTGGRFeeStr = string.Format(@"{0}人民币总费用:{1} CNY", CTGGRFeeStr, CTGGRCNYTotalPrice.ToString("#0.00"));
  655. #endregion
  656. #region 机票预订费用
  657. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  658. //ccp.RMBPrice As CNYPrice
  659. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  660. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  661. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  662. sd1.Name As PayMoneyCurrency,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  663. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime,
  664. atr.CType
  665. From Grp_AirTicketReservations atr
  666. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  667. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  668. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  669. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  670. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  671. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  672. Where atr.IsDel = 0 {1} And atr.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  673. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  674. string str = "";
  675. List<dynamic> airClientPris = new List<dynamic>();
  676. decimal AirCNYTotalPrice = 0.00M;
  677. decimal JJCCNYTotalPrice = 0.00M, JJCPeopleNum = 0.00M, JJCAveragePrice = 0.00M;
  678. decimal GWCCNYTotalPrice = 0.00M, GWCPeopleNum = 0.00M, GWCAveragePrice = 0.00M;
  679. //if (groupAirFeeViews.Count > 0)
  680. //{
  681. // JJCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.CNYPrice);
  682. // JJCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.ClientNum);
  683. // JJCAveragePrice = (JJCCNYTotalPrice / JJCPeopleNum).ConvertToDecimal1();
  684. // GWCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.CNYPrice);
  685. // GWCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.ClientNum);
  686. // GWCAveragePrice = (GWCCNYTotalPrice / GWCPeopleNum).ConvertToDecimal1();
  687. //}
  688. int Index = 0;
  689. foreach (var item in groupAirFeeViews)
  690. {
  691. if (item.AirId > 2924)
  692. {
  693. string itemClientName = "";
  694. if (!string.IsNullOrEmpty(item.ClientName))
  695. {
  696. System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  697. System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  698. if (m_EnName.Success || m_ZHName.Success)
  699. {
  700. itemClientName = item.ClientName;
  701. decimal unitCost = 0.00M;
  702. AirCNYTotalPrice += item.CNYPrice;
  703. continue;
  704. }
  705. string[] clientIds = new string[] { };
  706. if (item.ClientName.Contains(','))
  707. {
  708. clientIds = item.ClientName.Split(',');
  709. }
  710. else
  711. {
  712. clientIds = new string[] { item.ClientName };
  713. }
  714. if (clientIds.Length > 0)
  715. {
  716. int[] output = Array.ConvertAll<string, int>(clientIds, delegate (string s) { return int.Parse(s); });
  717. if (output.Contains(-1))
  718. {
  719. itemClientName += $@"行程单";
  720. output = output.Where(val => val != -1).ToArray();
  721. }
  722. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  723. decimal unitCost = 0.00M;
  724. unitCost = (item.PayMoney / item.ClientNum).ConvertToDecimal1();
  725. int clienIndex = 1;
  726. foreach (var client in clients)
  727. {
  728. airClientPris.Add(new
  729. {
  730. CnName = client.LastName + client.FirstName,
  731. EnName = client.Pinyin,
  732. Price = unitCost,
  733. AirType = item.AirTypeName
  734. });
  735. string six = "";
  736. if (client.Sex == 0) six = "Mr";
  737. else if (client.Sex == 1) six = "Ms";
  738. itemClientName += string.Format(@"{0}.{1} {2};", clienIndex, client.LastName + client.FirstName, six);
  739. clienIndex++;
  740. }
  741. }
  742. }
  743. item.ClientName = itemClientName;
  744. }
  745. else
  746. {
  747. string clientPinYinName = "";
  748. decimal unitCost = 0.00M;
  749. int cNum = item.ClientNum == 0 ? 1 : item.ClientNum;
  750. unitCost = (item.PayMoney / cNum).ConvertToDecimal1();
  751. Regex r = new Regex("[0-9]");
  752. string name1 = item.ClientName;
  753. name1 = r.Replace(name1, "");
  754. string[] clientNames = name1.Split('.');
  755. for (int i = 0; i < item.ClientNum; i++)
  756. {
  757. string name = "";
  758. if (clientNames.Length > 0)
  759. {
  760. int index = i + 1;
  761. if (index < clientNames.Length)
  762. {
  763. name = clientNames[index].Replace("MR", "").Replace("MS", "").Trim();
  764. if (!string.IsNullOrEmpty(name))
  765. {
  766. airClientPris.Add(new
  767. {
  768. CnName = name,
  769. EnName = name,
  770. Price = unitCost,
  771. AirType = item.AirTypeName
  772. });
  773. }
  774. //if (name.Length > 0)
  775. //{
  776. // string nameLastStr = name[name.Length - 1].ToString();
  777. // if (nameLastStr.IsNumeric())
  778. // {
  779. // name = name.Substring(0, name.Length - 1).Trim();
  780. // }
  781. //}
  782. }
  783. }
  784. clientPinYinName += string.Format(@"{0}.{1}出票价为:{2} CNY;", Index + 1, name, unitCost.ToString("#0.00"));
  785. }
  786. }
  787. if (!string.IsNullOrEmpty(item.AuditGMDate))
  788. {
  789. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  790. }
  791. AirCNYTotalPrice += item.CNYPrice;
  792. }
  793. _geView.GroupAirFeeViews = groupAirFeeViews;
  794. if (airClientPris.Count > 0)
  795. {
  796. var peoplePriStr = "";
  797. var airClientPris1 = airClientPris.GroupBy(item => item.CnName)
  798. .Select(group => group.First())
  799. .ToList();
  800. int airClientPrisIndex = 1;
  801. foreach (var item in airClientPris1)
  802. {
  803. decimal price = 0.00M;
  804. var prices = airClientPris.Where(it => it.CnName == item.CnName).ToList();
  805. foreach (var pri in prices)
  806. {
  807. price += pri.Price;
  808. }
  809. peoplePriStr += $@"{airClientPrisIndex}.{item.EnName}出票价为: {price.ToString("#0.00")} CNY;";
  810. airClientPrisIndex++;
  811. }
  812. if (!string.IsNullOrEmpty(peoplePriStr))
  813. {
  814. str = $@"其中:{peoplePriStr}";
  815. }
  816. //经济舱均价
  817. var airJJCPris = airClientPris.Where(it => it.AirType == "经济舱").ToList();
  818. if (airJJCPris.Count > 0)
  819. {
  820. decimal jjcTotalPrice = 0.00M;
  821. foreach (var item in airJJCPris)
  822. {
  823. jjcTotalPrice += item.Price;
  824. }
  825. decimal jjcPeopleNum = airJJCPris.GroupBy(item => item.CnName)
  826. .Select(group => group.First())
  827. .ToList().Count;
  828. JJCAveragePrice = jjcTotalPrice / jjcPeopleNum;
  829. }
  830. //公务舱均价
  831. var airGWCPris = airClientPris.Where(it => it.AirType == "公务舱").ToList();
  832. if (airGWCPris.Count > 0)
  833. {
  834. decimal gwcTotalPrice = 0.00M;
  835. foreach (var item in airGWCPris)
  836. {
  837. gwcTotalPrice += item.Price;
  838. }
  839. decimal gwcPeopleNum = airGWCPris.GroupBy(item => item.CnName)
  840. .Select(group => group.First())
  841. .ToList().Count;
  842. GWCAveragePrice = gwcTotalPrice / gwcPeopleNum;
  843. }
  844. }
  845. _geView.GroupAirFeeStr = $@"人民币总费用:{AirCNYTotalPrice.ToString("#0.00")} CNY\r\n{str}\r\n经济舱均价为:{JJCAveragePrice.ToString("#0.00")}CNY/人;公务舱均价为:{GWCAveragePrice.ToString("#0.00")}CNY/人;";
  846. #endregion
  847. #region 签证费用
  848. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  849. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  850. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  851. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime,
  852. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  853. From Grp_VisaInfo vi
  854. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  855. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  856. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  857. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  858. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  859. Where vi.IsDel = 0 {1} And vi.DIId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  860. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  861. decimal VisaCNYTotalPirce = 0.00M;
  862. foreach (var item in groupVisaFeeViews)
  863. {
  864. string itemClientName = "";
  865. string visaClients = item.VisaClient;
  866. if (!string.IsNullOrEmpty(visaClients))
  867. {
  868. string[] clientIds = new string[] { };
  869. if (visaClients.Contains(','))
  870. {
  871. clientIds = visaClients.Split(',');
  872. }
  873. else
  874. {
  875. clientIds = new string[] { visaClients };
  876. }
  877. if (clientIds.Length > 0)
  878. {
  879. List<int> clientIds1 = new List<int>() { };
  880. foreach (var clientIdStr in clientIds)
  881. {
  882. if (clientIdStr.IsNumeric())
  883. {
  884. clientIds1.Add(int.Parse(clientIdStr));
  885. }
  886. }
  887. if (clientIds1.Count > 0)
  888. {
  889. var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
  890. foreach (var client in clients)
  891. {
  892. itemClientName += $"{client.LastName + client.FirstName},";
  893. }
  894. }
  895. else
  896. {
  897. itemClientName = visaClients;
  898. }
  899. }
  900. }
  901. if (itemClientName.Length > 0)
  902. {
  903. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  904. }
  905. item.VisaClient = itemClientName;
  906. VisaCNYTotalPirce += item.CNYPrice;
  907. if (!string.IsNullOrEmpty(item.AuditGMDate))
  908. {
  909. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  910. }
  911. }
  912. _geView.GroupVisaFeeViews = groupVisaFeeViews;
  913. _geView.GroupVisaFeeStr = string.Format(@"人民币总费用:{0} CNY", VisaCNYTotalPirce.ConvertToDecimal1().ToString("#.00"));
  914. #endregion
  915. #region 邀请/公务活动 CTable = 81
  916. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  917. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  918. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  919. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  920. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,
  921. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice2,ccp.Payee,ccp.AuditGMDate,
  922. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  923. From Grp_InvitationOfficialActivities ioa
  924. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  925. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  926. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  927. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  928. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  929. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  930. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  931. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  932. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  933. Where ioa.IsDel = 0 {1} And ioa.Diid = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  934. groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
  935. #region 邀请/公务活动 - 模拟数据
  936. //if (groupInvitationalFeeViews.Count < 1)
  937. //{
  938. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  939. // {
  940. // IOAId = 0,
  941. // IOADiId = 2334,
  942. // InviterArea = "模拟数据-邀请方地区",
  943. // Inviter = "模拟数据-邀请方",
  944. // InviteTime = "2023-10-10",
  945. // InviteCost = 100.00M,
  946. // InviteCurrency = "EUR",
  947. // SendCost = 100.00M,
  948. // SendCurrency = "EUR",
  949. // EventsCost = 10000.00M,
  950. // EventsCurrency = "EUR",
  951. // TranslateCost = 300.00M,
  952. // TranslateCurrency = "EUR",
  953. // PayMoney = 10500.00M,
  954. // PaymentCurrency = "EUR",
  955. // CNYPrice = 76765.50M,
  956. // Payee = "模拟数据-收款方",
  957. // AuditGMDate = "2023-12-05",
  958. // OrbitalPrivateTransfer = 1,
  959. // PayWay = "刷卡",
  960. // IsPay = 1,
  961. // Applicant = "刘华举"
  962. // });
  963. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  964. // {
  965. // IOAId = 0,
  966. // IOADiId = 2334,
  967. // InviterArea = "模拟数据-邀请方地区",
  968. // Inviter = "模拟数据-邀请方",
  969. // InviteTime = "2023-10-10",
  970. // InviteCost = 100.00M,
  971. // InviteCurrency = "EUR",
  972. // SendCost = 100.00M,
  973. // SendCurrency = "EUR",
  974. // EventsCost = 10000.00M,
  975. // EventsCurrency = "EUR",
  976. // TranslateCost = 300.00M,
  977. // TranslateCurrency = "EUR",
  978. // PayMoney = 10500.00M,
  979. // PaymentCurrency = "EUR",
  980. // CNYPrice = 76765.50M,
  981. // Payee = "模拟数据-收款方",
  982. // AuditGMDate = "2023-12-05",
  983. // OrbitalPrivateTransfer = 1,
  984. // PayWay = "刷卡",
  985. // IsPay = 1,
  986. // Applicant = "刘华举"
  987. // });
  988. //}
  989. #endregion
  990. decimal InvitationalCNYTotalPrice = 0.00M;
  991. foreach (var item in groupInvitationalFeeViews)
  992. {
  993. InvitationalCNYTotalPrice += item.CNYPrice2;
  994. if (!string.IsNullOrEmpty(item.AuditGMDate))
  995. {
  996. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  997. }
  998. string currencyRateStr = "";
  999. List<string> currencys = new List<string>();
  1000. if (!string.IsNullOrEmpty(item.InviteCurrency)) currencys.Add(item.InviteCurrency);
  1001. if (!string.IsNullOrEmpty(item.SendCurrency)) currencys.Add(item.SendCurrency);
  1002. if (!string.IsNullOrEmpty(item.EventsCurrency)) currencys.Add(item.EventsCurrency);
  1003. if (!string.IsNullOrEmpty(item.TranslateCurrency)) currencys.Add(item.TranslateCurrency);
  1004. if (!string.IsNullOrEmpty(item.PaymentCurrency)) currencys.Add(item.PaymentCurrency);
  1005. currencyRateStr = await GeneralMethod.PostGroupRateByCTableAndCurrency(teamRateData, 81, currencys);
  1006. item.CurrencyRateStr = currencyRateStr;
  1007. }
  1008. _geView.GroupInvitationalFeeViews = groupInvitationalFeeViews;
  1009. _geView.GroupInvitationalFeeStr = string.Format(@"人民币总费用:{0} CNY", InvitationalCNYTotalPrice.ToString("#.00"));
  1010. #endregion
  1011. #region 保险费用
  1012. List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
  1013. string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.PayMoney * ccp.DayRate As CNYPrice,
  1014. sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  1015. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
  1016. From Grp_Customers ic
  1017. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  1018. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1019. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1020. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1021. Where ic.IsDel = 0 {1} And ic.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1022. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  1023. decimal InsuranceCNYTotalPrice = 0.00M;
  1024. foreach (var item in groupInsuranceFeeViews)
  1025. {
  1026. InsuranceCNYTotalPrice += item.CNYPrice;
  1027. string itemClientName = "";
  1028. string insClients = item.ClientName;
  1029. if (!string.IsNullOrEmpty(insClients))
  1030. {
  1031. //System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  1032. //System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  1033. //if (m_EnName.Success || m_ZHName.Success)
  1034. //{
  1035. // itemClientName = insClients;
  1036. // continue;
  1037. //}
  1038. string[] clientIds = new string[] { };
  1039. if (insClients.Contains(','))
  1040. {
  1041. clientIds = insClients.Split(',');
  1042. }
  1043. else
  1044. {
  1045. clientIds = new string[] { insClients };
  1046. }
  1047. if (clientIds.Length > 0)
  1048. {
  1049. List<int> output = new List<int>();
  1050. foreach (var clientId in clientIds)
  1051. {
  1052. if (clientId.IsNumeric())
  1053. {
  1054. output.Add(int.Parse(clientId));
  1055. }
  1056. }
  1057. if (output.Count > 0)
  1058. {
  1059. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  1060. foreach (var client in clients)
  1061. {
  1062. itemClientName += $"{client.LastName + client.FirstName},";
  1063. }
  1064. if (itemClientName.Length > 0)
  1065. {
  1066. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  1067. }
  1068. }
  1069. else
  1070. {
  1071. itemClientName = insClients;
  1072. }
  1073. }
  1074. }
  1075. item.ClientName = itemClientName;
  1076. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1077. {
  1078. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1079. }
  1080. }
  1081. _geView.GroupInsuranceFeeViews = groupInsuranceFeeViews;
  1082. _geView.GroupInsuranceFeeStr = string.Format(@"人民币总费用:{0} CNY", InsuranceCNYTotalPrice.ToString("#0.00"));
  1083. #endregion
  1084. #region 其他款项费用 98
  1085. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  1086. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1087. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  1088. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  1089. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  1090. From Grp_DecreasePayments dp
  1091. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  1092. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1093. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1094. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1095. Where dp.IsDel = 0 And ccp.Ctable = 98 {1} And dp.Diid = {0}
  1096. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1097. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  1098. #region 保险费用 - 模拟数据
  1099. //if (groupDecreaseFeeViews.Count < 1)
  1100. //{
  1101. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  1102. // {
  1103. // DPId = 0,
  1104. // DPDiId = 2334,
  1105. // PriceName = "模拟数据-费用名称",
  1106. // PayMoney = 1000.00M,
  1107. // PayMoneyCurrency = "CNY",
  1108. // DayRate = 1.0000M,
  1109. // CNYPrice = 1.0000M,
  1110. // AuditGMDate = "2023-12-10 12:13:00",
  1111. // Payee = "模拟数据-付款方",
  1112. // OrbitalPrivateTransfer = 1,
  1113. // PayWay = "现金",
  1114. // IsPay = 1,
  1115. // Applicant = "刘华举"
  1116. // });
  1117. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  1118. // {
  1119. // DPId = 0,
  1120. // DPDiId = 2334,
  1121. // PriceName = "模拟数据-费用名称",
  1122. // PayMoney = 1000.00M,
  1123. // PayMoneyCurrency = "CNY",
  1124. // DayRate = 1.0000M,
  1125. // CNYPrice = 1.0000M,
  1126. // AuditGMDate = "2023-12-10 12:13:00",
  1127. // Payee = "模拟数据-付款方",
  1128. // OrbitalPrivateTransfer = 1,
  1129. // PayWay = "现金",
  1130. // IsPay = 1,
  1131. // Applicant = "刘华举"
  1132. // });
  1133. //}
  1134. #endregion
  1135. decimal DecreaseCNYTotalPrice = 0.00M;
  1136. foreach (var item in groupDecreaseFeeViews)
  1137. {
  1138. item.CNYPrice = Convert.ToDecimal(item.CNYPrice.ToString("#0.00"));
  1139. DecreaseCNYTotalPrice += item.CNYPrice;
  1140. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1141. {
  1142. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1143. }
  1144. }
  1145. _geView.GroupDecreaseFeeViews = groupDecreaseFeeViews;
  1146. _geView.GroupDecreaseFeeStr = string.Format(@"人民币总费用:{0} CNY", DecreaseCNYTotalPrice.ToString("#0.00"));
  1147. #endregion
  1148. #region 公司内部操作人员提成
  1149. var royaltyDatas = await _sqlSugar
  1150. .Queryable<Fin_RoyaltyConfirm, Sys_Users, Sys_Users>((rc, u1, u2) =>
  1151. new JoinQueryInfos(
  1152. JoinType.Left, rc.UserId == u1.Id,
  1153. JoinType.Left, rc.CreateUserId == u2.Id
  1154. ))
  1155. .Where((rc, u1, u2) => rc.IsDel == 0 && rc.TeamId == _dto.DiId && rc.IsConfirm == 1)
  1156. .Select((rc, u1, u2) => new GroupRoyaltyFeeInfo()
  1157. {
  1158. GroupId = rc.TeamId,
  1159. OverviewInfo = rc.Temp,
  1160. DetailedInfo = rc.ChiArr,
  1161. Amount = rc.Price,
  1162. IsConfirm = rc.IsConfirm ,
  1163. IsSeed = rc.IsSeed ,
  1164. RoyaltyUserName = u1.CnName,
  1165. CreateUserName = u2.CnName,
  1166. CreateTime = rc.CreateTime
  1167. })
  1168. .ToListAsync();
  1169. decimal royaltyCNYTotalPrice = royaltyDatas.Sum(x => x.Amount);
  1170. _geView.GroupRoyaltyFeeViews = _mapper.Map<List<GroupRoyaltyFeeView>>(royaltyDatas);
  1171. _geView.GroupRoyaltyFeeStr = string.Format(@"人民币总费用:{0} CNY", royaltyCNYTotalPrice.ToString("#0.00"));
  1172. #endregion
  1173. _view.GroupExpenditure = _geView;
  1174. #endregion
  1175. /*
  1176. * 团组报表计算方式
  1177. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  1178. * 应收金额 = 应收表.Sum()
  1179. * 已收金额 = 已收表.Sum()
  1180. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  1181. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  1182. *
  1183. */
  1184. decimal _totalExpenditure = 0.00M; //总支出
  1185. decimal _amountReceivable = 0.00M; //应收金额
  1186. decimal _amountReceived = 0.00M; //已收金额
  1187. decimal _receivableProfit = 0.00M; //应收利润
  1188. decimal _receivedProfit = 0.00M; //已收利润
  1189. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  1190. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount + royaltyCNYTotalPrice;
  1191. _amountReceivable = frTotalAmount;
  1192. _amountReceived = prTotalAmount;
  1193. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  1194. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  1195. _view.FeeTotalStr = string.Format(@$"<span>
  1196. <span>当前总支出:{_totalExpenditure.ToString("#0.00")} CNY</span>
  1197. <span style='padding-left:10px;color: Green;'>应收金额:{_amountReceivable.ToString("#0.00")} CNY</span>
  1198. <span style='padding-left:10px;color: Green;'>已收金额:{_amountReceived.ToString("#0.00")} CNY</span>
  1199. <span style='padding-left:10px;color: Green;'>应收利润(应收-支出):{_receivableProfit.ToString("#0.00")} CNY</span>
  1200. <span style='padding-left:10px;color: Green;'>已收利润(已收-支出):{_receivedProfit.ToString("#0.00")} CNY</span>
  1201. </span>");
  1202. return Ok(JsonView(true, "查询成功!", _view));
  1203. }
  1204. else
  1205. {
  1206. return Ok(JsonView(false, "查询成功"));
  1207. }
  1208. }
  1209. /// <summary>
  1210. /// 团组报表
  1211. /// Excel 下载
  1212. /// </summary>
  1213. /// <param name="_dto">团组列表请求dto</param>
  1214. /// <returns></returns>
  1215. [HttpPost("PostGroupStatementExportExcel")]
  1216. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1217. public async Task<IActionResult> PostGroupStatementExportExcel(GroupStatementDetailsDto _dto)
  1218. {
  1219. //pageId 38
  1220. int currUserId = _dto.UserId, pageId = _dto.PageId, diId = _dto.DiId;
  1221. bool isAudit = _dto.isAudit;
  1222. #region 参数验证
  1223. if (currUserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1224. if (pageId < 1) return Ok(JsonView(false, "页面Id为空"));
  1225. if (diId < 1) return Ok(JsonView(false, "数据Id为空"));
  1226. #region 页面操作权限验证
  1227. var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(currUserId, pageId);
  1228. if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权!"));
  1229. #endregion
  1230. #endregion
  1231. var groupInfo = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => x.IsDel == 0 && x.Id == diId).First();
  1232. if (groupInfo == null) return Ok(JsonView(false, "暂无该条团组信息!"));
  1233. var userInfo = _sqlSugar.Queryable<Sys_Users>().Where(x => x.IsDel == 0 && x.Id == currUserId).First();
  1234. string groupNo = groupInfo.TourCode,
  1235. groupName = groupInfo.TeamName.Replace("|", "、"),
  1236. lister = userInfo?.CnName ?? "-";
  1237. var _clientDatas = _sqlSugar.Queryable<Crm_DeleClient>()
  1238. .Where(it => it.IsDel == 0)
  1239. .Select(x => new Crm_DeleClient { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, Sex = x.Sex })
  1240. .ToList();
  1241. //获取模板
  1242. string tempPath = (AppSettingsHelper.Get("ExcelBasePath") + "Template/团组费用统计模板.xls");
  1243. var designer = new WorkbookDesigner();
  1244. designer.Workbook = new Workbook(tempPath);
  1245. // 获取工作簿中的工作表集合
  1246. var worksheets = designer.Workbook.Worksheets;
  1247. #region 获取sheet,定义datatable,局部变量
  1248. //酒店费用相关
  1249. var hotelFeeSheet = worksheets["酒店费用"];
  1250. var hotelFeeDt = new DataTable($"HotelFeeView");
  1251. decimal hotelCNYTotalCost = 0.00M;
  1252. //地接费用相关
  1253. var OPFeeSheet = worksheets["地接费用"];
  1254. var OPFeeDt = new DataTable($"OPFeeView");
  1255. var OPFeeLabel = string.Empty;
  1256. decimal OPCNYTotalCost = 0.00M;
  1257. //签证费用相关
  1258. var visaFeeSheet = worksheets["签证费用"];
  1259. var visaFeeDt = new DataTable($"VisaFeeView");
  1260. decimal visaCNYTotalCost = 0.00M;
  1261. //邀请费用相关
  1262. var OAFeeSheet = worksheets["邀请费用"];
  1263. var OAFeeDt = new DataTable($"OAFeeView");
  1264. decimal OACNYTotalCost = 0.00M;
  1265. //机票费用相关
  1266. var airTicketFeeSheet = worksheets["机票费用"];
  1267. var airTicketFeeDt = new DataTable($"AirTicketFeeView");
  1268. decimal airTicketCNYTotalCost = 0.00M;
  1269. //保险费用相关
  1270. var insureFeeSheet = worksheets["保险费用"];
  1271. var insureFeeDt = new DataTable($"InsureFeeView");
  1272. decimal insureCNYTotalCost = 0.00M;
  1273. //其他费用相关
  1274. var otherFeeSheet = worksheets["其他费用"];
  1275. var otherFeeDt = new DataTable($"OtherFeeView");
  1276. decimal otherCNYTotalCost = 0.00M;
  1277. //收款退还相关
  1278. var SKTHFeeSheet = worksheets["收款退还"];
  1279. var SKTHFeeDt = new DataTable($"SKTHFeeView");
  1280. decimal SKTHCNYTotalCost = 0.00M;
  1281. //操作提成
  1282. var royaltyFeeSheet = worksheets["操作提成"];
  1283. var royaltyFeeDt = new DataTable($"royaltyFeeView");
  1284. decimal royaltyCNYTotalCost = 0.00M;
  1285. var totalAmount = 0.00M; //支出成本合计
  1286. var accountsAmount = 0.00M; //应收金额合计
  1287. var receivedAmount = 0.00M; //已收金额合计
  1288. var accountsProfit = 0.00M; //应收利润合计
  1289. var receiveProfit = 0.00M; //已收利润合计
  1290. var profitMargin = 0.00M; //利润差合计
  1291. //应收合计相关
  1292. var receivableFeeSheet = worksheets["团组收入(未收)"];
  1293. var receivableFeeDt = new DataTable($"ReceivableFeeView");
  1294. //已收合计相关
  1295. var receivedFeeSheet = worksheets["团组收入(已收)"];
  1296. var receivedFeeDt = new DataTable($"ReceivedFeeView");
  1297. //团组收入支出利润
  1298. var groupIEProfitDt = new DataTable($"IEProfitFeeView");
  1299. #endregion
  1300. #region 酒店费用
  1301. if (hotelFeeSheet != null)
  1302. {
  1303. string hotelFeeSql = string.Format(@"
  1304. SELECT
  1305. hr.Id AS HrId,
  1306. hr.DiId AS HrDiId,
  1307. hr.City,
  1308. hr.HotelName,
  1309. hr.CheckInDate,
  1310. hr.CheckOutDate,
  1311. hr.CardPrice AS RoomPrice,
  1312. sd1.Name AS PaymentCurrency,
  1313. hr.SingleRoomPrice,
  1314. hr.SingleRoomCount,
  1315. hr.DoubleRoomPrice,
  1316. hr.DoubleRoomCount,
  1317. hr.SuiteRoomPrice,
  1318. hr.SuiteRoomCount,
  1319. hr.OtherRoomPrice,
  1320. hr.OtherRoomCount,
  1321. hr.BreakfastPrice,
  1322. sd4.Name AS BreakfastCurrency,
  1323. hr.Isoppay,
  1324. hr.GovernmentRent,
  1325. sd5.Name AS GovernmentRentCurrency,
  1326. hr.CityTax,
  1327. sd6.Name AS CityTaxCurrency,
  1328. ccp.PayMoney,
  1329. (
  1330. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  1331. ) AS CNYPrice,
  1332. ccp.PayPercentage,
  1333. ccp.DayRate,
  1334. ccp.Payee,
  1335. ccp.OrbitalPrivateTransfer,
  1336. sd2.Name AS PayWay,
  1337. sd3.Name AS CardType,
  1338. ccp.IsPay,
  1339. u.CnName AS Applicant,
  1340. hr.Remark
  1341. FROM
  1342. Grp_HotelReservations hr
  1343. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  1344. LEFT JOIN Sys_SetData sd1 ON ccp.PaymentCurrency = sd1.Id
  1345. LEFT JOIN Sys_SetData sd2 ON ccp.PayDId = sd2.Id
  1346. LEFT JOIN Sys_SetData sd3 ON ccp.CTDId = sd3.Id
  1347. LEFT JOIN Sys_Users u ON ccp.CreateUserId = u.Id
  1348. LEFT JOIN Sys_SetData sd4 ON hr.BreakfastCurrency = sd4.Id
  1349. LEFT JOIN Sys_SetData sd5 ON hr.GovernmentRentCurrency = sd5.Id
  1350. LEFT JOIN Sys_SetData sd6 ON hr.CityTaxCurrency = sd6.Id
  1351. WHERE
  1352. hr.IsDel = 0
  1353. AND ccp.IsDel = 0
  1354. AND ccp.CTable = 76 {1}
  1355. AND ccp.PayMoney <> 0
  1356. AND hr.DiId = {0}
  1357. ORDER BY
  1358. CheckInDate Asc", _dto.DiId, _dto.isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  1359. var groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  1360. if (groupHotelFeeViews.Any())
  1361. {
  1362. var _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  1363. var hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
  1364. var groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
  1365. var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
  1366. foreach (var item in groupHotelFeeViews)
  1367. {
  1368. if (groupHotelContentFeeViews.Count > 0)
  1369. {
  1370. string paymentStr = string.Empty;
  1371. var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
  1372. item.RoomPrice = roomData?.Price ?? 0.00M;
  1373. if (item.RoomPrice != 0)
  1374. {
  1375. if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
  1376. item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
  1377. string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1378. string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
  1379. item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
  1380. 收款方:{roomData?.Payee}<br/>
  1381. 费用标识:{feeMark1} <br/>
  1382. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  1383. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
  1384. 是否由地接支付:{isFeeMark1} <br/>";
  1385. }
  1386. var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
  1387. item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
  1388. if (item.BreakfastPrice != 0)
  1389. {
  1390. if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
  1391. item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
  1392. string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1393. string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
  1394. item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
  1395. 收款方:{breakfastData?.Payee}<br/>
  1396. 费用标识:{feeMark2} <br/>
  1397. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  1398. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
  1399. 是否由地接支付:{isFeeMark2} <br/>";
  1400. }
  1401. var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
  1402. item.GovernmentRent = landTaxData?.Price ?? 0.00M;
  1403. if (item.GovernmentRent != 0)
  1404. {
  1405. if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
  1406. item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
  1407. string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1408. string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
  1409. item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
  1410. 收款方:{landTaxData?.Payee}<br/>
  1411. 费用标识:{feeMark3} <br/>
  1412. 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
  1413. 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
  1414. 是否由地接支付:{isFeeMark3} <br/>";
  1415. }
  1416. var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
  1417. item.CityTax = cityTaxData?.Price ?? 0.00M;
  1418. if (item.CityTax != 0)
  1419. {
  1420. if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
  1421. item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
  1422. string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1423. string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
  1424. item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
  1425. 收款方:{cityTaxData?.Payee}<br/>
  1426. 费用标识:{feeMark4} <br/>
  1427. 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
  1428. 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
  1429. 是否由地接支付:{isFeeMark4} <br/>";
  1430. }
  1431. if (!string.IsNullOrEmpty(paymentStr))
  1432. {
  1433. item.IsPay = 2;
  1434. item.PayTips = paymentStr;
  1435. }
  1436. //item.CNYPrice = roomData?.Price ?? 0.00M * roomData?.Rate ?? 0.00M +
  1437. // breakfastData?.Price ?? 0.00M * breakfastData?.Rate ?? 0.00M +
  1438. // landTaxData?.Price ?? 0.00M * landTaxData?.Rate ?? 0.00M +
  1439. // cityTaxData?.Price ?? 0.00M * cityTaxData?.Rate ?? 0.00M;
  1440. }
  1441. else
  1442. {
  1443. decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
  1444. (item.DoubleRoomCount * item.DoubleRoomPrice) +
  1445. (item.SuiteRoomCount * item.SuiteRoomPrice) +
  1446. (item.OtherRoomCount * item.OtherRoomPrice);
  1447. //item.RoomPrice = item.CardPrice;
  1448. item.RoomPriceCurrency = item.PaymentCurrency;
  1449. }
  1450. item.PayMoney = item.PayMoney.ConvertToDecimal1();
  1451. item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
  1452. }
  1453. }
  1454. hotelCNYTotalCost = groupHotelFeeViews.Sum(x => x.CNYPrice);
  1455. hotelFeeDt = CommonFun.ToDataTableArray(groupHotelFeeViews);
  1456. hotelFeeDt.TableName = $"HotelFeeView";
  1457. }
  1458. #endregion
  1459. #region 地接费用
  1460. if (OPFeeSheet != null)
  1461. {
  1462. string CTGGRFeeSql = string.Empty;
  1463. if (groupInfo.VisitDate > Convert.ToDateTime("2024-04-17"))
  1464. {
  1465. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
  1466. sd2.name As PaymentCurrency,ccp.PayPercentage,
  1467. (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
  1468. (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
  1469. ccp.DayRate,(ctggrc.Price * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  1470. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  1471. From Grp_CarTouristGuideGroundReservations ctggr
  1472. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
  1473. cggrc.DatePrice,cggrc.PriceContent
  1474. From Grp_CarTouristGuideGroundReservationsContent cggrc
  1475. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  1476. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  1477. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  1478. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  1479. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  1480. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  1481. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  1482. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1483. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  1484. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  1485. }
  1486. else
  1487. {
  1488. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,
  1489. ccp.PayMoney,sd2.name As PaymentCurrency,ccp.PayPercentage,
  1490. (ccp.PayMoney * (ccp.PayPercentage / 100)) As AmountPaid,
  1491. (ccp.PayMoney -ccp.PayMoney * (ccp.PayPercentage / 100)) As BalancePayment,
  1492. ccp.DayRate,(ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,
  1493. ccp.Payee,ccp.AuditGMDate,
  1494. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  1495. From Grp_CarTouristGuideGroundReservations ctggr
  1496. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  1497. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  1498. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  1499. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1500. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  1501. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  1502. }
  1503. var groupOPFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  1504. string CTGGRFeeStr = "";
  1505. var OPToDataTableViews = groupOPFeeViews;
  1506. decimal CTGGRCNYTotalPrice = 0.00M;
  1507. //按1 地区,2 币种,3 汇率 分组计算
  1508. var groupCTGGRFeeDatas = groupOPFeeViews.GroupBy(it => it.Area);
  1509. foreach (var ctggfr in groupCTGGRFeeDatas)
  1510. {
  1511. var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
  1512. if (ctggfr_curr.Count() > 0)
  1513. {
  1514. foreach (var curr in ctggfr_curr)
  1515. {
  1516. var ctggfr_rate = curr.GroupBy(it => it.DayRate);
  1517. if (ctggfr_rate.Count() > 0)
  1518. {
  1519. foreach (var rate in ctggfr_rate)
  1520. {
  1521. 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");
  1522. CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1523. }
  1524. }
  1525. else
  1526. {
  1527. 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");
  1528. CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1529. }
  1530. }
  1531. }
  1532. else
  1533. {
  1534. 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");
  1535. CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1536. }
  1537. }
  1538. foreach (var item in groupOPFeeViews)
  1539. {
  1540. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1541. {
  1542. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1543. }
  1544. if (item.DatePrice != null)
  1545. {
  1546. item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
  1547. }
  1548. }
  1549. OPCNYTotalCost = CTGGRCNYTotalPrice;
  1550. OPFeeDt = CommonFun.ToDataTableArray(OPToDataTableViews);
  1551. OPFeeLabel = CTGGRFeeStr;
  1552. OPFeeDt.TableName = $"OPFeeView";
  1553. }
  1554. #endregion
  1555. #region 签证费用
  1556. if (visaFeeSheet != null)
  1557. {
  1558. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1559. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,sd2.Name As PaymentModes,sd3.Name As CardTypeName,u.CnName As Applicant,vi.CreateTime,
  1560. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
  1561. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1562. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,vi.Remark
  1563. From Grp_VisaInfo vi
  1564. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  1565. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1566. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1567. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  1568. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1569. Where vi.IsDel = 0 {1} And vi.DIId = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1570. var groupVisaFeeViews = _sqlSugar.SqlQueryable<GroupVisaFeeExcelView>(groupVisaFeeSql).ToList();
  1571. foreach (var item in groupVisaFeeViews)
  1572. {
  1573. string names = string.Empty;
  1574. string visaClients = item.VisaClient;
  1575. if (!string.IsNullOrEmpty(visaClients))
  1576. {
  1577. var clientIds = new string[] { };
  1578. if (visaClients.Contains(',')) clientIds = visaClients.Split(',');
  1579. else clientIds = new string[] { visaClients };
  1580. if (clientIds.Length > 0)
  1581. {
  1582. var clientIds1 = new List<int>() { };
  1583. foreach (var clientIdStr in clientIds)
  1584. {
  1585. var isInt = int.TryParse(clientIdStr, out int id);
  1586. if (isInt) clientIds1.Add(id);
  1587. }
  1588. if (clientIds1.Count > 0)
  1589. {
  1590. var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
  1591. foreach (var client in clients)
  1592. {
  1593. EncryptionProcessor.DecryptProperties(client);
  1594. names += $"{client.LastName + client.FirstName},";
  1595. }
  1596. }
  1597. else names = visaClients;
  1598. }
  1599. if (names.Length > 0) names = names.Substring(0, names.Length - 1);
  1600. item.VisaClient = names;
  1601. }
  1602. }
  1603. visaCNYTotalCost = groupVisaFeeViews.Sum(x => x.CNYPrice);
  1604. visaFeeDt = CommonFun.ToDataTableArray(groupVisaFeeViews);
  1605. visaFeeDt.TableName = $"VisaFeeView";
  1606. }
  1607. #endregion
  1608. #region 邀请费用
  1609. if (OAFeeSheet != null)
  1610. {
  1611. string feeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,CONVERT(DATE, ioa.InviteTime) AS InviteTime,
  1612. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  1613. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  1614. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,ccp.ConsumptionDate,
  1615. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1616. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1617. ccp.Payee,ioa.Remark,ccp.AuditGMDate,u.CnName As Applicant,ioa.CreateTime
  1618. From Grp_InvitationOfficialActivities ioa
  1619. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  1620. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1621. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1622. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  1623. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  1624. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  1625. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  1626. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  1627. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1628. Where ioa.IsDel = 0 {1} And ioa.Diid = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1629. var feeViews = _sqlSugar.SqlQueryable<GroupOAFeeExcelView>(feeSql).ToList();
  1630. OACNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1631. OAFeeDt = CommonFun.ToDataTableArray(feeViews);
  1632. OAFeeDt.TableName = $"OAFeeView";
  1633. }
  1634. #endregion
  1635. #region 机票费用
  1636. if (airTicketFeeSheet != null)
  1637. {
  1638. string feeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,
  1639. sd4.Name As AirTypeName,atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,
  1640. atr.PriceDescription,ccp.PayMoney,ccp.DayRate,sd1.Name As PayMoneyCurrency,
  1641. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
  1642. ccp.Payee,Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1643. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1644. sd3.Name As CardType,ccp.AuditGMDate,u.CnName As Applicant,atr.CreateTime,atr.Remark
  1645. From Grp_AirTicketReservations atr
  1646. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  1647. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1648. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1649. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  1650. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  1651. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1652. Where atr.IsDel = 0 {1} And atr.DiId = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1653. var feeViews = _sqlSugar.SqlQueryable<GroupAirTicketExcelView>(feeSql).ToList();
  1654. airTicketCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1655. airTicketFeeDt = CommonFun.ToDataTableArray(feeViews);
  1656. airTicketFeeDt.TableName = $"AirTicketFeeView";
  1657. }
  1658. #endregion
  1659. #region 保险费用
  1660. if (insureFeeSheet != null)
  1661. {
  1662. string feeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,
  1663. sd1.Name As PayMoneyCurrency,ccp.DayRate,ccp.PayMoney * ccp.DayRate As CNYPrice,ccp.ConsumptionDate,
  1664. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1665. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1666. ccp.Payee,ccp.AuditGMDate,u.CnName As Applicant,ic.CreateTime,ic.Remark
  1667. From Grp_Customers ic
  1668. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  1669. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1670. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1671. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1672. Where ic.IsDel = 0 {1} And ic.DiId = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1673. var feeViews = _sqlSugar.SqlQueryable<GroupInsureExcelView>(feeSql).ToList();
  1674. foreach (var item in feeViews)
  1675. {
  1676. string itemClientName = "";
  1677. string insClients = item.ClientName;
  1678. if (!string.IsNullOrEmpty(insClients))
  1679. {
  1680. string[] clientIds = new string[] { };
  1681. if (insClients.Contains(',')) clientIds = insClients.Split(',');
  1682. else clientIds = new string[] { insClients };
  1683. if (clientIds.Length > 0)
  1684. {
  1685. List<int> output = new List<int>();
  1686. foreach (var clientId in clientIds)
  1687. if (int.TryParse(clientId, out int id))
  1688. output.Add(id);
  1689. if (output.Count > 0)
  1690. {
  1691. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  1692. foreach (var client in clients)
  1693. {
  1694. EncryptionProcessor.DecryptProperties(client);
  1695. itemClientName += $"{client.LastName + client.FirstName},";
  1696. }
  1697. if (itemClientName.Length > 0)
  1698. {
  1699. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  1700. }
  1701. }
  1702. else itemClientName = insClients;
  1703. }
  1704. }
  1705. item.ClientName = itemClientName;
  1706. }
  1707. insureCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1708. insureFeeDt = CommonFun.ToDataTableArray(feeViews);
  1709. insureFeeDt.TableName = $"InsureFeeView";
  1710. }
  1711. #endregion
  1712. #region 其他费用
  1713. if (insureFeeSheet != null)
  1714. {
  1715. string feeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1716. ccp.DayRate,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
  1717. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1718. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1719. ccp.Payee,ccp.AuditGMDate,u.CnName As Applicant,dp.CreateTime,dp.Remark
  1720. From Grp_DecreasePayments dp
  1721. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  1722. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1723. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1724. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1725. Where dp.IsDel = 0 And ccp.Ctable = 98 {1} And dp.Diid = {0}
  1726. Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1727. var feeViews = _sqlSugar.SqlQueryable<GroupOtherFeeExcelView>(feeSql).ToList();
  1728. otherCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1729. otherFeeDt = CommonFun.ToDataTableArray(feeViews);
  1730. otherFeeDt.TableName = $"OtherFeeView";
  1731. }
  1732. #endregion
  1733. #region 收款退还
  1734. if (SKTHFeeSheet != null)
  1735. {
  1736. //删除了 And prom.PriceType = 1
  1737. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  1738. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  1739. prom.PayType As PrPayType,prom.PriceType As PrPriceType,
  1740. ccp.RMBPrice * ccp.DayRate As RMBPrice,ccp.*,prom.CreateTime As PrCreateTime,prom.Remark AS SKTHRemark
  1741. From Fin_PaymentRefundAndOtherMoney prom
  1742. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  1743. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1744. Where prom.IsDel = 0
  1745. And prom.PayType = 1
  1746. And ccp.CTable = 285
  1747. {1}
  1748. And prom.DiId = {0} Order By PrCreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1749. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  1750. if (_promDatas.Any())
  1751. {
  1752. var _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  1753. var _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  1754. foreach (var ropItem in _promDatas)
  1755. {
  1756. string thisCueencyCode = "Unknown";
  1757. string thisCueencyName = "Unknown";
  1758. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  1759. if (currency != null)
  1760. {
  1761. thisCueencyCode = currency.Name;
  1762. thisCueencyName = currency.Remark;
  1763. }
  1764. string orbitalPrivateTransferStr = "Unknown";
  1765. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  1766. if (orbitalPrivateTransfer != null)
  1767. {
  1768. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  1769. }
  1770. string payStr = "Unknown";
  1771. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  1772. if (pay != null)
  1773. {
  1774. payStr = pay.Name;
  1775. }
  1776. var gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  1777. {
  1778. Id = ropItem.Id,
  1779. DiId = ropItem.DIId,
  1780. PriceName = ropItem.PrPriceName,
  1781. PayCurrencyCode = thisCueencyCode,
  1782. PayCurrencyName = thisCueencyName,
  1783. Price = ropItem.PrPrice,
  1784. CNYPrice = ropItem.PayMoney * ropItem.DayRate,
  1785. ThisRate = ropItem.DayRate,
  1786. Payee = ropItem.Payee,
  1787. PayTime = ropItem.AuditGMDate,
  1788. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  1789. PayType = payStr,
  1790. IsPay = ropItem.IsPay,
  1791. Applicant = ropItem.Appliction,
  1792. Remark = ropItem.SKTHRemark
  1793. };
  1794. _promView.Add(gsd_PaymentRefund);
  1795. }
  1796. SKTHCNYTotalCost = _promView.Sum(x => x.CNYPrice);
  1797. SKTHFeeDt = CommonFun.ToDataTableArray(_promView);
  1798. SKTHFeeDt.TableName = $"SKTHFeeView";
  1799. }
  1800. }
  1801. #endregion
  1802. #region 操作提成
  1803. if (SKTHFeeSheet != null)
  1804. {
  1805. var _royaltyDatas = await _sqlSugar
  1806. .Queryable<Fin_RoyaltyConfirm, Sys_Users, Sys_Users>((rc, u1, u2) =>
  1807. new JoinQueryInfos(
  1808. JoinType.Left, rc.UserId == u1.Id,
  1809. JoinType.Left, rc.CreateUserId == u2.Id
  1810. ))
  1811. .Where((rc, u1, u2) => rc.IsDel == 0 && rc.TeamId == _dto.DiId && rc.IsConfirm == 1)
  1812. .Select((rc, u1, u2) => new GroupRoyaltyFeeInfo()
  1813. {
  1814. GroupId = rc.TeamId,
  1815. OverviewInfo = rc.Temp,
  1816. DetailedInfo = rc.ChiArr,
  1817. Amount = rc.Price,
  1818. IsConfirm = rc.IsConfirm,
  1819. IsSeed = rc.IsSeed,
  1820. RoyaltyUserName = u1.CnName,
  1821. CreateUserName = u2.CnName,
  1822. CreateTime = rc.CreateTime
  1823. })
  1824. .ToListAsync();
  1825. if (_royaltyDatas.Any())
  1826. {
  1827. decimal royaltyCNYTotalPrice = _royaltyDatas.Sum(x => x.Amount);
  1828. var _royaltyFeeViews = _mapper.Map<List<GroupRoyaltyFeeExcelView>>(_royaltyDatas);
  1829. royaltyCNYTotalCost = _royaltyFeeViews.Sum(x => x.Amount);
  1830. royaltyFeeDt = CommonFun.ToDataTableArray(_royaltyFeeViews);
  1831. royaltyFeeDt.TableName = $"RoyaltyFeeView";
  1832. }
  1833. }
  1834. #endregion
  1835. #region 应收金额(增加方式=实际报价时 费用必须审核才能进入团组报表)
  1836. decimal frTotalAmount = 0.00M;//应收总金额
  1837. 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,
  1838. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime,fr.Remark
  1839. From Fin_ForeignReceivables fr
  1840. Left Join Sys_SetData sd On fr.Currency = sd.Id
  1841. Left Join Sys_Users u On fr.Auditor = u.Id
  1842. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
  1843. var _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  1844. _frViews.ForEach(x =>
  1845. {
  1846. string namePrefix = string.Empty;
  1847. if (x.AddingWay == 0) namePrefix = $"账单模块-";
  1848. else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
  1849. else if (x.AddingWay == 2) namePrefix = $"实际报价-";
  1850. x.PriceName = $"{namePrefix}{x.PriceName}";
  1851. });
  1852. if (_frViews.Any())
  1853. {
  1854. accountsAmount = _frViews.Sum(it => it.ItemSumPrice);
  1855. receivableFeeDt = CommonFun.ToDataTableArray(_frViews);
  1856. receivableFeeDt.TableName = $"ReceivedFeeView";
  1857. }
  1858. #endregion
  1859. #region 已收金额
  1860. decimal prTotalAmount = 0.00M;//已收总金额
  1861. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  1862. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  1863. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  1864. From Fin_ProceedsReceived pr
  1865. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  1866. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  1867. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
  1868. var _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  1869. if (_prViews.Any())
  1870. {
  1871. receivedAmount = _prViews.Sum(it => it.Price);
  1872. receivedFeeDt = CommonFun.ToDataTableArray(_prViews);
  1873. receivedFeeDt.TableName = $"ReceivableFeeView";
  1874. }
  1875. #endregion
  1876. #region 团组收入支出利润
  1877. groupIEProfitDt.Columns.AddRange(new DataColumn[] {
  1878. new DataColumn(){ ColumnName = "ModuleName"},
  1879. new DataColumn(){ ColumnName = "FeeTotal",DataType = typeof(decimal)},
  1880. new DataColumn(){ ColumnName = "FeeCurrency"},
  1881. });
  1882. var groupIEProfitDt_rows = new[] {
  1883. new object[] { $"签证费用", visaCNYTotalCost, $"CNY" },
  1884. new object[] { $"酒店费用", hotelCNYTotalCost, $"CNY" },
  1885. new object[] { $"地接费用", OPCNYTotalCost, $"CNY" },
  1886. new object[] { $"商邀费用", OACNYTotalCost, $"CNY" },
  1887. new object[] { $"机票费用", airTicketCNYTotalCost, $"CNY" },
  1888. new object[] { $"保险费用", insureCNYTotalCost, $"CNY" },
  1889. new object[] { $"其他费用", otherCNYTotalCost, $"CNY" },
  1890. new object[] { $"收款退还费用", SKTHCNYTotalCost, $"CNY" },
  1891. new object[] { $"操作提成费用", royaltyCNYTotalCost, $"CNY" },
  1892. };
  1893. // 批量添加
  1894. foreach (var rowData in groupIEProfitDt_rows)
  1895. {
  1896. groupIEProfitDt.Rows.Add(rowData);
  1897. }
  1898. #endregion
  1899. #region 统一填充数据源
  1900. designer.SetDataSource("GroupNo", groupNo);
  1901. designer.SetDataSource("GroupName", groupName);
  1902. designer.SetDataSource("Lister", lister);
  1903. //酒店
  1904. designer.SetDataSource(hotelFeeDt);
  1905. designer.SetDataSource("HotelCNYTotalCost", $"{hotelCNYTotalCost.ToString("#0.00")} CNY");
  1906. //地接
  1907. designer.SetDataSource(OPFeeDt);
  1908. designer.SetDataSource("OPFeeLabel", OPFeeLabel);
  1909. designer.SetDataSource("OPCNYTotalCost", $"{OPCNYTotalCost.ToString("#0.00")} CNY");
  1910. //签证
  1911. designer.SetDataSource(visaFeeDt);
  1912. designer.SetDataSource("VisaCNYTotalCost", $"{visaCNYTotalCost.ToString("#0.00")} CNY");
  1913. //商邀
  1914. designer.SetDataSource(OAFeeDt);
  1915. designer.SetDataSource("OACNYTotalCost", $"{OACNYTotalCost.ToString("#0.00")} CNY");
  1916. //机票
  1917. designer.SetDataSource(airTicketFeeDt);
  1918. designer.SetDataSource("AirTicketCNYTotalCost", $"{airTicketCNYTotalCost.ToString("#0.00")} CNY");
  1919. //保险
  1920. designer.SetDataSource(insureFeeDt);
  1921. designer.SetDataSource("InsureCNYTotalCost", $"{insureCNYTotalCost.ToString("#0.00")} CNY");
  1922. //其他费用
  1923. designer.SetDataSource(otherFeeDt);
  1924. designer.SetDataSource("OtherCNYTotalCost", $"{otherCNYTotalCost.ToString("#0.00")} CNY");
  1925. //收款退还
  1926. designer.SetDataSource(SKTHFeeDt);
  1927. designer.SetDataSource("SKTHCNYTotalCost", $"{SKTHCNYTotalCost.ToString("#0.00")} CNY");
  1928. //操作提成
  1929. designer.SetDataSource(royaltyFeeDt);
  1930. designer.SetDataSource("RoyaltyCNYTotalCost", $"{royaltyCNYTotalCost.ToString("#0.00")} CNY");
  1931. //已收金额
  1932. designer.SetDataSource(receivedFeeDt);
  1933. designer.SetDataSource("ReceivedAmount", $"{receivedAmount.ToString("#0.00")}");
  1934. //应收金额
  1935. designer.SetDataSource(receivableFeeDt);
  1936. designer.SetDataSource("AccountsAmount", $"{accountsAmount.ToString("#0.00")}");
  1937. //应收已收 -- 尾款
  1938. var balancePayment = accountsAmount - SKTHCNYTotalCost - receivedAmount;
  1939. designer.SetDataSource("BalancePayment", $"{balancePayment.ToString("#0.00")}");
  1940. //团组收入支出利润
  1941. designer.SetDataSource(groupIEProfitDt);
  1942. #region 各项费用计算
  1943. /*
  1944. * 团组报表计算方式
  1945. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  1946. * 应收金额 = 应收表.Sum() - 收款退还
  1947. * 已收金额 = 已收表.Sum() - 收款退还
  1948. * 应收利润(应收-支出) = 应收金额 - 当前总支出
  1949. * 已收利润(已收-支出) = 已收金额 - 当前总支出
  1950. * 利润差 = 应收利润 - 已收利润
  1951. */
  1952. totalAmount = visaCNYTotalCost + hotelCNYTotalCost + OPCNYTotalCost + OACNYTotalCost + airTicketCNYTotalCost + insureCNYTotalCost + otherCNYTotalCost + royaltyCNYTotalCost;//合计金额
  1953. accountsProfit = accountsAmount - totalAmount - SKTHCNYTotalCost; //应收利润
  1954. receiveProfit = receivedAmount - totalAmount - SKTHCNYTotalCost; //已收利润
  1955. profitMargin = accountsProfit - receiveProfit; //利润差
  1956. designer.SetDataSource("TotalAmount", $"{totalAmount.ToString("#0.00")}");
  1957. designer.SetDataSource("AccountsProfit", $"{accountsProfit.ToString("#0.00")}");
  1958. designer.SetDataSource("ReceiveProfit", $"{receiveProfit.ToString("#0.00")}");
  1959. designer.SetDataSource("ProfitMargin", $"{profitMargin.ToString("#0.00")}");
  1960. #endregion
  1961. designer.Process();
  1962. #endregion
  1963. #region 单元格样式设置 未付款设置为红色
  1964. /*
  1965. * 设置单元格样式
  1966. */
  1967. //背景颜色
  1968. Style style = designer.Workbook.CreateStyle();
  1969. style.ForegroundColor = Color.FromArgb(254, 242, 203);
  1970. style.Pattern = BackgroundType.Solid;
  1971. //字体
  1972. style.Font.Name = "微软雅黑"; // 字体名称
  1973. style.Font.Size = 10; // 字体大小
  1974. style.Font.Color = System.Drawing.Color.Black; // 字体颜色
  1975. StatementExportExcelSetCell(designer, hotelFeeSheet, hotelFeeDt, style, "IsPayLable", 8, "A", "V"); //酒店
  1976. StatementExportExcelSetCell(designer, OPFeeSheet, OPFeeDt, style, "IsPayLabel", 6, "A", "M"); //OP
  1977. StatementExportExcelSetCell(designer, visaFeeSheet, visaFeeDt, style, "IsPay", 6, "A", "I"); //签证
  1978. StatementExportExcelSetCell(designer, OAFeeSheet, OAFeeDt, style, "IsPay", 6, "A", "R"); //商邀
  1979. StatementExportExcelSetCell(designer, airTicketFeeSheet, airTicketFeeDt, style, "IsPay", 6, "A", "M"); //机票
  1980. StatementExportExcelSetCell(designer, insureFeeSheet, insureFeeDt, style, "IsPay", 6, "A", "I"); //保险
  1981. StatementExportExcelSetCell(designer, otherFeeSheet, otherFeeDt, style, "IsPay", 6, "A", "J"); //其他
  1982. StatementExportExcelSetCell(designer, SKTHFeeSheet, SKTHFeeDt, style, "IsPayLable", 6, "A", "K"); //首款退还
  1983. #endregion
  1984. //文件名
  1985. string fileName = $"{groupName}[{groupNo}]_团组费用清单{DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
  1986. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + "GroupStatement/" + fileName);
  1987. string url = AppSettingsHelper.Get("ExcelBaseUrl") + "Office/Excel/GroupStatement/" + fileName;
  1988. return Ok(JsonView(true, "成功", url));
  1989. }
  1990. private void StatementExportExcelSetCell(WorkbookDesigner designer, Worksheet sheet, DataTable dt, Style style, string judgeLable, int startIndex, string startRange, string endRange)
  1991. {
  1992. if (designer == null) return;
  1993. if (sheet == null) return;
  1994. if (style == null) return;
  1995. if (dt == null) return;
  1996. if (string.IsNullOrEmpty(startRange)) return;
  1997. if (string.IsNullOrEmpty(endRange)) return;
  1998. for (int i = 0; i < dt.Rows.Count; i++)
  1999. {
  2000. var isPayStr = dt.Rows[i][$"{judgeLable}"].ToString();
  2001. if (string.IsNullOrEmpty(isPayStr)) continue;
  2002. if (isPayStr.Contains("未付款"))
  2003. {
  2004. var excelIndex = startIndex + i;
  2005. Aspose.Cells.Range range = sheet.Cells.CreateRange($"{startRange}{excelIndex}", $"{endRange}{excelIndex}");
  2006. range.ApplyStyle(style, new StyleFlag() { CellShading = true, Font = true });
  2007. }
  2008. }
  2009. }
  2010. #endregion
  2011. #region 报表/折线图统计
  2012. //企业利润-团组利润
  2013. //企业利润-会务利润
  2014. /// <summary>
  2015. /// 企业利润
  2016. /// Details
  2017. /// 待添加权限验证
  2018. /// </summary>
  2019. /// <param name="_dto">团组列表请求dto</param>
  2020. /// <returns></returns>
  2021. [HttpPost("PostCorporateProfit")]
  2022. //[JsonConverter(typeof(DecimalConverter), 2)]
  2023. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2024. public async Task<IActionResult> PostCorporateProfit(PostCorporateProfitDto _dto)
  2025. {
  2026. #region 参数验证
  2027. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  2028. if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  2029. if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));
  2030. if (_dto.StatisticsType > 2 && _dto.StatisticsType < 1) return Ok(JsonView(false, "请输入有效的StatisticsType参数,1 月份 2 季度"));
  2031. if (_dto.BusinessType > 3 && _dto.BusinessType < 1) return Ok(JsonView(false, "请输入有效的BusinessType参数,1 所有 2 团组 3 会务"));
  2032. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2033. #region 页面操作权限验证
  2034. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2035. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  2036. #endregion
  2037. string sqlWhere = string.Empty;
  2038. //起止时间
  2039. DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");
  2040. DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");
  2041. sqlWhere = string.Format(@$" Where Isdel = 0 ");
  2042. //业务类型
  2043. List<int> groupTypeId = new List<int>();
  2044. if (_dto.BusinessType == 2) //团组
  2045. {
  2046. groupTypeId.AddRange(new List<int>() {
  2047. 38, // 政府团
  2048. 39, // 企业团
  2049. 40, // 散客团
  2050. 1048 // 高校团
  2051. });
  2052. }
  2053. else if (_dto.BusinessType == 3) //会务
  2054. {
  2055. groupTypeId.AddRange(new List<int>() {
  2056. 102, // 未知
  2057. 248, // 非团组
  2058. 302, // 成都-会务活动
  2059. 691, // 四川-会务活动
  2060. 762, // 四川-赛事项目收入
  2061. 1047 // 成都-赛事项目收入
  2062. });
  2063. }
  2064. if (groupTypeId.Count > 0)
  2065. {
  2066. sqlWhere += string.Format(@$" And TeamDid In ({string.Join(',', groupTypeId)})");
  2067. }
  2068. string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");
  2069. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();
  2070. if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));
  2071. List<int> diIds = groupInfos.Select(it => it.Id).ToList();
  2072. List<CorporateProfit> corporateProfits = await CorporateProfit(diIds);
  2073. List<MonthInfo> months = new List<MonthInfo>();
  2074. if (_dto.StatisticsType == 1) //月份
  2075. {
  2076. months = GeneralMethod.GetMonthInfos(Convert.ToInt32(_dto.Year));
  2077. }
  2078. else if (_dto.StatisticsType == 1) //季度
  2079. {
  2080. months = GeneralMethod.GetQuarter(Convert.ToInt32(_dto.Year));
  2081. }
  2082. List<CorporateProfitMonthView> _view = new List<CorporateProfitMonthView>();
  2083. foreach (var item in months)
  2084. {
  2085. DateTime monthBeginDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.BeginDays} 00:00:00");
  2086. DateTime monthEndDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.EndDays} 23:59:59");
  2087. var corporateProfit = corporateProfits.Where(it => it.CreateDt >= monthBeginDt && it.CreateDt <= monthEndDt).ToList();
  2088. _view.Add(new CorporateProfitMonthView()
  2089. {
  2090. Month = item.Month,
  2091. Profit = corporateProfit.Sum(it => it.ReceivedProfit),
  2092. GroupInfos = corporateProfit.OrderBy(it => it.CreateDt).ToList()
  2093. });
  2094. }
  2095. return Ok(JsonView(true, "操作成功!", _view));
  2096. #endregion
  2097. }
  2098. /// <summary>
  2099. /// 计算团组利润
  2100. /// </summary>
  2101. /// <param name="diIds"></param>
  2102. /// <returns></returns>
  2103. private async Task<List<CorporateProfit>> CorporateProfit(List<int> diIds)
  2104. {
  2105. List<CorporateProfit> corporateProfits = new List<CorporateProfit>();
  2106. if (diIds.Count < 1)
  2107. {
  2108. return corporateProfits;
  2109. }
  2110. #region 计算团组利润
  2111. /*
  2112. * 团组报表计算方式
  2113. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  2114. * 应收金额 = 应收表.Sum()
  2115. * 已收金额 = 已收表.Sum()
  2116. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  2117. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  2118. *
  2119. */
  2120. string diIdStr = string.Join(",", diIds);
  2121. string sql = string.Format(@$"Select * From Grp_DelegationInfo Where Isdel = 0 And Id In ({diIdStr})");
  2122. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).ToListAsync();
  2123. #region 费用类型 币种,转账,客户信息
  2124. List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  2125. var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>().Where(it => it.IsDel == 0).ToListAsync();
  2126. #endregion
  2127. foreach (var _diId in diIds)
  2128. {
  2129. List<ExpenditureInfo> expenditureInfos = new List<ExpenditureInfo>();
  2130. #region 团组收入
  2131. /*
  2132. * 应收报表
  2133. */
  2134. decimal frTotalAmount = 0.00M;//应收总金额
  2135. string _frSql = string.Format(@"Select fr.Id,fr.Diid,fr.PriceName,fr.Price,fr.Count,fr.Unit,fr.Currency,
  2136. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  2137. From Fin_ForeignReceivables fr
  2138. Left Join Sys_SetData sd On fr.Currency = sd.Id
  2139. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _diId);
  2140. List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  2141. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  2142. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "应收项", Amount = frTotalAmount });
  2143. /*
  2144. * 已收报表
  2145. */
  2146. decimal prTotalAmount = 0.00M;//已收总金额
  2147. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  2148. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  2149. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  2150. From Fin_ProceedsReceived pr
  2151. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  2152. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  2153. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _diId);
  2154. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  2155. prTotalAmount = _prViews.Sum(it => it.Price);
  2156. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "已收项", Amount = prTotalAmount });
  2157. /*
  2158. * 超支费用
  2159. */
  2160. decimal exTotalAmount = 0.00M;
  2161. string _ecSql = string.Format(@"Select gec.Id As GECId,gec.DiId As GECDiId,gec.PriceName,ccp.PayMoney,sd1.Name As PaymentCurrency,
  2162. ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  2163. sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  2164. From OA2023DB.dbo.Fin_GroupExtraCost gec
  2165. Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  2166. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2167. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2168. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2169. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2170. Where ccp.IsDel = 0 And ccp.CTable = 1015 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ccp.DiId = {0} Order By CreateTime", _diId);
  2171. List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(_ecSql).ToListAsync();
  2172. exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  2173. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "超支费用", Amount = exTotalAmount });
  2174. /*
  2175. * 收款退还
  2176. */
  2177. decimal promTotalAmount = 0.00M;// 收款退还总金额
  2178. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  2179. //删除了 And prom.PriceType = 1
  2180. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  2181. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  2182. prom.PayType As PrPayType,prom.PriceType As PrPriceType,ccp.*,prom.CreateTime As PrCreateTime
  2183. From Fin_PaymentRefundAndOtherMoney prom
  2184. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  2185. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2186. Where prom.IsDel = 0 And prom.PayType = 1 And ccp.CTable = 285
  2187. And ccp.IsAuditGM = 1 And ccp.IsPay = 1
  2188. And prom.DiId = {0} Order By PrCreateTime", _diId);
  2189. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  2190. foreach (var ropItem in _promDatas)
  2191. {
  2192. string thisCueencyCode = "Unknown";
  2193. string thisCueencyName = "Unknown";
  2194. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  2195. if (currency != null)
  2196. {
  2197. thisCueencyCode = currency.Name;
  2198. thisCueencyName = currency.Remark;
  2199. }
  2200. string orbitalPrivateTransferStr = "Unknown";
  2201. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  2202. if (orbitalPrivateTransfer != null)
  2203. {
  2204. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  2205. }
  2206. string payStr = "Unknown";
  2207. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  2208. if (pay != null)
  2209. {
  2210. payStr = pay.Name;
  2211. }
  2212. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  2213. {
  2214. Id = ropItem.Id,
  2215. DiId = ropItem.DIId,
  2216. PriceName = ropItem.PrPriceName,
  2217. PayCurrencyCode = thisCueencyCode,
  2218. PayCurrencyName = thisCueencyName,
  2219. Price = ropItem.PrPrice,
  2220. CNYPrice = ropItem.RMBPrice,
  2221. ThisRate = ropItem.DayRate,
  2222. Payee = ropItem.Payee,
  2223. PayTime = ropItem.AuditGMDate,
  2224. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  2225. PayType = payStr,
  2226. IsPay = ropItem.IsPay,
  2227. Applicant = ropItem.Appliction
  2228. };
  2229. _promView.Add(gsd_PaymentRefund);
  2230. }
  2231. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  2232. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "收款退还", Amount = promTotalAmount });
  2233. #endregion
  2234. #region 团组支出
  2235. GroupExpenditureView _geView = new GroupExpenditureView();
  2236. #region 酒店预定费用
  2237. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  2238. string hotelFeeSql = string.Format(@"Select hr.Id As HrId,hr.DiId As HrDiId,hr.City,hr.HotelName,hr.CheckInDate,hr.CheckOutDate,
  2239. sd1.Name As PaymentCurrency,hr.SingleRoomPrice,hr.SingleRoomCount,hr.DoubleRoomPrice,
  2240. hr.DoubleRoomCount,hr.SuiteRoomPrice,hr.SuiteRoomCount,hr.OtherRoomPrice,hr.OtherRoomCount,
  2241. hr.BreakfastPrice,sd4.Name As BreakfastCurrency,hr.Isoppay,hr.GovernmentRent,
  2242. sd5.Name As GovernmentRentCurrency,hr.CityTax,sd6.Name As CityTaxCurrency,
  2243. ccp.PayMoney,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,
  2244. sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant
  2245. From Grp_HotelReservations hr
  2246. Left Join Grp_CreditCardPayment ccp On hr.Id = ccp.CId
  2247. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2248. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2249. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2250. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2251. Left Join Sys_SetData sd4 On hr.BreakfastCurrency = sd4.Id
  2252. Left Join Sys_SetData sd5 On hr.GovernmentRentCurrency = sd5.Id
  2253. Left Join Sys_SetData sd6 On hr.CityTaxCurrency = sd6.Id
  2254. Where hr.IsDel = 0 And ccp.IsDel = 0 And ccp.CTable = 76 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And hr.DiId = {0}
  2255. Order By CheckInDate Asc", _diId);
  2256. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  2257. decimal HotelCNYTotalPrice = groupHotelFeeViews.Sum(it => it.CNYPrice);
  2258. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "酒店预定", Amount = HotelCNYTotalPrice });
  2259. #endregion
  2260. #region 地接费用
  2261. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  2262. string CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.Area,ctggrc.*,ctggrc.Price As PayMoney,
  2263. sd2.name As PaymentCurrency,ccp.PayPercentage,
  2264. (ctggrc.Price / (ccp.PayPercentage / 100)) As AmountPaid,
  2265. (ctggrc.Price / (ccp.PayPercentage / 100) - ctggrc.Price) As BalancePayment,
  2266. ccp.DayRate,(ctggrc.Price * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  2267. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  2268. From Grp_CarTouristGuideGroundReservations ctggr
  2269. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price,sd2.Name As PriceCurrency,
  2270. cggrc.PriceContent
  2271. From Grp_CarTouristGuideGroundReservationsContent cggrc
  2272. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  2273. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  2274. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  2275. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  2276. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  2277. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  2278. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  2279. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2280. Where ctggr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ctggr.DiId = {0}
  2281. Order By CreateTime", _diId);
  2282. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  2283. decimal CTGGRCNYTotalPrice = groupCTGGRFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  2284. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "地接", Amount = CTGGRCNYTotalPrice });
  2285. #endregion
  2286. #region 机票预订费用
  2287. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  2288. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  2289. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  2290. sd1.Name As PayMoneyCurrency,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  2291. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime
  2292. From Grp_AirTicketReservations atr
  2293. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  2294. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2295. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2296. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2297. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  2298. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2299. Where atr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And atr.DiId = {0} Order By CreateTime", _diId);
  2300. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  2301. decimal AirCNYTotalPrice = groupAirFeeViews.Sum(it => it.CNYPrice);
  2302. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "机票预订", Amount = AirCNYTotalPrice });
  2303. #endregion
  2304. #region 签证费用
  2305. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  2306. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  2307. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  2308. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime
  2309. From Grp_VisaInfo vi
  2310. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  2311. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2312. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2313. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2314. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2315. Where vi.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And vi.DIId = {0} Order By CreateTime", _diId);
  2316. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  2317. decimal VisaCNYTotalPirce = groupVisaFeeViews.Sum(it => it.PayMoney);
  2318. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "签证", Amount = VisaCNYTotalPirce });
  2319. #endregion
  2320. #region 邀请/公务活动 CTable = 81
  2321. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  2322. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  2323. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  2324. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  2325. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  2326. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  2327. From Grp_InvitationOfficialActivities ioa
  2328. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  2329. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2330. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2331. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  2332. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  2333. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  2334. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  2335. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  2336. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2337. Where ioa.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ioa.Diid = {0} Order By CreateTime", _diId);
  2338. groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
  2339. decimal InvitationalCNYTotalPrice = groupInvitationalFeeViews.Sum(it => it.CNYPrice);
  2340. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "邀请/公务活动", Amount = InvitationalCNYTotalPrice });
  2341. #endregion
  2342. #region 保险费用
  2343. List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
  2344. string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.RMBPrice As CNYPrice,
  2345. sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  2346. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
  2347. From Grp_Customers ic
  2348. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  2349. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2350. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2351. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2352. Where ic.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ic.DiId = {0} Order By CreateTime", _diId);
  2353. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  2354. decimal InsuranceCNYTotalPrice = groupInsuranceFeeViews.Sum(it => it.CNYPrice);
  2355. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "保险费用", Amount = InsuranceCNYTotalPrice });
  2356. #endregion
  2357. #region 其他款项费用 98
  2358. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  2359. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  2360. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  2361. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  2362. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  2363. From Grp_DecreasePayments dp
  2364. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  2365. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2366. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2367. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2368. Where dp.IsDel = 0 And ccp.Ctable = 98 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And dp.Diid = {0}
  2369. Order By CreateTime", _diId);
  2370. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  2371. decimal DecreaseCNYTotalPrice = groupDecreaseFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  2372. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "其他款项", Amount = DecreaseCNYTotalPrice });
  2373. #endregion
  2374. #endregion
  2375. /*
  2376. * 团组报表计算方式
  2377. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  2378. * 应收金额 = 应收表.Sum()
  2379. * 已收金额 = 已收表.Sum()
  2380. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  2381. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  2382. *
  2383. */
  2384. decimal _totalExpenditure = 0.00M; //总支出
  2385. decimal _amountReceivable = 0.00M; //应收金额
  2386. decimal _amountReceived = 0.00M; //已收金额
  2387. decimal _receivableProfit = 0.00M; //应收利润
  2388. decimal _receivedProfit = 0.00M; //已收利润
  2389. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  2390. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount;
  2391. _amountReceivable = frTotalAmount;
  2392. _amountReceived = prTotalAmount;
  2393. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  2394. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  2395. var groupInfo = groupInfos.Find(it => it.Id == _diId);
  2396. corporateProfits.Add(new CorporateProfit()
  2397. {
  2398. DiId = _diId,
  2399. TeamName = groupInfo?.TeamName ?? "Unkwnon",
  2400. CreateDt = Convert.ToDateTime(groupInfo?.CreateTime),
  2401. TotalExpenditure = _totalExpenditure,
  2402. ExpenditureItem = expenditureInfos,
  2403. AmountReceivable = _amountReceivable,
  2404. AmountReceived = _amountReceived,
  2405. ReceivableProfit = _receivableProfit,
  2406. ReceivedProfit = _receivedProfit,
  2407. });
  2408. }
  2409. #endregion
  2410. return corporateProfits;
  2411. }
  2412. //未来预测-地区接团/出团量
  2413. //未来预测-地区酒店预订量
  2414. //未来预测-地区机票预订量
  2415. //未来预测-地区车辆预订量
  2416. /// <summary>
  2417. /// (国家/城市)地区预订数量(团,酒店,机票,车辆)
  2418. /// Details
  2419. /// 待添加权限验证
  2420. /// </summary>
  2421. /// <param name="_dto">团组列表请求dto</param>
  2422. /// <returns></returns>
  2423. [HttpPost("PostRegionalBookingsNumber")]
  2424. //[JsonConverter(typeof(DecimalConverter), 2)]
  2425. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2426. public async Task<IActionResult> PostRegionalBookingsNumber(PostRegionalBookingsNumberDto _dto)
  2427. {
  2428. #region 参数验证
  2429. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  2430. //if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  2431. if (_dto.Type > 1 && _dto.Type > 5) return Ok(JsonView(false, "请输入有效的Type参数,1 团 2 酒店 3 机票 4 车辆"));
  2432. if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));
  2433. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2434. #region 页面操作权限验证
  2435. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2436. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  2437. #endregion
  2438. string sqlWhere = string.Empty;
  2439. //起止时间
  2440. DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");
  2441. DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");
  2442. sqlWhere = string.Format(@$" Where Isdel = 0 ");
  2443. string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");
  2444. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();
  2445. if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));
  2446. List<GroupTypeNumberInfo> datas = new List<GroupTypeNumberInfo>();
  2447. foreach (var item in groupInfos)
  2448. {
  2449. var data = await GroupBookingsNumber(_dto.Type, item);
  2450. if (data.TypeItem.Count > 0)
  2451. {
  2452. datas.Add(data);
  2453. }
  2454. }
  2455. //类型处理
  2456. if (_dto.Type == 1)//接团
  2457. {
  2458. List<GroupBookingNumberView> views = new List<GroupBookingNumberView>();
  2459. dynamic groupData = null;
  2460. foreach (var item in datas)
  2461. {
  2462. if (item.TypeItem.Count > 0)
  2463. {
  2464. foreach (var item1 in item.TypeItem)
  2465. {
  2466. if (item1.RegionItem.Count > 0)
  2467. {
  2468. GroupInfo groupInfo = new GroupInfo()
  2469. {
  2470. DiId = item.DiId,
  2471. TeamName = item.GroupName,
  2472. CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",
  2473. ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",
  2474. Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",
  2475. };
  2476. views.Add(new GroupBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, GroupItem = new List<GroupInfo>() { groupInfo } });
  2477. }
  2478. }
  2479. }
  2480. }
  2481. var viewsGroup = views.GroupBy(it => it.Name);
  2482. List<GroupBookingNumberView> _view = new List<GroupBookingNumberView>();
  2483. foreach (var item in viewsGroup)
  2484. {
  2485. List<GroupInfo> infos = new List<GroupInfo>();
  2486. foreach (var item1 in item)
  2487. {
  2488. infos.AddRange(item1.GroupItem);
  2489. }
  2490. infos = infos.OrderByDescending(it => it.CreateTime).ToList(); //
  2491. _view.Add(new GroupBookingNumberView() { Name = item.Key, Number = item.Count(), GroupItem = infos });
  2492. }
  2493. _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();
  2494. return Ok(JsonView(true, "操作成功!", _view, _view.Count));
  2495. }
  2496. else if (_dto.Type == 2)
  2497. {
  2498. List<HotelBookingNumberView> views = new List<HotelBookingNumberView>();
  2499. foreach (var item in datas)
  2500. {
  2501. if (item.TypeItem.Count > 0)
  2502. {
  2503. foreach (var item1 in item.TypeItem)
  2504. {
  2505. if (item1.RegionItem.Count > 0)
  2506. {
  2507. foreach (var item2 in item1.RegionItem)
  2508. {
  2509. GroupInfo groupInfo = new GroupInfo()
  2510. {
  2511. DiId = item.DiId,
  2512. TeamName = item.GroupName,
  2513. CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",
  2514. ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",
  2515. Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",
  2516. };
  2517. List<HotelInfo> hotels = new List<HotelInfo>();
  2518. foreach (var item3 in item2.Data)
  2519. {
  2520. StatisticsHotelInfo statisticsHotelInfos = JsonConvert.DeserializeObject<StatisticsHotelInfo>(JsonConvert.SerializeObject(item3));
  2521. HotelInfo hotelInfo = new HotelInfo()
  2522. {
  2523. HotelName = statisticsHotelInfos.HotelName,
  2524. SingleRoomNum = statisticsHotelInfos.SingleRoomNum,
  2525. DoubleRoomNum = statisticsHotelInfos.DoubleRoomNum,
  2526. SuiteRoomNum = statisticsHotelInfos.SuiteRoomNum,
  2527. OtherRoomNum = statisticsHotelInfos.OtherRoomNum,
  2528. GroupInfo = groupInfo
  2529. };
  2530. hotels.Add(hotelInfo);
  2531. }
  2532. views.Add(new HotelBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, HotelItem = hotels });
  2533. }
  2534. }
  2535. }
  2536. }
  2537. }
  2538. var viewsGroup = views.GroupBy(it => it.Name);
  2539. List<HotelBookingNumberView> _view = new List<HotelBookingNumberView>();
  2540. foreach (var item in viewsGroup)
  2541. {
  2542. List<HotelInfo> infos = new List<HotelInfo>();
  2543. foreach (var item1 in item)
  2544. {
  2545. infos.AddRange(item1.HotelItem);
  2546. }
  2547. _view.Add(new HotelBookingNumberView() { Name = item.Key, Number = item.Count(), HotelItem = infos });
  2548. }
  2549. _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();
  2550. return Ok(JsonView(true, "操作成功!", views, views.Count));
  2551. }
  2552. return Ok(JsonView(false, "操作失败!"));
  2553. #endregion
  2554. }
  2555. /// <summary>
  2556. /// 计算团组ALLType预订数量
  2557. /// </summary>
  2558. /// <param name="diIds"></param>
  2559. /// <returns></returns>
  2560. private async Task<GroupTypeNumberInfo> GroupBookingsNumber(int type, Grp_DelegationInfo info)
  2561. {
  2562. GroupTypeNumberInfo _view = new GroupTypeNumberInfo();
  2563. if (info == null)
  2564. {
  2565. return _view;
  2566. }
  2567. _view.DiId = info.Id;
  2568. _view.GroupName = info.TeamName;
  2569. List<TypeInfo> _types = new List<TypeInfo>();
  2570. #region 计算团组ALLType预订数量
  2571. if (type == 1)
  2572. {
  2573. //接团 客户集团所在地区
  2574. string group_region = string.Empty;
  2575. int group_number = 0;
  2576. if (!string.IsNullOrEmpty(info.ClientUnit))
  2577. {
  2578. var _NewClientData = await _sqlSugar.Queryable<Crm_NewClientData>()
  2579. .Where(it => it.IsDel == 0 && it.Client.Equals(AesEncryptionHelper.Encrypt(info.ClientUnit)))
  2580. .FirstAsync();
  2581. if (_NewClientData != null)
  2582. {
  2583. var regionInfo = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.Id == _NewClientData.Lvlid).FirstAsync();
  2584. if (regionInfo != null)
  2585. {
  2586. group_region = regionInfo.Name.Replace("级", "");
  2587. group_number++;
  2588. }
  2589. }
  2590. }
  2591. if (group_number > 0)
  2592. {
  2593. _types.Add(new TypeInfo() { Id = 1, RegionItem = new List<RegionInfo>() { new RegionInfo() { Name = group_region, Number = group_number } } });
  2594. }
  2595. }
  2596. else if (type == 2)
  2597. {
  2598. //酒店
  2599. var hotelInfos = await _sqlSugar.Queryable<Grp_HotelReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  2600. if (hotelInfos.Count > 0)
  2601. {
  2602. List<RegionInfo> hotelRegions = new List<RegionInfo>();
  2603. foreach (var item in hotelInfos)
  2604. {
  2605. var hotelNumberInfo = new StatisticsHotelInfo()
  2606. {
  2607. HotelName = item.HotelName,
  2608. SingleRoomNum = item.SingleRoomCount,
  2609. DoubleRoomNum = item.DoubleRoomCount,
  2610. SuiteRoomNum = item.SuiteRoomCount,
  2611. OtherRoomNum = item.OtherRoomCount,
  2612. };
  2613. int hotelRoomTotal = item.SingleRoomCount + item.DoubleRoomCount + item.SuiteRoomCount + item.OtherRoomCount;
  2614. if (hotelRegions.Select(it => it.Name).ToList().Contains(item.City))
  2615. {
  2616. RegionInfo hotelRegion = hotelRegions.Find(it => it.Name.Equals(item.City));
  2617. if (hotelRegion != null)
  2618. {
  2619. hotelRegions.Remove(hotelRegion);
  2620. if (hotelRegion.Data.Count > 0)
  2621. {
  2622. hotelRegion.Data.Add(hotelNumberInfo);
  2623. }
  2624. hotelRegion.Number += hotelRoomTotal;
  2625. hotelRegions.Add(hotelRegion);
  2626. }
  2627. }
  2628. else
  2629. {
  2630. hotelRegions.Add(new RegionInfo() { Name = item.City, Number = hotelRoomTotal, Data = new List<dynamic>() { hotelNumberInfo } });
  2631. }
  2632. }
  2633. _types.Add(new TypeInfo() { Id = 2, RegionItem = hotelRegions });
  2634. }
  2635. }
  2636. else if (type == 3)
  2637. {
  2638. //机票
  2639. var airTicketInfos = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
  2640. .LeftJoin<Grp_CreditCardPayment>((atr, ccp) => atr.Id == ccp.CId && ccp.IsPay == 1)
  2641. .LeftJoin<Sys_SetData>((atr, ccp, sd) => atr.CType == sd.Id)
  2642. .Where((atr, ccp, sd) => atr.IsDel == 0 && atr.DIId == info.Id)
  2643. .Select((atr, ccp, sd) => new { atr.ClientNum, atr.CType, ccp.Payee, AirType = sd.Name })
  2644. .ToListAsync();
  2645. if (airTicketInfos.Count > 0)
  2646. {
  2647. List<RegionInfo> airTicketRegions = new List<RegionInfo>();
  2648. foreach (var item in airTicketInfos)
  2649. {
  2650. var ticketClass = new
  2651. {
  2652. TiketClass = item.AirType,
  2653. Number = item.ClientNum
  2654. };
  2655. if (airTicketRegions.Select(it => it.Name).ToList().Contains(item.Payee))
  2656. {
  2657. RegionInfo airTicketRegion = airTicketRegions.Find(it => it.Name.Equals(item.Payee));
  2658. if (airTicketRegion != null)
  2659. {
  2660. airTicketRegions.Remove(airTicketRegion);
  2661. if (airTicketRegion.Data.Count > 0)
  2662. {
  2663. airTicketRegion.Data.Add(ticketClass);
  2664. }
  2665. airTicketRegion.Number += item.ClientNum;
  2666. airTicketRegions.Add(airTicketRegion);
  2667. }
  2668. }
  2669. else
  2670. {
  2671. airTicketRegions.Add(new RegionInfo() { Name = item.Payee, Number = item.ClientNum, Data = new List<dynamic>() { ticketClass } });
  2672. }
  2673. }
  2674. _types.Add(new TypeInfo() { Id = 3, RegionItem = airTicketRegions });
  2675. }
  2676. }
  2677. else if (type == 4)
  2678. {
  2679. //车辆
  2680. var opInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  2681. var opContentInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservationsContent>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  2682. if (opInfos.Count > 0)
  2683. {
  2684. List<RegionInfo> opRegions = new List<RegionInfo>();
  2685. foreach (var item in opInfos)
  2686. {
  2687. int carNum = 0;
  2688. var opContentInfo = opContentInfos.Where(it => it.CTGGRId == item.Id && it.SId == 91).ToList();
  2689. if (opContentInfo.Count > 0)
  2690. {
  2691. foreach (var item1 in opContentInfo)
  2692. {
  2693. if (item1.Price > 0 && item1.Count > 0)
  2694. {
  2695. carNum += item1.Count;
  2696. }
  2697. }
  2698. }
  2699. if (carNum > 0)
  2700. {
  2701. var opData = new
  2702. {
  2703. ServiceCompany = item.ServiceCompany,
  2704. BusName = item.BusName,
  2705. Numbuer = carNum
  2706. };
  2707. if (opRegions.Select(it => it.Name).ToList().Contains(item.Area))
  2708. {
  2709. RegionInfo opRegion = opRegions.Find(it => it.Name.Equals(item.Area));
  2710. if (opRegion != null)
  2711. {
  2712. opRegions.Remove(opRegion);
  2713. if (opRegion.Data.Count > 0)
  2714. {
  2715. opRegion.Data.Add(opData);
  2716. }
  2717. opRegion.Number += carNum;
  2718. opRegions.Add(opRegion);
  2719. }
  2720. }
  2721. else
  2722. {
  2723. opRegions.Add(new RegionInfo() { Name = item.Area, Number = carNum, Data = new List<dynamic>() { opData } });
  2724. }
  2725. }
  2726. }
  2727. _types.Add(new TypeInfo() { Id = 4, RegionItem = opRegions });
  2728. }
  2729. }
  2730. #endregion
  2731. _view.TypeItem = _types;
  2732. return _view;
  2733. }
  2734. #endregion
  2735. #region 市场部销售额
  2736. /// <summary>
  2737. /// 市场部销售额
  2738. /// Init 基础数据(公司/人员/年份/季度/月份)
  2739. /// </summary>
  2740. /// <param name="_dto">市场部销售额请求dto</param>
  2741. /// <returns></returns>
  2742. [HttpPost("PostMarketingSalesInitData")]
  2743. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2744. public async Task<IActionResult> PostMarketingSalesInitData(MarketingSalesInitDataDto _dto)
  2745. {
  2746. #region 参数验证
  2747. MarketingSalesInitDataDtoFoalidator validationRules = new MarketingSalesInitDataDtoFoalidator();
  2748. var validResult = await validationRules.ValidateAsync(_dto);
  2749. if (!validResult.IsValid)
  2750. {
  2751. var errors = new StringBuilder();
  2752. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2753. return Ok(JsonView(false, errors.ToString()));
  2754. }
  2755. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2756. #region 页面操作权限验证
  2757. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2758. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2759. #endregion
  2760. var companyData = _sqlSugar.Queryable<Sys_Company>().Where(it => it.IsDel == 0)
  2761. .Select(it => new { id = it.Id, name = it.CompanyName })
  2762. .ToList();
  2763. List<int> companyIds = companyData.Select(it => it.id).ToList();
  2764. List<int> pickGroupUserIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0)
  2765. .Select(it => it.JietuanOperator)
  2766. .ToList();
  2767. var userData = _sqlSugar.Queryable<Sys_Users>()
  2768. .Where(it => it.IsDel == 0 && (pickGroupUserIds.Contains(it.Id) || it.Id == 21))
  2769. .Select(it => new { id = it.Id, companyId = it.CompanyId, name = it.CnName })
  2770. .ToList();
  2771. companyData.Insert(0, new { id = -1, name = "全部" });
  2772. userData.Insert(0, new { id = -1, companyId = -1, name = "全部" });
  2773. #region 年份
  2774. var dtData = new List<dynamic>();
  2775. int dt = DateTime.Now.Year;
  2776. for (int y = dt; y >= dt - 4; y--)
  2777. {
  2778. //季度
  2779. var quarterDatas = new List<dynamic>();
  2780. quarterDatas.Add(new { name = "全部", beginDt = $"{y}-01-01", endDt = $"{y}-12-31" });
  2781. for (int q = 0; q < 4; q++)
  2782. {
  2783. dynamic quarterData = null;
  2784. if (q == 0)
  2785. {
  2786. var monthDatas = new List<dynamic>();
  2787. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-01-01", endDt = $" {y}-03-31" });
  2788. for (int m = 1; m < 4; m++)
  2789. {
  2790. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  2791. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  2792. }
  2793. //quarterData = new { name = "第一季度", beginDt = $"{y}-01-01", endDt = $" {y}-03-31", monthData = monthDatas };
  2794. quarterData = new { name = "第一季度", monthData = monthDatas };
  2795. }
  2796. else if (q == 1)
  2797. {
  2798. var monthDatas = new List<dynamic>();
  2799. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-04-01", endDt = $"{y}-06-30" });
  2800. for (int m = 4; m < 7; m++)
  2801. {
  2802. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  2803. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  2804. }
  2805. //quarterData = new { name = "第二季度", beginDt = $"{y}-04-01", endDt = $"{y}-06-30", monthData = monthDatas };
  2806. quarterData = new { name = "第二季度", monthData = monthDatas };
  2807. }
  2808. else if (q == 2)
  2809. {
  2810. var monthDatas = new List<dynamic>();
  2811. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-07-01", endDt = $"{y}-09-30" });
  2812. for (int m = 7; m < 10; m++)
  2813. {
  2814. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  2815. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  2816. }
  2817. //quarterData = new { name = "第三季度", beginDt = $"{y}-07-01", endDt = $"{y}-09-30", monthData = monthDatas };
  2818. quarterData = new { name = "第三季度", monthData = monthDatas };
  2819. }
  2820. else if (q == 3)
  2821. {
  2822. var monthDatas = new List<dynamic>();
  2823. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-10-01", endDt = $"{y}-12-31" });
  2824. for (int m = 10; m < 13; m++)
  2825. {
  2826. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  2827. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  2828. }
  2829. //quarterData = new { name = "第四季度", beginDt = $"{y}-10-01", endDt = $"{y}-12-31", monthData = monthDatas };
  2830. quarterData = new { name = "第四季度", monthData = monthDatas };
  2831. }
  2832. quarterDatas.Add(quarterData);
  2833. }
  2834. dtData.Add(new
  2835. {
  2836. year = y,
  2837. //yearData = new { beginDt = $"{y}-01-01", endDt = $"{y}-12-31" },
  2838. quarterData = quarterDatas,
  2839. });
  2840. }
  2841. #endregion
  2842. return Ok(JsonView(true, "操作成功!", new { companyData = companyData, userData = userData, dtData = dtData }));
  2843. #endregion
  2844. }
  2845. private static string ConvertToChinese(int month)
  2846. {
  2847. if (month < 1 || month > 12)
  2848. throw new ArgumentOutOfRangeException(nameof(month), "月份必须在1到12之间。");
  2849. var cultureInfo = new System.Globalization.CultureInfo("zh-CN");
  2850. var dateTimeFormat = cultureInfo.DateTimeFormat;
  2851. return dateTimeFormat.GetMonthName(month);
  2852. }
  2853. /// <summary>
  2854. /// 市场部销售额
  2855. /// 年度/季度/月度 报表(同比)
  2856. /// </summary>
  2857. /// <param name="_dto">市场部销售额请求dto</param>
  2858. /// <returns></returns>
  2859. [HttpPost("PostMarketingSalesStatistics")]
  2860. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2861. public async Task<IActionResult> PostMarketingSalesStatistics_Year(MarketingSalesStatisticsDto _dto)
  2862. {
  2863. #region 参数验证
  2864. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  2865. var validResult = await validationRules.ValidateAsync(_dto);
  2866. if (!validResult.IsValid)
  2867. {
  2868. var errors = new StringBuilder();
  2869. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2870. return Ok(JsonView(false, errors.ToString()));
  2871. }
  2872. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2873. #region 页面操作权限验证
  2874. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2875. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2876. #endregion
  2877. #endregion
  2878. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  2879. return Ok(JsonView(true, "操作成功!", await GroupSales(_dto.CompanyId, _dto.GroupPickupUserId, beginDt, endDt)));
  2880. }
  2881. private async Task<List<int>> GetUserIds(int companyId, int groupPickupUserId)
  2882. {
  2883. //全部人员Id
  2884. //查询所有公司的市场部
  2885. var pickGroupIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0).Select(it => it.JietuanOperator).Distinct().ToList();
  2886. var userIds = new List<int>();
  2887. var userDatas = await _sqlSugar.Queryable<Sys_Users>()
  2888. .InnerJoin<Sys_Company>((u, c) => u.CompanyId == c.Id)
  2889. .Where((u, c) => u.IsDel == 0 && pickGroupIds.Contains(u.Id))
  2890. .Select((u, c) => new { u.Id, u.CompanyId, u.CnName })
  2891. .ToListAsync();
  2892. userIds = userDatas.Select(it => it.Id).ToList();
  2893. if (companyId > 0)
  2894. {
  2895. userIds = userDatas.Where(it => it.CompanyId == companyId).Select(it => it.Id).ToList();
  2896. }
  2897. if (groupPickupUserId > 0)
  2898. {
  2899. userIds = userDatas.Where(it => it.Id == groupPickupUserId).Select(it => it.Id).ToList();
  2900. }
  2901. return userIds;
  2902. }
  2903. /// <summary>
  2904. /// 计算团组销售额
  2905. /// </summary>
  2906. /// <param name="companyId"></param>
  2907. /// <param name="groupPickupUserId"></param>
  2908. /// <param name="beginDt"></param>
  2909. /// <param name="endDt"></param>
  2910. /// <returns></returns>
  2911. private async Task<SalesYOYView> GroupSales(int companyId, int groupPickupUserId, string beginDt, string endDt)
  2912. {
  2913. decimal thisSales = 0.00M, lastSales = 0.00M, yoy = 1.00M;
  2914. var _view = new SalesYOYView();
  2915. List<int> userIds = new List<int>();
  2916. userIds = await GetUserIds(companyId, groupPickupUserId);
  2917. string userSqlWhere = "";
  2918. if (userIds.Count > 0)
  2919. {
  2920. userSqlWhere = string.Format($" And Id IN ({string.Join(',', userIds)})");
  2921. }
  2922. else
  2923. {
  2924. _view = new SalesYOYView
  2925. {
  2926. thisYearSales = "0.00",
  2927. lastYearSales = "0.00",
  2928. };
  2929. return _view;
  2930. }
  2931. string lastBeginDt = Convert.ToDateTime(beginDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss"),
  2932. lastEndDt = Convert.ToDateTime(endDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss");
  2933. // string salesSql = string.Format(@"
  2934. //SELECT
  2935. // 'ThisSales' As [Name],
  2936. // CAST(SUM(Sales) AS decimal(12,2)) As Sales
  2937. //FROM
  2938. // (
  2939. // SELECT di.VisitDate,
  2940. // (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  2941. // WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  2942. // ) AS Sales
  2943. // FROM
  2944. // Grp_DelegationInfo di
  2945. // WHERE di.IsDel = 0 AND di.IsSure = 1
  2946. // AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
  2947. // AND di.VisitDate BETWEEN '{1}' AND '{2}'
  2948. // ) temp
  2949. //Union ALL
  2950. //SELECT
  2951. // 'LastSales' As [Name],
  2952. // CAST(SUM(Sales) AS decimal(12,2)) As Sales
  2953. //FROM
  2954. // (
  2955. // SELECT di.VisitDate,
  2956. // (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  2957. // WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  2958. // ) AS Sales
  2959. // FROM
  2960. // Grp_DelegationInfo di
  2961. // WHERE di.IsDel = 0 AND di.IsSure = 1
  2962. // AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {3})
  2963. // AND di.VisitDate BETWEEN '{4}' AND '{5}'
  2964. // ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
  2965. string salesSql = string.Format(@"
  2966. SELECT
  2967. 'ThisSales' As [Name],
  2968. CAST(SUM(Sales) AS decimal(12,2)) As Sales
  2969. FROM
  2970. (
  2971. SELECT di.VisitDate,
  2972. (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  2973. WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  2974. ) AS Sales
  2975. FROM
  2976. Grp_DelegationInfo di
  2977. WHERE di.IsDel = 0
  2978. AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
  2979. AND di.VisitDate BETWEEN '{1}' AND '{2}'
  2980. ) temp
  2981. Union ALL
  2982. SELECT
  2983. 'LastSales' As [Name],
  2984. CAST(SUM(Sales) AS decimal(12,2)) As Sales
  2985. FROM
  2986. (
  2987. SELECT di.VisitDate,
  2988. (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  2989. WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  2990. ) AS Sales
  2991. FROM
  2992. Grp_DelegationInfo di
  2993. WHERE di.IsDel = 0
  2994. AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {3})
  2995. AND di.IsBid = 0
  2996. AND di.TeamName Not Like '%投标%'
  2997. AND di.VisitDate BETWEEN '{4}' AND '{5}'
  2998. ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
  2999. var salesData = await _sqlSugar.SqlQueryable<SalesView>(salesSql).ToListAsync();
  3000. thisSales = salesData.Where(x => x.Name.Equals("ThisSales")).First()?.Sales ?? 0;
  3001. lastSales = salesData.Where(x => x.Name.Equals("LastSales")).First()?.Sales ?? 0;
  3002. if (lastSales != 0 && thisSales != 0) yoy = (thisSales - lastSales) / lastSales;
  3003. return new SalesYOYView()
  3004. {
  3005. thisYearSales = thisSales.ToString("#0.00"),
  3006. lastYearSales = lastSales.ToString("#0.00"),
  3007. yoy = yoy.ToString("#0.00")
  3008. };
  3009. }
  3010. private class SalesView
  3011. {
  3012. public string Name { get; set; }
  3013. public decimal Sales { get; set; }
  3014. }
  3015. private class SalesYOYView
  3016. {
  3017. public string thisYearSales { get; set; }
  3018. public string lastYearSales { get; set; }
  3019. public string yoy { get; set; } = "1.00";
  3020. }
  3021. /// <summary>
  3022. /// 市场部销售额
  3023. /// 团组列表
  3024. /// </summary>
  3025. /// <param name="_dto">市场部销售额请求dto</param>
  3026. /// <returns></returns>
  3027. [HttpPost("PostMarketingSalesGroupList")]
  3028. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3029. public async Task<IActionResult> PostMarketingSalesGroupList(MarketingSalesGroupListDto _dto)
  3030. {
  3031. #region 参数验证
  3032. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  3033. var validResult = await validationRules.ValidateAsync(_dto);
  3034. if (!validResult.IsValid)
  3035. {
  3036. var errors = new StringBuilder();
  3037. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3038. return Ok(JsonView(false, errors.ToString()));
  3039. }
  3040. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3041. #region 页面操作权限验证
  3042. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3043. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3044. #endregion
  3045. #endregion
  3046. string userSql = "";
  3047. List<int> userIds = new List<int>();
  3048. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  3049. if (userIds.Count <= 0)
  3050. {
  3051. return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  3052. }
  3053. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  3054. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  3055. {
  3056. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  3057. }
  3058. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  3059. // string sql = string.Format(@$"SELECT
  3060. // ROW_NUMBER() OVER (
  3061. // ORDER BY
  3062. // CollectionDays
  3063. // ) AS RowNumber,
  3064. // *
  3065. //FROM
  3066. // (
  3067. // SELECT
  3068. // di.Id,
  3069. // di.TeamName,
  3070. // di.ClientUnit,
  3071. // di.ClientName,
  3072. // di.VisitDate,
  3073. // di.VisitPNumber,
  3074. // di.JietuanOperator,
  3075. // di.VisitEndDate,
  3076. // (
  3077. // SELECT
  3078. // CAST(
  3079. // COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3080. // ) AS GroupSales
  3081. // FROM
  3082. // Fin_ForeignReceivables
  3083. // WHERE
  3084. // IsDel = 0
  3085. // AND di.Id = Diid
  3086. // AND AddingWay IN (0, 1, 2)
  3087. // ) AS GroupSales,
  3088. // u.CnName AS GroupPickupUser,
  3089. // DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  3090. // FROM
  3091. // Grp_DelegationInfo di
  3092. // WITH
  3093. // (NoLock)
  3094. // LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  3095. // WHERE
  3096. // di.Isdel = 0
  3097. // AND di.IsSure = 1 {userSql}
  3098. // AND VisitDate Between '{beginDt}' And '{endDt}'
  3099. // ) Temp ");
  3100. string sql = string.Format(@$"SELECT
  3101. ROW_NUMBER() OVER (
  3102. ORDER BY
  3103. CollectionDays
  3104. ) AS RowNumber,
  3105. *
  3106. FROM
  3107. (
  3108. SELECT
  3109. di.Id,
  3110. di.TeamName,
  3111. di.ClientUnit,
  3112. di.ClientName,
  3113. di.VisitDate,
  3114. di.VisitPNumber,
  3115. di.JietuanOperator,
  3116. di.VisitEndDate,
  3117. (
  3118. SELECT
  3119. CAST(
  3120. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3121. ) AS GroupSales
  3122. FROM
  3123. Fin_ForeignReceivables
  3124. WHERE
  3125. IsDel = 0
  3126. AND di.Id = Diid
  3127. AND AddingWay IN (0, 1, 2)
  3128. ) AS GroupSales,
  3129. u.CnName AS GroupPickupUser,
  3130. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  3131. FROM
  3132. Grp_DelegationInfo di
  3133. WITH
  3134. (NoLock)
  3135. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  3136. WHERE
  3137. di.Isdel = 0
  3138. AND (
  3139. SELECT
  3140. CAST(
  3141. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3142. ) AS GroupSales
  3143. FROM
  3144. Fin_ForeignReceivables
  3145. WHERE
  3146. IsDel = 0
  3147. AND di.Id = Diid
  3148. AND AddingWay IN (0, 1, 2)
  3149. ) > 0
  3150. {userSql}
  3151. AND di.IsBid = 0
  3152. AND di.TeamName Not Like '%投标%'
  3153. AND VisitDate Between '{beginDt}' And '{endDt}'
  3154. ) Temp ");
  3155. RefAsync<int> total = 0;
  3156. var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  3157. return Ok(JsonView(true, "操作成功!", groupData, total));
  3158. }
  3159. /// <summary>
  3160. /// 市场部销售额
  3161. /// 团组列表Excel下载
  3162. /// </summary>
  3163. /// <param name="_dto">市场部销售额请求dto</param>
  3164. /// <returns></returns>
  3165. [HttpPost("PostMarketingSalesGroupExcel")]
  3166. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3167. public async Task<IActionResult> PostMarketingSalesGroupExcel(MarketingSalesGroupListDto _dto)
  3168. {
  3169. #region 参数验证
  3170. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  3171. var validResult = await validationRules.ValidateAsync(_dto);
  3172. if (!validResult.IsValid)
  3173. {
  3174. var errors = new StringBuilder();
  3175. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3176. return Ok(JsonView(false, errors.ToString()));
  3177. }
  3178. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3179. #region 页面操作权限验证
  3180. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3181. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3182. #endregion
  3183. #endregion
  3184. string userSql = "";
  3185. var userIds = new List<int>();
  3186. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  3187. if (userIds.Count <= 0)
  3188. {
  3189. return Ok(JsonView(false));
  3190. }
  3191. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  3192. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  3193. {
  3194. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  3195. }
  3196. string beginDt = $"{_dto.BeginDt} 00:00:00",
  3197. endDt = $"{_dto.EndDt} 23:59:59";
  3198. string sql = string.Format(@$"SELECT
  3199. ROW_NUMBER() OVER (
  3200. ORDER BY
  3201. CollectionDays
  3202. ) AS RowNumber,
  3203. *
  3204. FROM
  3205. (
  3206. SELECT
  3207. di.Id,
  3208. di.TeamName,
  3209. di.ClientUnit,
  3210. di.ClientName,
  3211. di.VisitDate,
  3212. di.VisitPNumber,
  3213. di.JietuanOperator,
  3214. di.VisitEndDate,
  3215. (
  3216. SELECT
  3217. CAST(
  3218. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3219. ) AS GroupSales
  3220. FROM
  3221. Fin_ForeignReceivables
  3222. WHERE
  3223. IsDel = 0
  3224. AND di.Id = Diid
  3225. AND AddingWay IN (0, 1, 2)
  3226. ) AS GroupSales,
  3227. u.CnName AS GroupPickupUser,
  3228. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  3229. FROM
  3230. Grp_DelegationInfo di
  3231. WITH
  3232. (NoLock)
  3233. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  3234. WHERE
  3235. di.Isdel = 0
  3236. AND (
  3237. SELECT
  3238. CAST(
  3239. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3240. ) AS GroupSales
  3241. FROM
  3242. Fin_ForeignReceivables
  3243. WHERE
  3244. IsDel = 0
  3245. AND di.Id = Diid
  3246. AND AddingWay IN (0, 1, 2)
  3247. ) > 0
  3248. {userSql}
  3249. AND di.IsBid = 0
  3250. AND di.TeamName Not Like '%投标%'
  3251. AND VisitDate Between '{beginDt}' And '{endDt}'
  3252. ) Temp ");
  3253. var view = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToListAsync();
  3254. if (view.Count < 1) return Ok(JsonView(false, "暂无数据!"));
  3255. //DataTable dt = GeneralMethod.
  3256. DataTable dt = CommonFun.GetDataTableFromIList(view);
  3257. dt.TableName = $"_view";
  3258. WorkbookDesigner designer = new WorkbookDesigner();
  3259. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/营业额团组报表模板.xls");
  3260. designer.SetDataSource(dt);
  3261. designer.SetDataSource("Total", view.Sum(x => x.GroupSales));
  3262. designer.Workbook.Worksheets[0].Name = "营业额团组报表";
  3263. designer.Process();
  3264. string fileName = $"MarketingSales/{_dto.BeginDt}~{_dto.EndDt}营业额团组报表{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
  3265. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  3266. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  3267. return Ok(JsonView(true, "操作成功", new { url = rst }));
  3268. }
  3269. /// <summary>
  3270. /// 市场部销售额
  3271. /// 客户类型、客户等级 统计
  3272. /// </summary>
  3273. /// <param name="_dto">市场部销售额请求dto</param>
  3274. /// <returns></returns>
  3275. [HttpPost("PostMarketingSalesGroupStatistics")]
  3276. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3277. public async Task<IActionResult> PostMarketingSalesGroupStatistics(MarketingSalesGroupStatisticsDto _dto)
  3278. {
  3279. #region 参数验证
  3280. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  3281. var validResult = await validationRules.ValidateAsync(_dto);
  3282. if (!validResult.IsValid)
  3283. {
  3284. var errors = new StringBuilder();
  3285. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3286. return Ok(JsonView(false, errors.ToString()));
  3287. }
  3288. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3289. #region 页面操作权限验证
  3290. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3291. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3292. #endregion
  3293. #endregion
  3294. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  3295. List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  3296. string userSql = "";
  3297. if (userIds.Count > 0)
  3298. {
  3299. userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
  3300. }
  3301. else
  3302. {
  3303. if (_dto.PortType == 2 || _dto.PortType == 3)
  3304. {
  3305. return Ok(JsonView(true, "操作成功!", new List<object> { }));
  3306. }
  3307. else
  3308. {
  3309. return Ok(JsonView(true, "操作成功!", new
  3310. {
  3311. customerTypeData = new List<object> { },
  3312. clientGradeData = new List<object> { }
  3313. }));
  3314. }
  3315. }
  3316. string sql = "";
  3317. if (_dto.StatisticsType == 1)
  3318. {
  3319. sql = string.Format(@$"Select
  3320. sd.[Name],
  3321. Count(*) As [Count]
  3322. From Grp_DelegationInfo di
  3323. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  3324. Where di.Isdel = 0
  3325. And (
  3326. SELECT
  3327. CAST(
  3328. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3329. ) AS GroupSales
  3330. FROM
  3331. Fin_ForeignReceivables fr
  3332. WHERE
  3333. fr.IsDel = 0
  3334. AND di.Id = fr.Diid
  3335. AND AddingWay IN (0, 1, 2)
  3336. ) > 0
  3337. {userSql}
  3338. AND di.IsBid = 0
  3339. AND di.TeamName Not Like '%投标%'
  3340. And VisitDate Between '{beginDt}' And '{endDt}'
  3341. Group By [Name]
  3342. Order By Count Desc");
  3343. }
  3344. else if (_dto.StatisticsType == 2)
  3345. {
  3346. sql = string.Format(@$"Select
  3347. sd.[Name],
  3348. Count(*) As [Count]
  3349. From Grp_DelegationInfo di
  3350. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  3351. Where di.Isdel = 0
  3352. And (
  3353. SELECT
  3354. CAST(
  3355. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3356. ) AS GroupSales
  3357. FROM
  3358. Fin_ForeignReceivables fr
  3359. WHERE
  3360. fr.IsDel = 0
  3361. AND di.Id = fr.Diid
  3362. AND AddingWay IN (0, 1, 2)
  3363. ) > 0
  3364. {userSql}
  3365. AND di.IsBid = 0
  3366. AND di.TeamName Not Like '%投标%'
  3367. And VisitDate Between '{beginDt}' And '{endDt}'
  3368. Group By [Name]
  3369. Order By Count Desc");
  3370. }
  3371. else return Ok(JsonView(false, "StatisticsType不在可取范围!"));
  3372. if (_dto.PortType == 1)
  3373. {
  3374. string sql1 = string.Format(@$"Select
  3375. sd.[Name],
  3376. Count(*) As [Count]
  3377. From Grp_DelegationInfo di
  3378. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  3379. Where di.Isdel = 0
  3380. And (
  3381. SELECT
  3382. CAST(
  3383. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3384. ) AS GroupSales
  3385. FROM
  3386. Fin_ForeignReceivables fr
  3387. WHERE
  3388. fr.IsDel = 0
  3389. AND di.Id = fr.Diid
  3390. AND AddingWay IN (0, 1, 2)
  3391. ) > 0
  3392. {userSql}
  3393. AND di.IsBid = 0
  3394. AND di.TeamName Not Like '%投标%'
  3395. And VisitDate Between '{beginDt}' And '{endDt}'
  3396. Group By [Name]
  3397. Order By Count Desc");
  3398. var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
  3399. string sql2 = string.Format(@$"Select
  3400. sd.[Name],
  3401. Count(*) As [Count]
  3402. From Grp_DelegationInfo di
  3403. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  3404. Where di.Isdel = 0
  3405. And (
  3406. SELECT
  3407. CAST(
  3408. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3409. ) AS GroupSales
  3410. FROM
  3411. Fin_ForeignReceivables fr
  3412. WHERE
  3413. fr.IsDel = 0
  3414. AND di.Id = fr.Diid
  3415. AND AddingWay IN (0, 1, 2)
  3416. ) > 0
  3417. {userSql}
  3418. AND di.IsBid = 0
  3419. AND di.TeamName Not Like '%投标%'
  3420. And VisitDate Between '{beginDt}' And '{endDt}'
  3421. Group By [Name]
  3422. Order By Count Desc");
  3423. var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
  3424. return Ok(JsonView(true, "操作成功!", new
  3425. {
  3426. customerTypeData = customerTypeData,
  3427. clientGradeData = clientGradeData
  3428. }));
  3429. }
  3430. else if (_dto.PortType == 2 || _dto.PortType == 3)
  3431. {
  3432. var data = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql).ToListAsync();
  3433. return Ok(JsonView(true, "操作成功!", data, data.Count));
  3434. }
  3435. else return Ok(JsonView(false, MsgTips.Port));
  3436. }
  3437. /// <summary>
  3438. /// 市场部销售额
  3439. /// 接单排名
  3440. /// </summary>
  3441. /// <param name="_dto">市场部销售额请求dto</param>
  3442. /// <returns></returns>
  3443. [HttpPost("PostMarketingSalesOrderRanking")]
  3444. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3445. public async Task<IActionResult> PostMarketingSalesOrderRanking(MarketingSalesOrderRankingDto _dto)
  3446. {
  3447. #region 参数验证
  3448. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  3449. var validResult = await validationRules.ValidateAsync(_dto);
  3450. if (!validResult.IsValid)
  3451. {
  3452. var errors = new StringBuilder();
  3453. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3454. return Ok(JsonView(false, errors.ToString()));
  3455. }
  3456. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3457. #region 页面操作权限验证
  3458. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3459. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3460. #endregion
  3461. #endregion
  3462. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  3463. List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  3464. string userSql = "";
  3465. if (userIds.Count > 0)
  3466. {
  3467. userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
  3468. }
  3469. else return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  3470. string sql = string.Format(@$"Select
  3471. ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
  3472. u.CnName As UserName,
  3473. Count(*) As [Count]
  3474. From Grp_DelegationInfo di
  3475. Left Join Sys_Users u On di.JietuanOperator = u.Id
  3476. Where di.Isdel = 0
  3477. AND (
  3478. SELECT
  3479. CAST(
  3480. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3481. ) AS GroupSales
  3482. FROM
  3483. Fin_ForeignReceivables fr
  3484. WHERE
  3485. fr.IsDel = 0
  3486. AND di.Id = fr.Diid
  3487. AND AddingWay IN (0, 1, 2)
  3488. ) > 0
  3489. {userSql}
  3490. AND di.IsBid = 0
  3491. AND di.TeamName Not Like '%投标%'
  3492. AND VisitDate Between '{beginDt}' AND '{endDt}'
  3493. Group By CnName");
  3494. RefAsync<int> total = 0;
  3495. var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  3496. return Ok(JsonView(true, "操作成功!", rankingData, total));
  3497. }
  3498. /// <summary>
  3499. /// 市场部销售额
  3500. /// 团组列表、客户类型、客户等级、接单排名
  3501. /// </summary>
  3502. /// <param name="_dto">市场部销售额请求dto</param>
  3503. /// <returns></returns>
  3504. [HttpPost("PostMarketingSalesGroupItem")]
  3505. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3506. public async Task<IActionResult> PostMarketingSalesGroupItem(MarketingSalesGroupListDto _dto)
  3507. {
  3508. #region 参数验证
  3509. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  3510. var validResult = await validationRules.ValidateAsync(_dto);
  3511. if (!validResult.IsValid)
  3512. {
  3513. var errors = new StringBuilder();
  3514. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3515. return Ok(JsonView(false, errors.ToString()));
  3516. }
  3517. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3518. #region 页面操作权限验证
  3519. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3520. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3521. #endregion
  3522. #endregion
  3523. string userSql = "";
  3524. List<int> userIds = new List<int>();
  3525. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  3526. if (userIds.Count <= 0)
  3527. {
  3528. return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  3529. }
  3530. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  3531. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  3532. {
  3533. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  3534. }
  3535. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  3536. #region 团组List
  3537. string sql = string.Format(@$"SELECT
  3538. ROW_NUMBER() OVER (
  3539. ORDER BY
  3540. CollectionDays
  3541. ) AS RowNumber,
  3542. *
  3543. FROM
  3544. (
  3545. SELECT
  3546. di.Id,
  3547. di.TeamName,
  3548. di.ClientUnit,
  3549. di.ClientName,
  3550. di.VisitDate,
  3551. di.VisitPNumber,
  3552. di.JietuanOperator,
  3553. di.VisitEndDate,
  3554. (
  3555. SELECT
  3556. CAST(
  3557. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3558. ) AS GroupSales
  3559. FROM
  3560. Fin_ForeignReceivables
  3561. WHERE
  3562. IsDel = 0
  3563. AND di.Id = Diid
  3564. AND AddingWay IN (0, 1, 2)
  3565. ) AS GroupSales,
  3566. u.CnName AS GroupPickupUser,
  3567. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  3568. FROM
  3569. Grp_DelegationInfo di
  3570. WITH
  3571. (NoLock)
  3572. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  3573. WHERE
  3574. di.Isdel = 0
  3575. AND (
  3576. SELECT
  3577. CAST(
  3578. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3579. ) AS GroupSales
  3580. FROM
  3581. Fin_ForeignReceivables fr
  3582. WHERE
  3583. fr.IsDel = 0
  3584. AND di.Id = fr.Diid
  3585. AND AddingWay IN (0, 1, 2)
  3586. ) > 0
  3587. {userSql}
  3588. AND di.IsBid = 0
  3589. AND di.TeamName Not Like '%投标%'
  3590. AND VisitDate Between '{beginDt}' And '{endDt}'
  3591. ) Temp ");
  3592. RefAsync<int> total = 0;
  3593. var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  3594. #endregion
  3595. #region 客户类型、客户等级 统计
  3596. string sql1 = string.Format(@$"Select
  3597. sd.[Name],
  3598. Count(*) As [Count]
  3599. From Grp_DelegationInfo di
  3600. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  3601. Where di.Isdel = 0
  3602. And (
  3603. SELECT
  3604. CAST(
  3605. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3606. ) AS GroupSales
  3607. FROM
  3608. Fin_ForeignReceivables fr
  3609. WHERE
  3610. fr.IsDel = 0
  3611. AND di.Id = fr.Diid
  3612. AND AddingWay IN (0, 1, 2)
  3613. ) > 0
  3614. {userSql}
  3615. AND di.IsBid = 0
  3616. AND di.TeamName Not Like '%投标%'
  3617. And VisitDate Between '{beginDt}' And '{endDt}'
  3618. Group By [Name]
  3619. Order By Count Desc");
  3620. var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
  3621. string sql2 = string.Format(@$"Select
  3622. sd.[Name],
  3623. Count(*) As [Count]
  3624. From Grp_DelegationInfo di
  3625. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  3626. Where di.Isdel = 0
  3627. And (
  3628. SELECT
  3629. CAST(
  3630. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3631. ) AS GroupSales
  3632. FROM
  3633. Fin_ForeignReceivables fr
  3634. WHERE
  3635. fr.IsDel = 0
  3636. AND di.Id = fr.Diid
  3637. AND AddingWay IN (0, 1, 2)
  3638. ) > 0
  3639. {userSql}
  3640. AND di.IsBid = 0
  3641. AND di.TeamName Not Like '%投标%'
  3642. And VisitDate Between '{beginDt}' And '{endDt}'
  3643. Group By [Name]
  3644. Order By Count Desc");
  3645. var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
  3646. #endregion
  3647. #region 接单排名
  3648. string sql4 = string.Format(@$"Select
  3649. ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
  3650. u.CnName As UserName,
  3651. Count(*) As [Count]
  3652. From Grp_DelegationInfo di
  3653. Left Join Sys_Users u On di.JietuanOperator = u.Id
  3654. Where di.Isdel = 0
  3655. And (
  3656. SELECT
  3657. CAST(
  3658. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3659. ) AS GroupSales
  3660. FROM
  3661. Fin_ForeignReceivables fr
  3662. WHERE
  3663. fr.IsDel = 0
  3664. AND di.Id = fr.Diid
  3665. AND AddingWay IN (0, 1, 2)
  3666. ) > 0
  3667. {userSql}
  3668. AND di.IsBid = 0
  3669. AND di.TeamName Not Like '%投标%'
  3670. And VisitDate Between '{beginDt}' And '{endDt}'
  3671. Group By CnName");
  3672. var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql4).ToListAsync();
  3673. #endregion
  3674. var viewData = new
  3675. {
  3676. groupData = groupData,
  3677. groupTotal = total,
  3678. customerTypeData = customerTypeData,
  3679. clientGradeData = clientGradeData,
  3680. rankingData = rankingData
  3681. };
  3682. return Ok(JsonView(true, "操作成功!", viewData, total));
  3683. }
  3684. /// <summary>
  3685. /// 市场部销售额
  3686. /// 客户拜访列表
  3687. /// </summary>
  3688. /// <param name="_dto">市场部销售额请求dto</param>
  3689. /// <returns></returns>
  3690. [HttpPost("PostMarketingSalesVCList")]
  3691. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3692. public async Task<IActionResult> PostMarketingSalesVCList(MarketingSalesVCListDto _dto)
  3693. {
  3694. #region 参数验证
  3695. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  3696. var validResult = await validationRules.ValidateAsync(_dto);
  3697. if (!validResult.IsValid)
  3698. {
  3699. var errors = new StringBuilder();
  3700. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3701. return Ok(JsonView(false, errors.ToString()));
  3702. }
  3703. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3704. #region 页面操作权限验证
  3705. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3706. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3707. #endregion
  3708. #endregion
  3709. return Ok(await _visitingClientsRep._List(_dto.PortType, _dto.PageIndex, _dto.PageSize, _dto.DiId, _dto.Search));
  3710. }
  3711. /// <summary>
  3712. /// 市场部销售额
  3713. /// 客户拜访 操作(添加 Or 编辑)
  3714. /// </summary>
  3715. /// <param name="_dto">市场部销售额请求dto</param>
  3716. /// <returns></returns>
  3717. [HttpPost("PostMarketingSalesVCOperate")]
  3718. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3719. public async Task<IActionResult> PostMarketingSalesVCOperate(MarketingSalesVCOperrateDto _dto)
  3720. {
  3721. #region 参数验证
  3722. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  3723. var validResult = await validationRules.ValidateAsync(_dto);
  3724. if (!validResult.IsValid)
  3725. {
  3726. var errors = new StringBuilder();
  3727. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3728. return Ok(JsonView(false, errors.ToString()));
  3729. }
  3730. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3731. #region 页面操作权限验证
  3732. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3733. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3734. #endregion
  3735. #endregion
  3736. return Ok(await _visitingClientsRep._AddOrEdit(_dto));
  3737. }
  3738. /// <summary>
  3739. /// 市场部销售额
  3740. /// 客户拜访 Del
  3741. /// </summary>
  3742. /// <param name="_dto">市场部销售额请求dto</param>
  3743. /// <returns></returns>
  3744. [HttpPost("PostMarketingSalesVCDel")]
  3745. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3746. public async Task<IActionResult> PostMarketingSalesVCDel(MarketingSalesVCDelDto _dto)
  3747. {
  3748. return Ok(await _visitingClientsRep._Del(_dto.Id, _dto.UserId));
  3749. }
  3750. /// <summary>
  3751. /// 市场部销售额
  3752. /// 客户拜访 操作 save
  3753. /// </summary>
  3754. /// <param name="_dto">市场部销售额请求dto</param>
  3755. /// <returns></returns>
  3756. [HttpPost("PostMarketingSalesVCSave")]
  3757. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3758. public async Task<IActionResult> PostMarketingSalesVCSave(MarketingSalesVCSaveDto _dto)
  3759. {
  3760. #region 参数验证
  3761. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  3762. var validResult = await validationRules.ValidateAsync(_dto);
  3763. if (!validResult.IsValid)
  3764. {
  3765. var errors = new StringBuilder();
  3766. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3767. return Ok(JsonView(false, errors.ToString()));
  3768. }
  3769. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3770. #region 页面操作权限验证
  3771. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3772. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3773. #endregion
  3774. #endregion
  3775. return Ok(await _visitingClientsRep._Save(_dto));
  3776. }
  3777. #endregion
  3778. #region 日付报表
  3779. /// <summary>
  3780. /// 日付类型数据
  3781. /// </summary>
  3782. /// <param name="_dto"></param>
  3783. /// <returns></returns>
  3784. [HttpPost("DailypaymentTypeInit")]
  3785. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3786. public async Task<IActionResult> DailypaymentTypeInit(DailypaymentTypeInitDto _dto)
  3787. {
  3788. #region 参数验证
  3789. if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
  3790. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3791. #region 页面操作权限验证
  3792. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3793. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  3794. #endregion
  3795. #endregion
  3796. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  3797. {
  3798. var defaultParentIds = new List<int>() {
  3799. 48,// 人员费用
  3800. 49,// 办公费用
  3801. 50,// 销售费用
  3802. 51,// 其他费用
  3803. 55,// 大运会
  3804. };
  3805. var dailypaymentTypeData = await RedisRepository.RedisFactory
  3806. .CreateRedisRepository()
  3807. .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
  3808. var dailyTypeData = await _sqlSugar.Queryable<DailypaymentParentTypeView>()
  3809. .Includes(x => x.SubData)
  3810. .Where(x => defaultParentIds.Contains(x.Id))
  3811. .ToListAsync();
  3812. dailyTypeData.ForEach(x =>
  3813. {
  3814. x.SubData.ForEach(y =>
  3815. {
  3816. int currId = dailypaymentTypeData.Find(z => z == y.Id);
  3817. y.IsChecked = currId == 0 ? false : true;
  3818. });
  3819. });
  3820. var companyData = await _sqlSugar.Queryable<Sys_Company>()
  3821. .Where(x => x.IsDel == 0)
  3822. .Select(x => new { id = x.Id, name = x.CompanyName })
  3823. .ToListAsync();
  3824. return Ok(JsonView(true, "查询成功!", new { dailyTypeData = dailyTypeData, companyData = companyData }));
  3825. }
  3826. else
  3827. {
  3828. return Ok(JsonView(false, "查询失败"));
  3829. }
  3830. }
  3831. /// <summary>
  3832. /// 日付类型数据 Save
  3833. /// </summary>
  3834. /// <param name="_dto"></param>
  3835. /// <returns></returns>
  3836. [HttpPost("DailypaymentTypeDataSave")]
  3837. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3838. public async Task<IActionResult> DailypaymentTypeDataSave(DailypaymentTypeDataSaveDto _dto)
  3839. {
  3840. #region 参数验证
  3841. if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
  3842. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3843. #region 页面操作权限验证
  3844. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3845. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  3846. #endregion
  3847. #endregion
  3848. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  3849. {
  3850. if (_dto.TypeIds.Count < 1) return Ok(JsonView(false, "请传入需要保存的TypeIds"));
  3851. var res = await RedisRepository.RedisFactory
  3852. .CreateRedisRepository()
  3853. .StringSetAsync(
  3854. key: "DailypaymentTypeData",
  3855. _dto.TypeIds,
  3856. timeout: null);
  3857. if (!res) return Ok(JsonView(false, "操作失败"));
  3858. return Ok(JsonView(true, "操作成功!"));
  3859. }
  3860. else return Ok(JsonView(false, "操作失败"));
  3861. }
  3862. /// <summary>
  3863. /// 日付数据列表
  3864. /// </summary>
  3865. /// <param name="_dto"></param>
  3866. /// <returns></returns>
  3867. [HttpPost("DailypaymentRange")]
  3868. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3869. public async Task<IActionResult> DailypaymentRange(DailypaymentRangeDto _dto)
  3870. {
  3871. #region 参数验证
  3872. var validator = new DailypaymentRangeDtoValidator();
  3873. var validationRes = validator.Validate(_dto);
  3874. if (!validationRes.IsValid)
  3875. {
  3876. StringBuilder sb = new StringBuilder();
  3877. foreach (var item in validationRes.Errors)
  3878. {
  3879. sb.AppendLine(item.ErrorMessage);
  3880. }
  3881. return Ok(JsonView(false, sb.ToString()));
  3882. }
  3883. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3884. #region 页面操作权限验证
  3885. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3886. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  3887. #endregion
  3888. #endregion
  3889. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  3890. {
  3891. DateTime _beginDt = Convert.ToDateTime($"{_dto.BeginDt} 00:00:00"),
  3892. _endDt = Convert.ToDateTime($"{_dto.EndDt} 23:59:59");
  3893. var sqlWhere = string.Format(@" And dfp.CreateTime Between '{0}' And '{1}'", _beginDt, _endDt);
  3894. var dailypaymentTypeData = await RedisRepository.RedisFactory
  3895. .CreateRedisRepository()
  3896. .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
  3897. var sql = string.Format(@"
  3898. Select
  3899. dfp.Id,
  3900. dfp.Instructions,
  3901. dfp.PriceTypeId,
  3902. sd1.Name As FeeType,
  3903. dfp.TransferTypeId,
  3904. sd2.Name As TransferType,
  3905. dfp.SumPrice,
  3906. dfp.FAuditDate,
  3907. dfp.MAuditDate,
  3908. dfp.CompanyId,
  3909. c.CompanyName,
  3910. dfp.CreateUserId As ApplicantId,
  3911. u.CnName As Applicant,
  3912. dfp.CreateTime As ApplicantDt,
  3913. dfp.Instructions+u.CnName As ViewStr
  3914. From Fin_DailyFeePayment dfp
  3915. Left Join Sys_Users u On dfp.CreateUserId = u.Id
  3916. Left Join Sys_SetData sd1 On dfp.TransferTypeId = sd1.Id
  3917. Left Join Sys_Company c On dfp.CompanyId = c.Id
  3918. Left Join Sys_SetData sd2 On dfp.PriceTypeId = sd2.Id
  3919. Where dfp.IsDel = 0 And dfp.IsPay = 1
  3920. ");//--Order By dfp.CreateTime Desc
  3921. if (_dto.Type == 1) //data
  3922. {
  3923. RefAsync<int> total = 0;
  3924. var _view = await _sqlSugar.SqlQueryable<DailyFeePaymentRangeView>(sql)
  3925. .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
  3926. .WhereIF(dailypaymentTypeData.Count > 0,
  3927. x => dailypaymentTypeData.Contains(x.PriceTypeId))
  3928. .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
  3929. .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
  3930. .OrderByDescending(x => x.ApplicantDt)
  3931. .ToPageListAsync(
  3932. pageNumber: _dto.PageIndex,
  3933. pageSize: _dto.PageSize,
  3934. totalNumber: total
  3935. );
  3936. _sqlSugar.ThenMapper(_view, x =>
  3937. {
  3938. x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
  3939. .SetContext(x1 => x1.DFPId, () => x.Id, x)
  3940. .ToList();
  3941. });
  3942. //单独处理
  3943. return Ok(JsonView(true, "操作成功!", new { data = _view, total = _view.Sum(x => x.SumPrice) }, total));
  3944. }
  3945. else if (_dto.Type == 2) //view
  3946. {
  3947. var _view = await _sqlSugar.SqlQueryable<ExcelView>(sql)
  3948. .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
  3949. .WhereIF(dailypaymentTypeData.Count > 0,
  3950. x => dailypaymentTypeData.Contains(x.PriceTypeId))
  3951. .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
  3952. .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
  3953. .OrderByDescending(x => x.ApplicantDt)
  3954. .ToPageListAsync(
  3955. pageNumber: 1,
  3956. pageSize: 99999
  3957. );
  3958. _sqlSugar.ThenMapper(_view, x =>
  3959. {
  3960. x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
  3961. .SetContext(x1 => x1.DFPId, () => x.Id, x)
  3962. .ToList();
  3963. string str = "";
  3964. int index = 1;
  3965. foreach (var item in x.Contents)
  3966. {
  3967. string str1 = $"{index}、费用名称:[{item.PriceName}] 单价:[{item.Price:#0.00}] 数量:[{item.Quantity:#0.00}] 小计:[{item.ItemTotal:#0.00}] 备注:[{item.Remark}]";
  3968. if (index == x.Contents.Count) str += str1;
  3969. else str += str1 + "\r\n";
  3970. index++;
  3971. }
  3972. x.ContentStr = str;
  3973. });
  3974. if (_view.Count > 0)
  3975. {
  3976. //DataTable dt = GeneralMethod.
  3977. DataTable dt = CommonFun.GetDataTableFromIList(_view);
  3978. dt.TableName = $"_view";
  3979. decimal total = _view.Sum(x => x.SumPrice);
  3980. WorkbookDesigner designer = new WorkbookDesigner();
  3981. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/日付报表模板.xls");
  3982. designer.SetDataSource(dt);
  3983. designer.SetDataSource("Total", total);
  3984. designer.Workbook.Worksheets[0].Name = "日付报表";
  3985. designer.Process();
  3986. string fileName = $"DailyPayment/日付报表{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
  3987. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  3988. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  3989. return Ok(JsonView(true, "操作成功", new { url = rst }));
  3990. }
  3991. return Ok(JsonView(true, ",暂无数据"));
  3992. }
  3993. return Ok(JsonView(false, "操作失败"));
  3994. }
  3995. else return Ok(JsonView(false, "操作失败"));
  3996. }
  3997. #endregion
  3998. #region 统计模块
  3999. /// <summary>
  4000. /// 同比
  4001. /// 营业额(今年和去年的)、成本支出(今年和去年的)、毛利润(今年和去年的)
  4002. /// </summary>
  4003. /// <param name="_dto">市场部销售额请求dto</param>
  4004. /// <returns></returns>
  4005. [HttpPost("StatisticsYOY")]
  4006. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4007. public async Task<IActionResult> StatisticsYOY(YOYDto _dto)
  4008. {
  4009. //同比增长率 = (本期 - 同期) / 同期 * 100%;
  4010. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4011. string beginDt = $"{_dto.Year - 1}-01-01 00:00:00",
  4012. endDt = $"{_dto.Year}-12-31 23:59:59";
  4013. string sql = string.Format(@"
  4014. SELECT
  4015. di.Id,
  4016. di.TeamName,
  4017. di.VisitDate,
  4018. YEAR(di.VisitDate) AS YEAR,
  4019. MONTH(di.VisitDate) AS MONTH,
  4020. (
  4021. SELECT
  4022. CAST(SUM(ItemSumPrice * Rate) AS DECIMAL(12, 2))
  4023. FROM
  4024. Fin_ForeignReceivables
  4025. WHERE
  4026. IsDel = 0
  4027. AND AddingWay IN (0, 1, 2)
  4028. AND di.Id = Diid
  4029. ) AS SaleAmount,
  4030. (
  4031. SELECT
  4032. CAST(
  4033. SUM(
  4034. (
  4035. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  4036. )
  4037. ) AS DECIMAL(12, 2)
  4038. )
  4039. FROM
  4040. Grp_AirTicketReservations atr
  4041. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  4042. AND ccp.CTable = 85
  4043. AND atr.Id = ccp.CId
  4044. WHERE
  4045. atr.IsDel = 0
  4046. AND ccp.IsAuditGM = 1
  4047. AND ccp.IsPay = 1
  4048. AND di.Id = atr.DiId
  4049. ) AirTicketAmount,
  4050. (
  4051. SELECT
  4052. CAST(
  4053. SUM(
  4054. (
  4055. ctggr.ServiceQuotedPrice * (ccp.PayPercentage / 100) * ccp.DayRate
  4056. )
  4057. ) AS DECIMAL(12, 2)
  4058. )
  4059. FROM
  4060. Grp_CarTouristGuideGroundReservations ctggr
  4061. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  4062. AND ccp.CTable = 79
  4063. AND ctggr.Id = ccp.CId
  4064. WHERE
  4065. ctggr.IsDel = 0
  4066. AND ccp.IsAuditGM = 1
  4067. AND ccp.IsPay = 1
  4068. AND di.Id = ctggr.DiId
  4069. ) AS OPAmount,
  4070. (
  4071. SELECT
  4072. CAST(SUM((ccp.PayMoney * ccp.DayRate)) AS DECIMAL(12, 2))
  4073. FROM
  4074. Grp_DecreasePayments dp
  4075. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  4076. AND ccp.CTable = 98
  4077. AND dp.Id = ccp.CId
  4078. WHERE
  4079. dp.IsDel = 0
  4080. AND ccp.Ctable = 98
  4081. AND ccp.IsAuditGM = 1
  4082. AND ccp.IsPay = 1
  4083. AND di.Id = dp.Diid
  4084. ) AS OtherCostAmount,
  4085. (
  4086. SELECT
  4087. CAST(
  4088. SUM(
  4089. (
  4090. (ccp.PayMoney * ccp.DayRate)
  4091. )
  4092. ) AS DECIMAL(12, 2)
  4093. )
  4094. FROM
  4095. Grp_VisaInfo vi
  4096. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  4097. AND ccp.CTable = 80
  4098. AND vi.Id = ccp.CId
  4099. WHERE
  4100. vi.IsDel = 0
  4101. AND ccp.IsAuditGM = 1
  4102. AND ccp.IsPay = 1
  4103. AND di.Id = vi.DIId
  4104. ) AS VisaAmount,
  4105. (
  4106. SELECT
  4107. CAST(
  4108. SUM(
  4109. (ccp.PayMoney * ccp.DayRate)
  4110. ) AS DECIMAL(12, 2)
  4111. )
  4112. FROM
  4113. Grp_InvitationOfficialActivities ioa
  4114. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  4115. AND ccp.CTable = 81
  4116. AND ioa.Id = ccp.CId
  4117. WHERE
  4118. ioa.IsDel = 0
  4119. AND ccp.IsAuditGM = 1
  4120. AND ccp.IsPay = 1
  4121. AND di.Id = ioa.Diid
  4122. ) AS OAAmount,
  4123. (
  4124. SELECT
  4125. CAST(
  4126. SUM(
  4127. (ccp.PayMoney * ccp.DayRate)
  4128. ) AS DECIMAL(12, 2)
  4129. )
  4130. FROM
  4131. Grp_Customers ic
  4132. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  4133. AND ccp.CTable = 82
  4134. AND ic.Id = ccp.CId
  4135. WHERE
  4136. ic.IsDel = 0
  4137. AND ccp.IsAuditGM = 1
  4138. AND ccp.IsPay = 1
  4139. AND di.Id = ic.DiId
  4140. ) AS InsureAmount,
  4141. (
  4142. SELECT
  4143. CAST(
  4144. SUM(
  4145. (ccp.PayMoney * ccp.DayRate)
  4146. ) AS DECIMAL(12, 2)
  4147. )
  4148. FROM
  4149. Grp_HotelReservations hr
  4150. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  4151. WHERE
  4152. hr.IsDel = 0
  4153. AND ccp.IsDel = 0
  4154. AND ccp.CTable = 76
  4155. AND ccp.IsAuditGM = 1
  4156. AND ccp.PayMoney <> 0
  4157. AND ccp.IsPay = 1
  4158. AND di.Id = hr.DiId
  4159. ) AS HotelAmount,
  4160. (
  4161. SELECT
  4162. CAST(
  4163. SUM((gec.PriceSum * gec.Coefficient * ccp.DayRate)) AS DECIMAL(12, 2)
  4164. )
  4165. FROM
  4166. OA2023DB.dbo.Fin_GroupExtraCost gec
  4167. INNER JOIN Grp_CreditCardPayment ccp ON gec.Id = ccp.CId
  4168. WHERE
  4169. ccp.IsDel = 0
  4170. AND ccp.CTable = 1015
  4171. AND ccp.IsAuditGM = 1
  4172. AND ccp.IsPay = 1
  4173. AND di.Id = gec.DiId
  4174. ) AS ExcessAmount,
  4175. (
  4176. SELECT
  4177. CAST(
  4178. SUM(
  4179. (ccp.PayMoney * ccp.DayRate)
  4180. ) AS DECIMAL(12, 2)
  4181. )
  4182. FROM
  4183. Fin_PaymentRefundAndOtherMoney prom
  4184. INNER JOIN Grp_CreditCardPayment ccp ON prom.DiId = ccp.DIId
  4185. AND prom.Id = ccp.CId
  4186. WHERE
  4187. prom.IsDel = 0
  4188. AND prom.PayType = 1
  4189. AND ccp.CTable = 285
  4190. AND ccp.IsAuditGM = 1
  4191. AND ccp.IsPay = 1
  4192. AND di.Id = prom.DiId
  4193. ) AS SKTHAmount
  4194. FROM
  4195. Grp_DelegationInfo di
  4196. WHERE
  4197. di.IsDel = 0
  4198. AND di.TeamDid IN (38,39,40,1048)
  4199. AND di.VisitDate BETWEEN '{0}' AND '{1}'
  4200. ORDER BY
  4201. di.VisitDate
  4202. ", beginDt, endDt);
  4203. var data = await _sqlSugar.SqlQueryable<StatisticsYOYView>(sql).ToListAsync();
  4204. var thisYearData = data.Where(x => x.Year == _dto.Year).ToList();
  4205. var lastYearData = data.Where(x => x.Year == (_dto.Year - 1)).ToList();
  4206. List<YOYReturnView> salesYOYData = new List<YOYReturnView>();
  4207. List<YOYReturnView> costYOYData = new List<YOYReturnView>();
  4208. List<YOYReturnView> grossProfitYOYData = new List<YOYReturnView>();
  4209. int monthIndex = 1;
  4210. while (monthIndex < 13)
  4211. {
  4212. var thisMonthData = thisYearData.Where(x => x.Month == monthIndex).ToList();
  4213. var lastMonthData = lastYearData.Where(x => x.Month == monthIndex).ToList();
  4214. var thisGroupIds = thisMonthData.Select(x => x.Id).ToList();
  4215. var lastGroupIds = lastMonthData.Select(x => x.Id).ToList();
  4216. decimal thisSalesAmount = thisMonthData.Sum(x => x?.SaleAmount ?? 0.00M),
  4217. lastSalesAmount = lastMonthData.Sum(x => x?.SaleAmount ?? 0.00M),
  4218. thisCostAmount = thisMonthData.Sum(x => x?.CostAmount ?? 0.00M),
  4219. lastCostAmount = lastMonthData.Sum(x => x?.CostAmount ?? 0.00M),
  4220. thisgrossProfitAmount = thisMonthData.Sum(x => x?.GrossProfitAmount ?? 0.00M),
  4221. lastgrossProfitAmount = lastMonthData.Sum(x => x?.GrossProfitAmount ?? 0.00M);
  4222. salesYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisSalesAmount, lastSalesAmount, thisGroupIds, lastGroupIds));
  4223. costYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisCostAmount, lastCostAmount, thisGroupIds, lastGroupIds));
  4224. grossProfitYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisgrossProfitAmount, lastgrossProfitAmount, thisGroupIds, lastGroupIds));
  4225. monthIndex++;
  4226. }
  4227. salesYOYData = salesYOYData.OrderBy(x => x.Month).ToList();
  4228. costYOYData = costYOYData.OrderBy(x => x.Month).ToList();
  4229. grossProfitYOYData = grossProfitYOYData.OrderBy(x => x.Month).ToList();
  4230. return Ok(JsonView(true, "操作成功!", new { salesYOYData = salesYOYData, costYOYData = costYOYData, grossProfitYOYData = grossProfitYOYData }));
  4231. }
  4232. /// <summary>
  4233. /// 国交数据统计-机票相关
  4234. /// 机票票数、机票到达地、预订平台
  4235. /// </summary>
  4236. /// <param name="_dto"></param>
  4237. /// <returns></returns>
  4238. [HttpPost("StatisticsAirTicket")]
  4239. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4240. public async Task<IActionResult> StatisticsAirTicket(YOYDto _dto)
  4241. {
  4242. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4243. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4244. endDt = $"{_dto.Year}-12-31 23:59:59";
  4245. string sql = string.Format(@"
  4246. SELECT
  4247. atr.DIId,
  4248. atr.FlightsDate,
  4249. YEAR(atr.FlightsDate) AS YEAR,
  4250. MONTH(atr.FlightsDate) AS MONTH,
  4251. atr.CType,
  4252. sd.Name As CTypeName,
  4253. atr.FlightsCity,
  4254. atr.ClientNum,
  4255. atr.ClientName,
  4256. di.TeamName As 'GroupName',
  4257. CASE
  4258. WHEN ccp.Payee = '' OR ccp.Payee IS NULL THEN '未知'
  4259. ELSE ccp.Payee
  4260. END AS 'Platform'
  4261. FROM
  4262. Grp_AirTicketReservations atr
  4263. INNER JOIN Grp_CreditCardPayment ccp ON atr.Id = ccp.CId
  4264. AND ccp.IsDel = 0
  4265. AND CTable = 85
  4266. INNER JOIN Grp_DelegationInfo di ON atr.DIId = di.Id
  4267. LEFT JOIN Sys_SetData sd On atr.CType = sd.Id
  4268. WHERE
  4269. atr.IsDel = 0
  4270. AND di.TeamDid IN (38,39,40,1048)
  4271. AND atr.CType IN(457,458,459,460,574,575)
  4272. AND CHARINDEX('行程单',atr.ClientName) = 0
  4273. AND CHARINDEX('返点',atr.ClientName) = 0
  4274. AND CHARINDEX('-1',atr.ClientName) = 0
  4275. AND ccp.IsPay = 1
  4276. AND atr.FlightsDate BETWEEN '{0}' AND '{1}'
  4277. ORDER BY atr.FlightsDate
  4278. ", beginDt, endDt);
  4279. var data = await _sqlSugar.SqlQueryable<StatisticsAirTicketView>(sql).ToListAsync();
  4280. var groupIds = data.Select(x => x.DIId).ToList();
  4281. //处理城市数据
  4282. var threeCodeData = await _sqlSugar.Queryable<Res_ThreeCode>().Where(x => x.IsDel == 0).ToListAsync();
  4283. //处理团组名称
  4284. var groupNames = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => groupIds.Contains(x.Id)).Select(x => new { Id = x.Id, GroupName = x.TeamName }).ToListAsync();
  4285. data.ForEach(x =>
  4286. {
  4287. string cityName = "";
  4288. if (!string.IsNullOrEmpty(x.FlightsCity))
  4289. {
  4290. string cityCode = x.FlightsCity.Replace("-", "").Replace("/", "");
  4291. int cityNum = cityCode.Length / 3;
  4292. if (cityCode.Length % 3 == 0)
  4293. {
  4294. for (int i = 0; i < cityNum; i++)
  4295. {
  4296. string code = "";
  4297. if (i == 0) code = cityCode.Substring(0, 3);
  4298. else code = cityCode.Substring(i * 3, 3);
  4299. if (!string.IsNullOrEmpty(code))
  4300. {
  4301. if (i == cityNum - 1)
  4302. {
  4303. cityName += threeCodeData.Find(x1 => x1.Three.Equals(code))?.City ?? "";
  4304. }
  4305. else
  4306. {
  4307. var str1 = threeCodeData.Find(x1 => x1.Three.Equals(code))?.City ?? "";
  4308. cityName += str1 + "、";
  4309. }
  4310. }
  4311. }
  4312. }
  4313. }
  4314. x.FlightsCityName = cityName;
  4315. });
  4316. var airTicketNumData = new List<AirTicketReturnView>();
  4317. var airTicketAreaData = new List<AirTicketCityReturnView>();
  4318. int monthIndex = 1;
  4319. while (monthIndex < 13)
  4320. {
  4321. var monthData = data.Where(x => x.Month == monthIndex).ToList();
  4322. //机票票数处理
  4323. int airticket_quantity = monthData.Sum(x => x.ClientNum);
  4324. var linkGroupIds = monthData.Select(x => x.DIId).ToList();
  4325. List<AitTicketInfo> aitTicketInfos = new List<AitTicketInfo>();
  4326. foreach (var item in monthData)
  4327. {
  4328. string groupName = groupNames.Find(x => item.DIId == x.Id)?.GroupName ?? "";
  4329. aitTicketInfos.Add(new AitTicketInfo(item.DIId, groupName, item.ClientNum));
  4330. }
  4331. var aitTicketInfosGroupBy = aitTicketInfos.GroupBy(x => x.Id);
  4332. List<AitTicketInfo> aitTicketInfos1 = new List<AitTicketInfo>();
  4333. foreach (var item in aitTicketInfosGroupBy)
  4334. {
  4335. aitTicketInfos1.Add(new AitTicketInfo(item.Key, item.First().GroupName, item.Sum(x => x.Quantity)));
  4336. }
  4337. aitTicketInfos1 = aitTicketInfos1.OrderBy(x => x.Quantity).ToList();
  4338. linkGroupIds = linkGroupIds.Distinct().ToList();
  4339. airTicketNumData.Add(new AirTicketReturnView(_dto.Year, monthIndex, airticket_quantity, aitTicketInfos1, linkGroupIds));
  4340. //机票城市处理
  4341. //城市处理
  4342. var airTicketCityInfos = new List<string>();
  4343. foreach (var item in monthData)
  4344. {
  4345. if (!string.IsNullOrEmpty(item.FlightsCityName))
  4346. {
  4347. if (item.FlightsCityName.Contains("、"))
  4348. {
  4349. var cityArray = item.FlightsCityName.Split("、").ToList();
  4350. foreach (var item1 in cityArray)
  4351. {
  4352. if (!string.IsNullOrEmpty(item1))
  4353. {
  4354. airTicketCityInfos.Add(item1);
  4355. }
  4356. }
  4357. }
  4358. else
  4359. {
  4360. airTicketCityInfos.Add(item.FlightsCityName);
  4361. }
  4362. }
  4363. }
  4364. //int quantity1 = airTicketCityInfos.Count;
  4365. int city_totalquantity = 0;
  4366. var airTicketCityInfosGroupby = airTicketCityInfos.GroupBy(x => x);
  4367. var airTicketCityInfos1 = new List<AirTicketCityInfo>();
  4368. foreach (var item in airTicketCityInfosGroupby)
  4369. {
  4370. var city_quantity = item.ToList().Count;
  4371. city_totalquantity += city_quantity;
  4372. airTicketCityInfos1.Add(new AirTicketCityInfo(item.Key, city_quantity));
  4373. }
  4374. airTicketCityInfos1 = airTicketCityInfos1.OrderByDescending(x => x.Quantity).ToList();
  4375. airTicketAreaData.Add(new AirTicketCityReturnView(_dto.Year, monthIndex, city_totalquantity, airTicketCityInfos1, linkGroupIds));
  4376. monthIndex++;
  4377. }
  4378. var airTicketPlatformData = data.GroupBy(g => g.Platform)
  4379. .Select(g => new
  4380. {
  4381. platform = g.Key,
  4382. total = g.Sum(x => x.ClientNum),
  4383. children = g.GroupBy(g1 => g1.DIId)
  4384. .Select(g1 => new
  4385. {
  4386. diId = g1.Key,
  4387. groupName = g1.FirstOrDefault()?.GroupName ?? "-",
  4388. total = g1.Sum(x1 => x1.ClientNum),
  4389. children = g1.Select(x1 => new
  4390. {
  4391. //diId = x1.DIId,
  4392. //groupName = x1.GroupName,
  4393. flightsCityName = x1.FlightsCityName,
  4394. total = x1.ClientNum
  4395. })
  4396. .ToList()
  4397. })
  4398. .OrderByDescending(x1 => x1.total)
  4399. .ToList()
  4400. })
  4401. .OrderByDescending(x => x.total)
  4402. .ToList();
  4403. return Ok(JsonView(true, "操作成功!", new
  4404. {
  4405. airTicketNumData = airTicketNumData,
  4406. airTicketAreaData = airTicketAreaData,
  4407. airTicketPlatformData = airTicketPlatformData
  4408. }));
  4409. }
  4410. /// <summary>
  4411. /// 国交数据统计-酒店
  4412. /// 国家TOP10、地区TOP10、预订平台
  4413. /// </summary>
  4414. /// <param name="_dto"></param>
  4415. /// <returns></returns>
  4416. [HttpPost("StatisticsHotel")]
  4417. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4418. public async Task<IActionResult> StatisticsHotel(YOYDto _dto)
  4419. {
  4420. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4421. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4422. endDt = $"{_dto.Year}-12-31 23:59:59";
  4423. string sql = string.Format(@"
  4424. SELECT
  4425. hr.DIId,
  4426. CASE
  4427. WHEN ntf.Country IS NULL THEN '未选择'
  4428. ELSE ntf.Country
  4429. END AS 'Country',
  4430. hr.City,
  4431. hr.HotelName,
  4432. sd.Name AS BookinSite,
  4433. hr.CheckInDate,
  4434. YEAR(hr.CheckInDate) AS YEAR,
  4435. MONTH(hr.CheckInDate) AS MONTH,
  4436. hr.CheckOutDate,
  4437. hr.SingleRoomCount,
  4438. hr.DoubleRoomCount,
  4439. hr.SuiteRoomCount,
  4440. hr.OtherRoomCount
  4441. FROM
  4442. Grp_HotelReservations hr
  4443. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  4444. AND ccp.IsDel = 0
  4445. AND CTable = 76
  4446. INNER JOIN Grp_DelegationInfo di ON hr.DiId = di.Id
  4447. LEFT JOIN Sys_SetData sd ON hr.ReservationsWebsite = sd.Id
  4448. LEFT JOIN Grp_NationalTravelFee ntf ON hr.AreaId = ntf.Id
  4449. WHERE
  4450. hr.IsDel = 0
  4451. AND di.TeamDid IN (38,39,40,1048)
  4452. AND ccp.IsPay = 1
  4453. AND (
  4454. hr.SingleRoomCount > 0
  4455. OR hr.DoubleRoomCount > 0
  4456. OR hr.SuiteRoomCount > 0
  4457. OR hr.OtherRoomCount > 0
  4458. )
  4459. AND CHARINDEX('早餐',hr.HotelName) = 0
  4460. AND CHARINDEX('晚餐',hr.HotelName) = 0
  4461. AND CHARINDEX('升级',hr.HotelName) = 0
  4462. AND CHARINDEX('饮料茶水费',hr.HotelName) = 0
  4463. AND CHARINDEX('城市税',hr.HotelName) = 0
  4464. AND CHARINDEX('退款',hr.HotelName) = 0
  4465. AND CHARINDEX('返现',hr.HotelName) = 0
  4466. AND CHARINDEX('会议室',hr.HotelName) = 0
  4467. AND CHARINDEX('迷你吧消费',hr.HotelName) = 0
  4468. AND CHARINDEX('运费',hr.HotelName) = 0
  4469. AND CHARINDEX('地接',hr.HotelName) = 0
  4470. AND CHARINDEX('损失',hr.HotelName) = 0
  4471. AND CHARINDEX('补差',hr.HotelName) = 0
  4472. AND hr.CheckInDate BETWEEN CONVERT(datetime,'{0}') AND CONVERT(datetime,'{1}')
  4473. ORDER BY
  4474. hr.CheckInDate
  4475. ", beginDt, endDt);
  4476. var data = await _sqlSugar.SqlQueryable<StatisticsHotelView>(sql).ToListAsync();
  4477. var hotelCountryGroupByData = data.GroupBy(x => x.Country)
  4478. .Select(g => new
  4479. {
  4480. Country = g.Key,
  4481. BookingRoomNum = g.Sum(x => x.RoomTotal),
  4482. hotelData = g.GroupBy(x => x.HotelName)
  4483. .Select(g1 => new
  4484. {
  4485. hotelName = g1.Key,
  4486. roomNights = g1.Sum(x => x.RoomNights),
  4487. roomTotal = g1.Sum(x => x.RoomTotal),
  4488. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  4489. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  4490. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  4491. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  4492. })
  4493. .ToList(),
  4494. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  4495. })
  4496. .OrderByDescending(x => x.BookingRoomNum)
  4497. .Take(10)
  4498. .ToList();
  4499. var hotelData = data.OrderBy(x => x.CityStr).ToList();
  4500. var hotelCityGroupByData = data.GroupBy(x => x.CityStr)
  4501. .Select(g => new
  4502. {
  4503. city = g.Key,
  4504. BookingRoomNum = g.Sum(x => x.RoomTotal),
  4505. hotelData = g.GroupBy(x => x.HotelName)
  4506. .Select(g1 => new
  4507. {
  4508. hotelName = g1.Key,
  4509. roomNights = g1.Sum(x => x.RoomNights),
  4510. roomTotal = g1.Sum(x => x.RoomTotal),
  4511. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  4512. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  4513. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  4514. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  4515. })
  4516. .ToList(),
  4517. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  4518. })
  4519. .OrderByDescending(x => x.BookingRoomNum)
  4520. .Take(10)
  4521. .ToList();
  4522. var hotelPlatformGroupByData = data.GroupBy(x => x.BookinSite)
  4523. .Select(g => new
  4524. {
  4525. Platform = g.Key,
  4526. BookingRoomNum = g.Sum(x => x.RoomTotal),
  4527. hotelData = g.GroupBy(x => x.HotelName)
  4528. .Select(g1 => new
  4529. {
  4530. hotelName = g1.Key,
  4531. roomNights = g1.Sum(x => x.RoomNights),
  4532. roomTotal = g1.Sum(x => x.RoomTotal),
  4533. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  4534. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  4535. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  4536. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  4537. })
  4538. .ToList(),
  4539. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  4540. })
  4541. .OrderByDescending(x => x.BookingRoomNum)
  4542. .ToList();
  4543. return Ok(JsonView(true, "操作成功!", new { hotelCountryGroupByData = hotelCountryGroupByData, hotelCityData = hotelCityGroupByData, hotelPlatformData = hotelPlatformGroupByData }));
  4544. }
  4545. /// <summary>
  4546. /// 国交数据统计
  4547. /// 商邀邀请国家数量TOP10
  4548. /// </summary>
  4549. /// <param name="_dto"></param>
  4550. /// <returns></returns>
  4551. [HttpPost("StatisticsInvitation")]
  4552. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4553. public async Task<IActionResult> StatisticsInvitation(YOYDto _dto)
  4554. {
  4555. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4556. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4557. endDt = $"{_dto.Year}-12-31 23:59:59";
  4558. string sql = string.Format(@"
  4559. SELECT
  4560. oa.DiId,
  4561. di.TeamName AS GroupName,
  4562. oa.Country,
  4563. oa.Area AS City,
  4564. oa.Client,
  4565. oa.Date
  4566. FROM
  4567. Res_OfficialActivities oa
  4568. LEFT JOIN Grp_DelegationInfo di ON oa.DiId = di.Id
  4569. WHERE
  4570. oa.IsDel = 0
  4571. AND oa.Date BETWEEN '{0}' AND '{1}'
  4572. ", beginDt, endDt);
  4573. var data = await _sqlSugar.SqlQueryable<StatisticsInvitation_HW>(sql).ToListAsync();
  4574. var groupByCountry = data.GroupBy(x => x.Country)
  4575. .Select(g => new
  4576. {
  4577. Country = g.Key,
  4578. TimeNum = g.Count(),
  4579. LinkGroupIds = g.Select(x => x.GroupName).Distinct().ToList()
  4580. })
  4581. .OrderByDescending(x => x.TimeNum)
  4582. .Take(10)
  4583. .ToList();
  4584. var groupByClient = data.GroupBy(x => x.Client)
  4585. .Select(g => new
  4586. {
  4587. Country = g.Key,
  4588. TimeNum = g.Count(),
  4589. LinkGroupIds = g.Select(x => x.GroupName).Distinct().ToList()
  4590. })
  4591. .OrderByDescending(x => x.TimeNum)
  4592. .Take(10)
  4593. .ToList();
  4594. return Ok(JsonView(true, "操作成功!", new { groupByCountry = groupByCountry, groupByClient = groupByClient }));
  4595. }
  4596. /// <summary>
  4597. /// 会务数据统计
  4598. /// 会务城市TOP10排序
  4599. /// </summary>
  4600. /// <param name="_dto"></param>
  4601. /// <returns></returns>
  4602. [HttpPost("StatisticsConferenceCity")]
  4603. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4604. public async Task<IActionResult> StatisticsConferenceCity(YOYDto _dto)
  4605. {
  4606. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4607. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4608. endDt = $"{_dto.Year}-12-31 23:59:59";
  4609. string sql = string.Format(@"
  4610. SELECT
  4611. ioa.DiId,
  4612. ioa.InviterArea AS Country
  4613. FROM
  4614. Grp_InvitationOfficialActivities ioa
  4615. INNER JOIN Grp_CreditCardPayment ccp ON ioa.Id = ccp.CId
  4616. AND ccp.IsDel = 0
  4617. AND ccp.CTable = 81
  4618. INNER JOIN Grp_DelegationInfo di ON ioa.DiId = di.Id
  4619. WHERE
  4620. ioa.IsDel = 0
  4621. AND di.TeamDid IN (102,248,302,691,762,1047)
  4622. AND ccp.IsPay = 1
  4623. AND ioa.CreateTime BETWEEN '{0}' AND '{1}'
  4624. ", beginDt, endDt);
  4625. var data = await _sqlSugar.SqlQueryable<StatisticsInvitation>(sql).ToListAsync();
  4626. var groupByData = data.GroupBy(x => x.Country)
  4627. .Select(g => new
  4628. {
  4629. Country = g.Key,
  4630. TimeNum = g.Count(),
  4631. LinkGroupIds = g.Select(x => x.DIId).ToList()
  4632. })
  4633. .OrderByDescending(x => x.TimeNum)
  4634. .Take(10)
  4635. .ToList();
  4636. return Ok(JsonView(true, "操作成功!", groupByData));
  4637. }
  4638. /// <summary>
  4639. /// 团组数据统计
  4640. /// 团组合作前十的客户TOP10排序
  4641. /// </summary>
  4642. /// <param name="_dto"></param>
  4643. /// <returns></returns>
  4644. [HttpPost("StatisticsCooperativeCustomer")]
  4645. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4646. public async Task<IActionResult> StatisticsCooperativeCustomer(YOYDto _dto)
  4647. {
  4648. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4649. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4650. endDt = $"{_dto.Year}-12-31 23:59:59";
  4651. DateTime _beginDt = Convert.ToDateTime(beginDt),
  4652. _endDt = Convert.ToDateTime(endDt);
  4653. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  4654. .Where(x => x.IsDel == 0)
  4655. //.Where(x => x.IsSure == 1)
  4656. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  4657. .ToListAsync();
  4658. var groupInfos1 = groupInfos.GroupBy(x => x.ClientName);
  4659. var view = groupInfos1.Select(x =>
  4660. new
  4661. {
  4662. clienName = x.Key,
  4663. clientUnit = x.FirstOrDefault()?.ClientUnit ?? "",
  4664. visitsNum = x.Count()
  4665. }
  4666. )
  4667. .OrderByDescending(x => x.visitsNum)
  4668. .Take(10)
  4669. .ToList();
  4670. return Ok(JsonView(true, "操作成功!", view));
  4671. }
  4672. /// <summary>
  4673. /// 团组数据统计
  4674. /// 已出团客户单位的类型比例图(饼状图-政府团、企业团等)
  4675. /// </summary>
  4676. /// <param name="_dto"></param>
  4677. /// <returns></returns>
  4678. [HttpPost("StatisticsCooperativeCustomerType")]
  4679. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4680. public async Task<IActionResult> StatisticsCooperativeCustomerType(YOYDto _dto)
  4681. {
  4682. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4683. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4684. endDt = $"{_dto.Year}-12-31 23:59:59";
  4685. DateTime _beginDt = Convert.ToDateTime(beginDt),
  4686. _endDt = Convert.ToDateTime(endDt);
  4687. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  4688. .LeftJoin<Sys_SetData>((di, sd) => di.TeamDid == sd.Id)
  4689. .Where((di, sd) => di.IsDel == 0)
  4690. .Where((di, sd) => di.VisitDate >= _beginDt && di.VisitDate <= _endDt)
  4691. .Select((di, sd) => new
  4692. {
  4693. Id = di.Id,
  4694. GroupTypeId = di.TeamDid,
  4695. GroupTypeName = sd.Name,
  4696. })
  4697. .ToListAsync();
  4698. var groupInfos1 = groupInfos.GroupBy(x => x.GroupTypeName);
  4699. var view = groupInfos1.Select(x =>
  4700. new
  4701. {
  4702. groupTypeName = x.Key,
  4703. groupNum = x.Count(),
  4704. linkGroupId = x.Select(x1 => x1.Id).ToList()
  4705. }
  4706. )
  4707. .OrderByDescending(x => x.groupNum)
  4708. .ToList();
  4709. return Ok(JsonView(true, "操作成功!", view));
  4710. }
  4711. /// <summary>
  4712. /// 团组数据统计
  4713. /// 团组数量
  4714. /// </summary>
  4715. /// <param name="_dto"></param>
  4716. /// <returns></returns>
  4717. [HttpPost("StatisticsGroupNum")]
  4718. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4719. public async Task<IActionResult> StatisticsGroupNum(YOYDto _dto)
  4720. {
  4721. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4722. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4723. endDt = $"{_dto.Year}-12-31 23:59:59";
  4724. DateTime _beginDt = Convert.ToDateTime(beginDt),
  4725. _endDt = Convert.ToDateTime(endDt);
  4726. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  4727. .Where(x => x.IsDel == 0)
  4728. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  4729. .Select(x => new StatisticsGroupInfoEntity
  4730. {
  4731. Id = x.Id,
  4732. VisitDate = x.VisitDate,
  4733. Month = x.VisitDate.Month,
  4734. //MonthName = x.VisitDate.ToString("MMM", CultureInfo.GetCultureInfo("zh-CN")),
  4735. VisitPNumber = x.VisitPNumber
  4736. })
  4737. .MergeTable()
  4738. .OrderBy(x => new { x.Month })
  4739. .ToListAsync();
  4740. string groupNumStr = $"年度出访量:{groupInfos.Count}\r\n";
  4741. var groupNumYearData = new
  4742. {
  4743. year = _dto.Year,
  4744. yearName = _dto.Year + "年",
  4745. num = groupInfos.Count,
  4746. linkGroupIds = groupInfos.Select(x => x.Id).ToList()
  4747. };
  4748. var groupNumData = groupInfos.GroupBy(x => x.Quarter)
  4749. .Select(x => new
  4750. {
  4751. Quarter = x.Key,
  4752. QuarterName = x.FirstOrDefault()?.QuarterName ?? "-",
  4753. Num = x.Count(),
  4754. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  4755. })
  4756. .OrderBy(x => x.Quarter)
  4757. .ToList();
  4758. groupNumData.ForEach(x =>
  4759. {
  4760. groupNumStr += $"{x.QuarterName}出访量:{x.Num};";
  4761. });
  4762. var groupNumMonthData = groupInfos.GroupBy(x => x.Month)
  4763. .Select(x => new
  4764. {
  4765. Month = x.Key,
  4766. MonthName = x.FirstOrDefault()?.MonthName ?? "-",
  4767. Num = x.Count(),
  4768. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  4769. })
  4770. .OrderBy(x => x.Month)
  4771. .ToList();
  4772. return Ok(JsonView(true, "操作成功!", new
  4773. {
  4774. yearData = groupNumYearData,
  4775. quarterData = groupNumData,
  4776. monthData = groupNumMonthData,
  4777. remark = groupNumStr
  4778. }));
  4779. }
  4780. /// <summary>
  4781. /// 团组数据统计
  4782. /// 团组人数
  4783. /// </summary>
  4784. /// <param name="_dto"></param>
  4785. /// <returns></returns>
  4786. [HttpPost("StatisticsGroupPeopleNum")]
  4787. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4788. public async Task<IActionResult> StatisticsGroupPeopleNum(YOYDto _dto)
  4789. {
  4790. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4791. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4792. endDt = $"{_dto.Year}-12-31 23:59:59";
  4793. DateTime _beginDt = Convert.ToDateTime(beginDt),
  4794. _endDt = Convert.ToDateTime(endDt);
  4795. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  4796. .Where(x => x.IsDel == 0)
  4797. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  4798. .Select(x => new StatisticsGroupInfoEntity
  4799. {
  4800. Id = x.Id,
  4801. VisitDate = x.VisitDate,
  4802. Month = x.VisitDate.Month,
  4803. VisitPNumber = x.VisitPNumber
  4804. })
  4805. .MergeTable()
  4806. .OrderBy(x => new { x.Month })
  4807. .ToListAsync();
  4808. string groupPeopleNumStr = $"年度出访人数:{groupInfos.Sum(x => x.VisitPNumber)}\r\n";
  4809. var groupPeopleNumYearData = new
  4810. {
  4811. year = _dto.Year,
  4812. yearName = _dto.Year + "年",
  4813. num = groupInfos.Sum(x => x.VisitPNumber),
  4814. linkGroupIds = groupInfos.Select(x => x.Id).ToList()
  4815. };
  4816. var groupPeopleNumData = groupInfos.GroupBy(x => x.Quarter)
  4817. .Select(x => new
  4818. {
  4819. Quarter = x.Key,
  4820. QuarterName = x.FirstOrDefault()?.QuarterName ?? "-",
  4821. Num = x.Sum(x1 => x1.VisitPNumber),
  4822. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  4823. })
  4824. .OrderBy(x => x.Quarter)
  4825. .ToList();
  4826. groupPeopleNumData.ForEach(x =>
  4827. {
  4828. groupPeopleNumStr += $"{x.QuarterName}出访人数:{x.Num};";
  4829. });
  4830. var groupPeopleNumMonthData = groupInfos.GroupBy(x => x.Month)
  4831. .Select(x => new
  4832. {
  4833. Month = x.Key,
  4834. MonthName = x.FirstOrDefault()?.MonthName ?? "-",
  4835. Num = x.Sum(x1 => x1.VisitPNumber),
  4836. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  4837. })
  4838. .OrderBy(x => x.Month)
  4839. .ToList();
  4840. return Ok(JsonView(true, "操作成功!", new
  4841. {
  4842. yearData = groupPeopleNumYearData,
  4843. quarterData = groupPeopleNumData,
  4844. monthData = groupPeopleNumMonthData,
  4845. remark = groupPeopleNumStr
  4846. }));
  4847. }
  4848. /// <summary>
  4849. /// 团组数据统计
  4850. /// OP 成本
  4851. /// </summary>
  4852. /// <param name="_dto"></param>
  4853. /// <returns></returns>
  4854. [HttpPost("StatisticsOP")]
  4855. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4856. public async Task<IActionResult> StatisticsOP(StatisticsOPDto _dto)
  4857. {
  4858. if (_dto.Year < 1) return Ok(JsonView(false, "Year参数错误!"));
  4859. if (_dto.Type < 1 || _dto.Type > 2) return Ok(JsonView(false, "Type参数错误!"));
  4860. int thisYear = _dto.Year, lastYear = _dto.Year - 1;
  4861. string beginDt = $"{lastYear}-01-01 00:00:00",
  4862. endDt = $"{thisYear}-12-31 23:59:59";
  4863. string sql = string.Format(@"
  4864. SELECT
  4865. temp.Id,
  4866. DiId,
  4867. PaymentTime,
  4868. [Year],
  4869. [Quarter],
  4870. [Month],
  4871. Area,
  4872. FeeType,
  4873. sd1.Name AS FeeTypeName,
  4874. FeeSubType,
  4875. sd2.Name AS FeeSubTypeName,
  4876. CONVERT(DECIMAL(12, 2), Price * Qauntity * ExchangeRate) AS Price
  4877. FROM
  4878. (
  4879. SELECT
  4880. ctggr.Id,
  4881. ctggr.DiId,
  4882. ctggr.Area,
  4883. CASE
  4884. WHEN ctggr.PriceType IS NULL THEN 1069
  4885. ELSE ctggr.PriceType
  4886. END AS FeeType,
  4887. ctggrc.SId AS FeeSubType,
  4888. ctggrc.Price,
  4889. CASE
  4890. WHEN ctggrc.Count IS NULL THEN 1
  4891. ELSE ctggrc.Count
  4892. END AS Qauntity,
  4893. ccp.DayRate AS ExchangeRate,
  4894. ctggrc.CreateTime AS PaymentTime,
  4895. YEAR(ctggrc.CreateTime) AS [Year],
  4896. CONVERT(INT,DATENAME(QUARTER, ctggrc.CreateTime)) AS [Quarter],
  4897. MONTH(ctggrc.CreateTime) AS [Month]
  4898. FROM
  4899. Grp_CarTouristGuideGroundReservations ctggr
  4900. INNER JOIN Grp_CarTouristGuideGroundReservationsContent ctggrc ON ctggr.Id = ctggrc.CTGGRId
  4901. AND ctggrc.IsDel = 0
  4902. INNER JOIN Grp_CreditCardPayment ccp ON ctggr.Id = ccp.CId
  4903. AND ccp.CTable = 79
  4904. AND ccp.IsDel = 0
  4905. WHERE
  4906. ctggr.IsDel = 0
  4907. AND ctggrc.SId != 1070 --费用子项筛掉尾款
  4908. AND ctggrc.Price > 0 --筛选真实存在的数据
  4909. AND ccp.IsPay = 1
  4910. ) temp
  4911. LEFT JOIN Sys_SetData sd1 ON FeeType = sd1.Id
  4912. LEFT JOIN Sys_SetData sd2 ON FeeSubType = sd2.Id
  4913. WHERE
  4914. temp.Area NOT LIKE '%尾款%' -- 筛选掉尾款相关信息
  4915. AND temp.FeeType != 1062 --费用类型筛选掉全款和首付款数据
  4916. AND temp.PaymentTime BETWEEN CONVERT(datetime,'{0}') AND CONVERT(datetime,'{1}')
  4917. ORDER BY
  4918. temp.[Year],
  4919. temp.[Quarter],
  4920. temp.[Month]
  4921. ", beginDt, endDt);
  4922. var opInfos = await _sqlSugar.SqlQueryable<StatisticsOP>(sql).ToListAsync();
  4923. //处理地区相关信息
  4924. var countrys = await _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(x => x.IsDel == 0).ToListAsync();
  4925. for (int i = 0; i < opInfos.Count; i++)
  4926. {
  4927. string country = string.Empty, city = string.Empty;
  4928. int dataId = 0;
  4929. bool isCountryId = int.TryParse(opInfos[i].Area, out dataId);
  4930. string[] citySelecter = new string[] { "其他城市", "所有城市" };
  4931. if (isCountryId)
  4932. {
  4933. var countryInfo = countrys.Find(x => x.Id == dataId);
  4934. country = countryInfo?.Country ?? "";
  4935. if (citySelecter.Contains(countryInfo?.City)) city = country;
  4936. else city = countryInfo?.City ?? "";
  4937. }
  4938. else
  4939. {
  4940. var countryInfo1 = countrys.Find(x => opInfos[i].Area.Contains(x.Country));
  4941. if (countryInfo1 != null)
  4942. {
  4943. country = countryInfo1?.Country ?? "";
  4944. city = countryInfo1?.City ?? country;
  4945. var countryInfo2 = countrys.Find(x => opInfos[i].Area.Contains(x.City));
  4946. if (citySelecter.Contains(countryInfo2?.City)) city = country;
  4947. else city = countryInfo2?.City ?? country;
  4948. }
  4949. else
  4950. {
  4951. var countryInfo2 = countrys.Find(x => opInfos[i].Area.Contains(x.City));
  4952. if (countryInfo2 != null)
  4953. {
  4954. country = countryInfo2?.Country ?? "";
  4955. city = countryInfo2?.City ?? "";
  4956. if (citySelecter.Contains(countryInfo2?.City)) city = country;
  4957. }
  4958. }
  4959. }
  4960. opInfos[i].Country = country;
  4961. opInfos[i].City = city;
  4962. }
  4963. var opParentFeeData = new StatisticsOP()._OPParentFeeInfo;
  4964. if (_dto.Type == 1)
  4965. {
  4966. //同比增长率=(本期数-同期数)/ 同期数
  4967. var yearData = opInfos.GroupBy(x => x.ParentFeeName)
  4968. .Select(x => new StatisticsOPYOY(
  4969. feeId: x.FirstOrDefault()?.ParentFeeId ?? 0,
  4970. feeName: x.Key,
  4971. currPeriodFee: x.Where(x => x.Year == thisYear).Sum(x => x.Price),
  4972. samePeriodFee: x.Where(x => x.Year == lastYear).Sum(x => x.Price),
  4973. currPeriodGroupTotal: x.Where(x => x.Year == thisYear).Select(x => x.DiId).Distinct().Count(),
  4974. samePeriodGroupTotal: x.Where(x => x.Year == lastYear).Select(x => x.DiId).Distinct().Count(),
  4975. subFeeData: x.GroupBy(x1 => x1.FeeSubType)
  4976. .Select(x1 => new StatisticsOPSubFeeYOY(
  4977. feeId: x1.Key,
  4978. feeName: x1.FirstOrDefault()?.FeeSubTypeName ?? "",
  4979. currPeriodFee: x1.Where(x1 => x1.Year == thisYear).Sum(x1 => x1.Price),
  4980. samePeriodFee: x1.Where(x1 => x1.Year == lastYear).Sum(x1 => x1.Price),
  4981. currPeriodGroupTotal: x1.Where(x1 => x1.Year == thisYear).Select(x1 => x1.DiId).Distinct().Count(),
  4982. samePeriodGroupTotal: x1.Where(x1 => x1.Year == lastYear).Select(x1 => x1.DiId).Distinct().Count(),
  4983. cityData: x1.GroupBy(x2 => x2.City)
  4984. .Select(x2 => new StatisticsOPCityYOY(
  4985. cityName: x2.Key,
  4986. currPeriodGroupTotal: x2.Where(x2 => x2.Year == thisYear).Select(x2 => x2.DiId).Distinct().Count(),
  4987. samePeriodGroupTotal: x2.Where(x2 => x2.Year == lastYear).Select(x2 => x2.DiId).Distinct().Count(),
  4988. currPeriodFee: x2.Where(x2 => x2.Year == thisYear).Sum(x2 => x2.Price),
  4989. samePeriodFee: x2.Where(x2 => x2.Year == lastYear).Sum(x2 => x2.Price)
  4990. ))
  4991. .ToArray()
  4992. ))
  4993. .ToArray()
  4994. ))
  4995. .OrderBy(x => x.FeeId)
  4996. .ToList();
  4997. var opParentYearIds = yearData.Select(x => x.FeeId).ToList();
  4998. var opParentYearDataSelector = opParentFeeData.Where(x => !opParentYearIds.Contains(x.Id)).ToList();
  4999. if (opParentYearDataSelector.Count > 0)
  5000. {
  5001. foreach (var item in opParentYearDataSelector)
  5002. {
  5003. yearData.Add(
  5004. new StatisticsOPYOY(feeId: item.Id,
  5005. feeName: item.Name,
  5006. currPeriodFee: 0.00M,
  5007. samePeriodFee: 0.00M,
  5008. currPeriodGroupTotal: 0,
  5009. samePeriodGroupTotal: 0,
  5010. subFeeData: new StatisticsOPSubFeeYOY[] { }
  5011. ));
  5012. }
  5013. yearData = yearData.OrderBy(x => x.FeeId).ToList();
  5014. }
  5015. return Ok(JsonView(true, "操作成功!", yearData));
  5016. }
  5017. else if (_dto.Type == 2)
  5018. {
  5019. var monthData = opInfos.GroupBy(x => x.Month)
  5020. .Select(x => new StatisticsOPMonthYOY(
  5021. monthId: x.Key,
  5022. monthName: System.Enum.IsDefined(typeof(MonthEnum), (int)x.Key) ? ((MonthEnum)(int)x.Key).GetEnumDescription() : "",
  5023. feeDatas: x.GroupBy(x1 => x1.ParentFeeId)
  5024. .Select(x1 => new StatisticsOPYOY(
  5025. feeId: x1.Key,
  5026. feeName: x1.FirstOrDefault()?.ParentFeeName ?? "",
  5027. currPeriodFee: x1.Where(x1 => x1.Year == thisYear).Sum(x1 => x1.Price),
  5028. samePeriodFee: x1.Where(x1 => x1.Year == lastYear).Sum(x1 => x1.Price),
  5029. currPeriodGroupTotal: x1.Where(x1 => x1.Year == thisYear).Select(x1 => x1.DiId).Distinct().Count(),
  5030. samePeriodGroupTotal: x1.Where(x1 => x1.Year == lastYear).Select(x1 => x1.DiId).Distinct().Count(),
  5031. subFeeData: x1.GroupBy(x2 => x2.FeeSubType)
  5032. .Select(x2 => new StatisticsOPSubFeeYOY(
  5033. feeId: x2.Key,
  5034. feeName: x2.FirstOrDefault()?.FeeSubTypeName ?? "",
  5035. currPeriodFee: x2.Where(x2 => x2.Year == thisYear).Sum(x2 => x2.Price),
  5036. samePeriodFee: x2.Where(x2 => x2.Year == lastYear).Sum(x2 => x2.Price),
  5037. currPeriodGroupTotal: x2.Where(x2 => x2.Year == thisYear).Select(x2 => x2.DiId).Distinct().Count(),
  5038. samePeriodGroupTotal: x2.Where(x2 => x2.Year == lastYear).Select(x2 => x2.DiId).Distinct().Count(),
  5039. cityData: x2.GroupBy(x3 => x3.City)
  5040. .Select(x3 => new StatisticsOPCityYOY(
  5041. cityName: x3.Key,
  5042. currPeriodFee: x3.Where(x3 => x3.Year == thisYear).Sum(x3 => x3.Price),
  5043. samePeriodFee: x3.Where(x3 => x3.Year == lastYear).Sum(x3 => x3.Price),
  5044. currPeriodGroupTotal: x3.Where(x3 => x3.Year == thisYear).Select(x3 => x3.DiId).Distinct().Count(),
  5045. samePeriodGroupTotal: x3.Where(x3 => x3.Year == lastYear).Select(x3 => x3.DiId).Distinct().Count()
  5046. ))
  5047. .ToArray()
  5048. ))
  5049. .ToArray()
  5050. ))
  5051. .ToArray()
  5052. ))
  5053. //.OrderBy(x => x.MonthId)
  5054. .ToList();
  5055. //1、月份是否足够十二月
  5056. var monthIds = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
  5057. var monthDataIds = monthData.Select(x => x.MonthId).ToArray();
  5058. var newMonthIds = monthIds.Where(x => !monthDataIds.Contains(x)).ToList();
  5059. if (newMonthIds.Count > 0)
  5060. {
  5061. foreach (var item in newMonthIds)
  5062. {
  5063. monthData.Add(new StatisticsOPMonthYOY(
  5064. monthId: item,
  5065. monthName: System.Enum.IsDefined(typeof(MonthEnum), (int)item) ? ((MonthEnum)(int)item).GetEnumDescription() : "",
  5066. feeDatas: Array.Empty<StatisticsOPYOY>()
  5067. ));
  5068. }
  5069. monthData = monthData.OrderBy(x => x.MonthId).ToList();
  5070. }
  5071. //2、费用父类是否足够
  5072. for (int i = 0; i < monthData.Count; i++)
  5073. {
  5074. var month = monthData[i];
  5075. var opParentFeeIds = month.FeeDatas.Select(x => x.FeeId).ToList();
  5076. var opParentFeeDataSelector = opParentFeeData.Where(x => !opParentFeeIds.Contains(x.Id)).ToList();
  5077. if (opParentFeeDataSelector.Count > 0)
  5078. {
  5079. var feeDatas = month.FeeDatas.ToList();
  5080. foreach (var item in opParentFeeDataSelector)
  5081. {
  5082. feeDatas.Add(new StatisticsOPYOY(
  5083. feeId: item.Id,
  5084. feeName: item.Name,
  5085. currPeriodFee: 0.00M,
  5086. samePeriodFee: 0.00M,
  5087. currPeriodGroupTotal: 0,
  5088. samePeriodGroupTotal: 0,
  5089. subFeeData: Array.Empty<StatisticsOPSubFeeYOY>()
  5090. ));
  5091. }
  5092. feeDatas = feeDatas.OrderBy(x => x.FeeId).ToList();
  5093. monthData[i].FeeDatas = feeDatas.ToArray();
  5094. }
  5095. }
  5096. //3、费用子类是否足够
  5097. return Ok(JsonView(true, "操作成功!", monthData));
  5098. }
  5099. return Ok(JsonView(false, "操作失败!"));
  5100. }
  5101. /// <summary>
  5102. /// 团组数据统计
  5103. /// 团组预算/实际成本
  5104. /// </summary>
  5105. /// <param name="_dto"></param>
  5106. /// <returns></returns>
  5107. [HttpPost("StatisticsGroupCost")]
  5108. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5109. public async Task<IActionResult> StatisticsBRCost(StatisticsBRCostDto _dto)
  5110. {
  5111. if (_dto.Year < 1) return Ok(JsonView(false, "Year参数错误!"));
  5112. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5113. endDt = $"{_dto.Year}-12-31 23:59:59";
  5114. var sql = string.Format(@"
  5115. SELECT
  5116. ROW_NUMBER() OVER(
  5117. ORDER BY
  5118. di.VisitDate DESC
  5119. ) AS 'RowNumber',
  5120. di.Id,
  5121. di.TeamName AS 'GroupName',
  5122. di.ClientUnit,
  5123. di.VisitDate,
  5124. di.VisitDays,
  5125. di.VisitPNumber,
  5126. (
  5127. SELECT
  5128. TOP 1 CASE
  5129. ISNUMERIC (gcp.Currency)
  5130. WHEN 1 THEN (
  5131. SELECT
  5132. Name
  5133. FROM
  5134. Sys_SetData sd
  5135. WHERE
  5136. CAST(gcp.Currency AS INT) = sd.Id
  5137. )
  5138. ELSE gcp.Currency
  5139. END AS 'CurrencyCode'
  5140. FROM
  5141. Grp_GroupCostParameter gcp
  5142. WHERE
  5143. gcp.IsDel = 0
  5144. AND gcp.DiId = di.Id
  5145. ) Budget_CurrencyCode,
  5146. --预算币种
  5147. (
  5148. SELECT
  5149. TOP 1 CAST(COALESCE(gcp.Rate, 0.0000) AS DECIMAL(12, 4))
  5150. FROM
  5151. Grp_GroupCostParameter gcp
  5152. WHERE
  5153. gcp.IsDel = 0
  5154. AND gcp.DiId = di.Id
  5155. ) Budget_Rate,
  5156. --预算汇率
  5157. (
  5158. SELECT
  5159. CAST(
  5160. SUM(COALESCE(gcp.VisaCB, 0) * COALESCE(gcp.VisaRS, 0)) AS DECIMAL(12, 2)
  5161. )
  5162. FROM
  5163. Grp_GroupCostParameter gcp
  5164. WHERE
  5165. gcp.IsDel = 0
  5166. AND gcp.DiId = di.id
  5167. ) Budget_VisaAmount,
  5168. -- 预算签证成本
  5169. (
  5170. SELECT
  5171. CAST(
  5172. SUM(
  5173. (
  5174. (ccp.PayMoney * ccp.DayRate)
  5175. )
  5176. ) AS DECIMAL(12, 2)
  5177. )
  5178. FROM
  5179. Grp_VisaInfo vi
  5180. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5181. AND ccp.CTable = 80
  5182. AND vi.Id = ccp.CId
  5183. WHERE
  5184. vi.IsDel = 0
  5185. AND ccp.IsAuditGM = 1
  5186. AND ccp.IsPay = 1
  5187. AND di.Id = vi.DIId
  5188. ) AS Reality_VisaAmount,
  5189. -- 实际签证成本
  5190. (
  5191. SELECT
  5192. CAST(
  5193. SUM(
  5194. COALESCE(gcp.JJCCB, 0) * COALESCE(gcp.JJCRS, 0) + COALESCE(gcp.GWCCB, 0) * COALESCE(gcp.GWCRS, 0) + COALESCE(gcp.TDCCB, 0) * COALESCE(gcp.TDCRS, 0)
  5195. ) AS DECIMAL(12, 2)
  5196. )
  5197. FROM
  5198. Grp_GroupCostParameter gcp
  5199. WHERE
  5200. gcp.IsDel = 0
  5201. AND gcp.DiId = di.id
  5202. ) Budget_AirTicketAmount,
  5203. -- 预算机票成本
  5204. (
  5205. SELECT
  5206. CAST(
  5207. SUM(
  5208. (
  5209. (ccp.PayMoney * ccp.DayRate)
  5210. )
  5211. ) AS DECIMAL(12, 2)
  5212. )
  5213. FROM
  5214. Grp_AirTicketReservations atr
  5215. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5216. AND ccp.CTable = 85
  5217. AND atr.Id = ccp.CId
  5218. WHERE
  5219. atr.IsDel = 0
  5220. AND ccp.IsAuditGM = 1
  5221. AND ccp.IsPay = 1
  5222. AND di.Id = atr.DiId
  5223. ) Reality_AirTicketAmount,
  5224. --实际机票
  5225. (
  5226. SELECT
  5227. CAST(
  5228. SUM(
  5229. 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)
  5230. ) AS DECIMAL(12, 2)
  5231. )
  5232. FROM
  5233. Grp_GroupCostParameter gcp
  5234. WHERE
  5235. gcp.IsDel = 0
  5236. AND gcp.DiId = di.id
  5237. ) Budget_HotelAmount,
  5238. -- 预算酒店成本
  5239. (
  5240. SELECT
  5241. CAST(
  5242. SUM(
  5243. (ccp.PayMoney * ccp.DayRate)
  5244. ) AS DECIMAL(12, 2)
  5245. )
  5246. FROM
  5247. Grp_HotelReservations hr
  5248. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  5249. WHERE
  5250. hr.IsDel = 0
  5251. AND ccp.IsDel = 0
  5252. AND ccp.CTable = 76
  5253. AND ccp.IsAuditGM = 1
  5254. AND ccp.PayMoney <> 0
  5255. AND ccp.IsPay = 1
  5256. AND di.Id = hr.DiId
  5257. ) AS Reality_HotelAmount,
  5258. -- 实际酒店成本
  5259. (
  5260. SELECT
  5261. CAST(
  5262. SUM(COALESCE(gcp.DJCB, 0) * COALESCE(gcp.DJRS, 0)) AS DECIMAL(12, 2)
  5263. )
  5264. FROM
  5265. Grp_GroupCostParameter gcp
  5266. WHERE
  5267. gcp.IsDel = 0
  5268. AND gcp.DiId = di.id
  5269. ) Budget_OPAmount,
  5270. -- 预算 OP
  5271. (
  5272. SELECT
  5273. CAST(
  5274. SUM(
  5275. (
  5276. ctggr.ServiceQuotedPrice * (ccp.PayPercentage / 100) * ccp.DayRate
  5277. )
  5278. ) AS DECIMAL(12, 2)
  5279. )
  5280. FROM
  5281. Grp_CarTouristGuideGroundReservations ctggr
  5282. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  5283. AND ccp.CTable = 79
  5284. AND ctggr.Id = ccp.CId
  5285. WHERE
  5286. ctggr.IsDel = 0
  5287. AND ccp.IsAuditGM = 1
  5288. AND ccp.IsPay = 1
  5289. AND di.Id = ctggr.DiId
  5290. ) AS Reality_OPAmount,
  5291. -- 实际 OP
  5292. (
  5293. SELECT
  5294. CAST(
  5295. SUM(COALESCE(gcp.GWCB, 0) * COALESCE(gcp.GWRS, 0)) AS DECIMAL(12, 2)
  5296. )
  5297. FROM
  5298. Grp_GroupCostParameter gcp
  5299. WHERE
  5300. gcp.IsDel = 0
  5301. AND gcp.DiId = di.id
  5302. ) Budget_OAAmount,
  5303. -- 预算 商邀
  5304. (
  5305. SELECT
  5306. CAST(
  5307. SUM(
  5308. (ccp.PayMoney * ccp.DayRate)
  5309. ) AS DECIMAL(12, 2)
  5310. )
  5311. FROM
  5312. Grp_InvitationOfficialActivities ioa
  5313. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5314. AND ccp.CTable = 81
  5315. AND ioa.Id = ccp.CId
  5316. WHERE
  5317. ioa.IsDel = 0
  5318. AND ccp.IsAuditGM = 1
  5319. AND ccp.IsPay = 1
  5320. AND di.Id = ioa.Diid
  5321. ) AS Reality_OAAmount,
  5322. -- 实际 商邀
  5323. (
  5324. SELECT
  5325. CAST(
  5326. SUM(
  5327. 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)
  5328. ) AS DECIMAL(12, 2)
  5329. )
  5330. FROM
  5331. Grp_GroupCostParameter gcp
  5332. WHERE
  5333. gcp.IsDel = 0
  5334. AND gcp.DiId = di.id
  5335. ) Budget_OtherAmount,
  5336. -- 预算其他成本
  5337. (
  5338. SELECT
  5339. CAST(
  5340. SUM(
  5341. (ccp.PayMoney * ccp.DayRate)
  5342. ) AS DECIMAL(12, 2)
  5343. )
  5344. FROM
  5345. Grp_Customers ic
  5346. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5347. AND ccp.CTable = 82
  5348. AND ic.Id = ccp.CId
  5349. WHERE
  5350. ic.IsDel = 0
  5351. AND ccp.IsAuditGM = 1And ccp.IsPay = 1
  5352. AND di.Id = ic.DiId
  5353. ) AS Reality_InsureAmount,
  5354. -- 实际保险成本
  5355. (
  5356. SELECT
  5357. CAST(SUM((ccp.PayMoney * ccp.DayRate)) AS DECIMAL(12, 2))
  5358. FROM
  5359. Grp_DecreasePayments dp
  5360. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5361. AND ccp.CTable = 98
  5362. AND dp.Id = ccp.CId
  5363. WHERE
  5364. dp.IsDel = 0
  5365. AND ccp.Ctable = 98
  5366. AND ccp.IsAuditGM = 1
  5367. AND ccp.IsPay = 1
  5368. AND di.Id = dp.Diid
  5369. ) AS Reality_OtherCostAmount -- 实际其他款项
  5370. FROM
  5371. Grp_DelegationInfo di
  5372. WHERE
  5373. di.IsDel = 0
  5374. AND di.IsBid = 0
  5375. --AND di.TeamDid IN (38, 39, 40, 1048)
  5376. AND di.VisitDate BETWEEN '{0}' AND '{1}'
  5377. ", beginDt, endDt);
  5378. if (!string.IsNullOrEmpty(_dto.Search))
  5379. {
  5380. sql += $"AND di.TeamName Like '%{_dto.Search}%'";
  5381. }
  5382. var view = await _sqlSugar.SqlQueryable<StatisticsBRCostView>(sql).ToListAsync();
  5383. view = view.Where(x => !x.GroupName.Contains("投标") && x.RealityAmount > 0).OrderByDescending(x => x.Id).ToList();
  5384. var total = view.Count;
  5385. var toSkip = (_dto.PageIndex - 1) * _dto.PageSize;
  5386. var data = view.Skip(toSkip).Take(_dto.PageSize).ToList();
  5387. if (data.Count > 0)
  5388. {
  5389. var diIds = data.Select(x => x.Id).ToList();
  5390. var currencyData = await _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0 && x.STid == 66).ToListAsync();
  5391. var ccpData = await _sqlSugar.Queryable<Grp_CreditCardPayment>()
  5392. .Where(x => x.IsDel == 0 &&
  5393. diIds.Contains(x.DIId) &&
  5394. x.IsPay == 1 &&
  5395. x.IsAuditGM == 1
  5396. )
  5397. .ToListAsync();
  5398. for (int i = 0; i < data.Count; i++)
  5399. {
  5400. var info = data[i];
  5401. info.RowNumber = i + 1;
  5402. #region 1:签证 80
  5403. var visaDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 80).ToList();
  5404. var visaDesc = "-";
  5405. if (visaDatas.Count > 0)
  5406. {
  5407. visaDesc = $"实际币种金额:";
  5408. foreach (var visa in visaDatas)
  5409. {
  5410. var currencyCode = currencyData.Find(x => x.Id == visa.PaymentCurrency)?.Name;
  5411. visaDesc += $"{visa.PayMoney} {currencyCode} 汇率:{visa.DayRate.ToString("#0.0000")};";
  5412. }
  5413. }
  5414. info.Reality_VisaAmountDesc = visaDesc;
  5415. #endregion
  5416. #region 2:机票 85
  5417. var airDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 85).ToList();
  5418. var airDesc = "-";
  5419. if (airDatas.Count > 0)
  5420. {
  5421. airDesc = $"实际币种金额:";
  5422. foreach (var air in airDatas)
  5423. {
  5424. var currencyCode = currencyData.Find(x => x.Id == air.PaymentCurrency)?.Name;
  5425. airDesc += $"{air.PayMoney} {currencyCode} 汇率:{air.DayRate.ToString("#0.0000")};";
  5426. }
  5427. }
  5428. info.Reality_AirTicketAmountDesc = airDesc;
  5429. #endregion
  5430. #region 3:酒店 76
  5431. var hotelDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 76 && x.PayMoney != 0).ToList();
  5432. var hotelDesc = "-";
  5433. if (hotelDatas.Count > 0)
  5434. {
  5435. hotelDesc = $"实际币种金额:";
  5436. foreach (var hotel in hotelDatas)
  5437. {
  5438. var currencyCode = currencyData.Find(x => x.Id == hotel.PaymentCurrency)?.Name;
  5439. hotelDesc += $"{hotel.PayMoney} {currencyCode} 汇率:{hotel.DayRate.ToString("#0.0000")};";
  5440. }
  5441. }
  5442. info.Reality_HotelAmountDesc = hotelDesc;
  5443. #endregion
  5444. #region 4:OP 79
  5445. var opDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 79 && x.PayMoney != 0).ToList();
  5446. var opDesc = "-";
  5447. if (opDatas.Count > 0)
  5448. {
  5449. opDesc = $"实际币种金额;";
  5450. foreach (var op in opDatas)
  5451. {
  5452. var currencyCode = currencyData.Find(x => x.Id == op.PaymentCurrency)?.Name;
  5453. opDesc += $"{op.PayMoney} {currencyCode} 汇率:{op.DayRate.ToString("#0.0000")};";
  5454. }
  5455. }
  5456. info.Reality_OPAmountDesc = opDesc;
  5457. #endregion
  5458. #region 5:商邀 81
  5459. var oaDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 81 && x.PayMoney != 0).ToList();
  5460. var oaDesc = "-";
  5461. if (oaDatas.Count > 0)
  5462. {
  5463. oaDesc = $"实际币种金额:";
  5464. foreach (var oa in oaDatas)
  5465. {
  5466. var currencyCode = currencyData.Find(x => x.Id == oa.PaymentCurrency)?.Name;
  5467. oaDesc += $"{oa.PayMoney} {currencyCode} 汇率:{oa.DayRate.ToString("#0.0000")};";
  5468. }
  5469. }
  5470. info.Reality_OAAmountDesc = oaDesc;
  5471. #endregion
  5472. #region 6:其他款项(保险 82、其他款项 98)
  5473. var cTables = new List<int>() { 82, 98 };
  5474. var otherDatas = ccpData.Where(x => x.DIId == info.Id && cTables.Contains(x.CTable) && x.PayMoney != 0).ToList();
  5475. var otherDesc = "-";
  5476. if (otherDatas.Count > 0)
  5477. {
  5478. otherDesc = $"实际币种金额:";
  5479. foreach (var other in otherDatas)
  5480. {
  5481. var currencyCode = currencyData.Find(x => x.Id == other.PaymentCurrency)?.Name;
  5482. otherDesc += $"{other.PayMoney} {currencyCode} 汇率:{other.DayRate.ToString("#0.0000")};";
  5483. }
  5484. }
  5485. info.Reality_OtherCostAmountDesc = otherDesc;
  5486. #endregion
  5487. }
  5488. }
  5489. var briefData = _mapper.Map<List<StatisticsBRCostBriefView>>(data);
  5490. return Ok(JsonView(briefData, total));
  5491. }
  5492. /// <summary>
  5493. /// 团组数据统计
  5494. /// 当前时间团组所在城市
  5495. /// </summary>
  5496. /// <param name="dto"></param>
  5497. /// <returns></returns>
  5498. [HttpPost("StatisticsNowCityOfGroup")]
  5499. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5500. public async Task<IActionResult> StatisticsNowCityOfGroup(StatisticsNowCityOfGroupDto dto)
  5501. {
  5502. var dt1 = GetCountryOrCityCurrentDateTime("美国", "纽约");
  5503. var dt2 = GetCountryOrCityCurrentDateTime("日本", "东京");
  5504. var dt3 = GetCountryOrCityCurrentDateTime("加拿大", "多伦多");
  5505. var dt4 = GetCountryOrCityCurrentDateTime("韩国", "首尔");
  5506. var dt5 = GetCountryOrCityCurrentDateTime("美国", "华盛顿");
  5507. var dt6 = GetCountryOrCityCurrentDateTime("印度", "孟买");
  5508. if (!SharingStaticData.PortTypes.Contains(dto.PortType)) return Ok(JsonView(false, MsgTips.Port));
  5509. var nowLable = DateTime.Now.ToString("yyyy-MM-dd");
  5510. var sql = string.Format(@"SELECT * FROM Grp_DelegationInfo WHERE ISdel = 0 AND '{0}' BETWEEN VisitStartDate AND VisitEndDate", nowLable);
  5511. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql)
  5512. .Select(x => new { x.Id, x.VisitCountry, x.TeamName,x.ClientUnit, x.VisitStartDate, x.VisitEndDate }).
  5513. ToListAsync();
  5514. if (!groupInfos.Any()) return Ok(JsonView(false, "今日暂无团组出行!"));
  5515. var groupIds = groupInfos.Select(x => x.Id).ToList();
  5516. //三字码
  5517. var threeDatas = await _sqlSugar.Queryable<Res_ThreeCode>().Where(x => x.IsDel == 0).ToListAsync();
  5518. //国家
  5519. var countryDatas = await _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(x => x.IsDel == 0 && !string.IsNullOrEmpty(x.Country) && !string.IsNullOrEmpty(x.City)).ToListAsync();
  5520. //公务
  5521. var OADatas = await _sqlSugar
  5522. .Queryable<Res_OfficialActivities>().Where(x => x.IsDel == 0 && groupIds.Contains(x.DiId) && !string.IsNullOrEmpty(x.Country) && !string.IsNullOrEmpty(x.Area))
  5523. .ToListAsync();
  5524. //酒店
  5525. var hotelDatas = await _sqlSugar.Queryable<Grp_HotelReservations>()
  5526. .LeftJoin<Grp_NationalTravelFee>((hr, ntf) => hr.AreaId == ntf.Id)
  5527. .Where((hr, ntf) => hr.IsDel == 0 && groupIds.Contains(hr.DiId))
  5528. .Select((hr, ntf) => new {
  5529. hr.DiId,
  5530. hr.AreaId,
  5531. hr.HotelName,
  5532. hr.CheckInDate,
  5533. hr.CheckOutDate,
  5534. hr.HotelAddress,
  5535. ntf.Country,
  5536. ntf.City
  5537. })
  5538. .ToListAsync();
  5539. //机票
  5540. /*
  5541. *舱位类型
  5542. *457 头等舱
  5543. *458 公务舱
  5544. *459 超经舱
  5545. *460 经济舱
  5546. *461 退票
  5547. *565 其他
  5548. *574 长段公务舱
  5549. *575 短途经济舱
  5550. *1023 行程单打印费
  5551. *1024 选座费
  5552. */
  5553. var classTypes = new int[] { 457, 458, 459, 460, 574, 575 };
  5554. var airDatas = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
  5555. .Where(atr => atr.IsDel == 0 && groupIds.Contains(atr.DIId) && classTypes.Contains(atr.CType))
  5556. .ToListAsync();
  5557. string[] characters = { "|", "、" };
  5558. var result = new List<StatisticsNowCityOfGroupResultView>();
  5559. foreach (var item in groupInfos)
  5560. {
  5561. string statusText = string.Empty,
  5562. address = string.Empty;
  5563. var countrys = item.VisitCountry;
  5564. if (string.IsNullOrEmpty(countrys)) continue;
  5565. var currCountrys = item.VisitCountry.Split(characters, StringSplitOptions.RemoveEmptyEntries);
  5566. var stutus = true;
  5567. #region 公务
  5568. var currOADatas = OADatas.Where(x => x.DiId == item.Id && currCountrys.Any(c => x.Country.Contains(c))).ToList();
  5569. if (currOADatas.Any())
  5570. {
  5571. foreach (var curr_oa in currOADatas)
  5572. {
  5573. var localTime = GetCountryOrCityCurrentDateTime(curr_oa.Country, curr_oa.Area);
  5574. if (localTime == null) continue;
  5575. var currOaDtStart = Convert.ToDateTime($"{Convert.ToDateTime(curr_oa.Date).ToString("yyyy-MM-dd")} {curr_oa.Time}");
  5576. var currOaDtEnd = currOaDtStart.AddHours(2);
  5577. var currTimeZoneStatus = localTime >= currOaDtStart && localTime <= currOaDtEnd;
  5578. if (!currTimeZoneStatus) continue;
  5579. stutus = false;
  5580. statusText = "公务活动中";
  5581. address = curr_oa.Address;
  5582. break;
  5583. }
  5584. }
  5585. #endregion
  5586. #region 酒店
  5587. var currHotelDatas = hotelDatas.Where(x => x.DiId == item.Id && !string.IsNullOrEmpty(x.Country) && currCountrys.Any(c => x.Country.Contains(c))).ToList();
  5588. if (stutus && hotelDatas.Any())
  5589. {
  5590. foreach (var curr_hotel in currHotelDatas)
  5591. {
  5592. var checkInDt = Convert.ToDateTime(curr_hotel.CheckInDate);
  5593. List<(DateTime start, DateTime end)> timeRanges = new List<(DateTime, DateTime)>();
  5594. while (checkInDt <= Convert.ToDateTime(curr_hotel.CheckOutDate))
  5595. {
  5596. int year = checkInDt.Year,
  5597. month = checkInDt.Month,
  5598. day = checkInDt.Day;
  5599. timeRanges.Add((new DateTime(year, month, day, 0, 0, 0), new DateTime(year, month, day, 9, 0, 0)));
  5600. timeRanges.Add((new DateTime(year, month, day, 18, 0, 0), new DateTime(year, month, day, 23, 59, 59)));
  5601. checkInDt = checkInDt.AddDays(1);
  5602. }
  5603. if (!timeRanges.Any()) continue;
  5604. if (string.IsNullOrEmpty(curr_hotel.Country) && string.IsNullOrEmpty(curr_hotel.City)) continue;
  5605. var countryInfo = countryDatas.Where(x => x.Id == curr_hotel.AreaId).FirstOrDefault();
  5606. if (countryInfo == null) continue;
  5607. var localTime = GetCountryOrCityCurrentDateTime(countryInfo.Country, countryInfo.City);
  5608. var currTimeZoneStatus = timeRanges.Any(range => localTime >= range.start && localTime <= range.end);
  5609. if (!currTimeZoneStatus) continue;
  5610. stutus = false;
  5611. statusText = "入住酒店中";
  5612. address = curr_hotel.HotelAddress;
  5613. break;
  5614. }
  5615. }
  5616. #endregion
  5617. #region 机票--通过三字码解析处理
  5618. var airTicketDatas = GetTableByBlackCode(item.Id);
  5619. if (stutus && airTicketDatas != null)
  5620. {
  5621. foreach (DataRow curr_airTicket in airTicketDatas.Rows)
  5622. {
  5623. string departDate = curr_airTicket["Date"].ToString(), //出发日期
  5624. departThree = curr_airTicket["Three"].ToString(), //城市三字码
  5625. departTime = curr_airTicket["StartTime"].ToString(), //出发时刻
  5626. departTerminal = curr_airTicket["StartBuilding"].ToString(), //出发航站楼
  5627. arriveTerminal = curr_airTicket["EndBuilding"].ToString(), //抵达航站楼
  5628. arrivedDate = curr_airTicket["ArrivedDate"].ToString(), //抵达日期
  5629. arrivedTime = curr_airTicket["EndTime"].ToString(), //抵达日期
  5630. flightTime = curr_airTicket["FlightTime"].ToString(); //飞行时间
  5631. if (string.IsNullOrEmpty(departThree)) continue;
  5632. string departAirThree = departThree.Substring(0, 3),
  5633. arriveAirThree = departThree.Substring(3, 3);
  5634. string departCountry = string.Empty,
  5635. departCity = string.Empty,
  5636. departAirport = string.Empty,
  5637. arriveCountry = string.Empty,
  5638. arriveCity = string.Empty,
  5639. arriveAirport = string.Empty;
  5640. var departCountryInfo = threeDatas.Find(x => x.Three.Equals(departAirThree));
  5641. var arriveCountryInfo = threeDatas.Find(x => x.Three.Equals(arriveAirThree));
  5642. if (departCountryInfo == null || arriveCountryInfo == null) continue;
  5643. departCountry = departCountryInfo.Country;
  5644. departCity = departCountryInfo.City;
  5645. departAirport = departCountryInfo.AirPort;
  5646. arriveCountry = arriveCountryInfo.Country;
  5647. arriveCity = arriveCountryInfo.City;
  5648. arriveAirport = arriveCountryInfo.AirPort;
  5649. var arriveDateTimeBool = DateTime.TryParse(arrivedDate + " " + arrivedTime.Insert(2, ":"),out DateTime arriveDateTime);
  5650. if (!arriveDateTimeBool) continue;
  5651. var filghtHoursBool = int.TryParse(flightTime.Split("H")[0].ToString(), out int filghtHours);
  5652. var filghtMinutesBool= int.TryParse(flightTime.Split("H")[1].Remove(2).ToString(), out int filghtMinutes);
  5653. if (!filghtHoursBool || !filghtHoursBool) continue;
  5654. var departDateTime = arriveDateTime.AddHours(-filghtHours).AddMinutes(-filghtMinutes);
  5655. var localTime = GetCountryOrCityCurrentDateTime(arriveCountry,arriveCity);
  5656. var currTimeZoneStatus = localTime >= departDateTime && localTime <= arriveDateTime;
  5657. if (!currTimeZoneStatus) continue;
  5658. stutus = false;
  5659. statusText = $"正飞往{arriveCity}城市中";
  5660. address = $"{arriveCountry}{arriveAirport}{arriveTerminal}";
  5661. break;
  5662. }
  5663. }
  5664. if (stutus) statusText = $"其他";
  5665. #endregion
  5666. result.Add(new StatisticsNowCityOfGroupResultView()
  5667. {
  5668. GroupName = item.TeamName,
  5669. Client = item.ClientUnit,
  5670. StatusText = statusText,
  5671. Address = address
  5672. });
  5673. }
  5674. result.AddRange(new List<StatisticsNowCityOfGroupResultView>() {
  5675. new StatisticsNowCityOfGroupResultView(){ GroupName = "模拟数据团组1",Client = "模拟数据单位1",StatusText = "正在公务中",Address = "日本〒104-0032 Tokyo, Chuo City, Hatchobori, 1 Chome−12−8 EAST2階" },
  5676. new StatisticsNowCityOfGroupResultView(){ GroupName = "模拟数据团组2",Client = "模拟数据单位2",StatusText = "入住酒店中",Address = "日本〒104-0032 Tokyo, Chuo City, Hatchobori, 1 Chome−12−8 EAST2階" },
  5677. new StatisticsNowCityOfGroupResultView(){ GroupName = "模拟数据团组3",Client = "模拟数据单位3",StatusText = "其他",Address = "日本〒104-0032 Tokyo, Chuo City, Hatchobori, 1 Chome−12−8 EAST2階" },
  5678. });
  5679. var result1 = result.GroupBy(x => x.Address).Select(g => new
  5680. {
  5681. address = g.Key,
  5682. Items = g.ToList().Select(gg => new { gg.GroupName, gg.Client, gg.StatusText }).ToList()
  5683. });
  5684. return Ok(JsonView(result1));
  5685. }
  5686. private StatisticsNowCityOfGroupView CitySplit(string cityLable, List<Res_ThreeCode> cities)
  5687. {
  5688. var info = new StatisticsNowCityOfGroupView();
  5689. if (string.IsNullOrEmpty(cityLable)) return info;
  5690. var cityArray = cityLable.Split("-");
  5691. var departCityCode = cityArray[0];
  5692. var arriveCityCode = cityArray[1];
  5693. var departAirportInfo = cities.Find(x => x.Three.Equals(departCityCode.ToUpper()));
  5694. info.DepartAirportCode = departCityCode;
  5695. info.DepartCountryName = departAirportInfo?.Country ?? "-";
  5696. info.DepartCityName = departAirportInfo?.City ?? "-";
  5697. var arriveAirportInfo = cities.Find(x => x.Three.Equals(arriveCityCode.ToUpper()));
  5698. info.ArriveAirportCode = arriveCityCode;
  5699. info.ArriveCountryName = arriveAirportInfo?.Country ?? "-";
  5700. info.ArriveCityName = arriveAirportInfo?.City ?? "-";
  5701. return info;
  5702. }
  5703. #endregion
  5704. }
  5705. }