StatisticsController.cs 445 KB

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