StatisticsController.cs 450 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428
  1. using Aspose.Cells;
  2. using FluentValidation;
  3. using Humanizer;
  4. using NPOI.SS.Formula.Functions;
  5. using OASystem.API.OAMethodLib;
  6. using OASystem.API.OAMethodLib.JuHeAPI;
  7. using OASystem.Domain.AesEncryption;
  8. using OASystem.Domain.Common;
  9. using OASystem.Domain.Dtos.Statistics;
  10. using OASystem.Domain.Entities.Customer;
  11. using OASystem.Domain.Entities.Financial;
  12. using OASystem.Domain.Entities.Groups;
  13. using OASystem.Domain.ViewModels.Financial;
  14. using OASystem.Domain.ViewModels.Groups;
  15. using OASystem.Domain.ViewModels.Statistics;
  16. using OASystem.Infrastructure.Repositories.Groups;
  17. using SqlSugar;
  18. using StackExchange.Redis;
  19. using System.ComponentModel;
  20. using System.ComponentModel.DataAnnotations;
  21. using System.Data;
  22. using System.Diagnostics.Eventing.Reader;
  23. using static OASystem.API.OAMethodLib.GeneralMethod;
  24. using TypeInfo = OASystem.Domain.ViewModels.Statistics.TypeInfo;
  25. namespace OASystem.API.Controllers
  26. {
  27. /// <summary>
  28. /// 统计模块
  29. /// </summary>
  30. [Route("api/[controller]")]
  31. [ApiController]
  32. public class StatisticsController : ControllerBase
  33. {
  34. //private readonly int _decimalPlaces;
  35. private readonly IConfiguration _config;
  36. private readonly IMapper _mapper;
  37. private readonly SqlSugarClient _sqlSugar;
  38. private readonly DelegationInfoRepository _groupRep;
  39. private readonly SetDataRepository _setDataRep;
  40. private readonly TeamRateRepository _teamRateRep;
  41. private readonly VisitingClientsRepository _visitingClientsRep;
  42. private readonly IJuHeApiService _juHeApiService;
  43. /// <summary>
  44. /// Init
  45. /// </summary>
  46. /// <param name="mapper"></param>
  47. /// <param name="config"></param>
  48. /// <param name="sqlSugar"></param>
  49. /// <param name="groupRep"></param>
  50. /// <param name="setDataRep"></param>
  51. /// <param name="teamRate"></param>
  52. /// <param name="visitingClientsRep"></param>
  53. /// <param name="juHeApiService"></param>
  54. public StatisticsController(
  55. IMapper mapper,
  56. IConfiguration config,
  57. SqlSugarClient sqlSugar,
  58. DelegationInfoRepository groupRep,
  59. SetDataRepository setDataRep,
  60. TeamRateRepository teamRate,
  61. VisitingClientsRepository visitingClientsRep,
  62. IJuHeApiService juHeApiService
  63. )
  64. {
  65. _mapper = mapper;
  66. _config = config;
  67. _groupRep = groupRep;
  68. _setDataRep = setDataRep;
  69. _sqlSugar = sqlSugar;
  70. _teamRateRep = teamRate;
  71. _visitingClientsRep = visitingClientsRep;
  72. _juHeApiService = juHeApiService;
  73. }
  74. #region 团组报表
  75. /// <summary>
  76. /// 团组报表
  77. /// </summary>
  78. /// <param name="dto"></param>
  79. /// <returns></returns>
  80. [HttpPost("PostGroupStatementItems")]
  81. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  82. public async Task<IActionResult> PostGroupStatementItems(GroupStatementItemsDto dto)
  83. {
  84. #region 参数验证
  85. if (dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  86. if (dto.PageId < 1) return Ok(JsonView(false, "页面Id为空"));
  87. var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  88. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  89. #endregion
  90. if (dto.PortType < 1 || dto.PortType > 3)
  91. return Ok(JsonView(false, "端口类型错误"));
  92. try
  93. {
  94. // 构建基础查询 - 使用正确的SQLSugar链式调用
  95. var query = _sqlSugar.Queryable<Grp_DelegationInfo>()
  96. .LeftJoin<Sys_SetData>((gdi, ssd) => gdi.TeamDid == ssd.Id)
  97. .LeftJoin<Sys_SetData>((gdi, ssd, ssd1) => gdi.TeamLevSId == ssd1.Id)
  98. .LeftJoin<Sys_Users>((gdi, ssd, ssd1, su) => gdi.JietuanOperator == su.Id)
  99. .Where((gdi, ssd, ssd1, su) => gdi.IsDel == 0);
  100. // 状态筛选
  101. if (dto.IsSure == 0)
  102. {
  103. query = query.Where((gdi, ssd, ssd1, su) => gdi.IsSure == 0);
  104. }
  105. else if (dto.IsSure == 1)
  106. {
  107. query = query.Where((gdi, ssd, ssd1, su) => gdi.IsSure == 1);
  108. }
  109. // 多字段搜索 - 使用正确的表别名
  110. if (!string.IsNullOrWhiteSpace(dto.SearchCriteria))
  111. {
  112. var keywords = dto.SearchCriteria.Trim()
  113. .Split(new[] { ' ', ',', ',' }, StringSplitOptions.RemoveEmptyEntries);
  114. foreach (var keyword in keywords.Where(k => !string.IsNullOrWhiteSpace(k)))
  115. {
  116. var cleanKeyword = keyword.Trim();
  117. query = query.Where((gdi, ssd, ssd1, su) =>
  118. gdi.TeamName.Contains(cleanKeyword) ||
  119. gdi.ClientName.Contains(cleanKeyword) ||
  120. su.CnName.Contains(cleanKeyword) ||
  121. gdi.TourCode.Contains(cleanKeyword) ||
  122. gdi.ClientUnit.Contains(cleanKeyword) ||
  123. ssd.Name.Contains(cleanKeyword) ||
  124. ssd1.Name.Contains(cleanKeyword)
  125. );
  126. }
  127. }
  128. // 排序
  129. query = query.OrderBy((gdi, ssd, ssd1, su) => gdi.VisitDate, OrderByType.Desc);
  130. // 查询数据
  131. var totalCount = new RefAsync<int>(0);
  132. var data = await query
  133. .Select((gdi, ssd, ssd1, su) => new
  134. {
  135. Id = gdi.Id,
  136. TourCode = gdi.TourCode,
  137. TeamName = gdi.TeamName,
  138. ClientName = gdi.ClientName,
  139. ClientUnit = gdi.ClientUnit,
  140. VisitDate = gdi.VisitDate,
  141. VisitDays = gdi.VisitDays,
  142. VisitPNumber = gdi.VisitPNumber,
  143. IsSure = gdi.IsSure,
  144. TeamTypeId = ssd.Id,
  145. TeamTypeName = ssd.Name, // 使用正确的字段名
  146. TeamLevId = ssd1.Id,
  147. TeamLevName = ssd1.Name, // 使用正确的字段名
  148. JietuanOperatorName = su.CnName
  149. })
  150. .Distinct() // 确保数据不重复
  151. .ToPageListAsync(dto.PageIndex, dto.PageSize, totalCount);
  152. // 如果有数据,单独查询每个团组的最后收款时间
  153. if (data.Any())
  154. {
  155. var delegationIds = data.Select(x => x.Id).ToList();
  156. // 查询每个团组的最新收款时间
  157. var lastCollectionTimes = await _sqlSugar.Queryable<Fin_ProceedsReceived>()
  158. .Where(pr => delegationIds.Contains(pr.Diid))
  159. .GroupBy(pr => pr.Diid)
  160. .Select(pr => new
  161. {
  162. Diid = pr.Diid,
  163. LastTime = SqlFunc.AggregateMax(pr.CreateTime)
  164. })
  165. .ToListAsync();
  166. // 转换为最终的视图模型
  167. var lastCollectionDict = lastCollectionTimes.ToDictionary(x => x.Diid, x => x.LastTime);
  168. var resultData = data.Select(item => new GroupStatementItemView
  169. {
  170. Id = item.Id,
  171. TourCode = item.TourCode,
  172. TeamName = item.TeamName,
  173. ClientName = item.ClientName,
  174. ClientUnit = item.ClientUnit,
  175. VisitDate = item.VisitDate,
  176. VisitDays = item.VisitDays,
  177. VisitPNumber = item.VisitPNumber,
  178. IsSure = item.IsSure,
  179. TeamTypeId = item.TeamTypeId,
  180. TeamType = item.TeamTypeName, // 映射到正确的属性
  181. TeamLevId = item.TeamLevId,
  182. TeamLev = item.TeamLevName, // 映射到正确的属性
  183. JietuanOperator = item.JietuanOperatorName,
  184. LastCollectionTime = lastCollectionDict.TryGetValue(item.Id, out var lastTime) ? lastTime : null
  185. }).ToList();
  186. var result = new
  187. {
  188. PageFuncAuth = pageFunAuthView,
  189. Data = resultData
  190. };
  191. return Ok(JsonView(true, "查询成功!", result, totalCount));
  192. }
  193. // 没有数据的情况
  194. return Ok(JsonView(true, "查询成功!", new
  195. {
  196. PageFuncAuth = pageFunAuthView,
  197. Data = new List<GroupStatementItemView>()
  198. }));
  199. }
  200. catch (Exception ex)
  201. {
  202. return Ok(JsonView(false, "查询失败:" + ex.Message));
  203. }
  204. }
  205. /// <summary>
  206. /// 团组报表
  207. /// Details
  208. /// </summary>
  209. /// <param name="_dto">团组列表请求dto</param>
  210. /// <returns></returns>
  211. [HttpPost("PostGroupStatementDetails")]
  212. //[JsonConverter(typeof(DecimalConverter), 2)]
  213. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  214. public async Task<IActionResult> PostGroupStatementDetails(GroupStatementDetailsDto _dto)
  215. {
  216. /*
  217. * 团组报表计算方式
  218. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  219. * 应收金额 = 应收表.Sum()
  220. * 已收金额 = 已收表.Sum()
  221. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  222. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  223. *
  224. */
  225. #region 参数验证
  226. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  227. if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  228. if (_dto.DiId < 1) return Ok(JsonView(false, "团组Id为空"));
  229. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  230. #region 页面操作权限验证
  231. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  232. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  233. #endregion
  234. #endregion
  235. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  236. {
  237. GroupStatementDetailsView _view = new GroupStatementDetailsView();
  238. #region 费用类型 币种,转账,客户信息
  239. List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  240. var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>()
  241. .Where(it => it.IsDel == 0)
  242. .Select(x => new Crm_DeleClient { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, Sex = x.Sex })
  243. .ToListAsync();
  244. foreach (var item in _clientDatas) EncryptionProcessor.DecryptProperties(item);
  245. var groupInfo = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => x.Id == _dto.DiId).FirstAsync();
  246. var visitDate = groupInfo.VisitDate;
  247. #endregion
  248. #region 团组收入
  249. GroupIncomeView _giView = new GroupIncomeView();
  250. /*
  251. * 应收报表
  252. * 增加方式=实际报价时 费用必须审核才能进入团组报表
  253. */
  254. decimal frTotalAmount = 0.00M;//应收总金额
  255. 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,
  256. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  257. From Fin_ForeignReceivables fr
  258. Left Join Sys_SetData sd On fr.Currency = sd.Id
  259. Left Join Sys_Users u On fr.Auditor = u.Id
  260. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
  261. List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  262. //List<Gsd_ForeignReceivablesView> _frViews = new List<Gsd_ForeignReceivablesView>();
  263. //if (_frViews1.Count > 0)
  264. //{
  265. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay != 2).ToList());
  266. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay == 2 && x.Status == 1).ToList());
  267. //}
  268. _frViews.ForEach(x =>
  269. {
  270. string namePrefix = string.Empty;
  271. if (x.AddingWay == 0) namePrefix = $"账单模块-";
  272. else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
  273. else if (x.AddingWay == 2) namePrefix = $"实际报价-";
  274. x.PriceName = $"{namePrefix}{x.PriceName}";
  275. });
  276. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  277. _giView.Receivables = _frViews;
  278. _giView.ReceivableStr = string.Format(@"应收款合计:{0} CNY(人民币)", frTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  279. /*
  280. * 已收报表
  281. */
  282. decimal prTotalAmount = 0.00M;//已收总金额
  283. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  284. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  285. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  286. From Fin_ProceedsReceived pr
  287. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  288. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  289. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
  290. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  291. prTotalAmount = _prViews.Sum(it => it.Price);
  292. _giView.ProceedsReceivedViews = _prViews;
  293. _giView.ProceedsReceivedStr = string.Format(@$"应收合计:{frTotalAmount:#0.00} CNY 已收款合计:{prTotalAmount.ConvertToDecimal1():#0.00} CNY");
  294. /*
  295. * 超支费用
  296. */
  297. decimal exTotalAmount = 0.00M;
  298. // 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,
  299. // (gec.PriceSum * gec.Coefficient * ccp.DayRate) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  300. // sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  301. //From OA2023DB.dbo.Fin_GroupExtraCost gec
  302. //Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  303. // Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  304. // Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  305. // Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  306. // Left Join Sys_Users u On ccp.CreateUserId = u.Id
  307. //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 " : " ");
  308. // List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(ecSql).ToListAsync();
  309. // #region 超支费用 - 模拟数据
  310. // //if (_ExtraCostsViews.Count < 1)
  311. // //{
  312. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  313. // // {
  314. // // GECId = 0,
  315. // // GECDiId = 2334,
  316. // // PriceName = "模拟数据-超支费用名称",
  317. // // PayMoney = 1000.00M,
  318. // // PaymentCurrency = "CNY",
  319. // // DayRate = 1.0000M,
  320. // // CNYPrice = 1000.00M,
  321. // // Payee = "模拟数据-超支费用收款方",
  322. // // OrbitalPrivateTransfer = 1,
  323. // // PayWay = "刷卡",
  324. // // CardType = "招行卡",
  325. // // IsPay = 1,
  326. // // Applicant = "刘华举"
  327. // // });
  328. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  329. // // {
  330. // // GECId = 0,
  331. // // GECDiId = 2334,
  332. // // PriceName = "模拟数据-超支费用名称",
  333. // // PayMoney = 1000.00M,
  334. // // PaymentCurrency = "CNY",
  335. // // DayRate = 1.0000M,
  336. // // CNYPrice = 1000.00M,
  337. // // Payee = "模拟数据-超支费用收款方",
  338. // // OrbitalPrivateTransfer = 1,
  339. // // PayWay = "刷卡",
  340. // // CardType = "招行卡",
  341. // // IsPay = 1,
  342. // // Applicant = "刘华举"
  343. // // });
  344. // //}
  345. // #endregion
  346. // exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  347. // _giView.ExtraCostsViews = _ExtraCostsViews;
  348. // _giView.ExtraCostsStr = string.Format(@"人民币总费用:{0} CNY", exTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  349. /*
  350. * 收款退还
  351. */
  352. decimal promTotalAmount = 0.00M;// 收款退还总金额
  353. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  354. //删除了 And prom.PriceType = 1
  355. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  356. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  357. prom.PayType As PrPayType,prom.PriceType As PrPriceType,
  358. ccp.RMBPrice * ccp.DayRate As RMBPrice,ccp.*,prom.CreateTime As PrCreateTime
  359. From Fin_PaymentRefundAndOtherMoney prom
  360. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  361. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  362. Where prom.IsDel = 0
  363. And prom.PayType = 1
  364. And ccp.CTable = 285
  365. {1}
  366. And prom.DiId = {0} Order By PrCreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  367. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  368. foreach (var ropItem in _promDatas)
  369. {
  370. string thisCueencyCode = "Unknown";
  371. string thisCueencyName = "Unknown";
  372. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  373. if (currency != null)
  374. {
  375. thisCueencyCode = currency.Name;
  376. thisCueencyName = currency.Remark;
  377. }
  378. string orbitalPrivateTransferStr = "Unknown";
  379. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  380. if (orbitalPrivateTransfer != null)
  381. {
  382. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  383. }
  384. string payStr = "Unknown";
  385. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  386. if (pay != null)
  387. {
  388. payStr = pay.Name;
  389. }
  390. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  391. {
  392. Id = ropItem.Id,
  393. DiId = ropItem.DIId,
  394. PriceName = ropItem.PrPriceName,
  395. PayCurrencyCode = thisCueencyCode,
  396. PayCurrencyName = thisCueencyName,
  397. Price = ropItem.PrPrice,
  398. CNYPrice = ropItem.PayMoney * ropItem.DayRate,
  399. ThisRate = ropItem.DayRate,
  400. Payee = ropItem.Payee,
  401. PayTime = ropItem.AuditGMDate,
  402. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  403. PayType = payStr,
  404. IsPay = ropItem.IsPay,
  405. Applicant = ropItem.Appliction
  406. };
  407. _promView.Add(gsd_PaymentRefund);
  408. }
  409. #region 收款退还 - 模拟数据
  410. //if (_promView.Count < 1)
  411. //{
  412. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  413. // {
  414. // Id = 0,
  415. // DiId = 2334,
  416. // PriceName = "模拟数据-费用名称",
  417. // PayCurrencyCode = "CNY",
  418. // PayCurrencyName = "人民币",
  419. // Price = 1000.00M,
  420. // CNYPrice = 1000.00M,
  421. // ThisRate = 1.00M,
  422. // Payee = "模拟数据-收款方",
  423. // PayTime = "2023-01-01 15:20:01",
  424. // OrbitalPrivateTransfer = 1,
  425. // PayType = "刷卡",
  426. // IsPay = 1,
  427. // Applicant = "刘华举"
  428. // });
  429. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  430. // {
  431. // Id = 0,
  432. // DiId = 2334,
  433. // PriceName = "模拟数据-费用名称",
  434. // PayCurrencyCode = "CNY",
  435. // PayCurrencyName = "人民币",
  436. // Price = 1000.00M,
  437. // CNYPrice = 1000.00M,
  438. // ThisRate = 1.00M,
  439. // Payee = "模拟数据-收款方",
  440. // PayTime = "2023-01-01 15:20:01",
  441. // OrbitalPrivateTransfer = 1,
  442. // PayType = "刷卡",
  443. // IsPay = 1,
  444. // Applicant = "刘华举"
  445. // });
  446. //}
  447. #endregion
  448. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  449. _giView.PaymentRefundAndOtherMoneyViews = _promView;
  450. _giView.PaymentRefundAndOtherMoneyStr = string.Format(@"人民币总费用:{0} CNY", promTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  451. decimal BalancePayment = frTotalAmount - prTotalAmount + promTotalAmount;
  452. _view.GroupIncome = _giView;
  453. _view.GroupIncomeStr = string.Format(@"<span style='color:red;'>剩余尾款:{0} CNY(包含了收款退还费用数据)</span>", BalancePayment.ConvertToDecimal1().ToString("#0.00"));
  454. #endregion
  455. #region 团组支出
  456. GroupExpenditureView _geView = new GroupExpenditureView();
  457. var isAudit = _dto.isAudit;
  458. var isAuditSql = string.Format($" AND (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3) ");
  459. var isAuditStatus = new int[] {
  460. 1, //已通过
  461. 3, //自动审核
  462. };
  463. #region 酒店预定费用 76 isAuditSql
  464. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  465. //ccp.RMBPrice As CNYPrice
  466. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  467. string hotelFeeSql = string.Format(@"
  468. SELECT
  469. hr.Id AS HrId,
  470. hr.DiId AS HrDiId,
  471. hr.City,
  472. hr.HotelName,
  473. hr.CheckInDate,
  474. hr.CheckOutDate,
  475. hr.CardPrice AS RoomPrice,
  476. sd1.Name AS PaymentCurrency,
  477. hr.SingleRoomPrice,
  478. hr.SingleRoomCount,
  479. hr.DoubleRoomPrice,
  480. hr.DoubleRoomCount,
  481. hr.SuiteRoomPrice,
  482. hr.SuiteRoomCount,
  483. hr.OtherRoomPrice,
  484. hr.OtherRoomCount,
  485. hr.BreakfastPrice,
  486. sd4.Name AS BreakfastCurrency,
  487. hr.Isoppay,
  488. hr.GovernmentRent,
  489. sd5.Name AS GovernmentRentCurrency,
  490. hr.CityTax,
  491. sd6.Name AS CityTaxCurrency,
  492. ccp.PayMoney,
  493. (
  494. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  495. ) AS CNYPrice,
  496. ccp.PayPercentage,
  497. ccp.DayRate,
  498. ccp.Payee,
  499. ccp.OrbitalPrivateTransfer,
  500. sd2.Name AS PayWay,
  501. sd3.Name AS CardType,
  502. ccp.IsPay,
  503. u.CnName AS Applicant
  504. FROM
  505. Grp_HotelReservations hr
  506. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  507. LEFT JOIN Sys_SetData sd1 ON ccp.PaymentCurrency = sd1.Id
  508. LEFT JOIN Sys_SetData sd2 ON ccp.PayDId = sd2.Id
  509. LEFT JOIN Sys_SetData sd3 ON ccp.CTDId = sd3.Id
  510. LEFT JOIN Sys_Users u ON ccp.CreateUserId = u.Id
  511. LEFT JOIN Sys_SetData sd4 ON hr.BreakfastCurrency = sd4.Id
  512. LEFT JOIN Sys_SetData sd5 ON hr.GovernmentRentCurrency = sd5.Id
  513. LEFT JOIN Sys_SetData sd6 ON hr.CityTaxCurrency = sd6.Id
  514. WHERE
  515. hr.IsDel = 0
  516. AND ccp.IsDel = 0
  517. AND ccp.CTable = 76 {1}
  518. AND ccp.PayMoney <> 0
  519. AND hr.DiId = {0}
  520. ORDER BY
  521. CheckInDate Asc",
  522. _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty);
  523. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  524. List<int> hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
  525. var groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
  526. decimal HotelCNYTotalPrice = 0.00M;
  527. var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
  528. foreach (var item in groupHotelFeeViews)
  529. {
  530. if (groupHotelContentFeeViews.Count > 0)
  531. {
  532. string paymentStr = string.Empty;
  533. var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
  534. item.RoomPrice = roomData?.Price ?? 0.00M;
  535. if (item.RoomPrice != 0)
  536. {
  537. if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
  538. item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
  539. string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  540. string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
  541. item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
  542. 收款方:{roomData?.Payee}<br/>
  543. 费用标识:{feeMark1} <br/>
  544. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  545. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
  546. 是否由地接支付:{isFeeMark1} <br/>";
  547. }
  548. var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
  549. item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
  550. if (item.BreakfastPrice != 0)
  551. {
  552. if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
  553. item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
  554. string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  555. string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
  556. item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
  557. 收款方:{breakfastData?.Payee}<br/>
  558. 费用标识:{feeMark2} <br/>
  559. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  560. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
  561. 是否由地接支付:{isFeeMark2} <br/>";
  562. }
  563. var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
  564. item.GovernmentRent = landTaxData?.Price ?? 0.00M;
  565. if (item.GovernmentRent != 0)
  566. {
  567. if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
  568. item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
  569. string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  570. string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
  571. item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
  572. 收款方:{landTaxData?.Payee}<br/>
  573. 费用标识:{feeMark3} <br/>
  574. 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
  575. 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
  576. 是否由地接支付:{isFeeMark3} <br/>";
  577. }
  578. var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
  579. item.CityTax = cityTaxData?.Price ?? 0.00M;
  580. if (item.CityTax != 0)
  581. {
  582. if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
  583. item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
  584. string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  585. string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
  586. item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
  587. 收款方:{cityTaxData?.Payee}<br/>
  588. 费用标识:{feeMark4} <br/>
  589. 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
  590. 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
  591. 是否由地接支付:{isFeeMark4} <br/>";
  592. }
  593. if (!string.IsNullOrEmpty(paymentStr))
  594. {
  595. item.IsPay = 2;
  596. item.PayTips = paymentStr;
  597. }
  598. //item.CNYPrice = roomData?.Price ?? 0.00M * roomData?.Rate ?? 0.00M +
  599. // breakfastData?.Price ?? 0.00M * breakfastData?.Rate ?? 0.00M +
  600. // landTaxData?.Price ?? 0.00M * landTaxData?.Rate ?? 0.00M +
  601. // cityTaxData?.Price ?? 0.00M * cityTaxData?.Rate ?? 0.00M;
  602. }
  603. else
  604. {
  605. decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
  606. (item.DoubleRoomCount * item.DoubleRoomPrice) +
  607. (item.SuiteRoomCount * item.SuiteRoomPrice) +
  608. (item.OtherRoomCount * item.OtherRoomPrice);
  609. //item.RoomPrice = item.CardPrice;
  610. item.RoomPriceCurrency = item.PaymentCurrency;
  611. }
  612. HotelCNYTotalPrice += item.CNYPrice;
  613. item.PayMoney = item.PayMoney.ConvertToDecimal1();
  614. item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
  615. }
  616. _geView.GroupHotelFeeViews = groupHotelFeeViews;
  617. _geView.GroupHotelFeeStr = string.Format(@"人民币总费用:{0} CNY", HotelCNYTotalPrice.ToString("#0.00"));
  618. #endregion
  619. #region 地接费用 79 isAuditSql
  620. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  621. string CTGGRFeeSql = string.Empty;
  622. if (visitDate > Convert.ToDateTime("2024-04-17"))
  623. {
  624. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
  625. sd2.name As PaymentCurrency,ccp.PayPercentage,
  626. (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
  627. (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
  628. ccp.DayRate,(ctggrc.Price * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  629. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  630. From Grp_CarTouristGuideGroundReservations ctggr
  631. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
  632. cggrc.DatePrice,cggrc.PriceContent
  633. From Grp_CarTouristGuideGroundReservationsContent cggrc
  634. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  635. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  636. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  637. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  638. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  639. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  640. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  641. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  642. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  643. Order By CreateTime", _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty);
  644. }
  645. else
  646. {
  647. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,
  648. ccp.PayMoney,sd2.name As PaymentCurrency,ccp.PayPercentage,
  649. (ccp.PayMoney * (ccp.PayPercentage / 100)) As AmountPaid,
  650. (ccp.PayMoney -ccp.PayMoney * (ccp.PayPercentage / 100)) As BalancePayment,
  651. ccp.DayRate,(ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,
  652. ccp.Payee,ccp.AuditGMDate,
  653. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  654. From Grp_CarTouristGuideGroundReservations ctggr
  655. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  656. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  657. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  658. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  659. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  660. Order By CreateTime", _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty);
  661. }
  662. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  663. string CTGGRFeeStr = "";
  664. decimal CTGGRCNYTotalPrice = 0.00M;
  665. //按1 地区,2 币种,3 汇率 分组计算
  666. var groupCTGGRFeeDatas = groupCTGGRFeeViews.GroupBy(it => it.Area);
  667. foreach (var ctggfr in groupCTGGRFeeDatas)
  668. {
  669. var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
  670. if (ctggfr_curr.Count() > 0)
  671. {
  672. foreach (var curr in ctggfr_curr)
  673. {
  674. var ctggfr_rate = curr.GroupBy(it => it.DayRate);
  675. if (ctggfr_rate.Count() > 0)
  676. {
  677. foreach (var rate in ctggfr_rate)
  678. {
  679. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{rate.Sum(it => it.AmountPaid).ToString("#0.00")}
  680. {rate.FirstOrDefault()?.PaymentCurrency}(人民币:
  681. {rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  682. {rate.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  683. CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  684. }
  685. }
  686. else
  687. {
  688. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{curr.Sum(it => it.AmountPaid).ToString("#0.00")}
  689. {curr.FirstOrDefault()?.PaymentCurrency}(人民币:
  690. {curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  691. {curr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  692. CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  693. }
  694. }
  695. }
  696. else
  697. {
  698. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{ctggfr.Sum(it => it.AmountPaid).ToString("#0.00")}
  699. {ctggfr.FirstOrDefault()?.PaymentCurrency}(人民币:
  700. {ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  701. {ctggfr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  702. CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  703. }
  704. }
  705. foreach (var item in groupCTGGRFeeViews)
  706. {
  707. if (!string.IsNullOrEmpty(item.AuditGMDate))
  708. {
  709. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  710. }
  711. if (item.DatePrice != DateTime.MinValue)
  712. {
  713. item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
  714. }
  715. //CTGGRFeeStr += string.Format(@"{0} 总费用:{1} {2}(人民币:{3} CNY 当时支付汇率:{4})\r\n",
  716. // item.Area, item.AmountPaid.ConvertToDecimal1().ToString("#0.00"), item.PaymentCurrency, item.CNYPrice.ToString("#0.0000"), item.DayRate.ToString("#0.0000"));
  717. //CTGGRCNYTotalPrice += item.CNYPrice;
  718. }
  719. _geView.GroupCTGGRFeeViews = groupCTGGRFeeViews;
  720. _geView.GroupCTGGRFeeStr = string.Format(@"{0}人民币总费用:{1} CNY", CTGGRFeeStr, CTGGRCNYTotalPrice.ToString("#0.00"));
  721. #endregion
  722. #region 机票预订费用 85 isAuditSql
  723. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  724. //ccp.RMBPrice As CNYPrice
  725. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  726. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  727. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  728. sd1.Name As PayMoneyCurrency,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  729. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime,
  730. atr.CType
  731. From Grp_AirTicketReservations atr
  732. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  733. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  734. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  735. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  736. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  737. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  738. Where atr.IsDel = 0 {1} And atr.DiId = {0} Order By CreateTime",
  739. _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty);
  740. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  741. string str = "";
  742. List<dynamic> airClientPris = new List<dynamic>();
  743. decimal AirCNYTotalPrice = 0.00M;
  744. //decimal JJCCNYTotalPrice = 0.00M, JJCPeopleNum = 0.00M;
  745. decimal JJCAveragePrice = 0.00M;
  746. //decimal GWCCNYTotalPrice = 0.00M, GWCPeopleNum = 0.00M;
  747. decimal GWCAveragePrice = 0.00M;
  748. //if (groupAirFeeViews.Count > 0)
  749. //{
  750. // JJCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.CNYPrice);
  751. // JJCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.ClientNum);
  752. // JJCAveragePrice = (JJCCNYTotalPrice / JJCPeopleNum).ConvertToDecimal1();
  753. // GWCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.CNYPrice);
  754. // GWCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.ClientNum);
  755. // GWCAveragePrice = (GWCCNYTotalPrice / GWCPeopleNum).ConvertToDecimal1();
  756. //}
  757. // 原始数据
  758. var flights = await _sqlSugar.Queryable<Grp_AirTicketReservations>().Where(it => it.DIId == _dto.DiId && it.IsDel == 0).ToListAsync();
  759. int Index = 0;
  760. foreach (var item in groupAirFeeViews)
  761. {
  762. // 2026版处理 航班信息
  763. var currFlight = flights.Where(it => it.Id == item.AirId).FirstOrDefault();
  764. if (currFlight != null)
  765. {
  766. if (currFlight.IsNew == 1)
  767. {
  768. item.FlightsCode = string.Join("、", currFlight.AirTicketBasicInfos.Select(x => x.FlightsCode).ToList());
  769. item.FlightsCity = string.Join("/", currFlight.AirTicketBasicInfos.Select(x => x.FlightsCity).ToList());
  770. item.FlightsDate = currFlight.AirTicketBasicInfos.FirstOrDefault()?.FlightsDate ?? "";
  771. item.FlightsTime = currFlight.AirTicketBasicInfos.FirstOrDefault()?.FlightsTime ?? "";
  772. // 退票金额处理 显示为负数
  773. if (currFlight.RecordType == 1)
  774. {
  775. item.CNYPrice = -Math.Abs(item.CNYPrice);
  776. }
  777. }
  778. }
  779. if (item.AirId > 2924)
  780. {
  781. string itemClientName = "";
  782. if (!string.IsNullOrEmpty(item.ClientName))
  783. {
  784. System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  785. System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  786. if (m_EnName.Success || m_ZHName.Success)
  787. {
  788. itemClientName = item.ClientName;
  789. AirCNYTotalPrice += item.CNYPrice;
  790. continue;
  791. }
  792. string[] clientIds = Array.Empty<string>();
  793. if (item.ClientName.Contains(','))
  794. {
  795. clientIds = item.ClientName.Split(',');
  796. }
  797. else
  798. {
  799. clientIds = new string[] { item.ClientName };
  800. }
  801. if (clientIds.Length > 0)
  802. {
  803. int[] output = System.Array.ConvertAll<string, int>(clientIds, delegate (string s) { return int.Parse(s); });
  804. if (output.Contains(-1))
  805. {
  806. itemClientName += $@"行程单";
  807. output = output.Where(val => val != -1).ToArray();
  808. }
  809. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  810. decimal unitCost = 0.00M;
  811. unitCost = (item.PayMoney / item.ClientNum).ConvertToDecimal1();
  812. int clienIndex = 1;
  813. foreach (var client in clients)
  814. {
  815. airClientPris.Add(new
  816. {
  817. CnName = client.LastName + client.FirstName,
  818. EnName = client.Pinyin,
  819. Price = unitCost,
  820. AirType = item.AirTypeName
  821. });
  822. string six = "";
  823. if (client.Sex == 0) six = "Mr";
  824. else if (client.Sex == 1) six = "Ms";
  825. itemClientName += string.Format(@"{0}.{1} {2};", clienIndex, client.LastName + client.FirstName, six);
  826. clienIndex++;
  827. }
  828. }
  829. }
  830. item.ClientName = itemClientName;
  831. }
  832. else
  833. {
  834. string clientPinYinName = "";
  835. decimal unitCost = 0.00M;
  836. int cNum = item.ClientNum == 0 ? 1 : item.ClientNum;
  837. unitCost = (item.PayMoney / cNum).ConvertToDecimal1();
  838. Regex r = new Regex("[0-9]");
  839. string name1 = item.ClientName;
  840. name1 = r.Replace(name1, "");
  841. string[] clientNames = name1.Split('.');
  842. for (int i = 0; i < item.ClientNum; i++)
  843. {
  844. string name = "";
  845. if (clientNames.Length > 0)
  846. {
  847. int index = i + 1;
  848. if (index < clientNames.Length)
  849. {
  850. name = clientNames[index].Replace("MR", "").Replace("MS", "").Trim();
  851. if (!string.IsNullOrEmpty(name))
  852. {
  853. airClientPris.Add(new
  854. {
  855. CnName = name,
  856. EnName = name,
  857. Price = unitCost,
  858. AirType = item.AirTypeName
  859. });
  860. }
  861. //if (name.Length > 0)
  862. //{
  863. // string nameLastStr = name[name.Length - 1].ToString();
  864. // if (nameLastStr.IsNumeric())
  865. // {
  866. // name = name.Substring(0, name.Length - 1).Trim();
  867. // }
  868. //}
  869. }
  870. }
  871. clientPinYinName += string.Format(@"{0}.{1}出票价为:{2} CNY;", Index + 1, name, unitCost.ToString("#0.00"));
  872. }
  873. }
  874. if (!string.IsNullOrEmpty(item.AuditGMDate))
  875. {
  876. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  877. }
  878. AirCNYTotalPrice += item.CNYPrice;
  879. }
  880. #region 加载机票附加服务费用
  881. List<GroupAirFeeView> groupFeeFinalList = new List<GroupAirFeeView>();
  882. decimal aadiFeeTotalPrice = 0.00M;
  883. foreach (var rItem in groupAirFeeViews)
  884. {
  885. groupFeeFinalList.Add(rItem);
  886. #region 强制赋值
  887. string aadiFeeSql = string.Format(@"Select aads.Id As AirId, {1} As AirDiId, '-' As FlightsCode,'-' As FlightsCity,'-' As AirTypeName,
  888. '-' As FlightsDate,'-' As FlightsTime,aads.ClientId As ClientName,1 As ClientNum,ccp.PayMoney,
  889. sd1.Name As PayMoneyCurrency,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  890. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,aads.CreateTime,
  891. aads.SysTypeId As CType
  892. From Grp_AirAdditionServices aads
  893. Inner Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable In (1561,1562,1563,1564,1565,1566) And aads.Id = ccp.CId
  894. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  895. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  896. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  897. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  898. Where aads.IsDel = 0 And aads.ResId = {0} {2} Order By aads.CreateTime",
  899. rItem.AirId, rItem.AirDiId, _dto.isAudit ? isAuditSql : string.Empty);
  900. List<GroupAirFeeView> aadiFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(aadiFeeSql).ToListAsync();
  901. foreach (var fjItem in aadiFeeViews)
  902. {
  903. aadiFeeTotalPrice += fjItem.CNYPrice;
  904. AirCNYTotalPrice += fjItem.CNYPrice;
  905. string itemClientName = "";
  906. if (!string.IsNullOrEmpty(fjItem.ClientName))
  907. {
  908. System.Text.RegularExpressions.Match m_EnName = Regex.Match(fjItem.ClientName, @"[A-Za-z]+");
  909. System.Text.RegularExpressions.Match m_ZHName = Regex.Match(fjItem.ClientName, @"[\u4e00-\u9fa5]");
  910. if (m_EnName.Success || m_ZHName.Success)
  911. {
  912. itemClientName = fjItem.ClientName;
  913. continue;
  914. }
  915. string[] clientIds = Array.Empty<string>();
  916. if (fjItem.ClientName.Contains(','))
  917. {
  918. clientIds = fjItem.ClientName.Split(',');
  919. }
  920. else
  921. {
  922. clientIds = new string[] { fjItem.ClientName };
  923. }
  924. if (clientIds.Length > 0)
  925. {
  926. int[] output = System.Array.ConvertAll<string, int>(clientIds, delegate (string s) { return int.Parse(s); });
  927. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  928. decimal unitCost = 0.00M;
  929. unitCost = (fjItem.PayMoney / fjItem.ClientNum).ConvertToDecimal1();
  930. foreach (var client in clients)
  931. {
  932. //附加服务类型
  933. Sys_SetData tempSd = _setDatas.Where(it => it.Id == fjItem.CType).FirstOrDefault();
  934. itemClientName += string.Format(@"[{0}]附加服务:{1};", client.LastName + client.FirstName, tempSd?.Name);
  935. }
  936. }
  937. }
  938. fjItem.ClientName = itemClientName;
  939. if (!string.IsNullOrEmpty(fjItem.AuditGMDate))
  940. {
  941. fjItem.AuditGMDate = Convert.ToDateTime(fjItem.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  942. }
  943. groupFeeFinalList.Add(fjItem);
  944. }
  945. #endregion
  946. }
  947. #endregion
  948. _geView.GroupAirFeeViews = groupFeeFinalList;
  949. if (airClientPris.Count > 0)
  950. {
  951. var peoplePriStr = "";
  952. var airClientPris1 = airClientPris.GroupBy(item => item.CnName)
  953. .Select(group => group.First())
  954. .ToList();
  955. int airClientPrisIndex = 1;
  956. foreach (var item in airClientPris1)
  957. {
  958. decimal price = 0.00M;
  959. var prices = airClientPris.Where(it => it.CnName == item.CnName).ToList();
  960. foreach (var pri in prices)
  961. {
  962. price += pri.Price;
  963. }
  964. peoplePriStr += $@"{airClientPrisIndex}.{item.EnName}出票价为: {price.ToString("#0.00")} CNY;";
  965. airClientPrisIndex++;
  966. }
  967. peoplePriStr += $@"\r\n附加服务费用为:{aadiFeeTotalPrice.ToString("#0.00")} CNY;";
  968. if (!string.IsNullOrEmpty(peoplePriStr))
  969. {
  970. str = $@"其中:{peoplePriStr}";
  971. }
  972. //经济舱均价
  973. var airJJCPris = airClientPris.Where(it => it.AirType == "经济舱").ToList();
  974. if (airJJCPris.Count > 0)
  975. {
  976. decimal jjcTotalPrice = 0.00M;
  977. foreach (var item in airJJCPris)
  978. {
  979. jjcTotalPrice += item.Price;
  980. }
  981. decimal jjcPeopleNum = airJJCPris.GroupBy(item => item.CnName)
  982. .Select(group => group.First())
  983. .ToList().Count;
  984. JJCAveragePrice = jjcTotalPrice / jjcPeopleNum;
  985. }
  986. //公务舱均价
  987. var airGWCPris = airClientPris.Where(it => it.AirType == "公务舱").ToList();
  988. if (airGWCPris.Count > 0)
  989. {
  990. decimal gwcTotalPrice = 0.00M;
  991. foreach (var item in airGWCPris)
  992. {
  993. gwcTotalPrice += item.Price;
  994. }
  995. decimal gwcPeopleNum = airGWCPris.GroupBy(item => item.CnName)
  996. .Select(group => group.First())
  997. .ToList().Count;
  998. GWCAveragePrice = gwcTotalPrice / gwcPeopleNum;
  999. }
  1000. }
  1001. _geView.GroupAirFeeStr = $@"人民币总费用:{AirCNYTotalPrice.ToString("#0.00")} CNY\r\n{str}\r\n经济舱均价为:{JJCAveragePrice.ToString("#0.00")}CNY/人;公务舱均价为:{GWCAveragePrice.ToString("#0.00")}CNY/人;";
  1002. #endregion
  1003. #region 签证费用 80 isAuditSql
  1004. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  1005. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1006. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  1007. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime,
  1008. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  1009. From Grp_VisaInfo vi
  1010. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  1011. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1012. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1013. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  1014. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1015. Where vi.IsDel = 0 {1} And vi.DIId = {0} Order By CreateTime",
  1016. _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty);
  1017. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  1018. decimal VisaCNYTotalPirce = 0.00M;
  1019. foreach (var item in groupVisaFeeViews)
  1020. {
  1021. string itemClientName = "";
  1022. string visaClients = item.VisaClient;
  1023. if (!string.IsNullOrEmpty(visaClients))
  1024. {
  1025. string[] clientIds = Array.Empty<string>();
  1026. if (visaClients.Contains(','))
  1027. {
  1028. clientIds = visaClients.Split(',');
  1029. }
  1030. else
  1031. {
  1032. clientIds = new string[] { visaClients };
  1033. }
  1034. if (clientIds.Length > 0)
  1035. {
  1036. List<int> clientIds1 = new List<int>() { };
  1037. foreach (var clientIdStr in clientIds)
  1038. {
  1039. if (clientIdStr.IsNumeric())
  1040. {
  1041. clientIds1.Add(int.Parse(clientIdStr));
  1042. }
  1043. }
  1044. if (clientIds1.Count > 0)
  1045. {
  1046. var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
  1047. foreach (var client in clients)
  1048. {
  1049. itemClientName += $"{client.LastName + client.FirstName},";
  1050. }
  1051. }
  1052. else
  1053. {
  1054. itemClientName = visaClients;
  1055. }
  1056. }
  1057. }
  1058. if (itemClientName.Length > 0)
  1059. {
  1060. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  1061. }
  1062. item.VisaClient = itemClientName;
  1063. VisaCNYTotalPirce += item.CNYPrice;
  1064. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1065. {
  1066. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1067. }
  1068. }
  1069. _geView.GroupVisaFeeViews = groupVisaFeeViews;
  1070. _geView.GroupVisaFeeStr = string.Format(@"人民币总费用:{0} CNY", VisaCNYTotalPirce.ConvertToDecimal1().ToString("#0.00"));
  1071. #endregion
  1072. #region 邀请/公务活动 81 isAuditSql
  1073. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  1074. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  1075. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  1076. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  1077. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,
  1078. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice2,ccp.Payee,ccp.AuditGMDate,
  1079. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  1080. From Grp_InvitationOfficialActivities ioa
  1081. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  1082. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1083. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1084. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  1085. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  1086. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  1087. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  1088. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  1089. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1090. Where ioa.IsDel = 0 {1} And ioa.Diid = {0} Order By CreateTime",
  1091. _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty);
  1092. groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
  1093. #region 邀请/公务活动 - 模拟数据
  1094. //if (groupInvitationalFeeViews.Count < 1)
  1095. //{
  1096. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  1097. // {
  1098. // IOAId = 0,
  1099. // IOADiId = 2334,
  1100. // InviterArea = "模拟数据-邀请方地区",
  1101. // Inviter = "模拟数据-邀请方",
  1102. // InviteTime = "2023-10-10",
  1103. // InviteCost = 100.00M,
  1104. // InviteCurrency = "EUR",
  1105. // SendCost = 100.00M,
  1106. // SendCurrency = "EUR",
  1107. // EventsCost = 10000.00M,
  1108. // EventsCurrency = "EUR",
  1109. // TranslateCost = 300.00M,
  1110. // TranslateCurrency = "EUR",
  1111. // PayMoney = 10500.00M,
  1112. // PaymentCurrency = "EUR",
  1113. // CNYPrice = 76765.50M,
  1114. // Payee = "模拟数据-收款方",
  1115. // AuditGMDate = "2023-12-05",
  1116. // OrbitalPrivateTransfer = 1,
  1117. // PayWay = "刷卡",
  1118. // IsPay = 1,
  1119. // Applicant = "刘华举"
  1120. // });
  1121. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  1122. // {
  1123. // IOAId = 0,
  1124. // IOADiId = 2334,
  1125. // InviterArea = "模拟数据-邀请方地区",
  1126. // Inviter = "模拟数据-邀请方",
  1127. // InviteTime = "2023-10-10",
  1128. // InviteCost = 100.00M,
  1129. // InviteCurrency = "EUR",
  1130. // SendCost = 100.00M,
  1131. // SendCurrency = "EUR",
  1132. // EventsCost = 10000.00M,
  1133. // EventsCurrency = "EUR",
  1134. // TranslateCost = 300.00M,
  1135. // TranslateCurrency = "EUR",
  1136. // PayMoney = 10500.00M,
  1137. // PaymentCurrency = "EUR",
  1138. // CNYPrice = 76765.50M,
  1139. // Payee = "模拟数据-收款方",
  1140. // AuditGMDate = "2023-12-05",
  1141. // OrbitalPrivateTransfer = 1,
  1142. // PayWay = "刷卡",
  1143. // IsPay = 1,
  1144. // Applicant = "刘华举"
  1145. // });
  1146. //}
  1147. #endregion
  1148. decimal InvitationalCNYTotalPrice = 0.00M;
  1149. foreach (var item in groupInvitationalFeeViews)
  1150. {
  1151. InvitationalCNYTotalPrice += item.CNYPrice2;
  1152. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1153. {
  1154. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1155. }
  1156. string currencyRateStr = "";
  1157. List<string> currencys = new List<string>();
  1158. if (!string.IsNullOrEmpty(item.InviteCurrency)) currencys.Add(item.InviteCurrency);
  1159. if (!string.IsNullOrEmpty(item.SendCurrency)) currencys.Add(item.SendCurrency);
  1160. if (!string.IsNullOrEmpty(item.EventsCurrency)) currencys.Add(item.EventsCurrency);
  1161. if (!string.IsNullOrEmpty(item.TranslateCurrency)) currencys.Add(item.TranslateCurrency);
  1162. if (!string.IsNullOrEmpty(item.PaymentCurrency)) currencys.Add(item.PaymentCurrency);
  1163. currencyRateStr = await GeneralMethod.PostGroupRateByCTableAndCurrency(teamRateData, 81, currencys);
  1164. item.CurrencyRateStr = currencyRateStr;
  1165. }
  1166. _geView.GroupInvitationalFeeViews = groupInvitationalFeeViews;
  1167. _geView.GroupInvitationalFeeStr = string.Format(@"人民币总费用:{0} CNY", InvitationalCNYTotalPrice.ToString("#0.00"));
  1168. #endregion
  1169. #region 保险费用 82 isAuditSql
  1170. List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
  1171. string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.PayMoney * ccp.DayRate As CNYPrice,
  1172. sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  1173. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
  1174. From Grp_Customers ic
  1175. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  1176. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1177. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1178. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1179. Where ic.IsDel = 0 {1} And ic.DiId = {0} Order By CreateTime",
  1180. _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty);
  1181. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  1182. decimal InsuranceCNYTotalPrice = 0.00M;
  1183. foreach (var item in groupInsuranceFeeViews)
  1184. {
  1185. InsuranceCNYTotalPrice += item.CNYPrice;
  1186. string itemClientName = "";
  1187. string insClients = item.ClientName;
  1188. if (!string.IsNullOrEmpty(insClients))
  1189. {
  1190. //System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  1191. //System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  1192. //if (m_EnName.Success || m_ZHName.Success)
  1193. //{
  1194. // itemClientName = insClients;
  1195. // continue;
  1196. //}
  1197. string[] clientIds = Array.Empty<string>();
  1198. if (insClients.Contains(','))
  1199. {
  1200. clientIds = insClients.Split(',');
  1201. }
  1202. else
  1203. {
  1204. clientIds = new string[] { insClients };
  1205. }
  1206. if (clientIds.Length > 0)
  1207. {
  1208. List<int> output = new List<int>();
  1209. foreach (var clientId in clientIds)
  1210. {
  1211. if (clientId.IsNumeric())
  1212. {
  1213. output.Add(int.Parse(clientId));
  1214. }
  1215. }
  1216. if (output.Count > 0)
  1217. {
  1218. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  1219. foreach (var client in clients)
  1220. {
  1221. itemClientName += $"{client.LastName + client.FirstName},";
  1222. }
  1223. if (itemClientName.Length > 0)
  1224. {
  1225. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  1226. }
  1227. }
  1228. else
  1229. {
  1230. itemClientName = insClients;
  1231. }
  1232. }
  1233. }
  1234. item.ClientName = itemClientName;
  1235. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1236. {
  1237. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1238. }
  1239. }
  1240. _geView.GroupInsuranceFeeViews = groupInsuranceFeeViews;
  1241. _geView.GroupInsuranceFeeStr = string.Format(@"人民币总费用:{0} CNY", InsuranceCNYTotalPrice.ToString("#0.00"));
  1242. #endregion
  1243. #region 其他款项费用 98 isAuditSql
  1244. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  1245. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,
  1246. CASE
  1247. WHEN dp.PaymentPercent <> 100
  1248. THEN dp.PriceName
  1249. + '('
  1250. + dp.PaymentType
  1251. + ')'
  1252. -- + ' '
  1253. -- + CAST(CAST(dp.PaymentPercent AS INT) AS VARCHAR(10))
  1254. -- + '%)'
  1255. ELSE dp.PriceName
  1256. END AS PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1257. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  1258. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  1259. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  1260. From Grp_DecreasePayments dp
  1261. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  1262. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1263. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1264. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1265. Where dp.IsDel = 0 And ccp.Ctable = 98 {1} And dp.Diid = {0}
  1266. Order By CreateTime", _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty);
  1267. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  1268. #region 保险费用 - 模拟数据
  1269. //if (groupDecreaseFeeViews.Count < 1)
  1270. //{
  1271. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  1272. // {
  1273. // DPId = 0,
  1274. // DPDiId = 2334,
  1275. // PriceName = "模拟数据-费用名称",
  1276. // PayMoney = 1000.00M,
  1277. // PayMoneyCurrency = "CNY",
  1278. // DayRate = 1.0000M,
  1279. // CNYPrice = 1.0000M,
  1280. // AuditGMDate = "2023-12-10 12:13:00",
  1281. // Payee = "模拟数据-付款方",
  1282. // OrbitalPrivateTransfer = 1,
  1283. // PayWay = "现金",
  1284. // IsPay = 1,
  1285. // Applicant = "刘华举"
  1286. // });
  1287. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  1288. // {
  1289. // DPId = 0,
  1290. // DPDiId = 2334,
  1291. // PriceName = "模拟数据-费用名称",
  1292. // PayMoney = 1000.00M,
  1293. // PayMoneyCurrency = "CNY",
  1294. // DayRate = 1.0000M,
  1295. // CNYPrice = 1.0000M,
  1296. // AuditGMDate = "2023-12-10 12:13:00",
  1297. // Payee = "模拟数据-付款方",
  1298. // OrbitalPrivateTransfer = 1,
  1299. // PayWay = "现金",
  1300. // IsPay = 1,
  1301. // Applicant = "刘华举"
  1302. // });
  1303. //}
  1304. #endregion
  1305. decimal DecreaseCNYTotalPrice = 0.00M;
  1306. foreach (var item in groupDecreaseFeeViews)
  1307. {
  1308. item.CNYPrice = Convert.ToDecimal(item.CNYPrice.ToString("#0.00"));
  1309. DecreaseCNYTotalPrice += item.CNYPrice;
  1310. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1311. {
  1312. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1313. }
  1314. }
  1315. _geView.GroupDecreaseFeeViews = groupDecreaseFeeViews;
  1316. _geView.GroupDecreaseFeeStr = string.Format(@"人民币总费用:{0} CNY", DecreaseCNYTotalPrice.ToString("#0.00"));
  1317. #endregion
  1318. #region 公司内部操作人员提成(提成表) isAudit
  1319. var royaltyDatas = await _sqlSugar
  1320. .Queryable<Fin_RoyaltyConfirm, Sys_Users, Sys_Users>((rc, u1, u2) =>
  1321. new JoinQueryInfos(
  1322. JoinType.Left, rc.UserId == u1.Id,
  1323. JoinType.Left, rc.CreateUserId == u2.Id
  1324. ))
  1325. .Where((rc, u1, u2) => rc.IsDel == 0 && rc.TeamId == _dto.DiId)
  1326. .WhereIF(isAudit, (rc, u1, u2) => rc.IsConfirm == 1)
  1327. .Select((rc, u1, u2) => new GroupRoyaltyFeeInfo()
  1328. {
  1329. GroupId = rc.TeamId,
  1330. OverviewInfo = rc.Temp,
  1331. DetailedInfo = rc.ChiArr,
  1332. Amount = rc.Price,
  1333. IsConfirm = rc.IsConfirm,
  1334. IsSeed = rc.IsSeed,
  1335. RoyaltyUserName = u1.CnName,
  1336. CreateUserName = u2.CnName,
  1337. CreateTime = rc.CreateTime
  1338. })
  1339. .ToListAsync();
  1340. decimal royaltyCNYTotalPrice = royaltyDatas.Sum(x => x.Amount);
  1341. _geView.GroupRoyaltyFeeViews = _mapper.Map<List<GroupRoyaltyFeeView>>(royaltyDatas);
  1342. _geView.GroupRoyaltyFeeStr = string.Format(@"人民币总费用:{0} CNY", royaltyCNYTotalPrice.ToString("#0.00"));
  1343. #endregion
  1344. #region 公司内部人员报销(日付表) isAuditStatus
  1345. var reimburseDatas = await _sqlSugar
  1346. .Queryable<Fin_DailyFeePayment, Sys_Users, Sys_SetData, Sys_Company>((dfp, u, sd1, c) =>
  1347. new JoinQueryInfos(
  1348. JoinType.Left, dfp.CreateUserId == u.Id,
  1349. JoinType.Left, dfp.TransferTypeId == sd1.Id,
  1350. JoinType.Left, dfp.CompanyId == c.Id
  1351. ))
  1352. .Where((dfp, u, sd1, c) => dfp.IsDel == 0 && dfp.PriceTypeId == 1353 && dfp.GroupId == _dto.DiId)
  1353. .WhereIF(isAudit, (dfp, u, sd1, c) => isAuditStatus.Contains(dfp.FAudit) && isAuditStatus.Contains(dfp.MAudit))
  1354. .Select((dfp, u, sd1, c) => new GroupReimburseFeeInfoView()
  1355. {
  1356. TotalAmt = dfp.SumPrice,
  1357. //FeeItems = SqlFunc.Subqueryable<Fin_DailyFeePaymentContent>()
  1358. // .Where(x => x.DFPId == dfp.Id && x.IsDel == 0)
  1359. // .Select(x => new GroupReimburseFeeSubInfo()
  1360. // {
  1361. // PriceName = x.PriceName,
  1362. // Quantity = x.Quantity,
  1363. // Price = x.Price,
  1364. // SubTotal = x.ItemTotal,
  1365. // Remark = x.Remark
  1366. // })
  1367. // .ToList(),
  1368. AppReason = dfp.Instructions,
  1369. TransferLabel = sd1.Name,
  1370. ApplyComp = c.CompanyName,
  1371. FAudit = dfp.FAudit,
  1372. MAudit = dfp.MAudit,
  1373. PayStatusFlag = dfp.IsPay == 0 ? "未付款" : "已付款",
  1374. ApplyName = u.CnName,
  1375. ApplyTime = dfp.CreateTime
  1376. })
  1377. .ToListAsync();
  1378. var reimburseTotalPrice = reimburseDatas.Sum(x => x.TotalAmt);
  1379. _geView.GroupReimburseFeeViews = reimburseDatas;
  1380. _geView.GroupReimburseFeeStr = string.Format(@"人民币总费用:{0} CNY", reimburseTotalPrice.ToString("#0.00"));
  1381. #endregion
  1382. _view.GroupExpenditure = _geView;
  1383. #endregion
  1384. /*
  1385. * 团组报表计算方式
  1386. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  1387. * 应收金额 = 应收表.Sum()
  1388. * 已收金额 = 已收表.Sum()
  1389. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  1390. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  1391. *
  1392. */
  1393. decimal _totalExpenditure = 0.00M; //总支出
  1394. decimal _amountReceivable = 0.00M; //应收金额
  1395. decimal _amountReceived = 0.00M; //已收金额
  1396. decimal _receivableProfit = 0.00M; //应收利润
  1397. decimal _receivedProfit = 0.00M; //已收利润
  1398. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  1399. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount + royaltyCNYTotalPrice + reimburseTotalPrice;
  1400. _amountReceivable = frTotalAmount;
  1401. _amountReceived = prTotalAmount;
  1402. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  1403. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  1404. _view.FeeTotalStr = string.Format(@$"<span>
  1405. <span>当前总支出:{_totalExpenditure.ToString("#0.00")} CNY</span>
  1406. <span style='padding-left:10px;color: Green;'>应收金额:{_amountReceivable.ToString("#0.00")} CNY</span>
  1407. <span style='padding-left:10px;color: Green;'>已收金额:{_amountReceived.ToString("#0.00")} CNY</span>
  1408. <span style='padding-left:10px;color: Green;'>应收利润(应收-支出):{_receivableProfit.ToString("#0.00")} CNY</span>
  1409. <span style='padding-left:10px;color: Green;'>已收利润(已收-支出):{_receivedProfit.ToString("#0.00")} CNY</span>
  1410. </span>");
  1411. return Ok(JsonView(true, "查询成功!", _view));
  1412. }
  1413. else
  1414. {
  1415. return Ok(JsonView(false, "查询成功"));
  1416. }
  1417. }
  1418. /// <summary>
  1419. /// 团组报表
  1420. /// Excel 下载
  1421. /// </summary>
  1422. /// <param name="_dto">团组列表请求dto</param>
  1423. /// <returns></returns>
  1424. [HttpPost("PostGroupStatementExportExcel")]
  1425. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1426. public async Task<IActionResult> PostGroupStatementExportExcel(GroupStatementDetailsDto _dto)
  1427. {
  1428. //pageId 38
  1429. int currUserId = _dto.UserId, pageId = _dto.PageId, diId = _dto.DiId;
  1430. //默认查看所有数据
  1431. bool isAudit = _dto.isAudit;
  1432. #region 参数验证
  1433. if (currUserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1434. if (pageId < 1) return Ok(JsonView(false, "页面Id为空"));
  1435. if (diId < 1) return Ok(JsonView(false, "数据Id为空"));
  1436. #region 页面操作权限验证
  1437. var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(currUserId, pageId);
  1438. if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权!"));
  1439. #endregion
  1440. #endregion
  1441. var groupInfo = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => x.IsDel == 0 && x.Id == diId).First();
  1442. if (groupInfo == null) return Ok(JsonView(false, "暂无该条团组信息!"));
  1443. var userInfo = _sqlSugar.Queryable<Sys_Users>().Where(x => x.IsDel == 0 && x.Id == currUserId).First();
  1444. string groupNo = groupInfo.TourCode,
  1445. groupName = groupInfo.TeamName.Replace("|", "、"),
  1446. lister = userInfo?.CnName ?? "-";
  1447. var _clientDatas = _sqlSugar.Queryable<Crm_DeleClient>()
  1448. .Where(it => it.IsDel == 0)
  1449. .Select(x => new Crm_DeleClient { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, Sex = x.Sex })
  1450. .ToList();
  1451. //获取模板
  1452. string tempPath = (AppSettingsHelper.Get("ExcelBasePath") + "Template/团组费用统计模板.xls");
  1453. var designer = new WorkbookDesigner();
  1454. designer.Workbook = new Workbook(tempPath);
  1455. // 获取工作簿中的工作表集合
  1456. var worksheets = designer.Workbook.Worksheets;
  1457. #region 获取sheet,定义datatable,局部变量
  1458. //酒店费用相关
  1459. var hotelFeeSheet = worksheets["酒店费用"];
  1460. var hotelFeeDt = new DataTable($"HotelFeeView");
  1461. decimal hotelCNYTotalCost = 0.00M;
  1462. //地接费用相关
  1463. var OPFeeSheet = worksheets["地接费用"];
  1464. var OPFeeDt = new DataTable($"OPFeeView");
  1465. var OPFeeLabel = string.Empty;
  1466. decimal OPCNYTotalCost = 0.00M;
  1467. //签证费用相关
  1468. var visaFeeSheet = worksheets["签证费用"];
  1469. var visaFeeDt = new DataTable($"VisaFeeView");
  1470. decimal visaCNYTotalCost = 0.00M;
  1471. //邀请费用相关
  1472. var OAFeeSheet = worksheets["邀请费用"];
  1473. var OAFeeDt = new DataTable($"OAFeeView");
  1474. decimal OACNYTotalCost = 0.00M;
  1475. //机票费用相关
  1476. var airTicketFeeSheet = worksheets["机票费用"];
  1477. var airTicketFeeDt = new DataTable($"AirTicketFeeView");
  1478. decimal airTicketCNYTotalCost = 0.00M;
  1479. //保险费用相关
  1480. var insureFeeSheet = worksheets["保险费用"];
  1481. var insureFeeDt = new DataTable($"InsureFeeView");
  1482. decimal insureCNYTotalCost = 0.00M;
  1483. //其他费用相关
  1484. var otherFeeSheet = worksheets["其他费用"];
  1485. var otherFeeDt = new DataTable($"OtherFeeView");
  1486. decimal otherCNYTotalCost = 0.00M;
  1487. //收款退还相关
  1488. var SKTHFeeSheet = worksheets["收款退还"];
  1489. var SKTHFeeDt = new DataTable($"SKTHFeeView");
  1490. decimal SKTHCNYTotalCost = 0.00M;
  1491. //操作提成
  1492. var royaltyFeeSheet = worksheets["操作提成"];
  1493. var royaltyFeeDt = new DataTable($"royaltyFeeView");
  1494. decimal royaltyCNYTotalCost = 0.00M;
  1495. var totalAmount = 0.00M; //支出成本合计
  1496. var accountsAmount = 0.00M; //应收金额合计
  1497. var receivedAmount = 0.00M; //已收金额合计
  1498. var accountsProfit = 0.00M; //应收利润合计
  1499. var receiveProfit = 0.00M; //已收利润合计
  1500. var profitMargin = 0.00M; //利润差合计
  1501. //应收合计相关
  1502. var receivableFeeSheet = worksheets["团组收入(未收)"];
  1503. var receivableFeeDt = new DataTable($"ReceivableFeeView");
  1504. //已收合计相关
  1505. var receivedFeeSheet = worksheets["团组收入(已收)"];
  1506. var receivedFeeDt = new DataTable($"ReceivedFeeView");
  1507. //团组收入支出利润
  1508. var groupIEProfitDt = new DataTable($"IEProfitFeeView");
  1509. #endregion
  1510. #region 酒店费用
  1511. if (hotelFeeSheet != null)
  1512. {
  1513. string hotelFeeSql = string.Format(@"
  1514. SELECT
  1515. hr.Id AS HrId,
  1516. hr.DiId AS HrDiId,
  1517. hr.City,
  1518. hr.HotelName,
  1519. hr.CheckInDate,
  1520. hr.CheckOutDate,
  1521. hr.CardPrice AS RoomPrice,
  1522. sd1.Name AS PaymentCurrency,
  1523. hr.SingleRoomPrice,
  1524. hr.SingleRoomCount,
  1525. hr.DoubleRoomPrice,
  1526. hr.DoubleRoomCount,
  1527. hr.SuiteRoomPrice,
  1528. hr.SuiteRoomCount,
  1529. hr.OtherRoomPrice,
  1530. hr.OtherRoomCount,
  1531. hr.BreakfastPrice,
  1532. sd4.Name AS BreakfastCurrency,
  1533. hr.Isoppay,
  1534. hr.GovernmentRent,
  1535. sd5.Name AS GovernmentRentCurrency,
  1536. hr.CityTax,
  1537. sd6.Name AS CityTaxCurrency,
  1538. ccp.PayMoney,
  1539. (
  1540. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  1541. ) AS CNYPrice,
  1542. ccp.PayPercentage,
  1543. ccp.DayRate,
  1544. ccp.Payee,
  1545. ccp.OrbitalPrivateTransfer,
  1546. sd2.Name AS PayWay,
  1547. sd3.Name AS CardType,
  1548. ccp.IsPay,
  1549. u.CnName AS Applicant,
  1550. hr.Remark
  1551. FROM
  1552. Grp_HotelReservations hr
  1553. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  1554. LEFT JOIN Sys_SetData sd1 ON ccp.PaymentCurrency = sd1.Id
  1555. LEFT JOIN Sys_SetData sd2 ON ccp.PayDId = sd2.Id
  1556. LEFT JOIN Sys_SetData sd3 ON ccp.CTDId = sd3.Id
  1557. LEFT JOIN Sys_Users u ON ccp.CreateUserId = u.Id
  1558. LEFT JOIN Sys_SetData sd4 ON hr.BreakfastCurrency = sd4.Id
  1559. LEFT JOIN Sys_SetData sd5 ON hr.GovernmentRentCurrency = sd5.Id
  1560. LEFT JOIN Sys_SetData sd6 ON hr.CityTaxCurrency = sd6.Id
  1561. WHERE
  1562. hr.IsDel = 0
  1563. AND ccp.IsDel = 0
  1564. AND ccp.CTable = 76 {1}
  1565. AND ccp.PayMoney <> 0
  1566. AND hr.DiId = {0}
  1567. ORDER BY
  1568. CheckInDate Asc", _dto.DiId, _dto.isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  1569. var groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  1570. if (groupHotelFeeViews.Any())
  1571. {
  1572. var _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  1573. var hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
  1574. var groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
  1575. var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
  1576. foreach (var item in groupHotelFeeViews)
  1577. {
  1578. if (groupHotelContentFeeViews.Count > 0)
  1579. {
  1580. string paymentStr = string.Empty;
  1581. var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
  1582. item.RoomPrice = roomData?.Price ?? 0.00M;
  1583. if (item.RoomPrice != 0)
  1584. {
  1585. if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
  1586. item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
  1587. string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1588. string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
  1589. item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
  1590. 收款方:{roomData?.Payee}<br/>
  1591. 费用标识:{feeMark1} <br/>
  1592. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  1593. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
  1594. 是否由地接支付:{isFeeMark1} <br/>";
  1595. }
  1596. var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
  1597. item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
  1598. if (item.BreakfastPrice != 0)
  1599. {
  1600. if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
  1601. item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
  1602. string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1603. string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
  1604. item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
  1605. 收款方:{breakfastData?.Payee}<br/>
  1606. 费用标识:{feeMark2} <br/>
  1607. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  1608. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
  1609. 是否由地接支付:{isFeeMark2} <br/>";
  1610. }
  1611. var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
  1612. item.GovernmentRent = landTaxData?.Price ?? 0.00M;
  1613. if (item.GovernmentRent != 0)
  1614. {
  1615. if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
  1616. item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
  1617. string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1618. string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
  1619. item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
  1620. 收款方:{landTaxData?.Payee}<br/>
  1621. 费用标识:{feeMark3} <br/>
  1622. 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
  1623. 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
  1624. 是否由地接支付:{isFeeMark3} <br/>";
  1625. }
  1626. var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
  1627. item.CityTax = cityTaxData?.Price ?? 0.00M;
  1628. if (item.CityTax != 0)
  1629. {
  1630. if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
  1631. item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
  1632. string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1633. string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
  1634. item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
  1635. 收款方:{cityTaxData?.Payee}<br/>
  1636. 费用标识:{feeMark4} <br/>
  1637. 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
  1638. 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
  1639. 是否由地接支付:{isFeeMark4} <br/>";
  1640. }
  1641. if (!string.IsNullOrEmpty(paymentStr))
  1642. {
  1643. item.IsPay = 2;
  1644. item.PayTips = paymentStr;
  1645. }
  1646. //item.CNYPrice = roomData?.Price ?? 0.00M * roomData?.Rate ?? 0.00M +
  1647. // breakfastData?.Price ?? 0.00M * breakfastData?.Rate ?? 0.00M +
  1648. // landTaxData?.Price ?? 0.00M * landTaxData?.Rate ?? 0.00M +
  1649. // cityTaxData?.Price ?? 0.00M * cityTaxData?.Rate ?? 0.00M;
  1650. }
  1651. else
  1652. {
  1653. decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
  1654. (item.DoubleRoomCount * item.DoubleRoomPrice) +
  1655. (item.SuiteRoomCount * item.SuiteRoomPrice) +
  1656. (item.OtherRoomCount * item.OtherRoomPrice);
  1657. //item.RoomPrice = item.CardPrice;
  1658. item.RoomPriceCurrency = item.PaymentCurrency;
  1659. }
  1660. item.PayMoney = item.PayMoney.ConvertToDecimal1();
  1661. item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
  1662. }
  1663. }
  1664. hotelCNYTotalCost = groupHotelFeeViews.Sum(x => x.CNYPrice);
  1665. hotelFeeDt = CommonFun.ToDataTableArray(groupHotelFeeViews);
  1666. hotelFeeDt.TableName = $"HotelFeeView";
  1667. }
  1668. #endregion
  1669. #region 地接费用
  1670. if (OPFeeSheet != null)
  1671. {
  1672. string CTGGRFeeSql = string.Empty;
  1673. if (groupInfo.VisitDate > Convert.ToDateTime("2024-04-17"))
  1674. {
  1675. CTGGRFeeSql = string.Format(@"
  1676. Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
  1677. sd2.name As PaymentCurrency,ccp.PayPercentage,
  1678. (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
  1679. (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
  1680. ccp.DayRate,(ctggrc.Price * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  1681. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  1682. From Grp_CarTouristGuideGroundReservations ctggr
  1683. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
  1684. cggrc.DatePrice,cggrc.PriceContent
  1685. From Grp_CarTouristGuideGroundReservationsContent cggrc
  1686. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  1687. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  1688. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  1689. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  1690. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  1691. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  1692. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  1693. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1694. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  1695. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  1696. }
  1697. else
  1698. {
  1699. CTGGRFeeSql = string.Format(@"
  1700. Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,
  1701. ccp.PayMoney,sd2.name As PaymentCurrency,ccp.PayPercentage,
  1702. (ccp.PayMoney * (ccp.PayPercentage / 100)) As AmountPaid,
  1703. (ccp.PayMoney -ccp.PayMoney * (ccp.PayPercentage / 100)) As BalancePayment,
  1704. ccp.DayRate,(ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,
  1705. ccp.Payee,ccp.AuditGMDate,
  1706. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  1707. From Grp_CarTouristGuideGroundReservations ctggr
  1708. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  1709. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  1710. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  1711. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1712. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  1713. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  1714. }
  1715. var groupOPFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  1716. string CTGGRFeeStr = "";
  1717. var OPToDataTableViews = groupOPFeeViews;
  1718. decimal CTGGRCNYTotalPrice = 0.00M;
  1719. //按1 地区,2 币种,3 汇率 分组计算
  1720. var groupCTGGRFeeDatas = groupOPFeeViews.GroupBy(it => it.Area);
  1721. foreach (var ctggfr in groupCTGGRFeeDatas)
  1722. {
  1723. var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
  1724. if (ctggfr_curr.Count() > 0)
  1725. {
  1726. foreach (var curr in ctggfr_curr)
  1727. {
  1728. var ctggfr_rate = curr.GroupBy(it => it.DayRate);
  1729. if (ctggfr_rate.Count() > 0)
  1730. {
  1731. foreach (var rate in ctggfr_rate)
  1732. {
  1733. 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");
  1734. CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1735. }
  1736. }
  1737. else
  1738. {
  1739. 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");
  1740. CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1741. }
  1742. }
  1743. }
  1744. else
  1745. {
  1746. 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");
  1747. CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1748. }
  1749. }
  1750. foreach (var item in groupOPFeeViews)
  1751. {
  1752. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1753. {
  1754. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1755. }
  1756. if (item.DatePrice != DateTime.MinValue)
  1757. {
  1758. item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
  1759. }
  1760. }
  1761. OPCNYTotalCost = CTGGRCNYTotalPrice;
  1762. OPFeeDt = CommonFun.ToDataTableArray(OPToDataTableViews);
  1763. OPFeeLabel = CTGGRFeeStr;
  1764. OPFeeDt.TableName = $"OPFeeView";
  1765. }
  1766. #endregion
  1767. #region 签证费用
  1768. if (visaFeeSheet != null)
  1769. {
  1770. string groupVisaFeeSql = string.Format(@"
  1771. Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1772. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,sd2.Name As PaymentModes,sd3.Name As CardTypeName,u.CnName As Applicant,vi.CreateTime,
  1773. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) 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,vi.Remark
  1776. From Grp_VisaInfo vi
  1777. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  1778. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1779. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1780. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  1781. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1782. Where vi.IsDel = 0 {1} And vi.DIId = {0} Order By CreateTime", diId, isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  1783. var groupVisaFeeViews = _sqlSugar.SqlQueryable<GroupVisaFeeExcelView>(groupVisaFeeSql).ToList();
  1784. foreach (var item in groupVisaFeeViews)
  1785. {
  1786. string names = string.Empty;
  1787. string visaClients = item.VisaClient;
  1788. if (!string.IsNullOrEmpty(visaClients))
  1789. {
  1790. var clientIds = Array.Empty<string>();
  1791. if (visaClients.Contains(',')) clientIds = visaClients.Split(',');
  1792. else clientIds = new string[] { visaClients };
  1793. if (clientIds.Length > 0)
  1794. {
  1795. var clientIds1 = new List<int>() { };
  1796. foreach (var clientIdStr in clientIds)
  1797. {
  1798. var isInt = int.TryParse(clientIdStr, out int id);
  1799. if (isInt) clientIds1.Add(id);
  1800. }
  1801. if (clientIds1.Count > 0)
  1802. {
  1803. var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
  1804. foreach (var client in clients)
  1805. {
  1806. EncryptionProcessor.DecryptProperties(client);
  1807. names += $"{client.LastName + client.FirstName},";
  1808. }
  1809. }
  1810. else names = visaClients;
  1811. }
  1812. if (names.Length > 0) names = names.Substring(0, names.Length - 1);
  1813. item.VisaClient = names;
  1814. }
  1815. }
  1816. visaCNYTotalCost = groupVisaFeeViews.Sum(x => x.CNYPrice);
  1817. visaFeeDt = CommonFun.ToDataTableArray(groupVisaFeeViews);
  1818. visaFeeDt.TableName = $"VisaFeeView";
  1819. }
  1820. #endregion
  1821. #region 邀请费用
  1822. if (OAFeeSheet != null)
  1823. {
  1824. string feeSql = string.Format(@"
  1825. Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,CONVERT(DATE, ioa.InviteTime) AS InviteTime,
  1826. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  1827. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  1828. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,ccp.ConsumptionDate,
  1829. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1830. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1831. ccp.Payee,ioa.Remark,ccp.AuditGMDate,u.CnName As Applicant,ioa.CreateTime
  1832. From Grp_InvitationOfficialActivities ioa
  1833. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  1834. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1835. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1836. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  1837. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  1838. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  1839. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  1840. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  1841. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1842. Where ioa.IsDel = 0 {1} And ioa.Diid = {0} Order By CreateTime", diId, isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  1843. var feeViews = _sqlSugar.SqlQueryable<GroupOAFeeExcelView>(feeSql).ToList();
  1844. OACNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1845. OAFeeDt = CommonFun.ToDataTableArray(feeViews);
  1846. OAFeeDt.TableName = $"OAFeeView";
  1847. }
  1848. #endregion
  1849. #region 机票费用
  1850. if (airTicketFeeSheet != null)
  1851. {
  1852. string feeSql = string.Format(@"
  1853. Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,
  1854. sd4.Name As AirTypeName,atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,
  1855. atr.PriceDescription,ccp.PayMoney,ccp.DayRate,sd1.Name As PayMoneyCurrency,
  1856. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
  1857. ccp.Payee,Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1858. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1859. sd3.Name As CardType,ccp.AuditGMDate,u.CnName As Applicant,atr.CreateTime,atr.Remark
  1860. From Grp_AirTicketReservations atr
  1861. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  1862. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1863. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1864. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  1865. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  1866. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1867. Where atr.IsDel = 0 {1} And atr.DiId = {0} Order By CreateTime", diId, isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  1868. var feeViews = _sqlSugar.SqlQueryable<GroupAirTicketExcelView>(feeSql).ToList();
  1869. airTicketCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1870. airTicketFeeDt = CommonFun.ToDataTableArray(feeViews);
  1871. airTicketFeeDt.TableName = $"AirTicketFeeView";
  1872. }
  1873. #endregion
  1874. #region 保险费用
  1875. if (insureFeeSheet != null)
  1876. {
  1877. string feeSql = string.Format(@"
  1878. Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,
  1879. sd1.Name As PayMoneyCurrency,ccp.DayRate,ccp.PayMoney * ccp.DayRate As CNYPrice,ccp.ConsumptionDate,
  1880. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1881. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1882. ccp.Payee,ccp.AuditGMDate,u.CnName As Applicant,ic.CreateTime,ic.Remark
  1883. From Grp_Customers ic
  1884. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  1885. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1886. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1887. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1888. Where ic.IsDel = 0 {1} And ic.DiId = {0} Order By CreateTime", diId, isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  1889. var feeViews = _sqlSugar.SqlQueryable<GroupInsureExcelView>(feeSql).ToList();
  1890. foreach (var item in feeViews)
  1891. {
  1892. string itemClientName = "";
  1893. string insClients = item.ClientName;
  1894. if (!string.IsNullOrEmpty(insClients))
  1895. {
  1896. string[] clientIds = Array.Empty<string>();
  1897. if (insClients.Contains(',')) clientIds = insClients.Split(',');
  1898. else clientIds = new string[] { insClients };
  1899. if (clientIds.Length > 0)
  1900. {
  1901. List<int> output = new List<int>();
  1902. foreach (var clientId in clientIds)
  1903. if (int.TryParse(clientId, out int id))
  1904. output.Add(id);
  1905. if (output.Count > 0)
  1906. {
  1907. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  1908. foreach (var client in clients)
  1909. {
  1910. EncryptionProcessor.DecryptProperties(client);
  1911. itemClientName += $"{client.LastName + client.FirstName},";
  1912. }
  1913. if (itemClientName.Length > 0)
  1914. {
  1915. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  1916. }
  1917. }
  1918. else itemClientName = insClients;
  1919. }
  1920. }
  1921. item.ClientName = itemClientName;
  1922. }
  1923. insureCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1924. insureFeeDt = CommonFun.ToDataTableArray(feeViews);
  1925. insureFeeDt.TableName = $"InsureFeeView";
  1926. }
  1927. #endregion
  1928. #region 其他费用
  1929. if (insureFeeSheet != null)
  1930. {
  1931. string feeSql = string.Format(@"
  1932. Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1933. ccp.DayRate,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
  1934. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1935. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1936. ccp.Payee,ccp.AuditGMDate,u.CnName As Applicant,dp.CreateTime,dp.Remark
  1937. From Grp_DecreasePayments dp
  1938. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  1939. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1940. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1941. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1942. Where dp.IsDel = 0 And ccp.Ctable = 98 {1} And dp.Diid = {0}
  1943. Order By CreateTime", diId, isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  1944. var feeViews = _sqlSugar.SqlQueryable<GroupOtherFeeExcelView>(feeSql).ToList();
  1945. otherCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1946. otherFeeDt = CommonFun.ToDataTableArray(feeViews);
  1947. otherFeeDt.TableName = $"OtherFeeView";
  1948. }
  1949. #endregion
  1950. #region 收款退还
  1951. if (SKTHFeeSheet != null)
  1952. {
  1953. //删除了 And prom.PriceType = 1
  1954. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  1955. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  1956. prom.PayType As PrPayType,prom.PriceType As PrPriceType,
  1957. ccp.RMBPrice * ccp.DayRate As RMBPrice,ccp.*,prom.CreateTime As PrCreateTime,prom.Remark AS SKTHRemark
  1958. From Fin_PaymentRefundAndOtherMoney prom
  1959. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  1960. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1961. Where prom.IsDel = 0
  1962. And prom.PayType = 1
  1963. And ccp.CTable = 285
  1964. {1}
  1965. And prom.DiId = {0} Order By PrCreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1966. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  1967. if (_promDatas.Any())
  1968. {
  1969. var _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  1970. var _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  1971. foreach (var ropItem in _promDatas)
  1972. {
  1973. string thisCueencyCode = "Unknown";
  1974. string thisCueencyName = "Unknown";
  1975. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  1976. if (currency != null)
  1977. {
  1978. thisCueencyCode = currency.Name;
  1979. thisCueencyName = currency.Remark;
  1980. }
  1981. string orbitalPrivateTransferStr = "Unknown";
  1982. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  1983. if (orbitalPrivateTransfer != null)
  1984. {
  1985. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  1986. }
  1987. string payStr = "Unknown";
  1988. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  1989. if (pay != null)
  1990. {
  1991. payStr = pay.Name;
  1992. }
  1993. var gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  1994. {
  1995. Id = ropItem.Id,
  1996. DiId = ropItem.DIId,
  1997. PriceName = ropItem.PrPriceName,
  1998. PayCurrencyCode = thisCueencyCode,
  1999. PayCurrencyName = thisCueencyName,
  2000. Price = ropItem.PrPrice,
  2001. CNYPrice = ropItem.PayMoney * ropItem.DayRate,
  2002. ThisRate = ropItem.DayRate,
  2003. Payee = ropItem.Payee,
  2004. PayTime = ropItem.AuditGMDate,
  2005. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  2006. PayType = payStr,
  2007. IsPay = ropItem.IsPay,
  2008. Applicant = ropItem.Appliction,
  2009. Remark = ropItem.SKTHRemark
  2010. };
  2011. _promView.Add(gsd_PaymentRefund);
  2012. }
  2013. SKTHCNYTotalCost = _promView.Sum(x => x.CNYPrice);
  2014. SKTHFeeDt = CommonFun.ToDataTableArray(_promView);
  2015. SKTHFeeDt.TableName = $"SKTHFeeView";
  2016. }
  2017. }
  2018. #endregion
  2019. #region 操作提成
  2020. if (SKTHFeeSheet != null)
  2021. {
  2022. var _royaltyDatas = await _sqlSugar
  2023. .Queryable<Fin_RoyaltyConfirm, Sys_Users, Sys_Users>((rc, u1, u2) =>
  2024. new JoinQueryInfos(
  2025. JoinType.Left, rc.UserId == u1.Id,
  2026. JoinType.Left, rc.CreateUserId == u2.Id
  2027. ))
  2028. .Where((rc, u1, u2) => rc.IsDel == 0 && rc.TeamId == _dto.DiId && rc.IsConfirm == 1)
  2029. .Select((rc, u1, u2) => new GroupRoyaltyFeeInfo()
  2030. {
  2031. GroupId = rc.TeamId,
  2032. OverviewInfo = rc.Temp,
  2033. DetailedInfo = rc.ChiArr,
  2034. Amount = rc.Price,
  2035. IsConfirm = rc.IsConfirm,
  2036. IsSeed = rc.IsSeed,
  2037. RoyaltyUserName = u1.CnName,
  2038. CreateUserName = u2.CnName,
  2039. CreateTime = rc.CreateTime
  2040. })
  2041. .ToListAsync();
  2042. if (_royaltyDatas.Any())
  2043. {
  2044. decimal royaltyCNYTotalPrice = _royaltyDatas.Sum(x => x.Amount);
  2045. var _royaltyFeeViews = _mapper.Map<List<GroupRoyaltyFeeExcelView>>(_royaltyDatas);
  2046. royaltyCNYTotalCost = _royaltyFeeViews.Sum(x => x.Amount);
  2047. royaltyFeeDt = CommonFun.ToDataTableArray(_royaltyFeeViews);
  2048. royaltyFeeDt.TableName = $"RoyaltyFeeView";
  2049. }
  2050. }
  2051. #endregion
  2052. #region 应收金额(增加方式=实际报价时 费用必须审核才能进入团组报表)
  2053. //decimal frTotalAmount = 0.00M;//应收总金额
  2054. 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,
  2055. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime,fr.Remark
  2056. From Fin_ForeignReceivables fr
  2057. Left Join Sys_SetData sd On fr.Currency = sd.Id
  2058. Left Join Sys_Users u On fr.Auditor = u.Id
  2059. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
  2060. var _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  2061. _frViews.ForEach(x =>
  2062. {
  2063. string namePrefix = string.Empty;
  2064. if (x.AddingWay == 0) namePrefix = $"账单模块-";
  2065. else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
  2066. else if (x.AddingWay == 2) namePrefix = $"实际报价-";
  2067. x.PriceName = $"{namePrefix}{x.PriceName}";
  2068. });
  2069. if (_frViews.Any())
  2070. {
  2071. accountsAmount = _frViews.Sum(it => it.ItemSumPrice);
  2072. receivableFeeDt = CommonFun.ToDataTableArray(_frViews);
  2073. receivableFeeDt.TableName = $"ReceivedFeeView";
  2074. }
  2075. #endregion
  2076. #region 已收金额
  2077. //decimal prTotalAmount = 0.00M;//已收总金额
  2078. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  2079. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  2080. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  2081. From Fin_ProceedsReceived pr
  2082. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  2083. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  2084. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
  2085. var _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  2086. if (_prViews.Any())
  2087. {
  2088. receivedAmount = _prViews.Sum(it => it.Price);
  2089. receivedFeeDt = CommonFun.ToDataTableArray(_prViews);
  2090. receivedFeeDt.TableName = $"ReceivableFeeView";
  2091. }
  2092. #endregion
  2093. #region 团组收入支出利润
  2094. groupIEProfitDt.Columns.AddRange(new DataColumn[] {
  2095. new DataColumn(){ ColumnName = "ModuleName"},
  2096. new DataColumn(){ ColumnName = "FeeTotal",DataType = typeof(decimal)},
  2097. new DataColumn(){ ColumnName = "FeeCurrency"},
  2098. });
  2099. var groupIEProfitDt_rows = new[] {
  2100. new object[] { $"签证费用", visaCNYTotalCost, $"CNY" },
  2101. new object[] { $"酒店费用", hotelCNYTotalCost, $"CNY" },
  2102. new object[] { $"地接费用", OPCNYTotalCost, $"CNY" },
  2103. new object[] { $"商邀费用", OACNYTotalCost, $"CNY" },
  2104. new object[] { $"机票费用", airTicketCNYTotalCost, $"CNY" },
  2105. new object[] { $"保险费用", insureCNYTotalCost, $"CNY" },
  2106. new object[] { $"其他费用", otherCNYTotalCost, $"CNY" },
  2107. new object[] { $"收款退还费用", SKTHCNYTotalCost, $"CNY" },
  2108. new object[] { $"操作提成费用", royaltyCNYTotalCost, $"CNY" },
  2109. };
  2110. // 批量添加
  2111. foreach (var rowData in groupIEProfitDt_rows)
  2112. {
  2113. groupIEProfitDt.Rows.Add(rowData);
  2114. }
  2115. #endregion
  2116. #region 统一填充数据源
  2117. designer.SetDataSource("GroupNo", groupNo);
  2118. designer.SetDataSource("GroupName", groupName);
  2119. designer.SetDataSource("Lister", lister);
  2120. //酒店
  2121. designer.SetDataSource(hotelFeeDt);
  2122. designer.SetDataSource("HotelCNYTotalCost", $"{hotelCNYTotalCost.ToString("#0.00")} CNY");
  2123. //地接
  2124. designer.SetDataSource(OPFeeDt);
  2125. designer.SetDataSource("OPFeeLabel", OPFeeLabel);
  2126. designer.SetDataSource("OPCNYTotalCost", $"{OPCNYTotalCost.ToString("#0.00")} CNY");
  2127. //签证
  2128. designer.SetDataSource(visaFeeDt);
  2129. designer.SetDataSource("VisaCNYTotalCost", $"{visaCNYTotalCost.ToString("#0.00")} CNY");
  2130. //商邀
  2131. designer.SetDataSource(OAFeeDt);
  2132. designer.SetDataSource("OACNYTotalCost", $"{OACNYTotalCost.ToString("#0.00")} CNY");
  2133. //机票
  2134. designer.SetDataSource(airTicketFeeDt);
  2135. designer.SetDataSource("AirTicketCNYTotalCost", $"{airTicketCNYTotalCost.ToString("#0.00")} CNY");
  2136. //保险
  2137. designer.SetDataSource(insureFeeDt);
  2138. designer.SetDataSource("InsureCNYTotalCost", $"{insureCNYTotalCost.ToString("#0.00")} CNY");
  2139. //其他费用
  2140. designer.SetDataSource(otherFeeDt);
  2141. designer.SetDataSource("OtherCNYTotalCost", $"{otherCNYTotalCost.ToString("#0.00")} CNY");
  2142. //收款退还
  2143. designer.SetDataSource(SKTHFeeDt);
  2144. designer.SetDataSource("SKTHCNYTotalCost", $"{SKTHCNYTotalCost.ToString("#0.00")}");
  2145. //操作提成
  2146. designer.SetDataSource(royaltyFeeDt);
  2147. designer.SetDataSource("RoyaltyCNYTotalCost", $"{royaltyCNYTotalCost.ToString("#0.00")} CNY");
  2148. //已收金额
  2149. designer.SetDataSource(receivedFeeDt);
  2150. designer.SetDataSource("ReceivedAmount", $"{receivedAmount.ToString("#0.00")}");
  2151. //应收金额
  2152. designer.SetDataSource(receivableFeeDt);
  2153. designer.SetDataSource("AccountsAmount", $"{accountsAmount.ToString("#0.00")}");
  2154. //应收已收 -- 尾款
  2155. var balancePayment = accountsAmount - SKTHCNYTotalCost - receivedAmount;
  2156. designer.SetDataSource("BalancePayment", $"{balancePayment.ToString("#0.00")}");
  2157. //团组收入支出利润
  2158. designer.SetDataSource(groupIEProfitDt);
  2159. #region 各项费用计算
  2160. /*
  2161. * 团组报表计算方式
  2162. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  2163. * 应收金额 = 应收表.Sum() - 收款退还
  2164. * 已收金额 = 已收表.Sum() - 收款退还
  2165. * 应收利润(应收-支出) = 应收金额 - 当前总支出
  2166. * 已收利润(已收-支出) = 已收金额 - 当前总支出
  2167. * 利润差 = 应收利润 - 已收利润
  2168. */
  2169. totalAmount = visaCNYTotalCost + hotelCNYTotalCost + OPCNYTotalCost + OACNYTotalCost + airTicketCNYTotalCost + insureCNYTotalCost + otherCNYTotalCost + royaltyCNYTotalCost;//合计金额
  2170. accountsProfit = accountsAmount - totalAmount - SKTHCNYTotalCost; //应收利润
  2171. receiveProfit = receivedAmount - totalAmount - SKTHCNYTotalCost; //已收利润
  2172. profitMargin = accountsProfit - receiveProfit; //利润差
  2173. designer.SetDataSource("TotalAmount", $"{totalAmount.ToString("#0.00")}");
  2174. designer.SetDataSource("AccountsProfit", $"{accountsProfit.ToString("#0.00")}");
  2175. designer.SetDataSource("ReceiveProfit", $"{receiveProfit.ToString("#0.00")}");
  2176. designer.SetDataSource("ProfitMargin", $"{profitMargin.ToString("#0.00")}");
  2177. #endregion
  2178. designer.Process();
  2179. #endregion
  2180. #region 单元格样式设置 未付款设置为红色
  2181. /*
  2182. * 设置单元格样式
  2183. */
  2184. //背景颜色
  2185. Style style = designer.Workbook.CreateStyle();
  2186. style.ForegroundColor = Color.FromArgb(254, 242, 203);
  2187. style.Pattern = BackgroundType.Solid;
  2188. //字体
  2189. style.Font.Name = "微软雅黑"; // 字体名称
  2190. style.Font.Size = 10; // 字体大小
  2191. style.Font.Color = System.Drawing.Color.Black; // 字体颜色
  2192. StatementExportExcelSetCell(designer, hotelFeeSheet, hotelFeeDt, style, "IsPayLable", 8, "A", "V"); //酒店
  2193. StatementExportExcelSetCell(designer, OPFeeSheet, OPFeeDt, style, "IsPayLabel", 6, "A", "M"); //OP
  2194. StatementExportExcelSetCell(designer, visaFeeSheet, visaFeeDt, style, "IsPay", 6, "A", "I"); //签证
  2195. StatementExportExcelSetCell(designer, OAFeeSheet, OAFeeDt, style, "IsPay", 6, "A", "R"); //商邀
  2196. StatementExportExcelSetCell(designer, airTicketFeeSheet, airTicketFeeDt, style, "IsPay", 6, "A", "M"); //机票
  2197. StatementExportExcelSetCell(designer, insureFeeSheet, insureFeeDt, style, "IsPay", 6, "A", "I"); //保险
  2198. StatementExportExcelSetCell(designer, otherFeeSheet, otherFeeDt, style, "IsPay", 6, "A", "J"); //其他
  2199. StatementExportExcelSetCell(designer, SKTHFeeSheet, SKTHFeeDt, style, "IsPayLable", 6, "A", "K"); //首款退还
  2200. #endregion
  2201. //文件名
  2202. string fileName = $"{groupName}[{groupNo}]_团组费用清单{DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
  2203. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + "GroupStatement/" + fileName);
  2204. string url = AppSettingsHelper.Get("ExcelBaseUrl") + "Office/Excel/GroupStatement/" + fileName;
  2205. return Ok(JsonView(true, "成功", url));
  2206. }
  2207. /// <summary>
  2208. /// 团组报表
  2209. /// 利润相关数据
  2210. /// </summary>
  2211. /// <returns></returns>
  2212. [HttpPost("PostGroupStatementDetails1")]
  2213. //[JsonConverter(typeof(DecimalConverter), 2)]
  2214. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2215. public async Task<IActionResult> PostGroupStatementDetails1()
  2216. {
  2217. var groupInfos = _sqlSugar.Queryable<Grp_DelegationInfo>()
  2218. .Where(x => x.IsDel == 0 && x.VisitDate >= DateTime.Parse("2024-01-01") && x.VisitDate <= DateTime.Parse("2024-12-31"))
  2219. .OrderByDescending(x => x.VisitDate)
  2220. .ToList();
  2221. #region 费用类型 币种,转账,客户信息
  2222. List<Sys_SetData> _setDatas = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToList();
  2223. var _clientDatas = _sqlSugar.Queryable<Crm_DeleClient>()
  2224. .Where(it => it.IsDel == 0)
  2225. .Select(x => new Crm_DeleClient { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, Sex = x.Sex })
  2226. .ToList();
  2227. // foreach (var item1 in _clientDatas) EncryptionProcessor.DecryptProperties(item1);
  2228. #endregion
  2229. var _views = new List<GroupStatisticsInfo>();
  2230. int index1 = 0;
  2231. foreach (var info in groupInfos)
  2232. {
  2233. var _dto = new { DiId = info.Id, isAudit = false };
  2234. /*
  2235. * 团组报表计算方式
  2236. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  2237. * 应收金额 = 应收表.Sum()
  2238. * 已收金额 = 已收表.Sum()
  2239. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  2240. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  2241. *
  2242. */
  2243. GroupStatementDetailsView _view = new GroupStatementDetailsView();
  2244. var groupInfo = info;
  2245. var visitDate = info.VisitDate;
  2246. #region 团组收入
  2247. GroupIncomeView _giView = new GroupIncomeView();
  2248. /*
  2249. * 应收报表
  2250. * 增加方式=实际报价时 费用必须审核才能进入团组报表
  2251. */
  2252. decimal frTotalAmount = 0.00M;//应收总金额
  2253. 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,
  2254. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  2255. From Fin_ForeignReceivables fr
  2256. Left Join Sys_SetData sd On fr.Currency = sd.Id
  2257. Left Join Sys_Users u On fr.Auditor = u.Id
  2258. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
  2259. List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  2260. //List<Gsd_ForeignReceivablesView> _frViews = new List<Gsd_ForeignReceivablesView>();
  2261. //if (_frViews1.Count > 0)
  2262. //{
  2263. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay != 2).ToList());
  2264. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay == 2 && x.Status == 1).ToList());
  2265. //}
  2266. _frViews.ForEach(x =>
  2267. {
  2268. string namePrefix = string.Empty;
  2269. if (x.AddingWay == 0) namePrefix = $"账单模块-";
  2270. else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
  2271. else if (x.AddingWay == 2) namePrefix = $"实际报价-";
  2272. x.PriceName = $"{namePrefix}{x.PriceName}";
  2273. });
  2274. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  2275. _giView.Receivables = _frViews;
  2276. _giView.ReceivableStr = string.Format(@"应收款合计:{0} CNY(人民币)", frTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  2277. /*
  2278. * 已收报表
  2279. */
  2280. decimal prTotalAmount = 0.00M;//已收总金额
  2281. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  2282. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  2283. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  2284. From Fin_ProceedsReceived pr
  2285. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  2286. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  2287. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
  2288. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  2289. prTotalAmount = _prViews.Sum(it => it.Price);
  2290. _giView.ProceedsReceivedViews = _prViews;
  2291. _giView.ProceedsReceivedStr = string.Format(@$"应收合计:{frTotalAmount:#0.00} CNY 已收款合计:{prTotalAmount.ConvertToDecimal1():#0.00} CNY");
  2292. /*
  2293. * 超支费用
  2294. */
  2295. decimal exTotalAmount = 0.00M;
  2296. // 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,
  2297. // (gec.PriceSum * gec.Coefficient * ccp.DayRate) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  2298. // sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  2299. //From OA2023DB.dbo.Fin_GroupExtraCost gec
  2300. //Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  2301. // Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2302. // Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2303. // Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2304. // Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2305. //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 " : " ");
  2306. // List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(ecSql).ToListAsync();
  2307. // #region 超支费用 - 模拟数据
  2308. // //if (_ExtraCostsViews.Count < 1)
  2309. // //{
  2310. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  2311. // // {
  2312. // // GECId = 0,
  2313. // // GECDiId = 2334,
  2314. // // PriceName = "模拟数据-超支费用名称",
  2315. // // PayMoney = 1000.00M,
  2316. // // PaymentCurrency = "CNY",
  2317. // // DayRate = 1.0000M,
  2318. // // CNYPrice = 1000.00M,
  2319. // // Payee = "模拟数据-超支费用收款方",
  2320. // // OrbitalPrivateTransfer = 1,
  2321. // // PayWay = "刷卡",
  2322. // // CardType = "招行卡",
  2323. // // IsPay = 1,
  2324. // // Applicant = "刘华举"
  2325. // // });
  2326. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  2327. // // {
  2328. // // GECId = 0,
  2329. // // GECDiId = 2334,
  2330. // // PriceName = "模拟数据-超支费用名称",
  2331. // // PayMoney = 1000.00M,
  2332. // // PaymentCurrency = "CNY",
  2333. // // DayRate = 1.0000M,
  2334. // // CNYPrice = 1000.00M,
  2335. // // Payee = "模拟数据-超支费用收款方",
  2336. // // OrbitalPrivateTransfer = 1,
  2337. // // PayWay = "刷卡",
  2338. // // CardType = "招行卡",
  2339. // // IsPay = 1,
  2340. // // Applicant = "刘华举"
  2341. // // });
  2342. // //}
  2343. // #endregion
  2344. // exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  2345. // _giView.ExtraCostsViews = _ExtraCostsViews;
  2346. // _giView.ExtraCostsStr = string.Format(@"人民币总费用:{0} CNY", exTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  2347. /*
  2348. * 收款退还
  2349. */
  2350. decimal promTotalAmount = 0.00M;// 收款退还总金额
  2351. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  2352. //删除了 And prom.PriceType = 1
  2353. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  2354. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  2355. prom.PayType As PrPayType,prom.PriceType As PrPriceType,
  2356. ccp.RMBPrice * ccp.DayRate As RMBPrice,ccp.*,prom.CreateTime As PrCreateTime
  2357. From Fin_PaymentRefundAndOtherMoney prom
  2358. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  2359. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2360. Where prom.IsDel = 0
  2361. And prom.PayType = 1
  2362. And ccp.CTable = 285
  2363. {1}
  2364. And prom.DiId = {0} Order By PrCreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  2365. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  2366. foreach (var ropItem in _promDatas)
  2367. {
  2368. string thisCueencyCode = "Unknown";
  2369. string thisCueencyName = "Unknown";
  2370. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  2371. if (currency != null)
  2372. {
  2373. thisCueencyCode = currency.Name;
  2374. thisCueencyName = currency.Remark;
  2375. }
  2376. string orbitalPrivateTransferStr = "Unknown";
  2377. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  2378. if (orbitalPrivateTransfer != null)
  2379. {
  2380. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  2381. }
  2382. string payStr = "Unknown";
  2383. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  2384. if (pay != null)
  2385. {
  2386. payStr = pay.Name;
  2387. }
  2388. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  2389. {
  2390. Id = ropItem.Id,
  2391. DiId = ropItem.DIId,
  2392. PriceName = ropItem.PrPriceName,
  2393. PayCurrencyCode = thisCueencyCode,
  2394. PayCurrencyName = thisCueencyName,
  2395. Price = ropItem.PrPrice,
  2396. CNYPrice = ropItem.PayMoney * ropItem.DayRate,
  2397. ThisRate = ropItem.DayRate,
  2398. Payee = ropItem.Payee,
  2399. PayTime = ropItem.AuditGMDate,
  2400. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  2401. PayType = payStr,
  2402. IsPay = ropItem.IsPay,
  2403. Applicant = ropItem.Appliction
  2404. };
  2405. _promView.Add(gsd_PaymentRefund);
  2406. }
  2407. #region 收款退还 - 模拟数据
  2408. //if (_promView.Count < 1)
  2409. //{
  2410. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  2411. // {
  2412. // Id = 0,
  2413. // DiId = 2334,
  2414. // PriceName = "模拟数据-费用名称",
  2415. // PayCurrencyCode = "CNY",
  2416. // PayCurrencyName = "人民币",
  2417. // Price = 1000.00M,
  2418. // CNYPrice = 1000.00M,
  2419. // ThisRate = 1.00M,
  2420. // Payee = "模拟数据-收款方",
  2421. // PayTime = "2023-01-01 15:20:01",
  2422. // OrbitalPrivateTransfer = 1,
  2423. // PayType = "刷卡",
  2424. // IsPay = 1,
  2425. // Applicant = "刘华举"
  2426. // });
  2427. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  2428. // {
  2429. // Id = 0,
  2430. // DiId = 2334,
  2431. // PriceName = "模拟数据-费用名称",
  2432. // PayCurrencyCode = "CNY",
  2433. // PayCurrencyName = "人民币",
  2434. // Price = 1000.00M,
  2435. // CNYPrice = 1000.00M,
  2436. // ThisRate = 1.00M,
  2437. // Payee = "模拟数据-收款方",
  2438. // PayTime = "2023-01-01 15:20:01",
  2439. // OrbitalPrivateTransfer = 1,
  2440. // PayType = "刷卡",
  2441. // IsPay = 1,
  2442. // Applicant = "刘华举"
  2443. // });
  2444. //}
  2445. #endregion
  2446. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  2447. _giView.PaymentRefundAndOtherMoneyViews = _promView;
  2448. _giView.PaymentRefundAndOtherMoneyStr = string.Format(@"人民币总费用:{0} CNY", promTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  2449. decimal BalancePayment = frTotalAmount - prTotalAmount + promTotalAmount;
  2450. _view.GroupIncome = _giView;
  2451. _view.GroupIncomeStr = string.Format(@"<span style='color:red;'>剩余尾款:{0} CNY(包含了收款退还费用数据)</span>", BalancePayment.ConvertToDecimal1().ToString("#0.00"));
  2452. #endregion
  2453. #region 团组支出
  2454. GroupExpenditureView _geView = new GroupExpenditureView();
  2455. #region 酒店预定费用
  2456. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  2457. //ccp.RMBPrice As CNYPrice
  2458. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  2459. string hotelFeeSql = string.Format(@"
  2460. SELECT
  2461. hr.Id AS HrId,
  2462. hr.DiId AS HrDiId,
  2463. hr.City,
  2464. hr.HotelName,
  2465. hr.CheckInDate,
  2466. hr.CheckOutDate,
  2467. hr.CardPrice AS RoomPrice,
  2468. sd1.Name AS PaymentCurrency,
  2469. hr.SingleRoomPrice,
  2470. hr.SingleRoomCount,
  2471. hr.DoubleRoomPrice,
  2472. hr.DoubleRoomCount,
  2473. hr.SuiteRoomPrice,
  2474. hr.SuiteRoomCount,
  2475. hr.OtherRoomPrice,
  2476. hr.OtherRoomCount,
  2477. hr.BreakfastPrice,
  2478. sd4.Name AS BreakfastCurrency,
  2479. hr.Isoppay,
  2480. hr.GovernmentRent,
  2481. sd5.Name AS GovernmentRentCurrency,
  2482. hr.CityTax,
  2483. sd6.Name AS CityTaxCurrency,
  2484. ccp.PayMoney,
  2485. (
  2486. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  2487. ) AS CNYPrice,
  2488. ccp.PayPercentage,
  2489. ccp.DayRate,
  2490. ccp.Payee,
  2491. ccp.OrbitalPrivateTransfer,
  2492. sd2.Name AS PayWay,
  2493. sd3.Name AS CardType,
  2494. ccp.IsPay,
  2495. u.CnName AS Applicant
  2496. FROM
  2497. Grp_HotelReservations hr
  2498. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  2499. LEFT JOIN Sys_SetData sd1 ON ccp.PaymentCurrency = sd1.Id
  2500. LEFT JOIN Sys_SetData sd2 ON ccp.PayDId = sd2.Id
  2501. LEFT JOIN Sys_SetData sd3 ON ccp.CTDId = sd3.Id
  2502. LEFT JOIN Sys_Users u ON ccp.CreateUserId = u.Id
  2503. LEFT JOIN Sys_SetData sd4 ON hr.BreakfastCurrency = sd4.Id
  2504. LEFT JOIN Sys_SetData sd5 ON hr.GovernmentRentCurrency = sd5.Id
  2505. LEFT JOIN Sys_SetData sd6 ON hr.CityTaxCurrency = sd6.Id
  2506. WHERE
  2507. hr.IsDel = 0
  2508. AND ccp.IsDel = 0
  2509. AND ccp.CTable = 76 {1}
  2510. AND ccp.PayMoney <> 0
  2511. AND hr.DiId = {0}
  2512. ORDER BY
  2513. CheckInDate Asc", _dto.DiId, _dto.isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  2514. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  2515. List<int> hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
  2516. var groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
  2517. decimal HotelCNYTotalPrice = 0.00M;
  2518. var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
  2519. foreach (var item in groupHotelFeeViews)
  2520. {
  2521. if (groupHotelContentFeeViews.Count > 0)
  2522. {
  2523. string paymentStr = string.Empty;
  2524. var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
  2525. item.RoomPrice = roomData?.Price ?? 0.00M;
  2526. if (item.RoomPrice != 0)
  2527. {
  2528. if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
  2529. item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
  2530. string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  2531. string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
  2532. item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
  2533. 收款方:{roomData?.Payee}<br/>
  2534. 费用标识:{feeMark1} <br/>
  2535. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  2536. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
  2537. 是否由地接支付:{isFeeMark1} <br/>";
  2538. }
  2539. var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
  2540. item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
  2541. if (item.BreakfastPrice != 0)
  2542. {
  2543. if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
  2544. item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
  2545. string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  2546. string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
  2547. item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
  2548. 收款方:{breakfastData?.Payee}<br/>
  2549. 费用标识:{feeMark2} <br/>
  2550. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  2551. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
  2552. 是否由地接支付:{isFeeMark2} <br/>";
  2553. }
  2554. var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
  2555. item.GovernmentRent = landTaxData?.Price ?? 0.00M;
  2556. if (item.GovernmentRent != 0)
  2557. {
  2558. if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
  2559. item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
  2560. string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  2561. string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
  2562. item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
  2563. 收款方:{landTaxData?.Payee}<br/>
  2564. 费用标识:{feeMark3} <br/>
  2565. 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
  2566. 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
  2567. 是否由地接支付:{isFeeMark3} <br/>";
  2568. }
  2569. var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
  2570. item.CityTax = cityTaxData?.Price ?? 0.00M;
  2571. if (item.CityTax != 0)
  2572. {
  2573. if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
  2574. item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
  2575. string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  2576. string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
  2577. item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
  2578. 收款方:{cityTaxData?.Payee}<br/>
  2579. 费用标识:{feeMark4} <br/>
  2580. 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
  2581. 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
  2582. 是否由地接支付:{isFeeMark4} <br/>";
  2583. }
  2584. if (!string.IsNullOrEmpty(paymentStr))
  2585. {
  2586. item.IsPay = 2;
  2587. item.PayTips = paymentStr;
  2588. }
  2589. //item.CNYPrice = roomData?.Price ?? 0.00M * roomData?.Rate ?? 0.00M +
  2590. // breakfastData?.Price ?? 0.00M * breakfastData?.Rate ?? 0.00M +
  2591. // landTaxData?.Price ?? 0.00M * landTaxData?.Rate ?? 0.00M +
  2592. // cityTaxData?.Price ?? 0.00M * cityTaxData?.Rate ?? 0.00M;
  2593. }
  2594. else
  2595. {
  2596. decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
  2597. (item.DoubleRoomCount * item.DoubleRoomPrice) +
  2598. (item.SuiteRoomCount * item.SuiteRoomPrice) +
  2599. (item.OtherRoomCount * item.OtherRoomPrice);
  2600. //item.RoomPrice = item.CardPrice;
  2601. item.RoomPriceCurrency = item.PaymentCurrency;
  2602. }
  2603. HotelCNYTotalPrice += item.CNYPrice;
  2604. item.PayMoney = item.PayMoney.ConvertToDecimal1();
  2605. item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
  2606. }
  2607. _geView.GroupHotelFeeViews = groupHotelFeeViews;
  2608. _geView.GroupHotelFeeStr = string.Format(@"人民币总费用:{0} CNY", HotelCNYTotalPrice.ToString("#0.00"));
  2609. #endregion
  2610. #region 地接费用
  2611. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  2612. string CTGGRFeeSql = string.Empty;
  2613. if (visitDate > Convert.ToDateTime("2024-04-17"))
  2614. {
  2615. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
  2616. sd2.name As PaymentCurrency,ccp.PayPercentage,
  2617. (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
  2618. (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
  2619. ccp.DayRate,(ctggrc.Price * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  2620. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  2621. From Grp_CarTouristGuideGroundReservations ctggr
  2622. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
  2623. cggrc.DatePrice,cggrc.PriceContent
  2624. From Grp_CarTouristGuideGroundReservationsContent cggrc
  2625. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  2626. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  2627. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  2628. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  2629. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  2630. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  2631. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  2632. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2633. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  2634. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  2635. }
  2636. else
  2637. {
  2638. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,
  2639. ccp.PayMoney,sd2.name As PaymentCurrency,ccp.PayPercentage,
  2640. (ccp.PayMoney * (ccp.PayPercentage / 100)) As AmountPaid,
  2641. (ccp.PayMoney -ccp.PayMoney * (ccp.PayPercentage / 100)) As BalancePayment,
  2642. ccp.DayRate,(ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,
  2643. ccp.Payee,ccp.AuditGMDate,
  2644. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  2645. From Grp_CarTouristGuideGroundReservations ctggr
  2646. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  2647. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  2648. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  2649. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2650. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  2651. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  2652. }
  2653. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  2654. string CTGGRFeeStr = "";
  2655. decimal CTGGRCNYTotalPrice = 0.00M;
  2656. //按1 地区,2 币种,3 汇率 分组计算
  2657. var groupCTGGRFeeDatas = groupCTGGRFeeViews.GroupBy(it => it.Area);
  2658. foreach (var ctggfr in groupCTGGRFeeDatas)
  2659. {
  2660. var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
  2661. if (ctggfr_curr.Count() > 0)
  2662. {
  2663. foreach (var curr in ctggfr_curr)
  2664. {
  2665. var ctggfr_rate = curr.GroupBy(it => it.DayRate);
  2666. if (ctggfr_rate.Count() > 0)
  2667. {
  2668. foreach (var rate in ctggfr_rate)
  2669. {
  2670. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{rate.Sum(it => it.AmountPaid).ToString("#0.00")}
  2671. {rate.FirstOrDefault()?.PaymentCurrency}(人民币:
  2672. {rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  2673. {rate.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  2674. CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  2675. }
  2676. }
  2677. else
  2678. {
  2679. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{curr.Sum(it => it.AmountPaid).ToString("#0.00")}
  2680. {curr.FirstOrDefault()?.PaymentCurrency}(人民币:
  2681. {curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  2682. {curr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  2683. CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  2684. }
  2685. }
  2686. }
  2687. else
  2688. {
  2689. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{ctggfr.Sum(it => it.AmountPaid).ToString("#0.00")}
  2690. {ctggfr.FirstOrDefault()?.PaymentCurrency}(人民币:
  2691. {ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  2692. {ctggfr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  2693. CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  2694. }
  2695. }
  2696. foreach (var item in groupCTGGRFeeViews)
  2697. {
  2698. if (!string.IsNullOrEmpty(item.AuditGMDate))
  2699. {
  2700. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  2701. }
  2702. if (item.DatePrice != DateTime.MinValue)
  2703. {
  2704. item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
  2705. }
  2706. //CTGGRFeeStr += string.Format(@"{0} 总费用:{1} {2}(人民币:{3} CNY 当时支付汇率:{4})\r\n",
  2707. // item.Area, item.AmountPaid.ConvertToDecimal1().ToString("#0.00"), item.PaymentCurrency, item.CNYPrice.ToString("#0.0000"), item.DayRate.ToString("#0.0000"));
  2708. //CTGGRCNYTotalPrice += item.CNYPrice;
  2709. }
  2710. _geView.GroupCTGGRFeeViews = groupCTGGRFeeViews;
  2711. _geView.GroupCTGGRFeeStr = string.Format(@"{0}人民币总费用:{1} CNY", CTGGRFeeStr, CTGGRCNYTotalPrice.ToString("#0.00"));
  2712. #endregion
  2713. #region 机票预订费用
  2714. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  2715. //ccp.RMBPrice As CNYPrice
  2716. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  2717. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  2718. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  2719. sd1.Name As PayMoneyCurrency,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  2720. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime,
  2721. atr.CType
  2722. From Grp_AirTicketReservations atr
  2723. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  2724. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2725. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2726. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2727. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  2728. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2729. Where atr.IsDel = 0 {1} And atr.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  2730. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  2731. string str = "";
  2732. List<dynamic> airClientPris = new List<dynamic>();
  2733. decimal AirCNYTotalPrice = 0.00M;
  2734. //decimal JJCCNYTotalPrice = 0.00M, JJCPeopleNum = 0.00M;
  2735. decimal JJCAveragePrice = 0.00M;
  2736. //decimal GWCCNYTotalPrice = 0.00M, GWCPeopleNum = 0.00M;
  2737. decimal GWCAveragePrice = 0.00M;
  2738. //if (groupAirFeeViews.Count > 0)
  2739. //{
  2740. // JJCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.CNYPrice);
  2741. // JJCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.ClientNum);
  2742. // JJCAveragePrice = (JJCCNYTotalPrice / JJCPeopleNum).ConvertToDecimal1();
  2743. // GWCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.CNYPrice);
  2744. // GWCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.ClientNum);
  2745. // GWCAveragePrice = (GWCCNYTotalPrice / GWCPeopleNum).ConvertToDecimal1();
  2746. //}
  2747. int Index = 0;
  2748. foreach (var item in groupAirFeeViews)
  2749. {
  2750. if (item.AirId > 2924)
  2751. {
  2752. string itemClientName = "";
  2753. if (!string.IsNullOrEmpty(item.ClientName))
  2754. {
  2755. System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  2756. System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  2757. if (m_EnName.Success || m_ZHName.Success)
  2758. {
  2759. itemClientName = item.ClientName;
  2760. AirCNYTotalPrice += item.CNYPrice;
  2761. continue;
  2762. }
  2763. string[] clientIds = Array.Empty<string>();
  2764. if (item.ClientName.Contains(','))
  2765. {
  2766. clientIds = item.ClientName.Split(',');
  2767. }
  2768. else
  2769. {
  2770. clientIds = new string[] { item.ClientName };
  2771. }
  2772. if (clientIds.Length > 0)
  2773. {
  2774. int[] output = System.Array.ConvertAll<string, int>(clientIds, delegate (string s) { return int.Parse(s); });
  2775. if (output.Contains(-1))
  2776. {
  2777. itemClientName += $@"行程单";
  2778. output = output.Where(val => val != -1).ToArray();
  2779. }
  2780. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  2781. decimal unitCost = 0.00M;
  2782. unitCost = (item.PayMoney / item.ClientNum).ConvertToDecimal1();
  2783. int clienIndex = 1;
  2784. foreach (var client in clients)
  2785. {
  2786. airClientPris.Add(new
  2787. {
  2788. CnName = client.LastName + client.FirstName,
  2789. EnName = client.Pinyin,
  2790. Price = unitCost,
  2791. AirType = item.AirTypeName
  2792. });
  2793. string six = "";
  2794. if (client.Sex == 0) six = "Mr";
  2795. else if (client.Sex == 1) six = "Ms";
  2796. itemClientName += string.Format(@"{0}.{1} {2};", clienIndex, client.LastName + client.FirstName, six);
  2797. clienIndex++;
  2798. }
  2799. }
  2800. }
  2801. item.ClientName = itemClientName;
  2802. }
  2803. else
  2804. {
  2805. string clientPinYinName = "";
  2806. decimal unitCost = 0.00M;
  2807. int cNum = item.ClientNum == 0 ? 1 : item.ClientNum;
  2808. unitCost = (item.PayMoney / cNum).ConvertToDecimal1();
  2809. Regex r = new Regex("[0-9]");
  2810. string name1 = item.ClientName;
  2811. name1 = r.Replace(name1, "");
  2812. string[] clientNames = name1.Split('.');
  2813. for (int i = 0; i < item.ClientNum; i++)
  2814. {
  2815. string name = "";
  2816. if (clientNames.Length > 0)
  2817. {
  2818. int index = i + 1;
  2819. if (index < clientNames.Length)
  2820. {
  2821. name = clientNames[index].Replace("MR", "").Replace("MS", "").Trim();
  2822. if (!string.IsNullOrEmpty(name))
  2823. {
  2824. airClientPris.Add(new
  2825. {
  2826. CnName = name,
  2827. EnName = name,
  2828. Price = unitCost,
  2829. AirType = item.AirTypeName
  2830. });
  2831. }
  2832. //if (name.Length > 0)
  2833. //{
  2834. // string nameLastStr = name[name.Length - 1].ToString();
  2835. // if (nameLastStr.IsNumeric())
  2836. // {
  2837. // name = name.Substring(0, name.Length - 1).Trim();
  2838. // }
  2839. //}
  2840. }
  2841. }
  2842. clientPinYinName += string.Format(@"{0}.{1}出票价为:{2} CNY;", Index + 1, name, unitCost.ToString("#0.00"));
  2843. }
  2844. }
  2845. if (!string.IsNullOrEmpty(item.AuditGMDate))
  2846. {
  2847. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  2848. }
  2849. AirCNYTotalPrice += item.CNYPrice;
  2850. }
  2851. _geView.GroupAirFeeViews = groupAirFeeViews;
  2852. if (airClientPris.Count > 0)
  2853. {
  2854. var peoplePriStr = "";
  2855. var airClientPris1 = airClientPris.GroupBy(item => item.CnName)
  2856. .Select(group => group.First())
  2857. .ToList();
  2858. int airClientPrisIndex = 1;
  2859. foreach (var item in airClientPris1)
  2860. {
  2861. decimal price = 0.00M;
  2862. var prices = airClientPris.Where(it => it.CnName == item.CnName).ToList();
  2863. foreach (var pri in prices)
  2864. {
  2865. price += pri.Price;
  2866. }
  2867. peoplePriStr += $@"{airClientPrisIndex}.{item.EnName}出票价为: {price.ToString("#0.00")} CNY;";
  2868. airClientPrisIndex++;
  2869. }
  2870. if (!string.IsNullOrEmpty(peoplePriStr))
  2871. {
  2872. str = $@"其中:{peoplePriStr}";
  2873. }
  2874. //经济舱均价
  2875. var airJJCPris = airClientPris.Where(it => it.AirType == "经济舱").ToList();
  2876. if (airJJCPris.Count > 0)
  2877. {
  2878. decimal jjcTotalPrice = 0.00M;
  2879. foreach (var item in airJJCPris)
  2880. {
  2881. jjcTotalPrice += item.Price;
  2882. }
  2883. decimal jjcPeopleNum = airJJCPris.GroupBy(item => item.CnName)
  2884. .Select(group => group.First())
  2885. .ToList().Count;
  2886. JJCAveragePrice = jjcTotalPrice / jjcPeopleNum;
  2887. }
  2888. //公务舱均价
  2889. var airGWCPris = airClientPris.Where(it => it.AirType == "公务舱").ToList();
  2890. if (airGWCPris.Count > 0)
  2891. {
  2892. decimal gwcTotalPrice = 0.00M;
  2893. foreach (var item in airGWCPris)
  2894. {
  2895. gwcTotalPrice += item.Price;
  2896. }
  2897. decimal gwcPeopleNum = airGWCPris.GroupBy(item => item.CnName)
  2898. .Select(group => group.First())
  2899. .ToList().Count;
  2900. GWCAveragePrice = gwcTotalPrice / gwcPeopleNum;
  2901. }
  2902. }
  2903. _geView.GroupAirFeeStr = $@"人民币总费用:{AirCNYTotalPrice.ToString("#0.00")} CNY\r\n{str}\r\n经济舱均价为:{JJCAveragePrice.ToString("#0.00")}CNY/人;公务舱均价为:{GWCAveragePrice.ToString("#0.00")}CNY/人;";
  2904. #endregion
  2905. #region 签证费用
  2906. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  2907. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  2908. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  2909. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime,
  2910. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  2911. From Grp_VisaInfo vi
  2912. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  2913. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2914. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2915. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2916. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2917. Where vi.IsDel = 0 {1} And vi.DIId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  2918. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  2919. decimal VisaCNYTotalPirce = 0.00M;
  2920. foreach (var item in groupVisaFeeViews)
  2921. {
  2922. string itemClientName = "";
  2923. string visaClients = item.VisaClient;
  2924. if (!string.IsNullOrEmpty(visaClients))
  2925. {
  2926. string[] clientIds = Array.Empty<string>();
  2927. if (visaClients.Contains(','))
  2928. {
  2929. clientIds = visaClients.Split(',');
  2930. }
  2931. else
  2932. {
  2933. clientIds = new string[] { visaClients };
  2934. }
  2935. if (clientIds.Length > 0)
  2936. {
  2937. List<int> clientIds1 = new List<int>() { };
  2938. foreach (var clientIdStr in clientIds)
  2939. {
  2940. if (clientIdStr.IsNumeric())
  2941. {
  2942. clientIds1.Add(int.Parse(clientIdStr));
  2943. }
  2944. }
  2945. if (clientIds1.Count > 0)
  2946. {
  2947. var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
  2948. foreach (var client in clients)
  2949. {
  2950. itemClientName += $"{client.LastName + client.FirstName},";
  2951. }
  2952. }
  2953. else
  2954. {
  2955. itemClientName = visaClients;
  2956. }
  2957. }
  2958. }
  2959. if (itemClientName.Length > 0)
  2960. {
  2961. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  2962. }
  2963. item.VisaClient = itemClientName;
  2964. VisaCNYTotalPirce += item.CNYPrice;
  2965. if (!string.IsNullOrEmpty(item.AuditGMDate))
  2966. {
  2967. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  2968. }
  2969. }
  2970. _geView.GroupVisaFeeViews = groupVisaFeeViews;
  2971. _geView.GroupVisaFeeStr = string.Format(@"人民币总费用:{0} CNY", VisaCNYTotalPirce.ConvertToDecimal1().ToString("#0.00"));
  2972. #endregion
  2973. #region 邀请/公务活动 CTable = 81
  2974. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  2975. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  2976. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  2977. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  2978. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,
  2979. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice2,ccp.Payee,ccp.AuditGMDate,
  2980. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  2981. From Grp_InvitationOfficialActivities ioa
  2982. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  2983. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2984. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2985. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  2986. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  2987. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  2988. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  2989. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  2990. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2991. Where ioa.IsDel = 0 {1} And ioa.Diid = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  2992. groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
  2993. #region 邀请/公务活动 - 模拟数据
  2994. //if (groupInvitationalFeeViews.Count < 1)
  2995. //{
  2996. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  2997. // {
  2998. // IOAId = 0,
  2999. // IOADiId = 2334,
  3000. // InviterArea = "模拟数据-邀请方地区",
  3001. // Inviter = "模拟数据-邀请方",
  3002. // InviteTime = "2023-10-10",
  3003. // InviteCost = 100.00M,
  3004. // InviteCurrency = "EUR",
  3005. // SendCost = 100.00M,
  3006. // SendCurrency = "EUR",
  3007. // EventsCost = 10000.00M,
  3008. // EventsCurrency = "EUR",
  3009. // TranslateCost = 300.00M,
  3010. // TranslateCurrency = "EUR",
  3011. // PayMoney = 10500.00M,
  3012. // PaymentCurrency = "EUR",
  3013. // CNYPrice = 76765.50M,
  3014. // Payee = "模拟数据-收款方",
  3015. // AuditGMDate = "2023-12-05",
  3016. // OrbitalPrivateTransfer = 1,
  3017. // PayWay = "刷卡",
  3018. // IsPay = 1,
  3019. // Applicant = "刘华举"
  3020. // });
  3021. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  3022. // {
  3023. // IOAId = 0,
  3024. // IOADiId = 2334,
  3025. // InviterArea = "模拟数据-邀请方地区",
  3026. // Inviter = "模拟数据-邀请方",
  3027. // InviteTime = "2023-10-10",
  3028. // InviteCost = 100.00M,
  3029. // InviteCurrency = "EUR",
  3030. // SendCost = 100.00M,
  3031. // SendCurrency = "EUR",
  3032. // EventsCost = 10000.00M,
  3033. // EventsCurrency = "EUR",
  3034. // TranslateCost = 300.00M,
  3035. // TranslateCurrency = "EUR",
  3036. // PayMoney = 10500.00M,
  3037. // PaymentCurrency = "EUR",
  3038. // CNYPrice = 76765.50M,
  3039. // Payee = "模拟数据-收款方",
  3040. // AuditGMDate = "2023-12-05",
  3041. // OrbitalPrivateTransfer = 1,
  3042. // PayWay = "刷卡",
  3043. // IsPay = 1,
  3044. // Applicant = "刘华举"
  3045. // });
  3046. //}
  3047. #endregion
  3048. decimal InvitationalCNYTotalPrice = 0.00M;
  3049. foreach (var item in groupInvitationalFeeViews)
  3050. {
  3051. InvitationalCNYTotalPrice += item.CNYPrice2;
  3052. if (!string.IsNullOrEmpty(item.AuditGMDate))
  3053. {
  3054. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  3055. }
  3056. string currencyRateStr = "";
  3057. List<string> currencys = new List<string>();
  3058. if (!string.IsNullOrEmpty(item.InviteCurrency)) currencys.Add(item.InviteCurrency);
  3059. if (!string.IsNullOrEmpty(item.SendCurrency)) currencys.Add(item.SendCurrency);
  3060. if (!string.IsNullOrEmpty(item.EventsCurrency)) currencys.Add(item.EventsCurrency);
  3061. if (!string.IsNullOrEmpty(item.TranslateCurrency)) currencys.Add(item.TranslateCurrency);
  3062. if (!string.IsNullOrEmpty(item.PaymentCurrency)) currencys.Add(item.PaymentCurrency);
  3063. currencyRateStr = await GeneralMethod.PostGroupRateByCTableAndCurrency(teamRateData, 81, currencys);
  3064. item.CurrencyRateStr = currencyRateStr;
  3065. }
  3066. _geView.GroupInvitationalFeeViews = groupInvitationalFeeViews;
  3067. _geView.GroupInvitationalFeeStr = string.Format(@"人民币总费用:{0} CNY", InvitationalCNYTotalPrice.ToString("#0.00"));
  3068. #endregion
  3069. #region 保险费用
  3070. List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
  3071. string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.PayMoney * ccp.DayRate As CNYPrice,
  3072. sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  3073. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
  3074. From Grp_Customers ic
  3075. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  3076. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3077. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3078. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3079. Where ic.IsDel = 0 {1} And ic.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  3080. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  3081. decimal InsuranceCNYTotalPrice = 0.00M;
  3082. foreach (var item in groupInsuranceFeeViews)
  3083. {
  3084. InsuranceCNYTotalPrice += item.CNYPrice;
  3085. string itemClientName = "";
  3086. string insClients = item.ClientName;
  3087. if (!string.IsNullOrEmpty(insClients))
  3088. {
  3089. //System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  3090. //System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  3091. //if (m_EnName.Success || m_ZHName.Success)
  3092. //{
  3093. // itemClientName = insClients;
  3094. // continue;
  3095. //}
  3096. string[] clientIds = Array.Empty<string>();
  3097. if (insClients.Contains(','))
  3098. {
  3099. clientIds = insClients.Split(',');
  3100. }
  3101. else
  3102. {
  3103. clientIds = new string[] { insClients };
  3104. }
  3105. if (clientIds.Length > 0)
  3106. {
  3107. List<int> output = new List<int>();
  3108. foreach (var clientId in clientIds)
  3109. {
  3110. if (clientId.IsNumeric())
  3111. {
  3112. output.Add(int.Parse(clientId));
  3113. }
  3114. }
  3115. if (output.Count > 0)
  3116. {
  3117. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  3118. foreach (var client in clients)
  3119. {
  3120. itemClientName += $"{client.LastName + client.FirstName},";
  3121. }
  3122. if (itemClientName.Length > 0)
  3123. {
  3124. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  3125. }
  3126. }
  3127. else
  3128. {
  3129. itemClientName = insClients;
  3130. }
  3131. }
  3132. }
  3133. item.ClientName = itemClientName;
  3134. if (!string.IsNullOrEmpty(item.AuditGMDate))
  3135. {
  3136. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  3137. }
  3138. }
  3139. _geView.GroupInsuranceFeeViews = groupInsuranceFeeViews;
  3140. _geView.GroupInsuranceFeeStr = string.Format(@"人民币总费用:{0} CNY", InsuranceCNYTotalPrice.ToString("#0.00"));
  3141. #endregion
  3142. #region 其他款项费用 98
  3143. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  3144. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  3145. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  3146. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  3147. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  3148. From Grp_DecreasePayments dp
  3149. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  3150. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3151. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3152. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3153. Where dp.IsDel = 0 And ccp.Ctable = 98 {1} And dp.Diid = {0}
  3154. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  3155. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  3156. #region 保险费用 - 模拟数据
  3157. //if (groupDecreaseFeeViews.Count < 1)
  3158. //{
  3159. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  3160. // {
  3161. // DPId = 0,
  3162. // DPDiId = 2334,
  3163. // PriceName = "模拟数据-费用名称",
  3164. // PayMoney = 1000.00M,
  3165. // PayMoneyCurrency = "CNY",
  3166. // DayRate = 1.0000M,
  3167. // CNYPrice = 1.0000M,
  3168. // AuditGMDate = "2023-12-10 12:13:00",
  3169. // Payee = "模拟数据-付款方",
  3170. // OrbitalPrivateTransfer = 1,
  3171. // PayWay = "现金",
  3172. // IsPay = 1,
  3173. // Applicant = "刘华举"
  3174. // });
  3175. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  3176. // {
  3177. // DPId = 0,
  3178. // DPDiId = 2334,
  3179. // PriceName = "模拟数据-费用名称",
  3180. // PayMoney = 1000.00M,
  3181. // PayMoneyCurrency = "CNY",
  3182. // DayRate = 1.0000M,
  3183. // CNYPrice = 1.0000M,
  3184. // AuditGMDate = "2023-12-10 12:13:00",
  3185. // Payee = "模拟数据-付款方",
  3186. // OrbitalPrivateTransfer = 1,
  3187. // PayWay = "现金",
  3188. // IsPay = 1,
  3189. // Applicant = "刘华举"
  3190. // });
  3191. //}
  3192. #endregion
  3193. decimal DecreaseCNYTotalPrice = 0.00M;
  3194. foreach (var item in groupDecreaseFeeViews)
  3195. {
  3196. item.CNYPrice = Convert.ToDecimal(item.CNYPrice.ToString("#0.00"));
  3197. DecreaseCNYTotalPrice += item.CNYPrice;
  3198. if (!string.IsNullOrEmpty(item.AuditGMDate))
  3199. {
  3200. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  3201. }
  3202. }
  3203. _geView.GroupDecreaseFeeViews = groupDecreaseFeeViews;
  3204. _geView.GroupDecreaseFeeStr = string.Format(@"人民币总费用:{0} CNY", DecreaseCNYTotalPrice.ToString("#0.00"));
  3205. #endregion
  3206. #region 公司内部操作人员提成
  3207. var royaltyDatas = await _sqlSugar
  3208. .Queryable<Fin_RoyaltyConfirm, Sys_Users, Sys_Users>((rc, u1, u2) =>
  3209. new JoinQueryInfos(
  3210. JoinType.Left, rc.UserId == u1.Id,
  3211. JoinType.Left, rc.CreateUserId == u2.Id
  3212. ))
  3213. .Where((rc, u1, u2) => rc.IsDel == 0 && rc.TeamId == _dto.DiId && rc.IsConfirm == 1)
  3214. .Select((rc, u1, u2) => new GroupRoyaltyFeeInfo()
  3215. {
  3216. GroupId = rc.TeamId,
  3217. OverviewInfo = rc.Temp,
  3218. DetailedInfo = rc.ChiArr,
  3219. Amount = rc.Price,
  3220. IsConfirm = rc.IsConfirm,
  3221. IsSeed = rc.IsSeed,
  3222. RoyaltyUserName = u1.CnName,
  3223. CreateUserName = u2.CnName,
  3224. CreateTime = rc.CreateTime
  3225. })
  3226. .ToListAsync();
  3227. decimal royaltyCNYTotalPrice = royaltyDatas.Sum(x => x.Amount);
  3228. _geView.GroupRoyaltyFeeViews = _mapper.Map<List<GroupRoyaltyFeeView>>(royaltyDatas);
  3229. _geView.GroupRoyaltyFeeStr = string.Format(@"人民币总费用:{0} CNY", royaltyCNYTotalPrice.ToString("#0.00"));
  3230. #endregion
  3231. _view.GroupExpenditure = _geView;
  3232. #endregion
  3233. /*
  3234. * 团组报表计算方式
  3235. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  3236. * 应收金额 = 应收表.Sum()
  3237. * 已收金额 = 已收表.Sum()
  3238. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  3239. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  3240. *
  3241. */
  3242. decimal _totalExpenditure = 0.00M; //总支出
  3243. decimal _amountReceivable = 0.00M; //应收金额
  3244. decimal _amountReceived = 0.00M; //已收金额
  3245. decimal _receivableProfit = 0.00M; //应收利润
  3246. decimal _receivedProfit = 0.00M; //已收利润
  3247. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  3248. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount + royaltyCNYTotalPrice;
  3249. _amountReceivable = frTotalAmount;
  3250. _amountReceived = prTotalAmount;
  3251. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  3252. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  3253. _view.FeeTotalStr = string.Format(@$"<span>
  3254. <span>当前总支出:{_totalExpenditure.ToString("#0.00")} CNY</span>
  3255. <span style='padding-left:10px;color: Green;'>应收金额:{_amountReceivable.ToString("#0.00")} CNY</span>
  3256. <span style='padding-left:10px;color: Green;'>已收金额:{_amountReceived.ToString("#0.00")} CNY</span>
  3257. <span style='padding-left:10px;color: Green;'>应收利润(应收-支出):{_receivableProfit.ToString("#0.00")} CNY</span>
  3258. <span style='padding-left:10px;color: Green;'>已收利润(已收-支出):{_receivedProfit.ToString("#0.00")} CNY</span>
  3259. </span>");
  3260. index1++;
  3261. _views.Add(new GroupStatisticsInfo()
  3262. {
  3263. Index = index1,
  3264. Id = info.Id,
  3265. GroupName = info.TeamName,
  3266. VisitDate = info.VisitDate,
  3267. Receivable = Math.Floor(_amountReceivable * 100) / 100,
  3268. Cost = Math.Floor(_totalExpenditure * 100) / 100,
  3269. Grossprofit = Math.Floor((_amountReceivable - _totalExpenditure) * 100) / 100,
  3270. });
  3271. }
  3272. return Ok(JsonView(true, "查询成功!", _views));
  3273. }
  3274. private class GroupStatisticsInfo
  3275. {
  3276. public int Index { get; set; }
  3277. public int Id { get; set; }
  3278. public string GroupName { get; set; }
  3279. public DateTime VisitDate { get; set; }
  3280. public decimal Receivable { get; set; }
  3281. public decimal Cost { get; set; }
  3282. public decimal Grossprofit { get; set; }
  3283. }
  3284. private void StatementExportExcelSetCell(WorkbookDesigner designer, Worksheet sheet, DataTable dt, Style style, string judgeLable, int startIndex, string startRange, string endRange)
  3285. {
  3286. if (designer == null) return;
  3287. if (sheet == null) return;
  3288. if (style == null) return;
  3289. if (dt == null) return;
  3290. if (string.IsNullOrEmpty(startRange)) return;
  3291. if (string.IsNullOrEmpty(endRange)) return;
  3292. for (int i = 0; i < dt.Rows.Count; i++)
  3293. {
  3294. var isPayStr = dt.Rows[i][$"{judgeLable}"].ToString();
  3295. if (string.IsNullOrEmpty(isPayStr)) continue;
  3296. if (isPayStr.Contains("未付款"))
  3297. {
  3298. var excelIndex = startIndex + i;
  3299. Aspose.Cells.Range range = sheet.Cells.CreateRange($"{startRange}{excelIndex}", $"{endRange}{excelIndex}");
  3300. range.ApplyStyle(style, new StyleFlag() { CellShading = true, Font = true });
  3301. }
  3302. }
  3303. }
  3304. /// <summary>
  3305. /// 团组报表 - 会务超支验证excel下载
  3306. /// </summary>
  3307. /// <param name="dto"></param>
  3308. /// <returns></returns>
  3309. [HttpPost("PostGroupStatementValidateExpenses")]
  3310. public async Task<IActionResult> PostGroupStatementValidateExpenses(PostGroupStatementValidateExpensesDto dto)
  3311. {
  3312. // 1. 参数与业务校验
  3313. if (dto.GroupId <= 0 || dto.CurrUserId <= 0) return Ok(JsonView(false, "参数非法"));
  3314. var isConfGroup = await _sqlSugar.Queryable<Grp_DelegationInfo, Sys_SetData>((g, s) => g.TeamDid == s.Id)
  3315. .Where((g, s) => g.IsDel == 0 && g.Id == dto.GroupId && s.STid == 10 && s.Name.Contains("会务活动"))
  3316. .AnyAsync();
  3317. if (!isConfGroup) return Ok(JsonView(false, "当前团组非会务团组,禁止操作"));
  3318. // 2. 数据查询与处理
  3319. var feeList = await _sqlSugar.Queryable<Grp_DecreasePayments>()
  3320. .InnerJoin<Grp_CreditCardPayment>((x, y) => x.Id == y.CId && x.DiId == y.DIId && y.CTable == 98)
  3321. .LeftJoin<Sys_Users>((x, y, z) => x.CreateUserId == z.Id)
  3322. .Where((x, y, z) => x.IsDel == 0 && x.DiId == dto.GroupId)
  3323. .Select((x, y, z) => new ConfValidateExpensesView
  3324. {
  3325. PriceName = x.PriceName,
  3326. FeeEntry = y.PayMoney * y.DayRate,
  3327. AuditStatus = y.IsAuditGM.ToString(),
  3328. AuditTime = y.AuditGMDate,
  3329. PayLabel = y.IsPay.ToString(),
  3330. Remark = x.Remark,
  3331. Applicant = z.CnName,
  3332. ApplicantTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")
  3333. }).ToListAsync();
  3334. if (!feeList.Any()) return Ok(JsonView(false, "未检索到实际费用记录"));
  3335. var expenseData = await _sqlSugar.Queryable<Grp_ConferenceAffairsCostChild>()
  3336. .InnerJoin<Grp_ConferenceAffairsCost>((x, y) => x.ConferenceAffairsCostId == y.Id)
  3337. .Where((x, y) => y.IsDel == 0 && y.Diid == dto.GroupId && x.ReviewStatus == 1)
  3338. .Select((x, y) => new { x.PriceName, Total = x.CostPrice * x.Rate * x.Count })
  3339. .ToListAsync();
  3340. var expenseDict = expenseData.ToDictionary(k => k.PriceName, v => v.Total);
  3341. // 数据转换逻辑
  3342. int index = 1;
  3343. foreach (var item in feeList.OrderBy(x => x.PriceName).ThenBy(x => x.ApplicantTime))
  3344. {
  3345. item.Index = index++;
  3346. item.AuditStatus = MapAuditStatus(item.AuditStatus);
  3347. item.PayLabel = item.PayLabel == "1" ? "已支付" : "未支付";
  3348. if (expenseDict.TryGetValue(item.PriceName, out decimal budget))
  3349. {
  3350. item.ExpenseEntry = budget;
  3351. item.OverspentLabel = item.FeeEntry > budget ? "超支" : "未超支";
  3352. }
  3353. else
  3354. {
  3355. item.OverspentLabel = item.FeeEntry <= 0 ? "未超支" : "成本未录入项(系统判定超支)";
  3356. }
  3357. }
  3358. // 3. 路径与导出
  3359. try
  3360. {
  3361. var groupName = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => x.Id == dto.GroupId).Select(x => x.TeamName).FirstAsync() ?? "未知团组";
  3362. string baseUrl = AppSettingsHelper.Get("ExcelBaseUrl").TrimEnd('/');
  3363. string basePath = AppSettingsHelper.Get("ExcelBasePath").TrimEnd('\\').TrimEnd('/');
  3364. string fptPath = AppSettingsHelper.Get("ExcelFtpPath");
  3365. string dirName = "GroupConf";
  3366. // 目录不存在时创建
  3367. string targetDir = Path.Combine(basePath, dirName);
  3368. if (!Directory.Exists(targetDir)) Directory.CreateDirectory(targetDir);
  3369. string fileName = $"{groupName}_会务校验_{DateTime.Now:yyyyMMddHHmm}.xlsx";
  3370. string fullPath = Path.Combine(targetDir, fileName);
  3371. // 生成文件
  3372. var isSuccess = await ExportToExcel(feeList, fullPath, "超支验证明细");
  3373. if (isSuccess)
  3374. {
  3375. return Ok(JsonView(true, "操作成功", new { url = $"{baseUrl}{fptPath}{dirName}/{fileName}" }));
  3376. }
  3377. return Ok(JsonView(false, "文件生成失败"));
  3378. }
  3379. catch (Exception ex)
  3380. {
  3381. return Ok(JsonView(false, $"导出异常:{ex.Message}"));
  3382. }
  3383. }
  3384. private string MapAuditStatus(string status) => status switch
  3385. {
  3386. "0" => "未审核",
  3387. "1" => "已审核",
  3388. "2" => "未通过",
  3389. "3" => "自动审核",
  3390. _ => "未知"
  3391. };
  3392. public static async Task<bool> ExportToExcel<T>(IEnumerable<T> data, string absolutePath, string sheetName)
  3393. {
  3394. Workbook workbook = new Workbook();
  3395. Worksheet sheet = workbook.Worksheets[0];
  3396. sheet.Name = sheetName;
  3397. PropertyInfo[] props = typeof(T).GetProperties();
  3398. // 1. 表头处理
  3399. Style headerStyle = workbook.CreateStyle();
  3400. headerStyle.Font.Name = "微软雅黑";
  3401. headerStyle.Font.IsBold = true;
  3402. headerStyle.Pattern = BackgroundType.Solid;
  3403. headerStyle.ForegroundColor = System.Drawing.Color.LightGray;
  3404. headerStyle.HorizontalAlignment = TextAlignmentType.Center;
  3405. for (int i = 0; i < props.Length; i++)
  3406. {
  3407. var attr = props[i].GetCustomAttribute<DisplayAttribute>();
  3408. sheet.Cells[0, i].PutValue(attr?.Name ?? props[i].Name);
  3409. sheet.Cells[0, i].SetStyle(headerStyle);
  3410. }
  3411. // 2. 数据处理
  3412. var list = data.ToList();
  3413. for (int r = 0; r < list.Count; r++)
  3414. {
  3415. for (int c = 0; c < props.Length; c++)
  3416. {
  3417. var val = props[c].GetValue(list[r]);
  3418. Aspose.Cells.Cell cell = sheet.Cells[r + 1, c];
  3419. cell.PutValue(val);
  3420. // 高亮逻辑:仅在超支单元格设置红色
  3421. if (props[c].Name == "OverspentLabel" && val?.ToString()?.Contains("超支") == true)
  3422. {
  3423. Style s = cell.GetStyle();
  3424. s.Font.Color = System.Drawing.Color.Red;
  3425. s.Font.IsBold = true;
  3426. cell.SetStyle(s);
  3427. }
  3428. }
  3429. }
  3430. sheet.AutoFitColumns();
  3431. // 3. 物理保存
  3432. try
  3433. {
  3434. using (FileStream fs = new FileStream(absolutePath, FileMode.Create, FileAccess.Write, FileShare.None))
  3435. {
  3436. workbook.Save(fs, SaveFormat.Xlsx);
  3437. await fs.FlushAsync();
  3438. }
  3439. return System.IO.File.Exists(absolutePath);
  3440. }
  3441. catch { return false; }
  3442. }
  3443. #endregion
  3444. #region 报表/折线图统计
  3445. //企业利润-团组利润
  3446. //企业利润-会务利润
  3447. /// <summary>
  3448. /// 企业利润
  3449. /// Details
  3450. /// 待添加权限验证
  3451. /// </summary>
  3452. /// <param name="_dto">团组列表请求dto</param>
  3453. /// <returns></returns>
  3454. [HttpPost("PostCorporateProfit")]
  3455. //[JsonConverter(typeof(DecimalConverter), 2)]
  3456. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3457. public async Task<IActionResult> PostCorporateProfit(PostCorporateProfitDto _dto)
  3458. {
  3459. #region 参数验证
  3460. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  3461. if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  3462. if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));
  3463. if (_dto.StatisticsType > 2 && _dto.StatisticsType < 1) return Ok(JsonView(false, "请输入有效的StatisticsType参数,1 月份 2 季度"));
  3464. if (_dto.BusinessType > 3 && _dto.BusinessType < 1) return Ok(JsonView(false, "请输入有效的BusinessType参数,1 所有 2 团组 3 会务"));
  3465. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3466. #region 页面操作权限验证
  3467. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3468. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  3469. #endregion
  3470. string sqlWhere = string.Empty;
  3471. //起止时间
  3472. DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");
  3473. DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");
  3474. sqlWhere = string.Format(@$" Where Isdel = 0 ");
  3475. //业务类型
  3476. List<int> groupTypeId = new List<int>();
  3477. if (_dto.BusinessType == 2) //团组
  3478. {
  3479. groupTypeId.AddRange(new List<int>() {
  3480. 38, // 政府团
  3481. 39, // 企业团
  3482. 40, // 散客团
  3483. 1048 // 高校团
  3484. });
  3485. }
  3486. else if (_dto.BusinessType == 3) //会务
  3487. {
  3488. groupTypeId.AddRange(new List<int>() {
  3489. 102, // 未知
  3490. 248, // 非团组
  3491. 302, // 成都-会务活动
  3492. 691, // 四川-会务活动
  3493. 762, // 四川-赛事项目收入
  3494. 1047 // 成都-赛事项目收入
  3495. });
  3496. }
  3497. if (groupTypeId.Count > 0)
  3498. {
  3499. sqlWhere += string.Format(@$" And TeamDid In ({string.Join(',', groupTypeId)})");
  3500. }
  3501. string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");
  3502. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();
  3503. if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));
  3504. List<int> diIds = groupInfos.Select(it => it.Id).ToList();
  3505. List<CorporateProfit> corporateProfits = await CorporateProfit(diIds);
  3506. List<MonthInfo> months = new List<MonthInfo>();
  3507. if (_dto.StatisticsType == 1) //月份
  3508. {
  3509. months = GeneralMethod.GetMonthInfos(Convert.ToInt32(_dto.Year));
  3510. }
  3511. else if (_dto.StatisticsType == 1) //季度
  3512. {
  3513. months = GeneralMethod.GetQuarter(Convert.ToInt32(_dto.Year));
  3514. }
  3515. List<CorporateProfitMonthView> _view = new List<CorporateProfitMonthView>();
  3516. foreach (var item in months)
  3517. {
  3518. DateTime monthBeginDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.BeginDays} 00:00:00");
  3519. DateTime monthEndDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.EndDays} 23:59:59");
  3520. var corporateProfit = corporateProfits.Where(it => it.CreateDt >= monthBeginDt && it.CreateDt <= monthEndDt).ToList();
  3521. _view.Add(new CorporateProfitMonthView()
  3522. {
  3523. Month = item.Month,
  3524. Profit = corporateProfit.Sum(it => it.ReceivedProfit),
  3525. GroupInfos = corporateProfit.OrderBy(it => it.CreateDt).ToList()
  3526. });
  3527. }
  3528. return Ok(JsonView(true, "操作成功!", _view));
  3529. #endregion
  3530. }
  3531. /// <summary>
  3532. /// 计算团组利润
  3533. /// </summary>
  3534. /// <param name="diIds"></param>
  3535. /// <returns></returns>
  3536. private async Task<List<CorporateProfit>> CorporateProfit(List<int> diIds)
  3537. {
  3538. List<CorporateProfit> corporateProfits = new List<CorporateProfit>();
  3539. if (diIds.Count < 1)
  3540. {
  3541. return corporateProfits;
  3542. }
  3543. #region 计算团组利润
  3544. /*
  3545. * 团组报表计算方式
  3546. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  3547. * 应收金额 = 应收表.Sum()
  3548. * 已收金额 = 已收表.Sum()
  3549. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  3550. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  3551. *
  3552. */
  3553. string diIdStr = string.Join(",", diIds);
  3554. string sql = string.Format(@$"Select * From Grp_DelegationInfo Where Isdel = 0 And Id In ({diIdStr})");
  3555. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).ToListAsync();
  3556. #region 费用类型 币种,转账,客户信息
  3557. List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  3558. var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>().Where(it => it.IsDel == 0).ToListAsync();
  3559. #endregion
  3560. foreach (var _diId in diIds)
  3561. {
  3562. List<ExpenditureInfo> expenditureInfos = new List<ExpenditureInfo>();
  3563. #region 团组收入
  3564. /*
  3565. * 应收报表
  3566. */
  3567. decimal frTotalAmount = 0.00M;//应收总金额
  3568. string _frSql = string.Format(@"Select fr.Id,fr.Diid,fr.PriceName,fr.Price,fr.Count,fr.Unit,fr.Currency,
  3569. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  3570. From Fin_ForeignReceivables fr
  3571. Left Join Sys_SetData sd On fr.Currency = sd.Id
  3572. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _diId);
  3573. List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  3574. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  3575. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "应收项", Amount = frTotalAmount });
  3576. /*
  3577. * 已收报表
  3578. */
  3579. decimal prTotalAmount = 0.00M;//已收总金额
  3580. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  3581. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  3582. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  3583. From Fin_ProceedsReceived pr
  3584. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  3585. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  3586. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _diId);
  3587. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  3588. prTotalAmount = _prViews.Sum(it => it.Price);
  3589. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "已收项", Amount = prTotalAmount });
  3590. /*
  3591. * 超支费用
  3592. */
  3593. decimal exTotalAmount = 0.00M;
  3594. string _ecSql = string.Format(@"Select gec.Id As GECId,gec.DiId As GECDiId,gec.PriceName,ccp.PayMoney,sd1.Name As PaymentCurrency,
  3595. ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  3596. sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  3597. From OA2023DB.dbo.Fin_GroupExtraCost gec
  3598. Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  3599. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3600. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3601. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  3602. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3603. Where ccp.IsDel = 0 And ccp.CTable = 1015 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ccp.DiId = {0} Order By CreateTime", _diId);
  3604. List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(_ecSql).ToListAsync();
  3605. exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  3606. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "超支费用", Amount = exTotalAmount });
  3607. /*
  3608. * 收款退还
  3609. */
  3610. decimal promTotalAmount = 0.00M;// 收款退还总金额
  3611. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  3612. //删除了 And prom.PriceType = 1
  3613. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  3614. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  3615. prom.PayType As PrPayType,prom.PriceType As PrPriceType,ccp.*,prom.CreateTime As PrCreateTime
  3616. From Fin_PaymentRefundAndOtherMoney prom
  3617. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  3618. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3619. Where prom.IsDel = 0 And prom.PayType = 1 And ccp.CTable = 285
  3620. And ccp.IsAuditGM = 1 And ccp.IsPay = 1
  3621. And prom.DiId = {0} Order By PrCreateTime", _diId);
  3622. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  3623. foreach (var ropItem in _promDatas)
  3624. {
  3625. string thisCueencyCode = "Unknown";
  3626. string thisCueencyName = "Unknown";
  3627. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  3628. if (currency != null)
  3629. {
  3630. thisCueencyCode = currency.Name;
  3631. thisCueencyName = currency.Remark;
  3632. }
  3633. string orbitalPrivateTransferStr = "Unknown";
  3634. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  3635. if (orbitalPrivateTransfer != null)
  3636. {
  3637. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  3638. }
  3639. string payStr = "Unknown";
  3640. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  3641. if (pay != null)
  3642. {
  3643. payStr = pay.Name;
  3644. }
  3645. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  3646. {
  3647. Id = ropItem.Id,
  3648. DiId = ropItem.DIId,
  3649. PriceName = ropItem.PrPriceName,
  3650. PayCurrencyCode = thisCueencyCode,
  3651. PayCurrencyName = thisCueencyName,
  3652. Price = ropItem.PrPrice,
  3653. CNYPrice = ropItem.RMBPrice,
  3654. ThisRate = ropItem.DayRate,
  3655. Payee = ropItem.Payee,
  3656. PayTime = ropItem.AuditGMDate,
  3657. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  3658. PayType = payStr,
  3659. IsPay = ropItem.IsPay,
  3660. Applicant = ropItem.Appliction
  3661. };
  3662. _promView.Add(gsd_PaymentRefund);
  3663. }
  3664. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  3665. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "收款退还", Amount = promTotalAmount });
  3666. #endregion
  3667. #region 团组支出
  3668. GroupExpenditureView _geView = new GroupExpenditureView();
  3669. #region 酒店预定费用
  3670. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  3671. string hotelFeeSql = string.Format(@"Select hr.Id As HrId,hr.DiId As HrDiId,hr.City,hr.HotelName,hr.CheckInDate,hr.CheckOutDate,
  3672. sd1.Name As PaymentCurrency,hr.SingleRoomPrice,hr.SingleRoomCount,hr.DoubleRoomPrice,
  3673. hr.DoubleRoomCount,hr.SuiteRoomPrice,hr.SuiteRoomCount,hr.OtherRoomPrice,hr.OtherRoomCount,
  3674. hr.BreakfastPrice,sd4.Name As BreakfastCurrency,hr.Isoppay,hr.GovernmentRent,
  3675. sd5.Name As GovernmentRentCurrency,hr.CityTax,sd6.Name As CityTaxCurrency,
  3676. ccp.PayMoney,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,
  3677. sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant
  3678. From Grp_HotelReservations hr
  3679. Left Join Grp_CreditCardPayment ccp On hr.Id = ccp.CId
  3680. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3681. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3682. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  3683. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3684. Left Join Sys_SetData sd4 On hr.BreakfastCurrency = sd4.Id
  3685. Left Join Sys_SetData sd5 On hr.GovernmentRentCurrency = sd5.Id
  3686. Left Join Sys_SetData sd6 On hr.CityTaxCurrency = sd6.Id
  3687. Where hr.IsDel = 0 And ccp.IsDel = 0 And ccp.CTable = 76 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And hr.DiId = {0}
  3688. Order By CheckInDate Asc", _diId);
  3689. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  3690. decimal HotelCNYTotalPrice = groupHotelFeeViews.Sum(it => it.CNYPrice);
  3691. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "酒店预定", Amount = HotelCNYTotalPrice });
  3692. #endregion
  3693. #region 地接费用
  3694. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  3695. string CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.Area,ctggrc.*,ctggrc.Price As PayMoney,
  3696. sd2.name As PaymentCurrency,ccp.PayPercentage,
  3697. (ctggrc.Price / (ccp.PayPercentage / 100)) As AmountPaid,
  3698. (ctggrc.Price / (ccp.PayPercentage / 100) - ctggrc.Price) As BalancePayment,
  3699. ccp.DayRate,(ctggrc.Price * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  3700. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  3701. From Grp_CarTouristGuideGroundReservations ctggr
  3702. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price,sd2.Name As PriceCurrency,
  3703. cggrc.PriceContent
  3704. From Grp_CarTouristGuideGroundReservationsContent cggrc
  3705. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  3706. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  3707. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  3708. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  3709. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  3710. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  3711. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  3712. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3713. Where ctggr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ctggr.DiId = {0}
  3714. Order By CreateTime", _diId);
  3715. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  3716. decimal CTGGRCNYTotalPrice = groupCTGGRFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  3717. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "地接", Amount = CTGGRCNYTotalPrice });
  3718. #endregion
  3719. #region 机票预订费用
  3720. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  3721. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  3722. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  3723. sd1.Name As PayMoneyCurrency,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  3724. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime
  3725. From Grp_AirTicketReservations atr
  3726. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  3727. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3728. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3729. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  3730. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  3731. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3732. Where atr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And atr.DiId = {0} Order By CreateTime", _diId);
  3733. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  3734. decimal AirCNYTotalPrice = groupAirFeeViews.Sum(it => it.CNYPrice);
  3735. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "机票预订", Amount = AirCNYTotalPrice });
  3736. #endregion
  3737. #region 签证费用
  3738. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  3739. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  3740. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  3741. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime
  3742. From Grp_VisaInfo vi
  3743. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  3744. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3745. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3746. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  3747. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3748. Where vi.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And vi.DIId = {0} Order By CreateTime", _diId);
  3749. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  3750. decimal VisaCNYTotalPirce = groupVisaFeeViews.Sum(it => it.PayMoney);
  3751. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "签证", Amount = VisaCNYTotalPirce });
  3752. #endregion
  3753. #region 邀请/公务活动 CTable = 81
  3754. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  3755. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  3756. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  3757. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  3758. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  3759. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  3760. From Grp_InvitationOfficialActivities ioa
  3761. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  3762. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3763. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3764. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  3765. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  3766. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  3767. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  3768. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  3769. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3770. Where ioa.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ioa.Diid = {0} Order By CreateTime", _diId);
  3771. groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
  3772. decimal InvitationalCNYTotalPrice = groupInvitationalFeeViews.Sum(it => it.CNYPrice);
  3773. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "邀请/公务活动", Amount = InvitationalCNYTotalPrice });
  3774. #endregion
  3775. #region 保险费用
  3776. List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
  3777. string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.RMBPrice As CNYPrice,
  3778. sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  3779. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
  3780. From Grp_Customers ic
  3781. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  3782. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3783. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3784. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3785. Where ic.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ic.DiId = {0} Order By CreateTime", _diId);
  3786. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  3787. decimal InsuranceCNYTotalPrice = groupInsuranceFeeViews.Sum(it => it.CNYPrice);
  3788. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "保险费用", Amount = InsuranceCNYTotalPrice });
  3789. #endregion
  3790. #region 其他款项费用 98
  3791. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  3792. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  3793. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  3794. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  3795. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  3796. From Grp_DecreasePayments dp
  3797. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  3798. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3799. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3800. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3801. Where dp.IsDel = 0 And ccp.Ctable = 98 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And dp.Diid = {0}
  3802. Order By CreateTime", _diId);
  3803. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  3804. decimal DecreaseCNYTotalPrice = groupDecreaseFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  3805. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "其他款项", Amount = DecreaseCNYTotalPrice });
  3806. #endregion
  3807. #endregion
  3808. /*
  3809. * 团组报表计算方式
  3810. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  3811. * 应收金额 = 应收表.Sum()
  3812. * 已收金额 = 已收表.Sum()
  3813. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  3814. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  3815. *
  3816. */
  3817. decimal _totalExpenditure = 0.00M; //总支出
  3818. decimal _amountReceivable = 0.00M; //应收金额
  3819. decimal _amountReceived = 0.00M; //已收金额
  3820. decimal _receivableProfit = 0.00M; //应收利润
  3821. decimal _receivedProfit = 0.00M; //已收利润
  3822. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  3823. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount;
  3824. _amountReceivable = frTotalAmount;
  3825. _amountReceived = prTotalAmount;
  3826. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  3827. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  3828. var groupInfo = groupInfos.Find(it => it.Id == _diId);
  3829. corporateProfits.Add(new CorporateProfit()
  3830. {
  3831. DiId = _diId,
  3832. TeamName = groupInfo?.TeamName ?? "Unkwnon",
  3833. CreateDt = Convert.ToDateTime(groupInfo?.CreateTime),
  3834. TotalExpenditure = _totalExpenditure,
  3835. ExpenditureItem = expenditureInfos,
  3836. AmountReceivable = _amountReceivable,
  3837. AmountReceived = _amountReceived,
  3838. ReceivableProfit = _receivableProfit,
  3839. ReceivedProfit = _receivedProfit,
  3840. });
  3841. }
  3842. #endregion
  3843. return corporateProfits;
  3844. }
  3845. //未来预测-地区接团/出团量
  3846. //未来预测-地区酒店预订量
  3847. //未来预测-地区机票预订量
  3848. //未来预测-地区车辆预订量
  3849. /// <summary>
  3850. /// (国家/城市)地区预订数量(团,酒店,机票,车辆)
  3851. /// Details
  3852. /// 待添加权限验证
  3853. /// </summary>
  3854. /// <param name="_dto">团组列表请求dto</param>
  3855. /// <returns></returns>
  3856. [HttpPost("PostRegionalBookingsNumber")]
  3857. //[JsonConverter(typeof(DecimalConverter), 2)]
  3858. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3859. public async Task<IActionResult> PostRegionalBookingsNumber(PostRegionalBookingsNumberDto _dto)
  3860. {
  3861. #region 参数验证
  3862. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  3863. //if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  3864. if (_dto.Type > 1 && _dto.Type > 5) return Ok(JsonView(false, "请输入有效的Type参数,1 团 2 酒店 3 机票 4 车辆"));
  3865. if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));
  3866. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3867. #region 页面操作权限验证
  3868. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3869. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  3870. #endregion
  3871. string sqlWhere = string.Empty;
  3872. //起止时间
  3873. DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");
  3874. DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");
  3875. sqlWhere = string.Format(@$" Where Isdel = 0 ");
  3876. string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");
  3877. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();
  3878. if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));
  3879. List<GroupTypeNumberInfo> datas = new List<GroupTypeNumberInfo>();
  3880. foreach (var item in groupInfos)
  3881. {
  3882. var data = await GroupBookingsNumber(_dto.Type, item);
  3883. if (data.TypeItem.Count > 0)
  3884. {
  3885. datas.Add(data);
  3886. }
  3887. }
  3888. //类型处理
  3889. if (_dto.Type == 1)//接团
  3890. {
  3891. List<GroupBookingNumberView> views = new List<GroupBookingNumberView>();
  3892. //dynamic groupData = null;
  3893. foreach (var item in datas)
  3894. {
  3895. if (item.TypeItem.Count > 0)
  3896. {
  3897. foreach (var item1 in item.TypeItem)
  3898. {
  3899. if (item1.RegionItem.Count > 0)
  3900. {
  3901. GroupInfo groupInfo = new GroupInfo()
  3902. {
  3903. DiId = item.DiId,
  3904. TeamName = item.GroupName,
  3905. CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",
  3906. ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",
  3907. Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",
  3908. };
  3909. views.Add(new GroupBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, GroupItem = new List<GroupInfo>() { groupInfo } });
  3910. }
  3911. }
  3912. }
  3913. }
  3914. var viewsGroup = views.GroupBy(it => it.Name);
  3915. List<GroupBookingNumberView> _view = new List<GroupBookingNumberView>();
  3916. foreach (var item in viewsGroup)
  3917. {
  3918. List<GroupInfo> infos = new List<GroupInfo>();
  3919. foreach (var item1 in item)
  3920. {
  3921. infos.AddRange(item1.GroupItem);
  3922. }
  3923. infos = infos.OrderByDescending(it => it.CreateTime).ToList(); //
  3924. _view.Add(new GroupBookingNumberView() { Name = item.Key, Number = item.Count(), GroupItem = infos });
  3925. }
  3926. _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();
  3927. return Ok(JsonView(true, "操作成功!", _view, _view.Count));
  3928. }
  3929. else if (_dto.Type == 2)
  3930. {
  3931. List<HotelBookingNumberView> views = new List<HotelBookingNumberView>();
  3932. foreach (var item in datas)
  3933. {
  3934. if (item.TypeItem.Count > 0)
  3935. {
  3936. foreach (var item1 in item.TypeItem)
  3937. {
  3938. if (item1.RegionItem.Count > 0)
  3939. {
  3940. foreach (var item2 in item1.RegionItem)
  3941. {
  3942. GroupInfo groupInfo = new GroupInfo()
  3943. {
  3944. DiId = item.DiId,
  3945. TeamName = item.GroupName,
  3946. CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",
  3947. ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",
  3948. Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",
  3949. };
  3950. List<HotelInfo> hotels = new List<HotelInfo>();
  3951. foreach (var item3 in item2.Data)
  3952. {
  3953. StatisticsHotelInfo statisticsHotelInfos = JsonConvert.DeserializeObject<StatisticsHotelInfo>(JsonConvert.SerializeObject(item3));
  3954. HotelInfo hotelInfo = new HotelInfo()
  3955. {
  3956. HotelName = statisticsHotelInfos.HotelName,
  3957. SingleRoomNum = statisticsHotelInfos.SingleRoomNum,
  3958. DoubleRoomNum = statisticsHotelInfos.DoubleRoomNum,
  3959. SuiteRoomNum = statisticsHotelInfos.SuiteRoomNum,
  3960. OtherRoomNum = statisticsHotelInfos.OtherRoomNum,
  3961. GroupInfo = groupInfo
  3962. };
  3963. hotels.Add(hotelInfo);
  3964. }
  3965. views.Add(new HotelBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, HotelItem = hotels });
  3966. }
  3967. }
  3968. }
  3969. }
  3970. }
  3971. var viewsGroup = views.GroupBy(it => it.Name);
  3972. List<HotelBookingNumberView> _view = new List<HotelBookingNumberView>();
  3973. foreach (var item in viewsGroup)
  3974. {
  3975. List<HotelInfo> infos = new List<HotelInfo>();
  3976. foreach (var item1 in item)
  3977. {
  3978. infos.AddRange(item1.HotelItem);
  3979. }
  3980. _view.Add(new HotelBookingNumberView() { Name = item.Key, Number = item.Count(), HotelItem = infos });
  3981. }
  3982. _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();
  3983. return Ok(JsonView(true, "操作成功!", views, views.Count));
  3984. }
  3985. return Ok(JsonView(false, "操作失败!"));
  3986. #endregion
  3987. }
  3988. /// <summary>
  3989. /// 计算团组ALLType预订数量
  3990. /// </summary>
  3991. /// <param name="type"></param>
  3992. /// <param name="info"></param>
  3993. /// <returns></returns>
  3994. private async Task<GroupTypeNumberInfo> GroupBookingsNumber(int type, Grp_DelegationInfo info)
  3995. {
  3996. GroupTypeNumberInfo _view = new GroupTypeNumberInfo();
  3997. if (info == null)
  3998. {
  3999. return _view;
  4000. }
  4001. _view.DiId = info.Id;
  4002. _view.GroupName = info.TeamName;
  4003. List<TypeInfo> _types = new List<TypeInfo>();
  4004. #region 计算团组ALLType预订数量
  4005. if (type == 1)
  4006. {
  4007. //接团 客户集团所在地区
  4008. string group_region = string.Empty;
  4009. int group_number = 0;
  4010. if (!string.IsNullOrEmpty(info.ClientUnit))
  4011. {
  4012. var _NewClientData = await _sqlSugar.Queryable<Crm_NewClientData>()
  4013. .Where(it => it.IsDel == 0 && it.Client.Equals(AesEncryptionHelper.Encrypt(info.ClientUnit)))
  4014. .FirstAsync();
  4015. if (_NewClientData != null)
  4016. {
  4017. var regionInfo = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.Id == _NewClientData.Lvlid).FirstAsync();
  4018. if (regionInfo != null)
  4019. {
  4020. group_region = regionInfo.Name.Replace("级", "");
  4021. group_number++;
  4022. }
  4023. }
  4024. }
  4025. if (group_number > 0)
  4026. {
  4027. _types.Add(new TypeInfo() { Id = 1, RegionItem = new List<RegionInfo>() { new RegionInfo() { Name = group_region, Number = group_number } } });
  4028. }
  4029. }
  4030. else if (type == 2)
  4031. {
  4032. //酒店
  4033. var hotelInfos = await _sqlSugar.Queryable<Grp_HotelReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  4034. if (hotelInfos.Count > 0)
  4035. {
  4036. List<RegionInfo> hotelRegions = new List<RegionInfo>();
  4037. foreach (var item in hotelInfos)
  4038. {
  4039. var hotelNumberInfo = new StatisticsHotelInfo()
  4040. {
  4041. HotelName = item.HotelName,
  4042. SingleRoomNum = item.SingleRoomCount,
  4043. DoubleRoomNum = item.DoubleRoomCount,
  4044. SuiteRoomNum = item.SuiteRoomCount,
  4045. OtherRoomNum = item.OtherRoomCount,
  4046. };
  4047. int hotelRoomTotal = item.SingleRoomCount + item.DoubleRoomCount + item.SuiteRoomCount + item.OtherRoomCount;
  4048. if (hotelRegions.Select(it => it.Name).ToList().Contains(item.City))
  4049. {
  4050. RegionInfo hotelRegion = hotelRegions.Find(it => it.Name.Equals(item.City));
  4051. if (hotelRegion != null)
  4052. {
  4053. hotelRegions.Remove(hotelRegion);
  4054. if (hotelRegion.Data.Count > 0)
  4055. {
  4056. hotelRegion.Data.Add(hotelNumberInfo);
  4057. }
  4058. hotelRegion.Number += hotelRoomTotal;
  4059. hotelRegions.Add(hotelRegion);
  4060. }
  4061. }
  4062. else
  4063. {
  4064. hotelRegions.Add(new RegionInfo() { Name = item.City, Number = hotelRoomTotal, Data = new List<dynamic>() { hotelNumberInfo } });
  4065. }
  4066. }
  4067. _types.Add(new TypeInfo() { Id = 2, RegionItem = hotelRegions });
  4068. }
  4069. }
  4070. else if (type == 3)
  4071. {
  4072. //机票
  4073. var airTicketInfos = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
  4074. .LeftJoin<Grp_CreditCardPayment>((atr, ccp) => atr.Id == ccp.CId && ccp.IsPay == 1)
  4075. .LeftJoin<Sys_SetData>((atr, ccp, sd) => atr.CType == sd.Id)
  4076. .Where((atr, ccp, sd) => atr.IsDel == 0 && atr.DIId == info.Id)
  4077. .Select((atr, ccp, sd) => new { atr.ClientNum, atr.CType, ccp.Payee, AirType = sd.Name })
  4078. .ToListAsync();
  4079. if (airTicketInfos.Count > 0)
  4080. {
  4081. List<RegionInfo> airTicketRegions = new List<RegionInfo>();
  4082. foreach (var item in airTicketInfos)
  4083. {
  4084. var ticketClass = new
  4085. {
  4086. TiketClass = item.AirType,
  4087. Number = item.ClientNum
  4088. };
  4089. if (airTicketRegions.Select(it => it.Name).ToList().Contains(item.Payee))
  4090. {
  4091. RegionInfo airTicketRegion = airTicketRegions.Find(it => it.Name.Equals(item.Payee));
  4092. if (airTicketRegion != null)
  4093. {
  4094. airTicketRegions.Remove(airTicketRegion);
  4095. if (airTicketRegion.Data.Count > 0)
  4096. {
  4097. airTicketRegion.Data.Add(ticketClass);
  4098. }
  4099. airTicketRegion.Number += item.ClientNum;
  4100. airTicketRegions.Add(airTicketRegion);
  4101. }
  4102. }
  4103. else
  4104. {
  4105. airTicketRegions.Add(new RegionInfo() { Name = item.Payee, Number = item.ClientNum, Data = new List<dynamic>() { ticketClass } });
  4106. }
  4107. }
  4108. _types.Add(new TypeInfo() { Id = 3, RegionItem = airTicketRegions });
  4109. }
  4110. }
  4111. else if (type == 4)
  4112. {
  4113. //车辆
  4114. var opInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  4115. var opContentInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservationsContent>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  4116. if (opInfos.Count > 0)
  4117. {
  4118. List<RegionInfo> opRegions = new List<RegionInfo>();
  4119. foreach (var item in opInfos)
  4120. {
  4121. int carNum = 0;
  4122. var opContentInfo = opContentInfos.Where(it => it.CTGGRId == item.Id && it.SId == 91).ToList();
  4123. if (opContentInfo.Count > 0)
  4124. {
  4125. foreach (var item1 in opContentInfo)
  4126. {
  4127. if (item1.Price > 0 && item1.Count > 0)
  4128. {
  4129. carNum += item1.Count;
  4130. }
  4131. }
  4132. }
  4133. if (carNum > 0)
  4134. {
  4135. var opData = new
  4136. {
  4137. ServiceCompany = item.ServiceCompany,
  4138. BusName = item.BusName,
  4139. Numbuer = carNum
  4140. };
  4141. if (opRegions.Select(it => it.Name).ToList().Contains(item.Area))
  4142. {
  4143. RegionInfo opRegion = opRegions.Find(it => it.Name.Equals(item.Area));
  4144. if (opRegion != null)
  4145. {
  4146. opRegions.Remove(opRegion);
  4147. if (opRegion.Data.Count > 0)
  4148. {
  4149. opRegion.Data.Add(opData);
  4150. }
  4151. opRegion.Number += carNum;
  4152. opRegions.Add(opRegion);
  4153. }
  4154. }
  4155. else
  4156. {
  4157. opRegions.Add(new RegionInfo() { Name = item.Area, Number = carNum, Data = new List<dynamic>() { opData } });
  4158. }
  4159. }
  4160. }
  4161. _types.Add(new TypeInfo() { Id = 4, RegionItem = opRegions });
  4162. }
  4163. }
  4164. #endregion
  4165. _view.TypeItem = _types;
  4166. return _view;
  4167. }
  4168. #endregion
  4169. #region 市场部销售额
  4170. /// <summary>
  4171. /// 市场部销售额
  4172. /// Init 基础数据(公司/人员/年份/季度/月份)
  4173. /// </summary>
  4174. /// <param name="_dto">市场部销售额请求dto</param>
  4175. /// <returns></returns>
  4176. [HttpPost("PostMarketingSalesInitData")]
  4177. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4178. public async Task<IActionResult> PostMarketingSalesInitData(MarketingSalesInitDataDto _dto)
  4179. {
  4180. #region 参数验证
  4181. MarketingSalesInitDataDtoFoalidator validationRules = new MarketingSalesInitDataDtoFoalidator();
  4182. var validResult = await validationRules.ValidateAsync(_dto);
  4183. if (!validResult.IsValid)
  4184. {
  4185. var errors = new StringBuilder();
  4186. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4187. return Ok(JsonView(false, errors.ToString()));
  4188. }
  4189. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4190. #region 页面操作权限验证
  4191. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4192. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4193. #endregion
  4194. var companyData = _sqlSugar.Queryable<Sys_Company>().Where(it => it.IsDel == 0)
  4195. .Select(it => new { id = it.Id, name = it.CompanyName })
  4196. .ToList();
  4197. List<int> companyIds = companyData.Select(it => it.id).ToList();
  4198. List<int> pickGroupUserIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0)
  4199. .Select(it => it.JietuanOperator)
  4200. .ToList();
  4201. var userData = _sqlSugar.Queryable<Sys_Users>()
  4202. .Where(it => it.IsDel == 0 && (pickGroupUserIds.Contains(it.Id) || it.Id == 21))
  4203. .Select(it => new { id = it.Id, companyId = it.CompanyId, name = it.CnName })
  4204. .ToList();
  4205. companyData.Insert(0, new { id = -1, name = "全部" });
  4206. userData.Insert(0, new { id = -1, companyId = -1, name = "全部" });
  4207. #region 年份
  4208. var dtData = new List<dynamic>();
  4209. int dt = DateTime.Now.Year;
  4210. for (int y = dt; y >= dt - 4; y--)
  4211. {
  4212. //季度
  4213. var quarterDatas = new List<dynamic>();
  4214. quarterDatas.Add(new { name = "全部", beginDt = $"{y}-01-01", endDt = $"{y}-12-31" });
  4215. for (int q = 0; q < 4; q++)
  4216. {
  4217. dynamic quarterData = null;
  4218. if (q == 0)
  4219. {
  4220. var monthDatas = new List<dynamic>();
  4221. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-01-01", endDt = $" {y}-03-31" });
  4222. for (int m = 1; m < 4; m++)
  4223. {
  4224. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  4225. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  4226. }
  4227. //quarterData = new { name = "第一季度", beginDt = $"{y}-01-01", endDt = $" {y}-03-31", monthData = monthDatas };
  4228. quarterData = new { name = "第一季度", monthData = monthDatas };
  4229. }
  4230. else if (q == 1)
  4231. {
  4232. var monthDatas = new List<dynamic>();
  4233. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-04-01", endDt = $"{y}-06-30" });
  4234. for (int m = 4; m < 7; m++)
  4235. {
  4236. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  4237. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  4238. }
  4239. //quarterData = new { name = "第二季度", beginDt = $"{y}-04-01", endDt = $"{y}-06-30", monthData = monthDatas };
  4240. quarterData = new { name = "第二季度", monthData = monthDatas };
  4241. }
  4242. else if (q == 2)
  4243. {
  4244. var monthDatas = new List<dynamic>();
  4245. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-07-01", endDt = $"{y}-09-30" });
  4246. for (int m = 7; m < 10; m++)
  4247. {
  4248. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  4249. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  4250. }
  4251. //quarterData = new { name = "第三季度", beginDt = $"{y}-07-01", endDt = $"{y}-09-30", monthData = monthDatas };
  4252. quarterData = new { name = "第三季度", monthData = monthDatas };
  4253. }
  4254. else if (q == 3)
  4255. {
  4256. var monthDatas = new List<dynamic>();
  4257. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-10-01", endDt = $"{y}-12-31" });
  4258. for (int m = 10; m < 13; m++)
  4259. {
  4260. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  4261. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  4262. }
  4263. //quarterData = new { name = "第四季度", beginDt = $"{y}-10-01", endDt = $"{y}-12-31", monthData = monthDatas };
  4264. quarterData = new { name = "第四季度", monthData = monthDatas };
  4265. }
  4266. quarterDatas.Add(quarterData);
  4267. }
  4268. dtData.Add(new
  4269. {
  4270. year = y,
  4271. //yearData = new { beginDt = $"{y}-01-01", endDt = $"{y}-12-31" },
  4272. quarterData = quarterDatas,
  4273. });
  4274. }
  4275. #endregion
  4276. return Ok(JsonView(true, "操作成功!", new { companyData = companyData, userData = userData, dtData = dtData }));
  4277. #endregion
  4278. }
  4279. private static string ConvertToChinese(int month)
  4280. {
  4281. if (month < 1 || month > 12)
  4282. throw new ArgumentOutOfRangeException(nameof(month), "月份必须在1到12之间。");
  4283. var cultureInfo = new System.Globalization.CultureInfo("zh-CN");
  4284. var dateTimeFormat = cultureInfo.DateTimeFormat;
  4285. return dateTimeFormat.GetMonthName(month);
  4286. }
  4287. /// <summary>
  4288. /// 市场部销售额
  4289. /// 年度/季度/月度 报表(同比)
  4290. /// </summary>
  4291. /// <param name="_dto">市场部销售额请求dto</param>
  4292. /// <returns></returns>
  4293. [HttpPost("PostMarketingSalesStatistics")]
  4294. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4295. public async Task<IActionResult> PostMarketingSalesStatistics_Year(MarketingSalesStatisticsDto _dto)
  4296. {
  4297. #region 参数验证
  4298. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4299. var validResult = await validationRules.ValidateAsync(_dto);
  4300. if (!validResult.IsValid)
  4301. {
  4302. var errors = new StringBuilder();
  4303. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4304. return Ok(JsonView(false, errors.ToString()));
  4305. }
  4306. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4307. #region 页面操作权限验证
  4308. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4309. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4310. #endregion
  4311. #endregion
  4312. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4313. return Ok(JsonView(true, "操作成功!", await GroupSales(_dto.CompanyId, _dto.GroupPickupUserId, beginDt, endDt)));
  4314. }
  4315. private async Task<List<int>> GetUserIds(int companyId, int groupPickupUserId)
  4316. {
  4317. //全部人员Id
  4318. //查询所有公司的市场部
  4319. var pickGroupIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0).Select(it => it.JietuanOperator).Distinct().ToList();
  4320. var userIds = new List<int>();
  4321. var userDatas = await _sqlSugar.Queryable<Sys_Users>()
  4322. .InnerJoin<Sys_Company>((u, c) => u.CompanyId == c.Id)
  4323. .Where((u, c) => u.IsDel == 0 && pickGroupIds.Contains(u.Id))
  4324. .Select((u, c) => new { u.Id, u.CompanyId, u.CnName })
  4325. .ToListAsync();
  4326. userIds = userDatas.Select(it => it.Id).ToList();
  4327. if (companyId > 0)
  4328. {
  4329. userIds = userDatas.Where(it => it.CompanyId == companyId).Select(it => it.Id).ToList();
  4330. }
  4331. if (groupPickupUserId > 0)
  4332. {
  4333. userIds = userDatas.Where(it => it.Id == groupPickupUserId).Select(it => it.Id).ToList();
  4334. }
  4335. return userIds;
  4336. }
  4337. /// <summary>
  4338. /// 计算团组销售额
  4339. /// </summary>
  4340. /// <param name="companyId"></param>
  4341. /// <param name="groupPickupUserId"></param>
  4342. /// <param name="beginDt"></param>
  4343. /// <param name="endDt"></param>
  4344. /// <returns></returns>
  4345. private async Task<SalesYOYView> GroupSales(int companyId, int groupPickupUserId, string beginDt, string endDt)
  4346. {
  4347. decimal thisSales = 0.00M, lastSales = 0.00M, yoy = 1.00M;
  4348. var _view = new SalesYOYView();
  4349. List<int> userIds = new List<int>();
  4350. userIds = await GetUserIds(companyId, groupPickupUserId);
  4351. string userSqlWhere = "";
  4352. if (userIds.Count > 0)
  4353. {
  4354. userSqlWhere = string.Format($" And Id IN ({string.Join(',', userIds)})");
  4355. }
  4356. else
  4357. {
  4358. _view = new SalesYOYView
  4359. {
  4360. thisYearSales = "0.00",
  4361. lastYearSales = "0.00",
  4362. };
  4363. return _view;
  4364. }
  4365. string lastBeginDt = Convert.ToDateTime(beginDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss"),
  4366. lastEndDt = Convert.ToDateTime(endDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss");
  4367. // string salesSql = string.Format(@"
  4368. //SELECT
  4369. // 'ThisSales' As [Name],
  4370. // CAST(SUM(Sales) AS decimal(12,2)) As Sales
  4371. //FROM
  4372. // (
  4373. // SELECT di.VisitDate,
  4374. // (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  4375. // WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  4376. // ) AS Sales
  4377. // FROM
  4378. // Grp_DelegationInfo di
  4379. // WHERE di.IsDel = 0 AND di.IsSure = 1
  4380. // AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
  4381. // AND di.VisitDate BETWEEN '{1}' AND '{2}'
  4382. // ) temp
  4383. //Union ALL
  4384. //SELECT
  4385. // 'LastSales' As [Name],
  4386. // CAST(SUM(Sales) AS decimal(12,2)) As Sales
  4387. //FROM
  4388. // (
  4389. // SELECT di.VisitDate,
  4390. // (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  4391. // WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  4392. // ) AS Sales
  4393. // FROM
  4394. // Grp_DelegationInfo di
  4395. // WHERE di.IsDel = 0 AND di.IsSure = 1
  4396. // AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {3})
  4397. // AND di.VisitDate BETWEEN '{4}' AND '{5}'
  4398. // ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
  4399. string salesSql = string.Format(@"
  4400. SELECT
  4401. 'ThisSales' As [Name],
  4402. CAST(SUM(Sales) AS decimal(12,2)) As Sales
  4403. FROM
  4404. (
  4405. SELECT di.VisitDate,
  4406. (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  4407. WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  4408. ) AS Sales
  4409. FROM
  4410. Grp_DelegationInfo di
  4411. WHERE di.IsDel = 0
  4412. AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
  4413. AND di.VisitDate BETWEEN '{1}' AND '{2}'
  4414. ) temp
  4415. Union ALL
  4416. SELECT
  4417. 'LastSales' As [Name],
  4418. CAST(SUM(Sales) AS decimal(12,2)) As Sales
  4419. FROM
  4420. (
  4421. SELECT di.VisitDate,
  4422. (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  4423. WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  4424. ) AS Sales
  4425. FROM
  4426. Grp_DelegationInfo di
  4427. WHERE di.IsDel = 0
  4428. AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {3})
  4429. AND di.IsBid = 0
  4430. AND di.TeamName Not Like '%投标%'
  4431. AND di.VisitDate BETWEEN '{4}' AND '{5}'
  4432. ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
  4433. var salesData = await _sqlSugar.SqlQueryable<SalesView>(salesSql).ToListAsync();
  4434. thisSales = salesData.Where(x => x.Name.Equals("ThisSales")).First()?.Sales ?? 0;
  4435. lastSales = salesData.Where(x => x.Name.Equals("LastSales")).First()?.Sales ?? 0;
  4436. if (lastSales != 0 && thisSales != 0) yoy = (thisSales - lastSales) / lastSales;
  4437. return new SalesYOYView()
  4438. {
  4439. thisYearSales = thisSales.ToString("#0.00"),
  4440. lastYearSales = lastSales.ToString("#0.00"),
  4441. yoy = yoy.ToString("#0.00")
  4442. };
  4443. }
  4444. private class SalesView
  4445. {
  4446. public string Name { get; set; }
  4447. public decimal Sales { get; set; }
  4448. }
  4449. private class SalesYOYView
  4450. {
  4451. public string thisYearSales { get; set; }
  4452. public string lastYearSales { get; set; }
  4453. public string yoy { get; set; } = "1.00";
  4454. }
  4455. /// <summary>
  4456. /// 市场部销售额
  4457. /// 团组列表
  4458. /// </summary>
  4459. /// <param name="_dto">市场部销售额请求dto</param>
  4460. /// <returns></returns>
  4461. [HttpPost("PostMarketingSalesGroupList")]
  4462. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4463. public async Task<IActionResult> PostMarketingSalesGroupList(MarketingSalesGroupListDto _dto)
  4464. {
  4465. #region 参数验证
  4466. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4467. var validResult = await validationRules.ValidateAsync(_dto);
  4468. if (!validResult.IsValid)
  4469. {
  4470. var errors = new StringBuilder();
  4471. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4472. return Ok(JsonView(false, errors.ToString()));
  4473. }
  4474. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4475. #region 页面操作权限验证
  4476. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4477. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4478. #endregion
  4479. #endregion
  4480. string userSql = "";
  4481. List<int> userIds = new List<int>();
  4482. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4483. if (userIds.Count <= 0)
  4484. {
  4485. return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  4486. }
  4487. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  4488. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  4489. {
  4490. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  4491. }
  4492. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4493. // string sql = string.Format(@$"SELECT
  4494. // ROW_NUMBER() OVER (
  4495. // ORDER BY
  4496. // CollectionDays
  4497. // ) AS RowNumber,
  4498. // *
  4499. //FROM
  4500. // (
  4501. // SELECT
  4502. // di.Id,
  4503. // di.TeamName,
  4504. // di.ClientUnit,
  4505. // di.ClientName,
  4506. // di.VisitDate,
  4507. // di.VisitPNumber,
  4508. // di.JietuanOperator,
  4509. // di.VisitEndDate,
  4510. // (
  4511. // SELECT
  4512. // CAST(
  4513. // COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4514. // ) AS GroupSales
  4515. // FROM
  4516. // Fin_ForeignReceivables
  4517. // WHERE
  4518. // IsDel = 0
  4519. // AND di.Id = Diid
  4520. // AND AddingWay IN (0, 1, 2)
  4521. // ) AS GroupSales,
  4522. // u.CnName AS GroupPickupUser,
  4523. // DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  4524. // FROM
  4525. // Grp_DelegationInfo di
  4526. // WITH
  4527. // (NoLock)
  4528. // LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  4529. // WHERE
  4530. // di.Isdel = 0
  4531. // AND di.IsSure = 1 {userSql}
  4532. // AND VisitDate Between '{beginDt}' And '{endDt}'
  4533. // ) Temp ");
  4534. string sql = string.Format(@$"SELECT
  4535. ROW_NUMBER() OVER (
  4536. ORDER BY
  4537. CollectionDays
  4538. ) AS RowNumber,
  4539. *
  4540. FROM
  4541. (
  4542. SELECT
  4543. di.Id,
  4544. di.TeamName,
  4545. di.ClientUnit,
  4546. di.ClientName,
  4547. di.VisitDate,
  4548. di.VisitPNumber,
  4549. di.JietuanOperator,
  4550. di.VisitEndDate,
  4551. (
  4552. SELECT
  4553. CAST(
  4554. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4555. ) AS GroupSales
  4556. FROM
  4557. Fin_ForeignReceivables
  4558. WHERE
  4559. IsDel = 0
  4560. AND di.Id = Diid
  4561. AND AddingWay IN (0, 1, 2)
  4562. ) AS GroupSales,
  4563. u.CnName AS GroupPickupUser,
  4564. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  4565. FROM
  4566. Grp_DelegationInfo di
  4567. WITH
  4568. (NoLock)
  4569. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  4570. WHERE
  4571. di.Isdel = 0
  4572. AND (
  4573. SELECT
  4574. CAST(
  4575. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4576. ) AS GroupSales
  4577. FROM
  4578. Fin_ForeignReceivables
  4579. WHERE
  4580. IsDel = 0
  4581. AND di.Id = Diid
  4582. AND AddingWay IN (0, 1, 2)
  4583. ) > 0
  4584. {userSql}
  4585. AND di.IsBid = 0
  4586. AND di.TeamName Not Like '%投标%'
  4587. AND VisitDate Between '{beginDt}' And '{endDt}'
  4588. ) Temp ");
  4589. RefAsync<int> total = 0;
  4590. var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  4591. return Ok(JsonView(true, "操作成功!", groupData, total));
  4592. }
  4593. /// <summary>
  4594. /// 市场部销售额
  4595. /// 团组列表Excel下载
  4596. /// </summary>
  4597. /// <param name="_dto">市场部销售额请求dto</param>
  4598. /// <returns></returns>
  4599. [HttpPost("PostMarketingSalesGroupExcel")]
  4600. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4601. public async Task<IActionResult> PostMarketingSalesGroupExcel(MarketingSalesGroupListDto _dto)
  4602. {
  4603. #region 参数验证
  4604. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4605. var validResult = await validationRules.ValidateAsync(_dto);
  4606. if (!validResult.IsValid)
  4607. {
  4608. var errors = new StringBuilder();
  4609. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4610. return Ok(JsonView(false, errors.ToString()));
  4611. }
  4612. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4613. #region 页面操作权限验证
  4614. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4615. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4616. #endregion
  4617. #endregion
  4618. string userSql = "";
  4619. var userIds = new List<int>();
  4620. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4621. if (userIds.Count <= 0)
  4622. {
  4623. return Ok(JsonView(false));
  4624. }
  4625. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  4626. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  4627. {
  4628. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  4629. }
  4630. string beginDt = $"{_dto.BeginDt} 00:00:00",
  4631. endDt = $"{_dto.EndDt} 23:59:59";
  4632. string sql = string.Format(@$"SELECT
  4633. ROW_NUMBER() OVER (
  4634. ORDER BY
  4635. CollectionDays
  4636. ) AS RowNumber,
  4637. *
  4638. FROM
  4639. (
  4640. SELECT
  4641. di.Id,
  4642. di.TeamName,
  4643. di.ClientUnit,
  4644. di.ClientName,
  4645. di.VisitDate,
  4646. di.VisitPNumber,
  4647. di.JietuanOperator,
  4648. di.VisitEndDate,
  4649. (
  4650. SELECT
  4651. CAST(
  4652. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4653. ) AS GroupSales
  4654. FROM
  4655. Fin_ForeignReceivables
  4656. WHERE
  4657. IsDel = 0
  4658. AND di.Id = Diid
  4659. AND AddingWay IN (0, 1, 2)
  4660. ) AS GroupSales,
  4661. u.CnName AS GroupPickupUser,
  4662. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  4663. FROM
  4664. Grp_DelegationInfo di
  4665. WITH
  4666. (NoLock)
  4667. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  4668. WHERE
  4669. di.Isdel = 0
  4670. AND (
  4671. SELECT
  4672. CAST(
  4673. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4674. ) AS GroupSales
  4675. FROM
  4676. Fin_ForeignReceivables
  4677. WHERE
  4678. IsDel = 0
  4679. AND di.Id = Diid
  4680. AND AddingWay IN (0, 1, 2)
  4681. ) > 0
  4682. {userSql}
  4683. AND di.IsBid = 0
  4684. AND di.TeamName Not Like '%投标%'
  4685. AND VisitDate Between '{beginDt}' And '{endDt}'
  4686. ) Temp ");
  4687. var view = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToListAsync();
  4688. if (view.Count < 1) return Ok(JsonView(false, "暂无数据!"));
  4689. //DataTable dt = GeneralMethod.
  4690. DataTable dt = CommonFun.GetDataTableFromIList(view);
  4691. dt.TableName = $"_view";
  4692. WorkbookDesigner designer = new WorkbookDesigner();
  4693. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/营业额团组报表模板.xls");
  4694. designer.SetDataSource(dt);
  4695. designer.SetDataSource("Total", view.Sum(x => x.GroupSales));
  4696. designer.Workbook.Worksheets[0].Name = "营业额团组报表";
  4697. designer.Process();
  4698. string fileName = $"MarketingSales/{_dto.BeginDt}~{_dto.EndDt}营业额团组报表{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
  4699. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  4700. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  4701. return Ok(JsonView(true, "操作成功", new { url = rst }));
  4702. }
  4703. /// <summary>
  4704. /// 市场部销售额
  4705. /// 客户类型、客户等级 统计
  4706. /// </summary>
  4707. /// <param name="_dto">市场部销售额请求dto</param>
  4708. /// <returns></returns>
  4709. [HttpPost("PostMarketingSalesGroupStatistics")]
  4710. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4711. public async Task<IActionResult> PostMarketingSalesGroupStatistics(MarketingSalesGroupStatisticsDto _dto)
  4712. {
  4713. #region 参数验证
  4714. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4715. var validResult = await validationRules.ValidateAsync(_dto);
  4716. if (!validResult.IsValid)
  4717. {
  4718. var errors = new StringBuilder();
  4719. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4720. return Ok(JsonView(false, errors.ToString()));
  4721. }
  4722. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4723. #region 页面操作权限验证
  4724. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4725. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4726. #endregion
  4727. #endregion
  4728. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4729. List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4730. string userSql = "";
  4731. if (userIds.Count > 0)
  4732. {
  4733. userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
  4734. }
  4735. else
  4736. {
  4737. if (_dto.PortType == 2 || _dto.PortType == 3)
  4738. {
  4739. return Ok(JsonView(true, "操作成功!", new List<object> { }));
  4740. }
  4741. else
  4742. {
  4743. return Ok(JsonView(true, "操作成功!", new
  4744. {
  4745. customerTypeData = new List<object> { },
  4746. clientGradeData = new List<object> { }
  4747. }));
  4748. }
  4749. }
  4750. string sql = "";
  4751. if (_dto.StatisticsType == 1)
  4752. {
  4753. sql = string.Format(@$"Select
  4754. sd.[Name],
  4755. Count(*) As [Count]
  4756. From Grp_DelegationInfo di
  4757. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  4758. Where di.Isdel = 0
  4759. And (
  4760. SELECT
  4761. CAST(
  4762. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4763. ) AS GroupSales
  4764. FROM
  4765. Fin_ForeignReceivables fr
  4766. WHERE
  4767. fr.IsDel = 0
  4768. AND di.Id = fr.Diid
  4769. AND AddingWay IN (0, 1, 2)
  4770. ) > 0
  4771. {userSql}
  4772. AND di.IsBid = 0
  4773. AND di.TeamName Not Like '%投标%'
  4774. And VisitDate Between '{beginDt}' And '{endDt}'
  4775. Group By [Name]
  4776. Order By Count Desc");
  4777. }
  4778. else if (_dto.StatisticsType == 2)
  4779. {
  4780. sql = string.Format(@$"Select
  4781. sd.[Name],
  4782. Count(*) As [Count]
  4783. From Grp_DelegationInfo di
  4784. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  4785. Where di.Isdel = 0
  4786. And (
  4787. SELECT
  4788. CAST(
  4789. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4790. ) AS GroupSales
  4791. FROM
  4792. Fin_ForeignReceivables fr
  4793. WHERE
  4794. fr.IsDel = 0
  4795. AND di.Id = fr.Diid
  4796. AND AddingWay IN (0, 1, 2)
  4797. ) > 0
  4798. {userSql}
  4799. AND di.IsBid = 0
  4800. AND di.TeamName Not Like '%投标%'
  4801. And VisitDate Between '{beginDt}' And '{endDt}'
  4802. Group By [Name]
  4803. Order By Count Desc");
  4804. }
  4805. else return Ok(JsonView(false, "StatisticsType不在可取范围!"));
  4806. if (_dto.PortType == 1)
  4807. {
  4808. string sql1 = string.Format(@$"Select
  4809. sd.[Name],
  4810. Count(*) As [Count]
  4811. From Grp_DelegationInfo di
  4812. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  4813. Where di.Isdel = 0
  4814. And (
  4815. SELECT
  4816. CAST(
  4817. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4818. ) AS GroupSales
  4819. FROM
  4820. Fin_ForeignReceivables fr
  4821. WHERE
  4822. fr.IsDel = 0
  4823. AND di.Id = fr.Diid
  4824. AND AddingWay IN (0, 1, 2)
  4825. ) > 0
  4826. {userSql}
  4827. AND di.IsBid = 0
  4828. AND di.TeamName Not Like '%投标%'
  4829. And VisitDate Between '{beginDt}' And '{endDt}'
  4830. Group By [Name]
  4831. Order By Count Desc");
  4832. var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
  4833. string sql2 = string.Format(@$"Select
  4834. sd.[Name],
  4835. Count(*) As [Count]
  4836. From Grp_DelegationInfo di
  4837. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  4838. Where di.Isdel = 0
  4839. And (
  4840. SELECT
  4841. CAST(
  4842. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4843. ) AS GroupSales
  4844. FROM
  4845. Fin_ForeignReceivables fr
  4846. WHERE
  4847. fr.IsDel = 0
  4848. AND di.Id = fr.Diid
  4849. AND AddingWay IN (0, 1, 2)
  4850. ) > 0
  4851. {userSql}
  4852. AND di.IsBid = 0
  4853. AND di.TeamName Not Like '%投标%'
  4854. And VisitDate Between '{beginDt}' And '{endDt}'
  4855. Group By [Name]
  4856. Order By Count Desc");
  4857. var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
  4858. return Ok(JsonView(true, "操作成功!", new
  4859. {
  4860. customerTypeData = customerTypeData,
  4861. clientGradeData = clientGradeData
  4862. }));
  4863. }
  4864. else if (_dto.PortType == 2 || _dto.PortType == 3)
  4865. {
  4866. var data = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql).ToListAsync();
  4867. return Ok(JsonView(true, "操作成功!", data, data.Count));
  4868. }
  4869. else return Ok(JsonView(false, MsgTips.Port));
  4870. }
  4871. /// <summary>
  4872. /// 市场部销售额
  4873. /// 接单排名
  4874. /// </summary>
  4875. /// <param name="_dto">市场部销售额请求dto</param>
  4876. /// <returns></returns>
  4877. [HttpPost("PostMarketingSalesOrderRanking")]
  4878. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4879. public async Task<IActionResult> PostMarketingSalesOrderRanking(MarketingSalesOrderRankingDto _dto)
  4880. {
  4881. #region 参数验证
  4882. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4883. var validResult = await validationRules.ValidateAsync(_dto);
  4884. if (!validResult.IsValid)
  4885. {
  4886. var errors = new StringBuilder();
  4887. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4888. return Ok(JsonView(false, errors.ToString()));
  4889. }
  4890. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4891. #region 页面操作权限验证
  4892. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4893. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4894. #endregion
  4895. #endregion
  4896. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4897. List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4898. string userSql = "";
  4899. if (userIds.Count > 0)
  4900. {
  4901. userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
  4902. }
  4903. else return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  4904. string sql = string.Format(@$"Select
  4905. ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
  4906. u.CnName As UserName,
  4907. Count(*) As [Count]
  4908. From Grp_DelegationInfo di
  4909. Left Join Sys_Users u On di.JietuanOperator = u.Id
  4910. Where di.Isdel = 0
  4911. AND (
  4912. SELECT
  4913. CAST(
  4914. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4915. ) AS GroupSales
  4916. FROM
  4917. Fin_ForeignReceivables fr
  4918. WHERE
  4919. fr.IsDel = 0
  4920. AND di.Id = fr.Diid
  4921. AND AddingWay IN (0, 1, 2)
  4922. ) > 0
  4923. {userSql}
  4924. AND di.IsBid = 0
  4925. AND di.TeamName Not Like '%投标%'
  4926. AND VisitDate Between '{beginDt}' AND '{endDt}'
  4927. Group By CnName");
  4928. RefAsync<int> total = 0;
  4929. var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  4930. return Ok(JsonView(true, "操作成功!", rankingData, total));
  4931. }
  4932. /// <summary>
  4933. /// 市场部销售额
  4934. /// 团组列表、客户类型、客户等级、接单排名
  4935. /// </summary>
  4936. /// <param name="_dto">市场部销售额请求dto</param>
  4937. /// <returns></returns>
  4938. [HttpPost("PostMarketingSalesGroupItem")]
  4939. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4940. public async Task<IActionResult> PostMarketingSalesGroupItem(MarketingSalesGroupListDto _dto)
  4941. {
  4942. #region 参数验证
  4943. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4944. var validResult = await validationRules.ValidateAsync(_dto);
  4945. if (!validResult.IsValid)
  4946. {
  4947. var errors = new StringBuilder();
  4948. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4949. return Ok(JsonView(false, errors.ToString()));
  4950. }
  4951. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4952. #region 页面操作权限验证
  4953. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4954. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4955. #endregion
  4956. #endregion
  4957. string userSql = "";
  4958. List<int> userIds = new List<int>();
  4959. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4960. if (userIds.Count <= 0)
  4961. {
  4962. return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  4963. }
  4964. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  4965. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  4966. {
  4967. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  4968. }
  4969. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4970. #region 团组List
  4971. string sql = string.Format(@$"SELECT
  4972. ROW_NUMBER() OVER (
  4973. ORDER BY
  4974. CollectionDays
  4975. ) AS RowNumber,
  4976. *
  4977. FROM
  4978. (
  4979. SELECT
  4980. di.Id,
  4981. di.TeamName,
  4982. di.ClientUnit,
  4983. di.ClientName,
  4984. di.VisitDate,
  4985. di.VisitPNumber,
  4986. di.JietuanOperator,
  4987. di.VisitEndDate,
  4988. (
  4989. SELECT
  4990. CAST(
  4991. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4992. ) AS GroupSales
  4993. FROM
  4994. Fin_ForeignReceivables
  4995. WHERE
  4996. IsDel = 0
  4997. AND di.Id = Diid
  4998. AND AddingWay IN (0, 1, 2)
  4999. ) AS GroupSales,
  5000. u.CnName AS GroupPickupUser,
  5001. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  5002. FROM
  5003. Grp_DelegationInfo di
  5004. WITH
  5005. (NoLock)
  5006. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  5007. WHERE
  5008. di.Isdel = 0
  5009. AND (
  5010. SELECT
  5011. CAST(
  5012. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  5013. ) AS GroupSales
  5014. FROM
  5015. Fin_ForeignReceivables fr
  5016. WHERE
  5017. fr.IsDel = 0
  5018. AND di.Id = fr.Diid
  5019. AND AddingWay IN (0, 1, 2)
  5020. ) > 0
  5021. {userSql}
  5022. AND di.IsBid = 0
  5023. AND di.TeamName Not Like '%投标%'
  5024. AND VisitDate Between '{beginDt}' And '{endDt}'
  5025. ) Temp ");
  5026. RefAsync<int> total = 0;
  5027. var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  5028. #endregion
  5029. #region 客户类型、客户等级 统计
  5030. string sql1 = string.Format(@$"Select
  5031. sd.[Name],
  5032. Count(*) As [Count]
  5033. From Grp_DelegationInfo di
  5034. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  5035. Where di.Isdel = 0
  5036. And (
  5037. SELECT
  5038. CAST(
  5039. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  5040. ) AS GroupSales
  5041. FROM
  5042. Fin_ForeignReceivables fr
  5043. WHERE
  5044. fr.IsDel = 0
  5045. AND di.Id = fr.Diid
  5046. AND AddingWay IN (0, 1, 2)
  5047. ) > 0
  5048. {userSql}
  5049. AND di.IsBid = 0
  5050. AND di.TeamName Not Like '%投标%'
  5051. And VisitDate Between '{beginDt}' And '{endDt}'
  5052. Group By [Name]
  5053. Order By Count Desc");
  5054. var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
  5055. string sql2 = string.Format(@$"Select
  5056. sd.[Name],
  5057. Count(*) As [Count]
  5058. From Grp_DelegationInfo di
  5059. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  5060. Where di.Isdel = 0
  5061. And (
  5062. SELECT
  5063. CAST(
  5064. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  5065. ) AS GroupSales
  5066. FROM
  5067. Fin_ForeignReceivables fr
  5068. WHERE
  5069. fr.IsDel = 0
  5070. AND di.Id = fr.Diid
  5071. AND AddingWay IN (0, 1, 2)
  5072. ) > 0
  5073. {userSql}
  5074. AND di.IsBid = 0
  5075. AND di.TeamName Not Like '%投标%'
  5076. And VisitDate Between '{beginDt}' And '{endDt}'
  5077. Group By [Name]
  5078. Order By Count Desc");
  5079. var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
  5080. #endregion
  5081. #region 接单排名
  5082. string sql4 = string.Format(@$"Select
  5083. ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
  5084. u.CnName As UserName,
  5085. Count(*) As [Count]
  5086. From Grp_DelegationInfo di
  5087. Left Join Sys_Users u On di.JietuanOperator = u.Id
  5088. Where di.Isdel = 0
  5089. And (
  5090. SELECT
  5091. CAST(
  5092. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  5093. ) AS GroupSales
  5094. FROM
  5095. Fin_ForeignReceivables fr
  5096. WHERE
  5097. fr.IsDel = 0
  5098. AND di.Id = fr.Diid
  5099. AND AddingWay IN (0, 1, 2)
  5100. ) > 0
  5101. {userSql}
  5102. AND di.IsBid = 0
  5103. AND di.TeamName Not Like '%投标%'
  5104. And VisitDate Between '{beginDt}' And '{endDt}'
  5105. Group By CnName");
  5106. var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql4).ToListAsync();
  5107. #endregion
  5108. var viewData = new
  5109. {
  5110. groupData = groupData,
  5111. groupTotal = total,
  5112. customerTypeData = customerTypeData,
  5113. clientGradeData = clientGradeData,
  5114. rankingData = rankingData
  5115. };
  5116. return Ok(JsonView(true, "操作成功!", viewData, total));
  5117. }
  5118. /// <summary>
  5119. /// 市场部销售额
  5120. /// 客户拜访列表
  5121. /// </summary>
  5122. /// <param name="_dto">市场部销售额请求dto</param>
  5123. /// <returns></returns>
  5124. [HttpPost("PostMarketingSalesVCList")]
  5125. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5126. public async Task<IActionResult> PostMarketingSalesVCList(MarketingSalesVCListDto _dto)
  5127. {
  5128. #region 参数验证
  5129. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  5130. var validResult = await validationRules.ValidateAsync(_dto);
  5131. if (!validResult.IsValid)
  5132. {
  5133. var errors = new StringBuilder();
  5134. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  5135. return Ok(JsonView(false, errors.ToString()));
  5136. }
  5137. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  5138. #region 页面操作权限验证
  5139. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  5140. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  5141. #endregion
  5142. #endregion
  5143. return Ok(await _visitingClientsRep._List(_dto.PortType, _dto.PageIndex, _dto.PageSize, _dto.DiId, _dto.Search));
  5144. }
  5145. /// <summary>
  5146. /// 市场部销售额
  5147. /// 客户拜访 操作(添加 Or 编辑)
  5148. /// </summary>
  5149. /// <param name="_dto">市场部销售额请求dto</param>
  5150. /// <returns></returns>
  5151. [HttpPost("PostMarketingSalesVCOperate")]
  5152. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5153. public async Task<IActionResult> PostMarketingSalesVCOperate(MarketingSalesVCOperrateDto _dto)
  5154. {
  5155. #region 参数验证
  5156. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  5157. var validResult = await validationRules.ValidateAsync(_dto);
  5158. if (!validResult.IsValid)
  5159. {
  5160. var errors = new StringBuilder();
  5161. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  5162. return Ok(JsonView(false, errors.ToString()));
  5163. }
  5164. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  5165. #region 页面操作权限验证
  5166. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  5167. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  5168. #endregion
  5169. #endregion
  5170. return Ok(await _visitingClientsRep._AddOrEdit(_dto));
  5171. }
  5172. /// <summary>
  5173. /// 市场部销售额
  5174. /// 客户拜访 Del
  5175. /// </summary>
  5176. /// <param name="_dto">市场部销售额请求dto</param>
  5177. /// <returns></returns>
  5178. [HttpPost("PostMarketingSalesVCDel")]
  5179. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5180. public async Task<IActionResult> PostMarketingSalesVCDel(MarketingSalesVCDelDto _dto)
  5181. {
  5182. return Ok(await _visitingClientsRep._Del(_dto.Id, _dto.UserId));
  5183. }
  5184. /// <summary>
  5185. /// 市场部销售额
  5186. /// 客户拜访 操作 save
  5187. /// </summary>
  5188. /// <param name="_dto">市场部销售额请求dto</param>
  5189. /// <returns></returns>
  5190. [HttpPost("PostMarketingSalesVCSave")]
  5191. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5192. public async Task<IActionResult> PostMarketingSalesVCSave(MarketingSalesVCSaveDto _dto)
  5193. {
  5194. #region 参数验证
  5195. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  5196. var validResult = await validationRules.ValidateAsync(_dto);
  5197. if (!validResult.IsValid)
  5198. {
  5199. var errors = new StringBuilder();
  5200. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  5201. return Ok(JsonView(false, errors.ToString()));
  5202. }
  5203. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  5204. #region 页面操作权限验证
  5205. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  5206. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  5207. #endregion
  5208. #endregion
  5209. return Ok(await _visitingClientsRep._Save(_dto));
  5210. }
  5211. #endregion
  5212. #region 日付报表
  5213. /// <summary>
  5214. /// 日付类型数据
  5215. /// </summary>
  5216. /// <param name="_dto"></param>
  5217. /// <returns></returns>
  5218. [HttpPost("DailypaymentTypeInit")]
  5219. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5220. public async Task<IActionResult> DailypaymentTypeInit(DailypaymentTypeInitDto _dto)
  5221. {
  5222. #region 参数验证
  5223. if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
  5224. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  5225. #region 页面操作权限验证
  5226. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  5227. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  5228. #endregion
  5229. #endregion
  5230. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  5231. {
  5232. var defaultParentIds = new List<int>()
  5233. {
  5234. 48, // 人员费用
  5235. 49, // 办公费用
  5236. 50, // 销售费用
  5237. 51, // 其他费用
  5238. 55, // 大运会
  5239. 90, // 各部门基础固定费用明细
  5240. 104, // 团组费用
  5241. 116, // 物资采购
  5242. };
  5243. var dailypaymentTypeData = await RedisRepository.RedisFactory
  5244. .CreateRedisRepository()
  5245. .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
  5246. var dailyTypeData = await _sqlSugar.Queryable<DailypaymentParentTypeView>()
  5247. .Includes(x => x.SubData)
  5248. .Where(x => defaultParentIds.Contains(x.Id))
  5249. .ToListAsync();
  5250. dailyTypeData.ForEach(x =>
  5251. {
  5252. x.SubData.ForEach(y =>
  5253. {
  5254. int currId = dailypaymentTypeData.Find(z => z == y.Id);
  5255. y.IsChecked = currId != 0;
  5256. });
  5257. });
  5258. var companyData = await _sqlSugar.Queryable<Sys_Company>()
  5259. .Where(x => x.IsDel == 0)
  5260. .Select(x => new { id = x.Id, name = x.CompanyName })
  5261. .ToListAsync();
  5262. return Ok(JsonView(true, "查询成功!", new { dailyTypeData, companyData }));
  5263. }
  5264. else return Ok(JsonView(false, "查询失败"));
  5265. }
  5266. /// <summary>
  5267. /// 日付类型数据 Save
  5268. /// </summary>
  5269. /// <param name="_dto"></param>
  5270. /// <returns></returns>
  5271. [HttpPost("DailypaymentTypeDataSave")]
  5272. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5273. public async Task<IActionResult> DailypaymentTypeDataSave(DailypaymentTypeDataSaveDto _dto)
  5274. {
  5275. #region 参数验证
  5276. if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
  5277. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  5278. #region 页面操作权限验证
  5279. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  5280. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  5281. #endregion
  5282. #endregion
  5283. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  5284. {
  5285. if (_dto.TypeIds.Count < 1) return Ok(JsonView(false, "请传入需要保存的TypeIds"));
  5286. var res = await RedisRepository.RedisFactory
  5287. .CreateRedisRepository()
  5288. .StringSetAsync(
  5289. key: "DailypaymentTypeData",
  5290. _dto.TypeIds,
  5291. timeout: null);
  5292. if (!res) return Ok(JsonView(false, "操作失败"));
  5293. return Ok(JsonView(true, "操作成功!"));
  5294. }
  5295. else return Ok(JsonView(false, "操作失败"));
  5296. }
  5297. /// <summary>
  5298. /// 日付数据列表
  5299. /// </summary>
  5300. /// <param name="_dto"></param>
  5301. /// <returns></returns>
  5302. [HttpPost("DailypaymentRange")]
  5303. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5304. public async Task<IActionResult> DailypaymentRange(DailypaymentRangeDto _dto)
  5305. {
  5306. #region 参数验证
  5307. var validator = new DailypaymentRangeDtoValidator();
  5308. var validationRes = validator.Validate(_dto);
  5309. if (!validationRes.IsValid)
  5310. {
  5311. StringBuilder sb = new StringBuilder();
  5312. foreach (var item in validationRes.Errors)
  5313. {
  5314. sb.AppendLine(item.ErrorMessage);
  5315. }
  5316. return Ok(JsonView(false, sb.ToString()));
  5317. }
  5318. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  5319. #region 页面操作权限验证
  5320. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  5321. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  5322. #endregion
  5323. #endregion
  5324. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  5325. {
  5326. DateTime _beginDt = Convert.ToDateTime($"{_dto.BeginDt} 00:00:00"),
  5327. _endDt = Convert.ToDateTime($"{_dto.EndDt} 23:59:59");
  5328. var sqlWhere = string.Format(@" And dfp.CreateTime Between '{0}' And '{1}'", _beginDt, _endDt);
  5329. var dailypaymentTypeData = await RedisRepository.RedisFactory
  5330. .CreateRedisRepository()
  5331. .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
  5332. var sql = string.Format(@"
  5333. Select
  5334. dfp.Id,
  5335. dfp.Instructions,
  5336. dfp.PriceTypeId,
  5337. sd1.Name As FeeType,
  5338. dfp.TransferTypeId,
  5339. sd2.Name As TransferType,
  5340. dfp.SumPrice,
  5341. dfp.FAuditDate,
  5342. dfp.MAuditDate,
  5343. dfp.CompanyId,
  5344. c.CompanyName,
  5345. dfp.CreateUserId As ApplicantId,
  5346. u.CnName As Applicant,
  5347. dfp.CreateTime As ApplicantDt,
  5348. dfp.Instructions+u.CnName As ViewStr
  5349. From Fin_DailyFeePayment dfp
  5350. Left Join Sys_Users u On dfp.CreateUserId = u.Id
  5351. Left Join Sys_SetData sd1 On dfp.TransferTypeId = sd1.Id
  5352. Left Join Sys_Company c On dfp.CompanyId = c.Id
  5353. Left Join Sys_SetData sd2 On dfp.PriceTypeId = sd2.Id
  5354. Where dfp.IsDel = 0
  5355. -- And dfp.IsPay = 1
  5356. ");//--Order By dfp.CreateTime Desc
  5357. if (_dto.Type == 1) //data
  5358. {
  5359. RefAsync<int> total = 0;
  5360. var _view = await _sqlSugar.SqlQueryable<DailyFeePaymentRangeView>(sql)
  5361. .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
  5362. .WhereIF(dailypaymentTypeData.Count > 0,
  5363. x => dailypaymentTypeData.Contains(x.PriceTypeId))
  5364. .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
  5365. .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
  5366. .OrderByDescending(x => x.ApplicantDt)
  5367. .ToPageListAsync(
  5368. pageNumber: _dto.PageIndex,
  5369. pageSize: _dto.PageSize,
  5370. totalNumber: total
  5371. );
  5372. _sqlSugar.ThenMapper(_view, x =>
  5373. {
  5374. x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
  5375. .SetContext(x1 => x1.DFPId, () => x.Id, x)
  5376. .Where(x => x.IsDel == 0)
  5377. .ToList();
  5378. });
  5379. //单独处理
  5380. return Ok(JsonView(true, "操作成功!", new { data = _view, total = _view.Sum(x => x.SumPrice) }, total));
  5381. }
  5382. else if (_dto.Type == 2) //view
  5383. {
  5384. var _view = await _sqlSugar.SqlQueryable<ExcelView>(sql)
  5385. .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
  5386. .WhereIF(dailypaymentTypeData.Count > 0,
  5387. x => dailypaymentTypeData.Contains(x.PriceTypeId))
  5388. .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
  5389. .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
  5390. .OrderByDescending(x => x.ApplicantDt)
  5391. .ToPageListAsync(
  5392. pageNumber: 1,
  5393. pageSize: 99999
  5394. );
  5395. _sqlSugar.ThenMapper(_view, x =>
  5396. {
  5397. x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
  5398. .SetContext(x1 => x1.DFPId, () => x.Id, x)
  5399. .Where(x => x.IsDel == 0)
  5400. .ToList();
  5401. string str = "";
  5402. int index = 1;
  5403. foreach (var item in x.Contents)
  5404. {
  5405. string str1 = $"{index}、费用名称:[{item.PriceName}] 单价:[{item.Price:#0.00}] 数量:[{item.Quantity:#0.00}] 小计:[{item.ItemTotal:#0.00}] 备注:[{item.Remark}]";
  5406. if (index == x.Contents.Count) str += str1;
  5407. else str += str1 + "\r\n";
  5408. index++;
  5409. }
  5410. x.ContentStr = str;
  5411. });
  5412. if (_view.Count > 0)
  5413. {
  5414. //DataTable dt = GeneralMethod.
  5415. DataTable dt = CommonFun.GetDataTableFromIList(_view);
  5416. dt.TableName = $"_view";
  5417. decimal total = _view.Sum(x => x.SumPrice);
  5418. WorkbookDesigner designer = new WorkbookDesigner();
  5419. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/日付报表模板.xls");
  5420. designer.SetDataSource(dt);
  5421. designer.SetDataSource("Total", total);
  5422. designer.Workbook.Worksheets[0].Name = "日付报表";
  5423. designer.Process();
  5424. string fileName = $"DailyPayment/日付报表{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
  5425. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  5426. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  5427. return Ok(JsonView(true, "操作成功", new { url = rst }));
  5428. }
  5429. return Ok(JsonView(true, ",暂无数据"));
  5430. }
  5431. return Ok(JsonView(false, "操作失败"));
  5432. }
  5433. else return Ok(JsonView(false, "操作失败"));
  5434. }
  5435. #endregion
  5436. #region 统计模块
  5437. /// <summary>
  5438. /// 同比
  5439. /// 营业额(今年和去年的)、成本支出(今年和去年的)、毛利润(今年和去年的)
  5440. /// </summary>
  5441. /// <param name="_dto">市场部销售额请求dto</param>
  5442. /// <returns></returns>
  5443. [HttpPost("StatisticsYOY")]
  5444. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5445. public async Task<IActionResult> StatisticsYOY(YOYDto _dto)
  5446. {
  5447. //同比增长率 = (本期 - 同期) / 同期 * 100%;
  5448. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5449. string beginDt = $"{_dto.Year - 1}-01-01 00:00:00",
  5450. endDt = $"{_dto.Year}-12-31 23:59:59";
  5451. string sql = string.Format(@"
  5452. SELECT
  5453. di.Id,
  5454. di.TeamName,
  5455. di.VisitDate,
  5456. YEAR(di.VisitDate) AS YEAR,
  5457. MONTH(di.VisitDate) AS MONTH,
  5458. (
  5459. SELECT
  5460. CAST(SUM(ItemSumPrice * Rate) AS DECIMAL(12, 2))
  5461. FROM
  5462. Fin_ForeignReceivables
  5463. WHERE
  5464. IsDel = 0
  5465. AND AddingWay IN (0, 1, 2)
  5466. AND di.Id = Diid
  5467. ) AS SaleAmount,
  5468. (
  5469. SELECT
  5470. CAST(
  5471. SUM(
  5472. (
  5473. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  5474. )
  5475. ) AS DECIMAL(12, 2)
  5476. )
  5477. FROM
  5478. Grp_AirTicketReservations atr
  5479. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5480. AND ccp.CTable = 85
  5481. AND atr.Id = ccp.CId
  5482. WHERE
  5483. atr.IsDel = 0
  5484. AND ccp.IsAuditGM = 1
  5485. AND ccp.IsPay = 1
  5486. AND di.Id = atr.DiId
  5487. ) AirTicketAmount,
  5488. (
  5489. SELECT
  5490. CAST(
  5491. SUM(
  5492. (
  5493. ctggr.ServiceQuotedPrice * (ccp.PayPercentage / 100) * ccp.DayRate
  5494. )
  5495. ) AS DECIMAL(12, 2)
  5496. )
  5497. FROM
  5498. Grp_CarTouristGuideGroundReservations ctggr
  5499. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  5500. AND ccp.CTable = 79
  5501. AND ctggr.Id = ccp.CId
  5502. WHERE
  5503. ctggr.IsDel = 0
  5504. AND ccp.IsAuditGM = 1
  5505. AND ccp.IsPay = 1
  5506. AND di.Id = ctggr.DiId
  5507. ) AS OPAmount,
  5508. (
  5509. SELECT
  5510. CAST(SUM((ccp.PayMoney * ccp.DayRate)) AS DECIMAL(12, 2))
  5511. FROM
  5512. Grp_DecreasePayments dp
  5513. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5514. AND ccp.CTable = 98
  5515. AND dp.Id = ccp.CId
  5516. WHERE
  5517. dp.IsDel = 0
  5518. AND ccp.Ctable = 98
  5519. AND ccp.IsAuditGM = 1
  5520. AND ccp.IsPay = 1
  5521. AND di.Id = dp.Diid
  5522. ) AS OtherCostAmount,
  5523. (
  5524. SELECT
  5525. CAST(
  5526. SUM(
  5527. (
  5528. (ccp.PayMoney * ccp.DayRate)
  5529. )
  5530. ) AS DECIMAL(12, 2)
  5531. )
  5532. FROM
  5533. Grp_VisaInfo vi
  5534. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5535. AND ccp.CTable = 80
  5536. AND vi.Id = ccp.CId
  5537. WHERE
  5538. vi.IsDel = 0
  5539. AND ccp.IsAuditGM = 1
  5540. AND ccp.IsPay = 1
  5541. AND di.Id = vi.DIId
  5542. ) AS VisaAmount,
  5543. (
  5544. SELECT
  5545. CAST(
  5546. SUM(
  5547. (ccp.PayMoney * ccp.DayRate)
  5548. ) AS DECIMAL(12, 2)
  5549. )
  5550. FROM
  5551. Grp_InvitationOfficialActivities ioa
  5552. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5553. AND ccp.CTable = 81
  5554. AND ioa.Id = ccp.CId
  5555. WHERE
  5556. ioa.IsDel = 0
  5557. AND ccp.IsAuditGM = 1
  5558. AND ccp.IsPay = 1
  5559. AND di.Id = ioa.Diid
  5560. ) AS OAAmount,
  5561. (
  5562. SELECT
  5563. CAST(
  5564. SUM(
  5565. (ccp.PayMoney * ccp.DayRate)
  5566. ) AS DECIMAL(12, 2)
  5567. )
  5568. FROM
  5569. Grp_Customers ic
  5570. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5571. AND ccp.CTable = 82
  5572. AND ic.Id = ccp.CId
  5573. WHERE
  5574. ic.IsDel = 0
  5575. AND ccp.IsAuditGM = 1
  5576. AND ccp.IsPay = 1
  5577. AND di.Id = ic.DiId
  5578. ) AS InsureAmount,
  5579. (
  5580. SELECT
  5581. CAST(
  5582. SUM(
  5583. (ccp.PayMoney * ccp.DayRate)
  5584. ) AS DECIMAL(12, 2)
  5585. )
  5586. FROM
  5587. Grp_HotelReservations hr
  5588. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  5589. WHERE
  5590. hr.IsDel = 0
  5591. AND ccp.IsDel = 0
  5592. AND ccp.CTable = 76
  5593. AND ccp.IsAuditGM = 1
  5594. AND ccp.PayMoney <> 0
  5595. AND ccp.IsPay = 1
  5596. AND di.Id = hr.DiId
  5597. ) AS HotelAmount,
  5598. (
  5599. SELECT
  5600. CAST(
  5601. SUM((gec.PriceSum * gec.Coefficient * ccp.DayRate)) AS DECIMAL(12, 2)
  5602. )
  5603. FROM
  5604. OA2023DB.dbo.Fin_GroupExtraCost gec
  5605. INNER JOIN Grp_CreditCardPayment ccp ON gec.Id = ccp.CId
  5606. WHERE
  5607. ccp.IsDel = 0
  5608. AND ccp.CTable = 1015
  5609. AND ccp.IsAuditGM = 1
  5610. AND ccp.IsPay = 1
  5611. AND di.Id = gec.DiId
  5612. ) AS ExcessAmount,
  5613. (
  5614. SELECT
  5615. CAST(
  5616. SUM(
  5617. (ccp.PayMoney * ccp.DayRate)
  5618. ) AS DECIMAL(12, 2)
  5619. )
  5620. FROM
  5621. Fin_PaymentRefundAndOtherMoney prom
  5622. INNER JOIN Grp_CreditCardPayment ccp ON prom.DiId = ccp.DIId
  5623. AND prom.Id = ccp.CId
  5624. WHERE
  5625. prom.IsDel = 0
  5626. AND prom.PayType = 1
  5627. AND ccp.CTable = 285
  5628. AND ccp.IsAuditGM = 1
  5629. AND ccp.IsPay = 1
  5630. AND di.Id = prom.DiId
  5631. ) AS SKTHAmount
  5632. FROM
  5633. Grp_DelegationInfo di
  5634. WHERE
  5635. di.IsDel = 0
  5636. AND di.TeamDid IN (38,39,40,1048)
  5637. AND di.VisitDate BETWEEN '{0}' AND '{1}'
  5638. ORDER BY
  5639. di.VisitDate
  5640. ", beginDt, endDt);
  5641. var data = await _sqlSugar.SqlQueryable<StatisticsYOYView>(sql).ToListAsync();
  5642. var thisYearData = data.Where(x => x.Year == _dto.Year).ToList();
  5643. var lastYearData = data.Where(x => x.Year == (_dto.Year - 1)).ToList();
  5644. List<YOYReturnView> salesYOYData = new List<YOYReturnView>();
  5645. List<YOYReturnView> costYOYData = new List<YOYReturnView>();
  5646. List<YOYReturnView> grossProfitYOYData = new List<YOYReturnView>();
  5647. int monthIndex = 1;
  5648. while (monthIndex < 13)
  5649. {
  5650. var thisMonthData = thisYearData.Where(x => x.Month == monthIndex).ToList();
  5651. var lastMonthData = lastYearData.Where(x => x.Month == monthIndex).ToList();
  5652. var thisGroupIds = thisMonthData.Select(x => x.Id).ToList();
  5653. var lastGroupIds = lastMonthData.Select(x => x.Id).ToList();
  5654. decimal thisSalesAmount = thisMonthData.Sum(x => x?.SaleAmount ?? 0.00M),
  5655. lastSalesAmount = lastMonthData.Sum(x => x?.SaleAmount ?? 0.00M),
  5656. thisCostAmount = thisMonthData.Sum(x => x?.CostAmount ?? 0.00M),
  5657. lastCostAmount = lastMonthData.Sum(x => x?.CostAmount ?? 0.00M),
  5658. thisgrossProfitAmount = thisMonthData.Sum(x => x?.GrossProfitAmount ?? 0.00M),
  5659. lastgrossProfitAmount = lastMonthData.Sum(x => x?.GrossProfitAmount ?? 0.00M);
  5660. salesYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisSalesAmount, lastSalesAmount, thisGroupIds, lastGroupIds));
  5661. costYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisCostAmount, lastCostAmount, thisGroupIds, lastGroupIds));
  5662. grossProfitYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisgrossProfitAmount, lastgrossProfitAmount, thisGroupIds, lastGroupIds));
  5663. monthIndex++;
  5664. }
  5665. salesYOYData = salesYOYData.OrderBy(x => x.Month).ToList();
  5666. costYOYData = costYOYData.OrderBy(x => x.Month).ToList();
  5667. grossProfitYOYData = grossProfitYOYData.OrderBy(x => x.Month).ToList();
  5668. return Ok(JsonView(true, "操作成功!", new { salesYOYData = salesYOYData, costYOYData = costYOYData, grossProfitYOYData = grossProfitYOYData }));
  5669. }
  5670. /// <summary>
  5671. /// 国交数据统计-机票相关
  5672. /// 机票票数、机票到达地、预订平台
  5673. /// </summary>
  5674. /// <param name="_dto"></param>
  5675. /// <returns></returns>
  5676. [HttpPost("StatisticsAirTicket")]
  5677. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5678. public async Task<IActionResult> StatisticsAirTicket(YOYDto _dto)
  5679. {
  5680. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5681. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5682. endDt = $"{_dto.Year}-12-31 23:59:59";
  5683. string sql = string.Format(@"
  5684. SELECT
  5685. atr.DIId,
  5686. atr.FlightsDate,
  5687. YEAR(atr.FlightsDate) AS YEAR,
  5688. MONTH(atr.FlightsDate) AS MONTH,
  5689. atr.CType,
  5690. sd.Name As CTypeName,
  5691. atr.FlightsCity,
  5692. atr.ClientNum,
  5693. atr.ClientName,
  5694. di.TeamName As 'GroupName',
  5695. CASE
  5696. WHEN ccp.Payee = '' OR ccp.Payee IS NULL THEN '未知'
  5697. ELSE ccp.Payee
  5698. END AS 'Platform'
  5699. FROM
  5700. Grp_AirTicketReservations atr
  5701. INNER JOIN Grp_CreditCardPayment ccp ON atr.Id = ccp.CId
  5702. AND ccp.IsDel = 0
  5703. AND CTable = 85
  5704. INNER JOIN Grp_DelegationInfo di ON atr.DIId = di.Id
  5705. LEFT JOIN Sys_SetData sd On atr.CType = sd.Id
  5706. WHERE
  5707. atr.IsDel = 0
  5708. AND di.TeamDid IN (38,39,40,1048)
  5709. AND atr.CType IN(457,458,459,460,574,575)
  5710. AND CHARINDEX('行程单',atr.ClientName) = 0
  5711. AND CHARINDEX('返点',atr.ClientName) = 0
  5712. AND CHARINDEX('-1',atr.ClientName) = 0
  5713. AND ccp.IsPay = 1
  5714. AND atr.FlightsDate BETWEEN '{0}' AND '{1}'
  5715. ORDER BY atr.FlightsDate
  5716. ", beginDt, endDt);
  5717. var data = await _sqlSugar.SqlQueryable<StatisticsAirTicketView>(sql).ToListAsync();
  5718. var groupIds = data.Select(x => x.DIId).ToList();
  5719. //处理城市数据
  5720. var threeCodeData = await _sqlSugar.Queryable<Res_ThreeCode>().Where(x => x.IsDel == 0).ToListAsync();
  5721. //处理团组名称
  5722. var groupNames = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => groupIds.Contains(x.Id)).Select(x => new { Id = x.Id, GroupName = x.TeamName }).ToListAsync();
  5723. data.ForEach(x =>
  5724. {
  5725. string cityName = "";
  5726. if (!string.IsNullOrEmpty(x.FlightsCity))
  5727. {
  5728. string cityCode = x.FlightsCity.Replace("-", "").Replace("/", "");
  5729. int cityNum = cityCode.Length / 3;
  5730. if (cityCode.Length % 3 == 0)
  5731. {
  5732. for (int i = 0; i < cityNum; i++)
  5733. {
  5734. string code = "";
  5735. if (i == 0) code = cityCode.Substring(0, 3);
  5736. else code = cityCode.Substring(i * 3, 3);
  5737. if (!string.IsNullOrEmpty(code))
  5738. {
  5739. if (i == cityNum - 1)
  5740. {
  5741. cityName += threeCodeData.Find(x1 => x1.Three.Equals(code))?.City ?? "";
  5742. }
  5743. else
  5744. {
  5745. var str1 = threeCodeData.Find(x1 => x1.Three.Equals(code))?.City ?? "";
  5746. cityName += str1 + "、";
  5747. }
  5748. }
  5749. }
  5750. }
  5751. }
  5752. x.FlightsCityName = cityName;
  5753. });
  5754. var airTicketNumData = new List<AirTicketReturnView>();
  5755. var airTicketAreaData = new List<AirTicketCityReturnView>();
  5756. int monthIndex = 1;
  5757. while (monthIndex < 13)
  5758. {
  5759. var monthData = data.Where(x => x.Month == monthIndex).ToList();
  5760. //机票票数处理
  5761. int airticket_quantity = monthData.Sum(x => x.ClientNum);
  5762. var linkGroupIds = monthData.Select(x => x.DIId).ToList();
  5763. List<AitTicketInfo> aitTicketInfos = new List<AitTicketInfo>();
  5764. foreach (var item in monthData)
  5765. {
  5766. string groupName = groupNames.Find(x => item.DIId == x.Id)?.GroupName ?? "";
  5767. aitTicketInfos.Add(new AitTicketInfo(item.DIId, groupName, item.ClientNum));
  5768. }
  5769. var aitTicketInfosGroupBy = aitTicketInfos.GroupBy(x => x.Id);
  5770. List<AitTicketInfo> aitTicketInfos1 = new List<AitTicketInfo>();
  5771. foreach (var item in aitTicketInfosGroupBy)
  5772. {
  5773. aitTicketInfos1.Add(new AitTicketInfo(item.Key, item.First().GroupName, item.Sum(x => x.Quantity)));
  5774. }
  5775. aitTicketInfos1 = aitTicketInfos1.OrderBy(x => x.Quantity).ToList();
  5776. linkGroupIds = linkGroupIds.Distinct().ToList();
  5777. airTicketNumData.Add(new AirTicketReturnView(_dto.Year, monthIndex, airticket_quantity, aitTicketInfos1, linkGroupIds));
  5778. //机票城市处理
  5779. //城市处理
  5780. var airTicketCityInfos = new List<string>();
  5781. foreach (var item in monthData)
  5782. {
  5783. if (!string.IsNullOrEmpty(item.FlightsCityName))
  5784. {
  5785. if (item.FlightsCityName.Contains("、"))
  5786. {
  5787. var cityArray = item.FlightsCityName.Split("、").ToList();
  5788. foreach (var item1 in cityArray)
  5789. {
  5790. if (!string.IsNullOrEmpty(item1))
  5791. {
  5792. airTicketCityInfos.Add(item1);
  5793. }
  5794. }
  5795. }
  5796. else
  5797. {
  5798. airTicketCityInfos.Add(item.FlightsCityName);
  5799. }
  5800. }
  5801. }
  5802. //int quantity1 = airTicketCityInfos.Count;
  5803. int city_totalquantity = 0;
  5804. var airTicketCityInfosGroupby = airTicketCityInfos.GroupBy(x => x);
  5805. var airTicketCityInfos1 = new List<AirTicketCityInfo>();
  5806. foreach (var item in airTicketCityInfosGroupby)
  5807. {
  5808. var city_quantity = item.ToList().Count;
  5809. city_totalquantity += city_quantity;
  5810. airTicketCityInfos1.Add(new AirTicketCityInfo(item.Key, city_quantity));
  5811. }
  5812. airTicketCityInfos1 = airTicketCityInfos1.OrderByDescending(x => x.Quantity).ToList();
  5813. airTicketAreaData.Add(new AirTicketCityReturnView(_dto.Year, monthIndex, city_totalquantity, airTicketCityInfos1, linkGroupIds));
  5814. monthIndex++;
  5815. }
  5816. var airTicketPlatformData = data.GroupBy(g => g.Platform)
  5817. .Select(g => new
  5818. {
  5819. platform = g.Key,
  5820. total = g.Sum(x => x.ClientNum),
  5821. children = g.GroupBy(g1 => g1.DIId)
  5822. .Select(g1 => new
  5823. {
  5824. diId = g1.Key,
  5825. groupName = g1.FirstOrDefault()?.GroupName ?? "-",
  5826. total = g1.Sum(x1 => x1.ClientNum),
  5827. children = g1.Select(x1 => new
  5828. {
  5829. //diId = x1.DIId,
  5830. //groupName = x1.GroupName,
  5831. flightsCityName = x1.FlightsCityName,
  5832. total = x1.ClientNum
  5833. })
  5834. .ToList()
  5835. })
  5836. .OrderByDescending(x1 => x1.total)
  5837. .ToList()
  5838. })
  5839. .OrderByDescending(x => x.total)
  5840. .ToList();
  5841. return Ok(JsonView(true, "操作成功!", new
  5842. {
  5843. airTicketNumData = airTicketNumData,
  5844. airTicketAreaData = airTicketAreaData,
  5845. airTicketPlatformData = airTicketPlatformData
  5846. }));
  5847. }
  5848. /// <summary>
  5849. /// 国交数据统计-酒店
  5850. /// 国家TOP10、地区TOP10、预订平台
  5851. /// </summary>
  5852. /// <param name="_dto"></param>
  5853. /// <returns></returns>
  5854. [HttpPost("StatisticsHotel")]
  5855. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5856. public async Task<IActionResult> StatisticsHotel(YOYDto _dto)
  5857. {
  5858. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5859. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5860. endDt = $"{_dto.Year}-12-31 23:59:59";
  5861. string sql = string.Format(@"
  5862. SELECT
  5863. hr.DIId,
  5864. CASE
  5865. WHEN ntf.Country IS NULL THEN '未选择'
  5866. ELSE ntf.Country
  5867. END AS 'Country',
  5868. hr.City,
  5869. hr.HotelName,
  5870. sd.Name AS BookinSite,
  5871. hr.CheckInDate,
  5872. YEAR(hr.CheckInDate) AS YEAR,
  5873. MONTH(hr.CheckInDate) AS MONTH,
  5874. hr.CheckOutDate,
  5875. hr.SingleRoomCount,
  5876. hr.DoubleRoomCount,
  5877. hr.SuiteRoomCount,
  5878. hr.OtherRoomCount
  5879. FROM
  5880. Grp_HotelReservations hr
  5881. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  5882. AND ccp.IsDel = 0
  5883. AND CTable = 76
  5884. INNER JOIN Grp_DelegationInfo di ON hr.DiId = di.Id
  5885. LEFT JOIN Sys_SetData sd ON hr.ReservationsWebsite = sd.Id
  5886. LEFT JOIN Grp_NationalTravelFee ntf ON hr.AreaId = ntf.Id
  5887. WHERE
  5888. hr.IsDel = 0
  5889. AND di.TeamDid IN (38,39,40,1048)
  5890. AND ccp.IsPay = 1
  5891. AND (
  5892. hr.SingleRoomCount > 0
  5893. OR hr.DoubleRoomCount > 0
  5894. OR hr.SuiteRoomCount > 0
  5895. OR hr.OtherRoomCount > 0
  5896. )
  5897. AND CHARINDEX('早餐',hr.HotelName) = 0
  5898. AND CHARINDEX('晚餐',hr.HotelName) = 0
  5899. AND CHARINDEX('升级',hr.HotelName) = 0
  5900. AND CHARINDEX('饮料茶水费',hr.HotelName) = 0
  5901. AND CHARINDEX('城市税',hr.HotelName) = 0
  5902. AND CHARINDEX('退款',hr.HotelName) = 0
  5903. AND CHARINDEX('返现',hr.HotelName) = 0
  5904. AND CHARINDEX('会议室',hr.HotelName) = 0
  5905. AND CHARINDEX('迷你吧消费',hr.HotelName) = 0
  5906. AND CHARINDEX('运费',hr.HotelName) = 0
  5907. AND CHARINDEX('地接',hr.HotelName) = 0
  5908. AND CHARINDEX('损失',hr.HotelName) = 0
  5909. AND CHARINDEX('补差',hr.HotelName) = 0
  5910. AND hr.CheckInDate BETWEEN CONVERT(datetime,'{0}') AND CONVERT(datetime,'{1}')
  5911. ORDER BY
  5912. hr.CheckInDate
  5913. ", beginDt, endDt);
  5914. var data = await _sqlSugar.SqlQueryable<StatisticsHotelView>(sql).ToListAsync();
  5915. var hotelCountryGroupByData = data.GroupBy(x => x.Country)
  5916. .Select(g => new
  5917. {
  5918. Country = g.Key,
  5919. BookingRoomNum = g.Sum(x => x.RoomTotal),
  5920. hotelData = g.GroupBy(x => x.HotelName)
  5921. .Select(g1 => new
  5922. {
  5923. hotelName = g1.Key,
  5924. roomNights = g1.Sum(x => x.RoomNights),
  5925. roomTotal = g1.Sum(x => x.RoomTotal),
  5926. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  5927. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  5928. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  5929. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  5930. })
  5931. .ToList(),
  5932. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  5933. })
  5934. .OrderByDescending(x => x.BookingRoomNum)
  5935. .Take(10)
  5936. .ToList();
  5937. var hotelData = data.OrderBy(x => x.CityStr).ToList();
  5938. var hotelCityGroupByData = data.GroupBy(x => x.CityStr)
  5939. .Select(g => new
  5940. {
  5941. city = g.Key,
  5942. BookingRoomNum = g.Sum(x => x.RoomTotal),
  5943. hotelData = g.GroupBy(x => x.HotelName)
  5944. .Select(g1 => new
  5945. {
  5946. hotelName = g1.Key,
  5947. roomNights = g1.Sum(x => x.RoomNights),
  5948. roomTotal = g1.Sum(x => x.RoomTotal),
  5949. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  5950. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  5951. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  5952. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  5953. })
  5954. .ToList(),
  5955. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  5956. })
  5957. .OrderByDescending(x => x.BookingRoomNum)
  5958. .Take(10)
  5959. .ToList();
  5960. var hotelPlatformGroupByData = data.GroupBy(x => x.BookinSite)
  5961. .Select(g => new
  5962. {
  5963. Platform = g.Key,
  5964. BookingRoomNum = g.Sum(x => x.RoomTotal),
  5965. hotelData = g.GroupBy(x => x.HotelName)
  5966. .Select(g1 => new
  5967. {
  5968. hotelName = g1.Key,
  5969. roomNights = g1.Sum(x => x.RoomNights),
  5970. roomTotal = g1.Sum(x => x.RoomTotal),
  5971. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  5972. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  5973. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  5974. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  5975. })
  5976. .ToList(),
  5977. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  5978. })
  5979. .OrderByDescending(x => x.BookingRoomNum)
  5980. .ToList();
  5981. return Ok(JsonView(true, "操作成功!", new { hotelCountryGroupByData = hotelCountryGroupByData, hotelCityData = hotelCityGroupByData, hotelPlatformData = hotelPlatformGroupByData }));
  5982. }
  5983. /// <summary>
  5984. /// 国交数据统计
  5985. /// 商邀邀请国家数量TOP10
  5986. /// </summary>
  5987. /// <param name="_dto"></param>
  5988. /// <returns></returns>
  5989. [HttpPost("StatisticsInvitation")]
  5990. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5991. public async Task<IActionResult> StatisticsInvitation(YOYDto _dto)
  5992. {
  5993. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5994. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5995. endDt = $"{_dto.Year}-12-31 23:59:59";
  5996. string sql = string.Format(@"
  5997. SELECT
  5998. oa.DiId,
  5999. di.TeamName AS GroupName,
  6000. oa.Country,
  6001. oa.Area AS City,
  6002. oa.Client,
  6003. oa.Date
  6004. FROM
  6005. Res_OfficialActivities oa
  6006. LEFT JOIN Grp_DelegationInfo di ON oa.DiId = di.Id
  6007. WHERE
  6008. oa.IsDel = 0
  6009. AND oa.Date BETWEEN '{0}' AND '{1}'
  6010. ", beginDt, endDt);
  6011. var data = await _sqlSugar.SqlQueryable<StatisticsInvitation_HW>(sql).ToListAsync();
  6012. var groupByCountry = data.GroupBy(x => x.Country)
  6013. .Select(g => new
  6014. {
  6015. Country = g.Key,
  6016. TimeNum = g.Count(),
  6017. LinkGroupIds = g.Select(x => x.GroupName).Distinct().ToList()
  6018. })
  6019. .OrderByDescending(x => x.TimeNum)
  6020. .Take(10)
  6021. .ToList();
  6022. var groupByClient = data.GroupBy(x => x.Client)
  6023. .Select(g => new
  6024. {
  6025. Country = g.Key,
  6026. TimeNum = g.Count(),
  6027. LinkGroupIds = g.Select(x => x.GroupName).Distinct().ToList()
  6028. })
  6029. .OrderByDescending(x => x.TimeNum)
  6030. .Take(10)
  6031. .ToList();
  6032. return Ok(JsonView(true, "操作成功!", new { groupByCountry = groupByCountry, groupByClient = groupByClient }));
  6033. }
  6034. /// <summary>
  6035. /// 会务数据统计
  6036. /// 会务城市TOP10排序
  6037. /// </summary>
  6038. /// <param name="_dto"></param>
  6039. /// <returns></returns>
  6040. [HttpPost("StatisticsConferenceCity")]
  6041. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6042. public async Task<IActionResult> StatisticsConferenceCity(YOYDto _dto)
  6043. {
  6044. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  6045. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  6046. endDt = $"{_dto.Year}-12-31 23:59:59";
  6047. string sql = string.Format(@"
  6048. SELECT
  6049. ioa.DiId,
  6050. ioa.InviterArea AS Country
  6051. FROM
  6052. Grp_InvitationOfficialActivities ioa
  6053. INNER JOIN Grp_CreditCardPayment ccp ON ioa.Id = ccp.CId
  6054. AND ccp.IsDel = 0
  6055. AND ccp.CTable = 81
  6056. INNER JOIN Grp_DelegationInfo di ON ioa.DiId = di.Id
  6057. WHERE
  6058. ioa.IsDel = 0
  6059. AND di.TeamDid IN (102,248,302,691,762,1047)
  6060. AND ccp.IsPay = 1
  6061. AND ioa.CreateTime BETWEEN '{0}' AND '{1}'
  6062. ", beginDt, endDt);
  6063. var data = await _sqlSugar.SqlQueryable<StatisticsInvitation>(sql).ToListAsync();
  6064. var groupByData = data.GroupBy(x => x.Country)
  6065. .Select(g => new
  6066. {
  6067. Country = g.Key,
  6068. TimeNum = g.Count(),
  6069. LinkGroupIds = g.Select(x => x.DIId).ToList()
  6070. })
  6071. .OrderByDescending(x => x.TimeNum)
  6072. .Take(10)
  6073. .ToList();
  6074. return Ok(JsonView(true, "操作成功!", groupByData));
  6075. }
  6076. /// <summary>
  6077. /// 团组数据统计
  6078. /// 团组合作前十的客户TOP10排序
  6079. /// </summary>
  6080. /// <param name="_dto"></param>
  6081. /// <returns></returns>
  6082. [HttpPost("StatisticsCooperativeCustomer")]
  6083. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6084. public async Task<IActionResult> StatisticsCooperativeCustomer(YOYDto _dto)
  6085. {
  6086. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  6087. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  6088. endDt = $"{_dto.Year}-12-31 23:59:59";
  6089. DateTime _beginDt = Convert.ToDateTime(beginDt),
  6090. _endDt = Convert.ToDateTime(endDt);
  6091. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  6092. .Where(x => x.IsDel == 0)
  6093. //.Where(x => x.IsSure == 1)
  6094. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  6095. .ToListAsync();
  6096. var groupInfos1 = groupInfos.GroupBy(x => x.ClientName);
  6097. var view = groupInfos1.Select(x =>
  6098. new
  6099. {
  6100. clienName = x.Key,
  6101. clientUnit = x.FirstOrDefault()?.ClientUnit ?? "",
  6102. visitsNum = x.Count()
  6103. }
  6104. )
  6105. .OrderByDescending(x => x.visitsNum)
  6106. .Take(10)
  6107. .ToList();
  6108. return Ok(JsonView(true, "操作成功!", view));
  6109. }
  6110. /// <summary>
  6111. /// 团组数据统计
  6112. /// 已出团客户单位的类型比例图(饼状图-政府团、企业团等)
  6113. /// </summary>
  6114. /// <param name="_dto"></param>
  6115. /// <returns></returns>
  6116. [HttpPost("StatisticsCooperativeCustomerType")]
  6117. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6118. public async Task<IActionResult> StatisticsCooperativeCustomerType(YOYDto _dto)
  6119. {
  6120. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  6121. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  6122. endDt = $"{_dto.Year}-12-31 23:59:59";
  6123. DateTime _beginDt = Convert.ToDateTime(beginDt),
  6124. _endDt = Convert.ToDateTime(endDt);
  6125. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  6126. .LeftJoin<Sys_SetData>((di, sd) => di.TeamDid == sd.Id)
  6127. .Where((di, sd) => di.IsDel == 0)
  6128. .Where((di, sd) => di.VisitDate >= _beginDt && di.VisitDate <= _endDt)
  6129. .Select((di, sd) => new
  6130. {
  6131. Id = di.Id,
  6132. GroupTypeId = di.TeamDid,
  6133. GroupTypeName = sd.Name,
  6134. })
  6135. .ToListAsync();
  6136. var groupInfos1 = groupInfos.GroupBy(x => x.GroupTypeName);
  6137. var view = groupInfos1.Select(x =>
  6138. new
  6139. {
  6140. groupTypeName = x.Key,
  6141. groupNum = x.Count(),
  6142. linkGroupId = x.Select(x1 => x1.Id).ToList()
  6143. }
  6144. )
  6145. .OrderByDescending(x => x.groupNum)
  6146. .ToList();
  6147. return Ok(JsonView(true, "操作成功!", view));
  6148. }
  6149. /// <summary>
  6150. /// 团组数据统计
  6151. /// 团组数量
  6152. /// </summary>
  6153. /// <param name="_dto"></param>
  6154. /// <returns></returns>
  6155. [HttpPost("StatisticsGroupNum")]
  6156. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6157. public async Task<IActionResult> StatisticsGroupNum(YOYDto _dto)
  6158. {
  6159. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  6160. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  6161. endDt = $"{_dto.Year}-12-31 23:59:59";
  6162. DateTime _beginDt = Convert.ToDateTime(beginDt),
  6163. _endDt = Convert.ToDateTime(endDt);
  6164. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  6165. .Where(x => x.IsDel == 0)
  6166. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  6167. .Select(x => new StatisticsGroupInfoEntity
  6168. {
  6169. Id = x.Id,
  6170. VisitDate = x.VisitDate,
  6171. Month = x.VisitDate.Month,
  6172. //MonthName = x.VisitDate.ToString("MMM", CultureInfo.GetCultureInfo("zh-CN")),
  6173. VisitPNumber = x.VisitPNumber
  6174. })
  6175. .MergeTable()
  6176. .OrderBy(x => new { x.Month })
  6177. .ToListAsync();
  6178. string groupNumStr = $"年度出访量:{groupInfos.Count}\r\n";
  6179. var groupNumYearData = new
  6180. {
  6181. year = _dto.Year,
  6182. yearName = _dto.Year + "年",
  6183. num = groupInfos.Count,
  6184. linkGroupIds = groupInfos.Select(x => x.Id).ToList()
  6185. };
  6186. var groupNumData = groupInfos.GroupBy(x => x.Quarter)
  6187. .Select(x => new
  6188. {
  6189. Quarter = x.Key,
  6190. QuarterName = x.FirstOrDefault()?.QuarterName ?? "-",
  6191. Num = x.Count(),
  6192. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  6193. })
  6194. .OrderBy(x => x.Quarter)
  6195. .ToList();
  6196. groupNumData.ForEach(x =>
  6197. {
  6198. groupNumStr += $"{x.QuarterName}出访量:{x.Num};";
  6199. });
  6200. var groupNumMonthData = groupInfos.GroupBy(x => x.Month)
  6201. .Select(x => new
  6202. {
  6203. Month = x.Key,
  6204. MonthName = x.FirstOrDefault()?.MonthName ?? "-",
  6205. Num = x.Count(),
  6206. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  6207. })
  6208. .OrderBy(x => x.Month)
  6209. .ToList();
  6210. return Ok(JsonView(true, "操作成功!", new
  6211. {
  6212. yearData = groupNumYearData,
  6213. quarterData = groupNumData,
  6214. monthData = groupNumMonthData,
  6215. remark = groupNumStr
  6216. }));
  6217. }
  6218. /// <summary>
  6219. /// 团组数据统计
  6220. /// 团组人数
  6221. /// </summary>
  6222. /// <param name="_dto"></param>
  6223. /// <returns></returns>
  6224. [HttpPost("StatisticsGroupPeopleNum")]
  6225. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6226. public async Task<IActionResult> StatisticsGroupPeopleNum(YOYDto _dto)
  6227. {
  6228. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  6229. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  6230. endDt = $"{_dto.Year}-12-31 23:59:59";
  6231. DateTime _beginDt = Convert.ToDateTime(beginDt),
  6232. _endDt = Convert.ToDateTime(endDt);
  6233. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  6234. .Where(x => x.IsDel == 0)
  6235. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  6236. .Select(x => new StatisticsGroupInfoEntity
  6237. {
  6238. Id = x.Id,
  6239. VisitDate = x.VisitDate,
  6240. Month = x.VisitDate.Month,
  6241. VisitPNumber = x.VisitPNumber
  6242. })
  6243. .MergeTable()
  6244. .OrderBy(x => new { x.Month })
  6245. .ToListAsync();
  6246. string groupPeopleNumStr = $"年度出访人数:{groupInfos.Sum(x => x.VisitPNumber)}\r\n";
  6247. var groupPeopleNumYearData = new
  6248. {
  6249. year = _dto.Year,
  6250. yearName = _dto.Year + "年",
  6251. num = groupInfos.Sum(x => x.VisitPNumber),
  6252. linkGroupIds = groupInfos.Select(x => x.Id).ToList()
  6253. };
  6254. var groupPeopleNumData = groupInfos.GroupBy(x => x.Quarter)
  6255. .Select(x => new
  6256. {
  6257. Quarter = x.Key,
  6258. QuarterName = x.FirstOrDefault()?.QuarterName ?? "-",
  6259. Num = x.Sum(x1 => x1.VisitPNumber),
  6260. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  6261. })
  6262. .OrderBy(x => x.Quarter)
  6263. .ToList();
  6264. groupPeopleNumData.ForEach(x =>
  6265. {
  6266. groupPeopleNumStr += $"{x.QuarterName}出访人数:{x.Num};";
  6267. });
  6268. var groupPeopleNumMonthData = groupInfos.GroupBy(x => x.Month)
  6269. .Select(x => new
  6270. {
  6271. Month = x.Key,
  6272. MonthName = x.FirstOrDefault()?.MonthName ?? "-",
  6273. Num = x.Sum(x1 => x1.VisitPNumber),
  6274. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  6275. })
  6276. .OrderBy(x => x.Month)
  6277. .ToList();
  6278. return Ok(JsonView(true, "操作成功!", new
  6279. {
  6280. yearData = groupPeopleNumYearData,
  6281. quarterData = groupPeopleNumData,
  6282. monthData = groupPeopleNumMonthData,
  6283. remark = groupPeopleNumStr
  6284. }));
  6285. }
  6286. /// <summary>
  6287. /// 团组数据统计
  6288. /// OP 成本
  6289. /// </summary>
  6290. /// <param name="_dto"></param>
  6291. /// <returns></returns>
  6292. [HttpPost("StatisticsOP")]
  6293. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6294. public async Task<IActionResult> StatisticsOP(StatisticsOPDto _dto)
  6295. {
  6296. if (_dto.Year < 1) return Ok(JsonView(false, "Year参数错误!"));
  6297. if (_dto.Type < 1 || _dto.Type > 2) return Ok(JsonView(false, "Type参数错误!"));
  6298. int thisYear = _dto.Year, lastYear = _dto.Year - 1;
  6299. string beginDt = $"{lastYear}-01-01 00:00:00",
  6300. endDt = $"{thisYear}-12-31 23:59:59";
  6301. string sql = string.Format(@"
  6302. SELECT
  6303. temp.Id,
  6304. DiId,
  6305. PaymentTime,
  6306. [Year],
  6307. [Quarter],
  6308. [Month],
  6309. Area,
  6310. FeeType,
  6311. sd1.Name AS FeeTypeName,
  6312. FeeSubType,
  6313. sd2.Name AS FeeSubTypeName,
  6314. CONVERT(DECIMAL(12, 2), Price * Qauntity * ExchangeRate) AS Price
  6315. FROM
  6316. (
  6317. SELECT
  6318. ctggr.Id,
  6319. ctggr.DiId,
  6320. ctggr.Area,
  6321. CASE
  6322. WHEN ctggr.PriceType IS NULL THEN 1069
  6323. ELSE ctggr.PriceType
  6324. END AS FeeType,
  6325. ctggrc.SId AS FeeSubType,
  6326. ctggrc.Price,
  6327. CASE
  6328. WHEN ctggrc.Count IS NULL THEN 1
  6329. ELSE ctggrc.Count
  6330. END AS Qauntity,
  6331. ccp.DayRate AS ExchangeRate,
  6332. ctggrc.CreateTime AS PaymentTime,
  6333. YEAR(ctggrc.CreateTime) AS [Year],
  6334. CONVERT(INT,DATENAME(QUARTER, ctggrc.CreateTime)) AS [Quarter],
  6335. MONTH(ctggrc.CreateTime) AS [Month]
  6336. FROM
  6337. Grp_CarTouristGuideGroundReservations ctggr
  6338. INNER JOIN Grp_CarTouristGuideGroundReservationsContent ctggrc ON ctggr.Id = ctggrc.CTGGRId
  6339. AND ctggrc.IsDel = 0
  6340. INNER JOIN Grp_CreditCardPayment ccp ON ctggr.Id = ccp.CId
  6341. AND ccp.CTable = 79
  6342. AND ccp.IsDel = 0
  6343. WHERE
  6344. ctggr.IsDel = 0
  6345. AND ctggrc.SId != 1070 --费用子项筛掉尾款
  6346. AND ctggrc.Price > 0 --筛选真实存在的数据
  6347. AND ccp.IsPay = 1
  6348. ) temp
  6349. LEFT JOIN Sys_SetData sd1 ON FeeType = sd1.Id
  6350. LEFT JOIN Sys_SetData sd2 ON FeeSubType = sd2.Id
  6351. WHERE
  6352. temp.Area NOT LIKE '%尾款%' -- 筛选掉尾款相关信息
  6353. AND temp.FeeType != 1062 --费用类型筛选掉全款和首付款数据
  6354. AND temp.PaymentTime BETWEEN CONVERT(datetime,'{0}') AND CONVERT(datetime,'{1}')
  6355. ORDER BY
  6356. temp.[Year],
  6357. temp.[Quarter],
  6358. temp.[Month]
  6359. ", beginDt, endDt);
  6360. var opInfos = await _sqlSugar.SqlQueryable<StatisticsOP>(sql).ToListAsync();
  6361. //处理地区相关信息
  6362. var countrys = await _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(x => x.IsDel == 0).ToListAsync();
  6363. for (int i = 0; i < opInfos.Count; i++)
  6364. {
  6365. string country = string.Empty, city = string.Empty;
  6366. int dataId = 0;
  6367. bool isCountryId = int.TryParse(opInfos[i].Area, out dataId);
  6368. string[] citySelecter = new string[] { "其他城市", "所有城市" };
  6369. if (isCountryId)
  6370. {
  6371. var countryInfo = countrys.Find(x => x.Id == dataId);
  6372. country = countryInfo?.Country ?? "";
  6373. if (citySelecter.Contains(countryInfo?.City)) city = country;
  6374. else city = countryInfo?.City ?? "";
  6375. }
  6376. else
  6377. {
  6378. var countryInfo1 = countrys.Find(x => opInfos[i].Area.Contains(x.Country));
  6379. if (countryInfo1 != null)
  6380. {
  6381. country = countryInfo1?.Country ?? "";
  6382. city = countryInfo1?.City ?? country;
  6383. var countryInfo2 = countrys.Find(x => opInfos[i].Area.Contains(x.City));
  6384. if (citySelecter.Contains(countryInfo2?.City)) city = country;
  6385. else city = countryInfo2?.City ?? country;
  6386. }
  6387. else
  6388. {
  6389. var countryInfo2 = countrys.Find(x => opInfos[i].Area.Contains(x.City));
  6390. if (countryInfo2 != null)
  6391. {
  6392. country = countryInfo2?.Country ?? "";
  6393. city = countryInfo2?.City ?? "";
  6394. if (citySelecter.Contains(countryInfo2?.City)) city = country;
  6395. }
  6396. }
  6397. }
  6398. opInfos[i].Country = country;
  6399. opInfos[i].City = city;
  6400. }
  6401. var opParentFeeData = new StatisticsOP()._OPParentFeeInfo;
  6402. if (_dto.Type == 1)
  6403. {
  6404. //同比增长率=(本期数-同期数)/ 同期数
  6405. var yearData = opInfos.GroupBy(x => x.ParentFeeName)
  6406. .Select(x => new StatisticsOPYOY(
  6407. feeId: x.FirstOrDefault()?.ParentFeeId ?? 0,
  6408. feeName: x.Key,
  6409. currPeriodFee: x.Where(x => x.Year == thisYear).Sum(x => x.Price),
  6410. samePeriodFee: x.Where(x => x.Year == lastYear).Sum(x => x.Price),
  6411. currPeriodGroupTotal: x.Where(x => x.Year == thisYear).Select(x => x.DiId).Distinct().Count(),
  6412. samePeriodGroupTotal: x.Where(x => x.Year == lastYear).Select(x => x.DiId).Distinct().Count(),
  6413. subFeeData: x.GroupBy(x1 => x1.FeeSubType)
  6414. .Select(x1 => new StatisticsOPSubFeeYOY(
  6415. feeId: x1.Key,
  6416. feeName: x1.FirstOrDefault()?.FeeSubTypeName ?? "",
  6417. currPeriodFee: x1.Where(x1 => x1.Year == thisYear).Sum(x1 => x1.Price),
  6418. samePeriodFee: x1.Where(x1 => x1.Year == lastYear).Sum(x1 => x1.Price),
  6419. currPeriodGroupTotal: x1.Where(x1 => x1.Year == thisYear).Select(x1 => x1.DiId).Distinct().Count(),
  6420. samePeriodGroupTotal: x1.Where(x1 => x1.Year == lastYear).Select(x1 => x1.DiId).Distinct().Count(),
  6421. cityData: x1.GroupBy(x2 => x2.City)
  6422. .Select(x2 => new StatisticsOPCityYOY(
  6423. cityName: x2.Key,
  6424. currPeriodGroupTotal: x2.Where(x2 => x2.Year == thisYear).Select(x2 => x2.DiId).Distinct().Count(),
  6425. samePeriodGroupTotal: x2.Where(x2 => x2.Year == lastYear).Select(x2 => x2.DiId).Distinct().Count(),
  6426. currPeriodFee: x2.Where(x2 => x2.Year == thisYear).Sum(x2 => x2.Price),
  6427. samePeriodFee: x2.Where(x2 => x2.Year == lastYear).Sum(x2 => x2.Price)
  6428. ))
  6429. .ToArray()
  6430. ))
  6431. .ToArray()
  6432. ))
  6433. .OrderBy(x => x.FeeId)
  6434. .ToList();
  6435. var opParentYearIds = yearData.Select(x => x.FeeId).ToList();
  6436. var opParentYearDataSelector = opParentFeeData.Where(x => !opParentYearIds.Contains(x.Id)).ToList();
  6437. if (opParentYearDataSelector.Count > 0)
  6438. {
  6439. foreach (var item in opParentYearDataSelector)
  6440. {
  6441. yearData.Add(
  6442. new StatisticsOPYOY(feeId: item.Id,
  6443. feeName: item.Name,
  6444. currPeriodFee: 0.00M,
  6445. samePeriodFee: 0.00M,
  6446. currPeriodGroupTotal: 0,
  6447. samePeriodGroupTotal: 0,
  6448. subFeeData: Array.Empty<StatisticsOPSubFeeYOY>()
  6449. ));
  6450. }
  6451. yearData = yearData.OrderBy(x => x.FeeId).ToList();
  6452. }
  6453. return Ok(JsonView(true, "操作成功!", yearData));
  6454. }
  6455. else if (_dto.Type == 2)
  6456. {
  6457. var monthData = opInfos.GroupBy(x => x.Month)
  6458. .Select(x => new StatisticsOPMonthYOY(
  6459. monthId: x.Key,
  6460. monthName: System.Enum.IsDefined(typeof(MonthEnum), (int)x.Key) ? ((MonthEnum)(int)x.Key).GetEnumDescription() : "",
  6461. feeDatas: x.GroupBy(x1 => x1.ParentFeeId)
  6462. .Select(x1 => new StatisticsOPYOY(
  6463. feeId: x1.Key,
  6464. feeName: x1.FirstOrDefault()?.ParentFeeName ?? "",
  6465. currPeriodFee: x1.Where(x1 => x1.Year == thisYear).Sum(x1 => x1.Price),
  6466. samePeriodFee: x1.Where(x1 => x1.Year == lastYear).Sum(x1 => x1.Price),
  6467. currPeriodGroupTotal: x1.Where(x1 => x1.Year == thisYear).Select(x1 => x1.DiId).Distinct().Count(),
  6468. samePeriodGroupTotal: x1.Where(x1 => x1.Year == lastYear).Select(x1 => x1.DiId).Distinct().Count(),
  6469. subFeeData: x1.GroupBy(x2 => x2.FeeSubType)
  6470. .Select(x2 => new StatisticsOPSubFeeYOY(
  6471. feeId: x2.Key,
  6472. feeName: x2.FirstOrDefault()?.FeeSubTypeName ?? "",
  6473. currPeriodFee: x2.Where(x2 => x2.Year == thisYear).Sum(x2 => x2.Price),
  6474. samePeriodFee: x2.Where(x2 => x2.Year == lastYear).Sum(x2 => x2.Price),
  6475. currPeriodGroupTotal: x2.Where(x2 => x2.Year == thisYear).Select(x2 => x2.DiId).Distinct().Count(),
  6476. samePeriodGroupTotal: x2.Where(x2 => x2.Year == lastYear).Select(x2 => x2.DiId).Distinct().Count(),
  6477. cityData: x2.GroupBy(x3 => x3.City)
  6478. .Select(x3 => new StatisticsOPCityYOY(
  6479. cityName: x3.Key,
  6480. currPeriodFee: x3.Where(x3 => x3.Year == thisYear).Sum(x3 => x3.Price),
  6481. samePeriodFee: x3.Where(x3 => x3.Year == lastYear).Sum(x3 => x3.Price),
  6482. currPeriodGroupTotal: x3.Where(x3 => x3.Year == thisYear).Select(x3 => x3.DiId).Distinct().Count(),
  6483. samePeriodGroupTotal: x3.Where(x3 => x3.Year == lastYear).Select(x3 => x3.DiId).Distinct().Count()
  6484. ))
  6485. .ToArray()
  6486. ))
  6487. .ToArray()
  6488. ))
  6489. .ToArray()
  6490. ))
  6491. //.OrderBy(x => x.MonthId)
  6492. .ToList();
  6493. //1、月份是否足够十二月
  6494. var monthIds = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
  6495. var monthDataIds = monthData.Select(x => x.MonthId).ToArray();
  6496. var newMonthIds = monthIds.Where(x => !monthDataIds.Contains(x)).ToList();
  6497. if (newMonthIds.Count > 0)
  6498. {
  6499. foreach (var item in newMonthIds)
  6500. {
  6501. monthData.Add(new StatisticsOPMonthYOY(
  6502. monthId: item,
  6503. monthName: System.Enum.IsDefined(typeof(MonthEnum), (int)item) ? ((MonthEnum)(int)item).GetEnumDescription() : "",
  6504. feeDatas: System.Array.Empty<StatisticsOPYOY>()
  6505. ));
  6506. }
  6507. monthData = monthData.OrderBy(x => x.MonthId).ToList();
  6508. }
  6509. //2、费用父类是否足够
  6510. for (int i = 0; i < monthData.Count; i++)
  6511. {
  6512. var month = monthData[i];
  6513. var opParentFeeIds = month.FeeDatas.Select(x => x.FeeId).ToList();
  6514. var opParentFeeDataSelector = opParentFeeData.Where(x => !opParentFeeIds.Contains(x.Id)).ToList();
  6515. if (opParentFeeDataSelector.Count > 0)
  6516. {
  6517. var feeDatas = month.FeeDatas.ToList();
  6518. foreach (var item in opParentFeeDataSelector)
  6519. {
  6520. feeDatas.Add(new StatisticsOPYOY(
  6521. feeId: item.Id,
  6522. feeName: item.Name,
  6523. currPeriodFee: 0.00M,
  6524. samePeriodFee: 0.00M,
  6525. currPeriodGroupTotal: 0,
  6526. samePeriodGroupTotal: 0,
  6527. subFeeData: System.Array.Empty<StatisticsOPSubFeeYOY>()
  6528. ));
  6529. }
  6530. feeDatas = feeDatas.OrderBy(x => x.FeeId).ToList();
  6531. monthData[i].FeeDatas = feeDatas.ToArray();
  6532. }
  6533. }
  6534. //3、费用子类是否足够
  6535. return Ok(JsonView(true, "操作成功!", monthData));
  6536. }
  6537. return Ok(JsonView(false, "操作失败!"));
  6538. }
  6539. /// <summary>
  6540. /// 团组数据统计
  6541. /// 团组预算/实际成本
  6542. /// </summary>
  6543. /// <param name="_dto"></param>
  6544. /// <returns></returns>
  6545. [HttpPost("StatisticsGroupCost")]
  6546. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6547. public async Task<IActionResult> StatisticsBRCost(StatisticsBRCostDto _dto)
  6548. {
  6549. if (_dto.Year < 1) return Ok(JsonView(false, "Year参数错误!"));
  6550. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  6551. endDt = $"{_dto.Year}-12-31 23:59:59";
  6552. var sql = string.Format(@"
  6553. SELECT
  6554. ROW_NUMBER() OVER(
  6555. ORDER BY
  6556. di.VisitDate DESC
  6557. ) AS 'RowNumber',
  6558. di.Id,
  6559. di.TeamName AS 'GroupName',
  6560. di.ClientUnit,
  6561. di.VisitDate,
  6562. di.VisitDays,
  6563. di.VisitPNumber,
  6564. (
  6565. SELECT
  6566. TOP 1 CASE
  6567. ISNUMERIC (gcp.Currency)
  6568. WHEN 1 THEN (
  6569. SELECT
  6570. Name
  6571. FROM
  6572. Sys_SetData sd
  6573. WHERE
  6574. CAST(gcp.Currency AS INT) = sd.Id
  6575. )
  6576. ELSE gcp.Currency
  6577. END AS 'CurrencyCode'
  6578. FROM
  6579. Grp_GroupCostParameter gcp
  6580. WHERE
  6581. gcp.IsDel = 0
  6582. AND gcp.DiId = di.Id
  6583. ) Budget_CurrencyCode,
  6584. --预算币种
  6585. (
  6586. SELECT
  6587. TOP 1 CAST(COALESCE(gcp.Rate, 0.0000) AS DECIMAL(12, 4))
  6588. FROM
  6589. Grp_GroupCostParameter gcp
  6590. WHERE
  6591. gcp.IsDel = 0
  6592. AND gcp.DiId = di.Id
  6593. ) Budget_Rate,
  6594. --预算汇率
  6595. (
  6596. SELECT
  6597. CAST(
  6598. SUM(COALESCE(gcp.VisaCB, 0) * COALESCE(gcp.VisaRS, 0)) AS DECIMAL(12, 2)
  6599. )
  6600. FROM
  6601. Grp_GroupCostParameter gcp
  6602. WHERE
  6603. gcp.IsDel = 0
  6604. AND gcp.DiId = di.id
  6605. ) Budget_VisaAmount,
  6606. -- 预算签证成本
  6607. (
  6608. SELECT
  6609. CAST(
  6610. SUM(
  6611. (
  6612. (ccp.PayMoney * ccp.DayRate)
  6613. )
  6614. ) AS DECIMAL(12, 2)
  6615. )
  6616. FROM
  6617. Grp_VisaInfo vi
  6618. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6619. AND ccp.CTable = 80
  6620. AND vi.Id = ccp.CId
  6621. WHERE
  6622. vi.IsDel = 0
  6623. AND ccp.IsAuditGM = 1
  6624. AND ccp.IsPay = 1
  6625. AND di.Id = vi.DIId
  6626. ) AS Reality_VisaAmount,
  6627. -- 实际签证成本
  6628. (
  6629. SELECT
  6630. CAST(
  6631. SUM(
  6632. COALESCE(gcp.JJCCB, 0) * COALESCE(gcp.JJCRS, 0) + COALESCE(gcp.GWCCB, 0) * COALESCE(gcp.GWCRS, 0) + COALESCE(gcp.TDCCB, 0) * COALESCE(gcp.TDCRS, 0)
  6633. ) AS DECIMAL(12, 2)
  6634. )
  6635. FROM
  6636. Grp_GroupCostParameter gcp
  6637. WHERE
  6638. gcp.IsDel = 0
  6639. AND gcp.DiId = di.id
  6640. ) Budget_AirTicketAmount,
  6641. -- 预算机票成本
  6642. (
  6643. SELECT
  6644. CAST(
  6645. SUM(
  6646. (
  6647. (ccp.PayMoney * ccp.DayRate)
  6648. )
  6649. ) AS DECIMAL(12, 2)
  6650. )
  6651. FROM
  6652. Grp_AirTicketReservations atr
  6653. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6654. AND ccp.CTable = 85
  6655. AND atr.Id = ccp.CId
  6656. WHERE
  6657. atr.IsDel = 0
  6658. AND ccp.IsAuditGM = 1
  6659. AND ccp.IsPay = 1
  6660. AND di.Id = atr.DiId
  6661. ) Reality_AirTicketAmount,
  6662. --实际机票
  6663. (
  6664. SELECT
  6665. CAST(
  6666. SUM(
  6667. 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)
  6668. ) AS DECIMAL(12, 2)
  6669. )
  6670. FROM
  6671. Grp_GroupCostParameter gcp
  6672. WHERE
  6673. gcp.IsDel = 0
  6674. AND gcp.DiId = di.id
  6675. ) Budget_HotelAmount,
  6676. -- 预算酒店成本
  6677. (
  6678. SELECT
  6679. CAST(
  6680. SUM(
  6681. (ccp.PayMoney * ccp.DayRate)
  6682. ) AS DECIMAL(12, 2)
  6683. )
  6684. FROM
  6685. Grp_HotelReservations hr
  6686. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  6687. WHERE
  6688. hr.IsDel = 0
  6689. AND ccp.IsDel = 0
  6690. AND ccp.CTable = 76
  6691. AND ccp.IsAuditGM = 1
  6692. AND ccp.PayMoney <> 0
  6693. AND ccp.IsPay = 1
  6694. AND di.Id = hr.DiId
  6695. ) AS Reality_HotelAmount,
  6696. -- 实际酒店成本
  6697. (
  6698. SELECT
  6699. CAST(
  6700. SUM(COALESCE(gcp.DJCB, 0) * COALESCE(gcp.DJRS, 0)) AS DECIMAL(12, 2)
  6701. )
  6702. FROM
  6703. Grp_GroupCostParameter gcp
  6704. WHERE
  6705. gcp.IsDel = 0
  6706. AND gcp.DiId = di.id
  6707. ) Budget_OPAmount,
  6708. -- 预算 OP
  6709. (
  6710. SELECT
  6711. CAST(
  6712. SUM(
  6713. (
  6714. ctggr.ServiceQuotedPrice * (ccp.PayPercentage / 100) * ccp.DayRate
  6715. )
  6716. ) AS DECIMAL(12, 2)
  6717. )
  6718. FROM
  6719. Grp_CarTouristGuideGroundReservations ctggr
  6720. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  6721. AND ccp.CTable = 79
  6722. AND ctggr.Id = ccp.CId
  6723. WHERE
  6724. ctggr.IsDel = 0
  6725. AND ccp.IsAuditGM = 1
  6726. AND ccp.IsPay = 1
  6727. AND di.Id = ctggr.DiId
  6728. ) AS Reality_OPAmount,
  6729. -- 实际 OP
  6730. (
  6731. SELECT
  6732. CAST(
  6733. SUM(COALESCE(gcp.GWCB, 0) * COALESCE(gcp.GWRS, 0)) AS DECIMAL(12, 2)
  6734. )
  6735. FROM
  6736. Grp_GroupCostParameter gcp
  6737. WHERE
  6738. gcp.IsDel = 0
  6739. AND gcp.DiId = di.id
  6740. ) Budget_OAAmount,
  6741. -- 预算 商邀
  6742. (
  6743. SELECT
  6744. CAST(
  6745. SUM(
  6746. (ccp.PayMoney * ccp.DayRate)
  6747. ) AS DECIMAL(12, 2)
  6748. )
  6749. FROM
  6750. Grp_InvitationOfficialActivities ioa
  6751. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6752. AND ccp.CTable = 81
  6753. AND ioa.Id = ccp.CId
  6754. WHERE
  6755. ioa.IsDel = 0
  6756. AND ccp.IsAuditGM = 1
  6757. AND ccp.IsPay = 1
  6758. AND di.Id = ioa.Diid
  6759. ) AS Reality_OAAmount,
  6760. -- 实际 商邀
  6761. (
  6762. SELECT
  6763. CAST(
  6764. SUM(
  6765. 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)
  6766. ) AS DECIMAL(12, 2)
  6767. )
  6768. FROM
  6769. Grp_GroupCostParameter gcp
  6770. WHERE
  6771. gcp.IsDel = 0
  6772. AND gcp.DiId = di.id
  6773. ) Budget_OtherAmount,
  6774. -- 预算其他成本
  6775. (
  6776. SELECT
  6777. CAST(
  6778. SUM(
  6779. (ccp.PayMoney * ccp.DayRate)
  6780. ) AS DECIMAL(12, 2)
  6781. )
  6782. FROM
  6783. Grp_Customers ic
  6784. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6785. AND ccp.CTable = 82
  6786. AND ic.Id = ccp.CId
  6787. WHERE
  6788. ic.IsDel = 0
  6789. AND ccp.IsAuditGM = 1And ccp.IsPay = 1
  6790. AND di.Id = ic.DiId
  6791. ) AS Reality_InsureAmount,
  6792. -- 实际保险成本
  6793. (
  6794. SELECT
  6795. CAST(SUM((ccp.PayMoney * ccp.DayRate)) AS DECIMAL(12, 2))
  6796. FROM
  6797. Grp_DecreasePayments dp
  6798. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6799. AND ccp.CTable = 98
  6800. AND dp.Id = ccp.CId
  6801. WHERE
  6802. dp.IsDel = 0
  6803. AND ccp.Ctable = 98
  6804. AND ccp.IsAuditGM = 1
  6805. AND ccp.IsPay = 1
  6806. AND di.Id = dp.Diid
  6807. ) AS Reality_OtherCostAmount -- 实际其他款项
  6808. FROM
  6809. Grp_DelegationInfo di
  6810. WHERE
  6811. di.IsDel = 0
  6812. AND di.IsBid = 0
  6813. --AND di.TeamDid IN (38, 39, 40, 1048)
  6814. AND di.VisitDate BETWEEN '{0}' AND '{1}'
  6815. ", beginDt, endDt);
  6816. if (!string.IsNullOrEmpty(_dto.Search))
  6817. {
  6818. sql += $"AND di.TeamName Like '%{_dto.Search}%'";
  6819. }
  6820. var view = await _sqlSugar.SqlQueryable<StatisticsBRCostView>(sql).ToListAsync();
  6821. view = view.Where(x => !x.GroupName.Contains("投标") && x.RealityAmount > 0).OrderByDescending(x => x.Id).ToList();
  6822. var total = view.Count;
  6823. var toSkip = (_dto.PageIndex - 1) * _dto.PageSize;
  6824. var data = view.Skip(toSkip).Take(_dto.PageSize).ToList();
  6825. if (data.Count > 0)
  6826. {
  6827. var diIds = data.Select(x => x.Id).ToList();
  6828. var currencyData = await _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0 && x.STid == 66).ToListAsync();
  6829. var ccpData = await _sqlSugar.Queryable<Grp_CreditCardPayment>()
  6830. .Where(x => x.IsDel == 0 &&
  6831. diIds.Contains(x.DIId) &&
  6832. x.IsPay == 1 &&
  6833. x.IsAuditGM == 1
  6834. )
  6835. .ToListAsync();
  6836. for (int i = 0; i < data.Count; i++)
  6837. {
  6838. var info = data[i];
  6839. info.RowNumber = i + 1;
  6840. #region 1:签证 80
  6841. var visaDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 80).ToList();
  6842. var visaDesc = "-";
  6843. if (visaDatas.Count > 0)
  6844. {
  6845. visaDesc = $"实际币种金额:";
  6846. foreach (var visa in visaDatas)
  6847. {
  6848. var currencyCode = currencyData.Find(x => x.Id == visa.PaymentCurrency)?.Name;
  6849. visaDesc += $"{visa.PayMoney} {currencyCode} 汇率:{visa.DayRate.ToString("#0.0000")};";
  6850. }
  6851. }
  6852. info.Reality_VisaAmountDesc = visaDesc;
  6853. #endregion
  6854. #region 2:机票 85
  6855. var airDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 85).ToList();
  6856. var airDesc = "-";
  6857. if (airDatas.Count > 0)
  6858. {
  6859. airDesc = $"实际币种金额:";
  6860. foreach (var air in airDatas)
  6861. {
  6862. var currencyCode = currencyData.Find(x => x.Id == air.PaymentCurrency)?.Name;
  6863. airDesc += $"{air.PayMoney} {currencyCode} 汇率:{air.DayRate.ToString("#0.0000")};";
  6864. }
  6865. }
  6866. info.Reality_AirTicketAmountDesc = airDesc;
  6867. #endregion
  6868. #region 3:酒店 76
  6869. var hotelDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 76 && x.PayMoney != 0).ToList();
  6870. var hotelDesc = "-";
  6871. if (hotelDatas.Count > 0)
  6872. {
  6873. hotelDesc = $"实际币种金额:";
  6874. foreach (var hotel in hotelDatas)
  6875. {
  6876. var currencyCode = currencyData.Find(x => x.Id == hotel.PaymentCurrency)?.Name;
  6877. hotelDesc += $"{hotel.PayMoney} {currencyCode} 汇率:{hotel.DayRate.ToString("#0.0000")};";
  6878. }
  6879. }
  6880. info.Reality_HotelAmountDesc = hotelDesc;
  6881. #endregion
  6882. #region 4:OP 79
  6883. var opDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 79 && x.PayMoney != 0).ToList();
  6884. var opDesc = "-";
  6885. if (opDatas.Count > 0)
  6886. {
  6887. opDesc = $"实际币种金额;";
  6888. foreach (var op in opDatas)
  6889. {
  6890. var currencyCode = currencyData.Find(x => x.Id == op.PaymentCurrency)?.Name;
  6891. opDesc += $"{op.PayMoney} {currencyCode} 汇率:{op.DayRate.ToString("#0.0000")};";
  6892. }
  6893. }
  6894. info.Reality_OPAmountDesc = opDesc;
  6895. #endregion
  6896. #region 5:商邀 81
  6897. var oaDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 81 && x.PayMoney != 0).ToList();
  6898. var oaDesc = "-";
  6899. if (oaDatas.Count > 0)
  6900. {
  6901. oaDesc = $"实际币种金额:";
  6902. foreach (var oa in oaDatas)
  6903. {
  6904. var currencyCode = currencyData.Find(x => x.Id == oa.PaymentCurrency)?.Name;
  6905. oaDesc += $"{oa.PayMoney} {currencyCode} 汇率:{oa.DayRate.ToString("#0.0000")};";
  6906. }
  6907. }
  6908. info.Reality_OAAmountDesc = oaDesc;
  6909. #endregion
  6910. #region 6:其他款项(保险 82、其他款项 98)
  6911. var cTables = new List<int>() { 82, 98 };
  6912. var otherDatas = ccpData.Where(x => x.DIId == info.Id && cTables.Contains(x.CTable) && x.PayMoney != 0).ToList();
  6913. var otherDesc = "-";
  6914. if (otherDatas.Count > 0)
  6915. {
  6916. otherDesc = $"实际币种金额:";
  6917. foreach (var other in otherDatas)
  6918. {
  6919. var currencyCode = currencyData.Find(x => x.Id == other.PaymentCurrency)?.Name;
  6920. otherDesc += $"{other.PayMoney} {currencyCode} 汇率:{other.DayRate.ToString("#0.0000")};";
  6921. }
  6922. }
  6923. info.Reality_OtherCostAmountDesc = otherDesc;
  6924. #endregion
  6925. }
  6926. }
  6927. var briefData = _mapper.Map<List<StatisticsBRCostBriefView>>(data);
  6928. return Ok(JsonView(briefData, total));
  6929. }
  6930. /// <summary>
  6931. /// 团组数据统计
  6932. /// 当前时间团组所在城市
  6933. /// </summary>
  6934. /// <param name="dto"></param>
  6935. /// <returns></returns>
  6936. [HttpPost("StatisticsNowCityOfGroup")]
  6937. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6938. public async Task<IActionResult> StatisticsNowCityOfGroup(StatisticsNowCityOfGroupDto dto)
  6939. {
  6940. if (!SharingStaticData.PortTypes.Contains(dto.PortType)) return Ok(JsonView(false, MsgTips.Port));
  6941. var nowLable = DateTime.Now.ToString("yyyy-MM-dd");
  6942. var sql = string.Format(@"SELECT * FROM Grp_DelegationInfo WHERE ISdel = 0 AND '{0}' BETWEEN VisitStartDate AND VisitEndDate", nowLable);
  6943. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql)
  6944. .Select(x => new { x.Id, x.VisitCountry, x.TeamName, x.ClientUnit, x.VisitStartDate, x.VisitEndDate }).
  6945. ToListAsync();
  6946. if (!groupInfos.Any()) return Ok(JsonView(false, "今日暂无团组出行!"));
  6947. var groupIds = groupInfos.Select(x => x.Id).ToList();
  6948. //三字码
  6949. var threeDatas = await _sqlSugar.Queryable<Res_ThreeCode>().Where(x => x.IsDel == 0).ToListAsync();
  6950. //国家
  6951. var countryDatas = await _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(x => x.IsDel == 0 && !string.IsNullOrEmpty(x.Country) && !string.IsNullOrEmpty(x.City)).ToListAsync();
  6952. //公务
  6953. var OADatas = await _sqlSugar
  6954. .Queryable<Res_OfficialActivities>().Where(x => x.IsDel == 0 && groupIds.Contains(x.DiId) && !string.IsNullOrEmpty(x.Country) && !string.IsNullOrEmpty(x.Area))
  6955. .ToListAsync();
  6956. //酒店
  6957. var hotelDatas = await _sqlSugar.Queryable<Grp_HotelReservations>()
  6958. .LeftJoin<Grp_NationalTravelFee>((hr, ntf) => hr.AreaId == ntf.Id)
  6959. .Where((hr, ntf) => hr.IsDel == 0 && groupIds.Contains(hr.DiId))
  6960. .Select((hr, ntf) => new
  6961. {
  6962. hr.DiId,
  6963. hr.AreaId,
  6964. hr.HotelName,
  6965. hr.CheckInDate,
  6966. hr.CheckOutDate,
  6967. hr.HotelAddress,
  6968. ntf.Country,
  6969. ntf.City
  6970. })
  6971. .ToListAsync();
  6972. //机票
  6973. /*
  6974. *舱位类型
  6975. *457 头等舱
  6976. *458 公务舱
  6977. *459 超经舱
  6978. *460 经济舱
  6979. *461 退票
  6980. *565 其他
  6981. *574 长段公务舱
  6982. *575 短途经济舱
  6983. *1023 行程单打印费
  6984. *1024 选座费
  6985. */
  6986. var classTypes = new int[] { 457, 458, 459, 460, 574, 575 };
  6987. var airDatas = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
  6988. .Where(atr => atr.IsDel == 0 && groupIds.Contains(atr.DIId) && classTypes.Contains(atr.CType))
  6989. .ToListAsync();
  6990. string[] characters = { "|", "、" };
  6991. var result = new List<StatisticsNowCityOfGroupResultView>();
  6992. foreach (var item in groupInfos)
  6993. {
  6994. string statusText = string.Empty,
  6995. address = string.Empty;
  6996. var countrys = item.VisitCountry;
  6997. if (string.IsNullOrEmpty(countrys)) continue;
  6998. var currCountrys = item.VisitCountry.Split(characters, StringSplitOptions.RemoveEmptyEntries);
  6999. var stutus = true;
  7000. #region 公务
  7001. var currOADatas = OADatas.Where(x => x.DiId == item.Id && currCountrys.Any(c => x.Country.Contains(c))).ToList();
  7002. if (currOADatas.Any())
  7003. {
  7004. foreach (var curr_oa in currOADatas)
  7005. {
  7006. var localTime = GetCountryOrCityCurrentDateTime(curr_oa.Country, curr_oa.Area);
  7007. if (localTime == null) continue;
  7008. var currOaDtStart = Convert.ToDateTime($"{Convert.ToDateTime(curr_oa.Date).ToString("yyyy-MM-dd")} {curr_oa.Time}");
  7009. var currOaDtEnd = currOaDtStart.AddHours(2);
  7010. var currTimeZoneStatus = localTime >= currOaDtStart && localTime <= currOaDtEnd;
  7011. if (!currTimeZoneStatus) continue;
  7012. stutus = false;
  7013. statusText = "公务活动中";
  7014. address = curr_oa.Address;
  7015. break;
  7016. }
  7017. }
  7018. #endregion
  7019. #region 酒店
  7020. var currHotelDatas = hotelDatas.Where(x => x.DiId == item.Id && !string.IsNullOrEmpty(x.Country) && currCountrys.Any(c => x.Country.Contains(c))).ToList();
  7021. if (stutus && hotelDatas.Any())
  7022. {
  7023. foreach (var curr_hotel in currHotelDatas)
  7024. {
  7025. var checkInDt = Convert.ToDateTime(curr_hotel.CheckInDate);
  7026. List<(DateTime start, DateTime end)> timeRanges = new List<(DateTime, DateTime)>();
  7027. while (checkInDt <= Convert.ToDateTime(curr_hotel.CheckOutDate))
  7028. {
  7029. int year = checkInDt.Year,
  7030. month = checkInDt.Month,
  7031. day = checkInDt.Day;
  7032. timeRanges.Add((new DateTime(year, month, day, 0, 0, 0), new DateTime(year, month, day, 9, 0, 0)));
  7033. timeRanges.Add((new DateTime(year, month, day, 18, 0, 0), new DateTime(year, month, day, 23, 59, 59)));
  7034. checkInDt = checkInDt.AddDays(1);
  7035. }
  7036. if (!timeRanges.Any()) continue;
  7037. if (string.IsNullOrEmpty(curr_hotel.Country) && string.IsNullOrEmpty(curr_hotel.City)) continue;
  7038. var countryInfo = countryDatas.Where(x => x.Id == curr_hotel.AreaId).FirstOrDefault();
  7039. if (countryInfo == null) continue;
  7040. var localTime = GetCountryOrCityCurrentDateTime(countryInfo.Country, countryInfo.City);
  7041. var currTimeZoneStatus = timeRanges.Any(range => localTime >= range.start && localTime <= range.end);
  7042. if (!currTimeZoneStatus) continue;
  7043. stutus = false;
  7044. statusText = "入住酒店中";
  7045. address = curr_hotel.HotelAddress;
  7046. break;
  7047. }
  7048. }
  7049. #endregion
  7050. #region 机票--通过三字码解析处理
  7051. var airTicketDatas = GetTableByBlackCode(item.Id);
  7052. if (stutus && airTicketDatas != null)
  7053. {
  7054. foreach (DataRow curr_airTicket in airTicketDatas.Rows)
  7055. {
  7056. string departDate = curr_airTicket["Date"].ToString(), //出发日期
  7057. departThree = curr_airTicket["Three"].ToString(), //城市三字码
  7058. departTime = curr_airTicket["StartTime"].ToString(), //出发时刻
  7059. departTerminal = curr_airTicket["StartBuilding"].ToString(), //出发航站楼
  7060. arriveTerminal = curr_airTicket["EndBuilding"].ToString(), //抵达航站楼
  7061. arrivedDate = curr_airTicket["ArrivedDate"].ToString(), //抵达日期
  7062. arrivedTime = curr_airTicket["EndTime"].ToString(), //抵达日期
  7063. flightTime = curr_airTicket["FlightTime"].ToString(); //飞行时间
  7064. if (string.IsNullOrEmpty(departThree)) continue;
  7065. string departAirThree = departThree.Substring(0, 3),
  7066. arriveAirThree = departThree.Substring(3, 3);
  7067. string departCountry = string.Empty,
  7068. departCity = string.Empty,
  7069. departAirport = string.Empty,
  7070. arriveCountry = string.Empty,
  7071. arriveCity = string.Empty,
  7072. arriveAirport = string.Empty;
  7073. var departCountryInfo = threeDatas.Find(x => x.Three.Equals(departAirThree));
  7074. var arriveCountryInfo = threeDatas.Find(x => x.Three.Equals(arriveAirThree));
  7075. if (departCountryInfo == null || arriveCountryInfo == null) continue;
  7076. departCountry = departCountryInfo.Country;
  7077. departCity = departCountryInfo.City;
  7078. departAirport = departCountryInfo.AirPort;
  7079. arriveCountry = arriveCountryInfo.Country;
  7080. arriveCity = arriveCountryInfo.City;
  7081. arriveAirport = arriveCountryInfo.AirPort;
  7082. var arriveDateTimeBool = DateTime.TryParse(arrivedDate + " " + arrivedTime.Insert(2, ":"), out DateTime arriveDateTime);
  7083. if (!arriveDateTimeBool) continue;
  7084. var filghtHoursBool = int.TryParse(flightTime.Split("H")[0].ToString(), out int filghtHours);
  7085. var filghtMinutesBool = int.TryParse(flightTime.Split("H")[1].Remove(2).ToString(), out int filghtMinutes);
  7086. if (!filghtHoursBool || !filghtHoursBool) continue;
  7087. var departDateTime = arriveDateTime.AddHours(-filghtHours).AddMinutes(-filghtMinutes);
  7088. var localTime = GetCountryOrCityCurrentDateTime(arriveCountry, arriveCity);
  7089. var currTimeZoneStatus = localTime >= departDateTime && localTime <= arriveDateTime;
  7090. if (!currTimeZoneStatus) continue;
  7091. stutus = false;
  7092. statusText = $"正飞往{arriveCity}城市中";
  7093. address = $"{arriveCountry}{arriveAirport}{arriveTerminal}";
  7094. break;
  7095. }
  7096. }
  7097. if (stutus) statusText = $"其他";
  7098. #endregion
  7099. result.Add(new StatisticsNowCityOfGroupResultView()
  7100. {
  7101. GroupName = item.TeamName,
  7102. Client = item.ClientUnit,
  7103. StatusText = statusText,
  7104. Address = address
  7105. });
  7106. }
  7107. result.AddRange(new List<StatisticsNowCityOfGroupResultView>() {
  7108. new StatisticsNowCityOfGroupResultView(){ GroupName = "模拟数据团组1",Client = "模拟数据单位1",StatusText = "正在公务中",Address = "日本〒104-0032 Tokyo, Chuo City, Hatchobori, 1 Chome−12−8 EAST2階" },
  7109. new StatisticsNowCityOfGroupResultView(){ GroupName = "模拟数据团组2",Client = "模拟数据单位2",StatusText = "入住酒店中",Address = "日本〒104-0032 Tokyo, Chuo City, Hatchobori, 1 Chome−12−8 EAST2階" },
  7110. new StatisticsNowCityOfGroupResultView(){ GroupName = "模拟数据团组3",Client = "模拟数据单位3",StatusText = "其他",Address = "日本〒104-0032 Tokyo, Chuo City, Hatchobori, 1 Chome−12−8 EAST2階" },
  7111. });
  7112. var result1 = result.GroupBy(x => x.Address).Select(g => new
  7113. {
  7114. address = g.Key,
  7115. Items = g.ToList().Select(gg => new { gg.GroupName, gg.Client, gg.StatusText }).ToList()
  7116. });
  7117. if (!result1.Any()) return Ok(JsonView(false, "今天暂无出行的的团!"));
  7118. return Ok(JsonView(result1));
  7119. }
  7120. private StatisticsNowCityOfGroupView CitySplit(string cityLable, List<Res_ThreeCode> cities)
  7121. {
  7122. var info = new StatisticsNowCityOfGroupView();
  7123. if (string.IsNullOrEmpty(cityLable)) return info;
  7124. var cityArray = cityLable.Split("-");
  7125. var departCityCode = cityArray[0];
  7126. var arriveCityCode = cityArray[1];
  7127. var departAirportInfo = cities.Find(x => x.Three.Equals(departCityCode.ToUpper()));
  7128. info.DepartAirportCode = departCityCode;
  7129. info.DepartCountryName = departAirportInfo?.Country ?? "-";
  7130. info.DepartCityName = departAirportInfo?.City ?? "-";
  7131. var arriveAirportInfo = cities.Find(x => x.Three.Equals(arriveCityCode.ToUpper()));
  7132. info.ArriveAirportCode = arriveCityCode;
  7133. info.ArriveCountryName = arriveAirportInfo?.Country ?? "-";
  7134. info.ArriveCityName = arriveAirportInfo?.City ?? "-";
  7135. return info;
  7136. }
  7137. #endregion
  7138. #region 企业利润
  7139. /// <summary>
  7140. /// 日常费用排除项
  7141. /// </summary>
  7142. private readonly List<int> _priceTypeIds = new List<int>()
  7143. {
  7144. 686, // 信用卡还款
  7145. 687, // 张总私人费用
  7146. 688, // 代报销社保生育补贴
  7147. 306, // 人事行政费用-张总家用类
  7148. 325, // 会展部备用金
  7149. 689 // 团组签证保险
  7150. };
  7151. /// <summary>
  7152. /// 企业利润 infos
  7153. /// </summary>
  7154. /// <param name="beginDt"></param>
  7155. /// <param name="endDt"></param>
  7156. /// <returns></returns>
  7157. private async Task<CorporateProfitInfosView> CorporateProfitInfos(string beginDt, string endDt)
  7158. {
  7159. var view = new CorporateProfitInfosView();
  7160. #region 已审核SQL
  7161. // string sql = string.Format(@"SELECT
  7162. // ROW_NUMBER() OVER(ORDER BY di.VisitDate Asc) AS 'RowIndex',
  7163. // di.Id,
  7164. // di.ClientName,
  7165. // di.TeamName,
  7166. // di.TeamDid,
  7167. // ss.Name AS 'GroupTypeName',
  7168. // di.VisitDate,
  7169. // di.VisitPNumber,
  7170. // (
  7171. // SELECT
  7172. // SUM(ffr.ItemSumPrice)
  7173. // FROM
  7174. // OA2023DB.dbo.Fin_ForeignReceivables ffr
  7175. // WHERE
  7176. // ffr.IsDel = 0
  7177. // AND ffr.Diid = di.Id
  7178. // ) 'ReceivableAmount',
  7179. // (
  7180. // SELECT
  7181. // SUM(fpr.Price)
  7182. // FROM
  7183. // OA2023DB.dbo.Fin_ProceedsReceived fpr
  7184. // WHERE
  7185. // fpr.IsDel = 0
  7186. // AND fpr.DIId = di.Id
  7187. // ) 'ReceivedAmount',
  7188. // (
  7189. // SELECT
  7190. // SUM(ccp.PayMoney * ccp.DayRate)
  7191. // FROM
  7192. // Fin_PaymentRefundAndOtherMoney prom
  7193. // INNER JOIN Grp_CreditCardPayment ccp ON prom.Id = ccp.CId
  7194. // AND prom.DiId = ccp.DIId
  7195. // WHERE
  7196. // prom.IsDel = 0
  7197. // AND prom.PayType = 1
  7198. // AND ccp.CTable = 285
  7199. // AND ccp.IsAuditGM = 1
  7200. // AND prom.DiId = di.Id
  7201. // ) AS 'RefundedAmount',
  7202. // (
  7203. // SELECT
  7204. // SUM(ccp.PayMoney * ccp.DayRate)
  7205. // FROM
  7206. // Grp_HotelReservations hr
  7207. // INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  7208. // WHERE
  7209. // hr.IsDel = 0
  7210. // AND ccp.IsDel = 0
  7211. // AND ccp.CTable = 76
  7212. // AND (
  7213. // ccp.IsAuditGM = 1
  7214. // OR ccp.IsAuditGM = 3
  7215. // )
  7216. // AND hr.DiId = di.Id
  7217. // ) AS 'HotelAmount',
  7218. // (
  7219. // SELECT
  7220. // SUM(
  7221. // (ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate)
  7222. // )
  7223. // FROM
  7224. // Grp_CarTouristGuideGroundReservations ctggr
  7225. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  7226. // AND ccp.CTable = 79
  7227. // AND ctggr.Id = ccp.CId
  7228. // WHERE
  7229. // ctggr.IsDel = 0
  7230. // AND (
  7231. // ccp.IsAuditGM = 1
  7232. // OR ccp.IsAuditGM = 3
  7233. // )
  7234. // AND ctggr.DiId = di.Id
  7235. // ) AS 'LocalGuideAmount',
  7236. // (
  7237. // SELECT
  7238. // SUM(ccp.PayMoney * ccp.DayRate)
  7239. // FROM
  7240. // Grp_AirTicketReservations atr
  7241. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7242. // AND ccp.CTable = 85
  7243. // AND atr.Id = ccp.CId
  7244. // WHERE
  7245. // atr.IsDel = 0
  7246. // AND ccp.IsAuditGM = 1
  7247. // AND atr.DIId = di.Id
  7248. // ) AS 'AirTicketAmount',
  7249. // (
  7250. // SELECT
  7251. // SUM(ccp.PayMoney * ccp.DayRate)
  7252. // FROM
  7253. // Grp_VisaInfo vi
  7254. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7255. // AND ccp.CTable = 80
  7256. // AND vi.Id = ccp.CId
  7257. // WHERE
  7258. // vi.IsDel = 0
  7259. // AND ccp.IsAuditGM = 1
  7260. // AND vi.DIId = di.Id
  7261. // ) AS 'VisaAmount',
  7262. // (
  7263. // SELECT
  7264. // SUM(ccp.PayMoney * ccp.DayRate)
  7265. // FROM
  7266. // Grp_InvitationOfficialActivities ioa
  7267. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7268. // AND ccp.CTable = 81
  7269. // AND ioa.Id = ccp.CId
  7270. // WHERE
  7271. // ioa.IsDel = 0
  7272. // AND ccp.IsAuditGM = 1
  7273. // AND ioa.DiId = di.Id
  7274. // ) AS 'OAAmount',
  7275. // (
  7276. // SELECT
  7277. // SUM(ccp.PayMoney * ccp.DayRate)
  7278. // FROM
  7279. // Grp_Customers ic
  7280. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7281. // AND ccp.CTable = 82
  7282. // AND ic.Id = ccp.CId
  7283. // WHERE
  7284. // ic.IsDel = 0
  7285. // AND ccp.IsAuditGM = 1
  7286. // AND ic.DiId = di.Id
  7287. // ) AS 'InsureAmount',
  7288. // (
  7289. // SELECT
  7290. // SUM(ccp.PayMoney * ccp.DayRate)
  7291. // FROM
  7292. // Grp_DecreasePayments dp
  7293. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7294. // AND ccp.CTable = 98
  7295. // AND dp.Id = ccp.CId
  7296. // WHERE
  7297. // dp.IsDel = 0
  7298. // AND ccp.IsAuditGM = 1
  7299. // AND dp.Diid = di.Id
  7300. // ) AS 'OtherAmount'
  7301. //FROM
  7302. // OA2023DB.dbo.Grp_DelegationInfo di
  7303. // LEFT JOIN Sys_SetData ss ON di.TeamDid = ss.Id
  7304. //WHERE
  7305. // di.IsDel = 0
  7306. // AND di.IsBid = 0
  7307. // AND di.VisitDate BETWEEN '{0}' AND '{1}'", beginDt, endDt);
  7308. #endregion
  7309. //含未审核SQL
  7310. string sql = string.Format(@"SELECT
  7311. ROW_NUMBER() OVER(
  7312. ORDER BY
  7313. di.VisitDate Asc
  7314. ) AS 'RowIndex',
  7315. di.Id,
  7316. di.ClientName,
  7317. di.TeamName,
  7318. di.TeamDid,
  7319. ss.Name AS 'GroupTypeName',
  7320. di.VisitDate,
  7321. di.VisitPNumber,
  7322. (
  7323. SELECT
  7324. SUM(ffr.ItemSumPrice)
  7325. FROM
  7326. OA2023DB.dbo.Fin_ForeignReceivables ffr
  7327. WHERE
  7328. ffr.IsDel = 0
  7329. AND ffr.Diid = di.Id
  7330. ) 'ReceivableAmount',
  7331. (
  7332. SELECT
  7333. SUM(fpr.Price)
  7334. FROM
  7335. OA2023DB.dbo.Fin_ProceedsReceived fpr
  7336. WHERE
  7337. fpr.IsDel = 0
  7338. AND fpr.DIId = di.Id
  7339. ) 'ReceivedAmount',
  7340. (
  7341. SELECT
  7342. SUM(ccp.PayMoney * ccp.DayRate)
  7343. FROM
  7344. Fin_PaymentRefundAndOtherMoney prom
  7345. INNER JOIN Grp_CreditCardPayment ccp ON prom.Id = ccp.CId
  7346. AND prom.DiId = ccp.DIId
  7347. WHERE
  7348. prom.IsDel = 0
  7349. AND prom.PayType = 1
  7350. AND ccp.CTable = 285 --AND ccp.IsAuditGM = 1
  7351. AND ccp.IsAuditGM != 2
  7352. AND prom.DiId = di.Id
  7353. ) AS 'RefundedAmount',
  7354. (
  7355. SELECT
  7356. SUM(ccp.PayMoney * ccp.DayRate)
  7357. FROM
  7358. Grp_HotelReservations hr
  7359. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  7360. WHERE
  7361. hr.IsDel = 0
  7362. AND ccp.IsDel = 0
  7363. AND ccp.CTable = 76 -- AND (
  7364. -- ccp.IsAuditGM = 1
  7365. -- OR ccp.IsAuditGM = 3
  7366. -- )
  7367. AND ccp.IsAuditGM != 2
  7368. AND hr.DiId = di.Id
  7369. ) AS 'HotelAmount',
  7370. (
  7371. SELECT
  7372. SUM(
  7373. (ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate)
  7374. )
  7375. FROM
  7376. Grp_CarTouristGuideGroundReservations ctggr
  7377. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  7378. AND ccp.CTable = 79
  7379. AND ctggr.Id = ccp.CId
  7380. WHERE
  7381. ctggr.IsDel = 0 -- AND (
  7382. -- ccp.IsAuditGM = 1
  7383. -- OR ccp.IsAuditGM = 3
  7384. -- )
  7385. AND ccp.IsAuditGM != 2
  7386. AND ctggr.DiId = di.Id
  7387. ) AS 'LocalGuideAmount',
  7388. (
  7389. SELECT
  7390. SUM(ccp.PayMoney * ccp.DayRate)
  7391. FROM
  7392. Grp_AirTicketReservations atr
  7393. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7394. AND ccp.CTable = 85
  7395. AND atr.Id = ccp.CId
  7396. WHERE
  7397. atr.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7398. AND ccp.IsAuditGM != 2
  7399. AND atr.DIId = di.Id
  7400. ) AS 'AirTicketAmount',
  7401. (
  7402. SELECT
  7403. SUM(ccp.PayMoney * ccp.DayRate)
  7404. FROM
  7405. Grp_VisaInfo vi
  7406. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7407. AND ccp.CTable = 80
  7408. AND vi.Id = ccp.CId
  7409. WHERE
  7410. vi.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7411. AND ccp.IsAuditGM != 2
  7412. AND vi.DIId = di.Id
  7413. ) AS 'VisaAmount',
  7414. (
  7415. SELECT
  7416. SUM(ccp.PayMoney * ccp.DayRate)
  7417. FROM
  7418. Grp_InvitationOfficialActivities ioa
  7419. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7420. AND ccp.CTable = 81
  7421. AND ioa.Id = ccp.CId
  7422. WHERE
  7423. ioa.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7424. AND ccp.IsAuditGM != 2
  7425. AND ioa.DiId = di.Id
  7426. ) AS 'OAAmount',
  7427. (
  7428. SELECT
  7429. SUM(ccp.PayMoney * ccp.DayRate)
  7430. FROM
  7431. Grp_Customers ic
  7432. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7433. AND ccp.CTable = 82
  7434. AND ic.Id = ccp.CId
  7435. WHERE
  7436. ic.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7437. AND ccp.IsAuditGM != 2
  7438. AND ic.DiId = di.Id
  7439. ) AS 'InsureAmount',
  7440. (
  7441. SELECT
  7442. SUM(ccp.PayMoney * ccp.DayRate)
  7443. FROM
  7444. Grp_DecreasePayments dp
  7445. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7446. AND ccp.CTable = 98
  7447. AND dp.Id = ccp.CId
  7448. WHERE
  7449. dp.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7450. AND ccp.IsAuditGM != 2
  7451. AND dp.Diid = di.Id
  7452. ) AS 'OtherAmount',
  7453. (
  7454. SELECT
  7455. SUM(dfp.SumPrice)
  7456. FROM
  7457. Fin_DailyFeePayment dfp
  7458. WHERE
  7459. dfp.IsDel = 0
  7460. AND dfp.GroupId = di.Id
  7461. ) AS 'DailyAmout'
  7462. FROM
  7463. OA2023DB.dbo.Grp_DelegationInfo di
  7464. LEFT JOIN Sys_SetData ss ON di.TeamDid = ss.Id
  7465. WHERE
  7466. di.IsDel = 0
  7467. -- AND di.IsBid = 0
  7468. AND di.VisitDate BETWEEN '{0}' AND '{1}'", beginDt, endDt);
  7469. var groupItems = await _sqlSugar.SqlQueryable<CorporateProfitInfo>(sql).ToArrayAsync();
  7470. if (groupItems.Any())
  7471. {
  7472. // 排除 投标、延期、取消 等团组名称包含的关键词 并且 团组成本费用为0 排除在外
  7473. var excludeKeywords = new List<string> { "测试", "延期", "投标", "取消" };
  7474. groupItems = groupItems.Where(g =>
  7475. !excludeKeywords.Any(keyword => g.TeamName.Contains(keyword)) &&
  7476. g.CostTotal != 0
  7477. ).ToArray();
  7478. var groupIds = groupItems.Select(x => x.Id).ToArray();
  7479. var feeCountInfos = await CorporateProfitFeeCount(groupIds);
  7480. if (feeCountInfos.Any())
  7481. {
  7482. foreach (var item in groupItems)
  7483. {
  7484. var tips = feeCountInfos.FirstOrDefault(x => x.Id == item.Id)?.FeeCountTipsLabel ?? "";
  7485. if (!string.IsNullOrEmpty(tips)) item.FeeCountTipsLabel = tips;
  7486. }
  7487. }
  7488. }
  7489. var dailySql = string.Format(@"SELECT
  7490. dfp.Id,
  7491. dfp.CompanyId,
  7492. sc.CompanyName,
  7493. sd.DepName AS 'Branch',
  7494. su.CnName AS 'Applicant',
  7495. dfp.PriceTypeId,
  7496. sst.Id AS 'PriceParentTypeId',
  7497. sst.Name AS 'PriceParentTypeName',
  7498. ss.Id AS 'PriceTypeId',
  7499. ss.Name AS 'PriceypeName',
  7500. dfp.Instructions,
  7501. dfp.SumPrice AS 'CNYTotal',
  7502. dfpc.PriceName,
  7503. dfpc.Quantity,
  7504. dfpc.Price,
  7505. dfpc.ItemTotal,
  7506. dfpc.Remark,
  7507. dfp.CreateTime
  7508. From
  7509. Fin_DailyFeePayment dfp
  7510. INNER JOIN Fin_DailyFeePaymentContent dfpc on dfp.Id = dfpc.DFPId
  7511. LEFT JOIN Sys_Company sc on dfp.CompanyId = sc.Id
  7512. LEFT JOIN Sys_Users su on dfp.CreateUserId = su.Id
  7513. LEFT JOIN Sys_Department sd on su.DepId = sd.Id
  7514. LEFT JOIN Sys_SetData ss on dfp.PriceTypeId = ss.Id
  7515. LEFT JOIN Sys_SetDataType sst on ss.STid = sst.Id
  7516. WHERE
  7517. dfp.IsDel = 0
  7518. AND dfpc.IsDel = 0
  7519. AND dfp.PriceTypeId != 686 -- 排除信用卡还款记录
  7520. AND dfp.Instructions Not LIKE '%投标保证金%'-- 684,排除投标保证金
  7521. AND dfp.CreateTime BETWEEN '{0}' AND '{1}'
  7522. -- AND dfp.IsPay = 1
  7523. ORDER BY
  7524. dfp.CompanyId,
  7525. su.DepId,
  7526. dfp.CreateUserId,
  7527. dfp.PriceTypeId,
  7528. dfp.CreateTime ASC", beginDt, endDt);
  7529. var dailyItems = await _sqlSugar.SqlQueryable<DailyInfo>(dailySql).ToArrayAsync();
  7530. view.GroupItems = groupItems.OrderBy(x => x.RowIndex).ToArray();
  7531. view.DailyItems = dailyItems;
  7532. return view;
  7533. }
  7534. /// <summary>
  7535. /// 企业利润
  7536. /// 团组费用条数统计
  7537. /// </summary>
  7538. /// <param name="groupIds"></param>
  7539. /// <returns></returns>
  7540. private async Task<CorporateProfitFeeCount[]> CorporateProfitFeeCount(int[] groupIds)
  7541. {
  7542. if (!groupIds.Any()) return Array.Empty<CorporateProfitFeeCount>();
  7543. //含未审核SQL
  7544. string sql = string.Format(@"SELECT
  7545. ROW_NUMBER() OVER(
  7546. ORDER BY
  7547. di.VisitDate Asc
  7548. ) AS 'RowIndex',
  7549. di.Id,
  7550. di.TeamName,
  7551. di.VisitDate,
  7552. (
  7553. SELECT
  7554. Count(1)
  7555. FROM
  7556. OA2023DB.dbo.Fin_ForeignReceivables ffr
  7557. WHERE
  7558. ffr.IsDel = 0
  7559. AND ffr.Diid = di.Id
  7560. ) 'ReceivableTotal',
  7561. (
  7562. SELECT
  7563. Count(1)
  7564. FROM
  7565. OA2023DB.dbo.Fin_ProceedsReceived fpr
  7566. WHERE
  7567. fpr.IsDel = 0
  7568. AND fpr.DIId = di.Id
  7569. ) 'ReceivedTotal',
  7570. (
  7571. SELECT
  7572. Count(1)
  7573. FROM
  7574. Fin_PaymentRefundAndOtherMoney prom
  7575. INNER JOIN Grp_CreditCardPayment ccp ON prom.Id = ccp.CId
  7576. AND prom.DiId = ccp.DIId
  7577. WHERE
  7578. prom.IsDel = 0
  7579. AND prom.PayType = 1
  7580. AND ccp.CTable = 285
  7581. --AND ccp.IsAuditGM = 1
  7582. AND ccp.IsAuditGM != 2
  7583. AND prom.DiId = di.Id
  7584. ) AS 'RefundedTotal',
  7585. (
  7586. SELECT
  7587. Count(1)
  7588. FROM
  7589. Grp_HotelReservations hr
  7590. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  7591. WHERE
  7592. hr.IsDel = 0
  7593. AND ccp.IsDel = 0
  7594. AND ccp.CTable = 76 -- AND (
  7595. -- ccp.IsAuditGM = 1
  7596. -- OR ccp.IsAuditGM = 3
  7597. -- )
  7598. AND ccp.IsAuditGM != 2
  7599. AND hr.DiId = di.Id
  7600. ) AS 'HotelTotal',
  7601. (
  7602. SELECT
  7603. Count(1)
  7604. FROM
  7605. Grp_CarTouristGuideGroundReservations ctggr
  7606. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  7607. AND ccp.CTable = 79
  7608. AND ctggr.Id = ccp.CId
  7609. WHERE
  7610. ctggr.IsDel = 0 -- AND (
  7611. -- ccp.IsAuditGM = 1
  7612. -- OR ccp.IsAuditGM = 3
  7613. -- )
  7614. AND ccp.IsAuditGM != 2
  7615. AND ctggr.DiId = di.Id
  7616. ) AS 'LocalGuideTotal',
  7617. (
  7618. SELECT
  7619. Count(1)
  7620. FROM
  7621. Grp_AirTicketReservations atr
  7622. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7623. AND ccp.CTable = 85
  7624. AND atr.Id = ccp.CId
  7625. WHERE
  7626. atr.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7627. AND ccp.IsAuditGM != 2
  7628. AND atr.DIId = di.Id
  7629. ) AS 'AirTicketToal',
  7630. (
  7631. SELECT
  7632. Count(1)
  7633. FROM
  7634. Grp_VisaInfo vi
  7635. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7636. AND ccp.CTable = 80
  7637. AND vi.Id = ccp.CId
  7638. WHERE
  7639. vi.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7640. AND ccp.IsAuditGM != 2
  7641. AND vi.DIId = di.Id
  7642. ) AS 'VisaTotal',
  7643. (
  7644. SELECT
  7645. Count(1)
  7646. FROM
  7647. Grp_InvitationOfficialActivities ioa
  7648. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7649. AND ccp.CTable = 81
  7650. AND ioa.Id = ccp.CId
  7651. WHERE
  7652. ioa.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7653. AND ccp.IsAuditGM != 2
  7654. AND ioa.DiId = di.Id
  7655. ) AS 'OATotal',
  7656. (
  7657. SELECT
  7658. Count(1)
  7659. FROM
  7660. Grp_Customers ic
  7661. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7662. AND ccp.CTable = 82
  7663. AND ic.Id = ccp.CId
  7664. WHERE
  7665. ic.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7666. AND ccp.IsAuditGM != 2
  7667. AND ic.DiId = di.Id
  7668. ) AS 'InsureTotal',
  7669. (
  7670. SELECT
  7671. Count(1)
  7672. FROM
  7673. Grp_DecreasePayments dp
  7674. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7675. AND ccp.CTable = 98
  7676. AND dp.Id = ccp.CId
  7677. WHERE
  7678. dp.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7679. AND ccp.IsAuditGM != 2
  7680. AND dp.Diid = di.Id
  7681. ) AS 'OtherTotal'
  7682. FROM
  7683. OA2023DB.dbo.Grp_DelegationInfo di
  7684. LEFT JOIN Sys_SetData ss ON di.TeamDid = ss.Id
  7685. WHERE
  7686. di.IsDel = 0
  7687. AND di.IsBid = 0
  7688. AND di.Id IN({0})", string.Join(",", groupIds));
  7689. return await _sqlSugar.SqlQueryable<CorporateProfitFeeCount>(sql).ToArrayAsync();
  7690. }
  7691. /// <summary>
  7692. /// 团组利润item详情
  7693. /// </summary>
  7694. /// <param name="type">
  7695. /// 1:详情
  7696. /// 2:excel 生成
  7697. /// </param>
  7698. /// <param name="begin"></param>
  7699. /// <param name="end"></param>
  7700. /// <returns></returns>
  7701. private async Task<CorporateProfitItemView> CorporateProfitItems(int type, string begin, string end)
  7702. {
  7703. var data = await CorporateProfitInfos(begin, end);
  7704. var groupItems = data.GroupItems;
  7705. var dailyItems = data.DailyItems;
  7706. var companyDailyItems = dailyItems
  7707. .Where(x => !_priceTypeIds.Contains(x.PriceTypeId))
  7708. .GroupBy(x => x.CompanyName)
  7709. .Select(g => new { CompanyName = g.Key, CNYTotal = g.Sum(x => x.CNYTotal) })
  7710. .OrderBy(x => x.CNYTotal)
  7711. .ToArray();
  7712. //业务类型
  7713. var groupTypeIds = new List<int>() {
  7714. 38, // 政府团
  7715. 39, // 企业团
  7716. 40, // 散客团
  7717. 1048 // 高校团
  7718. };
  7719. var inforTypeIds = new List<int>() {
  7720. 302, // 成都-会务活动
  7721. 691, // 四川-会务活动
  7722. 1539, // 纽茵-会务活动
  7723. 1548 // 重庆-会务活动
  7724. };
  7725. //团组 收款、成本、利润 合计
  7726. var groupCollectionTotal = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CollectionTotal);
  7727. var groupReceivableTotal = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableProfitTotal);
  7728. var groupCostTotal = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal);
  7729. var groupProfitTotal = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ProfitTotal);
  7730. //非团组 收款、成本、利润 合计
  7731. var notGroupCollectionTotal = groupItems.Where(x => !groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CollectionTotal);
  7732. var notGroupReceivableTotal = groupItems.Where(x => !groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableProfitTotal);
  7733. var notGroupCostTotal = groupItems.Where(x => !groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal);
  7734. var notGroupProfitTotal = groupItems.Where(x => !groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ProfitTotal);
  7735. //会务数量
  7736. int inforCount = groupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Count();
  7737. //服务人数
  7738. int serviceCount = groupItems.Sum(x => x.VisitPNumber);
  7739. //总利润
  7740. decimal totalProfit = groupProfitTotal + notGroupProfitTotal;
  7741. var dailyLabel = $"*不含日付费用类型(信用卡还款、张总私人费用、代报销社保生育补贴、人事行政费用 - 张总家用类、会展部备用金、团组签证保险)\r\n";
  7742. var dailyExcelLabel = dailyLabel;
  7743. if (companyDailyItems.Any())
  7744. {
  7745. foreach (var dailyFee in companyDailyItems)
  7746. {
  7747. dailyLabel += $"<p>[{dailyFee.CompanyName}]日常产生费用:{dailyFee.CNYTotal:#0.00} CNY </p>";
  7748. dailyExcelLabel += $"[{dailyFee.CompanyName}]日常产生费用:{dailyFee.CNYTotal:#0.00} CNY \r\n";
  7749. }
  7750. }
  7751. string label = string.Format(@$"<div style='color:black'><p>团组收款合计:{groupCollectionTotal:#0.00} CNY&nbsp;团组产生费用合计:{groupCostTotal:#0.00} CNY&nbsp;团组利润合计:{groupProfitTotal:#0.00} CNY</p><p>非团组收款合计:{notGroupCollectionTotal:#0.00} CNY&nbsp;非团组产生费用合计:{notGroupCostTotal:#0.00} CNY&nbsp;非团组利润合计:{notGroupProfitTotal.ToString("#0.00")} CNY</p>{dailyLabel}<p>其中会务:{inforCount}个</p><p>服务人数:{serviceCount}人</p>总利润:{totalProfit:#0.00} CNY</div>");
  7752. var datas = _mapper.Map<CorporateProfitItem[]>(groupItems);
  7753. if (type == 2) //excel 下载
  7754. {
  7755. var designer = new WorkbookDesigner();
  7756. var tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/团组利润模板.xls";
  7757. designer.Workbook = new Workbook(tempPath);
  7758. designer.SetDataSource("ReceivablesTemp", datas);
  7759. designer.SetDataSource("ReceivableProfitTotal", groupReceivableTotal.ToString("#0.00"));
  7760. designer.SetDataSource("NotReceivableProfitTotal", notGroupReceivableTotal.ToString("#0.00"));
  7761. designer.SetDataSource("SumAccounts", groupCollectionTotal.ToString("#0.00"));
  7762. designer.SetDataSource("SumReceived", groupCostTotal.ToString("#0.00"));
  7763. designer.SetDataSource("SumBalance", groupProfitTotal.ToString("#0.00"));
  7764. designer.SetDataSource("notSumAccounts", notGroupCollectionTotal.ToString("#0.00"));
  7765. designer.SetDataSource("notSumReceived", notGroupCostTotal.ToString("#0.00"));
  7766. designer.SetDataSource("SumOfNotTeamBalance", notGroupProfitTotal.ToString("#0.00"));
  7767. designer.SetDataSource("DailyLabel", dailyExcelLabel);
  7768. designer.SetDataSource("MeetingNumber", inforCount + "个");
  7769. designer.SetDataSource("ServiceNumber", serviceCount + "人");
  7770. designer.SetDataSource("SumAllBalance", totalProfit.ToString("#0.00"));
  7771. //根据数据源处理生成报表内容
  7772. designer.Process();
  7773. string fileName = $"团组利润({Convert.ToDateTime(begin).ToString("yyyy年MM月dd日")}~{Convert.ToDateTime(end).ToString("yyyy年MM月dd日")}){Guid.NewGuid().ToString()}.xls";
  7774. designer.Workbook.Save($"{AppSettingsHelper.Get("ExcelBasePath")}CorporateProfit/{fileName}");
  7775. string url = $"{AppSettingsHelper.Get("ExcelBaseUrl")}Office/Excel/CorporateProfit/{fileName}";
  7776. label = url;
  7777. }
  7778. return new CorporateProfitItemView()
  7779. {
  7780. Items = datas,
  7781. Label = label
  7782. };
  7783. }
  7784. /// <summary>
  7785. /// 企业利润
  7786. /// Item
  7787. /// </summary>
  7788. /// <param name="dto"></param>
  7789. /// <returns></returns>
  7790. [HttpPost("CorporateProfitItem")]
  7791. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  7792. public async Task<IActionResult> CorporateProfitItem(CorporateProfitItemDto dto)
  7793. {
  7794. int portType = dto.PortType,
  7795. userId = dto.UserId,
  7796. pageId = dto.PageId;
  7797. #region 参数验证
  7798. //var validationRules = new CorporateProfitItemDtoFoalidator();
  7799. //var validResult = await validationRules.ValidateAsync(dto);
  7800. //if (!validResult.IsValid)
  7801. //{
  7802. // var errors = new StringBuilder();
  7803. // foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  7804. // return Ok(JsonView(false, errors.ToString()));
  7805. //}
  7806. //#region 页面操作权限验证
  7807. //var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(userId, pageId);
  7808. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限!"));
  7809. //#endregion
  7810. #endregion
  7811. string beginDt = $"{dto.BeginDt} 00:00:00",
  7812. endDt = $"{dto.EndDt} 23:59:59";
  7813. return Ok(JsonView(true, "操作成功!", await CorporateProfitItems(1, beginDt, endDt)));
  7814. }
  7815. /// <summary>
  7816. /// 企业利润 Excel导出
  7817. /// </summary>
  7818. /// <param name="dto"></param>
  7819. /// <returns></returns>
  7820. [HttpPost("CorporateProfitExcelDownload")]
  7821. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  7822. public async Task<IActionResult> CorporateProfitExcelDownload(CorporateProfitExcelDownloadDto dto)
  7823. {
  7824. int portType = dto.PortType,
  7825. userId = dto.UserId,
  7826. pageId = dto.PageId,
  7827. excelType = dto.ExcelType;
  7828. #region 参数验证
  7829. var validationRules = new CorporateProfitExcelDownloadDtoFoalidator();
  7830. var validResult = await validationRules.ValidateAsync(dto);
  7831. if (!validResult.IsValid)
  7832. {
  7833. var errors = new StringBuilder();
  7834. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  7835. return Ok(JsonView(false, errors.ToString()));
  7836. }
  7837. #region 页面操作权限验证
  7838. //var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(userId,pageId);
  7839. //if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权限!"));
  7840. #endregion
  7841. #endregion
  7842. // 基础转换:解析传入的起止时间
  7843. DateTime beginDate = DateTime.Parse(dto.BeginDt).Date; // 强制取 00:00:00
  7844. DateTime endDate = DateTime.Parse(dto.EndDt).Date.AddDays(1).AddSeconds(-1); // 强制取 23:59:59
  7845. // 本月:按照时间范围的【最大月份】起止时间
  7846. // 逻辑:以 endDate 为基准,计算它所在月份的第一天和最后一天
  7847. DateTime monthBase = endDate;
  7848. DateTime monthBegin = new DateTime(monthBase.Year, monthBase.Month, 1);
  7849. DateTime monthEnd = monthBegin.AddMonths(1).AddSeconds(-1); // 自动处理 28/30/31 天及跨年
  7850. var montData = await CorporateProfitInfos(monthBegin.ToString("yyyy-MM-dd HH:mm:ss"), monthEnd.ToString("yyyy-MM-dd HH:mm:ss"));
  7851. var monthGroupItems = montData.GroupItems;
  7852. var monthDailyItems = montData.DailyItems;
  7853. var yearData = await CorporateProfitInfos(beginDate.ToString("yyyy-MM-dd HH:mm:ss"), endDate.ToString("yyyy-MM-dd HH:mm:ss"));
  7854. var yearGroupItems = yearData.GroupItems;
  7855. var yearDailyItems = yearData.DailyItems;
  7856. //筛选不统计的费用类型
  7857. //if (yearDailyItems.Any()) yearDailyItems = yearDailyItems.Where(x => !priceTypeIds.Contains(x.PriceTypeId)).ToArray();
  7858. #region 公共参数
  7859. //团组收款、成本、利润 合计
  7860. decimal monthGroupCollectionTotal = monthGroupItems.Sum(x => x.CollectionTotal),
  7861. monthGroupCostTotal = monthGroupItems.Sum(x => x.CostTotal),
  7862. yearGroupCollectionTotal = yearGroupItems.Sum(x => x.CollectionTotal),
  7863. yearGroupCostTotal = yearGroupItems.Sum(x => x.CostTotal);
  7864. // 日付申请 48 人员费用、 49 办公费用、50 销售费用、51 其他费用、55 大运会、90 各部门基础固定费用明细
  7865. decimal monthStaffCosts = monthDailyItems.Where(x => x.PriceParentTypeId == 48).Sum(x => x.CNYTotal),
  7866. monthOfficeExpenses = monthDailyItems.Where(x => x.PriceParentTypeId == 49).Sum(x => x.CNYTotal),
  7867. monthCostSales = monthDailyItems.Where(x => x.PriceParentTypeId == 50).Sum(x => x.CNYTotal),
  7868. monthOtherFees = monthDailyItems.Where(x => x.PriceParentTypeId == 51).Sum(x => x.CNYTotal),
  7869. monthDyhFees = monthDailyItems.Where(x => x.PriceParentTypeId == 55).Sum(x => x.CNYTotal),
  7870. monthDepartFixedExpenses = monthDailyItems.Where(x => x.PriceParentTypeId == 90).Sum(x => x.CNYTotal),
  7871. yearStaffCosts = yearDailyItems.Where(x => x.PriceParentTypeId == 48).Sum(x => x.CNYTotal),
  7872. yearOfficeExpenses = yearDailyItems.Where(x => x.PriceParentTypeId == 49).Sum(x => x.CNYTotal),
  7873. yearCostSales = yearDailyItems.Where(x => x.PriceParentTypeId == 50).Sum(x => x.CNYTotal),
  7874. yearOtherFees = yearDailyItems.Where(x => x.PriceParentTypeId == 51).Sum(x => x.CNYTotal),
  7875. yearDyhFees = yearDailyItems.Where(x => x.PriceParentTypeId == 55).Sum(x => x.CNYTotal),
  7876. yearDepartFixedExpenses = yearDailyItems.Where(x => x.PriceParentTypeId == 90).Sum(x => x.CNYTotal);
  7877. #endregion
  7878. //月度报表、季度报表、年度报表
  7879. if (excelType == 1 || excelType == 2 || excelType == 3)
  7880. {
  7881. var designer = new WorkbookDesigner();
  7882. string fileName = $"({beginDate.ToString("yyyy年MM月dd日")}~{endDate.ToString("yyyy年MM月dd日")}){Guid.NewGuid().ToString()}.xls",
  7883. fileNamePrefix = string.Empty,
  7884. tempPath = string.Empty,
  7885. workSheetName = string.Empty;
  7886. if (excelType == 1)
  7887. {
  7888. tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/月度报表模板.xls";
  7889. workSheetName = "月度报表";
  7890. fileNamePrefix = "月度报表";
  7891. }
  7892. else if (excelType == 2)
  7893. {
  7894. tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/季度报表模板.xls";
  7895. workSheetName = "季度报表";
  7896. fileNamePrefix = "季度报表";
  7897. }
  7898. else if (excelType == 3)
  7899. {
  7900. tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/年度报表模板.xls";
  7901. workSheetName = "年度报表";
  7902. fileNamePrefix = "年度报表";
  7903. }
  7904. else return Ok(JsonView(false));
  7905. designer.Workbook = new Workbook(tempPath);
  7906. designer.Workbook.Worksheets[0].Name = workSheetName;
  7907. #region 填充值
  7908. string time = $"所属期间: {beginDate.ToString("yyyy 年 MM 月 dd 日")} 至 {endDate.ToString("yyyy 年 MM 月 dd 日")}";
  7909. designer.SetDataSource("Time", time);
  7910. designer.SetDataSource("MonthReceivedPrice", monthGroupCollectionTotal.ToString("#0.00"));//本月已收
  7911. designer.SetDataSource("YearReceivedPrice", yearGroupCollectionTotal.ToString("#0.00")); //本年已收
  7912. designer.SetDataSource("MonthSumReceives", monthGroupCollectionTotal.ToString("#0.00"));//本月团组收款
  7913. designer.SetDataSource("MonthTeamCost", monthGroupCostTotal.ToString("#0.00")); //本月团组成本
  7914. designer.SetDataSource("YearSumReceives", yearGroupCollectionTotal.ToString("#0.00"));//本年团组收款
  7915. designer.SetDataSource("YearTeamCost", yearGroupCostTotal.ToString("#0.00")); //本年团组成本
  7916. designer.SetDataSource("MonthStaffCosts", monthStaffCosts.ToString("#0.00"));//本月人员费用
  7917. designer.SetDataSource("YearStaffCosts", yearStaffCosts.ToString("#0.00")); //本年人员费用
  7918. designer.SetDataSource("MonthOfficeExpenses", monthOfficeExpenses.ToString("#0.00"));//本月办公费用
  7919. designer.SetDataSource("YearOfficeExpenses", yearOfficeExpenses.ToString("#0.00")); //本年办公费用
  7920. designer.SetDataSource("MonthCostSales", monthCostSales.ToString("#0.00"));//本月销售费用
  7921. designer.SetDataSource("YearCostSales", yearCostSales.ToString("#0.00")); //本年销售费用
  7922. designer.SetDataSource("MonthOtherFees", monthOtherFees.ToString("#0.00"));//本月其他费用
  7923. designer.SetDataSource("YearOtherFees", yearOtherFees.ToString("#0.00")); //本年其他费用
  7924. designer.SetDataSource("MonthDYHFees", monthDyhFees.ToString("#0.00"));//本月大运会费用
  7925. designer.SetDataSource("YearDYHFees", yearDyhFees.ToString("#0.00")); //本年大运会费用
  7926. designer.SetDataSource("MonthDepartFixedFees", monthDepartFixedExpenses.ToString("#0.00"));//本月各部门基础固定费用明细费用
  7927. designer.SetDataSource("YearDepartFixedFees", yearDepartFixedExpenses.ToString("#0.00")); //本年各部门基础固定费用明细费用
  7928. // 填表时间
  7929. string fillingTime = $"填报时间:{DateTime.Now:yyyy.MM.dd}";
  7930. designer.SetDataSource("FillingTime", fillingTime);
  7931. #endregion
  7932. //根据数据源处理生成报表内容
  7933. designer.Process();
  7934. fileName = fileNamePrefix + fileName;
  7935. designer.Workbook.Save($"{AppSettingsHelper.Get("ExcelBasePath")}CorporateProfit/{fileName}");
  7936. string url = $"{AppSettingsHelper.Get("ExcelBaseUrl")}Office/Excel/CorporateProfit/{fileName}";
  7937. return Ok(JsonView(true, "操作成功!", url));
  7938. }
  7939. //利润报表
  7940. else if (excelType == 4)
  7941. {
  7942. var designer = new WorkbookDesigner();
  7943. var tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/利润报表New.xlsx";
  7944. designer.Workbook = new Workbook(tempPath);
  7945. #region 填充值
  7946. string time = $"所属期间: {beginDate.ToString("yyyy 年 MM 月 dd 日")} 至 {endDate.ToString("yyyy 年 MM 月 dd 日")}";
  7947. designer.SetDataSource("Time", time);
  7948. //业务类型
  7949. var groupTypeIds = new List<int>() {
  7950. 38, // 政府团
  7951. 39, // 企业团
  7952. 40, // 散客团
  7953. 1048 // 高校团
  7954. };
  7955. var inforTypeIds = new List<int>() {
  7956. 302, // 成都-会务活动
  7957. 691, // 四川-会务活动
  7958. 1539, // 纽茵-会务活动
  7959. 1548 // 重庆-会务活动
  7960. };
  7961. var competitionTypeIds = new List<int>() {
  7962. 762, // 四川-赛事项目收入
  7963. 1047, // 成都-赛事项目收入
  7964. };
  7965. var otherTypeIds = new List<int>();
  7966. otherTypeIds.AddRange(groupTypeIds);
  7967. otherTypeIds.AddRange(inforTypeIds);
  7968. otherTypeIds.AddRange(competitionTypeIds);
  7969. decimal monthAllIncomes = monthGroupItems.Sum(x => x.ReceivableAmount), //月-收入
  7970. monthTzIncomes = monthGroupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7971. monthHwIncomes = monthGroupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7972. monthSsIncomes = monthGroupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7973. monthQtIncomes = monthGroupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7974. monthAllCost = monthGroupItems.Sum(x => x.CostTotal), //月-成本
  7975. monthTzCost = monthGroupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7976. monthHwCost = monthGroupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7977. monthSsCost = monthGroupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7978. monthQtCost = monthGroupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7979. monthAllGross = monthAllIncomes - monthAllCost, //月-毛利金额
  7980. monthTzGross = monthTzIncomes - monthTzCost,
  7981. monthHwGross = monthHwIncomes - monthHwCost,
  7982. monthSsGross = monthSsIncomes - monthSsCost,
  7983. monthQtGross = monthQtIncomes - monthQtCost,
  7984. yearAllIncomes = yearGroupItems.Sum(x => x.ReceivableAmount), //年-收入
  7985. yearTzIncomes = yearGroupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7986. yearHwIncomes = yearGroupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7987. yearSsIncomes = yearGroupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7988. yearQtIncomes = yearGroupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7989. yearAllCost = yearGroupItems.Sum(x => x.CostTotal), //年-成本
  7990. yearTzCost = yearGroupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7991. yearHwCost = yearGroupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7992. yearSsCost = yearGroupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7993. yearQtCost = yearGroupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7994. yearAllGross = yearAllIncomes - yearAllCost, //年-毛利金额
  7995. yearTzGross = yearTzIncomes - yearTzCost,
  7996. yearHwGross = yearHwIncomes - yearHwCost,
  7997. yearSsGross = yearSsIncomes - yearSsCost,
  7998. yearQtGross = yearQtIncomes - yearQtCost;
  7999. //年-团数量
  8000. int yearAllCount = yearGroupItems.Length,
  8001. yearTzCount = yearGroupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Count(),
  8002. yearHwCount = yearGroupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Count(),
  8003. yearSsCount = yearGroupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Count(),
  8004. yearQtCount = yearGroupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Count();
  8005. //年-利率
  8006. string yearAllRate = "0.00 %",
  8007. yearTzRate = "0.00 %",
  8008. yearHwRate = "0.00 %",
  8009. yearSsRate = "0.00 %",
  8010. yearQtRate = "0.00 %";
  8011. if (yearAllIncomes != 0) yearAllRate = (yearAllGross / yearAllIncomes * 100).ToString("#0.00") + "%";
  8012. if (yearTzIncomes != 0) yearTzRate = (yearTzGross / yearTzIncomes * 100).ToString("#0.00") + "%";
  8013. if (yearHwIncomes != 0) yearHwRate = (yearHwGross / yearHwIncomes * 100).ToString("#0.00") + "%";
  8014. if (yearSsIncomes != 0) yearSsRate = (yearSsGross / yearSsIncomes * 100).ToString("#0.00") + "%";
  8015. if (yearQtIncomes != 0) yearQtRate = (yearQtGross / yearQtIncomes * 100).ToString("#0.00") + "%";
  8016. #region 月
  8017. //收入
  8018. designer.SetDataSource("MonthAllIncomes", monthAllIncomes.ToString("#0.00"));
  8019. designer.SetDataSource("MonthtzIncomes", monthTzIncomes.ToString("#0.00"));
  8020. designer.SetDataSource("MonthhwIncomes", monthHwIncomes.ToString("#0.00"));
  8021. designer.SetDataSource("MonthssIncomes", monthSsIncomes.ToString("#0.00"));
  8022. designer.SetDataSource("MonthqtIncomes", monthQtIncomes.ToString("#0.00"));
  8023. //成本
  8024. designer.SetDataSource("MonthAllCost", monthAllCost.ToString("#0.00"));
  8025. designer.SetDataSource("MonthtzCost", monthTzCost.ToString("#0.00"));
  8026. designer.SetDataSource("MonthhwCost", monthHwCost.ToString("#0.00"));
  8027. designer.SetDataSource("MonthssCost", monthSsCost.ToString("#0.00"));
  8028. designer.SetDataSource("MonthqtCost", monthQtCost.ToString("#0.00"));
  8029. //毛利金额
  8030. designer.SetDataSource("MonthAllGross", monthAllGross.ToString("#0.00"));
  8031. designer.SetDataSource("MonthtzGross", monthTzGross.ToString("#0.00"));
  8032. designer.SetDataSource("MonthhwGross", monthHwGross.ToString("#0.00"));
  8033. designer.SetDataSource("MonthssGross", monthSsGross.ToString("#0.00"));
  8034. designer.SetDataSource("MonthqtGross", monthQtGross.ToString("#0.00"));
  8035. #endregion
  8036. #region 年
  8037. //收入
  8038. designer.SetDataSource("YearAllIncomes", yearAllIncomes.ToString("#0.00"));
  8039. designer.SetDataSource("YeartzIncomes", yearTzIncomes.ToString("#0.00"));
  8040. designer.SetDataSource("YearhwIncomes", yearHwIncomes.ToString("#0.00"));
  8041. designer.SetDataSource("YearssIncomes", yearSsIncomes.ToString("#0.00"));
  8042. designer.SetDataSource("YearqtIncomes", yearQtIncomes.ToString("#0.00"));
  8043. //成本
  8044. designer.SetDataSource("YearAllCost", yearAllCost.ToString("#0.00"));
  8045. designer.SetDataSource("YeartzCost", yearTzCost.ToString("#0.00"));
  8046. designer.SetDataSource("YearhwCost", yearHwCost.ToString("#0.00"));
  8047. designer.SetDataSource("YearssCost", yearSsCost.ToString("#0.00"));
  8048. designer.SetDataSource("YearqtCost", yearQtCost.ToString("#0.00"));
  8049. //毛利金额
  8050. designer.SetDataSource("YearAllGross", yearAllGross.ToString("#0.00"));
  8051. designer.SetDataSource("YeartzGross", yearTzGross.ToString("#0.00"));
  8052. designer.SetDataSource("YearhwGross", yearHwGross.ToString("#0.00"));
  8053. designer.SetDataSource("YearssGross", yearSsGross.ToString("#0.00"));
  8054. designer.SetDataSource("YearqtGross", yearQtGross.ToString("#0.00"));
  8055. //毛利率
  8056. designer.SetDataSource("YearAllRate", yearAllRate);
  8057. designer.SetDataSource("YeartzRate", yearTzRate);
  8058. designer.SetDataSource("YearhwRate", yearHwRate);
  8059. designer.SetDataSource("YearssRate", yearSsRate);
  8060. designer.SetDataSource("YearqtRate", yearQtRate);
  8061. //数量
  8062. designer.SetDataSource("AllCount", yearAllCount.ToString());
  8063. designer.SetDataSource("tzCount", yearTzCount.ToString());
  8064. designer.SetDataSource("hwCount", yearHwCount.ToString());
  8065. designer.SetDataSource("ssCount", yearSsCount.ToString());
  8066. designer.SetDataSource("qtCount", yearQtCount.ToString());
  8067. #endregion
  8068. #region 日付相关
  8069. var dailyViewItems = new List<CorporateProfitDailyView>();
  8070. var dailyTypes = await _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0).ToListAsync();
  8071. var conmmentTexts = new List<CorporateProfitDailyCommentView>();
  8072. #region 员工费用 48
  8073. decimal monthStaffCostTotal = monthDailyItems.Where(x => x.PriceParentTypeId == 48).Sum(x => x.ItemTotal),
  8074. yearStaffCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 48).Sum(x => x.ItemTotal);
  8075. dailyViewItems.Add(new CorporateProfitDailyView() { No = "一", PriceName = "人员费用", ThisMonthAmount = monthStaffCostTotal, ThisYearAmount = yearStaffCostTotal });
  8076. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8077. {
  8078. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceParentTypeId == 48).ToArray()),
  8079. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 48).ToArray())
  8080. });
  8081. var dailyStaffTypes = dailyTypes.Where(x => x.STid == 48).OrderBy(x => x.Id).ToList();
  8082. foreach (var item in dailyStaffTypes)
  8083. {
  8084. string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
  8085. decimal monthAmount = monthDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  8086. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  8087. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  8088. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8089. {
  8090. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  8091. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  8092. });
  8093. }
  8094. #endregion
  8095. #region 办公费用
  8096. decimal monthWorkCostTotal = monthDailyItems.Where(x => x.PriceParentTypeId == 49).Sum(x => x.ItemTotal), //总费用
  8097. yearWorkCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 49).Sum(x => x.ItemTotal);
  8098. dailyViewItems.Add(new CorporateProfitDailyView() { No = "二", PriceName = "办公费用", ThisMonthAmount = monthWorkCostTotal, ThisYearAmount = yearWorkCostTotal });
  8099. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8100. {
  8101. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceParentTypeId == 49).ToArray()),
  8102. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 49).ToArray())
  8103. });
  8104. var dailyWorkTypes = dailyTypes.Where(x => x.STid == 49).OrderBy(x => x.Id).ToList();
  8105. foreach (var item in dailyWorkTypes)
  8106. {
  8107. string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
  8108. decimal monthAmount = monthDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  8109. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  8110. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  8111. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8112. {
  8113. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  8114. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  8115. });
  8116. }
  8117. #endregion
  8118. #region 销售费用
  8119. decimal monthSalesCostTotal = monthDailyItems.Where(x => x.PriceParentTypeId == 50).Sum(x => x.ItemTotal), //总费用
  8120. yearSalesCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 50).Sum(x => x.ItemTotal);
  8121. dailyViewItems.Add(new CorporateProfitDailyView() { No = "三", PriceName = "销售费用", ThisMonthAmount = monthSalesCostTotal, ThisYearAmount = yearSalesCostTotal });
  8122. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8123. {
  8124. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceParentTypeId == 50).ToArray()),
  8125. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 50).ToArray())
  8126. });
  8127. var dailySalesTypes = dailyTypes.Where(x => x.STid == 50).OrderBy(x => x.Id).ToList();
  8128. foreach (var item in dailySalesTypes)
  8129. {
  8130. string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
  8131. decimal monthAmount = monthDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  8132. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  8133. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  8134. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8135. {
  8136. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  8137. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  8138. });
  8139. }
  8140. #endregion
  8141. #region 51 其他费用
  8142. decimal monthOtherCostTotal = monthDailyItems.Where(x => x.PriceParentTypeId == 51).Sum(x => x.ItemTotal), //总费用
  8143. yearOtherCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 51).Sum(x => x.ItemTotal);
  8144. dailyViewItems.Add(new CorporateProfitDailyView() { No = "四", PriceName = "其他费用", ThisMonthAmount = monthOtherCostTotal, ThisYearAmount = yearOtherCostTotal });
  8145. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8146. {
  8147. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceParentTypeId == 51).ToArray()),
  8148. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 51).ToArray())
  8149. });
  8150. var dailyOtherTypes = dailyTypes.Where(x => x.STid == 51).OrderBy(x => x.Id).ToList();
  8151. foreach (var item in dailyOtherTypes)
  8152. {
  8153. string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
  8154. decimal monthAmount = monthDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  8155. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  8156. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  8157. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8158. {
  8159. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  8160. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  8161. });
  8162. }
  8163. #endregion
  8164. #region 55 大运会
  8165. decimal monthDyhCostTotal = monthDailyItems.Where(x => x.PriceParentTypeId == 55).Sum(x => x.ItemTotal), //总费用
  8166. yearDyhCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 55).Sum(x => x.ItemTotal);
  8167. dailyViewItems.Add(new CorporateProfitDailyView() { No = "五", PriceName = "大运会", ThisMonthAmount = monthDyhCostTotal, ThisYearAmount = yearDyhCostTotal });
  8168. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8169. {
  8170. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceParentTypeId == 55).ToArray()),
  8171. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 55).ToArray())
  8172. });
  8173. var dailyDyhTypes = dailyTypes.Where(x => x.STid == 55).OrderBy(x => x.Id).ToList();
  8174. foreach (var item in dailyDyhTypes)
  8175. {
  8176. string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
  8177. decimal monthAmount = monthDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  8178. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  8179. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  8180. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8181. {
  8182. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  8183. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  8184. });
  8185. }
  8186. #endregion
  8187. #region 90 各部门基础固定费用明细
  8188. decimal monthBasicCostTotal = monthDailyItems.Where(x => x.PriceParentTypeId == 90).Sum(x => x.ItemTotal), //总费用
  8189. yearBasicCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 90).Sum(x => x.ItemTotal);
  8190. dailyViewItems.Add(new CorporateProfitDailyView() { No = "六", PriceName = "各部门基础固定费用明细", ThisMonthAmount = monthBasicCostTotal, ThisYearAmount = yearBasicCostTotal });
  8191. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8192. {
  8193. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceParentTypeId == 90).ToArray()),
  8194. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 90).ToArray())
  8195. });
  8196. var dailyBasicTypes = dailyTypes.Where(x => x.STid == 90).OrderBy(x => x.Id).ToList();
  8197. foreach (var item in dailyBasicTypes)
  8198. {
  8199. string priceName = item.Name;
  8200. decimal monthAmount = monthDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  8201. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  8202. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  8203. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8204. {
  8205. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  8206. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  8207. });
  8208. }
  8209. #endregion
  8210. // 办公费用
  8211. // 月
  8212. decimal officePirceMonth = monthStaffCostTotal + monthWorkCostTotal + monthSalesCostTotal + monthOtherCostTotal + monthDyhCostTotal + monthBasicCostTotal;
  8213. designer.SetDataSource("officePirceMonth", officePirceMonth.ToString("#0.00"));
  8214. // 年
  8215. decimal officePirceYear = yearStaffCostTotal + yearWorkCostTotal + yearSalesCostTotal + yearOtherCostTotal + yearDyhCostTotal + yearBasicCostTotal;
  8216. designer.SetDataSource("officePirceYear", officePirceYear.ToString("#0.00"));
  8217. // 排除不统计的费用类型后的小计
  8218. // 月
  8219. decimal officePirceMonth1 = monthDailyItems.Where(x => !_priceTypeIds.Contains(x.PriceTypeId)).Sum(x => x.ItemTotal);
  8220. designer.SetDataSource("officePirceMonth1", officePirceMonth1.ToString("#0.00"));
  8221. // 年
  8222. decimal officePirceYear1 = yearDailyItems.Where(x => !_priceTypeIds.Contains(x.PriceTypeId)).Sum(x => x.ItemTotal);
  8223. designer.SetDataSource("officePirceYear1", officePirceYear1.ToString("#0.00"));
  8224. //designer.SetDataSource("DailyView", dailyViewItems);
  8225. var dt = CommonFun.ToDataTableArray(dailyViewItems);
  8226. dt.TableName = "DailyView";
  8227. designer.SetDataSource(dt);
  8228. #endregion
  8229. #endregion
  8230. //根据数据源处理生成报表内容
  8231. designer.Process();
  8232. var dailySheet = designer.Workbook.Worksheets[1];
  8233. //渲染批注
  8234. for (int i = 0; i < dailyViewItems.Count; i++)
  8235. {
  8236. string monthComment = $"C{i + 3}",
  8237. yearComment = $"D{i + 3}";
  8238. int monthCommentIndex = dailySheet.Comments.Add(monthComment),
  8239. yearCommentIndex = dailySheet.Comments.Add(yearComment);
  8240. if (dailyViewItems[i].ThisMonthAmount != 0.00M)
  8241. {
  8242. string commentText1 = conmmentTexts[i].MonthComment;
  8243. Aspose.Cells.Comment comment = dailySheet.Comments[monthCommentIndex];
  8244. comment.Note = commentText1;
  8245. comment.Width = 400;
  8246. comment.Height = 400;
  8247. comment.Font.Color = Color.Red;
  8248. }
  8249. if (dailyViewItems[i].ThisYearAmount != 0.00M)
  8250. {
  8251. string commentText2 = conmmentTexts[i].YearComment;
  8252. Aspose.Cells.Comment comment = dailySheet.Comments[yearCommentIndex];
  8253. comment.Note = commentText2;
  8254. comment.Width = 400;
  8255. comment.Height = 400;
  8256. comment.Font.Color = Color.Red;
  8257. }
  8258. }
  8259. string fileName = $"利润报表({beginDate.ToString("yyyy年MM月dd日")}~{endDate.ToString("yyyy年MM月dd日")}){Guid.NewGuid().ToString()}.xls";
  8260. designer.Workbook.Save($"{AppSettingsHelper.Get("ExcelBasePath")}CorporateProfit/{fileName}");
  8261. string url = $"{AppSettingsHelper.Get("ExcelBaseUrl")}Office/Excel/CorporateProfit/{fileName}";
  8262. return Ok(JsonView(true, "操作成功!", url));
  8263. }
  8264. else if (excelType == 5)
  8265. {
  8266. var view = await CorporateProfitItems(2, beginDate.ToString("yyyy-MM-dd HH:mm:ss"), endDate.ToString("yyyy-MM-dd HH:mm:ss"));
  8267. return Ok(JsonView(true, "操作成功!", view.Label));
  8268. }
  8269. return Ok(JsonView(false));
  8270. }
  8271. private static string DailyListToString(DailyInfo[] infos)
  8272. {
  8273. StringBuilder sb = new StringBuilder();
  8274. int index = 1;
  8275. foreach (var info in infos)
  8276. {
  8277. sb.Append(index + "、");
  8278. sb.Append($"[{info.ItemTotal.ToString("#0.00")}]:{info.PriceName};");
  8279. sb.Append(Environment.NewLine);
  8280. index++;
  8281. }
  8282. return sb.ToString();
  8283. }
  8284. #endregion
  8285. }
  8286. }