StatisticsController.cs 423 KB

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