StatisticsController.cs 431 KB

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