StatisticsController.cs 434 KB

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