12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657 |
- using Aspose.Cells;
- using Aspose.Words.Tables;
- using crypto;
- using EyeSoft.Collections.Generic;
- using FluentValidation;
- using Google.Protobuf.WellKnownTypes;
- using Microsoft.AspNetCore.Mvc.ViewEngines;
- using Microsoft.EntityFrameworkCore.Metadata.Internal;
- using Microsoft.Extensions.Hosting;
- using MySqlX.XDevAPI.Relational;
- using NetUV.Core.Handles;
- using NodaTime;
- using NPOI.HPSF;
- using NPOI.POIFS.Properties;
- using NPOI.SS.Formula.Functions;
- using NPOI.SS.Formula.PTG;
- using NPOI.XSSF.Streaming.Values;
- using OASystem.API.OAMethodLib;
- using OASystem.API.OAMethodLib.JuHeAPI;
- using OASystem.Domain.AesEncryption;
- using OASystem.Domain.Dtos.Statistics;
- using OASystem.Domain.Entities.Customer;
- using OASystem.Domain.Entities.Financial;
- using OASystem.Domain.Entities.Groups;
- using OASystem.Domain.ViewModels.Financial;
- using OASystem.Domain.ViewModels.JuHeExchangeRate;
- using OASystem.Domain.ViewModels.QiYeWeChat;
- using OASystem.Domain.ViewModels.Statistics;
- using OASystem.Infrastructure.Repositories.Groups;
- using StackExchange.Redis;
- using System;
- using System.Data;
- using System.Runtime.Intrinsics.Arm;
- using TencentCloud.Ocr.V20181119.Models;
- using static OASystem.API.OAMethodLib.GeneralMethod;
- using TypeInfo = OASystem.Domain.ViewModels.Statistics.TypeInfo;
- namespace OASystem.API.Controllers
- {
- /// <summary>
- /// 统计模块
- /// </summary>
- [Route("api/[controller]")]
- [ApiController]
- public class StatisticsController : ControllerBase
- {
- private readonly int _decimalPlaces;
- private readonly IConfiguration _config;
- private readonly IMapper _mapper;
- private readonly SqlSugarClient _sqlSugar;
- private readonly DelegationInfoRepository _groupRep;
- private readonly SetDataRepository _setDataRep;
- private readonly TeamRateRepository _teamRateRep;
- private readonly VisitingClientsRepository _visitingClientsRep;
- private readonly IJuHeApiService _juHeApiService;
- /// <summary>
- /// Init
- /// </summary>
- /// <param name="mapper"></param>
- /// <param name="config"></param>
- /// <param name="sqlSugar"></param>
- /// <param name="groupRep"></param>
- /// <param name="setDataRep"></param>
- /// <param name="teamRate"></param>
- /// <param name="visitingClientsRep"></param>
- /// <param name="juHeApiService"></param>
- public StatisticsController(
- IMapper mapper,
- IConfiguration config,
- SqlSugarClient sqlSugar,
- DelegationInfoRepository groupRep,
- SetDataRepository setDataRep,
- TeamRateRepository teamRate,
- VisitingClientsRepository visitingClientsRep,
- IJuHeApiService juHeApiService
- )
- {
- _mapper = mapper;
- _config = config;
- _groupRep = groupRep;
- _setDataRep = setDataRep;
- _sqlSugar = sqlSugar;
- _teamRateRep = teamRate;
- _visitingClientsRep = visitingClientsRep;
- _juHeApiService = juHeApiService;
- }
- #region 团组报表
- /// <summary>
- /// 团组报表
- /// Items
- /// </summary>
- /// <param name="_dto">团组列表请求dto</param>
- /// <returns></returns>
- [HttpPost("PostGroupStatementItems")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> PostGroupStatementItems(GroupStatementItemsDto _dto)
- {
- #region 参数验证
- if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
- if (_dto.PageId < 1) return Ok(JsonView(false, "页面Id为空"));
- PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
- #region 页面操作权限验证
- pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
- if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
- #endregion
- #endregion
- if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
- {
- string sqlWhere = string.Empty;
- if (_dto.IsSure == 0) //未完成
- {
- sqlWhere += string.Format(@" And IsSure = 0");
- }
- else if (_dto.IsSure == 1) //已完成
- {
- sqlWhere += string.Format(@" And IsSure = 1");
- }
- if (!string.IsNullOrEmpty(_dto.SearchCriteria))
- {
- string tj = _dto.SearchCriteria;
- sqlWhere += string.Format(@"And (ssd.Name Like '%{0}%' Or TeamName Like '%{1}%' Or ClientName Like '%{2}%' Or ClientName Like '%{3}%' Or su.CnName Like '%{4}%')",
- tj, tj, tj, tj, tj);
- }
- string sql = string.Format(@"Select row_number() over(order by gdi.VisitDate Desc) as Row_Number,
- gdi.Id,TourCode,ssd1.Id TeamLevId,ssd1.Name TeamLev,TeamName,
- ClientName,ClientUnit,VisitDate,ssd.Id TeamTypeId, ssd.Name TeamType,
- VisitDays,VisitPNumber,su.CnName JietuanOperator,IsSure,gdi.CreateTime,
- pr.LastCollectionTime
- From Grp_DelegationInfo gdi
- Left Join Sys_SetData ssd On gdi.TeamDid = ssd.Id
- Left Join Sys_SetData ssd1 On gdi.TeamLevSId = ssd1.Id
- Left Join Sys_Users su On gdi.JietuanOperator = su.Id
- Left Join (
- SELECT Diid, MAX(CreateTime) LastCollectionTime
- FROM Fin_ProceedsReceived
- Where IsDel = 0
- GROUP BY Diid
- ) pr On gdi.Id = pr.Diid
- Where gdi.IsDel = 0 {0} ", sqlWhere);
- RefAsync<int> total = 0;//REF和OUT不支持异步,想要真的异步这是最优解
- var _DelegationList = await _sqlSugar.SqlQueryable<GroupStatementItemView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);//ToPageAsync
- var _view = new
- {
- PageFuncAuth = pageFunAuthView,
- Data = _DelegationList
- };
- return Ok(JsonView(true, "查询成功!", _view, total));
- }
- else
- {
- return Ok(JsonView(false, "查询失败"));
- }
- }
- /// <summary>
- /// 团组报表
- /// Details
- /// </summary>
- /// <param name="_dto">团组列表请求dto</param>
- /// <returns></returns>
- [HttpPost("PostGroupStatementDetails")]
- //[JsonConverter(typeof(DecimalConverter), 2)]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> PostGroupStatementDetails(GroupStatementDetailsDto _dto)
- {
- /*
- * 团组报表计算方式
- * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
- * 应收金额 = 应收表.Sum()
- * 已收金额 = 已收表.Sum()
- * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
- * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
- *
- */
- #region 参数验证
- if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
- if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
- if (_dto.DiId < 1) return Ok(JsonView(false, "团组Id为空"));
- PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
- #region 页面操作权限验证
- pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
- if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
- #endregion
- #endregion
- if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
- {
- GroupStatementDetailsView _view = new GroupStatementDetailsView();
- #region 费用类型 币种,转账,客户信息
- List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
- var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>()
- .Where(it => it.IsDel == 0)
- .Select(x => new Crm_DeleClient { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, Sex = x.Sex })
- .ToListAsync();
- foreach (var item in _clientDatas) EncryptionProcessor.DecryptProperties(item);
- var groupInfo = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => x.Id == _dto.DiId).FirstAsync();
- var visitDate = groupInfo.VisitDate;
- #endregion
- #region 团组收入
- GroupIncomeView _giView = new GroupIncomeView();
- /*
- * 应收报表
- * 增加方式=实际报价时 费用必须审核才能进入团组报表
- */
- decimal frTotalAmount = 0.00M;//应收总金额
- 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,
- sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
- From Fin_ForeignReceivables fr
- Left Join Sys_SetData sd On fr.Currency = sd.Id
- Left Join Sys_Users u On fr.Auditor = u.Id
- Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
- List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
- //List<Gsd_ForeignReceivablesView> _frViews = new List<Gsd_ForeignReceivablesView>();
- //if (_frViews1.Count > 0)
- //{
- // _frViews.AddRange(_frViews1.Where(x => x.AddingWay != 2).ToList());
- // _frViews.AddRange(_frViews1.Where(x => x.AddingWay == 2 && x.Status == 1).ToList());
- //}
- _frViews.ForEach(x =>
- {
- string namePrefix = string.Empty;
- if (x.AddingWay == 0) namePrefix = $"账单模块-";
- else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
- else if (x.AddingWay == 2) namePrefix = $"实际报价-";
- x.PriceName = $"{namePrefix}{x.PriceName}";
- });
- frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
- _giView.Receivables = _frViews;
- _giView.ReceivableStr = string.Format(@"应收款合计:{0} CNY(人民币)", frTotalAmount.ConvertToDecimal1().ToString("#0.00"));
- /*
- * 已收报表
- */
- decimal prTotalAmount = 0.00M;//已收总金额
- string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
- sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
- pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
- From Fin_ProceedsReceived pr
- Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
- Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
- Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
- List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
- prTotalAmount = _prViews.Sum(it => it.Price);
- _giView.ProceedsReceivedViews = _prViews;
- _giView.ProceedsReceivedStr = string.Format(@$"应收合计:{frTotalAmount:#0.00} CNY 已收款合计:{prTotalAmount.ConvertToDecimal1():#0.00} CNY");
- /*
- * 超支费用
- */
- decimal exTotalAmount = 0.00M;
- // 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,
- // (gec.PriceSum * gec.Coefficient * ccp.DayRate) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
- // sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
- //From OA2023DB.dbo.Fin_GroupExtraCost gec
- //Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
- // Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- // Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- // Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
- // Left Join Sys_Users u On ccp.CreateUserId = u.Id
- //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 " : " ");
- // List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(ecSql).ToListAsync();
- // #region 超支费用 - 模拟数据
- // //if (_ExtraCostsViews.Count < 1)
- // //{
- // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
- // // {
- // // GECId = 0,
- // // GECDiId = 2334,
- // // PriceName = "模拟数据-超支费用名称",
- // // PayMoney = 1000.00M,
- // // PaymentCurrency = "CNY",
- // // DayRate = 1.0000M,
- // // CNYPrice = 1000.00M,
- // // Payee = "模拟数据-超支费用收款方",
- // // OrbitalPrivateTransfer = 1,
- // // PayWay = "刷卡",
- // // CardType = "招行卡",
- // // IsPay = 1,
- // // Applicant = "刘华举"
- // // });
- // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
- // // {
- // // GECId = 0,
- // // GECDiId = 2334,
- // // PriceName = "模拟数据-超支费用名称",
- // // PayMoney = 1000.00M,
- // // PaymentCurrency = "CNY",
- // // DayRate = 1.0000M,
- // // CNYPrice = 1000.00M,
- // // Payee = "模拟数据-超支费用收款方",
- // // OrbitalPrivateTransfer = 1,
- // // PayWay = "刷卡",
- // // CardType = "招行卡",
- // // IsPay = 1,
- // // Applicant = "刘华举"
- // // });
- // //}
- // #endregion
- // exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
- // _giView.ExtraCostsViews = _ExtraCostsViews;
- // _giView.ExtraCostsStr = string.Format(@"人民币总费用:{0} CNY", exTotalAmount.ConvertToDecimal1().ToString("#0.00"));
- /*
- * 收款退还
- */
- decimal promTotalAmount = 0.00M;// 收款退还总金额
- List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
- //删除了 And prom.PriceType = 1
- string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
- prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
- prom.PayType As PrPayType,prom.PriceType As PrPriceType,
- ccp.RMBPrice * ccp.DayRate As RMBPrice,ccp.*,prom.CreateTime As PrCreateTime
- From Fin_PaymentRefundAndOtherMoney prom
- Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where prom.IsDel = 0
- And prom.PayType = 1
- And ccp.CTable = 285
- {1}
- And prom.DiId = {0} Order By PrCreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
- var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
- foreach (var ropItem in _promDatas)
- {
- string thisCueencyCode = "Unknown";
- string thisCueencyName = "Unknown";
- var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
- if (currency != null)
- {
- thisCueencyCode = currency.Name;
- thisCueencyName = currency.Remark;
- }
- string orbitalPrivateTransferStr = "Unknown";
- var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
- if (orbitalPrivateTransfer != null)
- {
- orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
- }
- string payStr = "Unknown";
- var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
- if (pay != null)
- {
- payStr = pay.Name;
- }
- Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
- {
- Id = ropItem.Id,
- DiId = ropItem.DIId,
- PriceName = ropItem.PrPriceName,
- PayCurrencyCode = thisCueencyCode,
- PayCurrencyName = thisCueencyName,
- Price = ropItem.PrPrice,
- CNYPrice = ropItem.PayMoney * ropItem.DayRate,
- ThisRate = ropItem.DayRate,
- Payee = ropItem.Payee,
- PayTime = ropItem.AuditGMDate,
- OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
- PayType = payStr,
- IsPay = ropItem.IsPay,
- Applicant = ropItem.Appliction
- };
- _promView.Add(gsd_PaymentRefund);
- }
- #region 收款退还 - 模拟数据
- //if (_promView.Count < 1)
- //{
- // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
- // {
- // Id = 0,
- // DiId = 2334,
- // PriceName = "模拟数据-费用名称",
- // PayCurrencyCode = "CNY",
- // PayCurrencyName = "人民币",
- // Price = 1000.00M,
- // CNYPrice = 1000.00M,
- // ThisRate = 1.00M,
- // Payee = "模拟数据-收款方",
- // PayTime = "2023-01-01 15:20:01",
- // OrbitalPrivateTransfer = 1,
- // PayType = "刷卡",
- // IsPay = 1,
- // Applicant = "刘华举"
- // });
- // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
- // {
- // Id = 0,
- // DiId = 2334,
- // PriceName = "模拟数据-费用名称",
- // PayCurrencyCode = "CNY",
- // PayCurrencyName = "人民币",
- // Price = 1000.00M,
- // CNYPrice = 1000.00M,
- // ThisRate = 1.00M,
- // Payee = "模拟数据-收款方",
- // PayTime = "2023-01-01 15:20:01",
- // OrbitalPrivateTransfer = 1,
- // PayType = "刷卡",
- // IsPay = 1,
- // Applicant = "刘华举"
- // });
- //}
- #endregion
- promTotalAmount = _promView.Sum(it => it.CNYPrice);
- _giView.PaymentRefundAndOtherMoneyViews = _promView;
- _giView.PaymentRefundAndOtherMoneyStr = string.Format(@"人民币总费用:{0} CNY", promTotalAmount.ConvertToDecimal1().ToString("#0.00"));
- decimal BalancePayment = frTotalAmount - prTotalAmount + promTotalAmount;
- _view.GroupIncome = _giView;
- _view.GroupIncomeStr = string.Format(@"<span style='color:red;'>剩余尾款:{0} CNY(包含了收款退还费用数据)</span>", BalancePayment.ConvertToDecimal1().ToString("#0.00"));
- #endregion
- #region 团组支出
- GroupExpenditureView _geView = new GroupExpenditureView();
- #region 酒店预定费用
- List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
- //ccp.RMBPrice As CNYPrice
- //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
- string hotelFeeSql = string.Format(@"
- SELECT
- hr.Id AS HrId,
- hr.DiId AS HrDiId,
- hr.City,
- hr.HotelName,
- hr.CheckInDate,
- hr.CheckOutDate,
- hr.CardPrice AS RoomPrice,
- sd1.Name AS PaymentCurrency,
- hr.SingleRoomPrice,
- hr.SingleRoomCount,
- hr.DoubleRoomPrice,
- hr.DoubleRoomCount,
- hr.SuiteRoomPrice,
- hr.SuiteRoomCount,
- hr.OtherRoomPrice,
- hr.OtherRoomCount,
- hr.BreakfastPrice,
- sd4.Name AS BreakfastCurrency,
- hr.Isoppay,
- hr.GovernmentRent,
- sd5.Name AS GovernmentRentCurrency,
- hr.CityTax,
- sd6.Name AS CityTaxCurrency,
- ccp.PayMoney,
- (
- ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
- ) AS CNYPrice,
- ccp.PayPercentage,
- ccp.DayRate,
- ccp.Payee,
- ccp.OrbitalPrivateTransfer,
- sd2.Name AS PayWay,
- sd3.Name AS CardType,
- ccp.IsPay,
- u.CnName AS Applicant
- FROM
- Grp_HotelReservations hr
- INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
- LEFT JOIN Sys_SetData sd1 ON ccp.PaymentCurrency = sd1.Id
- LEFT JOIN Sys_SetData sd2 ON ccp.PayDId = sd2.Id
- LEFT JOIN Sys_SetData sd3 ON ccp.CTDId = sd3.Id
- LEFT JOIN Sys_Users u ON ccp.CreateUserId = u.Id
- LEFT JOIN Sys_SetData sd4 ON hr.BreakfastCurrency = sd4.Id
- LEFT JOIN Sys_SetData sd5 ON hr.GovernmentRentCurrency = sd5.Id
- LEFT JOIN Sys_SetData sd6 ON hr.CityTaxCurrency = sd6.Id
- WHERE
- hr.IsDel = 0
- AND ccp.IsDel = 0
- AND ccp.CTable = 76 {1}
- AND ccp.PayMoney <> 0
- AND hr.DiId = {0}
- ORDER BY
- CheckInDate Asc", _dto.DiId, _dto.isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
- groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
- List<int> hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
- var groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
- decimal HotelCNYTotalPrice = 0.00M;
- var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
- foreach (var item in groupHotelFeeViews)
- {
- if (groupHotelContentFeeViews.Count > 0)
- {
- string paymentStr = string.Empty;
- var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
- item.RoomPrice = roomData?.Price ?? 0.00M;
- if (item.RoomPrice != 0)
- {
- if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
- item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
- string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
- string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
- item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
- 收款方:{roomData?.Payee}<br/>
- 费用标识:{feeMark1} <br/>
- 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
- 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
- 是否由地接支付:{isFeeMark1} <br/>";
- }
- var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
- item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
- if (item.BreakfastPrice != 0)
- {
- if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
- item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
- string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
- string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
- item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
- 收款方:{breakfastData?.Payee}<br/>
- 费用标识:{feeMark2} <br/>
- 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
- 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
- 是否由地接支付:{isFeeMark2} <br/>";
- }
- var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
- item.GovernmentRent = landTaxData?.Price ?? 0.00M;
- if (item.GovernmentRent != 0)
- {
- if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
- item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
- string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
- string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
- item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
- 收款方:{landTaxData?.Payee}<br/>
- 费用标识:{feeMark3} <br/>
- 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
- 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
- 是否由地接支付:{isFeeMark3} <br/>";
- }
- var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
- item.CityTax = cityTaxData?.Price ?? 0.00M;
- if (item.CityTax != 0)
- {
- if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
- item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
- string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
- string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
- item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
- 收款方:{cityTaxData?.Payee}<br/>
- 费用标识:{feeMark4} <br/>
- 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
- 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
- 是否由地接支付:{isFeeMark4} <br/>";
- }
- if (!string.IsNullOrEmpty(paymentStr))
- {
- item.IsPay = 2;
- item.PayTips = paymentStr;
- }
- //item.CNYPrice = roomData?.Price ?? 0.00M * roomData?.Rate ?? 0.00M +
- // breakfastData?.Price ?? 0.00M * breakfastData?.Rate ?? 0.00M +
- // landTaxData?.Price ?? 0.00M * landTaxData?.Rate ?? 0.00M +
- // cityTaxData?.Price ?? 0.00M * cityTaxData?.Rate ?? 0.00M;
- }
- else
- {
- decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
- (item.DoubleRoomCount * item.DoubleRoomPrice) +
- (item.SuiteRoomCount * item.SuiteRoomPrice) +
- (item.OtherRoomCount * item.OtherRoomPrice);
- //item.RoomPrice = item.CardPrice;
- item.RoomPriceCurrency = item.PaymentCurrency;
- }
- HotelCNYTotalPrice += item.CNYPrice;
- item.PayMoney = item.PayMoney.ConvertToDecimal1();
- item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
- }
- _geView.GroupHotelFeeViews = groupHotelFeeViews;
- _geView.GroupHotelFeeStr = string.Format(@"人民币总费用:{0} CNY", HotelCNYTotalPrice.ToString("#0.00"));
- #endregion
- #region 地接费用
- List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
- string CTGGRFeeSql = string.Empty;
- if (visitDate > Convert.ToDateTime("2024-04-17"))
- {
- CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
- sd2.name As PaymentCurrency,ccp.PayPercentage,
- (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
- (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
- ccp.DayRate,(ctggrc.Price * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
- ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
- From Grp_CarTouristGuideGroundReservations ctggr
- Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
- cggrc.DatePrice,cggrc.PriceContent
- From Grp_CarTouristGuideGroundReservationsContent cggrc
- Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
- Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
- Where cggrc.ISdel = 0 And cggrc.Price != 0.00
- ) ctggrc On ctggr.Id = ctggrc.CTGGRId
- Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
- Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
- }
- else
- {
- CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,
- ccp.PayMoney,sd2.name As PaymentCurrency,ccp.PayPercentage,
- (ccp.PayMoney * (ccp.PayPercentage / 100)) As AmountPaid,
- (ccp.PayMoney -ccp.PayMoney * (ccp.PayPercentage / 100)) As BalancePayment,
- ccp.DayRate,(ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,
- ccp.Payee,ccp.AuditGMDate,
- ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
- From Grp_CarTouristGuideGroundReservations ctggr
- Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
- Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
- }
- groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
- string CTGGRFeeStr = "";
- decimal CTGGRCNYTotalPrice = 0.00M;
- //按1 地区,2 币种,3 汇率 分组计算
- var groupCTGGRFeeDatas = groupCTGGRFeeViews.GroupBy(it => it.Area);
- foreach (var ctggfr in groupCTGGRFeeDatas)
- {
- var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
- if (ctggfr_curr.Count() > 0)
- {
- foreach (var curr in ctggfr_curr)
- {
- var ctggfr_rate = curr.GroupBy(it => it.DayRate);
- if (ctggfr_rate.Count() > 0)
- {
- foreach (var rate in ctggfr_rate)
- {
- 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")})\r\n");
- CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
- }
- }
- else
- {
- 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")})\r\n");
- CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
- }
- }
- }
- else
- {
- 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")})\r\n");
- CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
- }
- }
- foreach (var item in groupCTGGRFeeViews)
- {
- if (!string.IsNullOrEmpty(item.AuditGMDate))
- {
- item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
- }
- if (item.DatePrice != null)
- {
- item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
- }
- //CTGGRFeeStr += string.Format(@"{0} 总费用:{1} {2}(人民币:{3} CNY 当时支付汇率:{4})\r\n",
- // item.Area, item.AmountPaid.ConvertToDecimal1().ToString("#0.00"), item.PaymentCurrency, item.CNYPrice.ToString("#0.0000"), item.DayRate.ToString("#0.0000"));
- //CTGGRCNYTotalPrice += item.CNYPrice;
- }
- _geView.GroupCTGGRFeeViews = groupCTGGRFeeViews;
- _geView.GroupCTGGRFeeStr = string.Format(@"{0}人民币总费用:{1} CNY", CTGGRFeeStr, CTGGRCNYTotalPrice.ToString("#0.00"));
- #endregion
- #region 机票预订费用
- //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
- //ccp.RMBPrice As CNYPrice
- List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
- string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
- atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
- sd1.Name As PayMoneyCurrency,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
- ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime,
- atr.CType
- From Grp_AirTicketReservations atr
- Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
- Left Join Sys_SetData sd4 On atr.CType = sd4.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where atr.IsDel = 0 {1} And atr.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
- groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
- string str = "";
- List<dynamic> airClientPris = new List<dynamic>();
- decimal AirCNYTotalPrice = 0.00M;
- decimal JJCCNYTotalPrice = 0.00M, JJCPeopleNum = 0.00M, JJCAveragePrice = 0.00M;
- decimal GWCCNYTotalPrice = 0.00M, GWCPeopleNum = 0.00M, GWCAveragePrice = 0.00M;
- //if (groupAirFeeViews.Count > 0)
- //{
- // JJCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.CNYPrice);
- // JJCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.ClientNum);
- // JJCAveragePrice = (JJCCNYTotalPrice / JJCPeopleNum).ConvertToDecimal1();
- // GWCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.CNYPrice);
- // GWCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.ClientNum);
- // GWCAveragePrice = (GWCCNYTotalPrice / GWCPeopleNum).ConvertToDecimal1();
- //}
- int Index = 0;
- foreach (var item in groupAirFeeViews)
- {
- if (item.AirId > 2924)
- {
- string itemClientName = "";
- if (!string.IsNullOrEmpty(item.ClientName))
- {
- System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
- System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
- if (m_EnName.Success || m_ZHName.Success)
- {
- itemClientName = item.ClientName;
- decimal unitCost = 0.00M;
- AirCNYTotalPrice += item.CNYPrice;
- continue;
- }
- string[] clientIds = new string[] { };
- if (item.ClientName.Contains(','))
- {
- clientIds = item.ClientName.Split(',');
- }
- else
- {
- clientIds = new string[] { item.ClientName };
- }
- if (clientIds.Length > 0)
- {
- int[] output = System.Array.ConvertAll<string, int>(clientIds, delegate (string s) { return int.Parse(s); });
- if (output.Contains(-1))
- {
- itemClientName += $@"行程单";
- output = output.Where(val => val != -1).ToArray();
- }
- var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
- decimal unitCost = 0.00M;
- unitCost = (item.PayMoney / item.ClientNum).ConvertToDecimal1();
- int clienIndex = 1;
- foreach (var client in clients)
- {
- airClientPris.Add(new
- {
- CnName = client.LastName + client.FirstName,
- EnName = client.Pinyin,
- Price = unitCost,
- AirType = item.AirTypeName
- });
- string six = "";
- if (client.Sex == 0) six = "Mr";
- else if (client.Sex == 1) six = "Ms";
- itemClientName += string.Format(@"{0}.{1} {2};", clienIndex, client.LastName + client.FirstName, six);
- clienIndex++;
- }
- }
- }
- item.ClientName = itemClientName;
- }
- else
- {
- string clientPinYinName = "";
- decimal unitCost = 0.00M;
- int cNum = item.ClientNum == 0 ? 1 : item.ClientNum;
- unitCost = (item.PayMoney / cNum).ConvertToDecimal1();
- Regex r = new Regex("[0-9]");
- string name1 = item.ClientName;
- name1 = r.Replace(name1, "");
- string[] clientNames = name1.Split('.');
- for (int i = 0; i < item.ClientNum; i++)
- {
- string name = "";
- if (clientNames.Length > 0)
- {
- int index = i + 1;
- if (index < clientNames.Length)
- {
- name = clientNames[index].Replace("MR", "").Replace("MS", "").Trim();
- if (!string.IsNullOrEmpty(name))
- {
- airClientPris.Add(new
- {
- CnName = name,
- EnName = name,
- Price = unitCost,
- AirType = item.AirTypeName
- });
- }
- //if (name.Length > 0)
- //{
- // string nameLastStr = name[name.Length - 1].ToString();
- // if (nameLastStr.IsNumeric())
- // {
- // name = name.Substring(0, name.Length - 1).Trim();
- // }
- //}
- }
- }
- clientPinYinName += string.Format(@"{0}.{1}出票价为:{2} CNY;", Index + 1, name, unitCost.ToString("#0.00"));
- }
- }
- if (!string.IsNullOrEmpty(item.AuditGMDate))
- {
- item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
- }
- AirCNYTotalPrice += item.CNYPrice;
- }
- _geView.GroupAirFeeViews = groupAirFeeViews;
- if (airClientPris.Count > 0)
- {
- var peoplePriStr = "";
- var airClientPris1 = airClientPris.GroupBy(item => item.CnName)
- .Select(group => group.First())
- .ToList();
- int airClientPrisIndex = 1;
- foreach (var item in airClientPris1)
- {
- decimal price = 0.00M;
- var prices = airClientPris.Where(it => it.CnName == item.CnName).ToList();
- foreach (var pri in prices)
- {
- price += pri.Price;
- }
- peoplePriStr += $@"{airClientPrisIndex}.{item.EnName}出票价为: {price.ToString("#0.00")} CNY;";
- airClientPrisIndex++;
- }
- if (!string.IsNullOrEmpty(peoplePriStr))
- {
- str = $@"其中:{peoplePriStr}";
- }
- //经济舱均价
- var airJJCPris = airClientPris.Where(it => it.AirType == "经济舱").ToList();
- if (airJJCPris.Count > 0)
- {
- decimal jjcTotalPrice = 0.00M;
- foreach (var item in airJJCPris)
- {
- jjcTotalPrice += item.Price;
- }
- decimal jjcPeopleNum = airJJCPris.GroupBy(item => item.CnName)
- .Select(group => group.First())
- .ToList().Count;
- JJCAveragePrice = jjcTotalPrice / jjcPeopleNum;
- }
- //公务舱均价
- var airGWCPris = airClientPris.Where(it => it.AirType == "公务舱").ToList();
- if (airGWCPris.Count > 0)
- {
- decimal gwcTotalPrice = 0.00M;
- foreach (var item in airGWCPris)
- {
- gwcTotalPrice += item.Price;
- }
- decimal gwcPeopleNum = airGWCPris.GroupBy(item => item.CnName)
- .Select(group => group.First())
- .ToList().Count;
- GWCAveragePrice = gwcTotalPrice / gwcPeopleNum;
- }
- }
- _geView.GroupAirFeeStr = $@"人民币总费用:{AirCNYTotalPrice.ToString("#0.00")} CNY\r\n{str}\r\n经济舱均价为:{JJCAveragePrice.ToString("#0.00")}CNY/人;公务舱均价为:{GWCAveragePrice.ToString("#0.00")}CNY/人;";
- #endregion
- #region 签证费用
- List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
- string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
- ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
- sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime,
- (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
- From Grp_VisaInfo vi
- Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where vi.IsDel = 0 {1} And vi.DIId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
- groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
- decimal VisaCNYTotalPirce = 0.00M;
- foreach (var item in groupVisaFeeViews)
- {
- string itemClientName = "";
- string visaClients = item.VisaClient;
- if (!string.IsNullOrEmpty(visaClients))
- {
- string[] clientIds = new string[] { };
- if (visaClients.Contains(','))
- {
- clientIds = visaClients.Split(',');
- }
- else
- {
- clientIds = new string[] { visaClients };
- }
- if (clientIds.Length > 0)
- {
- List<int> clientIds1 = new List<int>() { };
- foreach (var clientIdStr in clientIds)
- {
- if (clientIdStr.IsNumeric())
- {
- clientIds1.Add(int.Parse(clientIdStr));
- }
- }
- if (clientIds1.Count > 0)
- {
- var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
- foreach (var client in clients)
- {
- itemClientName += $"{client.LastName + client.FirstName},";
- }
- }
- else
- {
- itemClientName = visaClients;
- }
- }
- }
- if (itemClientName.Length > 0)
- {
- itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
- }
- item.VisaClient = itemClientName;
- VisaCNYTotalPirce += item.CNYPrice;
- if (!string.IsNullOrEmpty(item.AuditGMDate))
- {
- item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
- }
- }
- _geView.GroupVisaFeeViews = groupVisaFeeViews;
- _geView.GroupVisaFeeStr = string.Format(@"人民币总费用:{0} CNY", VisaCNYTotalPirce.ConvertToDecimal1().ToString("#.00"));
- #endregion
- #region 邀请/公务活动 CTable = 81
- List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
- string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
- ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
- sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
- sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,
- (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice2,ccp.Payee,ccp.AuditGMDate,
- ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
- From Grp_InvitationOfficialActivities ioa
- Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
- Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
- Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
- Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
- Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where ioa.IsDel = 0 {1} And ioa.Diid = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
- groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
- #region 邀请/公务活动 - 模拟数据
- //if (groupInvitationalFeeViews.Count < 1)
- //{
- // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
- // {
- // IOAId = 0,
- // IOADiId = 2334,
- // InviterArea = "模拟数据-邀请方地区",
- // Inviter = "模拟数据-邀请方",
- // InviteTime = "2023-10-10",
- // InviteCost = 100.00M,
- // InviteCurrency = "EUR",
- // SendCost = 100.00M,
- // SendCurrency = "EUR",
- // EventsCost = 10000.00M,
- // EventsCurrency = "EUR",
- // TranslateCost = 300.00M,
- // TranslateCurrency = "EUR",
- // PayMoney = 10500.00M,
- // PaymentCurrency = "EUR",
- // CNYPrice = 76765.50M,
- // Payee = "模拟数据-收款方",
- // AuditGMDate = "2023-12-05",
- // OrbitalPrivateTransfer = 1,
- // PayWay = "刷卡",
- // IsPay = 1,
- // Applicant = "刘华举"
- // });
- // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
- // {
- // IOAId = 0,
- // IOADiId = 2334,
- // InviterArea = "模拟数据-邀请方地区",
- // Inviter = "模拟数据-邀请方",
- // InviteTime = "2023-10-10",
- // InviteCost = 100.00M,
- // InviteCurrency = "EUR",
- // SendCost = 100.00M,
- // SendCurrency = "EUR",
- // EventsCost = 10000.00M,
- // EventsCurrency = "EUR",
- // TranslateCost = 300.00M,
- // TranslateCurrency = "EUR",
- // PayMoney = 10500.00M,
- // PaymentCurrency = "EUR",
- // CNYPrice = 76765.50M,
- // Payee = "模拟数据-收款方",
- // AuditGMDate = "2023-12-05",
- // OrbitalPrivateTransfer = 1,
- // PayWay = "刷卡",
- // IsPay = 1,
- // Applicant = "刘华举"
- // });
- //}
- #endregion
- decimal InvitationalCNYTotalPrice = 0.00M;
- foreach (var item in groupInvitationalFeeViews)
- {
- InvitationalCNYTotalPrice += item.CNYPrice2;
- if (!string.IsNullOrEmpty(item.AuditGMDate))
- {
- item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
- }
- string currencyRateStr = "";
- List<string> currencys = new List<string>();
- if (!string.IsNullOrEmpty(item.InviteCurrency)) currencys.Add(item.InviteCurrency);
- if (!string.IsNullOrEmpty(item.SendCurrency)) currencys.Add(item.SendCurrency);
- if (!string.IsNullOrEmpty(item.EventsCurrency)) currencys.Add(item.EventsCurrency);
- if (!string.IsNullOrEmpty(item.TranslateCurrency)) currencys.Add(item.TranslateCurrency);
- if (!string.IsNullOrEmpty(item.PaymentCurrency)) currencys.Add(item.PaymentCurrency);
- currencyRateStr = await GeneralMethod.PostGroupRateByCTableAndCurrency(teamRateData, 81, currencys);
- item.CurrencyRateStr = currencyRateStr;
- }
- _geView.GroupInvitationalFeeViews = groupInvitationalFeeViews;
- _geView.GroupInvitationalFeeStr = string.Format(@"人民币总费用:{0} CNY", InvitationalCNYTotalPrice.ToString("#.00"));
- #endregion
- #region 保险费用
- List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
- string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.PayMoney * ccp.DayRate As CNYPrice,
- sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
- sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
- From Grp_Customers ic
- Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where ic.IsDel = 0 {1} And ic.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
- groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
- decimal InsuranceCNYTotalPrice = 0.00M;
- foreach (var item in groupInsuranceFeeViews)
- {
- InsuranceCNYTotalPrice += item.CNYPrice;
- string itemClientName = "";
- string insClients = item.ClientName;
- if (!string.IsNullOrEmpty(insClients))
- {
- //System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
- //System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
- //if (m_EnName.Success || m_ZHName.Success)
- //{
- // itemClientName = insClients;
- // continue;
- //}
- string[] clientIds = new string[] { };
- if (insClients.Contains(','))
- {
- clientIds = insClients.Split(',');
- }
- else
- {
- clientIds = new string[] { insClients };
- }
- if (clientIds.Length > 0)
- {
- List<int> output = new List<int>();
- foreach (var clientId in clientIds)
- {
- if (clientId.IsNumeric())
- {
- output.Add(int.Parse(clientId));
- }
- }
- if (output.Count > 0)
- {
- var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
- foreach (var client in clients)
- {
- itemClientName += $"{client.LastName + client.FirstName},";
- }
- if (itemClientName.Length > 0)
- {
- itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
- }
- }
- else
- {
- itemClientName = insClients;
- }
- }
- }
- item.ClientName = itemClientName;
- if (!string.IsNullOrEmpty(item.AuditGMDate))
- {
- item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
- }
- }
- _geView.GroupInsuranceFeeViews = groupInsuranceFeeViews;
- _geView.GroupInsuranceFeeStr = string.Format(@"人民币总费用:{0} CNY", InsuranceCNYTotalPrice.ToString("#0.00"));
- #endregion
- #region 其他款项费用 98
- List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
- string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
- (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
- ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
- sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
- From Grp_DecreasePayments dp
- Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where dp.IsDel = 0 And ccp.Ctable = 98 {1} And dp.Diid = {0}
- Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
- groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
- #region 保险费用 - 模拟数据
- //if (groupDecreaseFeeViews.Count < 1)
- //{
- // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
- // {
- // DPId = 0,
- // DPDiId = 2334,
- // PriceName = "模拟数据-费用名称",
- // PayMoney = 1000.00M,
- // PayMoneyCurrency = "CNY",
- // DayRate = 1.0000M,
- // CNYPrice = 1.0000M,
- // AuditGMDate = "2023-12-10 12:13:00",
- // Payee = "模拟数据-付款方",
- // OrbitalPrivateTransfer = 1,
- // PayWay = "现金",
- // IsPay = 1,
- // Applicant = "刘华举"
- // });
- // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
- // {
- // DPId = 0,
- // DPDiId = 2334,
- // PriceName = "模拟数据-费用名称",
- // PayMoney = 1000.00M,
- // PayMoneyCurrency = "CNY",
- // DayRate = 1.0000M,
- // CNYPrice = 1.0000M,
- // AuditGMDate = "2023-12-10 12:13:00",
- // Payee = "模拟数据-付款方",
- // OrbitalPrivateTransfer = 1,
- // PayWay = "现金",
- // IsPay = 1,
- // Applicant = "刘华举"
- // });
- //}
- #endregion
- decimal DecreaseCNYTotalPrice = 0.00M;
- foreach (var item in groupDecreaseFeeViews)
- {
- item.CNYPrice = Convert.ToDecimal(item.CNYPrice.ToString("#0.00"));
- DecreaseCNYTotalPrice += item.CNYPrice;
- if (!string.IsNullOrEmpty(item.AuditGMDate))
- {
- item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
- }
- }
- _geView.GroupDecreaseFeeViews = groupDecreaseFeeViews;
- _geView.GroupDecreaseFeeStr = string.Format(@"人民币总费用:{0} CNY", DecreaseCNYTotalPrice.ToString("#0.00"));
- #endregion
- #region 公司内部操作人员提成
- var royaltyDatas = await _sqlSugar
- .Queryable<Fin_RoyaltyConfirm, Sys_Users, Sys_Users>((rc, u1, u2) =>
- new JoinQueryInfos(
- JoinType.Left, rc.UserId == u1.Id,
- JoinType.Left, rc.CreateUserId == u2.Id
- ))
- .Where((rc, u1, u2) => rc.IsDel == 0 && rc.TeamId == _dto.DiId && rc.IsConfirm == 1)
- .Select((rc, u1, u2) => new GroupRoyaltyFeeInfo()
- {
- GroupId = rc.TeamId,
- OverviewInfo = rc.Temp,
- DetailedInfo = rc.ChiArr,
- Amount = rc.Price,
- IsConfirm = rc.IsConfirm ,
- IsSeed = rc.IsSeed ,
- RoyaltyUserName = u1.CnName,
- CreateUserName = u2.CnName,
- CreateTime = rc.CreateTime
- })
- .ToListAsync();
- decimal royaltyCNYTotalPrice = royaltyDatas.Sum(x => x.Amount);
- _geView.GroupRoyaltyFeeViews = _mapper.Map<List<GroupRoyaltyFeeView>>(royaltyDatas);
- _geView.GroupRoyaltyFeeStr = string.Format(@"人民币总费用:{0} CNY", royaltyCNYTotalPrice.ToString("#0.00"));
- #endregion
- _view.GroupExpenditure = _geView;
- #endregion
- /*
- * 团组报表计算方式
- * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
- * 应收金额 = 应收表.Sum()
- * 已收金额 = 已收表.Sum()
- * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
- * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
- *
- */
- decimal _totalExpenditure = 0.00M; //总支出
- decimal _amountReceivable = 0.00M; //应收金额
- decimal _amountReceived = 0.00M; //已收金额
- decimal _receivableProfit = 0.00M; //应收利润
- decimal _receivedProfit = 0.00M; //已收利润
- _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
- InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount + royaltyCNYTotalPrice;
- _amountReceivable = frTotalAmount;
- _amountReceived = prTotalAmount;
- _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
- _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
- _view.FeeTotalStr = string.Format(@$"<span>
- <span>当前总支出:{_totalExpenditure.ToString("#0.00")} CNY</span>
- <span style='padding-left:10px;color: Green;'>应收金额:{_amountReceivable.ToString("#0.00")} CNY</span>
- <span style='padding-left:10px;color: Green;'>已收金额:{_amountReceived.ToString("#0.00")} CNY</span>
- <span style='padding-left:10px;color: Green;'>应收利润(应收-支出):{_receivableProfit.ToString("#0.00")} CNY</span>
- <span style='padding-left:10px;color: Green;'>已收利润(已收-支出):{_receivedProfit.ToString("#0.00")} CNY</span>
- </span>");
- return Ok(JsonView(true, "查询成功!", _view));
- }
- else
- {
- return Ok(JsonView(false, "查询成功"));
- }
- }
- /// <summary>
- /// 团组报表
- /// Excel 下载
- /// </summary>
- /// <param name="_dto">团组列表请求dto</param>
- /// <returns></returns>
- [HttpPost("PostGroupStatementExportExcel")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> PostGroupStatementExportExcel(GroupStatementDetailsDto _dto)
- {
- //pageId 38
- int currUserId = _dto.UserId, pageId = _dto.PageId, diId = _dto.DiId;
- bool isAudit = _dto.isAudit;
- #region 参数验证
- if (currUserId < 1) return Ok(JsonView(false, "员工Id为空"));
- if (pageId < 1) return Ok(JsonView(false, "页面Id为空"));
- if (diId < 1) return Ok(JsonView(false, "数据Id为空"));
- #region 页面操作权限验证
- var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(currUserId, pageId);
- if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权!"));
- #endregion
- #endregion
- var groupInfo = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => x.IsDel == 0 && x.Id == diId).First();
- if (groupInfo == null) return Ok(JsonView(false, "暂无该条团组信息!"));
- var userInfo = _sqlSugar.Queryable<Sys_Users>().Where(x => x.IsDel == 0 && x.Id == currUserId).First();
- string groupNo = groupInfo.TourCode,
- groupName = groupInfo.TeamName.Replace("|", "、"),
- lister = userInfo?.CnName ?? "-";
- var _clientDatas = _sqlSugar.Queryable<Crm_DeleClient>()
- .Where(it => it.IsDel == 0)
- .Select(x => new Crm_DeleClient { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, Sex = x.Sex })
- .ToList();
- //获取模板
- string tempPath = (AppSettingsHelper.Get("ExcelBasePath") + "Template/团组费用统计模板.xls");
- var designer = new WorkbookDesigner();
- designer.Workbook = new Workbook(tempPath);
- // 获取工作簿中的工作表集合
- var worksheets = designer.Workbook.Worksheets;
- #region 获取sheet,定义datatable,局部变量
- //酒店费用相关
- var hotelFeeSheet = worksheets["酒店费用"];
- var hotelFeeDt = new DataTable($"HotelFeeView");
- decimal hotelCNYTotalCost = 0.00M;
- //地接费用相关
- var OPFeeSheet = worksheets["地接费用"];
- var OPFeeDt = new DataTable($"OPFeeView");
- var OPFeeLabel = string.Empty;
- decimal OPCNYTotalCost = 0.00M;
- //签证费用相关
- var visaFeeSheet = worksheets["签证费用"];
- var visaFeeDt = new DataTable($"VisaFeeView");
- decimal visaCNYTotalCost = 0.00M;
- //邀请费用相关
- var OAFeeSheet = worksheets["邀请费用"];
- var OAFeeDt = new DataTable($"OAFeeView");
- decimal OACNYTotalCost = 0.00M;
- //机票费用相关
- var airTicketFeeSheet = worksheets["机票费用"];
- var airTicketFeeDt = new DataTable($"AirTicketFeeView");
- decimal airTicketCNYTotalCost = 0.00M;
- //保险费用相关
- var insureFeeSheet = worksheets["保险费用"];
- var insureFeeDt = new DataTable($"InsureFeeView");
- decimal insureCNYTotalCost = 0.00M;
- //其他费用相关
- var otherFeeSheet = worksheets["其他费用"];
- var otherFeeDt = new DataTable($"OtherFeeView");
- decimal otherCNYTotalCost = 0.00M;
- //收款退还相关
- var SKTHFeeSheet = worksheets["收款退还"];
- var SKTHFeeDt = new DataTable($"SKTHFeeView");
- decimal SKTHCNYTotalCost = 0.00M;
- //操作提成
- var royaltyFeeSheet = worksheets["操作提成"];
- var royaltyFeeDt = new DataTable($"royaltyFeeView");
- decimal royaltyCNYTotalCost = 0.00M;
- var totalAmount = 0.00M; //支出成本合计
- var accountsAmount = 0.00M; //应收金额合计
- var receivedAmount = 0.00M; //已收金额合计
- var accountsProfit = 0.00M; //应收利润合计
- var receiveProfit = 0.00M; //已收利润合计
- var profitMargin = 0.00M; //利润差合计
- //应收合计相关
- var receivableFeeSheet = worksheets["团组收入(未收)"];
- var receivableFeeDt = new DataTable($"ReceivableFeeView");
- //已收合计相关
- var receivedFeeSheet = worksheets["团组收入(已收)"];
- var receivedFeeDt = new DataTable($"ReceivedFeeView");
- //团组收入支出利润
- var groupIEProfitDt = new DataTable($"IEProfitFeeView");
- #endregion
- #region 酒店费用
- if (hotelFeeSheet != null)
- {
- string hotelFeeSql = string.Format(@"
- SELECT
- hr.Id AS HrId,
- hr.DiId AS HrDiId,
- hr.City,
- hr.HotelName,
- hr.CheckInDate,
- hr.CheckOutDate,
- hr.CardPrice AS RoomPrice,
- sd1.Name AS PaymentCurrency,
- hr.SingleRoomPrice,
- hr.SingleRoomCount,
- hr.DoubleRoomPrice,
- hr.DoubleRoomCount,
- hr.SuiteRoomPrice,
- hr.SuiteRoomCount,
- hr.OtherRoomPrice,
- hr.OtherRoomCount,
- hr.BreakfastPrice,
- sd4.Name AS BreakfastCurrency,
- hr.Isoppay,
- hr.GovernmentRent,
- sd5.Name AS GovernmentRentCurrency,
- hr.CityTax,
- sd6.Name AS CityTaxCurrency,
- ccp.PayMoney,
- (
- ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
- ) AS CNYPrice,
- ccp.PayPercentage,
- ccp.DayRate,
- ccp.Payee,
- ccp.OrbitalPrivateTransfer,
- sd2.Name AS PayWay,
- sd3.Name AS CardType,
- ccp.IsPay,
- u.CnName AS Applicant,
- hr.Remark
- FROM
- Grp_HotelReservations hr
- INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
- LEFT JOIN Sys_SetData sd1 ON ccp.PaymentCurrency = sd1.Id
- LEFT JOIN Sys_SetData sd2 ON ccp.PayDId = sd2.Id
- LEFT JOIN Sys_SetData sd3 ON ccp.CTDId = sd3.Id
- LEFT JOIN Sys_Users u ON ccp.CreateUserId = u.Id
- LEFT JOIN Sys_SetData sd4 ON hr.BreakfastCurrency = sd4.Id
- LEFT JOIN Sys_SetData sd5 ON hr.GovernmentRentCurrency = sd5.Id
- LEFT JOIN Sys_SetData sd6 ON hr.CityTaxCurrency = sd6.Id
- WHERE
- hr.IsDel = 0
- AND ccp.IsDel = 0
- AND ccp.CTable = 76 {1}
- AND ccp.PayMoney <> 0
- AND hr.DiId = {0}
- ORDER BY
- CheckInDate Asc", _dto.DiId, _dto.isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
- var groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
- if (groupHotelFeeViews.Any())
- {
- var _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
- var hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
- var groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
- var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
- foreach (var item in groupHotelFeeViews)
- {
- if (groupHotelContentFeeViews.Count > 0)
- {
- string paymentStr = string.Empty;
- var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
- item.RoomPrice = roomData?.Price ?? 0.00M;
- if (item.RoomPrice != 0)
- {
- if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
- item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
- string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
- string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
- item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
- 收款方:{roomData?.Payee}<br/>
- 费用标识:{feeMark1} <br/>
- 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
- 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
- 是否由地接支付:{isFeeMark1} <br/>";
- }
- var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
- item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
- if (item.BreakfastPrice != 0)
- {
- if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
- item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
- string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
- string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
- item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
- 收款方:{breakfastData?.Payee}<br/>
- 费用标识:{feeMark2} <br/>
- 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
- 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
- 是否由地接支付:{isFeeMark2} <br/>";
- }
- var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
- item.GovernmentRent = landTaxData?.Price ?? 0.00M;
- if (item.GovernmentRent != 0)
- {
- if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
- item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
- string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
- string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
- item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
- 收款方:{landTaxData?.Payee}<br/>
- 费用标识:{feeMark3} <br/>
- 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
- 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
- 是否由地接支付:{isFeeMark3} <br/>";
- }
- var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
- item.CityTax = cityTaxData?.Price ?? 0.00M;
- if (item.CityTax != 0)
- {
- if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
- item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
- string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
- string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
- item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
- 收款方:{cityTaxData?.Payee}<br/>
- 费用标识:{feeMark4} <br/>
- 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
- 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
- 是否由地接支付:{isFeeMark4} <br/>";
- }
- if (!string.IsNullOrEmpty(paymentStr))
- {
- item.IsPay = 2;
- item.PayTips = paymentStr;
- }
- //item.CNYPrice = roomData?.Price ?? 0.00M * roomData?.Rate ?? 0.00M +
- // breakfastData?.Price ?? 0.00M * breakfastData?.Rate ?? 0.00M +
- // landTaxData?.Price ?? 0.00M * landTaxData?.Rate ?? 0.00M +
- // cityTaxData?.Price ?? 0.00M * cityTaxData?.Rate ?? 0.00M;
- }
- else
- {
- decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
- (item.DoubleRoomCount * item.DoubleRoomPrice) +
- (item.SuiteRoomCount * item.SuiteRoomPrice) +
- (item.OtherRoomCount * item.OtherRoomPrice);
- //item.RoomPrice = item.CardPrice;
- item.RoomPriceCurrency = item.PaymentCurrency;
- }
- item.PayMoney = item.PayMoney.ConvertToDecimal1();
- item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
- }
- }
- hotelCNYTotalCost = groupHotelFeeViews.Sum(x => x.CNYPrice);
- hotelFeeDt = CommonFun.ToDataTableArray(groupHotelFeeViews);
- hotelFeeDt.TableName = $"HotelFeeView";
- }
- #endregion
- #region 地接费用
- if (OPFeeSheet != null)
- {
- string CTGGRFeeSql = string.Empty;
- if (groupInfo.VisitDate > Convert.ToDateTime("2024-04-17"))
- {
- CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
- sd2.name As PaymentCurrency,ccp.PayPercentage,
- (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
- (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
- ccp.DayRate,(ctggrc.Price * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
- ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
- From Grp_CarTouristGuideGroundReservations ctggr
- Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
- cggrc.DatePrice,cggrc.PriceContent
- From Grp_CarTouristGuideGroundReservationsContent cggrc
- Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
- Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
- Where cggrc.ISdel = 0 And cggrc.Price != 0.00
- ) ctggrc On ctggr.Id = ctggrc.CTGGRId
- Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
- Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
- }
- else
- {
- CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,
- ccp.PayMoney,sd2.name As PaymentCurrency,ccp.PayPercentage,
- (ccp.PayMoney * (ccp.PayPercentage / 100)) As AmountPaid,
- (ccp.PayMoney -ccp.PayMoney * (ccp.PayPercentage / 100)) As BalancePayment,
- ccp.DayRate,(ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,
- ccp.Payee,ccp.AuditGMDate,
- ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
- From Grp_CarTouristGuideGroundReservations ctggr
- Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
- Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
- }
- var groupOPFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
- string CTGGRFeeStr = "";
- var OPToDataTableViews = groupOPFeeViews;
- decimal CTGGRCNYTotalPrice = 0.00M;
- //按1 地区,2 币种,3 汇率 分组计算
- var groupCTGGRFeeDatas = groupOPFeeViews.GroupBy(it => it.Area);
- foreach (var ctggfr in groupCTGGRFeeDatas)
- {
- var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
- if (ctggfr_curr.Count() > 0)
- {
- foreach (var curr in ctggfr_curr)
- {
- var ctggfr_rate = curr.GroupBy(it => it.DayRate);
- if (ctggfr_rate.Count() > 0)
- {
- foreach (var rate in ctggfr_rate)
- {
- 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");
- CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
- }
- }
- else
- {
- 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");
- CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
- }
- }
- }
- else
- {
- 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");
- CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
- }
- }
- foreach (var item in groupOPFeeViews)
- {
- if (!string.IsNullOrEmpty(item.AuditGMDate))
- {
- item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
- }
- if (item.DatePrice != null)
- {
- item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
- }
- }
- OPCNYTotalCost = CTGGRCNYTotalPrice;
- OPFeeDt = CommonFun.ToDataTableArray(OPToDataTableViews);
- OPFeeLabel = CTGGRFeeStr;
- OPFeeDt.TableName = $"OPFeeView";
- }
- #endregion
- #region 签证费用
- if (visaFeeSheet != null)
- {
- string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
- ccp.DayRate,ccp.Payee,ccp.AuditGMDate,sd2.Name As PaymentModes,sd3.Name As CardTypeName,u.CnName As Applicant,vi.CreateTime,
- (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
- Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
- Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,vi.Remark
- From Grp_VisaInfo vi
- Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where vi.IsDel = 0 {1} And vi.DIId = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
- var groupVisaFeeViews = _sqlSugar.SqlQueryable<GroupVisaFeeExcelView>(groupVisaFeeSql).ToList();
- foreach (var item in groupVisaFeeViews)
- {
- string names = string.Empty;
- string visaClients = item.VisaClient;
- if (!string.IsNullOrEmpty(visaClients))
- {
- var clientIds = new string[] { };
- if (visaClients.Contains(',')) clientIds = visaClients.Split(',');
- else clientIds = new string[] { visaClients };
- if (clientIds.Length > 0)
- {
- var clientIds1 = new List<int>() { };
- foreach (var clientIdStr in clientIds)
- {
- var isInt = int.TryParse(clientIdStr, out int id);
- if (isInt) clientIds1.Add(id);
- }
- if (clientIds1.Count > 0)
- {
- var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
- foreach (var client in clients)
- {
- EncryptionProcessor.DecryptProperties(client);
- names += $"{client.LastName + client.FirstName},";
- }
- }
- else names = visaClients;
- }
- if (names.Length > 0) names = names.Substring(0, names.Length - 1);
- item.VisaClient = names;
- }
- }
- visaCNYTotalCost = groupVisaFeeViews.Sum(x => x.CNYPrice);
- visaFeeDt = CommonFun.ToDataTableArray(groupVisaFeeViews);
- visaFeeDt.TableName = $"VisaFeeView";
- }
- #endregion
- #region 邀请费用
- if (OAFeeSheet != null)
- {
- string feeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,CONVERT(DATE, ioa.InviteTime) AS InviteTime,
- ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
- sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
- sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,ccp.ConsumptionDate,
- Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
- Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
- ccp.Payee,ioa.Remark,ccp.AuditGMDate,u.CnName As Applicant,ioa.CreateTime
- From Grp_InvitationOfficialActivities ioa
- Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
- Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
- Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
- Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
- Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where ioa.IsDel = 0 {1} And ioa.Diid = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
- var feeViews = _sqlSugar.SqlQueryable<GroupOAFeeExcelView>(feeSql).ToList();
- OACNYTotalCost = feeViews.Sum(x => x.CNYPrice);
- OAFeeDt = CommonFun.ToDataTableArray(feeViews);
- OAFeeDt.TableName = $"OAFeeView";
- }
- #endregion
- #region 机票费用
- if (airTicketFeeSheet != null)
- {
- string feeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,
- sd4.Name As AirTypeName,atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,
- atr.PriceDescription,ccp.PayMoney,ccp.DayRate,sd1.Name As PayMoneyCurrency,
- (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
- ccp.Payee,Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
- Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
- sd3.Name As CardType,ccp.AuditGMDate,u.CnName As Applicant,atr.CreateTime,atr.Remark
- From Grp_AirTicketReservations atr
- Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
- Left Join Sys_SetData sd4 On atr.CType = sd4.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where atr.IsDel = 0 {1} And atr.DiId = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
- var feeViews = _sqlSugar.SqlQueryable<GroupAirTicketExcelView>(feeSql).ToList();
- airTicketCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
- airTicketFeeDt = CommonFun.ToDataTableArray(feeViews);
- airTicketFeeDt.TableName = $"AirTicketFeeView";
- }
- #endregion
- #region 保险费用
- if (insureFeeSheet != null)
- {
- string feeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,
- sd1.Name As PayMoneyCurrency,ccp.DayRate,ccp.PayMoney * ccp.DayRate As CNYPrice,ccp.ConsumptionDate,
- Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
- Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
- ccp.Payee,ccp.AuditGMDate,u.CnName As Applicant,ic.CreateTime,ic.Remark
- From Grp_Customers ic
- Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where ic.IsDel = 0 {1} And ic.DiId = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
- var feeViews = _sqlSugar.SqlQueryable<GroupInsureExcelView>(feeSql).ToList();
- foreach (var item in feeViews)
- {
- string itemClientName = "";
- string insClients = item.ClientName;
- if (!string.IsNullOrEmpty(insClients))
- {
- string[] clientIds = new string[] { };
- if (insClients.Contains(',')) clientIds = insClients.Split(',');
- else clientIds = new string[] { insClients };
- if (clientIds.Length > 0)
- {
- List<int> output = new List<int>();
- foreach (var clientId in clientIds)
- if (int.TryParse(clientId, out int id))
- output.Add(id);
- if (output.Count > 0)
- {
- var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
- foreach (var client in clients)
- {
- EncryptionProcessor.DecryptProperties(client);
- itemClientName += $"{client.LastName + client.FirstName},";
- }
- if (itemClientName.Length > 0)
- {
- itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
- }
- }
- else itemClientName = insClients;
- }
- }
- item.ClientName = itemClientName;
- }
- insureCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
- insureFeeDt = CommonFun.ToDataTableArray(feeViews);
- insureFeeDt.TableName = $"InsureFeeView";
- }
- #endregion
- #region 其他费用
- if (insureFeeSheet != null)
- {
- string feeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
- ccp.DayRate,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
- Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
- Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
- ccp.Payee,ccp.AuditGMDate,u.CnName As Applicant,dp.CreateTime,dp.Remark
- From Grp_DecreasePayments dp
- Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where dp.IsDel = 0 And ccp.Ctable = 98 {1} And dp.Diid = {0}
- Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
- var feeViews = _sqlSugar.SqlQueryable<GroupOtherFeeExcelView>(feeSql).ToList();
- otherCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
- otherFeeDt = CommonFun.ToDataTableArray(feeViews);
- otherFeeDt.TableName = $"OtherFeeView";
- }
- #endregion
- #region 收款退还
- if (SKTHFeeSheet != null)
- {
- //删除了 And prom.PriceType = 1
- string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
- prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
- prom.PayType As PrPayType,prom.PriceType As PrPriceType,
- ccp.RMBPrice * ccp.DayRate As RMBPrice,ccp.*,prom.CreateTime As PrCreateTime,prom.Remark AS SKTHRemark
- From Fin_PaymentRefundAndOtherMoney prom
- Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where prom.IsDel = 0
- And prom.PayType = 1
- And ccp.CTable = 285
- {1}
- And prom.DiId = {0} Order By PrCreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
- var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
- if (_promDatas.Any())
- {
- var _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
- var _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
- foreach (var ropItem in _promDatas)
- {
- string thisCueencyCode = "Unknown";
- string thisCueencyName = "Unknown";
- var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
- if (currency != null)
- {
- thisCueencyCode = currency.Name;
- thisCueencyName = currency.Remark;
- }
- string orbitalPrivateTransferStr = "Unknown";
- var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
- if (orbitalPrivateTransfer != null)
- {
- orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
- }
- string payStr = "Unknown";
- var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
- if (pay != null)
- {
- payStr = pay.Name;
- }
- var gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
- {
- Id = ropItem.Id,
- DiId = ropItem.DIId,
- PriceName = ropItem.PrPriceName,
- PayCurrencyCode = thisCueencyCode,
- PayCurrencyName = thisCueencyName,
- Price = ropItem.PrPrice,
- CNYPrice = ropItem.PayMoney * ropItem.DayRate,
- ThisRate = ropItem.DayRate,
- Payee = ropItem.Payee,
- PayTime = ropItem.AuditGMDate,
- OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
- PayType = payStr,
- IsPay = ropItem.IsPay,
- Applicant = ropItem.Appliction,
- Remark = ropItem.SKTHRemark
- };
- _promView.Add(gsd_PaymentRefund);
- }
- SKTHCNYTotalCost = _promView.Sum(x => x.CNYPrice);
- SKTHFeeDt = CommonFun.ToDataTableArray(_promView);
- SKTHFeeDt.TableName = $"SKTHFeeView";
- }
- }
- #endregion
- #region 操作提成
- if (SKTHFeeSheet != null)
- {
- var _royaltyDatas = await _sqlSugar
- .Queryable<Fin_RoyaltyConfirm, Sys_Users, Sys_Users>((rc, u1, u2) =>
- new JoinQueryInfos(
- JoinType.Left, rc.UserId == u1.Id,
- JoinType.Left, rc.CreateUserId == u2.Id
- ))
- .Where((rc, u1, u2) => rc.IsDel == 0 && rc.TeamId == _dto.DiId && rc.IsConfirm == 1)
- .Select((rc, u1, u2) => new GroupRoyaltyFeeInfo()
- {
- GroupId = rc.TeamId,
- OverviewInfo = rc.Temp,
- DetailedInfo = rc.ChiArr,
- Amount = rc.Price,
- IsConfirm = rc.IsConfirm,
- IsSeed = rc.IsSeed,
- RoyaltyUserName = u1.CnName,
- CreateUserName = u2.CnName,
- CreateTime = rc.CreateTime
- })
- .ToListAsync();
- if (_royaltyDatas.Any())
- {
- decimal royaltyCNYTotalPrice = _royaltyDatas.Sum(x => x.Amount);
- var _royaltyFeeViews = _mapper.Map<List<GroupRoyaltyFeeExcelView>>(_royaltyDatas);
- royaltyCNYTotalCost = _royaltyFeeViews.Sum(x => x.Amount);
- royaltyFeeDt = CommonFun.ToDataTableArray(_royaltyFeeViews);
- royaltyFeeDt.TableName = $"RoyaltyFeeView";
- }
- }
- #endregion
- #region 应收金额(增加方式=实际报价时 费用必须审核才能进入团组报表)
- decimal frTotalAmount = 0.00M;//应收总金额
- 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,
- sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime,fr.Remark
- From Fin_ForeignReceivables fr
- Left Join Sys_SetData sd On fr.Currency = sd.Id
- Left Join Sys_Users u On fr.Auditor = u.Id
- Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
- var _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
- _frViews.ForEach(x =>
- {
- string namePrefix = string.Empty;
- if (x.AddingWay == 0) namePrefix = $"账单模块-";
- else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
- else if (x.AddingWay == 2) namePrefix = $"实际报价-";
- x.PriceName = $"{namePrefix}{x.PriceName}";
- });
- if (_frViews.Any())
- {
- accountsAmount = _frViews.Sum(it => it.ItemSumPrice);
- receivableFeeDt = CommonFun.ToDataTableArray(_frViews);
- receivableFeeDt.TableName = $"ReceivedFeeView";
- }
- #endregion
- #region 已收金额
- decimal prTotalAmount = 0.00M;//已收总金额
- string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
- sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
- pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
- From Fin_ProceedsReceived pr
- Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
- Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
- Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
- var _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
- if (_prViews.Any())
- {
- receivedAmount = _prViews.Sum(it => it.Price);
- receivedFeeDt = CommonFun.ToDataTableArray(_prViews);
- receivedFeeDt.TableName = $"ReceivableFeeView";
- }
- #endregion
- #region 团组收入支出利润
- groupIEProfitDt.Columns.AddRange(new DataColumn[] {
- new DataColumn(){ ColumnName = "ModuleName"},
- new DataColumn(){ ColumnName = "FeeTotal",DataType = typeof(decimal)},
- new DataColumn(){ ColumnName = "FeeCurrency"},
- });
- var groupIEProfitDt_rows = new[] {
- new object[] { $"签证费用", visaCNYTotalCost, $"CNY" },
- new object[] { $"酒店费用", hotelCNYTotalCost, $"CNY" },
- new object[] { $"地接费用", OPCNYTotalCost, $"CNY" },
- new object[] { $"商邀费用", OACNYTotalCost, $"CNY" },
- new object[] { $"机票费用", airTicketCNYTotalCost, $"CNY" },
- new object[] { $"保险费用", insureCNYTotalCost, $"CNY" },
- new object[] { $"其他费用", otherCNYTotalCost, $"CNY" },
- new object[] { $"收款退还费用", SKTHCNYTotalCost, $"CNY" },
- new object[] { $"操作提成费用", royaltyCNYTotalCost, $"CNY" },
- };
- // 批量添加
- foreach (var rowData in groupIEProfitDt_rows)
- {
- groupIEProfitDt.Rows.Add(rowData);
- }
- #endregion
- #region 统一填充数据源
- designer.SetDataSource("GroupNo", groupNo);
- designer.SetDataSource("GroupName", groupName);
- designer.SetDataSource("Lister", lister);
- //酒店
- designer.SetDataSource(hotelFeeDt);
- designer.SetDataSource("HotelCNYTotalCost", $"{hotelCNYTotalCost.ToString("#0.00")} CNY");
- //地接
- designer.SetDataSource(OPFeeDt);
- designer.SetDataSource("OPFeeLabel", OPFeeLabel);
- designer.SetDataSource("OPCNYTotalCost", $"{OPCNYTotalCost.ToString("#0.00")} CNY");
- //签证
- designer.SetDataSource(visaFeeDt);
- designer.SetDataSource("VisaCNYTotalCost", $"{visaCNYTotalCost.ToString("#0.00")} CNY");
- //商邀
- designer.SetDataSource(OAFeeDt);
- designer.SetDataSource("OACNYTotalCost", $"{OACNYTotalCost.ToString("#0.00")} CNY");
- //机票
- designer.SetDataSource(airTicketFeeDt);
- designer.SetDataSource("AirTicketCNYTotalCost", $"{airTicketCNYTotalCost.ToString("#0.00")} CNY");
- //保险
- designer.SetDataSource(insureFeeDt);
- designer.SetDataSource("InsureCNYTotalCost", $"{insureCNYTotalCost.ToString("#0.00")} CNY");
- //其他费用
- designer.SetDataSource(otherFeeDt);
- designer.SetDataSource("OtherCNYTotalCost", $"{otherCNYTotalCost.ToString("#0.00")} CNY");
- //收款退还
- designer.SetDataSource(SKTHFeeDt);
- designer.SetDataSource("SKTHCNYTotalCost", $"{SKTHCNYTotalCost.ToString("#0.00")}");
- //操作提成
- designer.SetDataSource(royaltyFeeDt);
- designer.SetDataSource("RoyaltyCNYTotalCost", $"{royaltyCNYTotalCost.ToString("#0.00")} CNY");
- //已收金额
- designer.SetDataSource(receivedFeeDt);
- designer.SetDataSource("ReceivedAmount", $"{receivedAmount.ToString("#0.00")}");
- //应收金额
- designer.SetDataSource(receivableFeeDt);
- designer.SetDataSource("AccountsAmount", $"{accountsAmount.ToString("#0.00")}");
- //应收已收 -- 尾款
- var balancePayment = accountsAmount - SKTHCNYTotalCost - receivedAmount;
- designer.SetDataSource("BalancePayment", $"{balancePayment.ToString("#0.00")}");
- //团组收入支出利润
- designer.SetDataSource(groupIEProfitDt);
- #region 各项费用计算
- /*
- * 团组报表计算方式
- * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
- * 应收金额 = 应收表.Sum() - 收款退还
- * 已收金额 = 已收表.Sum() - 收款退还
- * 应收利润(应收-支出) = 应收金额 - 当前总支出
- * 已收利润(已收-支出) = 已收金额 - 当前总支出
- * 利润差 = 应收利润 - 已收利润
- */
- totalAmount = visaCNYTotalCost + hotelCNYTotalCost + OPCNYTotalCost + OACNYTotalCost + airTicketCNYTotalCost + insureCNYTotalCost + otherCNYTotalCost + royaltyCNYTotalCost;//合计金额
- accountsProfit = accountsAmount - totalAmount - SKTHCNYTotalCost; //应收利润
- receiveProfit = receivedAmount - totalAmount - SKTHCNYTotalCost; //已收利润
- profitMargin = accountsProfit - receiveProfit; //利润差
- designer.SetDataSource("TotalAmount", $"{totalAmount.ToString("#0.00")}");
- designer.SetDataSource("AccountsProfit", $"{accountsProfit.ToString("#0.00")}");
- designer.SetDataSource("ReceiveProfit", $"{receiveProfit.ToString("#0.00")}");
- designer.SetDataSource("ProfitMargin", $"{profitMargin.ToString("#0.00")}");
- #endregion
- designer.Process();
- #endregion
- #region 单元格样式设置 未付款设置为红色
- /*
- * 设置单元格样式
- */
- //背景颜色
- Style style = designer.Workbook.CreateStyle();
- style.ForegroundColor = Color.FromArgb(254, 242, 203);
- style.Pattern = BackgroundType.Solid;
- //字体
- style.Font.Name = "微软雅黑"; // 字体名称
- style.Font.Size = 10; // 字体大小
- style.Font.Color = System.Drawing.Color.Black; // 字体颜色
- StatementExportExcelSetCell(designer, hotelFeeSheet, hotelFeeDt, style, "IsPayLable", 8, "A", "V"); //酒店
- StatementExportExcelSetCell(designer, OPFeeSheet, OPFeeDt, style, "IsPayLabel", 6, "A", "M"); //OP
- StatementExportExcelSetCell(designer, visaFeeSheet, visaFeeDt, style, "IsPay", 6, "A", "I"); //签证
- StatementExportExcelSetCell(designer, OAFeeSheet, OAFeeDt, style, "IsPay", 6, "A", "R"); //商邀
- StatementExportExcelSetCell(designer, airTicketFeeSheet, airTicketFeeDt, style, "IsPay", 6, "A", "M"); //机票
- StatementExportExcelSetCell(designer, insureFeeSheet, insureFeeDt, style, "IsPay", 6, "A", "I"); //保险
- StatementExportExcelSetCell(designer, otherFeeSheet, otherFeeDt, style, "IsPay", 6, "A", "J"); //其他
- StatementExportExcelSetCell(designer, SKTHFeeSheet, SKTHFeeDt, style, "IsPayLable", 6, "A", "K"); //首款退还
- #endregion
- //文件名
- string fileName = $"{groupName}[{groupNo}]_团组费用清单{DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
- designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + "GroupStatement/" + fileName);
- string url = AppSettingsHelper.Get("ExcelBaseUrl") + "Office/Excel/GroupStatement/" + fileName;
- return Ok(JsonView(true, "成功", url));
- }
- /// <summary>
- /// 团组报表
- /// 利润相关数据
- /// </summary>
- /// <returns></returns>
- [HttpPost("PostGroupStatementDetails1")]
- //[JsonConverter(typeof(DecimalConverter), 2)]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> PostGroupStatementDetails1()
- {
- var groupInfos = _sqlSugar.Queryable<Grp_DelegationInfo>()
- .Where(x => x.IsDel == 0 && x.VisitDate >= DateTime.Parse ("2024-01-01") && x.VisitDate <= DateTime.Parse("2024-12-31"))
- .OrderByDescending(x => x.VisitDate)
- .ToList();
- #region 费用类型 币种,转账,客户信息
- List<Sys_SetData> _setDatas = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToList();
- var _clientDatas = _sqlSugar.Queryable<Crm_DeleClient>()
- .Where(it => it.IsDel == 0)
- .Select(x => new Crm_DeleClient { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, Sex = x.Sex })
- .ToList();
- // foreach (var item1 in _clientDatas) EncryptionProcessor.DecryptProperties(item1);
- #endregion
- var _views = new List<GroupStatisticsInfo>();
- int index1 = 0;
- foreach (var info in groupInfos)
- {
- var _dto = new { DiId = info.Id, isAudit = false };
- /*
- * 团组报表计算方式
- * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
- * 应收金额 = 应收表.Sum()
- * 已收金额 = 已收表.Sum()
- * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
- * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
- *
- */
- GroupStatementDetailsView _view = new GroupStatementDetailsView();
- var groupInfo = info;
- var visitDate = info.VisitDate;
- #region 团组收入
- GroupIncomeView _giView = new GroupIncomeView();
- /*
- * 应收报表
- * 增加方式=实际报价时 费用必须审核才能进入团组报表
- */
- decimal frTotalAmount = 0.00M;//应收总金额
- 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,
- sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
- From Fin_ForeignReceivables fr
- Left Join Sys_SetData sd On fr.Currency = sd.Id
- Left Join Sys_Users u On fr.Auditor = u.Id
- Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
- List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
- //List<Gsd_ForeignReceivablesView> _frViews = new List<Gsd_ForeignReceivablesView>();
- //if (_frViews1.Count > 0)
- //{
- // _frViews.AddRange(_frViews1.Where(x => x.AddingWay != 2).ToList());
- // _frViews.AddRange(_frViews1.Where(x => x.AddingWay == 2 && x.Status == 1).ToList());
- //}
- _frViews.ForEach(x =>
- {
- string namePrefix = string.Empty;
- if (x.AddingWay == 0) namePrefix = $"账单模块-";
- else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
- else if (x.AddingWay == 2) namePrefix = $"实际报价-";
- x.PriceName = $"{namePrefix}{x.PriceName}";
- });
- frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
- _giView.Receivables = _frViews;
- _giView.ReceivableStr = string.Format(@"应收款合计:{0} CNY(人民币)", frTotalAmount.ConvertToDecimal1().ToString("#0.00"));
- /*
- * 已收报表
- */
- decimal prTotalAmount = 0.00M;//已收总金额
- string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
- sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
- pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
- From Fin_ProceedsReceived pr
- Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
- Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
- Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
- List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
- prTotalAmount = _prViews.Sum(it => it.Price);
- _giView.ProceedsReceivedViews = _prViews;
- _giView.ProceedsReceivedStr = string.Format(@$"应收合计:{frTotalAmount:#0.00} CNY 已收款合计:{prTotalAmount.ConvertToDecimal1():#0.00} CNY");
- /*
- * 超支费用
- */
- decimal exTotalAmount = 0.00M;
- // 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,
- // (gec.PriceSum * gec.Coefficient * ccp.DayRate) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
- // sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
- //From OA2023DB.dbo.Fin_GroupExtraCost gec
- //Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
- // Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- // Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- // Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
- // Left Join Sys_Users u On ccp.CreateUserId = u.Id
- //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 " : " ");
- // List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(ecSql).ToListAsync();
- // #region 超支费用 - 模拟数据
- // //if (_ExtraCostsViews.Count < 1)
- // //{
- // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
- // // {
- // // GECId = 0,
- // // GECDiId = 2334,
- // // PriceName = "模拟数据-超支费用名称",
- // // PayMoney = 1000.00M,
- // // PaymentCurrency = "CNY",
- // // DayRate = 1.0000M,
- // // CNYPrice = 1000.00M,
- // // Payee = "模拟数据-超支费用收款方",
- // // OrbitalPrivateTransfer = 1,
- // // PayWay = "刷卡",
- // // CardType = "招行卡",
- // // IsPay = 1,
- // // Applicant = "刘华举"
- // // });
- // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
- // // {
- // // GECId = 0,
- // // GECDiId = 2334,
- // // PriceName = "模拟数据-超支费用名称",
- // // PayMoney = 1000.00M,
- // // PaymentCurrency = "CNY",
- // // DayRate = 1.0000M,
- // // CNYPrice = 1000.00M,
- // // Payee = "模拟数据-超支费用收款方",
- // // OrbitalPrivateTransfer = 1,
- // // PayWay = "刷卡",
- // // CardType = "招行卡",
- // // IsPay = 1,
- // // Applicant = "刘华举"
- // // });
- // //}
- // #endregion
- // exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
- // _giView.ExtraCostsViews = _ExtraCostsViews;
- // _giView.ExtraCostsStr = string.Format(@"人民币总费用:{0} CNY", exTotalAmount.ConvertToDecimal1().ToString("#0.00"));
- /*
- * 收款退还
- */
- decimal promTotalAmount = 0.00M;// 收款退还总金额
- List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
- //删除了 And prom.PriceType = 1
- string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
- prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
- prom.PayType As PrPayType,prom.PriceType As PrPriceType,
- ccp.RMBPrice * ccp.DayRate As RMBPrice,ccp.*,prom.CreateTime As PrCreateTime
- From Fin_PaymentRefundAndOtherMoney prom
- Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where prom.IsDel = 0
- And prom.PayType = 1
- And ccp.CTable = 285
- {1}
- And prom.DiId = {0} Order By PrCreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
- var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
- foreach (var ropItem in _promDatas)
- {
- string thisCueencyCode = "Unknown";
- string thisCueencyName = "Unknown";
- var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
- if (currency != null)
- {
- thisCueencyCode = currency.Name;
- thisCueencyName = currency.Remark;
- }
- string orbitalPrivateTransferStr = "Unknown";
- var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
- if (orbitalPrivateTransfer != null)
- {
- orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
- }
- string payStr = "Unknown";
- var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
- if (pay != null)
- {
- payStr = pay.Name;
- }
- Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
- {
- Id = ropItem.Id,
- DiId = ropItem.DIId,
- PriceName = ropItem.PrPriceName,
- PayCurrencyCode = thisCueencyCode,
- PayCurrencyName = thisCueencyName,
- Price = ropItem.PrPrice,
- CNYPrice = ropItem.PayMoney * ropItem.DayRate,
- ThisRate = ropItem.DayRate,
- Payee = ropItem.Payee,
- PayTime = ropItem.AuditGMDate,
- OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
- PayType = payStr,
- IsPay = ropItem.IsPay,
- Applicant = ropItem.Appliction
- };
- _promView.Add(gsd_PaymentRefund);
- }
- #region 收款退还 - 模拟数据
- //if (_promView.Count < 1)
- //{
- // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
- // {
- // Id = 0,
- // DiId = 2334,
- // PriceName = "模拟数据-费用名称",
- // PayCurrencyCode = "CNY",
- // PayCurrencyName = "人民币",
- // Price = 1000.00M,
- // CNYPrice = 1000.00M,
- // ThisRate = 1.00M,
- // Payee = "模拟数据-收款方",
- // PayTime = "2023-01-01 15:20:01",
- // OrbitalPrivateTransfer = 1,
- // PayType = "刷卡",
- // IsPay = 1,
- // Applicant = "刘华举"
- // });
- // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
- // {
- // Id = 0,
- // DiId = 2334,
- // PriceName = "模拟数据-费用名称",
- // PayCurrencyCode = "CNY",
- // PayCurrencyName = "人民币",
- // Price = 1000.00M,
- // CNYPrice = 1000.00M,
- // ThisRate = 1.00M,
- // Payee = "模拟数据-收款方",
- // PayTime = "2023-01-01 15:20:01",
- // OrbitalPrivateTransfer = 1,
- // PayType = "刷卡",
- // IsPay = 1,
- // Applicant = "刘华举"
- // });
- //}
- #endregion
- promTotalAmount = _promView.Sum(it => it.CNYPrice);
- _giView.PaymentRefundAndOtherMoneyViews = _promView;
- _giView.PaymentRefundAndOtherMoneyStr = string.Format(@"人民币总费用:{0} CNY", promTotalAmount.ConvertToDecimal1().ToString("#0.00"));
- decimal BalancePayment = frTotalAmount - prTotalAmount + promTotalAmount;
- _view.GroupIncome = _giView;
- _view.GroupIncomeStr = string.Format(@"<span style='color:red;'>剩余尾款:{0} CNY(包含了收款退还费用数据)</span>", BalancePayment.ConvertToDecimal1().ToString("#0.00"));
- #endregion
- #region 团组支出
- GroupExpenditureView _geView = new GroupExpenditureView();
- #region 酒店预定费用
- List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
- //ccp.RMBPrice As CNYPrice
- //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
- string hotelFeeSql = string.Format(@"
- SELECT
- hr.Id AS HrId,
- hr.DiId AS HrDiId,
- hr.City,
- hr.HotelName,
- hr.CheckInDate,
- hr.CheckOutDate,
- hr.CardPrice AS RoomPrice,
- sd1.Name AS PaymentCurrency,
- hr.SingleRoomPrice,
- hr.SingleRoomCount,
- hr.DoubleRoomPrice,
- hr.DoubleRoomCount,
- hr.SuiteRoomPrice,
- hr.SuiteRoomCount,
- hr.OtherRoomPrice,
- hr.OtherRoomCount,
- hr.BreakfastPrice,
- sd4.Name AS BreakfastCurrency,
- hr.Isoppay,
- hr.GovernmentRent,
- sd5.Name AS GovernmentRentCurrency,
- hr.CityTax,
- sd6.Name AS CityTaxCurrency,
- ccp.PayMoney,
- (
- ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
- ) AS CNYPrice,
- ccp.PayPercentage,
- ccp.DayRate,
- ccp.Payee,
- ccp.OrbitalPrivateTransfer,
- sd2.Name AS PayWay,
- sd3.Name AS CardType,
- ccp.IsPay,
- u.CnName AS Applicant
- FROM
- Grp_HotelReservations hr
- INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
- LEFT JOIN Sys_SetData sd1 ON ccp.PaymentCurrency = sd1.Id
- LEFT JOIN Sys_SetData sd2 ON ccp.PayDId = sd2.Id
- LEFT JOIN Sys_SetData sd3 ON ccp.CTDId = sd3.Id
- LEFT JOIN Sys_Users u ON ccp.CreateUserId = u.Id
- LEFT JOIN Sys_SetData sd4 ON hr.BreakfastCurrency = sd4.Id
- LEFT JOIN Sys_SetData sd5 ON hr.GovernmentRentCurrency = sd5.Id
- LEFT JOIN Sys_SetData sd6 ON hr.CityTaxCurrency = sd6.Id
- WHERE
- hr.IsDel = 0
- AND ccp.IsDel = 0
- AND ccp.CTable = 76 {1}
- AND ccp.PayMoney <> 0
- AND hr.DiId = {0}
- ORDER BY
- CheckInDate Asc", _dto.DiId, _dto.isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
- groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
- List<int> hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
- var groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
- decimal HotelCNYTotalPrice = 0.00M;
- var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
- foreach (var item in groupHotelFeeViews)
- {
- if (groupHotelContentFeeViews.Count > 0)
- {
- string paymentStr = string.Empty;
- var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
- item.RoomPrice = roomData?.Price ?? 0.00M;
- if (item.RoomPrice != 0)
- {
- if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
- item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
- string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
- string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
- item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
- 收款方:{roomData?.Payee}<br/>
- 费用标识:{feeMark1} <br/>
- 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
- 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
- 是否由地接支付:{isFeeMark1} <br/>";
- }
- var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
- item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
- if (item.BreakfastPrice != 0)
- {
- if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
- item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
- string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
- string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
- item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
- 收款方:{breakfastData?.Payee}<br/>
- 费用标识:{feeMark2} <br/>
- 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
- 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
- 是否由地接支付:{isFeeMark2} <br/>";
- }
- var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
- item.GovernmentRent = landTaxData?.Price ?? 0.00M;
- if (item.GovernmentRent != 0)
- {
- if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
- item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
- string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
- string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
- item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
- 收款方:{landTaxData?.Payee}<br/>
- 费用标识:{feeMark3} <br/>
- 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
- 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
- 是否由地接支付:{isFeeMark3} <br/>";
- }
- var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
- item.CityTax = cityTaxData?.Price ?? 0.00M;
- if (item.CityTax != 0)
- {
- if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
- item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
- string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
- string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
- item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
- 收款方:{cityTaxData?.Payee}<br/>
- 费用标识:{feeMark4} <br/>
- 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
- 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
- 是否由地接支付:{isFeeMark4} <br/>";
- }
- if (!string.IsNullOrEmpty(paymentStr))
- {
- item.IsPay = 2;
- item.PayTips = paymentStr;
- }
- //item.CNYPrice = roomData?.Price ?? 0.00M * roomData?.Rate ?? 0.00M +
- // breakfastData?.Price ?? 0.00M * breakfastData?.Rate ?? 0.00M +
- // landTaxData?.Price ?? 0.00M * landTaxData?.Rate ?? 0.00M +
- // cityTaxData?.Price ?? 0.00M * cityTaxData?.Rate ?? 0.00M;
- }
- else
- {
- decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
- (item.DoubleRoomCount * item.DoubleRoomPrice) +
- (item.SuiteRoomCount * item.SuiteRoomPrice) +
- (item.OtherRoomCount * item.OtherRoomPrice);
- //item.RoomPrice = item.CardPrice;
- item.RoomPriceCurrency = item.PaymentCurrency;
- }
- HotelCNYTotalPrice += item.CNYPrice;
- item.PayMoney = item.PayMoney.ConvertToDecimal1();
- item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
- }
- _geView.GroupHotelFeeViews = groupHotelFeeViews;
- _geView.GroupHotelFeeStr = string.Format(@"人民币总费用:{0} CNY", HotelCNYTotalPrice.ToString("#0.00"));
- #endregion
- #region 地接费用
- List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
- string CTGGRFeeSql = string.Empty;
- if (visitDate > Convert.ToDateTime("2024-04-17"))
- {
- CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
- sd2.name As PaymentCurrency,ccp.PayPercentage,
- (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
- (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
- ccp.DayRate,(ctggrc.Price * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
- ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
- From Grp_CarTouristGuideGroundReservations ctggr
- Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
- cggrc.DatePrice,cggrc.PriceContent
- From Grp_CarTouristGuideGroundReservationsContent cggrc
- Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
- Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
- Where cggrc.ISdel = 0 And cggrc.Price != 0.00
- ) ctggrc On ctggr.Id = ctggrc.CTGGRId
- Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
- Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
- }
- else
- {
- CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,
- ccp.PayMoney,sd2.name As PaymentCurrency,ccp.PayPercentage,
- (ccp.PayMoney * (ccp.PayPercentage / 100)) As AmountPaid,
- (ccp.PayMoney -ccp.PayMoney * (ccp.PayPercentage / 100)) As BalancePayment,
- ccp.DayRate,(ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,
- ccp.Payee,ccp.AuditGMDate,
- ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
- From Grp_CarTouristGuideGroundReservations ctggr
- Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
- Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
- }
- groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
- string CTGGRFeeStr = "";
- decimal CTGGRCNYTotalPrice = 0.00M;
- //按1 地区,2 币种,3 汇率 分组计算
- var groupCTGGRFeeDatas = groupCTGGRFeeViews.GroupBy(it => it.Area);
- foreach (var ctggfr in groupCTGGRFeeDatas)
- {
- var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
- if (ctggfr_curr.Count() > 0)
- {
- foreach (var curr in ctggfr_curr)
- {
- var ctggfr_rate = curr.GroupBy(it => it.DayRate);
- if (ctggfr_rate.Count() > 0)
- {
- foreach (var rate in ctggfr_rate)
- {
- 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")})\r\n");
- CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
- }
- }
- else
- {
- 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")})\r\n");
- CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
- }
- }
- }
- else
- {
- 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")})\r\n");
- CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
- }
- }
- foreach (var item in groupCTGGRFeeViews)
- {
- if (!string.IsNullOrEmpty(item.AuditGMDate))
- {
- item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
- }
- if (item.DatePrice != null)
- {
- item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
- }
- //CTGGRFeeStr += string.Format(@"{0} 总费用:{1} {2}(人民币:{3} CNY 当时支付汇率:{4})\r\n",
- // item.Area, item.AmountPaid.ConvertToDecimal1().ToString("#0.00"), item.PaymentCurrency, item.CNYPrice.ToString("#0.0000"), item.DayRate.ToString("#0.0000"));
- //CTGGRCNYTotalPrice += item.CNYPrice;
- }
- _geView.GroupCTGGRFeeViews = groupCTGGRFeeViews;
- _geView.GroupCTGGRFeeStr = string.Format(@"{0}人民币总费用:{1} CNY", CTGGRFeeStr, CTGGRCNYTotalPrice.ToString("#0.00"));
- #endregion
- #region 机票预订费用
- //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
- //ccp.RMBPrice As CNYPrice
- List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
- string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
- atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
- sd1.Name As PayMoneyCurrency,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
- ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime,
- atr.CType
- From Grp_AirTicketReservations atr
- Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
- Left Join Sys_SetData sd4 On atr.CType = sd4.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where atr.IsDel = 0 {1} And atr.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
- groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
- string str = "";
- List<dynamic> airClientPris = new List<dynamic>();
- decimal AirCNYTotalPrice = 0.00M;
- decimal JJCCNYTotalPrice = 0.00M, JJCPeopleNum = 0.00M, JJCAveragePrice = 0.00M;
- decimal GWCCNYTotalPrice = 0.00M, GWCPeopleNum = 0.00M, GWCAveragePrice = 0.00M;
- //if (groupAirFeeViews.Count > 0)
- //{
- // JJCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.CNYPrice);
- // JJCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.ClientNum);
- // JJCAveragePrice = (JJCCNYTotalPrice / JJCPeopleNum).ConvertToDecimal1();
- // GWCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.CNYPrice);
- // GWCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.ClientNum);
- // GWCAveragePrice = (GWCCNYTotalPrice / GWCPeopleNum).ConvertToDecimal1();
- //}
- int Index = 0;
- foreach (var item in groupAirFeeViews)
- {
- if (item.AirId > 2924)
- {
- string itemClientName = "";
- if (!string.IsNullOrEmpty(item.ClientName))
- {
- System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
- System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
- if (m_EnName.Success || m_ZHName.Success)
- {
- itemClientName = item.ClientName;
- decimal unitCost = 0.00M;
- AirCNYTotalPrice += item.CNYPrice;
- continue;
- }
- string[] clientIds = new string[] { };
- if (item.ClientName.Contains(','))
- {
- clientIds = item.ClientName.Split(',');
- }
- else
- {
- clientIds = new string[] { item.ClientName };
- }
- if (clientIds.Length > 0)
- {
- int[] output = System.Array.ConvertAll<string, int>(clientIds, delegate (string s) { return int.Parse(s); });
- if (output.Contains(-1))
- {
- itemClientName += $@"行程单";
- output = output.Where(val => val != -1).ToArray();
- }
- var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
- decimal unitCost = 0.00M;
- unitCost = (item.PayMoney / item.ClientNum).ConvertToDecimal1();
- int clienIndex = 1;
- foreach (var client in clients)
- {
- airClientPris.Add(new
- {
- CnName = client.LastName + client.FirstName,
- EnName = client.Pinyin,
- Price = unitCost,
- AirType = item.AirTypeName
- });
- string six = "";
- if (client.Sex == 0) six = "Mr";
- else if (client.Sex == 1) six = "Ms";
- itemClientName += string.Format(@"{0}.{1} {2};", clienIndex, client.LastName + client.FirstName, six);
- clienIndex++;
- }
- }
- }
- item.ClientName = itemClientName;
- }
- else
- {
- string clientPinYinName = "";
- decimal unitCost = 0.00M;
- int cNum = item.ClientNum == 0 ? 1 : item.ClientNum;
- unitCost = (item.PayMoney / cNum).ConvertToDecimal1();
- Regex r = new Regex("[0-9]");
- string name1 = item.ClientName;
- name1 = r.Replace(name1, "");
- string[] clientNames = name1.Split('.');
- for (int i = 0; i < item.ClientNum; i++)
- {
- string name = "";
- if (clientNames.Length > 0)
- {
- int index = i + 1;
- if (index < clientNames.Length)
- {
- name = clientNames[index].Replace("MR", "").Replace("MS", "").Trim();
- if (!string.IsNullOrEmpty(name))
- {
- airClientPris.Add(new
- {
- CnName = name,
- EnName = name,
- Price = unitCost,
- AirType = item.AirTypeName
- });
- }
- //if (name.Length > 0)
- //{
- // string nameLastStr = name[name.Length - 1].ToString();
- // if (nameLastStr.IsNumeric())
- // {
- // name = name.Substring(0, name.Length - 1).Trim();
- // }
- //}
- }
- }
- clientPinYinName += string.Format(@"{0}.{1}出票价为:{2} CNY;", Index + 1, name, unitCost.ToString("#0.00"));
- }
- }
- if (!string.IsNullOrEmpty(item.AuditGMDate))
- {
- item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
- }
- AirCNYTotalPrice += item.CNYPrice;
- }
- _geView.GroupAirFeeViews = groupAirFeeViews;
- if (airClientPris.Count > 0)
- {
- var peoplePriStr = "";
- var airClientPris1 = airClientPris.GroupBy(item => item.CnName)
- .Select(group => group.First())
- .ToList();
- int airClientPrisIndex = 1;
- foreach (var item in airClientPris1)
- {
- decimal price = 0.00M;
- var prices = airClientPris.Where(it => it.CnName == item.CnName).ToList();
- foreach (var pri in prices)
- {
- price += pri.Price;
- }
- peoplePriStr += $@"{airClientPrisIndex}.{item.EnName}出票价为: {price.ToString("#0.00")} CNY;";
- airClientPrisIndex++;
- }
- if (!string.IsNullOrEmpty(peoplePriStr))
- {
- str = $@"其中:{peoplePriStr}";
- }
- //经济舱均价
- var airJJCPris = airClientPris.Where(it => it.AirType == "经济舱").ToList();
- if (airJJCPris.Count > 0)
- {
- decimal jjcTotalPrice = 0.00M;
- foreach (var item in airJJCPris)
- {
- jjcTotalPrice += item.Price;
- }
- decimal jjcPeopleNum = airJJCPris.GroupBy(item => item.CnName)
- .Select(group => group.First())
- .ToList().Count;
- JJCAveragePrice = jjcTotalPrice / jjcPeopleNum;
- }
- //公务舱均价
- var airGWCPris = airClientPris.Where(it => it.AirType == "公务舱").ToList();
- if (airGWCPris.Count > 0)
- {
- decimal gwcTotalPrice = 0.00M;
- foreach (var item in airGWCPris)
- {
- gwcTotalPrice += item.Price;
- }
- decimal gwcPeopleNum = airGWCPris.GroupBy(item => item.CnName)
- .Select(group => group.First())
- .ToList().Count;
- GWCAveragePrice = gwcTotalPrice / gwcPeopleNum;
- }
- }
- _geView.GroupAirFeeStr = $@"人民币总费用:{AirCNYTotalPrice.ToString("#0.00")} CNY\r\n{str}\r\n经济舱均价为:{JJCAveragePrice.ToString("#0.00")}CNY/人;公务舱均价为:{GWCAveragePrice.ToString("#0.00")}CNY/人;";
- #endregion
- #region 签证费用
- List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
- string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
- ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
- sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime,
- (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
- From Grp_VisaInfo vi
- Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where vi.IsDel = 0 {1} And vi.DIId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
- groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
- decimal VisaCNYTotalPirce = 0.00M;
- foreach (var item in groupVisaFeeViews)
- {
- string itemClientName = "";
- string visaClients = item.VisaClient;
- if (!string.IsNullOrEmpty(visaClients))
- {
- string[] clientIds = new string[] { };
- if (visaClients.Contains(','))
- {
- clientIds = visaClients.Split(',');
- }
- else
- {
- clientIds = new string[] { visaClients };
- }
- if (clientIds.Length > 0)
- {
- List<int> clientIds1 = new List<int>() { };
- foreach (var clientIdStr in clientIds)
- {
- if (clientIdStr.IsNumeric())
- {
- clientIds1.Add(int.Parse(clientIdStr));
- }
- }
- if (clientIds1.Count > 0)
- {
- var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
- foreach (var client in clients)
- {
- itemClientName += $"{client.LastName + client.FirstName},";
- }
- }
- else
- {
- itemClientName = visaClients;
- }
- }
- }
- if (itemClientName.Length > 0)
- {
- itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
- }
- item.VisaClient = itemClientName;
- VisaCNYTotalPirce += item.CNYPrice;
- if (!string.IsNullOrEmpty(item.AuditGMDate))
- {
- item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
- }
- }
- _geView.GroupVisaFeeViews = groupVisaFeeViews;
- _geView.GroupVisaFeeStr = string.Format(@"人民币总费用:{0} CNY", VisaCNYTotalPirce.ConvertToDecimal1().ToString("#.00"));
- #endregion
- #region 邀请/公务活动 CTable = 81
- List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
- string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
- ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
- sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
- sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,
- (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice2,ccp.Payee,ccp.AuditGMDate,
- ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
- From Grp_InvitationOfficialActivities ioa
- Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
- Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
- Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
- Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
- Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where ioa.IsDel = 0 {1} And ioa.Diid = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
- groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
- #region 邀请/公务活动 - 模拟数据
- //if (groupInvitationalFeeViews.Count < 1)
- //{
- // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
- // {
- // IOAId = 0,
- // IOADiId = 2334,
- // InviterArea = "模拟数据-邀请方地区",
- // Inviter = "模拟数据-邀请方",
- // InviteTime = "2023-10-10",
- // InviteCost = 100.00M,
- // InviteCurrency = "EUR",
- // SendCost = 100.00M,
- // SendCurrency = "EUR",
- // EventsCost = 10000.00M,
- // EventsCurrency = "EUR",
- // TranslateCost = 300.00M,
- // TranslateCurrency = "EUR",
- // PayMoney = 10500.00M,
- // PaymentCurrency = "EUR",
- // CNYPrice = 76765.50M,
- // Payee = "模拟数据-收款方",
- // AuditGMDate = "2023-12-05",
- // OrbitalPrivateTransfer = 1,
- // PayWay = "刷卡",
- // IsPay = 1,
- // Applicant = "刘华举"
- // });
- // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
- // {
- // IOAId = 0,
- // IOADiId = 2334,
- // InviterArea = "模拟数据-邀请方地区",
- // Inviter = "模拟数据-邀请方",
- // InviteTime = "2023-10-10",
- // InviteCost = 100.00M,
- // InviteCurrency = "EUR",
- // SendCost = 100.00M,
- // SendCurrency = "EUR",
- // EventsCost = 10000.00M,
- // EventsCurrency = "EUR",
- // TranslateCost = 300.00M,
- // TranslateCurrency = "EUR",
- // PayMoney = 10500.00M,
- // PaymentCurrency = "EUR",
- // CNYPrice = 76765.50M,
- // Payee = "模拟数据-收款方",
- // AuditGMDate = "2023-12-05",
- // OrbitalPrivateTransfer = 1,
- // PayWay = "刷卡",
- // IsPay = 1,
- // Applicant = "刘华举"
- // });
- //}
- #endregion
- decimal InvitationalCNYTotalPrice = 0.00M;
- foreach (var item in groupInvitationalFeeViews)
- {
- InvitationalCNYTotalPrice += item.CNYPrice2;
- if (!string.IsNullOrEmpty(item.AuditGMDate))
- {
- item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
- }
- string currencyRateStr = "";
- List<string> currencys = new List<string>();
- if (!string.IsNullOrEmpty(item.InviteCurrency)) currencys.Add(item.InviteCurrency);
- if (!string.IsNullOrEmpty(item.SendCurrency)) currencys.Add(item.SendCurrency);
- if (!string.IsNullOrEmpty(item.EventsCurrency)) currencys.Add(item.EventsCurrency);
- if (!string.IsNullOrEmpty(item.TranslateCurrency)) currencys.Add(item.TranslateCurrency);
- if (!string.IsNullOrEmpty(item.PaymentCurrency)) currencys.Add(item.PaymentCurrency);
- currencyRateStr = await GeneralMethod.PostGroupRateByCTableAndCurrency(teamRateData, 81, currencys);
- item.CurrencyRateStr = currencyRateStr;
- }
- _geView.GroupInvitationalFeeViews = groupInvitationalFeeViews;
- _geView.GroupInvitationalFeeStr = string.Format(@"人民币总费用:{0} CNY", InvitationalCNYTotalPrice.ToString("#.00"));
- #endregion
- #region 保险费用
- List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
- string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.PayMoney * ccp.DayRate As CNYPrice,
- sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
- sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
- From Grp_Customers ic
- Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where ic.IsDel = 0 {1} And ic.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
- groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
- decimal InsuranceCNYTotalPrice = 0.00M;
- foreach (var item in groupInsuranceFeeViews)
- {
- InsuranceCNYTotalPrice += item.CNYPrice;
- string itemClientName = "";
- string insClients = item.ClientName;
- if (!string.IsNullOrEmpty(insClients))
- {
- //System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
- //System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
- //if (m_EnName.Success || m_ZHName.Success)
- //{
- // itemClientName = insClients;
- // continue;
- //}
- string[] clientIds = new string[] { };
- if (insClients.Contains(','))
- {
- clientIds = insClients.Split(',');
- }
- else
- {
- clientIds = new string[] { insClients };
- }
- if (clientIds.Length > 0)
- {
- List<int> output = new List<int>();
- foreach (var clientId in clientIds)
- {
- if (clientId.IsNumeric())
- {
- output.Add(int.Parse(clientId));
- }
- }
- if (output.Count > 0)
- {
- var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
- foreach (var client in clients)
- {
- itemClientName += $"{client.LastName + client.FirstName},";
- }
- if (itemClientName.Length > 0)
- {
- itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
- }
- }
- else
- {
- itemClientName = insClients;
- }
- }
- }
- item.ClientName = itemClientName;
- if (!string.IsNullOrEmpty(item.AuditGMDate))
- {
- item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
- }
- }
- _geView.GroupInsuranceFeeViews = groupInsuranceFeeViews;
- _geView.GroupInsuranceFeeStr = string.Format(@"人民币总费用:{0} CNY", InsuranceCNYTotalPrice.ToString("#0.00"));
- #endregion
- #region 其他款项费用 98
- List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
- string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
- (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
- ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
- sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
- From Grp_DecreasePayments dp
- Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where dp.IsDel = 0 And ccp.Ctable = 98 {1} And dp.Diid = {0}
- Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
- groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
- #region 保险费用 - 模拟数据
- //if (groupDecreaseFeeViews.Count < 1)
- //{
- // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
- // {
- // DPId = 0,
- // DPDiId = 2334,
- // PriceName = "模拟数据-费用名称",
- // PayMoney = 1000.00M,
- // PayMoneyCurrency = "CNY",
- // DayRate = 1.0000M,
- // CNYPrice = 1.0000M,
- // AuditGMDate = "2023-12-10 12:13:00",
- // Payee = "模拟数据-付款方",
- // OrbitalPrivateTransfer = 1,
- // PayWay = "现金",
- // IsPay = 1,
- // Applicant = "刘华举"
- // });
- // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
- // {
- // DPId = 0,
- // DPDiId = 2334,
- // PriceName = "模拟数据-费用名称",
- // PayMoney = 1000.00M,
- // PayMoneyCurrency = "CNY",
- // DayRate = 1.0000M,
- // CNYPrice = 1.0000M,
- // AuditGMDate = "2023-12-10 12:13:00",
- // Payee = "模拟数据-付款方",
- // OrbitalPrivateTransfer = 1,
- // PayWay = "现金",
- // IsPay = 1,
- // Applicant = "刘华举"
- // });
- //}
- #endregion
- decimal DecreaseCNYTotalPrice = 0.00M;
- foreach (var item in groupDecreaseFeeViews)
- {
- item.CNYPrice = Convert.ToDecimal(item.CNYPrice.ToString("#0.00"));
- DecreaseCNYTotalPrice += item.CNYPrice;
- if (!string.IsNullOrEmpty(item.AuditGMDate))
- {
- item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
- }
- }
- _geView.GroupDecreaseFeeViews = groupDecreaseFeeViews;
- _geView.GroupDecreaseFeeStr = string.Format(@"人民币总费用:{0} CNY", DecreaseCNYTotalPrice.ToString("#0.00"));
- #endregion
- #region 公司内部操作人员提成
- var royaltyDatas = await _sqlSugar
- .Queryable<Fin_RoyaltyConfirm, Sys_Users, Sys_Users>((rc, u1, u2) =>
- new JoinQueryInfos(
- JoinType.Left, rc.UserId == u1.Id,
- JoinType.Left, rc.CreateUserId == u2.Id
- ))
- .Where((rc, u1, u2) => rc.IsDel == 0 && rc.TeamId == _dto.DiId && rc.IsConfirm == 1)
- .Select((rc, u1, u2) => new GroupRoyaltyFeeInfo()
- {
- GroupId = rc.TeamId,
- OverviewInfo = rc.Temp,
- DetailedInfo = rc.ChiArr,
- Amount = rc.Price,
- IsConfirm = rc.IsConfirm,
- IsSeed = rc.IsSeed,
- RoyaltyUserName = u1.CnName,
- CreateUserName = u2.CnName,
- CreateTime = rc.CreateTime
- })
- .ToListAsync();
- decimal royaltyCNYTotalPrice = royaltyDatas.Sum(x => x.Amount);
- _geView.GroupRoyaltyFeeViews = _mapper.Map<List<GroupRoyaltyFeeView>>(royaltyDatas);
- _geView.GroupRoyaltyFeeStr = string.Format(@"人民币总费用:{0} CNY", royaltyCNYTotalPrice.ToString("#0.00"));
- #endregion
- _view.GroupExpenditure = _geView;
- #endregion
- /*
- * 团组报表计算方式
- * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
- * 应收金额 = 应收表.Sum()
- * 已收金额 = 已收表.Sum()
- * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
- * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
- *
- */
- decimal _totalExpenditure = 0.00M; //总支出
- decimal _amountReceivable = 0.00M; //应收金额
- decimal _amountReceived = 0.00M; //已收金额
- decimal _receivableProfit = 0.00M; //应收利润
- decimal _receivedProfit = 0.00M; //已收利润
- _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
- InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount + royaltyCNYTotalPrice;
- _amountReceivable = frTotalAmount;
- _amountReceived = prTotalAmount;
- _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
- _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
- _view.FeeTotalStr = string.Format(@$"<span>
- <span>当前总支出:{_totalExpenditure.ToString("#0.00")} CNY</span>
- <span style='padding-left:10px;color: Green;'>应收金额:{_amountReceivable.ToString("#0.00")} CNY</span>
- <span style='padding-left:10px;color: Green;'>已收金额:{_amountReceived.ToString("#0.00")} CNY</span>
- <span style='padding-left:10px;color: Green;'>应收利润(应收-支出):{_receivableProfit.ToString("#0.00")} CNY</span>
- <span style='padding-left:10px;color: Green;'>已收利润(已收-支出):{_receivedProfit.ToString("#0.00")} CNY</span>
- </span>");
- index1++;
- _views.Add(new GroupStatisticsInfo()
- {
- Index = index1,
- Id = info.Id,
- GroupName = info.TeamName,
- VisitDate = info.VisitDate,
- Receivable = Math.Floor(_amountReceivable * 100) / 100,
- Cost = Math.Floor(_totalExpenditure * 100) / 100,
- Grossprofit = Math.Floor((_amountReceivable - _totalExpenditure) * 100) / 100,
- });
- }
- return Ok(JsonView(true, "查询成功!", _views));
- }
- private class GroupStatisticsInfo
- {
- public int Index { get; set; }
- public int Id { get; set; }
- public string GroupName { get; set; }
- public DateTime VisitDate { get; set; }
- public decimal Receivable { get; set; }
- public decimal Cost { get; set; }
- public decimal Grossprofit { get; set; }
- }
- private void StatementExportExcelSetCell(WorkbookDesigner designer, Worksheet sheet, DataTable dt, Style style, string judgeLable, int startIndex, string startRange, string endRange)
- {
- if (designer == null) return;
- if (sheet == null) return;
- if (style == null) return;
- if (dt == null) return;
- if (string.IsNullOrEmpty(startRange)) return;
- if (string.IsNullOrEmpty(endRange)) return;
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- var isPayStr = dt.Rows[i][$"{judgeLable}"].ToString();
- if (string.IsNullOrEmpty(isPayStr)) continue;
- if (isPayStr.Contains("未付款"))
- {
- var excelIndex = startIndex + i;
- Aspose.Cells.Range range = sheet.Cells.CreateRange($"{startRange}{excelIndex}", $"{endRange}{excelIndex}");
- range.ApplyStyle(style, new StyleFlag() { CellShading = true, Font = true });
- }
- }
- }
- #endregion
- #region 报表/折线图统计
- //企业利润-团组利润
- //企业利润-会务利润
- /// <summary>
- /// 企业利润
- /// Details
- /// 待添加权限验证
- /// </summary>
- /// <param name="_dto">团组列表请求dto</param>
- /// <returns></returns>
- [HttpPost("PostCorporateProfit")]
- //[JsonConverter(typeof(DecimalConverter), 2)]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> PostCorporateProfit(PostCorporateProfitDto _dto)
- {
- #region 参数验证
- if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
- if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
- if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));
- if (_dto.StatisticsType > 2 && _dto.StatisticsType < 1) return Ok(JsonView(false, "请输入有效的StatisticsType参数,1 月份 2 季度"));
- if (_dto.BusinessType > 3 && _dto.BusinessType < 1) return Ok(JsonView(false, "请输入有效的BusinessType参数,1 所有 2 团组 3 会务"));
- PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
- #region 页面操作权限验证
- //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
- //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
- #endregion
- string sqlWhere = string.Empty;
- //起止时间
- DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");
- DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");
- sqlWhere = string.Format(@$" Where Isdel = 0 ");
- //业务类型
- List<int> groupTypeId = new List<int>();
- if (_dto.BusinessType == 2) //团组
- {
- groupTypeId.AddRange(new List<int>() {
- 38, // 政府团
- 39, // 企业团
- 40, // 散客团
- 1048 // 高校团
- });
- }
- else if (_dto.BusinessType == 3) //会务
- {
- groupTypeId.AddRange(new List<int>() {
- 102, // 未知
- 248, // 非团组
- 302, // 成都-会务活动
- 691, // 四川-会务活动
- 762, // 四川-赛事项目收入
- 1047 // 成都-赛事项目收入
- });
- }
- if (groupTypeId.Count > 0)
- {
- sqlWhere += string.Format(@$" And TeamDid In ({string.Join(',', groupTypeId)})");
- }
- string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");
- var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();
- if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));
- List<int> diIds = groupInfos.Select(it => it.Id).ToList();
- List<CorporateProfit> corporateProfits = await CorporateProfit(diIds);
- List<MonthInfo> months = new List<MonthInfo>();
- if (_dto.StatisticsType == 1) //月份
- {
- months = GeneralMethod.GetMonthInfos(Convert.ToInt32(_dto.Year));
- }
- else if (_dto.StatisticsType == 1) //季度
- {
- months = GeneralMethod.GetQuarter(Convert.ToInt32(_dto.Year));
- }
- List<CorporateProfitMonthView> _view = new List<CorporateProfitMonthView>();
- foreach (var item in months)
- {
- DateTime monthBeginDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.BeginDays} 00:00:00");
- DateTime monthEndDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.EndDays} 23:59:59");
- var corporateProfit = corporateProfits.Where(it => it.CreateDt >= monthBeginDt && it.CreateDt <= monthEndDt).ToList();
- _view.Add(new CorporateProfitMonthView()
- {
- Month = item.Month,
- Profit = corporateProfit.Sum(it => it.ReceivedProfit),
- GroupInfos = corporateProfit.OrderBy(it => it.CreateDt).ToList()
- });
- }
- return Ok(JsonView(true, "操作成功!", _view));
- #endregion
- }
- /// <summary>
- /// 计算团组利润
- /// </summary>
- /// <param name="diIds"></param>
- /// <returns></returns>
- private async Task<List<CorporateProfit>> CorporateProfit(List<int> diIds)
- {
- List<CorporateProfit> corporateProfits = new List<CorporateProfit>();
- if (diIds.Count < 1)
- {
- return corporateProfits;
- }
- #region 计算团组利润
- /*
- * 团组报表计算方式
- * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
- * 应收金额 = 应收表.Sum()
- * 已收金额 = 已收表.Sum()
- * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
- * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
- *
- */
- string diIdStr = string.Join(",", diIds);
- string sql = string.Format(@$"Select * From Grp_DelegationInfo Where Isdel = 0 And Id In ({diIdStr})");
- var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).ToListAsync();
- #region 费用类型 币种,转账,客户信息
- List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
- var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>().Where(it => it.IsDel == 0).ToListAsync();
- #endregion
- foreach (var _diId in diIds)
- {
- List<ExpenditureInfo> expenditureInfos = new List<ExpenditureInfo>();
- #region 团组收入
- /*
- * 应收报表
- */
- decimal frTotalAmount = 0.00M;//应收总金额
- string _frSql = string.Format(@"Select fr.Id,fr.Diid,fr.PriceName,fr.Price,fr.Count,fr.Unit,fr.Currency,
- sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
- From Fin_ForeignReceivables fr
- Left Join Sys_SetData sd On fr.Currency = sd.Id
- Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _diId);
- List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
- frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
- expenditureInfos.Add(new ExpenditureInfo() { ItemName = "应收项", Amount = frTotalAmount });
- /*
- * 已收报表
- */
- decimal prTotalAmount = 0.00M;//已收总金额
- string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
- sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
- pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
- From Fin_ProceedsReceived pr
- Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
- Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
- Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _diId);
- List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
- prTotalAmount = _prViews.Sum(it => it.Price);
- expenditureInfos.Add(new ExpenditureInfo() { ItemName = "已收项", Amount = prTotalAmount });
- /*
- * 超支费用
- */
- decimal exTotalAmount = 0.00M;
- string _ecSql = string.Format(@"Select gec.Id As GECId,gec.DiId As GECDiId,gec.PriceName,ccp.PayMoney,sd1.Name As PaymentCurrency,
- ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
- sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
- From OA2023DB.dbo.Fin_GroupExtraCost gec
- Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where ccp.IsDel = 0 And ccp.CTable = 1015 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ccp.DiId = {0} Order By CreateTime", _diId);
- List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(_ecSql).ToListAsync();
- exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
- expenditureInfos.Add(new ExpenditureInfo() { ItemName = "超支费用", Amount = exTotalAmount });
- /*
- * 收款退还
- */
- decimal promTotalAmount = 0.00M;// 收款退还总金额
- List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
- //删除了 And prom.PriceType = 1
- string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
- prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
- prom.PayType As PrPayType,prom.PriceType As PrPriceType,ccp.*,prom.CreateTime As PrCreateTime
- From Fin_PaymentRefundAndOtherMoney prom
- Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where prom.IsDel = 0 And prom.PayType = 1 And ccp.CTable = 285
- And ccp.IsAuditGM = 1 And ccp.IsPay = 1
- And prom.DiId = {0} Order By PrCreateTime", _diId);
- var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
- foreach (var ropItem in _promDatas)
- {
- string thisCueencyCode = "Unknown";
- string thisCueencyName = "Unknown";
- var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
- if (currency != null)
- {
- thisCueencyCode = currency.Name;
- thisCueencyName = currency.Remark;
- }
- string orbitalPrivateTransferStr = "Unknown";
- var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
- if (orbitalPrivateTransfer != null)
- {
- orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
- }
- string payStr = "Unknown";
- var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
- if (pay != null)
- {
- payStr = pay.Name;
- }
- Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
- {
- Id = ropItem.Id,
- DiId = ropItem.DIId,
- PriceName = ropItem.PrPriceName,
- PayCurrencyCode = thisCueencyCode,
- PayCurrencyName = thisCueencyName,
- Price = ropItem.PrPrice,
- CNYPrice = ropItem.RMBPrice,
- ThisRate = ropItem.DayRate,
- Payee = ropItem.Payee,
- PayTime = ropItem.AuditGMDate,
- OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
- PayType = payStr,
- IsPay = ropItem.IsPay,
- Applicant = ropItem.Appliction
- };
- _promView.Add(gsd_PaymentRefund);
- }
- promTotalAmount = _promView.Sum(it => it.CNYPrice);
- expenditureInfos.Add(new ExpenditureInfo() { ItemName = "收款退还", Amount = promTotalAmount });
- #endregion
- #region 团组支出
- GroupExpenditureView _geView = new GroupExpenditureView();
- #region 酒店预定费用
- List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
- string hotelFeeSql = string.Format(@"Select hr.Id As HrId,hr.DiId As HrDiId,hr.City,hr.HotelName,hr.CheckInDate,hr.CheckOutDate,
- sd1.Name As PaymentCurrency,hr.SingleRoomPrice,hr.SingleRoomCount,hr.DoubleRoomPrice,
- hr.DoubleRoomCount,hr.SuiteRoomPrice,hr.SuiteRoomCount,hr.OtherRoomPrice,hr.OtherRoomCount,
- hr.BreakfastPrice,sd4.Name As BreakfastCurrency,hr.Isoppay,hr.GovernmentRent,
- sd5.Name As GovernmentRentCurrency,hr.CityTax,sd6.Name As CityTaxCurrency,
- ccp.PayMoney,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,
- sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant
- From Grp_HotelReservations hr
- Left Join Grp_CreditCardPayment ccp On hr.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Left Join Sys_SetData sd4 On hr.BreakfastCurrency = sd4.Id
- Left Join Sys_SetData sd5 On hr.GovernmentRentCurrency = sd5.Id
- Left Join Sys_SetData sd6 On hr.CityTaxCurrency = sd6.Id
- Where hr.IsDel = 0 And ccp.IsDel = 0 And ccp.CTable = 76 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And hr.DiId = {0}
- Order By CheckInDate Asc", _diId);
- groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
- decimal HotelCNYTotalPrice = groupHotelFeeViews.Sum(it => it.CNYPrice);
- expenditureInfos.Add(new ExpenditureInfo() { ItemName = "酒店预定", Amount = HotelCNYTotalPrice });
- #endregion
- #region 地接费用
- List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
- string CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.Area,ctggrc.*,ctggrc.Price As PayMoney,
- sd2.name As PaymentCurrency,ccp.PayPercentage,
- (ctggrc.Price / (ccp.PayPercentage / 100)) As AmountPaid,
- (ctggrc.Price / (ccp.PayPercentage / 100) - ctggrc.Price) As BalancePayment,
- ccp.DayRate,(ctggrc.Price * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
- ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
- From Grp_CarTouristGuideGroundReservations ctggr
- Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price,sd2.Name As PriceCurrency,
- cggrc.PriceContent
- From Grp_CarTouristGuideGroundReservationsContent cggrc
- Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
- Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
- Where cggrc.ISdel = 0 And cggrc.Price != 0.00
- ) ctggrc On ctggr.Id = ctggrc.CTGGRId
- Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where ctggr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ctggr.DiId = {0}
- Order By CreateTime", _diId);
- groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
- decimal CTGGRCNYTotalPrice = groupCTGGRFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
- expenditureInfos.Add(new ExpenditureInfo() { ItemName = "地接", Amount = CTGGRCNYTotalPrice });
- #endregion
- #region 机票预订费用
- List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
- string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
- atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
- sd1.Name As PayMoneyCurrency,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
- ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime
- From Grp_AirTicketReservations atr
- Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
- Left Join Sys_SetData sd4 On atr.CType = sd4.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where atr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And atr.DiId = {0} Order By CreateTime", _diId);
- groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
- decimal AirCNYTotalPrice = groupAirFeeViews.Sum(it => it.CNYPrice);
- expenditureInfos.Add(new ExpenditureInfo() { ItemName = "机票预订", Amount = AirCNYTotalPrice });
- #endregion
- #region 签证费用
- List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
- string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
- ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
- sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime
- From Grp_VisaInfo vi
- Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where vi.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And vi.DIId = {0} Order By CreateTime", _diId);
- groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
- decimal VisaCNYTotalPirce = groupVisaFeeViews.Sum(it => it.PayMoney);
- expenditureInfos.Add(new ExpenditureInfo() { ItemName = "签证", Amount = VisaCNYTotalPirce });
- #endregion
- #region 邀请/公务活动 CTable = 81
- List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
- string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
- ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
- sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
- sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,ccp.Payee,ccp.AuditGMDate,
- ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
- From Grp_InvitationOfficialActivities ioa
- Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
- Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
- Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
- Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
- Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where ioa.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ioa.Diid = {0} Order By CreateTime", _diId);
- groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
- decimal InvitationalCNYTotalPrice = groupInvitationalFeeViews.Sum(it => it.CNYPrice);
- expenditureInfos.Add(new ExpenditureInfo() { ItemName = "邀请/公务活动", Amount = InvitationalCNYTotalPrice });
- #endregion
- #region 保险费用
- List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
- string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.RMBPrice As CNYPrice,
- sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
- sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
- From Grp_Customers ic
- Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where ic.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ic.DiId = {0} Order By CreateTime", _diId);
- groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
- decimal InsuranceCNYTotalPrice = groupInsuranceFeeViews.Sum(it => it.CNYPrice);
- expenditureInfos.Add(new ExpenditureInfo() { ItemName = "保险费用", Amount = InsuranceCNYTotalPrice });
- #endregion
- #region 其他款项费用 98
- List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
- string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
- (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
- ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
- sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
- From Grp_DecreasePayments dp
- Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
- Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
- Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
- Left Join Sys_Users u On ccp.CreateUserId = u.Id
- Where dp.IsDel = 0 And ccp.Ctable = 98 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And dp.Diid = {0}
- Order By CreateTime", _diId);
- groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
- decimal DecreaseCNYTotalPrice = groupDecreaseFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
- expenditureInfos.Add(new ExpenditureInfo() { ItemName = "其他款项", Amount = DecreaseCNYTotalPrice });
- #endregion
- #endregion
- /*
- * 团组报表计算方式
- * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
- * 应收金额 = 应收表.Sum()
- * 已收金额 = 已收表.Sum()
- * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
- * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
- *
- */
- decimal _totalExpenditure = 0.00M; //总支出
- decimal _amountReceivable = 0.00M; //应收金额
- decimal _amountReceived = 0.00M; //已收金额
- decimal _receivableProfit = 0.00M; //应收利润
- decimal _receivedProfit = 0.00M; //已收利润
- _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
- InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount;
- _amountReceivable = frTotalAmount;
- _amountReceived = prTotalAmount;
- _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
- _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
- var groupInfo = groupInfos.Find(it => it.Id == _diId);
- corporateProfits.Add(new CorporateProfit()
- {
- DiId = _diId,
- TeamName = groupInfo?.TeamName ?? "Unkwnon",
- CreateDt = Convert.ToDateTime(groupInfo?.CreateTime),
- TotalExpenditure = _totalExpenditure,
- ExpenditureItem = expenditureInfos,
- AmountReceivable = _amountReceivable,
- AmountReceived = _amountReceived,
- ReceivableProfit = _receivableProfit,
- ReceivedProfit = _receivedProfit,
- });
- }
- #endregion
- return corporateProfits;
- }
- //未来预测-地区接团/出团量
- //未来预测-地区酒店预订量
- //未来预测-地区机票预订量
- //未来预测-地区车辆预订量
- /// <summary>
- /// (国家/城市)地区预订数量(团,酒店,机票,车辆)
- /// Details
- /// 待添加权限验证
- /// </summary>
- /// <param name="_dto">团组列表请求dto</param>
- /// <returns></returns>
- [HttpPost("PostRegionalBookingsNumber")]
- //[JsonConverter(typeof(DecimalConverter), 2)]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> PostRegionalBookingsNumber(PostRegionalBookingsNumberDto _dto)
- {
- #region 参数验证
- if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
- //if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
- if (_dto.Type > 1 && _dto.Type > 5) return Ok(JsonView(false, "请输入有效的Type参数,1 团 2 酒店 3 机票 4 车辆"));
- if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));
- PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
- #region 页面操作权限验证
- //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
- //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
- #endregion
- string sqlWhere = string.Empty;
- //起止时间
- DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");
- DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");
- sqlWhere = string.Format(@$" Where Isdel = 0 ");
- string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");
- var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();
- if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));
- List<GroupTypeNumberInfo> datas = new List<GroupTypeNumberInfo>();
- foreach (var item in groupInfos)
- {
- var data = await GroupBookingsNumber(_dto.Type, item);
- if (data.TypeItem.Count > 0)
- {
- datas.Add(data);
- }
- }
- //类型处理
- if (_dto.Type == 1)//接团
- {
- List<GroupBookingNumberView> views = new List<GroupBookingNumberView>();
- dynamic groupData = null;
- foreach (var item in datas)
- {
- if (item.TypeItem.Count > 0)
- {
- foreach (var item1 in item.TypeItem)
- {
- if (item1.RegionItem.Count > 0)
- {
- GroupInfo groupInfo = new GroupInfo()
- {
- DiId = item.DiId,
- TeamName = item.GroupName,
- CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",
- ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",
- Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",
- };
- views.Add(new GroupBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, GroupItem = new List<GroupInfo>() { groupInfo } });
- }
- }
- }
- }
- var viewsGroup = views.GroupBy(it => it.Name);
- List<GroupBookingNumberView> _view = new List<GroupBookingNumberView>();
- foreach (var item in viewsGroup)
- {
- List<GroupInfo> infos = new List<GroupInfo>();
- foreach (var item1 in item)
- {
- infos.AddRange(item1.GroupItem);
- }
- infos = infos.OrderByDescending(it => it.CreateTime).ToList(); //
- _view.Add(new GroupBookingNumberView() { Name = item.Key, Number = item.Count(), GroupItem = infos });
- }
- _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();
- return Ok(JsonView(true, "操作成功!", _view, _view.Count));
- }
- else if (_dto.Type == 2)
- {
- List<HotelBookingNumberView> views = new List<HotelBookingNumberView>();
- foreach (var item in datas)
- {
- if (item.TypeItem.Count > 0)
- {
- foreach (var item1 in item.TypeItem)
- {
- if (item1.RegionItem.Count > 0)
- {
- foreach (var item2 in item1.RegionItem)
- {
- GroupInfo groupInfo = new GroupInfo()
- {
- DiId = item.DiId,
- TeamName = item.GroupName,
- CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",
- ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",
- Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",
- };
- List<HotelInfo> hotels = new List<HotelInfo>();
- foreach (var item3 in item2.Data)
- {
- StatisticsHotelInfo statisticsHotelInfos = JsonConvert.DeserializeObject<StatisticsHotelInfo>(JsonConvert.SerializeObject(item3));
- HotelInfo hotelInfo = new HotelInfo()
- {
- HotelName = statisticsHotelInfos.HotelName,
- SingleRoomNum = statisticsHotelInfos.SingleRoomNum,
- DoubleRoomNum = statisticsHotelInfos.DoubleRoomNum,
- SuiteRoomNum = statisticsHotelInfos.SuiteRoomNum,
- OtherRoomNum = statisticsHotelInfos.OtherRoomNum,
- GroupInfo = groupInfo
- };
- hotels.Add(hotelInfo);
- }
- views.Add(new HotelBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, HotelItem = hotels });
- }
- }
- }
- }
- }
- var viewsGroup = views.GroupBy(it => it.Name);
- List<HotelBookingNumberView> _view = new List<HotelBookingNumberView>();
- foreach (var item in viewsGroup)
- {
- List<HotelInfo> infos = new List<HotelInfo>();
- foreach (var item1 in item)
- {
- infos.AddRange(item1.HotelItem);
- }
- _view.Add(new HotelBookingNumberView() { Name = item.Key, Number = item.Count(), HotelItem = infos });
- }
- _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();
- return Ok(JsonView(true, "操作成功!", views, views.Count));
- }
- return Ok(JsonView(false, "操作失败!"));
- #endregion
- }
- /// <summary>
- /// 计算团组ALLType预订数量
- /// </summary>
- /// <param name="diIds"></param>
- /// <returns></returns>
- private async Task<GroupTypeNumberInfo> GroupBookingsNumber(int type, Grp_DelegationInfo info)
- {
- GroupTypeNumberInfo _view = new GroupTypeNumberInfo();
- if (info == null)
- {
- return _view;
- }
- _view.DiId = info.Id;
- _view.GroupName = info.TeamName;
- List<TypeInfo> _types = new List<TypeInfo>();
- #region 计算团组ALLType预订数量
- if (type == 1)
- {
- //接团 客户集团所在地区
- string group_region = string.Empty;
- int group_number = 0;
- if (!string.IsNullOrEmpty(info.ClientUnit))
- {
- var _NewClientData = await _sqlSugar.Queryable<Crm_NewClientData>()
- .Where(it => it.IsDel == 0 && it.Client.Equals(AesEncryptionHelper.Encrypt(info.ClientUnit)))
- .FirstAsync();
- if (_NewClientData != null)
- {
- var regionInfo = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.Id == _NewClientData.Lvlid).FirstAsync();
- if (regionInfo != null)
- {
- group_region = regionInfo.Name.Replace("级", "");
- group_number++;
- }
- }
- }
- if (group_number > 0)
- {
- _types.Add(new TypeInfo() { Id = 1, RegionItem = new List<RegionInfo>() { new RegionInfo() { Name = group_region, Number = group_number } } });
- }
- }
- else if (type == 2)
- {
- //酒店
- var hotelInfos = await _sqlSugar.Queryable<Grp_HotelReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
- if (hotelInfos.Count > 0)
- {
- List<RegionInfo> hotelRegions = new List<RegionInfo>();
- foreach (var item in hotelInfos)
- {
- var hotelNumberInfo = new StatisticsHotelInfo()
- {
- HotelName = item.HotelName,
- SingleRoomNum = item.SingleRoomCount,
- DoubleRoomNum = item.DoubleRoomCount,
- SuiteRoomNum = item.SuiteRoomCount,
- OtherRoomNum = item.OtherRoomCount,
- };
- int hotelRoomTotal = item.SingleRoomCount + item.DoubleRoomCount + item.SuiteRoomCount + item.OtherRoomCount;
- if (hotelRegions.Select(it => it.Name).ToList().Contains(item.City))
- {
- RegionInfo hotelRegion = hotelRegions.Find(it => it.Name.Equals(item.City));
- if (hotelRegion != null)
- {
- hotelRegions.Remove(hotelRegion);
- if (hotelRegion.Data.Count > 0)
- {
- hotelRegion.Data.Add(hotelNumberInfo);
- }
- hotelRegion.Number += hotelRoomTotal;
- hotelRegions.Add(hotelRegion);
- }
- }
- else
- {
- hotelRegions.Add(new RegionInfo() { Name = item.City, Number = hotelRoomTotal, Data = new List<dynamic>() { hotelNumberInfo } });
- }
- }
- _types.Add(new TypeInfo() { Id = 2, RegionItem = hotelRegions });
- }
- }
- else if (type == 3)
- {
- //机票
- var airTicketInfos = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
- .LeftJoin<Grp_CreditCardPayment>((atr, ccp) => atr.Id == ccp.CId && ccp.IsPay == 1)
- .LeftJoin<Sys_SetData>((atr, ccp, sd) => atr.CType == sd.Id)
- .Where((atr, ccp, sd) => atr.IsDel == 0 && atr.DIId == info.Id)
- .Select((atr, ccp, sd) => new { atr.ClientNum, atr.CType, ccp.Payee, AirType = sd.Name })
- .ToListAsync();
- if (airTicketInfos.Count > 0)
- {
- List<RegionInfo> airTicketRegions = new List<RegionInfo>();
- foreach (var item in airTicketInfos)
- {
- var ticketClass = new
- {
- TiketClass = item.AirType,
- Number = item.ClientNum
- };
- if (airTicketRegions.Select(it => it.Name).ToList().Contains(item.Payee))
- {
- RegionInfo airTicketRegion = airTicketRegions.Find(it => it.Name.Equals(item.Payee));
- if (airTicketRegion != null)
- {
- airTicketRegions.Remove(airTicketRegion);
- if (airTicketRegion.Data.Count > 0)
- {
- airTicketRegion.Data.Add(ticketClass);
- }
- airTicketRegion.Number += item.ClientNum;
- airTicketRegions.Add(airTicketRegion);
- }
- }
- else
- {
- airTicketRegions.Add(new RegionInfo() { Name = item.Payee, Number = item.ClientNum, Data = new List<dynamic>() { ticketClass } });
- }
- }
- _types.Add(new TypeInfo() { Id = 3, RegionItem = airTicketRegions });
- }
- }
- else if (type == 4)
- {
- //车辆
- var opInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
- var opContentInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservationsContent>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
- if (opInfos.Count > 0)
- {
- List<RegionInfo> opRegions = new List<RegionInfo>();
- foreach (var item in opInfos)
- {
- int carNum = 0;
- var opContentInfo = opContentInfos.Where(it => it.CTGGRId == item.Id && it.SId == 91).ToList();
- if (opContentInfo.Count > 0)
- {
- foreach (var item1 in opContentInfo)
- {
- if (item1.Price > 0 && item1.Count > 0)
- {
- carNum += item1.Count;
- }
- }
- }
- if (carNum > 0)
- {
- var opData = new
- {
- ServiceCompany = item.ServiceCompany,
- BusName = item.BusName,
- Numbuer = carNum
- };
- if (opRegions.Select(it => it.Name).ToList().Contains(item.Area))
- {
- RegionInfo opRegion = opRegions.Find(it => it.Name.Equals(item.Area));
- if (opRegion != null)
- {
- opRegions.Remove(opRegion);
- if (opRegion.Data.Count > 0)
- {
- opRegion.Data.Add(opData);
- }
- opRegion.Number += carNum;
- opRegions.Add(opRegion);
- }
- }
- else
- {
- opRegions.Add(new RegionInfo() { Name = item.Area, Number = carNum, Data = new List<dynamic>() { opData } });
- }
- }
- }
- _types.Add(new TypeInfo() { Id = 4, RegionItem = opRegions });
- }
- }
- #endregion
- _view.TypeItem = _types;
- return _view;
- }
- #endregion
- #region 市场部销售额
- /// <summary>
- /// 市场部销售额
- /// Init 基础数据(公司/人员/年份/季度/月份)
- /// </summary>
- /// <param name="_dto">市场部销售额请求dto</param>
- /// <returns></returns>
- [HttpPost("PostMarketingSalesInitData")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> PostMarketingSalesInitData(MarketingSalesInitDataDto _dto)
- {
- #region 参数验证
- MarketingSalesInitDataDtoFoalidator validationRules = new MarketingSalesInitDataDtoFoalidator();
- var validResult = await validationRules.ValidateAsync(_dto);
- if (!validResult.IsValid)
- {
- var errors = new StringBuilder();
- foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
- return Ok(JsonView(false, errors.ToString()));
- }
- PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
- #region 页面操作权限验证
- pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
- if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
- #endregion
- var companyData = _sqlSugar.Queryable<Sys_Company>().Where(it => it.IsDel == 0)
- .Select(it => new { id = it.Id, name = it.CompanyName })
- .ToList();
- List<int> companyIds = companyData.Select(it => it.id).ToList();
- List<int> pickGroupUserIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0)
- .Select(it => it.JietuanOperator)
- .ToList();
- var userData = _sqlSugar.Queryable<Sys_Users>()
- .Where(it => it.IsDel == 0 && (pickGroupUserIds.Contains(it.Id) || it.Id == 21))
- .Select(it => new { id = it.Id, companyId = it.CompanyId, name = it.CnName })
- .ToList();
- companyData.Insert(0, new { id = -1, name = "全部" });
- userData.Insert(0, new { id = -1, companyId = -1, name = "全部" });
- #region 年份
- var dtData = new List<dynamic>();
- int dt = DateTime.Now.Year;
- for (int y = dt; y >= dt - 4; y--)
- {
- //季度
- var quarterDatas = new List<dynamic>();
- quarterDatas.Add(new { name = "全部", beginDt = $"{y}-01-01", endDt = $"{y}-12-31" });
- for (int q = 0; q < 4; q++)
- {
- dynamic quarterData = null;
- if (q == 0)
- {
- var monthDatas = new List<dynamic>();
- monthDatas.Add(new { name = $"全部", beginDt = $"{y}-01-01", endDt = $" {y}-03-31" });
- for (int m = 1; m < 4; m++)
- {
- MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
- monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
- }
- //quarterData = new { name = "第一季度", beginDt = $"{y}-01-01", endDt = $" {y}-03-31", monthData = monthDatas };
- quarterData = new { name = "第一季度", monthData = monthDatas };
- }
- else if (q == 1)
- {
- var monthDatas = new List<dynamic>();
- monthDatas.Add(new { name = $"全部", beginDt = $"{y}-04-01", endDt = $"{y}-06-30" });
- for (int m = 4; m < 7; m++)
- {
- MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
- monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
- }
- //quarterData = new { name = "第二季度", beginDt = $"{y}-04-01", endDt = $"{y}-06-30", monthData = monthDatas };
- quarterData = new { name = "第二季度", monthData = monthDatas };
- }
- else if (q == 2)
- {
- var monthDatas = new List<dynamic>();
- monthDatas.Add(new { name = $"全部", beginDt = $"{y}-07-01", endDt = $"{y}-09-30" });
- for (int m = 7; m < 10; m++)
- {
- MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
- monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
- }
- //quarterData = new { name = "第三季度", beginDt = $"{y}-07-01", endDt = $"{y}-09-30", monthData = monthDatas };
- quarterData = new { name = "第三季度", monthData = monthDatas };
- }
- else if (q == 3)
- {
- var monthDatas = new List<dynamic>();
- monthDatas.Add(new { name = $"全部", beginDt = $"{y}-10-01", endDt = $"{y}-12-31" });
- for (int m = 10; m < 13; m++)
- {
- MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
- monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
- }
- //quarterData = new { name = "第四季度", beginDt = $"{y}-10-01", endDt = $"{y}-12-31", monthData = monthDatas };
- quarterData = new { name = "第四季度", monthData = monthDatas };
- }
- quarterDatas.Add(quarterData);
- }
- dtData.Add(new
- {
- year = y,
- //yearData = new { beginDt = $"{y}-01-01", endDt = $"{y}-12-31" },
- quarterData = quarterDatas,
- });
- }
- #endregion
- return Ok(JsonView(true, "操作成功!", new { companyData = companyData, userData = userData, dtData = dtData }));
- #endregion
- }
- private static string ConvertToChinese(int month)
- {
- if (month < 1 || month > 12)
- throw new ArgumentOutOfRangeException(nameof(month), "月份必须在1到12之间。");
- var cultureInfo = new System.Globalization.CultureInfo("zh-CN");
- var dateTimeFormat = cultureInfo.DateTimeFormat;
- return dateTimeFormat.GetMonthName(month);
- }
- /// <summary>
- /// 市场部销售额
- /// 年度/季度/月度 报表(同比)
- /// </summary>
- /// <param name="_dto">市场部销售额请求dto</param>
- /// <returns></returns>
- [HttpPost("PostMarketingSalesStatistics")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> PostMarketingSalesStatistics_Year(MarketingSalesStatisticsDto _dto)
- {
- #region 参数验证
- MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
- var validResult = await validationRules.ValidateAsync(_dto);
- if (!validResult.IsValid)
- {
- var errors = new StringBuilder();
- foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
- return Ok(JsonView(false, errors.ToString()));
- }
- PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
- #region 页面操作权限验证
- pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
- if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
- #endregion
- #endregion
- string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
- return Ok(JsonView(true, "操作成功!", await GroupSales(_dto.CompanyId, _dto.GroupPickupUserId, beginDt, endDt)));
- }
- private async Task<List<int>> GetUserIds(int companyId, int groupPickupUserId)
- {
- //全部人员Id
- //查询所有公司的市场部
- var pickGroupIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0).Select(it => it.JietuanOperator).Distinct().ToList();
- var userIds = new List<int>();
- var userDatas = await _sqlSugar.Queryable<Sys_Users>()
- .InnerJoin<Sys_Company>((u, c) => u.CompanyId == c.Id)
- .Where((u, c) => u.IsDel == 0 && pickGroupIds.Contains(u.Id))
- .Select((u, c) => new { u.Id, u.CompanyId, u.CnName })
- .ToListAsync();
- userIds = userDatas.Select(it => it.Id).ToList();
- if (companyId > 0)
- {
- userIds = userDatas.Where(it => it.CompanyId == companyId).Select(it => it.Id).ToList();
- }
- if (groupPickupUserId > 0)
- {
- userIds = userDatas.Where(it => it.Id == groupPickupUserId).Select(it => it.Id).ToList();
- }
- return userIds;
- }
- /// <summary>
- /// 计算团组销售额
- /// </summary>
- /// <param name="companyId"></param>
- /// <param name="groupPickupUserId"></param>
- /// <param name="beginDt"></param>
- /// <param name="endDt"></param>
- /// <returns></returns>
- private async Task<SalesYOYView> GroupSales(int companyId, int groupPickupUserId, string beginDt, string endDt)
- {
- decimal thisSales = 0.00M, lastSales = 0.00M, yoy = 1.00M;
- var _view = new SalesYOYView();
- List<int> userIds = new List<int>();
- userIds = await GetUserIds(companyId, groupPickupUserId);
- string userSqlWhere = "";
- if (userIds.Count > 0)
- {
- userSqlWhere = string.Format($" And Id IN ({string.Join(',', userIds)})");
- }
- else
- {
- _view = new SalesYOYView
- {
- thisYearSales = "0.00",
- lastYearSales = "0.00",
- };
- return _view;
- }
- string lastBeginDt = Convert.ToDateTime(beginDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss"),
- lastEndDt = Convert.ToDateTime(endDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss");
- // string salesSql = string.Format(@"
- //SELECT
- // 'ThisSales' As [Name],
- // CAST(SUM(Sales) AS decimal(12,2)) As Sales
- //FROM
- // (
- // SELECT di.VisitDate,
- // (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
- // WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
- // ) AS Sales
- // FROM
- // Grp_DelegationInfo di
- // WHERE di.IsDel = 0 AND di.IsSure = 1
- // AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
- // AND di.VisitDate BETWEEN '{1}' AND '{2}'
- // ) temp
- //Union ALL
- //SELECT
- // 'LastSales' As [Name],
- // CAST(SUM(Sales) AS decimal(12,2)) As Sales
- //FROM
- // (
- // SELECT di.VisitDate,
- // (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
- // WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
- // ) AS Sales
- // FROM
- // Grp_DelegationInfo di
- // WHERE di.IsDel = 0 AND di.IsSure = 1
- // AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {3})
- // AND di.VisitDate BETWEEN '{4}' AND '{5}'
- // ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
- string salesSql = string.Format(@"
- SELECT
- 'ThisSales' As [Name],
- CAST(SUM(Sales) AS decimal(12,2)) As Sales
- FROM
- (
- SELECT di.VisitDate,
- (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
- WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
- ) AS Sales
- FROM
- Grp_DelegationInfo di
- WHERE di.IsDel = 0
- AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
- AND di.VisitDate BETWEEN '{1}' AND '{2}'
- ) temp
- Union ALL
- SELECT
- 'LastSales' As [Name],
- CAST(SUM(Sales) AS decimal(12,2)) As Sales
- FROM
- (
- SELECT di.VisitDate,
- (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
- WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
- ) AS Sales
- FROM
- Grp_DelegationInfo di
- WHERE di.IsDel = 0
- AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {3})
- AND di.IsBid = 0
- AND di.TeamName Not Like '%投标%'
- AND di.VisitDate BETWEEN '{4}' AND '{5}'
- ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
- var salesData = await _sqlSugar.SqlQueryable<SalesView>(salesSql).ToListAsync();
- thisSales = salesData.Where(x => x.Name.Equals("ThisSales")).First()?.Sales ?? 0;
- lastSales = salesData.Where(x => x.Name.Equals("LastSales")).First()?.Sales ?? 0;
- if (lastSales != 0 && thisSales != 0) yoy = (thisSales - lastSales) / lastSales;
- return new SalesYOYView()
- {
- thisYearSales = thisSales.ToString("#0.00"),
- lastYearSales = lastSales.ToString("#0.00"),
- yoy = yoy.ToString("#0.00")
- };
- }
- private class SalesView
- {
- public string Name { get; set; }
- public decimal Sales { get; set; }
- }
- private class SalesYOYView
- {
- public string thisYearSales { get; set; }
- public string lastYearSales { get; set; }
- public string yoy { get; set; } = "1.00";
- }
- /// <summary>
- /// 市场部销售额
- /// 团组列表
- /// </summary>
- /// <param name="_dto">市场部销售额请求dto</param>
- /// <returns></returns>
- [HttpPost("PostMarketingSalesGroupList")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> PostMarketingSalesGroupList(MarketingSalesGroupListDto _dto)
- {
- #region 参数验证
- MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
- var validResult = await validationRules.ValidateAsync(_dto);
- if (!validResult.IsValid)
- {
- var errors = new StringBuilder();
- foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
- return Ok(JsonView(false, errors.ToString()));
- }
- PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
- #region 页面操作权限验证
- pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
- if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
- #endregion
- #endregion
- string userSql = "";
- List<int> userIds = new List<int>();
- userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
- if (userIds.Count <= 0)
- {
- return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
- }
- else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
- if (!string.IsNullOrEmpty(_dto.SearchCriteria))
- {
- userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
- }
- string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
- // string sql = string.Format(@$"SELECT
- // ROW_NUMBER() OVER (
- // ORDER BY
- // CollectionDays
- // ) AS RowNumber,
- // *
- //FROM
- // (
- // SELECT
- // di.Id,
- // di.TeamName,
- // di.ClientUnit,
- // di.ClientName,
- // di.VisitDate,
- // di.VisitPNumber,
- // di.JietuanOperator,
- // di.VisitEndDate,
- // (
- // SELECT
- // CAST(
- // COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
- // ) AS GroupSales
- // FROM
- // Fin_ForeignReceivables
- // WHERE
- // IsDel = 0
- // AND di.Id = Diid
- // AND AddingWay IN (0, 1, 2)
- // ) AS GroupSales,
- // u.CnName AS GroupPickupUser,
- // DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
- // FROM
- // Grp_DelegationInfo di
- // WITH
- // (NoLock)
- // LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
- // WHERE
- // di.Isdel = 0
- // AND di.IsSure = 1 {userSql}
- // AND VisitDate Between '{beginDt}' And '{endDt}'
- // ) Temp ");
- string sql = string.Format(@$"SELECT
- ROW_NUMBER() OVER (
- ORDER BY
- CollectionDays
- ) AS RowNumber,
- *
- FROM
- (
- SELECT
- di.Id,
- di.TeamName,
- di.ClientUnit,
- di.ClientName,
- di.VisitDate,
- di.VisitPNumber,
- di.JietuanOperator,
- di.VisitEndDate,
- (
- SELECT
- CAST(
- COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
- ) AS GroupSales
- FROM
- Fin_ForeignReceivables
- WHERE
- IsDel = 0
- AND di.Id = Diid
- AND AddingWay IN (0, 1, 2)
- ) AS GroupSales,
- u.CnName AS GroupPickupUser,
- DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
- FROM
- Grp_DelegationInfo di
- WITH
- (NoLock)
- LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
- WHERE
- di.Isdel = 0
- AND (
- SELECT
- CAST(
- COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
- ) AS GroupSales
- FROM
- Fin_ForeignReceivables
- WHERE
- IsDel = 0
- AND di.Id = Diid
- AND AddingWay IN (0, 1, 2)
- ) > 0
- {userSql}
- AND di.IsBid = 0
- AND di.TeamName Not Like '%投标%'
- AND VisitDate Between '{beginDt}' And '{endDt}'
- ) Temp ");
- RefAsync<int> total = 0;
- var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
- return Ok(JsonView(true, "操作成功!", groupData, total));
- }
- /// <summary>
- /// 市场部销售额
- /// 团组列表Excel下载
- /// </summary>
- /// <param name="_dto">市场部销售额请求dto</param>
- /// <returns></returns>
- [HttpPost("PostMarketingSalesGroupExcel")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> PostMarketingSalesGroupExcel(MarketingSalesGroupListDto _dto)
- {
- #region 参数验证
- MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
- var validResult = await validationRules.ValidateAsync(_dto);
- if (!validResult.IsValid)
- {
- var errors = new StringBuilder();
- foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
- return Ok(JsonView(false, errors.ToString()));
- }
- PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
- #region 页面操作权限验证
- pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
- if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
- #endregion
- #endregion
- string userSql = "";
- var userIds = new List<int>();
- userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
- if (userIds.Count <= 0)
- {
- return Ok(JsonView(false));
- }
- else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
- if (!string.IsNullOrEmpty(_dto.SearchCriteria))
- {
- userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
- }
- string beginDt = $"{_dto.BeginDt} 00:00:00",
- endDt = $"{_dto.EndDt} 23:59:59";
- string sql = string.Format(@$"SELECT
- ROW_NUMBER() OVER (
- ORDER BY
- CollectionDays
- ) AS RowNumber,
- *
- FROM
- (
- SELECT
- di.Id,
- di.TeamName,
- di.ClientUnit,
- di.ClientName,
- di.VisitDate,
- di.VisitPNumber,
- di.JietuanOperator,
- di.VisitEndDate,
- (
- SELECT
- CAST(
- COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
- ) AS GroupSales
- FROM
- Fin_ForeignReceivables
- WHERE
- IsDel = 0
- AND di.Id = Diid
- AND AddingWay IN (0, 1, 2)
- ) AS GroupSales,
- u.CnName AS GroupPickupUser,
- DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
- FROM
- Grp_DelegationInfo di
- WITH
- (NoLock)
- LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
- WHERE
- di.Isdel = 0
- AND (
- SELECT
- CAST(
- COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
- ) AS GroupSales
- FROM
- Fin_ForeignReceivables
- WHERE
- IsDel = 0
- AND di.Id = Diid
- AND AddingWay IN (0, 1, 2)
- ) > 0
- {userSql}
- AND di.IsBid = 0
- AND di.TeamName Not Like '%投标%'
- AND VisitDate Between '{beginDt}' And '{endDt}'
- ) Temp ");
- var view = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToListAsync();
- if (view.Count < 1) return Ok(JsonView(false, "暂无数据!"));
- //DataTable dt = GeneralMethod.
- DataTable dt = CommonFun.GetDataTableFromIList(view);
- dt.TableName = $"_view";
- WorkbookDesigner designer = new WorkbookDesigner();
- designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/营业额团组报表模板.xls");
- designer.SetDataSource(dt);
- designer.SetDataSource("Total", view.Sum(x => x.GroupSales));
- designer.Workbook.Worksheets[0].Name = "营业额团组报表";
- designer.Process();
- string fileName = $"MarketingSales/{_dto.BeginDt}~{_dto.EndDt}营业额团组报表{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
- designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
- string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
- return Ok(JsonView(true, "操作成功", new { url = rst }));
- }
- /// <summary>
- /// 市场部销售额
- /// 客户类型、客户等级 统计
- /// </summary>
- /// <param name="_dto">市场部销售额请求dto</param>
- /// <returns></returns>
- [HttpPost("PostMarketingSalesGroupStatistics")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> PostMarketingSalesGroupStatistics(MarketingSalesGroupStatisticsDto _dto)
- {
- #region 参数验证
- MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
- var validResult = await validationRules.ValidateAsync(_dto);
- if (!validResult.IsValid)
- {
- var errors = new StringBuilder();
- foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
- return Ok(JsonView(false, errors.ToString()));
- }
- PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
- #region 页面操作权限验证
- pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
- if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
- #endregion
- #endregion
- string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
- List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
- string userSql = "";
- if (userIds.Count > 0)
- {
- userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
- }
- else
- {
- if (_dto.PortType == 2 || _dto.PortType == 3)
- {
- return Ok(JsonView(true, "操作成功!", new List<object> { }));
- }
- else
- {
- return Ok(JsonView(true, "操作成功!", new
- {
- customerTypeData = new List<object> { },
- clientGradeData = new List<object> { }
- }));
- }
- }
- string sql = "";
- if (_dto.StatisticsType == 1)
- {
- sql = string.Format(@$"Select
- sd.[Name],
- Count(*) As [Count]
- From Grp_DelegationInfo di
- Left Join Sys_SetData sd On di.TeamDid = sd.Id
- Where di.Isdel = 0
- And (
- SELECT
- CAST(
- COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
- ) AS GroupSales
- FROM
- Fin_ForeignReceivables fr
- WHERE
- fr.IsDel = 0
- AND di.Id = fr.Diid
- AND AddingWay IN (0, 1, 2)
- ) > 0
- {userSql}
- AND di.IsBid = 0
- AND di.TeamName Not Like '%投标%'
- And VisitDate Between '{beginDt}' And '{endDt}'
- Group By [Name]
- Order By Count Desc");
- }
- else if (_dto.StatisticsType == 2)
- {
- sql = string.Format(@$"Select
- sd.[Name],
- Count(*) As [Count]
- From Grp_DelegationInfo di
- Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
- Where di.Isdel = 0
- And (
- SELECT
- CAST(
- COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
- ) AS GroupSales
- FROM
- Fin_ForeignReceivables fr
- WHERE
- fr.IsDel = 0
- AND di.Id = fr.Diid
- AND AddingWay IN (0, 1, 2)
- ) > 0
- {userSql}
- AND di.IsBid = 0
- AND di.TeamName Not Like '%投标%'
- And VisitDate Between '{beginDt}' And '{endDt}'
- Group By [Name]
- Order By Count Desc");
- }
- else return Ok(JsonView(false, "StatisticsType不在可取范围!"));
- if (_dto.PortType == 1)
- {
- string sql1 = string.Format(@$"Select
- sd.[Name],
- Count(*) As [Count]
- From Grp_DelegationInfo di
- Left Join Sys_SetData sd On di.TeamDid = sd.Id
- Where di.Isdel = 0
- And (
- SELECT
- CAST(
- COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
- ) AS GroupSales
- FROM
- Fin_ForeignReceivables fr
- WHERE
- fr.IsDel = 0
- AND di.Id = fr.Diid
- AND AddingWay IN (0, 1, 2)
- ) > 0
- {userSql}
- AND di.IsBid = 0
- AND di.TeamName Not Like '%投标%'
- And VisitDate Between '{beginDt}' And '{endDt}'
- Group By [Name]
- Order By Count Desc");
- var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
- string sql2 = string.Format(@$"Select
- sd.[Name],
- Count(*) As [Count]
- From Grp_DelegationInfo di
- Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
- Where di.Isdel = 0
- And (
- SELECT
- CAST(
- COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
- ) AS GroupSales
- FROM
- Fin_ForeignReceivables fr
- WHERE
- fr.IsDel = 0
- AND di.Id = fr.Diid
- AND AddingWay IN (0, 1, 2)
- ) > 0
- {userSql}
- AND di.IsBid = 0
- AND di.TeamName Not Like '%投标%'
- And VisitDate Between '{beginDt}' And '{endDt}'
- Group By [Name]
- Order By Count Desc");
- var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
- return Ok(JsonView(true, "操作成功!", new
- {
- customerTypeData = customerTypeData,
- clientGradeData = clientGradeData
- }));
- }
- else if (_dto.PortType == 2 || _dto.PortType == 3)
- {
- var data = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql).ToListAsync();
- return Ok(JsonView(true, "操作成功!", data, data.Count));
- }
- else return Ok(JsonView(false, MsgTips.Port));
- }
- /// <summary>
- /// 市场部销售额
- /// 接单排名
- /// </summary>
- /// <param name="_dto">市场部销售额请求dto</param>
- /// <returns></returns>
- [HttpPost("PostMarketingSalesOrderRanking")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> PostMarketingSalesOrderRanking(MarketingSalesOrderRankingDto _dto)
- {
- #region 参数验证
- MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
- var validResult = await validationRules.ValidateAsync(_dto);
- if (!validResult.IsValid)
- {
- var errors = new StringBuilder();
- foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
- return Ok(JsonView(false, errors.ToString()));
- }
- PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
- #region 页面操作权限验证
- pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
- if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
- #endregion
- #endregion
- string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
- List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
- string userSql = "";
- if (userIds.Count > 0)
- {
- userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
- }
- else return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
- string sql = string.Format(@$"Select
- ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
- u.CnName As UserName,
- Count(*) As [Count]
- From Grp_DelegationInfo di
- Left Join Sys_Users u On di.JietuanOperator = u.Id
- Where di.Isdel = 0
- AND (
- SELECT
- CAST(
- COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
- ) AS GroupSales
- FROM
- Fin_ForeignReceivables fr
- WHERE
- fr.IsDel = 0
- AND di.Id = fr.Diid
- AND AddingWay IN (0, 1, 2)
- ) > 0
- {userSql}
- AND di.IsBid = 0
- AND di.TeamName Not Like '%投标%'
- AND VisitDate Between '{beginDt}' AND '{endDt}'
- Group By CnName");
- RefAsync<int> total = 0;
- var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
- return Ok(JsonView(true, "操作成功!", rankingData, total));
- }
- /// <summary>
- /// 市场部销售额
- /// 团组列表、客户类型、客户等级、接单排名
- /// </summary>
- /// <param name="_dto">市场部销售额请求dto</param>
- /// <returns></returns>
- [HttpPost("PostMarketingSalesGroupItem")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> PostMarketingSalesGroupItem(MarketingSalesGroupListDto _dto)
- {
- #region 参数验证
- MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
- var validResult = await validationRules.ValidateAsync(_dto);
- if (!validResult.IsValid)
- {
- var errors = new StringBuilder();
- foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
- return Ok(JsonView(false, errors.ToString()));
- }
- PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
- #region 页面操作权限验证
- pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
- if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
- #endregion
- #endregion
- string userSql = "";
- List<int> userIds = new List<int>();
- userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
- if (userIds.Count <= 0)
- {
- return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
- }
- else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
- if (!string.IsNullOrEmpty(_dto.SearchCriteria))
- {
- userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
- }
- string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
- #region 团组List
- string sql = string.Format(@$"SELECT
- ROW_NUMBER() OVER (
- ORDER BY
- CollectionDays
- ) AS RowNumber,
- *
- FROM
- (
- SELECT
- di.Id,
- di.TeamName,
- di.ClientUnit,
- di.ClientName,
- di.VisitDate,
- di.VisitPNumber,
- di.JietuanOperator,
- di.VisitEndDate,
- (
- SELECT
- CAST(
- COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
- ) AS GroupSales
- FROM
- Fin_ForeignReceivables
- WHERE
- IsDel = 0
- AND di.Id = Diid
- AND AddingWay IN (0, 1, 2)
- ) AS GroupSales,
- u.CnName AS GroupPickupUser,
- DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
- FROM
- Grp_DelegationInfo di
- WITH
- (NoLock)
- LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
- WHERE
- di.Isdel = 0
- AND (
- SELECT
- CAST(
- COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
- ) AS GroupSales
- FROM
- Fin_ForeignReceivables fr
- WHERE
- fr.IsDel = 0
- AND di.Id = fr.Diid
- AND AddingWay IN (0, 1, 2)
- ) > 0
- {userSql}
- AND di.IsBid = 0
- AND di.TeamName Not Like '%投标%'
- AND VisitDate Between '{beginDt}' And '{endDt}'
- ) Temp ");
- RefAsync<int> total = 0;
- var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
- #endregion
- #region 客户类型、客户等级 统计
- string sql1 = string.Format(@$"Select
- sd.[Name],
- Count(*) As [Count]
- From Grp_DelegationInfo di
- Left Join Sys_SetData sd On di.TeamDid = sd.Id
- Where di.Isdel = 0
- And (
- SELECT
- CAST(
- COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
- ) AS GroupSales
- FROM
- Fin_ForeignReceivables fr
- WHERE
- fr.IsDel = 0
- AND di.Id = fr.Diid
- AND AddingWay IN (0, 1, 2)
- ) > 0
- {userSql}
- AND di.IsBid = 0
- AND di.TeamName Not Like '%投标%'
- And VisitDate Between '{beginDt}' And '{endDt}'
- Group By [Name]
- Order By Count Desc");
- var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
- string sql2 = string.Format(@$"Select
- sd.[Name],
- Count(*) As [Count]
- From Grp_DelegationInfo di
- Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
- Where di.Isdel = 0
- And (
- SELECT
- CAST(
- COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
- ) AS GroupSales
- FROM
- Fin_ForeignReceivables fr
- WHERE
- fr.IsDel = 0
- AND di.Id = fr.Diid
- AND AddingWay IN (0, 1, 2)
- ) > 0
- {userSql}
- AND di.IsBid = 0
- AND di.TeamName Not Like '%投标%'
- And VisitDate Between '{beginDt}' And '{endDt}'
- Group By [Name]
- Order By Count Desc");
- var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
- #endregion
- #region 接单排名
- string sql4 = string.Format(@$"Select
- ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
- u.CnName As UserName,
- Count(*) As [Count]
- From Grp_DelegationInfo di
- Left Join Sys_Users u On di.JietuanOperator = u.Id
- Where di.Isdel = 0
- And (
- SELECT
- CAST(
- COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
- ) AS GroupSales
- FROM
- Fin_ForeignReceivables fr
- WHERE
- fr.IsDel = 0
- AND di.Id = fr.Diid
- AND AddingWay IN (0, 1, 2)
- ) > 0
- {userSql}
- AND di.IsBid = 0
- AND di.TeamName Not Like '%投标%'
- And VisitDate Between '{beginDt}' And '{endDt}'
- Group By CnName");
- var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql4).ToListAsync();
- #endregion
- var viewData = new
- {
- groupData = groupData,
- groupTotal = total,
- customerTypeData = customerTypeData,
- clientGradeData = clientGradeData,
- rankingData = rankingData
- };
- return Ok(JsonView(true, "操作成功!", viewData, total));
- }
- /// <summary>
- /// 市场部销售额
- /// 客户拜访列表
- /// </summary>
- /// <param name="_dto">市场部销售额请求dto</param>
- /// <returns></returns>
- [HttpPost("PostMarketingSalesVCList")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> PostMarketingSalesVCList(MarketingSalesVCListDto _dto)
- {
- #region 参数验证
- MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
- var validResult = await validationRules.ValidateAsync(_dto);
- if (!validResult.IsValid)
- {
- var errors = new StringBuilder();
- foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
- return Ok(JsonView(false, errors.ToString()));
- }
- PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
- #region 页面操作权限验证
- pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
- if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
- #endregion
- #endregion
- return Ok(await _visitingClientsRep._List(_dto.PortType, _dto.PageIndex, _dto.PageSize, _dto.DiId, _dto.Search));
- }
- /// <summary>
- /// 市场部销售额
- /// 客户拜访 操作(添加 Or 编辑)
- /// </summary>
- /// <param name="_dto">市场部销售额请求dto</param>
- /// <returns></returns>
- [HttpPost("PostMarketingSalesVCOperate")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> PostMarketingSalesVCOperate(MarketingSalesVCOperrateDto _dto)
- {
- #region 参数验证
- MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
- var validResult = await validationRules.ValidateAsync(_dto);
- if (!validResult.IsValid)
- {
- var errors = new StringBuilder();
- foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
- return Ok(JsonView(false, errors.ToString()));
- }
- PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
- #region 页面操作权限验证
- pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
- if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
- #endregion
- #endregion
- return Ok(await _visitingClientsRep._AddOrEdit(_dto));
- }
- /// <summary>
- /// 市场部销售额
- /// 客户拜访 Del
- /// </summary>
- /// <param name="_dto">市场部销售额请求dto</param>
- /// <returns></returns>
- [HttpPost("PostMarketingSalesVCDel")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> PostMarketingSalesVCDel(MarketingSalesVCDelDto _dto)
- {
- return Ok(await _visitingClientsRep._Del(_dto.Id, _dto.UserId));
- }
- /// <summary>
- /// 市场部销售额
- /// 客户拜访 操作 save
- /// </summary>
- /// <param name="_dto">市场部销售额请求dto</param>
- /// <returns></returns>
- [HttpPost("PostMarketingSalesVCSave")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> PostMarketingSalesVCSave(MarketingSalesVCSaveDto _dto)
- {
- #region 参数验证
- MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
- var validResult = await validationRules.ValidateAsync(_dto);
- if (!validResult.IsValid)
- {
- var errors = new StringBuilder();
- foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
- return Ok(JsonView(false, errors.ToString()));
- }
- PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
- #region 页面操作权限验证
- pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
- if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
- #endregion
- #endregion
- return Ok(await _visitingClientsRep._Save(_dto));
- }
- #endregion
- #region 日付报表
- /// <summary>
- /// 日付类型数据
- /// </summary>
- /// <param name="_dto"></param>
- /// <returns></returns>
- [HttpPost("DailypaymentTypeInit")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> DailypaymentTypeInit(DailypaymentTypeInitDto _dto)
- {
- #region 参数验证
- if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
- PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
- #region 页面操作权限验证
- //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
- //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
- #endregion
- #endregion
- if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
- {
- var defaultParentIds = new List<int>() {
- 48,// 人员费用
- 49,// 办公费用
- 50,// 销售费用
- 51,// 其他费用
- 55,// 大运会
- };
- var dailypaymentTypeData = await RedisRepository.RedisFactory
- .CreateRedisRepository()
- .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
- var dailyTypeData = await _sqlSugar.Queryable<DailypaymentParentTypeView>()
- .Includes(x => x.SubData)
- .Where(x => defaultParentIds.Contains(x.Id))
- .ToListAsync();
- dailyTypeData.ForEach(x =>
- {
- x.SubData.ForEach(y =>
- {
- int currId = dailypaymentTypeData.Find(z => z == y.Id);
- y.IsChecked = currId == 0 ? false : true;
- });
- });
- var companyData = await _sqlSugar.Queryable<Sys_Company>()
- .Where(x => x.IsDel == 0)
- .Select(x => new { id = x.Id, name = x.CompanyName })
- .ToListAsync();
- return Ok(JsonView(true, "查询成功!", new { dailyTypeData = dailyTypeData, companyData = companyData }));
- }
- else
- {
- return Ok(JsonView(false, "查询失败"));
- }
- }
- /// <summary>
- /// 日付类型数据 Save
- /// </summary>
- /// <param name="_dto"></param>
- /// <returns></returns>
- [HttpPost("DailypaymentTypeDataSave")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> DailypaymentTypeDataSave(DailypaymentTypeDataSaveDto _dto)
- {
- #region 参数验证
- if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
- PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
- #region 页面操作权限验证
- //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
- //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
- #endregion
- #endregion
- if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
- {
- if (_dto.TypeIds.Count < 1) return Ok(JsonView(false, "请传入需要保存的TypeIds"));
- var res = await RedisRepository.RedisFactory
- .CreateRedisRepository()
- .StringSetAsync(
- key: "DailypaymentTypeData",
- _dto.TypeIds,
- timeout: null);
- if (!res) return Ok(JsonView(false, "操作失败"));
- return Ok(JsonView(true, "操作成功!"));
- }
- else return Ok(JsonView(false, "操作失败"));
- }
- /// <summary>
- /// 日付数据列表
- /// </summary>
- /// <param name="_dto"></param>
- /// <returns></returns>
- [HttpPost("DailypaymentRange")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> DailypaymentRange(DailypaymentRangeDto _dto)
- {
- #region 参数验证
- var validator = new DailypaymentRangeDtoValidator();
- var validationRes = validator.Validate(_dto);
- if (!validationRes.IsValid)
- {
- StringBuilder sb = new StringBuilder();
- foreach (var item in validationRes.Errors)
- {
- sb.AppendLine(item.ErrorMessage);
- }
- return Ok(JsonView(false, sb.ToString()));
- }
- PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
- #region 页面操作权限验证
- //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
- //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
- #endregion
- #endregion
- if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
- {
- DateTime _beginDt = Convert.ToDateTime($"{_dto.BeginDt} 00:00:00"),
- _endDt = Convert.ToDateTime($"{_dto.EndDt} 23:59:59");
- var sqlWhere = string.Format(@" And dfp.CreateTime Between '{0}' And '{1}'", _beginDt, _endDt);
- var dailypaymentTypeData = await RedisRepository.RedisFactory
- .CreateRedisRepository()
- .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
- var sql = string.Format(@"
- Select
- dfp.Id,
- dfp.Instructions,
- dfp.PriceTypeId,
- sd1.Name As FeeType,
- dfp.TransferTypeId,
- sd2.Name As TransferType,
- dfp.SumPrice,
- dfp.FAuditDate,
- dfp.MAuditDate,
- dfp.CompanyId,
- c.CompanyName,
- dfp.CreateUserId As ApplicantId,
- u.CnName As Applicant,
- dfp.CreateTime As ApplicantDt,
- dfp.Instructions+u.CnName As ViewStr
- From Fin_DailyFeePayment dfp
- Left Join Sys_Users u On dfp.CreateUserId = u.Id
- Left Join Sys_SetData sd1 On dfp.TransferTypeId = sd1.Id
- Left Join Sys_Company c On dfp.CompanyId = c.Id
- Left Join Sys_SetData sd2 On dfp.PriceTypeId = sd2.Id
- Where dfp.IsDel = 0 And dfp.IsPay = 1
- ");//--Order By dfp.CreateTime Desc
- if (_dto.Type == 1) //data
- {
- RefAsync<int> total = 0;
- var _view = await _sqlSugar.SqlQueryable<DailyFeePaymentRangeView>(sql)
- .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
- .WhereIF(dailypaymentTypeData.Count > 0,
- x => dailypaymentTypeData.Contains(x.PriceTypeId))
- .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
- .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
- .OrderByDescending(x => x.ApplicantDt)
- .ToPageListAsync(
- pageNumber: _dto.PageIndex,
- pageSize: _dto.PageSize,
- totalNumber: total
- );
- _sqlSugar.ThenMapper(_view, x =>
- {
- x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
- .SetContext(x1 => x1.DFPId, () => x.Id, x)
- .ToList();
- });
- //单独处理
- return Ok(JsonView(true, "操作成功!", new { data = _view, total = _view.Sum(x => x.SumPrice) }, total));
- }
- else if (_dto.Type == 2) //view
- {
- var _view = await _sqlSugar.SqlQueryable<ExcelView>(sql)
- .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
- .WhereIF(dailypaymentTypeData.Count > 0,
- x => dailypaymentTypeData.Contains(x.PriceTypeId))
- .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
- .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
- .OrderByDescending(x => x.ApplicantDt)
- .ToPageListAsync(
- pageNumber: 1,
- pageSize: 99999
- );
- _sqlSugar.ThenMapper(_view, x =>
- {
- x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
- .SetContext(x1 => x1.DFPId, () => x.Id, x)
- .ToList();
- string str = "";
- int index = 1;
- foreach (var item in x.Contents)
- {
- string str1 = $"{index}、费用名称:[{item.PriceName}] 单价:[{item.Price:#0.00}] 数量:[{item.Quantity:#0.00}] 小计:[{item.ItemTotal:#0.00}] 备注:[{item.Remark}]";
- if (index == x.Contents.Count) str += str1;
- else str += str1 + "\r\n";
- index++;
- }
- x.ContentStr = str;
- });
- if (_view.Count > 0)
- {
- //DataTable dt = GeneralMethod.
- DataTable dt = CommonFun.GetDataTableFromIList(_view);
- dt.TableName = $"_view";
- decimal total = _view.Sum(x => x.SumPrice);
- WorkbookDesigner designer = new WorkbookDesigner();
- designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/日付报表模板.xls");
- designer.SetDataSource(dt);
- designer.SetDataSource("Total", total);
- designer.Workbook.Worksheets[0].Name = "日付报表";
- designer.Process();
- string fileName = $"DailyPayment/日付报表{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
- designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
- string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
- return Ok(JsonView(true, "操作成功", new { url = rst }));
- }
- return Ok(JsonView(true, ",暂无数据"));
- }
- return Ok(JsonView(false, "操作失败"));
- }
- else return Ok(JsonView(false, "操作失败"));
- }
- #endregion
- #region 统计模块
- /// <summary>
- /// 同比
- /// 营业额(今年和去年的)、成本支出(今年和去年的)、毛利润(今年和去年的)
- /// </summary>
- /// <param name="_dto">市场部销售额请求dto</param>
- /// <returns></returns>
- [HttpPost("StatisticsYOY")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> StatisticsYOY(YOYDto _dto)
- {
- //同比增长率 = (本期 - 同期) / 同期 * 100%;
- if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
- string beginDt = $"{_dto.Year - 1}-01-01 00:00:00",
- endDt = $"{_dto.Year}-12-31 23:59:59";
- string sql = string.Format(@"
- SELECT
- di.Id,
- di.TeamName,
- di.VisitDate,
- YEAR(di.VisitDate) AS YEAR,
- MONTH(di.VisitDate) AS MONTH,
- (
- SELECT
- CAST(SUM(ItemSumPrice * Rate) AS DECIMAL(12, 2))
- FROM
- Fin_ForeignReceivables
- WHERE
- IsDel = 0
- AND AddingWay IN (0, 1, 2)
- AND di.Id = Diid
- ) AS SaleAmount,
- (
- SELECT
- CAST(
- SUM(
- (
- ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
- )
- ) AS DECIMAL(12, 2)
- )
- FROM
- Grp_AirTicketReservations atr
- INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
- AND ccp.CTable = 85
- AND atr.Id = ccp.CId
- WHERE
- atr.IsDel = 0
- AND ccp.IsAuditGM = 1
- AND ccp.IsPay = 1
- AND di.Id = atr.DiId
- ) AirTicketAmount,
- (
- SELECT
- CAST(
- SUM(
- (
- ctggr.ServiceQuotedPrice * (ccp.PayPercentage / 100) * ccp.DayRate
- )
- ) AS DECIMAL(12, 2)
- )
- FROM
- Grp_CarTouristGuideGroundReservations ctggr
- INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
- AND ccp.CTable = 79
- AND ctggr.Id = ccp.CId
- WHERE
- ctggr.IsDel = 0
- AND ccp.IsAuditGM = 1
- AND ccp.IsPay = 1
- AND di.Id = ctggr.DiId
- ) AS OPAmount,
- (
- SELECT
- CAST(SUM((ccp.PayMoney * ccp.DayRate)) AS DECIMAL(12, 2))
- FROM
- Grp_DecreasePayments dp
- INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
- AND ccp.CTable = 98
- AND dp.Id = ccp.CId
- WHERE
- dp.IsDel = 0
- AND ccp.Ctable = 98
- AND ccp.IsAuditGM = 1
- AND ccp.IsPay = 1
- AND di.Id = dp.Diid
- ) AS OtherCostAmount,
- (
- SELECT
- CAST(
- SUM(
- (
- (ccp.PayMoney * ccp.DayRate)
- )
- ) AS DECIMAL(12, 2)
- )
- FROM
- Grp_VisaInfo vi
- INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
- AND ccp.CTable = 80
- AND vi.Id = ccp.CId
- WHERE
- vi.IsDel = 0
- AND ccp.IsAuditGM = 1
- AND ccp.IsPay = 1
- AND di.Id = vi.DIId
- ) AS VisaAmount,
- (
- SELECT
- CAST(
- SUM(
- (ccp.PayMoney * ccp.DayRate)
- ) AS DECIMAL(12, 2)
- )
- FROM
- Grp_InvitationOfficialActivities ioa
- INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
- AND ccp.CTable = 81
- AND ioa.Id = ccp.CId
- WHERE
- ioa.IsDel = 0
- AND ccp.IsAuditGM = 1
- AND ccp.IsPay = 1
- AND di.Id = ioa.Diid
- ) AS OAAmount,
- (
- SELECT
- CAST(
- SUM(
- (ccp.PayMoney * ccp.DayRate)
- ) AS DECIMAL(12, 2)
- )
- FROM
- Grp_Customers ic
- INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
- AND ccp.CTable = 82
- AND ic.Id = ccp.CId
- WHERE
- ic.IsDel = 0
- AND ccp.IsAuditGM = 1
- AND ccp.IsPay = 1
- AND di.Id = ic.DiId
- ) AS InsureAmount,
- (
- SELECT
- CAST(
- SUM(
- (ccp.PayMoney * ccp.DayRate)
- ) AS DECIMAL(12, 2)
- )
- FROM
- Grp_HotelReservations hr
- INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
- WHERE
- hr.IsDel = 0
- AND ccp.IsDel = 0
- AND ccp.CTable = 76
- AND ccp.IsAuditGM = 1
- AND ccp.PayMoney <> 0
- AND ccp.IsPay = 1
- AND di.Id = hr.DiId
- ) AS HotelAmount,
- (
- SELECT
- CAST(
- SUM((gec.PriceSum * gec.Coefficient * ccp.DayRate)) AS DECIMAL(12, 2)
- )
- FROM
- OA2023DB.dbo.Fin_GroupExtraCost gec
- INNER JOIN Grp_CreditCardPayment ccp ON gec.Id = ccp.CId
- WHERE
- ccp.IsDel = 0
- AND ccp.CTable = 1015
- AND ccp.IsAuditGM = 1
- AND ccp.IsPay = 1
- AND di.Id = gec.DiId
- ) AS ExcessAmount,
- (
- SELECT
- CAST(
- SUM(
- (ccp.PayMoney * ccp.DayRate)
- ) AS DECIMAL(12, 2)
- )
- FROM
- Fin_PaymentRefundAndOtherMoney prom
- INNER JOIN Grp_CreditCardPayment ccp ON prom.DiId = ccp.DIId
- AND prom.Id = ccp.CId
- WHERE
- prom.IsDel = 0
- AND prom.PayType = 1
- AND ccp.CTable = 285
- AND ccp.IsAuditGM = 1
- AND ccp.IsPay = 1
- AND di.Id = prom.DiId
- ) AS SKTHAmount
- FROM
- Grp_DelegationInfo di
- WHERE
- di.IsDel = 0
- AND di.TeamDid IN (38,39,40,1048)
- AND di.VisitDate BETWEEN '{0}' AND '{1}'
- ORDER BY
- di.VisitDate
- ", beginDt, endDt);
- var data = await _sqlSugar.SqlQueryable<StatisticsYOYView>(sql).ToListAsync();
- var thisYearData = data.Where(x => x.Year == _dto.Year).ToList();
- var lastYearData = data.Where(x => x.Year == (_dto.Year - 1)).ToList();
- List<YOYReturnView> salesYOYData = new List<YOYReturnView>();
- List<YOYReturnView> costYOYData = new List<YOYReturnView>();
- List<YOYReturnView> grossProfitYOYData = new List<YOYReturnView>();
- int monthIndex = 1;
- while (monthIndex < 13)
- {
- var thisMonthData = thisYearData.Where(x => x.Month == monthIndex).ToList();
- var lastMonthData = lastYearData.Where(x => x.Month == monthIndex).ToList();
- var thisGroupIds = thisMonthData.Select(x => x.Id).ToList();
- var lastGroupIds = lastMonthData.Select(x => x.Id).ToList();
- decimal thisSalesAmount = thisMonthData.Sum(x => x?.SaleAmount ?? 0.00M),
- lastSalesAmount = lastMonthData.Sum(x => x?.SaleAmount ?? 0.00M),
- thisCostAmount = thisMonthData.Sum(x => x?.CostAmount ?? 0.00M),
- lastCostAmount = lastMonthData.Sum(x => x?.CostAmount ?? 0.00M),
- thisgrossProfitAmount = thisMonthData.Sum(x => x?.GrossProfitAmount ?? 0.00M),
- lastgrossProfitAmount = lastMonthData.Sum(x => x?.GrossProfitAmount ?? 0.00M);
- salesYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisSalesAmount, lastSalesAmount, thisGroupIds, lastGroupIds));
- costYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisCostAmount, lastCostAmount, thisGroupIds, lastGroupIds));
- grossProfitYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisgrossProfitAmount, lastgrossProfitAmount, thisGroupIds, lastGroupIds));
- monthIndex++;
- }
- salesYOYData = salesYOYData.OrderBy(x => x.Month).ToList();
- costYOYData = costYOYData.OrderBy(x => x.Month).ToList();
- grossProfitYOYData = grossProfitYOYData.OrderBy(x => x.Month).ToList();
- return Ok(JsonView(true, "操作成功!", new { salesYOYData = salesYOYData, costYOYData = costYOYData, grossProfitYOYData = grossProfitYOYData }));
- }
- /// <summary>
- /// 国交数据统计-机票相关
- /// 机票票数、机票到达地、预订平台
- /// </summary>
- /// <param name="_dto"></param>
- /// <returns></returns>
- [HttpPost("StatisticsAirTicket")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> StatisticsAirTicket(YOYDto _dto)
- {
- if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
- string beginDt = $"{_dto.Year}-01-01 00:00:00",
- endDt = $"{_dto.Year}-12-31 23:59:59";
- string sql = string.Format(@"
- SELECT
- atr.DIId,
- atr.FlightsDate,
- YEAR(atr.FlightsDate) AS YEAR,
- MONTH(atr.FlightsDate) AS MONTH,
- atr.CType,
- sd.Name As CTypeName,
- atr.FlightsCity,
- atr.ClientNum,
- atr.ClientName,
- di.TeamName As 'GroupName',
- CASE
- WHEN ccp.Payee = '' OR ccp.Payee IS NULL THEN '未知'
- ELSE ccp.Payee
- END AS 'Platform'
- FROM
- Grp_AirTicketReservations atr
- INNER JOIN Grp_CreditCardPayment ccp ON atr.Id = ccp.CId
- AND ccp.IsDel = 0
- AND CTable = 85
- INNER JOIN Grp_DelegationInfo di ON atr.DIId = di.Id
- LEFT JOIN Sys_SetData sd On atr.CType = sd.Id
- WHERE
- atr.IsDel = 0
- AND di.TeamDid IN (38,39,40,1048)
- AND atr.CType IN(457,458,459,460,574,575)
- AND CHARINDEX('行程单',atr.ClientName) = 0
- AND CHARINDEX('返点',atr.ClientName) = 0
- AND CHARINDEX('-1',atr.ClientName) = 0
- AND ccp.IsPay = 1
- AND atr.FlightsDate BETWEEN '{0}' AND '{1}'
- ORDER BY atr.FlightsDate
- ", beginDt, endDt);
- var data = await _sqlSugar.SqlQueryable<StatisticsAirTicketView>(sql).ToListAsync();
- var groupIds = data.Select(x => x.DIId).ToList();
- //处理城市数据
- var threeCodeData = await _sqlSugar.Queryable<Res_ThreeCode>().Where(x => x.IsDel == 0).ToListAsync();
- //处理团组名称
- var groupNames = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => groupIds.Contains(x.Id)).Select(x => new { Id = x.Id, GroupName = x.TeamName }).ToListAsync();
- data.ForEach(x =>
- {
- string cityName = "";
- if (!string.IsNullOrEmpty(x.FlightsCity))
- {
- string cityCode = x.FlightsCity.Replace("-", "").Replace("/", "");
- int cityNum = cityCode.Length / 3;
- if (cityCode.Length % 3 == 0)
- {
- for (int i = 0; i < cityNum; i++)
- {
- string code = "";
- if (i == 0) code = cityCode.Substring(0, 3);
- else code = cityCode.Substring(i * 3, 3);
- if (!string.IsNullOrEmpty(code))
- {
- if (i == cityNum - 1)
- {
- cityName += threeCodeData.Find(x1 => x1.Three.Equals(code))?.City ?? "";
- }
- else
- {
- var str1 = threeCodeData.Find(x1 => x1.Three.Equals(code))?.City ?? "";
- cityName += str1 + "、";
- }
- }
- }
- }
- }
- x.FlightsCityName = cityName;
- });
- var airTicketNumData = new List<AirTicketReturnView>();
- var airTicketAreaData = new List<AirTicketCityReturnView>();
- int monthIndex = 1;
- while (monthIndex < 13)
- {
- var monthData = data.Where(x => x.Month == monthIndex).ToList();
- //机票票数处理
- int airticket_quantity = monthData.Sum(x => x.ClientNum);
- var linkGroupIds = monthData.Select(x => x.DIId).ToList();
- List<AitTicketInfo> aitTicketInfos = new List<AitTicketInfo>();
- foreach (var item in monthData)
- {
- string groupName = groupNames.Find(x => item.DIId == x.Id)?.GroupName ?? "";
- aitTicketInfos.Add(new AitTicketInfo(item.DIId, groupName, item.ClientNum));
- }
- var aitTicketInfosGroupBy = aitTicketInfos.GroupBy(x => x.Id);
- List<AitTicketInfo> aitTicketInfos1 = new List<AitTicketInfo>();
- foreach (var item in aitTicketInfosGroupBy)
- {
- aitTicketInfos1.Add(new AitTicketInfo(item.Key, item.First().GroupName, item.Sum(x => x.Quantity)));
- }
- aitTicketInfos1 = aitTicketInfos1.OrderBy(x => x.Quantity).ToList();
- linkGroupIds = linkGroupIds.Distinct().ToList();
- airTicketNumData.Add(new AirTicketReturnView(_dto.Year, monthIndex, airticket_quantity, aitTicketInfos1, linkGroupIds));
- //机票城市处理
- //城市处理
- var airTicketCityInfos = new List<string>();
- foreach (var item in monthData)
- {
- if (!string.IsNullOrEmpty(item.FlightsCityName))
- {
- if (item.FlightsCityName.Contains("、"))
- {
- var cityArray = item.FlightsCityName.Split("、").ToList();
- foreach (var item1 in cityArray)
- {
- if (!string.IsNullOrEmpty(item1))
- {
- airTicketCityInfos.Add(item1);
- }
- }
- }
- else
- {
- airTicketCityInfos.Add(item.FlightsCityName);
- }
- }
- }
- //int quantity1 = airTicketCityInfos.Count;
- int city_totalquantity = 0;
- var airTicketCityInfosGroupby = airTicketCityInfos.GroupBy(x => x);
- var airTicketCityInfos1 = new List<AirTicketCityInfo>();
- foreach (var item in airTicketCityInfosGroupby)
- {
- var city_quantity = item.ToList().Count;
- city_totalquantity += city_quantity;
- airTicketCityInfos1.Add(new AirTicketCityInfo(item.Key, city_quantity));
- }
- airTicketCityInfos1 = airTicketCityInfos1.OrderByDescending(x => x.Quantity).ToList();
- airTicketAreaData.Add(new AirTicketCityReturnView(_dto.Year, monthIndex, city_totalquantity, airTicketCityInfos1, linkGroupIds));
- monthIndex++;
- }
- var airTicketPlatformData = data.GroupBy(g => g.Platform)
- .Select(g => new
- {
- platform = g.Key,
- total = g.Sum(x => x.ClientNum),
- children = g.GroupBy(g1 => g1.DIId)
- .Select(g1 => new
- {
- diId = g1.Key,
- groupName = g1.FirstOrDefault()?.GroupName ?? "-",
- total = g1.Sum(x1 => x1.ClientNum),
- children = g1.Select(x1 => new
- {
- //diId = x1.DIId,
- //groupName = x1.GroupName,
- flightsCityName = x1.FlightsCityName,
- total = x1.ClientNum
- })
- .ToList()
- })
- .OrderByDescending(x1 => x1.total)
- .ToList()
- })
- .OrderByDescending(x => x.total)
- .ToList();
- return Ok(JsonView(true, "操作成功!", new
- {
- airTicketNumData = airTicketNumData,
- airTicketAreaData = airTicketAreaData,
- airTicketPlatformData = airTicketPlatformData
- }));
- }
- /// <summary>
- /// 国交数据统计-酒店
- /// 国家TOP10、地区TOP10、预订平台
- /// </summary>
- /// <param name="_dto"></param>
- /// <returns></returns>
- [HttpPost("StatisticsHotel")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> StatisticsHotel(YOYDto _dto)
- {
- if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
- string beginDt = $"{_dto.Year}-01-01 00:00:00",
- endDt = $"{_dto.Year}-12-31 23:59:59";
- string sql = string.Format(@"
- SELECT
- hr.DIId,
- CASE
- WHEN ntf.Country IS NULL THEN '未选择'
- ELSE ntf.Country
- END AS 'Country',
- hr.City,
- hr.HotelName,
- sd.Name AS BookinSite,
- hr.CheckInDate,
- YEAR(hr.CheckInDate) AS YEAR,
- MONTH(hr.CheckInDate) AS MONTH,
- hr.CheckOutDate,
- hr.SingleRoomCount,
- hr.DoubleRoomCount,
- hr.SuiteRoomCount,
- hr.OtherRoomCount
- FROM
- Grp_HotelReservations hr
- INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
- AND ccp.IsDel = 0
- AND CTable = 76
- INNER JOIN Grp_DelegationInfo di ON hr.DiId = di.Id
- LEFT JOIN Sys_SetData sd ON hr.ReservationsWebsite = sd.Id
- LEFT JOIN Grp_NationalTravelFee ntf ON hr.AreaId = ntf.Id
- WHERE
- hr.IsDel = 0
- AND di.TeamDid IN (38,39,40,1048)
- AND ccp.IsPay = 1
- AND (
- hr.SingleRoomCount > 0
- OR hr.DoubleRoomCount > 0
- OR hr.SuiteRoomCount > 0
- OR hr.OtherRoomCount > 0
- )
- AND CHARINDEX('早餐',hr.HotelName) = 0
- AND CHARINDEX('晚餐',hr.HotelName) = 0
- AND CHARINDEX('升级',hr.HotelName) = 0
- AND CHARINDEX('饮料茶水费',hr.HotelName) = 0
- AND CHARINDEX('城市税',hr.HotelName) = 0
- AND CHARINDEX('退款',hr.HotelName) = 0
- AND CHARINDEX('返现',hr.HotelName) = 0
- AND CHARINDEX('会议室',hr.HotelName) = 0
- AND CHARINDEX('迷你吧消费',hr.HotelName) = 0
- AND CHARINDEX('运费',hr.HotelName) = 0
- AND CHARINDEX('地接',hr.HotelName) = 0
- AND CHARINDEX('损失',hr.HotelName) = 0
- AND CHARINDEX('补差',hr.HotelName) = 0
- AND hr.CheckInDate BETWEEN CONVERT(datetime,'{0}') AND CONVERT(datetime,'{1}')
- ORDER BY
- hr.CheckInDate
- ", beginDt, endDt);
- var data = await _sqlSugar.SqlQueryable<StatisticsHotelView>(sql).ToListAsync();
- var hotelCountryGroupByData = data.GroupBy(x => x.Country)
- .Select(g => new
- {
- Country = g.Key,
- BookingRoomNum = g.Sum(x => x.RoomTotal),
- hotelData = g.GroupBy(x => x.HotelName)
- .Select(g1 => new
- {
- hotelName = g1.Key,
- roomNights = g1.Sum(x => x.RoomNights),
- roomTotal = g1.Sum(x => x.RoomTotal),
- singleRoomCount = g1.Sum(x => x.SingleRoomCount),
- doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
- suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
- otherRoomCount = g1.Sum(x => x.OtherRoomCount),
- })
- .ToList(),
- linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
- })
- .OrderByDescending(x => x.BookingRoomNum)
- .Take(10)
- .ToList();
- var hotelData = data.OrderBy(x => x.CityStr).ToList();
- var hotelCityGroupByData = data.GroupBy(x => x.CityStr)
- .Select(g => new
- {
- city = g.Key,
- BookingRoomNum = g.Sum(x => x.RoomTotal),
- hotelData = g.GroupBy(x => x.HotelName)
- .Select(g1 => new
- {
- hotelName = g1.Key,
- roomNights = g1.Sum(x => x.RoomNights),
- roomTotal = g1.Sum(x => x.RoomTotal),
- singleRoomCount = g1.Sum(x => x.SingleRoomCount),
- doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
- suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
- otherRoomCount = g1.Sum(x => x.OtherRoomCount),
- })
- .ToList(),
- linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
- })
- .OrderByDescending(x => x.BookingRoomNum)
- .Take(10)
- .ToList();
- var hotelPlatformGroupByData = data.GroupBy(x => x.BookinSite)
- .Select(g => new
- {
- Platform = g.Key,
- BookingRoomNum = g.Sum(x => x.RoomTotal),
- hotelData = g.GroupBy(x => x.HotelName)
- .Select(g1 => new
- {
- hotelName = g1.Key,
- roomNights = g1.Sum(x => x.RoomNights),
- roomTotal = g1.Sum(x => x.RoomTotal),
- singleRoomCount = g1.Sum(x => x.SingleRoomCount),
- doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
- suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
- otherRoomCount = g1.Sum(x => x.OtherRoomCount),
- })
- .ToList(),
- linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
- })
- .OrderByDescending(x => x.BookingRoomNum)
- .ToList();
- return Ok(JsonView(true, "操作成功!", new { hotelCountryGroupByData = hotelCountryGroupByData, hotelCityData = hotelCityGroupByData, hotelPlatformData = hotelPlatformGroupByData }));
- }
- /// <summary>
- /// 国交数据统计
- /// 商邀邀请国家数量TOP10
- /// </summary>
- /// <param name="_dto"></param>
- /// <returns></returns>
- [HttpPost("StatisticsInvitation")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> StatisticsInvitation(YOYDto _dto)
- {
- if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
- string beginDt = $"{_dto.Year}-01-01 00:00:00",
- endDt = $"{_dto.Year}-12-31 23:59:59";
- string sql = string.Format(@"
- SELECT
- oa.DiId,
- di.TeamName AS GroupName,
- oa.Country,
- oa.Area AS City,
- oa.Client,
- oa.Date
- FROM
- Res_OfficialActivities oa
- LEFT JOIN Grp_DelegationInfo di ON oa.DiId = di.Id
- WHERE
- oa.IsDel = 0
- AND oa.Date BETWEEN '{0}' AND '{1}'
- ", beginDt, endDt);
- var data = await _sqlSugar.SqlQueryable<StatisticsInvitation_HW>(sql).ToListAsync();
- var groupByCountry = data.GroupBy(x => x.Country)
- .Select(g => new
- {
- Country = g.Key,
- TimeNum = g.Count(),
- LinkGroupIds = g.Select(x => x.GroupName).Distinct().ToList()
- })
- .OrderByDescending(x => x.TimeNum)
- .Take(10)
- .ToList();
- var groupByClient = data.GroupBy(x => x.Client)
- .Select(g => new
- {
- Country = g.Key,
- TimeNum = g.Count(),
- LinkGroupIds = g.Select(x => x.GroupName).Distinct().ToList()
- })
- .OrderByDescending(x => x.TimeNum)
- .Take(10)
- .ToList();
- return Ok(JsonView(true, "操作成功!", new { groupByCountry = groupByCountry, groupByClient = groupByClient }));
- }
- /// <summary>
- /// 会务数据统计
- /// 会务城市TOP10排序
- /// </summary>
- /// <param name="_dto"></param>
- /// <returns></returns>
- [HttpPost("StatisticsConferenceCity")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> StatisticsConferenceCity(YOYDto _dto)
- {
- if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
- string beginDt = $"{_dto.Year}-01-01 00:00:00",
- endDt = $"{_dto.Year}-12-31 23:59:59";
- string sql = string.Format(@"
- SELECT
- ioa.DiId,
- ioa.InviterArea AS Country
- FROM
- Grp_InvitationOfficialActivities ioa
- INNER JOIN Grp_CreditCardPayment ccp ON ioa.Id = ccp.CId
- AND ccp.IsDel = 0
- AND ccp.CTable = 81
- INNER JOIN Grp_DelegationInfo di ON ioa.DiId = di.Id
- WHERE
- ioa.IsDel = 0
- AND di.TeamDid IN (102,248,302,691,762,1047)
- AND ccp.IsPay = 1
- AND ioa.CreateTime BETWEEN '{0}' AND '{1}'
- ", beginDt, endDt);
- var data = await _sqlSugar.SqlQueryable<StatisticsInvitation>(sql).ToListAsync();
- var groupByData = data.GroupBy(x => x.Country)
- .Select(g => new
- {
- Country = g.Key,
- TimeNum = g.Count(),
- LinkGroupIds = g.Select(x => x.DIId).ToList()
- })
- .OrderByDescending(x => x.TimeNum)
- .Take(10)
- .ToList();
- return Ok(JsonView(true, "操作成功!", groupByData));
- }
- /// <summary>
- /// 团组数据统计
- /// 团组合作前十的客户TOP10排序
- /// </summary>
- /// <param name="_dto"></param>
- /// <returns></returns>
- [HttpPost("StatisticsCooperativeCustomer")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> StatisticsCooperativeCustomer(YOYDto _dto)
- {
- if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
- string beginDt = $"{_dto.Year}-01-01 00:00:00",
- endDt = $"{_dto.Year}-12-31 23:59:59";
- DateTime _beginDt = Convert.ToDateTime(beginDt),
- _endDt = Convert.ToDateTime(endDt);
- var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
- .Where(x => x.IsDel == 0)
- //.Where(x => x.IsSure == 1)
- .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
- .ToListAsync();
- var groupInfos1 = groupInfos.GroupBy(x => x.ClientName);
- var view = groupInfos1.Select(x =>
- new
- {
- clienName = x.Key,
- clientUnit = x.FirstOrDefault()?.ClientUnit ?? "",
- visitsNum = x.Count()
- }
- )
- .OrderByDescending(x => x.visitsNum)
- .Take(10)
- .ToList();
- return Ok(JsonView(true, "操作成功!", view));
- }
- /// <summary>
- /// 团组数据统计
- /// 已出团客户单位的类型比例图(饼状图-政府团、企业团等)
- /// </summary>
- /// <param name="_dto"></param>
- /// <returns></returns>
- [HttpPost("StatisticsCooperativeCustomerType")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> StatisticsCooperativeCustomerType(YOYDto _dto)
- {
- if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
- string beginDt = $"{_dto.Year}-01-01 00:00:00",
- endDt = $"{_dto.Year}-12-31 23:59:59";
- DateTime _beginDt = Convert.ToDateTime(beginDt),
- _endDt = Convert.ToDateTime(endDt);
- var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
- .LeftJoin<Sys_SetData>((di, sd) => di.TeamDid == sd.Id)
- .Where((di, sd) => di.IsDel == 0)
- .Where((di, sd) => di.VisitDate >= _beginDt && di.VisitDate <= _endDt)
- .Select((di, sd) => new
- {
- Id = di.Id,
- GroupTypeId = di.TeamDid,
- GroupTypeName = sd.Name,
- })
- .ToListAsync();
- var groupInfos1 = groupInfos.GroupBy(x => x.GroupTypeName);
- var view = groupInfos1.Select(x =>
- new
- {
- groupTypeName = x.Key,
- groupNum = x.Count(),
- linkGroupId = x.Select(x1 => x1.Id).ToList()
- }
- )
- .OrderByDescending(x => x.groupNum)
- .ToList();
- return Ok(JsonView(true, "操作成功!", view));
- }
- /// <summary>
- /// 团组数据统计
- /// 团组数量
- /// </summary>
- /// <param name="_dto"></param>
- /// <returns></returns>
- [HttpPost("StatisticsGroupNum")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> StatisticsGroupNum(YOYDto _dto)
- {
- if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
- string beginDt = $"{_dto.Year}-01-01 00:00:00",
- endDt = $"{_dto.Year}-12-31 23:59:59";
- DateTime _beginDt = Convert.ToDateTime(beginDt),
- _endDt = Convert.ToDateTime(endDt);
- var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
- .Where(x => x.IsDel == 0)
- .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
- .Select(x => new StatisticsGroupInfoEntity
- {
- Id = x.Id,
- VisitDate = x.VisitDate,
- Month = x.VisitDate.Month,
- //MonthName = x.VisitDate.ToString("MMM", CultureInfo.GetCultureInfo("zh-CN")),
- VisitPNumber = x.VisitPNumber
- })
- .MergeTable()
- .OrderBy(x => new { x.Month })
- .ToListAsync();
- string groupNumStr = $"年度出访量:{groupInfos.Count}\r\n";
- var groupNumYearData = new
- {
- year = _dto.Year,
- yearName = _dto.Year + "年",
- num = groupInfos.Count,
- linkGroupIds = groupInfos.Select(x => x.Id).ToList()
- };
- var groupNumData = groupInfos.GroupBy(x => x.Quarter)
- .Select(x => new
- {
- Quarter = x.Key,
- QuarterName = x.FirstOrDefault()?.QuarterName ?? "-",
- Num = x.Count(),
- LinkGroupIds = x.Select(x1 => x1.Id).ToList()
- })
- .OrderBy(x => x.Quarter)
- .ToList();
- groupNumData.ForEach(x =>
- {
- groupNumStr += $"{x.QuarterName}出访量:{x.Num};";
- });
- var groupNumMonthData = groupInfos.GroupBy(x => x.Month)
- .Select(x => new
- {
- Month = x.Key,
- MonthName = x.FirstOrDefault()?.MonthName ?? "-",
- Num = x.Count(),
- LinkGroupIds = x.Select(x1 => x1.Id).ToList()
- })
- .OrderBy(x => x.Month)
- .ToList();
- return Ok(JsonView(true, "操作成功!", new
- {
- yearData = groupNumYearData,
- quarterData = groupNumData,
- monthData = groupNumMonthData,
- remark = groupNumStr
- }));
- }
- /// <summary>
- /// 团组数据统计
- /// 团组人数
- /// </summary>
- /// <param name="_dto"></param>
- /// <returns></returns>
- [HttpPost("StatisticsGroupPeopleNum")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> StatisticsGroupPeopleNum(YOYDto _dto)
- {
- if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
- string beginDt = $"{_dto.Year}-01-01 00:00:00",
- endDt = $"{_dto.Year}-12-31 23:59:59";
- DateTime _beginDt = Convert.ToDateTime(beginDt),
- _endDt = Convert.ToDateTime(endDt);
- var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
- .Where(x => x.IsDel == 0)
- .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
- .Select(x => new StatisticsGroupInfoEntity
- {
- Id = x.Id,
- VisitDate = x.VisitDate,
- Month = x.VisitDate.Month,
- VisitPNumber = x.VisitPNumber
- })
- .MergeTable()
- .OrderBy(x => new { x.Month })
- .ToListAsync();
- string groupPeopleNumStr = $"年度出访人数:{groupInfos.Sum(x => x.VisitPNumber)}\r\n";
- var groupPeopleNumYearData = new
- {
- year = _dto.Year,
- yearName = _dto.Year + "年",
- num = groupInfos.Sum(x => x.VisitPNumber),
- linkGroupIds = groupInfos.Select(x => x.Id).ToList()
- };
- var groupPeopleNumData = groupInfos.GroupBy(x => x.Quarter)
- .Select(x => new
- {
- Quarter = x.Key,
- QuarterName = x.FirstOrDefault()?.QuarterName ?? "-",
- Num = x.Sum(x1 => x1.VisitPNumber),
- LinkGroupIds = x.Select(x1 => x1.Id).ToList()
- })
- .OrderBy(x => x.Quarter)
- .ToList();
- groupPeopleNumData.ForEach(x =>
- {
- groupPeopleNumStr += $"{x.QuarterName}出访人数:{x.Num};";
- });
- var groupPeopleNumMonthData = groupInfos.GroupBy(x => x.Month)
- .Select(x => new
- {
- Month = x.Key,
- MonthName = x.FirstOrDefault()?.MonthName ?? "-",
- Num = x.Sum(x1 => x1.VisitPNumber),
- LinkGroupIds = x.Select(x1 => x1.Id).ToList()
- })
- .OrderBy(x => x.Month)
- .ToList();
- return Ok(JsonView(true, "操作成功!", new
- {
- yearData = groupPeopleNumYearData,
- quarterData = groupPeopleNumData,
- monthData = groupPeopleNumMonthData,
- remark = groupPeopleNumStr
- }));
- }
- /// <summary>
- /// 团组数据统计
- /// OP 成本
- /// </summary>
- /// <param name="_dto"></param>
- /// <returns></returns>
- [HttpPost("StatisticsOP")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> StatisticsOP(StatisticsOPDto _dto)
- {
- if (_dto.Year < 1) return Ok(JsonView(false, "Year参数错误!"));
- if (_dto.Type < 1 || _dto.Type > 2) return Ok(JsonView(false, "Type参数错误!"));
- int thisYear = _dto.Year, lastYear = _dto.Year - 1;
- string beginDt = $"{lastYear}-01-01 00:00:00",
- endDt = $"{thisYear}-12-31 23:59:59";
- string sql = string.Format(@"
- SELECT
- temp.Id,
- DiId,
- PaymentTime,
- [Year],
- [Quarter],
- [Month],
- Area,
- FeeType,
- sd1.Name AS FeeTypeName,
- FeeSubType,
- sd2.Name AS FeeSubTypeName,
- CONVERT(DECIMAL(12, 2), Price * Qauntity * ExchangeRate) AS Price
- FROM
- (
- SELECT
- ctggr.Id,
- ctggr.DiId,
- ctggr.Area,
- CASE
- WHEN ctggr.PriceType IS NULL THEN 1069
- ELSE ctggr.PriceType
- END AS FeeType,
- ctggrc.SId AS FeeSubType,
- ctggrc.Price,
- CASE
- WHEN ctggrc.Count IS NULL THEN 1
- ELSE ctggrc.Count
- END AS Qauntity,
- ccp.DayRate AS ExchangeRate,
- ctggrc.CreateTime AS PaymentTime,
- YEAR(ctggrc.CreateTime) AS [Year],
- CONVERT(INT,DATENAME(QUARTER, ctggrc.CreateTime)) AS [Quarter],
- MONTH(ctggrc.CreateTime) AS [Month]
- FROM
- Grp_CarTouristGuideGroundReservations ctggr
- INNER JOIN Grp_CarTouristGuideGroundReservationsContent ctggrc ON ctggr.Id = ctggrc.CTGGRId
- AND ctggrc.IsDel = 0
- INNER JOIN Grp_CreditCardPayment ccp ON ctggr.Id = ccp.CId
- AND ccp.CTable = 79
- AND ccp.IsDel = 0
- WHERE
- ctggr.IsDel = 0
- AND ctggrc.SId != 1070 --费用子项筛掉尾款
- AND ctggrc.Price > 0 --筛选真实存在的数据
- AND ccp.IsPay = 1
- ) temp
- LEFT JOIN Sys_SetData sd1 ON FeeType = sd1.Id
- LEFT JOIN Sys_SetData sd2 ON FeeSubType = sd2.Id
- WHERE
- temp.Area NOT LIKE '%尾款%' -- 筛选掉尾款相关信息
- AND temp.FeeType != 1062 --费用类型筛选掉全款和首付款数据
- AND temp.PaymentTime BETWEEN CONVERT(datetime,'{0}') AND CONVERT(datetime,'{1}')
- ORDER BY
- temp.[Year],
- temp.[Quarter],
- temp.[Month]
- ", beginDt, endDt);
- var opInfos = await _sqlSugar.SqlQueryable<StatisticsOP>(sql).ToListAsync();
- //处理地区相关信息
- var countrys = await _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(x => x.IsDel == 0).ToListAsync();
- for (int i = 0; i < opInfos.Count; i++)
- {
- string country = string.Empty, city = string.Empty;
- int dataId = 0;
- bool isCountryId = int.TryParse(opInfos[i].Area, out dataId);
- string[] citySelecter = new string[] { "其他城市", "所有城市" };
- if (isCountryId)
- {
- var countryInfo = countrys.Find(x => x.Id == dataId);
- country = countryInfo?.Country ?? "";
- if (citySelecter.Contains(countryInfo?.City)) city = country;
- else city = countryInfo?.City ?? "";
- }
- else
- {
- var countryInfo1 = countrys.Find(x => opInfos[i].Area.Contains(x.Country));
- if (countryInfo1 != null)
- {
- country = countryInfo1?.Country ?? "";
- city = countryInfo1?.City ?? country;
- var countryInfo2 = countrys.Find(x => opInfos[i].Area.Contains(x.City));
- if (citySelecter.Contains(countryInfo2?.City)) city = country;
- else city = countryInfo2?.City ?? country;
- }
- else
- {
- var countryInfo2 = countrys.Find(x => opInfos[i].Area.Contains(x.City));
- if (countryInfo2 != null)
- {
- country = countryInfo2?.Country ?? "";
- city = countryInfo2?.City ?? "";
- if (citySelecter.Contains(countryInfo2?.City)) city = country;
- }
- }
- }
- opInfos[i].Country = country;
- opInfos[i].City = city;
- }
- var opParentFeeData = new StatisticsOP()._OPParentFeeInfo;
- if (_dto.Type == 1)
- {
- //同比增长率=(本期数-同期数)/ 同期数
- var yearData = opInfos.GroupBy(x => x.ParentFeeName)
- .Select(x => new StatisticsOPYOY(
- feeId: x.FirstOrDefault()?.ParentFeeId ?? 0,
- feeName: x.Key,
- currPeriodFee: x.Where(x => x.Year == thisYear).Sum(x => x.Price),
- samePeriodFee: x.Where(x => x.Year == lastYear).Sum(x => x.Price),
- currPeriodGroupTotal: x.Where(x => x.Year == thisYear).Select(x => x.DiId).Distinct().Count(),
- samePeriodGroupTotal: x.Where(x => x.Year == lastYear).Select(x => x.DiId).Distinct().Count(),
- subFeeData: x.GroupBy(x1 => x1.FeeSubType)
- .Select(x1 => new StatisticsOPSubFeeYOY(
- feeId: x1.Key,
- feeName: x1.FirstOrDefault()?.FeeSubTypeName ?? "",
- currPeriodFee: x1.Where(x1 => x1.Year == thisYear).Sum(x1 => x1.Price),
- samePeriodFee: x1.Where(x1 => x1.Year == lastYear).Sum(x1 => x1.Price),
- currPeriodGroupTotal: x1.Where(x1 => x1.Year == thisYear).Select(x1 => x1.DiId).Distinct().Count(),
- samePeriodGroupTotal: x1.Where(x1 => x1.Year == lastYear).Select(x1 => x1.DiId).Distinct().Count(),
- cityData: x1.GroupBy(x2 => x2.City)
- .Select(x2 => new StatisticsOPCityYOY(
- cityName: x2.Key,
- currPeriodGroupTotal: x2.Where(x2 => x2.Year == thisYear).Select(x2 => x2.DiId).Distinct().Count(),
- samePeriodGroupTotal: x2.Where(x2 => x2.Year == lastYear).Select(x2 => x2.DiId).Distinct().Count(),
- currPeriodFee: x2.Where(x2 => x2.Year == thisYear).Sum(x2 => x2.Price),
- samePeriodFee: x2.Where(x2 => x2.Year == lastYear).Sum(x2 => x2.Price)
- ))
- .ToArray()
- ))
- .ToArray()
- ))
- .OrderBy(x => x.FeeId)
- .ToList();
- var opParentYearIds = yearData.Select(x => x.FeeId).ToList();
- var opParentYearDataSelector = opParentFeeData.Where(x => !opParentYearIds.Contains(x.Id)).ToList();
- if (opParentYearDataSelector.Count > 0)
- {
- foreach (var item in opParentYearDataSelector)
- {
- yearData.Add(
- new StatisticsOPYOY(feeId: item.Id,
- feeName: item.Name,
- currPeriodFee: 0.00M,
- samePeriodFee: 0.00M,
- currPeriodGroupTotal: 0,
- samePeriodGroupTotal: 0,
- subFeeData: new StatisticsOPSubFeeYOY[] { }
- ));
- }
- yearData = yearData.OrderBy(x => x.FeeId).ToList();
- }
- return Ok(JsonView(true, "操作成功!", yearData));
- }
- else if (_dto.Type == 2)
- {
- var monthData = opInfos.GroupBy(x => x.Month)
- .Select(x => new StatisticsOPMonthYOY(
- monthId: x.Key,
- monthName: System.Enum.IsDefined(typeof(MonthEnum), (int)x.Key) ? ((MonthEnum)(int)x.Key).GetEnumDescription() : "",
- feeDatas: x.GroupBy(x1 => x1.ParentFeeId)
- .Select(x1 => new StatisticsOPYOY(
- feeId: x1.Key,
- feeName: x1.FirstOrDefault()?.ParentFeeName ?? "",
- currPeriodFee: x1.Where(x1 => x1.Year == thisYear).Sum(x1 => x1.Price),
- samePeriodFee: x1.Where(x1 => x1.Year == lastYear).Sum(x1 => x1.Price),
- currPeriodGroupTotal: x1.Where(x1 => x1.Year == thisYear).Select(x1 => x1.DiId).Distinct().Count(),
- samePeriodGroupTotal: x1.Where(x1 => x1.Year == lastYear).Select(x1 => x1.DiId).Distinct().Count(),
- subFeeData: x1.GroupBy(x2 => x2.FeeSubType)
- .Select(x2 => new StatisticsOPSubFeeYOY(
- feeId: x2.Key,
- feeName: x2.FirstOrDefault()?.FeeSubTypeName ?? "",
- currPeriodFee: x2.Where(x2 => x2.Year == thisYear).Sum(x2 => x2.Price),
- samePeriodFee: x2.Where(x2 => x2.Year == lastYear).Sum(x2 => x2.Price),
- currPeriodGroupTotal: x2.Where(x2 => x2.Year == thisYear).Select(x2 => x2.DiId).Distinct().Count(),
- samePeriodGroupTotal: x2.Where(x2 => x2.Year == lastYear).Select(x2 => x2.DiId).Distinct().Count(),
- cityData: x2.GroupBy(x3 => x3.City)
- .Select(x3 => new StatisticsOPCityYOY(
- cityName: x3.Key,
- currPeriodFee: x3.Where(x3 => x3.Year == thisYear).Sum(x3 => x3.Price),
- samePeriodFee: x3.Where(x3 => x3.Year == lastYear).Sum(x3 => x3.Price),
- currPeriodGroupTotal: x3.Where(x3 => x3.Year == thisYear).Select(x3 => x3.DiId).Distinct().Count(),
- samePeriodGroupTotal: x3.Where(x3 => x3.Year == lastYear).Select(x3 => x3.DiId).Distinct().Count()
- ))
- .ToArray()
- ))
- .ToArray()
- ))
- .ToArray()
- ))
- //.OrderBy(x => x.MonthId)
- .ToList();
- //1、月份是否足够十二月
- var monthIds = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
- var monthDataIds = monthData.Select(x => x.MonthId).ToArray();
- var newMonthIds = monthIds.Where(x => !monthDataIds.Contains(x)).ToList();
- if (newMonthIds.Count > 0)
- {
- foreach (var item in newMonthIds)
- {
- monthData.Add(new StatisticsOPMonthYOY(
- monthId: item,
- monthName: System.Enum.IsDefined(typeof(MonthEnum), (int)item) ? ((MonthEnum)(int)item).GetEnumDescription() : "",
- feeDatas: System.Array.Empty<StatisticsOPYOY>()
- ));
- }
- monthData = monthData.OrderBy(x => x.MonthId).ToList();
- }
- //2、费用父类是否足够
- for (int i = 0; i < monthData.Count; i++)
- {
- var month = monthData[i];
- var opParentFeeIds = month.FeeDatas.Select(x => x.FeeId).ToList();
- var opParentFeeDataSelector = opParentFeeData.Where(x => !opParentFeeIds.Contains(x.Id)).ToList();
- if (opParentFeeDataSelector.Count > 0)
- {
- var feeDatas = month.FeeDatas.ToList();
- foreach (var item in opParentFeeDataSelector)
- {
- feeDatas.Add(new StatisticsOPYOY(
- feeId: item.Id,
- feeName: item.Name,
- currPeriodFee: 0.00M,
- samePeriodFee: 0.00M,
- currPeriodGroupTotal: 0,
- samePeriodGroupTotal: 0,
- subFeeData: System.Array.Empty<StatisticsOPSubFeeYOY>()
- ));
- }
- feeDatas = feeDatas.OrderBy(x => x.FeeId).ToList();
- monthData[i].FeeDatas = feeDatas.ToArray();
- }
- }
- //3、费用子类是否足够
- return Ok(JsonView(true, "操作成功!", monthData));
- }
- return Ok(JsonView(false, "操作失败!"));
- }
- /// <summary>
- /// 团组数据统计
- /// 团组预算/实际成本
- /// </summary>
- /// <param name="_dto"></param>
- /// <returns></returns>
- [HttpPost("StatisticsGroupCost")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> StatisticsBRCost(StatisticsBRCostDto _dto)
- {
- if (_dto.Year < 1) return Ok(JsonView(false, "Year参数错误!"));
- string beginDt = $"{_dto.Year}-01-01 00:00:00",
- endDt = $"{_dto.Year}-12-31 23:59:59";
- var sql = string.Format(@"
- SELECT
- ROW_NUMBER() OVER(
- ORDER BY
- di.VisitDate DESC
- ) AS 'RowNumber',
- di.Id,
- di.TeamName AS 'GroupName',
- di.ClientUnit,
- di.VisitDate,
- di.VisitDays,
- di.VisitPNumber,
- (
- SELECT
- TOP 1 CASE
- ISNUMERIC (gcp.Currency)
- WHEN 1 THEN (
- SELECT
- Name
- FROM
- Sys_SetData sd
- WHERE
- CAST(gcp.Currency AS INT) = sd.Id
- )
- ELSE gcp.Currency
- END AS 'CurrencyCode'
- FROM
- Grp_GroupCostParameter gcp
- WHERE
- gcp.IsDel = 0
- AND gcp.DiId = di.Id
- ) Budget_CurrencyCode,
- --预算币种
- (
- SELECT
- TOP 1 CAST(COALESCE(gcp.Rate, 0.0000) AS DECIMAL(12, 4))
- FROM
- Grp_GroupCostParameter gcp
- WHERE
- gcp.IsDel = 0
- AND gcp.DiId = di.Id
- ) Budget_Rate,
- --预算汇率
- (
- SELECT
- CAST(
- SUM(COALESCE(gcp.VisaCB, 0) * COALESCE(gcp.VisaRS, 0)) AS DECIMAL(12, 2)
- )
- FROM
- Grp_GroupCostParameter gcp
- WHERE
- gcp.IsDel = 0
- AND gcp.DiId = di.id
- ) Budget_VisaAmount,
- -- 预算签证成本
- (
- SELECT
- CAST(
- SUM(
- (
- (ccp.PayMoney * ccp.DayRate)
- )
- ) AS DECIMAL(12, 2)
- )
- FROM
- Grp_VisaInfo vi
- INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
- AND ccp.CTable = 80
- AND vi.Id = ccp.CId
- WHERE
- vi.IsDel = 0
- AND ccp.IsAuditGM = 1
- AND ccp.IsPay = 1
- AND di.Id = vi.DIId
- ) AS Reality_VisaAmount,
- -- 实际签证成本
- (
- SELECT
- CAST(
- SUM(
- COALESCE(gcp.JJCCB, 0) * COALESCE(gcp.JJCRS, 0) + COALESCE(gcp.GWCCB, 0) * COALESCE(gcp.GWCRS, 0) + COALESCE(gcp.TDCCB, 0) * COALESCE(gcp.TDCRS, 0)
- ) AS DECIMAL(12, 2)
- )
- FROM
- Grp_GroupCostParameter gcp
- WHERE
- gcp.IsDel = 0
- AND gcp.DiId = di.id
- ) Budget_AirTicketAmount,
- -- 预算机票成本
- (
- SELECT
- CAST(
- SUM(
- (
- (ccp.PayMoney * ccp.DayRate)
- )
- ) AS DECIMAL(12, 2)
- )
- FROM
- Grp_AirTicketReservations atr
- INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
- AND ccp.CTable = 85
- AND atr.Id = ccp.CId
- WHERE
- atr.IsDel = 0
- AND ccp.IsAuditGM = 1
- AND ccp.IsPay = 1
- AND di.Id = atr.DiId
- ) Reality_AirTicketAmount,
- --实际机票
- (
- SELECT
- CAST(
- SUM(
- 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)
- ) AS DECIMAL(12, 2)
- )
- FROM
- Grp_GroupCostParameter gcp
- WHERE
- gcp.IsDel = 0
- AND gcp.DiId = di.id
- ) Budget_HotelAmount,
- -- 预算酒店成本
- (
- SELECT
- CAST(
- SUM(
- (ccp.PayMoney * ccp.DayRate)
- ) AS DECIMAL(12, 2)
- )
- FROM
- Grp_HotelReservations hr
- INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
- WHERE
- hr.IsDel = 0
- AND ccp.IsDel = 0
- AND ccp.CTable = 76
- AND ccp.IsAuditGM = 1
- AND ccp.PayMoney <> 0
- AND ccp.IsPay = 1
- AND di.Id = hr.DiId
- ) AS Reality_HotelAmount,
- -- 实际酒店成本
- (
- SELECT
- CAST(
- SUM(COALESCE(gcp.DJCB, 0) * COALESCE(gcp.DJRS, 0)) AS DECIMAL(12, 2)
- )
- FROM
- Grp_GroupCostParameter gcp
- WHERE
- gcp.IsDel = 0
- AND gcp.DiId = di.id
- ) Budget_OPAmount,
- -- 预算 OP
- (
- SELECT
- CAST(
- SUM(
- (
- ctggr.ServiceQuotedPrice * (ccp.PayPercentage / 100) * ccp.DayRate
- )
- ) AS DECIMAL(12, 2)
- )
- FROM
- Grp_CarTouristGuideGroundReservations ctggr
- INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
- AND ccp.CTable = 79
- AND ctggr.Id = ccp.CId
- WHERE
- ctggr.IsDel = 0
- AND ccp.IsAuditGM = 1
- AND ccp.IsPay = 1
- AND di.Id = ctggr.DiId
- ) AS Reality_OPAmount,
- -- 实际 OP
- (
- SELECT
- CAST(
- SUM(COALESCE(gcp.GWCB, 0) * COALESCE(gcp.GWRS, 0)) AS DECIMAL(12, 2)
- )
- FROM
- Grp_GroupCostParameter gcp
- WHERE
- gcp.IsDel = 0
- AND gcp.DiId = di.id
- ) Budget_OAAmount,
- -- 预算 商邀
- (
- SELECT
- CAST(
- SUM(
- (ccp.PayMoney * ccp.DayRate)
- ) AS DECIMAL(12, 2)
- )
- FROM
- Grp_InvitationOfficialActivities ioa
- INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
- AND ccp.CTable = 81
- AND ioa.Id = ccp.CId
- WHERE
- ioa.IsDel = 0
- AND ccp.IsAuditGM = 1
- AND ccp.IsPay = 1
- AND di.Id = ioa.Diid
- ) AS Reality_OAAmount,
- -- 实际 商邀
- (
- SELECT
- CAST(
- SUM(
- 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)
- ) AS DECIMAL(12, 2)
- )
- FROM
- Grp_GroupCostParameter gcp
- WHERE
- gcp.IsDel = 0
- AND gcp.DiId = di.id
- ) Budget_OtherAmount,
- -- 预算其他成本
- (
- SELECT
- CAST(
- SUM(
- (ccp.PayMoney * ccp.DayRate)
- ) AS DECIMAL(12, 2)
- )
- FROM
- Grp_Customers ic
- INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
- AND ccp.CTable = 82
- AND ic.Id = ccp.CId
- WHERE
- ic.IsDel = 0
- AND ccp.IsAuditGM = 1And ccp.IsPay = 1
- AND di.Id = ic.DiId
- ) AS Reality_InsureAmount,
- -- 实际保险成本
- (
- SELECT
- CAST(SUM((ccp.PayMoney * ccp.DayRate)) AS DECIMAL(12, 2))
- FROM
- Grp_DecreasePayments dp
- INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
- AND ccp.CTable = 98
- AND dp.Id = ccp.CId
- WHERE
- dp.IsDel = 0
- AND ccp.Ctable = 98
- AND ccp.IsAuditGM = 1
- AND ccp.IsPay = 1
- AND di.Id = dp.Diid
- ) AS Reality_OtherCostAmount -- 实际其他款项
- FROM
- Grp_DelegationInfo di
- WHERE
- di.IsDel = 0
- AND di.IsBid = 0
- --AND di.TeamDid IN (38, 39, 40, 1048)
- AND di.VisitDate BETWEEN '{0}' AND '{1}'
- ", beginDt, endDt);
- if (!string.IsNullOrEmpty(_dto.Search))
- {
- sql += $"AND di.TeamName Like '%{_dto.Search}%'";
- }
- var view = await _sqlSugar.SqlQueryable<StatisticsBRCostView>(sql).ToListAsync();
- view = view.Where(x => !x.GroupName.Contains("投标") && x.RealityAmount > 0).OrderByDescending(x => x.Id).ToList();
- var total = view.Count;
- var toSkip = (_dto.PageIndex - 1) * _dto.PageSize;
- var data = view.Skip(toSkip).Take(_dto.PageSize).ToList();
- if (data.Count > 0)
- {
- var diIds = data.Select(x => x.Id).ToList();
- var currencyData = await _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0 && x.STid == 66).ToListAsync();
- var ccpData = await _sqlSugar.Queryable<Grp_CreditCardPayment>()
- .Where(x => x.IsDel == 0 &&
- diIds.Contains(x.DIId) &&
- x.IsPay == 1 &&
- x.IsAuditGM == 1
- )
- .ToListAsync();
- for (int i = 0; i < data.Count; i++)
- {
- var info = data[i];
- info.RowNumber = i + 1;
- #region 1:签证 80
- var visaDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 80).ToList();
- var visaDesc = "-";
- if (visaDatas.Count > 0)
- {
- visaDesc = $"实际币种金额:";
- foreach (var visa in visaDatas)
- {
- var currencyCode = currencyData.Find(x => x.Id == visa.PaymentCurrency)?.Name;
- visaDesc += $"{visa.PayMoney} {currencyCode} 汇率:{visa.DayRate.ToString("#0.0000")};";
- }
- }
- info.Reality_VisaAmountDesc = visaDesc;
- #endregion
- #region 2:机票 85
- var airDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 85).ToList();
- var airDesc = "-";
- if (airDatas.Count > 0)
- {
- airDesc = $"实际币种金额:";
- foreach (var air in airDatas)
- {
- var currencyCode = currencyData.Find(x => x.Id == air.PaymentCurrency)?.Name;
- airDesc += $"{air.PayMoney} {currencyCode} 汇率:{air.DayRate.ToString("#0.0000")};";
- }
- }
- info.Reality_AirTicketAmountDesc = airDesc;
- #endregion
- #region 3:酒店 76
- var hotelDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 76 && x.PayMoney != 0).ToList();
- var hotelDesc = "-";
- if (hotelDatas.Count > 0)
- {
- hotelDesc = $"实际币种金额:";
- foreach (var hotel in hotelDatas)
- {
- var currencyCode = currencyData.Find(x => x.Id == hotel.PaymentCurrency)?.Name;
- hotelDesc += $"{hotel.PayMoney} {currencyCode} 汇率:{hotel.DayRate.ToString("#0.0000")};";
- }
- }
- info.Reality_HotelAmountDesc = hotelDesc;
- #endregion
- #region 4:OP 79
- var opDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 79 && x.PayMoney != 0).ToList();
- var opDesc = "-";
- if (opDatas.Count > 0)
- {
- opDesc = $"实际币种金额;";
- foreach (var op in opDatas)
- {
- var currencyCode = currencyData.Find(x => x.Id == op.PaymentCurrency)?.Name;
- opDesc += $"{op.PayMoney} {currencyCode} 汇率:{op.DayRate.ToString("#0.0000")};";
- }
- }
- info.Reality_OPAmountDesc = opDesc;
- #endregion
- #region 5:商邀 81
- var oaDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 81 && x.PayMoney != 0).ToList();
- var oaDesc = "-";
- if (oaDatas.Count > 0)
- {
- oaDesc = $"实际币种金额:";
- foreach (var oa in oaDatas)
- {
- var currencyCode = currencyData.Find(x => x.Id == oa.PaymentCurrency)?.Name;
- oaDesc += $"{oa.PayMoney} {currencyCode} 汇率:{oa.DayRate.ToString("#0.0000")};";
- }
- }
- info.Reality_OAAmountDesc = oaDesc;
- #endregion
- #region 6:其他款项(保险 82、其他款项 98)
- var cTables = new List<int>() { 82, 98 };
- var otherDatas = ccpData.Where(x => x.DIId == info.Id && cTables.Contains(x.CTable) && x.PayMoney != 0).ToList();
- var otherDesc = "-";
- if (otherDatas.Count > 0)
- {
- otherDesc = $"实际币种金额:";
- foreach (var other in otherDatas)
- {
- var currencyCode = currencyData.Find(x => x.Id == other.PaymentCurrency)?.Name;
- otherDesc += $"{other.PayMoney} {currencyCode} 汇率:{other.DayRate.ToString("#0.0000")};";
- }
- }
- info.Reality_OtherCostAmountDesc = otherDesc;
- #endregion
- }
- }
- var briefData = _mapper.Map<List<StatisticsBRCostBriefView>>(data);
- return Ok(JsonView(briefData, total));
- }
- /// <summary>
- /// 团组数据统计
- /// 当前时间团组所在城市
- /// </summary>
- /// <param name="dto"></param>
- /// <returns></returns>
- [HttpPost("StatisticsNowCityOfGroup")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> StatisticsNowCityOfGroup(StatisticsNowCityOfGroupDto dto)
- {
- if (!SharingStaticData.PortTypes.Contains(dto.PortType)) return Ok(JsonView(false, MsgTips.Port));
- var nowLable = DateTime.Now.ToString("yyyy-MM-dd");
- var sql = string.Format(@"SELECT * FROM Grp_DelegationInfo WHERE ISdel = 0 AND '{0}' BETWEEN VisitStartDate AND VisitEndDate", nowLable);
- var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql)
- .Select(x => new { x.Id, x.VisitCountry, x.TeamName,x.ClientUnit, x.VisitStartDate, x.VisitEndDate }).
- ToListAsync();
- if (!groupInfos.Any()) return Ok(JsonView(false, "今日暂无团组出行!"));
- var groupIds = groupInfos.Select(x => x.Id).ToList();
- //三字码
- var threeDatas = await _sqlSugar.Queryable<Res_ThreeCode>().Where(x => x.IsDel == 0).ToListAsync();
- //国家
- var countryDatas = await _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(x => x.IsDel == 0 && !string.IsNullOrEmpty(x.Country) && !string.IsNullOrEmpty(x.City)).ToListAsync();
- //公务
- var OADatas = await _sqlSugar
- .Queryable<Res_OfficialActivities>().Where(x => x.IsDel == 0 && groupIds.Contains(x.DiId) && !string.IsNullOrEmpty(x.Country) && !string.IsNullOrEmpty(x.Area))
- .ToListAsync();
- //酒店
- var hotelDatas = await _sqlSugar.Queryable<Grp_HotelReservations>()
- .LeftJoin<Grp_NationalTravelFee>((hr, ntf) => hr.AreaId == ntf.Id)
- .Where((hr, ntf) => hr.IsDel == 0 && groupIds.Contains(hr.DiId))
- .Select((hr, ntf) => new {
- hr.DiId,
- hr.AreaId,
- hr.HotelName,
- hr.CheckInDate,
- hr.CheckOutDate,
- hr.HotelAddress,
- ntf.Country,
- ntf.City
- })
- .ToListAsync();
- //机票
- /*
- *舱位类型
- *457 头等舱
- *458 公务舱
- *459 超经舱
- *460 经济舱
- *461 退票
- *565 其他
- *574 长段公务舱
- *575 短途经济舱
- *1023 行程单打印费
- *1024 选座费
- */
- var classTypes = new int[] { 457, 458, 459, 460, 574, 575 };
- var airDatas = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
- .Where(atr => atr.IsDel == 0 && groupIds.Contains(atr.DIId) && classTypes.Contains(atr.CType))
- .ToListAsync();
- string[] characters = { "|", "、" };
- var result = new List<StatisticsNowCityOfGroupResultView>();
- foreach (var item in groupInfos)
- {
- string statusText = string.Empty,
- address = string.Empty;
- var countrys = item.VisitCountry;
- if (string.IsNullOrEmpty(countrys)) continue;
- var currCountrys = item.VisitCountry.Split(characters, StringSplitOptions.RemoveEmptyEntries);
- var stutus = true;
- #region 公务
- var currOADatas = OADatas.Where(x => x.DiId == item.Id && currCountrys.Any(c => x.Country.Contains(c))).ToList();
- if (currOADatas.Any())
- {
- foreach (var curr_oa in currOADatas)
- {
- var localTime = GetCountryOrCityCurrentDateTime(curr_oa.Country, curr_oa.Area);
- if (localTime == null) continue;
- var currOaDtStart = Convert.ToDateTime($"{Convert.ToDateTime(curr_oa.Date).ToString("yyyy-MM-dd")} {curr_oa.Time}");
- var currOaDtEnd = currOaDtStart.AddHours(2);
- var currTimeZoneStatus = localTime >= currOaDtStart && localTime <= currOaDtEnd;
- if (!currTimeZoneStatus) continue;
- stutus = false;
- statusText = "公务活动中";
- address = curr_oa.Address;
- break;
- }
- }
- #endregion
- #region 酒店
- var currHotelDatas = hotelDatas.Where(x => x.DiId == item.Id && !string.IsNullOrEmpty(x.Country) && currCountrys.Any(c => x.Country.Contains(c))).ToList();
- if (stutus && hotelDatas.Any())
- {
- foreach (var curr_hotel in currHotelDatas)
- {
- var checkInDt = Convert.ToDateTime(curr_hotel.CheckInDate);
- List<(DateTime start, DateTime end)> timeRanges = new List<(DateTime, DateTime)>();
- while (checkInDt <= Convert.ToDateTime(curr_hotel.CheckOutDate))
- {
- int year = checkInDt.Year,
- month = checkInDt.Month,
- day = checkInDt.Day;
- timeRanges.Add((new DateTime(year, month, day, 0, 0, 0), new DateTime(year, month, day, 9, 0, 0)));
- timeRanges.Add((new DateTime(year, month, day, 18, 0, 0), new DateTime(year, month, day, 23, 59, 59)));
- checkInDt = checkInDt.AddDays(1);
- }
- if (!timeRanges.Any()) continue;
- if (string.IsNullOrEmpty(curr_hotel.Country) && string.IsNullOrEmpty(curr_hotel.City)) continue;
- var countryInfo = countryDatas.Where(x => x.Id == curr_hotel.AreaId).FirstOrDefault();
- if (countryInfo == null) continue;
- var localTime = GetCountryOrCityCurrentDateTime(countryInfo.Country, countryInfo.City);
- var currTimeZoneStatus = timeRanges.Any(range => localTime >= range.start && localTime <= range.end);
- if (!currTimeZoneStatus) continue;
- stutus = false;
- statusText = "入住酒店中";
- address = curr_hotel.HotelAddress;
- break;
- }
- }
- #endregion
- #region 机票--通过三字码解析处理
- var airTicketDatas = GetTableByBlackCode(item.Id);
- if (stutus && airTicketDatas != null)
- {
- foreach (DataRow curr_airTicket in airTicketDatas.Rows)
- {
- string departDate = curr_airTicket["Date"].ToString(), //出发日期
- departThree = curr_airTicket["Three"].ToString(), //城市三字码
- departTime = curr_airTicket["StartTime"].ToString(), //出发时刻
- departTerminal = curr_airTicket["StartBuilding"].ToString(), //出发航站楼
- arriveTerminal = curr_airTicket["EndBuilding"].ToString(), //抵达航站楼
- arrivedDate = curr_airTicket["ArrivedDate"].ToString(), //抵达日期
- arrivedTime = curr_airTicket["EndTime"].ToString(), //抵达日期
- flightTime = curr_airTicket["FlightTime"].ToString(); //飞行时间
- if (string.IsNullOrEmpty(departThree)) continue;
- string departAirThree = departThree.Substring(0, 3),
- arriveAirThree = departThree.Substring(3, 3);
- string departCountry = string.Empty,
- departCity = string.Empty,
- departAirport = string.Empty,
- arriveCountry = string.Empty,
- arriveCity = string.Empty,
- arriveAirport = string.Empty;
- var departCountryInfo = threeDatas.Find(x => x.Three.Equals(departAirThree));
- var arriveCountryInfo = threeDatas.Find(x => x.Three.Equals(arriveAirThree));
- if (departCountryInfo == null || arriveCountryInfo == null) continue;
- departCountry = departCountryInfo.Country;
- departCity = departCountryInfo.City;
- departAirport = departCountryInfo.AirPort;
- arriveCountry = arriveCountryInfo.Country;
- arriveCity = arriveCountryInfo.City;
- arriveAirport = arriveCountryInfo.AirPort;
- var arriveDateTimeBool = DateTime.TryParse(arrivedDate + " " + arrivedTime.Insert(2, ":"),out DateTime arriveDateTime);
- if (!arriveDateTimeBool) continue;
- var filghtHoursBool = int.TryParse(flightTime.Split("H")[0].ToString(), out int filghtHours);
- var filghtMinutesBool= int.TryParse(flightTime.Split("H")[1].Remove(2).ToString(), out int filghtMinutes);
- if (!filghtHoursBool || !filghtHoursBool) continue;
- var departDateTime = arriveDateTime.AddHours(-filghtHours).AddMinutes(-filghtMinutes);
- var localTime = GetCountryOrCityCurrentDateTime(arriveCountry,arriveCity);
- var currTimeZoneStatus = localTime >= departDateTime && localTime <= arriveDateTime;
- if (!currTimeZoneStatus) continue;
- stutus = false;
- statusText = $"正飞往{arriveCity}城市中";
- address = $"{arriveCountry}{arriveAirport}{arriveTerminal}";
- break;
- }
- }
- if (stutus) statusText = $"其他";
- #endregion
- result.Add(new StatisticsNowCityOfGroupResultView()
- {
- GroupName = item.TeamName,
- Client = item.ClientUnit,
- StatusText = statusText,
- Address = address
- });
- }
- result.AddRange(new List<StatisticsNowCityOfGroupResultView>() {
- new StatisticsNowCityOfGroupResultView(){ GroupName = "模拟数据团组1",Client = "模拟数据单位1",StatusText = "正在公务中",Address = "日本〒104-0032 Tokyo, Chuo City, Hatchobori, 1 Chome−12−8 EAST2階" },
- new StatisticsNowCityOfGroupResultView(){ GroupName = "模拟数据团组2",Client = "模拟数据单位2",StatusText = "入住酒店中",Address = "日本〒104-0032 Tokyo, Chuo City, Hatchobori, 1 Chome−12−8 EAST2階" },
- new StatisticsNowCityOfGroupResultView(){ GroupName = "模拟数据团组3",Client = "模拟数据单位3",StatusText = "其他",Address = "日本〒104-0032 Tokyo, Chuo City, Hatchobori, 1 Chome−12−8 EAST2階" },
- });
- var result1 = result.GroupBy(x => x.Address).Select(g => new
- {
- address = g.Key,
- Items = g.ToList().Select(gg => new { gg.GroupName, gg.Client, gg.StatusText }).ToList()
- });
- if (!result1.Any()) return Ok(JsonView(false,"今天暂无出行的的团!"));
- return Ok(JsonView(result1));
- }
- private StatisticsNowCityOfGroupView CitySplit(string cityLable, List<Res_ThreeCode> cities)
- {
- var info = new StatisticsNowCityOfGroupView();
- if (string.IsNullOrEmpty(cityLable)) return info;
- var cityArray = cityLable.Split("-");
- var departCityCode = cityArray[0];
- var arriveCityCode = cityArray[1];
- var departAirportInfo = cities.Find(x => x.Three.Equals(departCityCode.ToUpper()));
- info.DepartAirportCode = departCityCode;
- info.DepartCountryName = departAirportInfo?.Country ?? "-";
- info.DepartCityName = departAirportInfo?.City ?? "-";
- var arriveAirportInfo = cities.Find(x => x.Three.Equals(arriveCityCode.ToUpper()));
- info.ArriveAirportCode = arriveCityCode;
- info.ArriveCountryName = arriveAirportInfo?.Country ?? "-";
- info.ArriveCityName = arriveAirportInfo?.City ?? "-";
- return info;
- }
- #endregion
- #region 企业利润
- /// <summary>
- /// 企业利润 infos
- /// </summary>
- /// <param name="beginDt"></param>
- /// <param name="endDt"></param>
- /// <returns></returns>
- private async Task<CorporateProfitInfosView> CorporateProfitInfos(string beginDt, string endDt)
- {
- var view = new CorporateProfitInfosView();
- string sql = string.Format(@"SELECT
- ROW_NUMBER() OVER(ORDER BY di.VisitDate Asc) AS 'RowIndex',
- di.Id,
- di.ClientName,
- di.TeamName,
- di.TeamDid,
- ss.Name AS 'GroupTypeName',
- di.VisitDate,
- di.VisitPNumber,
- (
- SELECT
- SUM(ffr.ItemSumPrice * ffr.Rate)
- FROM
- OA2023DB.dbo.Fin_ForeignReceivables ffr
- WHERE
- ffr.IsDel = 0
- AND ffr.Diid = di.Id
- ) 'ReceivableAmount',
- (
- SELECT
- SUM(fpr.Price)
- FROM
- OA2023DB.dbo.Fin_ProceedsReceived fpr
- WHERE
- fpr.IsDel = 0
- AND fpr.DIId = di.Id
- ) 'ReceivedAmount',
- (
- SELECT
- SUM(ccp.PayMoney * ccp.DayRate)
- FROM
- Fin_PaymentRefundAndOtherMoney prom
- INNER JOIN Grp_CreditCardPayment ccp ON prom.Id = ccp.CId
- AND prom.DiId = ccp.DIId
- WHERE
- prom.IsDel = 0
- AND prom.PayType = 1
- AND ccp.CTable = 285
- AND ccp.IsAuditGM = 1
- AND prom.DiId = di.Id
- ) AS 'RefundedAmount',
- (
- SELECT
- SUM(ccp.PayMoney * ccp.DayRate)
- FROM
- Grp_HotelReservations hr
- INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
- WHERE
- hr.IsDel = 0
- AND ccp.IsDel = 0
- AND ccp.CTable = 76
- AND (
- ccp.IsAuditGM = 1
- OR ccp.IsAuditGM = 3
- )
- AND hr.DiId = di.Id
- ) AS 'HotelAmount',
- (
- SELECT
- SUM(
- (ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate)
- )
- FROM
- Grp_CarTouristGuideGroundReservations ctggr
- INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
- AND ccp.CTable = 79
- AND ctggr.Id = ccp.CId
- WHERE
- ctggr.IsDel = 0
- AND (
- ccp.IsAuditGM = 1
- OR ccp.IsAuditGM = 3
- )
- AND ctggr.DiId = di.Id
- ) AS 'LocalGuideAmount',
- (
- SELECT
- SUM(ccp.PayMoney * ccp.DayRate)
- FROM
- Grp_AirTicketReservations atr
- INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
- AND ccp.CTable = 85
- AND atr.Id = ccp.CId
- WHERE
- atr.IsDel = 0
- AND ccp.IsAuditGM = 1
- AND atr.DIId = di.Id
- ) AS 'AirTicketAmount',
- (
- SELECT
- SUM(ccp.PayMoney * ccp.DayRate)
- FROM
- Grp_VisaInfo vi
- INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
- AND ccp.CTable = 80
- AND vi.Id = ccp.CId
- WHERE
- vi.IsDel = 0
- AND ccp.IsAuditGM = 1
- AND vi.DIId = di.Id
- ) AS 'VisaAmount',
- (
- SELECT
- SUM(ccp.PayMoney * ccp.DayRate)
- FROM
- Grp_InvitationOfficialActivities ioa
- INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
- AND ccp.CTable = 81
- AND ioa.Id = ccp.CId
- WHERE
- ioa.IsDel = 0
- AND ccp.IsAuditGM = 1
- AND ioa.DiId = di.Id
- ) AS 'OAAmount',
- (
- SELECT
- SUM(ccp.PayMoney * ccp.DayRate)
- FROM
- Grp_Customers ic
- INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
- AND ccp.CTable = 82
- AND ic.Id = ccp.CId
- WHERE
- ic.IsDel = 0
- AND ccp.IsAuditGM = 1
- AND ic.DiId = di.Id
- ) AS 'InsureAmount',
- (
- SELECT
- SUM(ccp.PayMoney * ccp.DayRate)
- FROM
- Grp_DecreasePayments dp
- INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
- AND ccp.CTable = 98
- AND dp.Id = ccp.CId
- WHERE
- dp.IsDel = 0
- AND ccp.IsAuditGM = 1
- AND dp.Diid = di.Id
- ) AS 'OtherAmount'
- FROM
- OA2023DB.dbo.Grp_DelegationInfo di
- LEFT JOIN Sys_SetData ss ON di.TeamDid = ss.Id
- WHERE
- di.IsDel = 0
- AND di.IsBid = 0
- AND di.VisitDate BETWEEN '{0}' AND '{1}'", beginDt, endDt);
- var groupItems = await _sqlSugar.SqlQueryable<CorporateProfitInfo>(sql).ToArrayAsync();
- var dailySql = string.Format(@"SELECT
- dfp.Id,
- dfp.CompanyId,
- sc.CompanyName,
- sd.DepName AS 'Branch',
- su.CnName AS 'Applicant',
- dfp.PriceTypeId,
- sst.Id AS 'PriceParentTypeId',
- sst.Name AS 'PriceParentTypeName',
- ss.Id AS 'PriceTypeId',
- ss.Name AS 'PriceypeName',
- dfp.Instructions,
- dfp.SumPrice AS 'CNYTotal',
- dfpc.PriceName,
- dfpc.Quantity,
- dfpc.Price,
- dfpc.ItemTotal,
- dfpc.Remark,
- dfp.CreateTime
- From
- Fin_DailyFeePayment dfp
- INNER JOIN Fin_DailyFeePaymentContent dfpc on dfp.Id = dfpc.DFPId
- LEFT JOIN Sys_Company sc on dfp.CompanyId = sc.Id
- LEFT JOIN Sys_Users su on dfp.CreateUserId = su.Id
- LEFT JOIN Sys_Department sd on su.DepId = sd.Id
- LEFT JOIN Sys_SetData ss on dfp.PriceTypeId = ss.Id
- LEFT JOIN Sys_SetDataType sst on ss.STid = sst.Id
- WHERE
- dfp.IsDel = 0
- AND dfpc.IsDel = 0
- AND dfp.CreateTime BETWEEN '{0}' AND '{1}'
- AND dfp.IsPay = 1
- ORDER BY
- dfp.CompanyId,
- su.DepId,
- dfp.CreateUserId,
- dfp.PriceTypeId,
- dfp.CreateTime ASC", beginDt, endDt);
- var dailyItems = await _sqlSugar.SqlQueryable<DailyInfo>(dailySql).ToArrayAsync();
- view.GroupItems = groupItems;
- view.DailyItems = dailyItems;
- return view;
- }
- /// <summary>
- /// 团组利润item详情
- /// </summary>
- /// <param name="type">
- /// 1:详情
- /// 2:excel 生成
- /// </param>
- /// <param name="begin"></param>
- /// <param name="end"></param>
- /// <returns></returns>
- private async Task<CorporateProfitItemView> CorporateProfitItems(int type, string begin, string end)
- {
- var data = await CorporateProfitInfos(begin, end);
- var groupItems = data.GroupItems;
- var dailyItems = data.DailyItems;
- var priceTypeIds = new List<int>() {
- 686, //686 信用卡还款
- 687, //687 张总私人费用
- 688, //688 代报销社保生育补贴
- 688, //688 代报销社保生育补贴
- 306, //306 人事行政费用-张总家用类
- 325, //325 会展部备用金
- 689, //689 团组签证保险
- };
- var companyDailyItems = dailyItems
- .Where(x => !priceTypeIds.Contains(x.PriceTypeId))
- .GroupBy(x => x.CompanyName)
- .Select(g => new { CompanyName = g.Key, CNYTotal = g.Sum(x => x.CNYTotal) })
- .OrderBy(x => x.CNYTotal)
- .ToArray();
- //业务类型
- var groupTypeIds = new List<int>() {
- 38, // 政府团
- 39, // 企业团
- 40, // 散客团
- 1048 // 高校团
- };
- var inforTypeIds = new List<int>() {
- 302, // 成都-会务活动
- 691, // 四川-会务活动
- };
- //团组 收款、成本、利润 合计
- var groupCollectionTotal = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CollectionTotal);
- var groupCostTotal = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal);
- var groupProfitTotal = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ProfitTotal);
- //非团组 收款、成本、利润 合计
- var notGroupCollectionTotal = groupItems.Where(x => !groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CollectionTotal);
- var notGroupCostTotal = groupItems.Where(x => !groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal);
- var notGroupProfitTotal = groupItems.Where(x => !groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ProfitTotal);
- //会务数量
- int inforCount = groupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Count();
- //服务人数
- int serviceCount = groupItems.Sum(x => x.VisitPNumber);
- //总利润
- decimal totalProfit = groupProfitTotal + notGroupProfitTotal;
- var dailyLabel = $"*不含日付费用类型(信用卡还款、张总私人费用、代报销社保生育补贴、人事行政费用 - 张总家用类、会展部备用金、团组签证保险)\r\n";
- if (companyDailyItems.Any())
- {
- foreach (var dailyFee in companyDailyItems)
- {
- dailyLabel += $"[{dailyFee.CompanyName}]日常产生费用:{dailyFee.CNYTotal.ToString("#0.00")} CNY \r\n";
- }
- }
- string label = string.Format(@$"团组收款合计:{groupCollectionTotal.ToString("#0.00")} CNY\t团组产生费用合计:{groupCostTotal.ToString("#0.00")} CNY\t团组利润合计:{groupProfitTotal.ToString("#0.00")} CNY\r\n非团组收款合计:{notGroupCollectionTotal.ToString("#0.00")} CNY\t非团组产生费用合计:{notGroupCostTotal.ToString("#0.00")} CNY\t非团组利润合计:{notGroupProfitTotal.ToString("#0.00")} CNY\r\n{dailyLabel}其中会务:{inforCount}个\r\n服务人数:{serviceCount}人\r\n总利润:{totalProfit.ToString("#0.00")} CNY\r\n");
- var datas = _mapper.Map<CorporateProfitItem[]>(groupItems);
- if (type == 2) //excel 下载
- {
- var designer = new WorkbookDesigner();
- var tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/团组利润模板.xls";
- designer.Workbook = new Workbook(tempPath);
- designer.SetDataSource("ReceivablesTemp", datas);
- designer.SetDataSource("SumAccounts", groupCollectionTotal.ToString("#0.00"));
- designer.SetDataSource("SumReceived", groupCostTotal.ToString("#0.00"));
- designer.SetDataSource("SumBalance", groupProfitTotal.ToString("#0.00"));
- designer.SetDataSource("notSumAccounts", notGroupCollectionTotal.ToString("#0.00"));
- designer.SetDataSource("notSumReceived", notGroupCostTotal.ToString("#0.00"));
- designer.SetDataSource("SumOfNotTeamBalance", notGroupProfitTotal.ToString("#0.00"));
- designer.SetDataSource("DailyLabel", dailyLabel);
- designer.SetDataSource("MeetingNumber", inforCount + "个");
- designer.SetDataSource("ServiceNumber", serviceCount + "人");
- designer.SetDataSource("SumAllBalance", totalProfit.ToString("#0.00"));
- //根据数据源处理生成报表内容
- designer.Process();
- string fileName = $"团组利润({Convert.ToDateTime(begin).ToString("yyyy年MM月dd日")}~{Convert.ToDateTime(end).ToString("yyyy年MM月dd日")}){Guid.NewGuid().ToString()}.xls";
- designer.Workbook.Save($"{AppSettingsHelper.Get("ExcelBasePath")}CorporateProfit/{fileName}");
- string url = $"{AppSettingsHelper.Get("ExcelBaseUrl")}Office/Excel/CorporateProfit/{fileName}";
- label = url;
- }
- return new CorporateProfitItemView()
- {
- Items = datas,
- Label = label
- };
- }
- /// <summary>
- /// 企业利润
- /// Item
- /// </summary>
- /// <param name="dto"></param>
- /// <returns></returns>
- [HttpPost("CorporateProfitItem")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> CorporateProfitItem(CorporateProfitItemDto dto)
- {
- int portType = dto.PortType,
- userId = dto.UserId,
- pageId = dto.PageId;
- #region 参数验证
- //var validationRules = new CorporateProfitItemDtoFoalidator();
- //var validResult = await validationRules.ValidateAsync(dto);
- //if (!validResult.IsValid)
- //{
- // var errors = new StringBuilder();
- // foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
- // return Ok(JsonView(false, errors.ToString()));
- //}
- //#region 页面操作权限验证
- //var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(userId, pageId);
- //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限!"));
- //#endregion
- #endregion
- string beginDt = $"{dto.BeginDt} 00:00:00",
- endDt = $"{dto.EndDt} 23:59:59";
- return Ok(JsonView(true,"操作成功!", await CorporateProfitItems(1, beginDt, endDt)));
- }
- /// <summary>
- /// 企业利润 Excel导出
- /// </summary>
- /// <param name="dto"></param>
- /// <returns></returns>
- [HttpPost("CorporateProfitExcelDownload")]
- [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
- public async Task<IActionResult> CorporateProfitExcelDownload(CorporateProfitExcelDownloadDto dto)
- {
- int portType = dto.PortType,
- userId = dto.UserId,
- pageId = dto.PageId,
- excelType = dto.ExcelType;
- #region 参数验证
- var validationRules = new CorporateProfitExcelDownloadDtoFoalidator();
- var validResult = await validationRules.ValidateAsync(dto);
- if (!validResult.IsValid)
- {
- var errors = new StringBuilder();
- foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
- return Ok(JsonView(false, errors.ToString()));
- }
- #region 页面操作权限验证
- //var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(userId,pageId);
- //if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权限!"));
- #endregion
- #endregion
- string beginDt = $"{dto.BeginDt} 00:00:00",
- endDt = $"{dto.EndDt} 23:59:59";
- DateTime beginDate = DateTime.Parse(beginDt),
- endDate = DateTime.Parse(endDt);
- string yearBeginDt = $"{beginDate.Year}-01-01 00:00:00",
- yearEndDt = $"{beginDate.Year}-12-31 23:59:59";
- //业务类型
- var priceTypeIds = new List<int>() {
- 686, //686 信用卡还款
- 687, //687 张总私人费用
- 688, //688 代报销社保生育补贴
- 688, //688 代报销社保生育补贴
- 306, //306 人事行政费用-张总家用类
- 325, //325 会展部备用金
- 689, //689 团组签证保险
- };
- var data = await CorporateProfitInfos(beginDt, endDt);
- var groupItems = data.GroupItems;
- var dailyItems = data.DailyItems;
- //筛选不统计的费用类型
- //if (dailyItems.Any()) dailyItems = dailyItems.Where(x => !priceTypeIds.Contains(x.PriceTypeId)).ToArray();
- var yearData = await CorporateProfitInfos(yearBeginDt, yearEndDt);
- var yearGroupItems = yearData.GroupItems;
- var yearDailyItems = yearData.DailyItems;
- //筛选不统计的费用类型
- //if (yearDailyItems.Any()) yearDailyItems = yearDailyItems.Where(x => !priceTypeIds.Contains(x.PriceTypeId)).ToArray();
- #region 公共参数
- //团组收款、成本、利润 合计
- decimal monthGroupCollectionTotal = groupItems.Sum(x => x.CollectionTotal),
- monthGroupCostTotal = groupItems.Sum(x => x.CostTotal),
- yearGroupCollectionTotal = yearGroupItems.Sum(x => x.CollectionTotal),
- yearGroupCostTotal = yearGroupItems.Sum(x => x.CostTotal);
- //日付申请 48 人员费用、 49 办公费用、50 销售费用、51 其他费用、55 大运会、90 各部门基础固定费用明细
- decimal monthStaffCosts = dailyItems.Where(x => x.PriceParentTypeId == 48).Sum(x => x.CNYTotal),
- monthOfficeExpenses = dailyItems.Where(x => x.PriceParentTypeId == 49).Sum(x => x.CNYTotal),
- monthCostSales = dailyItems.Where(x => x.PriceParentTypeId == 50).Sum(x => x.CNYTotal),
- monthOtherFees = dailyItems.Where(x => x.PriceParentTypeId == 51).Sum(x => x.CNYTotal),
- monthDyhFees = dailyItems.Where(x => x.PriceParentTypeId == 55).Sum(x => x.CNYTotal),
- monthDepartFixedExpenses = dailyItems.Where(x => x.PriceParentTypeId == 90).Sum(x => x.CNYTotal),
- yearStaffCosts = yearDailyItems.Where(x => x.PriceParentTypeId == 48).Sum(x => x.CNYTotal),
- yearOfficeExpenses = yearDailyItems.Where(x => x.PriceParentTypeId == 49).Sum(x => x.CNYTotal),
- yearCostSales = yearDailyItems.Where(x => x.PriceParentTypeId == 50).Sum(x => x.CNYTotal),
- yearOtherFees = yearDailyItems.Where(x => x.PriceParentTypeId == 51).Sum(x => x.CNYTotal),
- yearDyhFees = yearDailyItems.Where(x => x.PriceParentTypeId == 55).Sum(x => x.CNYTotal),
- yearDepartFixedExpenses = yearDailyItems.Where(x => x.PriceParentTypeId == 90).Sum(x => x.CNYTotal);
- #endregion
- //月度报表、季度报表、年度报表
- if (excelType == 1 || excelType == 2 || excelType == 3)
- {
- var designer = new WorkbookDesigner();
- string fileName = $"({beginDate.ToString("yyyy年MM月dd日")}~{endDate.ToString("yyyy年MM月dd日")}){Guid.NewGuid().ToString()}.xls",
- fileNamePrefix = string.Empty,
- tempPath = string.Empty,
- workSheetName = string.Empty;
- if (excelType == 1)
- {
- tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/月度报表模板.xls";
- workSheetName = "月度报表";
- fileNamePrefix = "月度报表";
- }
- else if (excelType == 2)
- {
- tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/季度报表模板.xls";
- workSheetName = "季度报表";
- fileNamePrefix = "季度报表";
- }
- else if (excelType == 3)
- {
- tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/年度报表模板.xls";
- workSheetName = "年度报表";
- fileNamePrefix = "年度报表";
- }
- else return Ok(JsonView(false));
- designer.Workbook = new Workbook(tempPath);
- designer.Workbook.Worksheets[0].Name = workSheetName;
- #region 填充值
- string time = $"所属期间: {beginDate.ToString("yyyy 年 MM 月 dd 日")} 至 {endDate.ToString("yyyy 年 MM 月 dd 日")}";
- designer.SetDataSource("Time", time);
- designer.SetDataSource("MonthReceivedPrice", monthGroupCollectionTotal.ToString("#0.00"));//本月已收
- designer.SetDataSource("YearReceivedPrice", yearGroupCollectionTotal.ToString("#0.00")); //本年已收
- designer.SetDataSource("MonthSumReceives", monthGroupCollectionTotal.ToString("#0.00"));//本月团组收款
- designer.SetDataSource("MonthTeamCost", monthGroupCostTotal.ToString("#0.00")); //本月团组成本
- designer.SetDataSource("YearSumReceives", yearGroupCollectionTotal.ToString("#0.00"));//本年团组收款
- designer.SetDataSource("YearTeamCost", yearGroupCostTotal.ToString("#0.00")); //本年团组成本
- designer.SetDataSource("MonthStaffCosts", monthStaffCosts.ToString("#0.00"));//本月人员费用
- designer.SetDataSource("YearStaffCosts", yearStaffCosts.ToString("#0.00")); //本年人员费用
- designer.SetDataSource("MonthOfficeExpenses", monthOfficeExpenses.ToString("#0.00"));//本月办公费用
- designer.SetDataSource("YearOfficeExpenses", yearOfficeExpenses.ToString("#0.00")); //本年办公费用
- designer.SetDataSource("MonthCostSales", monthCostSales.ToString("#0.00"));//本月销售费用
- designer.SetDataSource("YearCostSales", yearCostSales.ToString("#0.00")); //本年销售费用
- designer.SetDataSource("MonthOtherFees", monthOtherFees.ToString("#0.00"));//本月其他费用
- designer.SetDataSource("YearOtherFees", yearOtherFees.ToString("#0.00")); //本年其他费用
- designer.SetDataSource("MonthDYHFees", monthDyhFees.ToString("#0.00"));//本月大运会费用
- designer.SetDataSource("YearDYHFees", yearDyhFees.ToString("#0.00")); //本年大运会费用
- designer.SetDataSource("MonthDepartFixedFees", monthDepartFixedExpenses.ToString("#0.00"));//本月各部门基础固定费用明细费用
- designer.SetDataSource("YearDepartFixedFees", yearDepartFixedExpenses.ToString("#0.00")); //本年各部门基础固定费用明细费用
- // 填表时间
- string fillingTime = $"填报时间:{DateTime.Now.ToString("yyyy.MM.dd")}";
- designer.SetDataSource("FillingTime", fillingTime);
- #endregion
- //根据数据源处理生成报表内容
- designer.Process();
- fileName = fileNamePrefix + fileName;
- designer.Workbook.Save($"{AppSettingsHelper.Get("ExcelBasePath")}CorporateProfit/{fileName}");
- string url = $"{AppSettingsHelper.Get("ExcelBaseUrl")}Office/Excel/CorporateProfit/{fileName}";
- return Ok(JsonView(true, "操作成功!", url));
- }
- //利润报表
- else if (excelType == 4)
- {
- var designer = new WorkbookDesigner();
- var tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/利润报表New.xlsx";
- designer.Workbook = new Workbook(tempPath);
- #region 填充值
- string time = $"所属期间: {beginDate.ToString("yyyy 年 MM 月 dd 日")} 至 {endDate.ToString("yyyy 年 MM 月 dd 日")}";
- designer.SetDataSource("Time", time);
- //办公费用
- decimal officePirce = yearStaffCosts + yearOfficeExpenses;
- designer.SetDataSource("officePirce", officePirce.ToString("#0.00"));
- //业务类型
- var groupTypeIds = new List<int>() {
- 38, // 政府团
- 39, // 企业团
- 40, // 散客团
- 1048 // 高校团
- };
- var inforTypeIds = new List<int>() {
- 302, // 成都-会务活动
- 691, // 四川-会务活动
- };
- var competitionTypeIds = new List<int>() {
- 762, //四川-赛事项目收入
- 1047, // 成都-赛事项目收入
- };
- var otherTypeIds = new List<int>();
- otherTypeIds.AddRange(groupTypeIds);
- otherTypeIds.AddRange(inforTypeIds);
- otherTypeIds.AddRange(competitionTypeIds);
- decimal monthAllIncomes = groupItems.Sum(x => x.ReceivedAmount), //月-收入
- monthTzIncomes = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivedAmount),
- monthHwIncomes = groupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivedAmount),
- monthSsIncomes = groupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivedAmount),
- monthQtIncomes = groupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivedAmount),
- monthAllCost = groupItems.Sum(x => x.CostTotal), //月-成本
- monthTzCost = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
- monthHwCost = groupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
- monthSsCost = groupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
- monthQtCost = groupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
- monthAllGross = monthAllIncomes - monthAllCost, //月-毛利金额
- monthTzGross = monthTzIncomes - monthTzCost,
- monthHwGross = monthHwIncomes - monthHwCost,
- monthSsGross = monthSsIncomes - monthSsCost,
- monthQtGross = monthQtIncomes - monthQtCost,
- yearAllIncomes = yearGroupItems.Sum(x => x.ReceivedAmount), //年-收入
- yearTzIncomes = yearGroupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivedAmount),
- yearHwIncomes = yearGroupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivedAmount),
- yearSsIncomes = yearGroupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivedAmount),
- yearQtIncomes = yearGroupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivedAmount),
- yearAllCost = yearGroupItems.Sum(x => x.CostTotal), //年-成本
- yearTzCost = yearGroupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
- yearHwCost = yearGroupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
- yearSsCost = yearGroupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
- yearQtCost = yearGroupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
- yearAllGross = yearAllIncomes - yearAllCost, //年-毛利金额
- yearTzGross = yearTzIncomes - yearTzCost,
- yearHwGross = yearHwIncomes - yearHwCost,
- yearSsGross = yearSsIncomes - yearSsCost,
- yearQtGross = yearQtIncomes - yearQtCost;
- //年-团数量
- int yearAllCount = yearGroupItems.Count(),
- yearTzCount = yearGroupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Count(),
- yearHwCount = yearGroupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Count(),
- yearSsCount = yearGroupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Count(),
- yearQtCount = yearGroupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Count();
- //年-利率
- string yearAllRate = "0.00 %",
- yearTzRate = "0.00 %",
- yearHwRate = "0.00 %",
- yearSsRate = "0.00 %",
- yearQtRate = "0.00 %";
- if (yearAllIncomes != 0) yearAllRate = (yearAllGross / yearAllIncomes * 100).ToString("#0.00") + "%";
- if (yearTzIncomes != 0) yearTzRate = (yearTzGross / yearTzIncomes * 100).ToString("#0.00") + "%";
- if (yearHwIncomes != 0) yearHwRate = (yearHwGross / yearHwIncomes * 100).ToString("#0.00") + "%";
- if (yearSsIncomes != 0) yearSsRate = (yearSsGross / yearSsIncomes * 100).ToString("#0.00") + "%";
- if (yearQtIncomes != 0) yearQtRate = (yearQtGross / yearQtIncomes * 100).ToString("#0.00") + "%";
- #region 月
- //收入
- designer.SetDataSource("MonthAllIncomes", monthAllIncomes.ToString("#0.00"));
- designer.SetDataSource("MonthtzIncomes", monthTzIncomes.ToString("#0.00"));
- designer.SetDataSource("MonthhwIncomes", monthHwIncomes.ToString("#0.00"));
- designer.SetDataSource("MonthssIncomes", monthSsIncomes.ToString("#0.00"));
- designer.SetDataSource("MonthqtIncomes", monthQtIncomes.ToString("#0.00"));
- //成本
- designer.SetDataSource("MonthAllCost", monthAllCost.ToString("#0.00"));
- designer.SetDataSource("MonthtzCost", monthTzCost.ToString("#0.00"));
- designer.SetDataSource("MonthhwCost", monthHwCost.ToString("#0.00"));
- designer.SetDataSource("MonthssCost", monthSsCost.ToString("#0.00"));
- designer.SetDataSource("MonthqtCost", monthQtCost.ToString("#0.00"));
- //毛利金额
- designer.SetDataSource("MonthAllGross", monthAllGross.ToString("#0.00"));
- designer.SetDataSource("MonthtzGross", monthTzGross.ToString("#0.00"));
- designer.SetDataSource("MonthhwGross", monthHwGross.ToString("#0.00"));
- designer.SetDataSource("MonthssGross", monthSsGross.ToString("#0.00"));
- designer.SetDataSource("MonthqtGross", monthQtGross.ToString("#0.00"));
- #endregion
- #region 年
- //收入
- designer.SetDataSource("YearAllIncomes", yearAllIncomes.ToString("#0.00"));
- designer.SetDataSource("YeartzIncomes", yearTzIncomes.ToString("#0.00"));
- designer.SetDataSource("YearhwIncomes", yearHwIncomes.ToString("#0.00"));
- designer.SetDataSource("YearssIncomes", yearSsIncomes.ToString("#0.00"));
- designer.SetDataSource("YearqtIncomes", yearQtIncomes.ToString("#0.00"));
- //成本
- designer.SetDataSource("YearAllCost", yearAllCost.ToString("#0.00"));
- designer.SetDataSource("YeartzCost", yearTzCost.ToString("#0.00"));
- designer.SetDataSource("YearhwCost", yearHwCost.ToString("#0.00"));
- designer.SetDataSource("YearssCost", yearSsCost.ToString("#0.00"));
- designer.SetDataSource("YearqtCost", yearQtCost.ToString("#0.00"));
- //毛利金额
- designer.SetDataSource("YearAllGross", yearAllGross.ToString("#0.00"));
- designer.SetDataSource("YeartzGross", yearTzGross.ToString("#0.00"));
- designer.SetDataSource("YearhwGross", yearHwGross.ToString("#0.00"));
- designer.SetDataSource("YearssGross", yearSsGross.ToString("#0.00"));
- designer.SetDataSource("YearqtGross", yearQtGross.ToString("#0.00"));
- //毛利率
- designer.SetDataSource("YearAllRate", yearAllRate);
- designer.SetDataSource("YeartzRate", yearTzRate);
- designer.SetDataSource("YearhwRate", yearHwRate);
- designer.SetDataSource("YearssRate", yearSsRate);
- designer.SetDataSource("YearqtRate", yearQtRate);
- //数量
- designer.SetDataSource("AllCount", yearAllCount.ToString());
- designer.SetDataSource("tzCount", yearTzCount.ToString());
- designer.SetDataSource("hwCount", yearHwCount.ToString());
- designer.SetDataSource("ssCount", yearSsCount.ToString());
- designer.SetDataSource("qtCount", yearQtCount.ToString());
- #endregion
- #region 日付相关
- var dailyViewItems = new List<CorporateProfitDailyView>();
- var dailyTypes = await _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0).ToListAsync();
- var conmmentTexts = new List<CorporateProfitDailyCommentView>();
- #region 员工费用 48
- decimal monthStaffCostTotal = dailyItems.Where(x => x.PriceParentTypeId == 48).Sum(x => x.ItemTotal),
- yearStaffCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 48).Sum(x => x.ItemTotal);
- dailyViewItems.Add(new CorporateProfitDailyView() { No = "一", PriceName = "人员费用", ThisMonthAmount = monthStaffCostTotal, ThisYearAmount = yearStaffCostTotal});
- conmmentTexts.Add(new CorporateProfitDailyCommentView()
- {
- MonthComment = DailyListToString(dailyItems.Where(x => x.PriceParentTypeId == 48).ToArray()),
- YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 48).ToArray())
- });
- var dailyStaffTypes = dailyTypes.Where(x => x.STid == 48).OrderBy(x => x.Id).ToList();
- foreach (var item in dailyStaffTypes)
- {
- string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
- decimal monthAmount = dailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
- yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
- dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
- conmmentTexts.Add(new CorporateProfitDailyCommentView()
- {
- MonthComment = DailyListToString(dailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
- YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
- });
- }
- #endregion
- #region 办公费用
- decimal monthWorkCostTotal = dailyItems.Where(x => x.PriceParentTypeId == 49).Sum(x => x.ItemTotal), //总费用
- yearWorkCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 49).Sum(x => x.ItemTotal);
- dailyViewItems.Add(new CorporateProfitDailyView() { No = "二", PriceName = "办公费用", ThisMonthAmount = monthWorkCostTotal, ThisYearAmount = yearWorkCostTotal });
- conmmentTexts.Add(new CorporateProfitDailyCommentView()
- {
- MonthComment = DailyListToString(dailyItems.Where(x => x.PriceParentTypeId == 49).ToArray()),
- YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 49).ToArray())
- });
- var dailyWorkTypes = dailyTypes.Where(x => x.STid == 49).OrderBy(x => x.Id).ToList();
- foreach (var item in dailyWorkTypes)
- {
- string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
- decimal monthAmount = dailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
- yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
- dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
- conmmentTexts.Add(new CorporateProfitDailyCommentView()
- {
- MonthComment = DailyListToString(dailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
- YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
- });
- }
- #endregion
- #region 销售费用
- decimal monthSalesCostTotal = dailyItems.Where(x => x.PriceParentTypeId == 50).Sum(x => x.ItemTotal), //总费用
- yearSalesCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 50).Sum(x => x.ItemTotal);
- dailyViewItems.Add(new CorporateProfitDailyView() { No = "三", PriceName = "销售费用", ThisMonthAmount = monthSalesCostTotal, ThisYearAmount = yearSalesCostTotal });
- conmmentTexts.Add(new CorporateProfitDailyCommentView()
- {
- MonthComment = DailyListToString(dailyItems.Where(x => x.PriceParentTypeId == 50).ToArray()),
- YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 50).ToArray())
- });
- var dailySalesTypes = dailyTypes.Where(x => x.STid == 50).OrderBy(x => x.Id).ToList();
- foreach (var item in dailySalesTypes)
- {
- string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
- decimal monthAmount = dailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
- yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
- dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
- conmmentTexts.Add(new CorporateProfitDailyCommentView()
- {
- MonthComment = DailyListToString(dailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
- YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
- });
- }
- #endregion
- #region 51 其他费用
- decimal monthOtherCostTotal = dailyItems.Where(x => x.PriceParentTypeId == 51).Sum(x => x.ItemTotal), //总费用
- yearOtherCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 51).Sum(x => x.ItemTotal);
- dailyViewItems.Add(new CorporateProfitDailyView() { No = "四", PriceName = "其他费用", ThisMonthAmount = monthOtherCostTotal, ThisYearAmount = yearOtherCostTotal });
- conmmentTexts.Add(new CorporateProfitDailyCommentView()
- {
- MonthComment = DailyListToString(dailyItems.Where(x => x.PriceParentTypeId == 51).ToArray()),
- YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 51).ToArray())
- });
- var dailyOtherTypes = dailyTypes.Where(x => x.STid == 51).OrderBy(x => x.Id).ToList();
- foreach (var item in dailyOtherTypes)
- {
- string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
- decimal monthAmount = dailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
- yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
- dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
- conmmentTexts.Add(new CorporateProfitDailyCommentView()
- {
- MonthComment = DailyListToString(dailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
- YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
- });
- }
- #endregion
- #region 55 大运会
- decimal monthDyhCostTotal = dailyItems.Where(x => x.PriceParentTypeId == 55).Sum(x => x.ItemTotal), //总费用
- yearDyhCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 55).Sum(x => x.ItemTotal);
- dailyViewItems.Add(new CorporateProfitDailyView() { No = "五", PriceName = "大运会", ThisMonthAmount = monthDyhCostTotal, ThisYearAmount = yearDyhCostTotal });
- conmmentTexts.Add(new CorporateProfitDailyCommentView()
- {
- MonthComment = DailyListToString(dailyItems.Where(x => x.PriceParentTypeId == 55).ToArray()),
- YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 55).ToArray())
- });
- var dailyDyhTypes = dailyTypes.Where(x => x.STid == 55).OrderBy(x => x.Id).ToList();
- foreach (var item in dailyDyhTypes)
- {
- string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
- decimal monthAmount = dailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
- yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
- dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
- conmmentTexts.Add(new CorporateProfitDailyCommentView()
- {
- MonthComment = DailyListToString(dailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
- YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
- });
- }
- #endregion
- #region 90 各部门基础固定费用明细
- decimal monthBasicCostTotal = dailyItems.Where(x => x.PriceParentTypeId == 90).Sum(x => x.ItemTotal), //总费用
- yearBasicCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 90).Sum(x => x.ItemTotal);
- dailyViewItems.Add(new CorporateProfitDailyView() { No = "六", PriceName = "各部门基础固定费用明细", ThisMonthAmount = monthBasicCostTotal, ThisYearAmount = yearBasicCostTotal });
- conmmentTexts.Add(new CorporateProfitDailyCommentView()
- {
- MonthComment = DailyListToString(dailyItems.Where(x => x.PriceParentTypeId == 90).ToArray()),
- YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 90).ToArray())
- });
- var dailyBasicTypes = dailyTypes.Where(x => x.STid == 90).OrderBy(x => x.Id).ToList();
- foreach (var item in dailyBasicTypes)
- {
- string priceName = item.Name;
- decimal monthAmount = dailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
- yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
- dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
- conmmentTexts.Add(new CorporateProfitDailyCommentView()
- {
- MonthComment = DailyListToString(dailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
- YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
- });
- }
- #endregion
- //designer.SetDataSource("DailyView", dailyViewItems);
- var dt = CommonFun.ToDataTableArray(dailyViewItems);
- dt.TableName = "DailyView";
- designer.SetDataSource(dt);
-
- #endregion
- #endregion
- //根据数据源处理生成报表内容
- designer.Process();
- var dailySheet = designer.Workbook.Worksheets[1];
- //渲染批注
- for (int i = 0; i < dailyViewItems.Count; i++)
- {
- string monthComment = $"C{i + 3}",
- yearComment = $"D{i + 3}";
- int monthCommentIndex = dailySheet.Comments.Add(monthComment),
- yearCommentIndex = dailySheet.Comments.Add(yearComment);
-
- string commentText1 = conmmentTexts[i].MonthComment,
- commentText2 = conmmentTexts[i].YearComment;
- Aspose.Cells.Comment comment1 = dailySheet.Comments[monthCommentIndex];
- comment1.Note = commentText1;
- comment1.Width = 400;
- comment1.Height = 400;
- comment1.Font.Color = Color.Red;
- Aspose.Cells.Comment comment2 = dailySheet.Comments[yearCommentIndex];
- comment2.Note = commentText2;
- comment2.Width = 400;
- comment2.Height = 400;
- comment2.Font.Color = Color.Red;
- }
- string fileName = $"利润报表({beginDate.ToString("yyyy年MM月dd日")}~{endDate.ToString("yyyy年MM月dd日")}){Guid.NewGuid().ToString()}.xls";
- designer.Workbook.Save($"{AppSettingsHelper.Get("ExcelBasePath")}CorporateProfit/{fileName}");
- string url = $"{AppSettingsHelper.Get("ExcelBaseUrl")}Office/Excel/CorporateProfit/{fileName}";
- return Ok(JsonView(true, "操作成功!", url));
- }
- else if (excelType == 5)
- {
- var view = await CorporateProfitItems(2, beginDt, endDt);
- return Ok(JsonView(true, "操作成功!", view.Label));
- }
- return Ok(JsonView(false));
- }
- private static string DailyListToString(DailyInfo[] infos)
- {
- StringBuilder sb = new StringBuilder();
- int index = 1;
- foreach (var info in infos)
- {
- sb.Append(index + "、");
- sb.Append($"[{info.ItemTotal.ToString("#0.00")}]:{info.PriceName};");
- sb.Append(Environment.NewLine);
- index++;
- }
- return sb.ToString();
- }
- #endregion
- }
- }
|